With X11, how can I get the user's time “away

2020-07-11 09:02发布

问题:

I'm making a little application that needs to know how long the user has been idle — as in, not using a keyboard or a mouse. Both XCB and Xlib promise to give me idle time through their respective screensaver extensions. Here is where I get idle time with XCB:

#include <stdlib.h>
#include <xcb/xcb.h>
#include <xcb/screensaver.h>

static xcb_connection_t * connection;
static xcb_screen_t * screen;

/**
 * Connects to the X server (via xcb) and gets the screen
 */
void magic_begin () {
    connection = xcb_connect (NULL, NULL);
    screen = xcb_setup_roots_iterator (xcb_get_setup (connection)).data;
}

/**
 * Asks X for the time the user has been idle
 * @returns idle time in milliseconds
 */
unsigned long magic_get_idle_time () {
    xcb_screensaver_query_info_cookie_t cookie;
    xcb_screensaver_query_info_reply_t *info;

    cookie = xcb_screensaver_query_info (connection, screen->root);
    info = xcb_screensaver_query_info_reply (connection, cookie, NULL);

    uint32_t idle = info->ms_since_user_input;
    free (info);

    return idle;
}

However, this is behaving very differently than "ms_since_user_input" suggests. If I am watching a video (tested with Totem), the idle time resets to 0 within 30 seconds, without exception. The same thing happens with a number of games, which cause this even when they are paused! Using XLib, I get the exact same behaviour.

I might be able to improve the code that uses the idle time so this behaviour isn't as much of a problem, but I'd really like to get rid of the problem completely. I would prefer if I was only getting the time since the last user input event (and only the last user input event). I wouldn't mind using some other libraries to get there, as long as my program doesn't generate a lot of traffic.

Do you have any ideas for how this can be done?

回答1:

What you're seeing with totem is it trying to avoid the screensaver kicking in. It does this by sending key event at regular intervals.

You can find the code that does that here: http://git.gnome.org/browse/totem/tree/lib/totem-scrsaver.c#n318

And since the screensaver uses the same extension as you're using this results in your counter hitting zero.



标签: linux x11 xcb