aboutsummaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rw-r--r--tools/gsr-global-hotkeys/README.md21
-rw-r--r--tools/gsr-global-hotkeys/hotplug.c79
-rw-r--r--tools/gsr-global-hotkeys/hotplug.h22
-rw-r--r--tools/gsr-global-hotkeys/keyboard_event.c740
-rw-r--r--tools/gsr-global-hotkeys/keyboard_event.h92
-rw-r--r--tools/gsr-global-hotkeys/keys.c21
-rw-r--r--tools/gsr-global-hotkeys/keys.h10
-rw-r--r--tools/gsr-global-hotkeys/main.c272
-rw-r--r--tools/gsr-ui-cli/main.c107
-rw-r--r--tools/gsr-window-name/main.c187
10 files changed, 1151 insertions, 400 deletions
diff --git a/tools/gsr-global-hotkeys/README.md b/tools/gsr-global-hotkeys/README.md
new file mode 100644
index 0000000..8744107
--- /dev/null
+++ b/tools/gsr-global-hotkeys/README.md
@@ -0,0 +1,21 @@
+# About
+Global hotkeys for X11 and all Wayland compositors by using linux device api. Keyboards are grabbed and only the non-hotkey keys are passed through to the system.
+The program accepts text commands as input. Run the program with the option `--virtual` to only grab virtual devices. This is useful when using keyboard input mapping software such as
+kanata, otherwise kanata may fail to launch or this program may fail to launch.
+# Commands
+## Bind
+To add a key send `bind <action> <keycode+keycode+...><newline>` to the programs stdin, for example:
+```
+bind show_hide 56+44
+
+```
+which will bind alt+z. When alt+z is pressed the program will output `show_hide` (and a newline) to stdout.
+The program only accepts one key for each keybind command but accepts a multiple modifier keys.
+The keybinding requires at least one modifier key (ctrl, alt, super or shift) and a key to be used.
+The keycodes are values from `<linux/input-event-codes.h>` linux api header (which is the same as X11 keycode value minus 8).
+## Unbind
+To unbind all keys send `unbind_all<newline>` to the programs stdin, for example:
+```
+unbind_all
+
+``` \ No newline at end of file
diff --git a/tools/gsr-global-hotkeys/hotplug.c b/tools/gsr-global-hotkeys/hotplug.c
new file mode 100644
index 0000000..2e8ca9f
--- /dev/null
+++ b/tools/gsr-global-hotkeys/hotplug.c
@@ -0,0 +1,79 @@
+#include "hotplug.h"
+
+/* C stdlib */
+#include <string.h>
+
+/* POSIX */
+#include <unistd.h>
+#include <sys/socket.h>
+
+/* LINUX */
+#include <linux/types.h>
+#include <linux/netlink.h>
+
+bool hotplug_event_init(hotplug_event *self) {
+ memset(self, 0, sizeof(*self));
+
+ struct sockaddr_nl nls = {
+ .nl_family = AF_NETLINK,
+ .nl_pid = getpid(),
+ .nl_groups = -1
+ };
+
+ const int fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+ if(fd == -1)
+ return false;
+
+ if(bind(fd, (void*)&nls, sizeof(struct sockaddr_nl))) {
+ close(fd);
+ return false;
+ }
+
+ self->fd = fd;
+ return true;
+}
+
+void hotplug_event_deinit(hotplug_event *self) {
+ if(self->fd > 0) {
+ close(self->fd);
+ self->fd = -1;
+ }
+}
+
+int hotplug_event_steal_fd(hotplug_event *self) {
+ const int fd = self->fd;
+ self->fd = -1;
+ return fd;
+}
+
+/* TODO: This assumes SUBSYSTEM= is output before DEVNAME=, is that always true? */
+static void hotplug_event_parse_netlink_data(hotplug_event *self, const char *line, hotplug_device_added_callback callback, void *userdata) {
+ const char *at_symbol = strchr(line, '@');
+ if(at_symbol) {
+ self->event_is_add = strncmp(line, "add@", 4) == 0;
+ self->subsystem_is_input = false;
+ } else if(self->event_is_add) {
+ if(strcmp(line, "SUBSYSTEM=input") == 0)
+ self->subsystem_is_input = true;
+
+ if(self->subsystem_is_input && strncmp(line, "DEVNAME=", 8) == 0) {
+ callback(line+8, userdata);
+ self->event_is_add = false;
+ }
+ }
+}
+
+/* Netlink uevent structure is documented here: https://web.archive.org/web/20160127215232/https://www.kernel.org/doc/pending/hotplug.txt */
+void hotplug_event_process_event_data(hotplug_event *self, int fd, hotplug_device_added_callback callback, void *userdata) {
+ const int bytes_read = read(fd, self->event_data, sizeof(self->event_data) - 1);
+ if(bytes_read <= 0)
+ return;
+ self->event_data[bytes_read] = '\0';
+
+ /* Hotplug data ends with a newline and a null terminator */
+ int data_index = 0;
+ while(data_index < bytes_read) {
+ hotplug_event_parse_netlink_data(self, self->event_data + data_index, callback, userdata);
+ data_index += strlen(self->event_data + data_index) + 1; /* Skip null terminator as well */
+ }
+}
diff --git a/tools/gsr-global-hotkeys/hotplug.h b/tools/gsr-global-hotkeys/hotplug.h
new file mode 100644
index 0000000..665485a
--- /dev/null
+++ b/tools/gsr-global-hotkeys/hotplug.h
@@ -0,0 +1,22 @@
+#ifndef HOTPLUG_H
+#define HOTPLUG_H
+
+/* C stdlib */
+#include <stdbool.h>
+
+typedef struct {
+ int fd;
+ bool event_is_add;
+ bool subsystem_is_input;
+ char event_data[1024];
+} hotplug_event;
+
+typedef void (*hotplug_device_added_callback)(const char *devname, void *userdata);
+
+bool hotplug_event_init(hotplug_event *self);
+void hotplug_event_deinit(hotplug_event *self);
+
+int hotplug_event_steal_fd(hotplug_event *self);
+void hotplug_event_process_event_data(hotplug_event *self, int fd, hotplug_device_added_callback callback, void *userdata);
+
+#endif /* HOTPLUG_H */
diff --git a/tools/gsr-global-hotkeys/keyboard_event.c b/tools/gsr-global-hotkeys/keyboard_event.c
new file mode 100644
index 0000000..6973d4b
--- /dev/null
+++ b/tools/gsr-global-hotkeys/keyboard_event.c
@@ -0,0 +1,740 @@
+#include "keyboard_event.h"
+#include "keys.h"
+
+/* C stdlib */
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <stdlib.h>
+
+/* POSIX */
+#include <fcntl.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <poll.h>
+
+/* LINUX */
+#include <linux/input.h>
+#include <linux/uinput.h>
+
+#define GSR_UI_VIRTUAL_KEYBOARD_NAME "gsr-ui virtual keyboard"
+
+#define KEY_RELEASE 0
+#define KEY_PRESS 1
+#define KEY_REPEAT 2
+
+#define KEY_STATES_SIZE (KEY_MAX/8 + 1)
+
+static inline int count_num_bits_set(unsigned char c) {
+ int n = 0;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ c >>= 1;
+ n += (c & 1);
+ return n;
+}
+
+static inline bool keyboard_event_has_exclusive_grab(const keyboard_event *self) {
+ return self->uinput_fd > 0;
+}
+
+static int keyboard_event_get_num_keys_pressed(const unsigned char *key_states) {
+ if(!key_states)
+ return 0;
+
+ int num_keys_pressed = 0;
+ for(int i = 0; i < KEY_STATES_SIZE; ++i) {
+ num_keys_pressed += count_num_bits_set(key_states[i]);
+ }
+ return num_keys_pressed;
+}
+
+static void keyboard_event_fetch_update_key_states(keyboard_event *self, event_extra_data *extra_data, int fd) {
+ fsync(fd);
+ if(!extra_data->key_states)
+ return;
+
+ if(ioctl(fd, EVIOCGKEY(KEY_STATES_SIZE), extra_data->key_states) == -1)
+ fprintf(stderr, "Warning: failed to fetch key states for device: /dev/input/event%d\n", extra_data->dev_input_id);
+
+ if(!keyboard_event_has_exclusive_grab(self) || extra_data->grabbed)
+ return;
+
+ extra_data->num_keys_pressed = keyboard_event_get_num_keys_pressed(extra_data->key_states);
+ if(extra_data->num_keys_pressed == 0) {
+ extra_data->grabbed = ioctl(fd, EVIOCGRAB, 1) != -1;
+ if(extra_data->grabbed)
+ fprintf(stderr, "Info: grabbed device: /dev/input/event%d\n", extra_data->dev_input_id);
+ else
+ fprintf(stderr, "Warning: failed to exclusively grab device: /dev/input/event%d. The focused application may receive keys used for global hotkeys\n", extra_data->dev_input_id);
+ }
+}
+
+static void keyboard_event_process_key_state_change(keyboard_event *self, const struct input_event *event, event_extra_data *extra_data, int fd) {
+ if(event->type != EV_KEY)
+ return;
+
+ if(!extra_data->key_states || event->code >= KEY_STATES_SIZE * 8)
+ return;
+
+ const unsigned int byte_index = event->code / 8;
+ const unsigned char bit_index = event->code % 8;
+ unsigned char key_byte_state = extra_data->key_states[byte_index];
+ const bool prev_key_pressed = (key_byte_state & (1 << bit_index)) != KEY_RELEASE;
+
+ if(event->value == KEY_RELEASE) {
+ key_byte_state &= ~(1 << bit_index);
+ if(prev_key_pressed)
+ --extra_data->num_keys_pressed;
+ } else {
+ key_byte_state |= (1 << bit_index);
+ if(!prev_key_pressed)
+ ++extra_data->num_keys_pressed;
+ }
+
+ extra_data->key_states[byte_index] = key_byte_state;
+
+ if(!keyboard_event_has_exclusive_grab(self) || extra_data->grabbed)
+ return;
+
+ if(extra_data->num_keys_pressed == 0) {
+ extra_data->grabbed = ioctl(fd, EVIOCGRAB, 1) != -1;
+ if(extra_data->grabbed)
+ fprintf(stderr, "Info: grabbed device: /dev/input/event%d\n", extra_data->dev_input_id);
+ else
+ fprintf(stderr, "Warning: failed to exclusively grab device: /dev/input/event%d. The focused application may receive keys used for global hotkeys\n", extra_data->dev_input_id);
+ }
+}
+
+/* Return true if a global hotkey is assigned to the key combination */
+static bool keyboard_event_on_key_pressed(keyboard_event *self, const struct input_event *event, uint32_t modifiers) {
+ if(event->value != KEYBOARD_BUTTON_PRESSED)
+ return false;
+
+ bool global_hotkey_match = false;
+ for(int i = 0; i < self->num_global_hotkeys; ++i) {
+ if(event->code == self->global_hotkeys[i].key && modifiers == self->global_hotkeys[i].modifiers) {
+ puts(self->global_hotkeys[i].action);
+ fflush(stdout);
+ global_hotkey_match = true;
+ }
+ }
+ return global_hotkey_match;
+}
+
+static inline uint32_t set_bit(uint32_t value, uint32_t bit_flag, bool set) {
+ if(set)
+ return value | bit_flag;
+ else
+ return value & ~bit_flag;
+}
+
+static uint32_t keycode_to_modifier_bit(uint32_t keycode) {
+ switch(keycode) {
+ case KEY_LEFTSHIFT: return KEYBOARD_MODKEY_LSHIFT;
+ case KEY_RIGHTSHIFT: return KEYBOARD_MODKEY_RSHIFT;
+ case KEY_LEFTCTRL: return KEYBOARD_MODKEY_LCTRL;
+ case KEY_RIGHTCTRL: return KEYBOARD_MODKEY_RCTRL;
+ case KEY_LEFTALT: return KEYBOARD_MODKEY_LALT;
+ case KEY_RIGHTALT: return KEYBOARD_MODKEY_RALT;
+ case KEY_LEFTMETA: return KEYBOARD_MODKEY_LSUPER;
+ case KEY_RIGHTMETA: return KEYBOARD_MODKEY_RSUPER;
+ }
+ return 0;
+}
+
+static void keyboard_event_process_input_event_data(keyboard_event *self, event_extra_data *extra_data, int fd) {
+ struct input_event event;
+ if(read(fd, &event, sizeof(event)) != sizeof(event)) {
+ fprintf(stderr, "Error: failed to read input event data\n");
+ return;
+ }
+
+ if(event.type == EV_SYN && event.code == SYN_DROPPED) {
+ /* TODO: Don't do this on every SYN_DROPPED to prevent spamming this, instead wait until the next event or wait for timeout */
+ keyboard_event_fetch_update_key_states(self, extra_data, fd);
+ return;
+ }
+
+ //if(event.type == EV_KEY && event.code == KEY_A && event.value == KEY_PRESS) {
+ //fprintf(stderr, "fd: %d, type: %d, pressed %d, value: %d\n", fd, event.type, event.code, event.value);
+ //}
+
+ if(event.type == EV_KEY && is_keyboard_key(event.code)) {
+ keyboard_event_process_key_state_change(self, &event, extra_data, fd);
+ const uint32_t modifier_bit = keycode_to_modifier_bit(event.code);
+ if(modifier_bit == 0) {
+ if(keyboard_event_on_key_pressed(self, &event, self->modifier_button_states))
+ return;
+ } else {
+ self->modifier_button_states = set_bit(self->modifier_button_states, modifier_bit, event.value >= 1);
+ }
+ }
+
+ if(extra_data->grabbed) {
+ /* TODO: What to do on error? */
+ if(write(self->uinput_fd, &event, sizeof(event)) != sizeof(event))
+ fprintf(stderr, "Error: failed to write event data to virtual keyboard for exclusively grabbed device\n");
+ }
+}
+
+/* Retarded linux takes very long time to close /dev/input/eventN files, even though they are virtual and opened read-only */
+static void* keyboard_event_close_fds_callback(void *userdata) {
+ keyboard_event *self = userdata;
+ while(self->running) {
+ pthread_mutex_lock(&self->close_dev_input_mutex);
+ for(int i = 0; i < self->num_close_fds; ++i) {
+ close(self->close_fds[i]);
+ }
+ self->num_close_fds = 0;
+ pthread_mutex_unlock(&self->close_dev_input_mutex);
+
+ usleep(100 * 1000); /* 100 milliseconds */
+ }
+ return NULL;
+}
+
+static bool keyboard_event_try_add_close_fd(keyboard_event *self, int fd) {
+ bool success = false;
+ pthread_mutex_lock(&self->close_dev_input_mutex);
+ if(self->num_close_fds < MAX_CLOSE_FDS) {
+ self->close_fds[self->num_close_fds] = fd;
+ ++self->num_close_fds;
+ success = true;
+ } else {
+ success = false;
+ }
+ pthread_mutex_unlock(&self->close_dev_input_mutex);
+ return success;
+}
+
+/* Returns -1 if invalid format. Expected |dev_input_filepath| to be in format /dev/input/eventN */
+static int get_dev_input_id_from_filepath(const char *dev_input_filepath) {
+ if(strncmp(dev_input_filepath, "/dev/input/event", 16) != 0)
+ return -1;
+
+ int dev_input_id = -1;
+ if(sscanf(dev_input_filepath + 16, "%d", &dev_input_id) == 1)
+ return dev_input_id;
+ return -1;
+}
+
+static bool keyboard_event_has_event_with_dev_input_fd(keyboard_event *self, int dev_input_id) {
+ for(int i = 0; i < self->num_event_polls; ++i) {
+ if(self->event_extra_data[i].dev_input_id == dev_input_id)
+ return true;
+ }
+ return false;
+}
+
+/* TODO: Is there a more efficient way to do this? */
+static bool dev_input_is_virtual(int dev_input_id) {
+ DIR *dir = opendir("/sys/devices/virtual/input");
+ if(!dir)
+ return false;
+
+ bool is_virtual = false;
+ char virtual_input_filepath[1024];
+ for(;;) {
+ struct dirent *entry = readdir(dir);
+ if(!entry)
+ break;
+
+ if(strncmp(entry->d_name, "input", 5) != 0)
+ continue;
+
+ snprintf(virtual_input_filepath, sizeof(virtual_input_filepath), "/sys/devices/virtual/input/%s/event%d", entry->d_name, dev_input_id);
+ if(access(virtual_input_filepath, F_OK) == 0) {
+ is_virtual = true;
+ break;
+ }
+ }
+
+ closedir(dir);
+ return is_virtual;
+}
+
+static bool keyboard_event_try_add_device_if_keyboard(keyboard_event *self, const char *dev_input_filepath) {
+ const int dev_input_id = get_dev_input_id_from_filepath(dev_input_filepath);
+ if(dev_input_id == -1)
+ return false;
+
+ const bool is_virtual_device = dev_input_is_virtual(dev_input_id);
+ if(self->grab_type == KEYBOARD_GRAB_TYPE_VIRTUAL && !is_virtual_device)
+ return false;
+
+ if(keyboard_event_has_event_with_dev_input_fd(self, dev_input_id))
+ return false;
+
+ const int fd = open(dev_input_filepath, O_RDONLY);
+ if(fd == -1)
+ return false;
+
+ char device_name[256];
+ device_name[0] = '\0';
+ ioctl(fd, EVIOCGNAME(sizeof(device_name)), device_name);
+
+ unsigned long evbit = 0;
+ ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), &evbit);
+ const bool is_keyboard = (evbit & (1 << EV_SYN)) && (evbit & (1 << EV_KEY));
+
+ if(is_keyboard && strcmp(device_name, GSR_UI_VIRTUAL_KEYBOARD_NAME) != 0) {
+ unsigned char key_bits[KEY_MAX/8 + 1] = {0};
+ ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)), &key_bits);
+
+ const bool supports_key_events = key_bits[KEY_A/8] & (1 << (KEY_A % 8));
+ const bool supports_mouse_events = key_bits[BTN_MOUSE/8] & (1 << (BTN_MOUSE % 8));
+ //const bool supports_touch_events = key_bits[BTN_TOUCH/8] & (1 << (BTN_TOUCH % 8));
+ const bool supports_joystick_events = key_bits[BTN_JOYSTICK/8] & (1 << (BTN_JOYSTICK % 8));
+ const bool supports_wheel_events = key_bits[BTN_WHEEL/8] & (1 << (BTN_WHEEL % 8));
+ if(supports_key_events && (is_virtual_device || (!supports_joystick_events && !supports_wheel_events))) {
+ unsigned char *key_states = calloc(1, KEY_STATES_SIZE);
+ if(key_states && self->num_event_polls < MAX_EVENT_POLLS) {
+ //fprintf(stderr, "%s (%s) supports key inputs\n", dev_input_filepath, device_name);
+ self->event_polls[self->num_event_polls] = (struct pollfd) {
+ .fd = fd,
+ .events = POLLIN,
+ .revents = 0
+ };
+
+ self->event_extra_data[self->num_event_polls] = (event_extra_data) {
+ .dev_input_id = dev_input_id,
+ .grabbed = false,
+ .key_states = key_states,
+ .num_keys_pressed = 0
+ };
+
+ if(supports_mouse_events || supports_joystick_events || supports_wheel_events) {
+ fprintf(stderr, "Info: device not grabbed yet because it might be a mouse: /dev/input/event%d\n", dev_input_id);
+ fsync(fd);
+ if(ioctl(fd, EVIOCGKEY(KEY_STATES_SIZE), self->event_extra_data[self->num_event_polls].key_states) == -1)
+ fprintf(stderr, "Warning: failed to fetch key states for device: /dev/input/event%d\n", dev_input_id);
+ } else {
+ keyboard_event_fetch_update_key_states(self, &self->event_extra_data[self->num_event_polls], fd);
+ if(self->event_extra_data[self->num_event_polls].num_keys_pressed > 0)
+ fprintf(stderr, "Info: device not grabbed yet because some keys are still being pressed: /dev/input/event%d\n", dev_input_id);
+ }
+
+ ++self->num_event_polls;
+ return true;
+ } else {
+ fprintf(stderr, "Warning: the maximum number of keyboard devices have been registered. The newly added keyboard will be ignored\n");
+ }
+ }
+ }
+
+ if(!keyboard_event_try_add_close_fd(self, fd)) {
+ fprintf(stderr, "Error: failed to add immediately, closing now\n");
+ close(fd);
+ }
+ return false;
+}
+
+static bool keyboard_event_add_dev_input_devices(keyboard_event *self) {
+ DIR *dir = opendir("/dev/input");
+ if(!dir) {
+ fprintf(stderr, "error: failed to open /dev/input, error: %s\n", strerror(errno));
+ return false;
+ }
+
+ char dev_input_filepath[1024];
+ for(;;) {
+ struct dirent *entry = readdir(dir);
+ if(!entry)
+ break;
+
+ if(strncmp(entry->d_name, "event", 5) != 0)
+ continue;
+
+ snprintf(dev_input_filepath, sizeof(dev_input_filepath), "/dev/input/%s", entry->d_name);
+ keyboard_event_try_add_device_if_keyboard(self, dev_input_filepath);
+ }
+
+ closedir(dir);
+ return true;
+}
+
+static void keyboard_event_remove_event(keyboard_event *self, int index) {
+ if(index < 0 || index >= self->num_event_polls)
+ return;
+
+ ioctl(self->event_polls[index].fd, EVIOCGRAB, 0);
+ close(self->event_polls[index].fd);
+ free(self->event_extra_data[index].key_states);
+
+ for(int i = index + 1; i < self->num_event_polls; ++i) {
+ self->event_polls[i - 1] = self->event_polls[i];
+ self->event_extra_data[i - 1] = self->event_extra_data[i];
+ }
+ --self->num_event_polls;
+}
+
+/* Returns the fd to the uinput */
+/* Documented here: https://www.kernel.org/doc/html/v4.12/input/uinput.html */
+static int setup_virtual_keyboard_input(const char *name) {
+ /* TODO: O_NONBLOCK? */
+ int fd = open("/dev/uinput", O_WRONLY);
+ if(fd == -1) {
+ fd = open("/dev/input/uinput", O_WRONLY);
+ if(fd == -1) {
+ fprintf(stderr, "Warning: failed to setup virtual device for exclusive grab (failed to open /dev/uinput or /dev/input/uinput), error: %s\n", strerror(errno));
+ return -1;
+ }
+ }
+
+ bool success = true;
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_SYN) != -1);
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_MSC) != -1);
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_KEY) != -1);
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_REP) != -1);
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_REL) != -1);
+ success &= (ioctl(fd, UI_SET_EVBIT, EV_LED) != -1);
+
+ success &= (ioctl(fd, UI_SET_MSCBIT, MSC_SCAN) != -1);
+ for(int i = 1; i < KEY_MAX; ++i) {
+ if(is_keyboard_key(i) || is_mouse_button(i))
+ success &= (ioctl(fd, UI_SET_KEYBIT, i) != -1);
+ }
+ for(int i = 0; i < REL_MAX; ++i) {
+ success &= (ioctl(fd, UI_SET_RELBIT, i) != -1);
+ }
+ for(int i = 0; i < LED_MAX; ++i) {
+ success &= (ioctl(fd, UI_SET_LEDBIT, i) != -1);
+ }
+
+ // success &= (ioctl(fd, UI_SET_EVBIT, EV_ABS) != -1);
+ // success &= (ioctl(fd, UI_SET_ABSBIT, ABS_X) != -1);
+ // success &= (ioctl(fd, UI_SET_ABSBIT, ABS_Y) != -1);
+ // success &= (ioctl(fd, UI_SET_ABSBIT, ABS_Z) != -1);
+
+ int ui_version = 0;
+ success &= (ioctl(fd, UI_GET_VERSION, &ui_version) != -1);
+
+ if(ui_version >= 5) {
+ struct uinput_setup usetup;
+ memset(&usetup, 0, sizeof(usetup));
+ usetup.id.bustype = BUS_USB;
+ usetup.id.vendor = 0xdec0;
+ usetup.id.product = 0x5eba;
+ snprintf(usetup.name, sizeof(usetup.name), "%s", name);
+ success &= (ioctl(fd, UI_DEV_SETUP, &usetup) != -1);
+ } else {
+ struct uinput_user_dev uud;
+ memset(&uud, 0, sizeof(uud));
+ snprintf(uud.name, UINPUT_MAX_NAME_SIZE, "%s", name);
+ if(write(fd, &uud, sizeof(uud)) != sizeof(uud))
+ success = false;
+ }
+
+ success &= (ioctl(fd, UI_DEV_CREATE) != -1);
+ if(!success) {
+ close(fd);
+ return -1;
+ }
+
+ return fd;
+}
+
+bool keyboard_event_init(keyboard_event *self, bool exclusive_grab, keyboard_grab_type grab_type) {
+ memset(self, 0, sizeof(*self));
+ self->stdin_event_index = -1;
+ self->hotplug_event_index = -1;
+ self->grab_type = grab_type;
+ self->running = true;
+
+ pthread_mutex_init(&self->close_dev_input_mutex, NULL);
+ if(pthread_create(&self->close_dev_input_fds_thread, NULL, keyboard_event_close_fds_callback, self) != 0) {
+ self->close_dev_input_fds_thread = 0;
+ fprintf(stderr, "Error: failed to create close fds thread\n");
+ return false;
+ }
+
+ if(exclusive_grab) {
+ self->uinput_fd = setup_virtual_keyboard_input(GSR_UI_VIRTUAL_KEYBOARD_NAME);
+ if(self->uinput_fd <= 0)
+ fprintf(stderr, "Warning: failed to setup virtual keyboard input for exclusive grab. The focused application will receive keys used for global hotkeys\n");
+ }
+
+ self->event_polls[self->num_event_polls] = (struct pollfd) {
+ .fd = STDIN_FILENO,
+ .events = POLLIN,
+ .revents = 0
+ };
+
+ self->event_extra_data[self->num_event_polls] = (event_extra_data) {
+ .dev_input_id = -1,
+ .grabbed = false,
+ .key_states = NULL,
+ .num_keys_pressed = 0
+ };
+
+ self->stdin_event_index = self->num_event_polls;
+ ++self->num_event_polls;
+
+ if(hotplug_event_init(&self->hotplug_ev)) {
+ self->event_polls[self->num_event_polls] = (struct pollfd) {
+ .fd = hotplug_event_steal_fd(&self->hotplug_ev),
+ .events = POLLIN,
+ .revents = 0
+ };
+
+ self->event_extra_data[self->num_event_polls] = (event_extra_data) {
+ .dev_input_id = -1,
+ .grabbed = false,
+ .key_states = NULL,
+ .num_keys_pressed = 0
+ };
+
+ self->hotplug_event_index = self->num_event_polls;
+ ++self->num_event_polls;
+ } else {
+ fprintf(stderr, "Warning: failed to setup hotplugging\n");
+ }
+
+ keyboard_event_add_dev_input_devices(self);
+
+ /* Neither hotplugging nor any keyboard devices were found. We will never listen to keyboard events so might as well fail */
+ if(self->num_event_polls == 0) {
+ keyboard_event_deinit(self);
+ return false;
+ }
+
+ return true;
+}
+
+void keyboard_event_deinit(keyboard_event *self) {
+ self->running = false;
+
+ for(int i = 0; i < self->num_global_hotkeys; ++i) {
+ free(self->global_hotkeys[i].action);
+ }
+ self->num_global_hotkeys = 0;
+
+ if(self->uinput_fd > 0) {
+ ioctl(self->uinput_fd, UI_DEV_DESTROY);
+ close(self->uinput_fd);
+ self->uinput_fd = -1;
+ }
+
+ for(int i = 0; i < self->num_event_polls; ++i) {
+ ioctl(self->event_polls[i].fd, EVIOCGRAB, 0);
+ close(self->event_polls[i].fd);
+ free(self->event_extra_data[i].key_states);
+ }
+ self->num_event_polls = 0;
+
+ hotplug_event_deinit(&self->hotplug_ev);
+
+ if(self->close_dev_input_fds_thread > 0) {
+ pthread_join(self->close_dev_input_fds_thread, NULL);
+ self->close_dev_input_fds_thread = 0;
+ }
+
+ pthread_mutex_destroy(&self->close_dev_input_mutex);
+}
+
+static void on_device_added_callback(const char *devname, void *userdata) {
+ keyboard_event *keyboard_ev = userdata;
+ char dev_input_filepath[256];
+ snprintf(dev_input_filepath, sizeof(dev_input_filepath), "/dev/%s", devname);
+ keyboard_event_try_add_device_if_keyboard(keyboard_ev, dev_input_filepath);
+}
+
+/* Returns -1 on error */
+static int parse_u8(const char *str, int size) {
+ if(size <= 0)
+ return -1;
+
+ int result = 0;
+ for(int i = 0; i < size; ++i) {
+ char c = str[i];
+ if(c >= '0' && c <= '9') {
+ result = result * 10 + (c - '0');
+ if(result > 255)
+ return -1;
+ } else {
+ return -1;
+ }
+ }
+ return result;
+}
+
+static bool keyboard_event_parse_bind_keys(const char *str, int size, uint8_t *key, uint32_t *modifiers) {
+ *key = 0;
+ *modifiers = 0;
+
+ const char *number_start = str;
+ const char *end = str + size;
+ for(;;) {
+ const char *next = strchr(number_start, '+');
+ if(!next)
+ next = end;
+
+ const int number_len = next - number_start;
+ const int number = parse_u8(number_start, number_len);
+ if(number == -1) {
+ fprintf(stderr, "Error: bind command keys \"%s\" is in invalid format\n", str);
+ return false;
+ }
+
+ const uint32_t modifier_bit = keycode_to_modifier_bit(number);
+ if(modifier_bit == 0) {
+ if(*key != 0) {
+ fprintf(stderr, "Error: can't bind hotkey with multiple non-modifier keys\n");
+ return false;
+ }
+ *key = number;
+ } else {
+ *modifiers = set_bit(*modifiers, modifier_bit, true);
+ }
+
+ number_start = next + 1;
+ if(next == end)
+ break;
+ }
+
+ if(key == 0) {
+ fprintf(stderr, "Error: can't bind hotkey without a non-modifier key\n");
+ return false;
+ }
+
+ if(modifiers == 0) {
+ fprintf(stderr, "Error: can't bind hotkey without a modifier\n");
+ return false;
+ }
+
+ return true;
+}
+
+/* |command| is null-terminated */
+static void keyboard_event_parse_stdin_command(keyboard_event *self, const char *command, int command_size) {
+ if(strncmp(command, "bind ", 5) == 0) {
+ /* Example: |bind show_hide 20+40| */
+ if(self->num_global_hotkeys >= MAX_GLOBAL_HOTKEYS) {
+ fprintf(stderr, "Error: can't add another hotkey. The maximum number of hotkeys (%d) has been reached\n", MAX_GLOBAL_HOTKEYS);
+ return;
+ }
+
+ const char *action_name_end = strchr(command + 5, ' ');
+ if(!action_name_end) {
+ fprintf(stderr, "Error: command \"%s\" is in invalid format\n", command);
+ return;
+ }
+
+ const char *action_name = command + 5;
+ const int action_name_size = action_name_end - action_name;
+
+ uint8_t key = 0;
+ uint32_t modifiers = 0;
+ const char *number_start = action_name_end + 1;
+ const char *end = command + command_size;
+ if(!keyboard_event_parse_bind_keys(number_start, end - number_start, &key, &modifiers))
+ return;
+
+ char *action = strndup(action_name, action_name_size);
+ if(!action) {
+ fprintf(stderr, "Error: failed to duplicate %.*s\n", action_name_size, action_name);
+ return;
+ }
+
+ self->global_hotkeys[self->num_global_hotkeys] = (global_hotkey) {
+ .action = action,
+ .key = key,
+ .modifiers = modifiers
+ };
+ ++self->num_global_hotkeys;
+ fprintf(stderr, "Info: binded hotkey: %s\n", action);
+ } else if(strncmp(command, "unbind_all", 10) == 0) {
+ for(int i = 0; i < self->num_global_hotkeys; ++i) {
+ free(self->global_hotkeys[i].action);
+ }
+ self->num_global_hotkeys = 0;
+ fprintf(stderr, "Info: unbinded all hotkeys\n");
+ } else {
+ fprintf(stderr, "Warning: got invalid command: \"%s\", expected command to start with either \"bind\" or \"unbind_all\"\n", command);
+ }
+}
+
+static void keyboard_event_process_stdin_command_data(keyboard_event *self, int fd) {
+ const int num_bytes_to_read = sizeof(self->stdin_command_data) - self->stdin_command_data_size;
+ if(num_bytes_to_read == 0) {
+ fprintf(stderr, "Error: failed to read data from stdin, buffer is full. Clearing buffer\n");
+ self->stdin_command_data_size = 0;
+ return;
+ }
+
+ const ssize_t bytes_read = read(fd, self->stdin_command_data + self->stdin_command_data_size, num_bytes_to_read);
+ if(bytes_read <= 0)
+ return;
+
+ const char *command_start = self->stdin_command_data;
+ const char *search = self->stdin_command_data + self->stdin_command_data_size;
+ const char *end = search + bytes_read;
+ self->stdin_command_data_size += bytes_read;
+
+ for(;;) {
+ char *next = memchr(search, '\n', end - search);
+ if(!next)
+ break;
+
+ *next = '\0';
+ keyboard_event_parse_stdin_command(self, command_start, next - command_start);
+ search = next + 1;
+ command_start = search;
+ if(next == end)
+ break;
+ }
+
+ const int bytes_parsed = command_start - self->stdin_command_data;
+ if(bytes_parsed > 0) {
+ self->stdin_command_data_size -= bytes_parsed;
+ memmove(self->stdin_command_data, command_start, self->stdin_command_data_size);
+ }
+}
+
+void keyboard_event_poll_events(keyboard_event *self, int timeout_milliseconds) {
+ if(poll(self->event_polls, self->num_event_polls, timeout_milliseconds) <= 0)
+ return;
+
+ if(self->stdin_failed)
+ return;
+
+ for(int i = 0; i < self->num_event_polls; ++i) {
+ if(i == self->stdin_event_index && (self->event_polls[i].revents & (POLLHUP|POLLERR)))
+ self->stdin_failed = true;
+
+ if(self->event_polls[i].revents & POLLHUP) { /* TODO: What if this is the hotplug fd? */
+ keyboard_event_remove_event(self, i);
+ --i; /* Repeat same index since the current element has been removed */
+ continue;
+ }
+
+ if(!(self->event_polls[i].revents & POLLIN))
+ continue;
+
+ if(i == self->hotplug_event_index) {
+ /* Device is added to end of |event_polls| so it's ok to add while iterating it via index */
+ hotplug_event_process_event_data(&self->hotplug_ev, self->event_polls[i].fd, on_device_added_callback, self);
+ } else if(i == self->stdin_event_index) {
+ keyboard_event_process_stdin_command_data(self, self->event_polls[i].fd);
+ } else {
+ keyboard_event_process_input_event_data(self, &self->event_extra_data[i], self->event_polls[i].fd);
+ }
+ }
+}
+
+bool keyboard_event_stdin_has_failed(const keyboard_event *self) {
+ return self->stdin_failed;
+}
diff --git a/tools/gsr-global-hotkeys/keyboard_event.h b/tools/gsr-global-hotkeys/keyboard_event.h
new file mode 100644
index 0000000..a86b3dd
--- /dev/null
+++ b/tools/gsr-global-hotkeys/keyboard_event.h
@@ -0,0 +1,92 @@
+#ifndef KEYBOARD_EVENT_H
+#define KEYBOARD_EVENT_H
+
+/* Read keyboard input from linux /dev/input/eventN devices, with hotplug support */
+
+#include "hotplug.h"
+
+/* C stdlib */
+#include <stdbool.h>
+#include <stdint.h>
+
+/* POSIX */
+#include <poll.h>
+#include <pthread.h>
+
+/* LINUX */
+#include <linux/input-event-codes.h>
+
+#define MAX_EVENT_POLLS 32
+#define MAX_CLOSE_FDS 256
+#define MAX_GLOBAL_HOTKEYS 32
+
+typedef enum {
+ KEYBOARD_MODKEY_LALT = 1 << 0,
+ KEYBOARD_MODKEY_RALT = 1 << 1,
+ KEYBOARD_MODKEY_LSUPER = 1 << 2,
+ KEYBOARD_MODKEY_RSUPER = 1 << 3,
+ KEYBOARD_MODKEY_LCTRL = 1 << 4,
+ KEYBOARD_MODKEY_RCTRL = 1 << 5,
+ KEYBOARD_MODKEY_LSHIFT = 1 << 6,
+ KEYBOARD_MODKEY_RSHIFT = 1 << 7
+} keyboard_modkeys;
+
+typedef enum {
+ KEYBOARD_BUTTON_RELEASED,
+ KEYBOARD_BUTTON_PRESSED
+} keyboard_button_state;
+
+typedef struct {
+ int dev_input_id;
+ bool grabbed;
+ unsigned char *key_states;
+ int num_keys_pressed;
+} event_extra_data;
+
+typedef enum {
+ KEYBOARD_GRAB_TYPE_ALL,
+ KEYBOARD_GRAB_TYPE_VIRTUAL
+} keyboard_grab_type;
+
+typedef struct {
+ uint32_t key;
+ uint32_t modifiers; /* keyboard_modkeys bitmask */
+ char *action;
+} global_hotkey;
+
+typedef struct {
+ struct pollfd event_polls[MAX_EVENT_POLLS]; /* Current size is |num_event_polls| */
+ event_extra_data event_extra_data[MAX_EVENT_POLLS]; /* Current size is |num_event_polls| */
+ int num_event_polls;
+
+ int stdin_event_index;
+ int hotplug_event_index;
+ int uinput_fd;
+ bool stdin_failed;
+ keyboard_grab_type grab_type;
+
+ pthread_t close_dev_input_fds_thread;
+ pthread_mutex_t close_dev_input_mutex;
+ int close_fds[MAX_CLOSE_FDS];
+ int num_close_fds;
+ bool running;
+
+ char stdin_command_data[512];
+ int stdin_command_data_size;
+
+ global_hotkey global_hotkeys[MAX_GLOBAL_HOTKEYS];
+ int num_global_hotkeys;
+
+ hotplug_event hotplug_ev;
+
+ uint32_t modifier_button_states;
+} keyboard_event;
+
+bool keyboard_event_init(keyboard_event *self, bool exclusive_grab, keyboard_grab_type grab_type);
+void keyboard_event_deinit(keyboard_event *self);
+
+/* If |timeout_milliseconds| is -1 then wait until an event is received */
+void keyboard_event_poll_events(keyboard_event *self, int timeout_milliseconds);
+bool keyboard_event_stdin_has_failed(const keyboard_event *self);
+
+#endif /* KEYBOARD_EVENT_H */
diff --git a/tools/gsr-global-hotkeys/keys.c b/tools/gsr-global-hotkeys/keys.c
new file mode 100644
index 0000000..3b8fc8a
--- /dev/null
+++ b/tools/gsr-global-hotkeys/keys.c
@@ -0,0 +1,21 @@
+#include "keys.h"
+#include <linux/input-event-codes.h>
+
+bool is_keyboard_key(uint32_t keycode) {
+ return (keycode >= KEY_ESC && keycode <= KEY_KPDOT)
+ || (keycode >= KEY_ZENKAKUHANKAKU && keycode <= KEY_F24)
+ || (keycode >= KEY_PLAYCD && keycode <= KEY_MICMUTE)
+ || (keycode >= KEY_OK && keycode <= KEY_IMAGES)
+ || (keycode >= KEY_DEL_EOL && keycode <= KEY_DEL_LINE)
+ || (keycode >= KEY_FN && keycode <= KEY_FN_B)
+ || (keycode >= KEY_BRL_DOT1 && keycode <= KEY_BRL_DOT10)
+ || (keycode >= KEY_NUMERIC_0 && keycode <= KEY_LIGHTS_TOGGLE)
+ || (keycode == KEY_ALS_TOGGLE)
+ || (keycode >= KEY_BUTTONCONFIG && keycode <= KEY_VOICECOMMAND)
+ || (keycode >= KEY_BRIGHTNESS_MIN && keycode <= KEY_BRIGHTNESS_MAX)
+ || (keycode >= KEY_KBDINPUTASSIST_PREV && keycode <= KEY_ONSCREEN_KEYBOARD);
+}
+
+bool is_mouse_button(uint32_t keycode) {
+ return (keycode >= BTN_MOUSE && keycode <= BTN_TASK);
+}
diff --git a/tools/gsr-global-hotkeys/keys.h b/tools/gsr-global-hotkeys/keys.h
new file mode 100644
index 0000000..4f31882
--- /dev/null
+++ b/tools/gsr-global-hotkeys/keys.h
@@ -0,0 +1,10 @@
+#ifndef KEYS_H
+#define KEYS_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+bool is_keyboard_key(uint32_t keycode);
+bool is_mouse_button(uint32_t keycode);
+
+#endif /* KEYS_H */
diff --git a/tools/gsr-global-hotkeys/main.c b/tools/gsr-global-hotkeys/main.c
index 11eaee5..41e5ca5 100644
--- a/tools/gsr-global-hotkeys/main.c
+++ b/tools/gsr-global-hotkeys/main.c
@@ -1,244 +1,90 @@
+#include "keyboard_event.h"
+
+/* C stdlib */
#include <stdio.h>
-#include <unistd.h>
-#include <fcntl.h>
#include <string.h>
-#include <errno.h>
-#include <stdbool.h>
-#include <poll.h>
-
-#include <libudev.h>
-#include <libinput.h>
-#include <libevdev/libevdev.h>
-#include <xkbcommon/xkbcommon.h>
-
-typedef struct {
- struct xkb_context *xkb_context;
- struct xkb_keymap *xkb_keymap;
- struct xkb_state *xkb_state;
-} key_mapper;
-
-typedef enum {
- MODKEY_ALT = 1 << 0,
- MODKEY_SUPER = 1 << 1,
- MODKEY_CTRL = 1 << 2,
- MODKEY_SHIFT = 1 << 3
-} modkeys;
-
-typedef struct {
- uint32_t key;
- uint32_t modifiers; /* modkeys */
- const char *action;
-} global_hotkey;
-
-#define NUM_GLOBAL_HOTKEYS 6
-static global_hotkey global_hotkeys[NUM_GLOBAL_HOTKEYS] = {
- { .key = XKB_KEY_z, .modifiers = MODKEY_ALT, .action = "show_hide" },
- { .key = XKB_KEY_F9, .modifiers = MODKEY_ALT, .action = "record" },
- { .key = XKB_KEY_F7, .modifiers = MODKEY_ALT, .action = "pause" },
- { .key = XKB_KEY_F8, .modifiers = MODKEY_ALT, .action = "stream" },
- { .key = XKB_KEY_F10, .modifiers = MODKEY_ALT | MODKEY_SHIFT, .action = "replay_start" },
- { .key = XKB_KEY_F10, .modifiers = MODKEY_ALT, .action = "replay_save" }
-};
-
-static int open_restricted(const char *path, int flags, void *user_data) {
- (void)user_data;
- int fd = open(path, flags);
- if(fd < 0)
- fprintf(stderr, "error: failed to open %s, error: %s\n", path, strerror(errno));
- return fd < 0 ? -errno : fd;
-}
+#include <locale.h>
-static void close_restricted(int fd, void *user_data) {
- (void)user_data;
- close(fd);
-}
-
-static const struct libinput_interface interface = {
- .open_restricted = open_restricted,
- .close_restricted = close_restricted,
-};
-
-static bool is_mod_key(xkb_keycode_t xkb_key_code) {
- return xkb_key_code >= XKB_KEY_Shift_L && xkb_key_code <= XKB_KEY_Hyper_R;
-}
-
-typedef struct {
- const char *modname;
- modkeys key;
-} modname_to_modkey_map;
-
-static uint32_t xkb_state_to_modifiers(struct xkb_state *xkb_state) {
- const modname_to_modkey_map modifier_keys[] = {
- { .modname = XKB_MOD_NAME_ALT, .key = MODKEY_ALT },
- { .modname = XKB_MOD_NAME_LOGO, .key = MODKEY_SUPER },
- { .modname = XKB_MOD_NAME_SHIFT, .key = MODKEY_SHIFT },
- { .modname = XKB_MOD_NAME_CTRL, .key = MODKEY_CTRL }
- };
+/* POSIX */
+#include <unistd.h>
- uint32_t modifiers = 0;
- for(int i = 0; i < 4; ++i) {
- if(xkb_state_mod_name_is_active(xkb_state, modifier_keys[i].modname, XKB_STATE_MODS_EFFECTIVE) > 0)
- modifiers |= modifier_keys[i].key;
- }
- return modifiers;
+static void usage(void) {
+ fprintf(stderr, "usage: gsr-global-hotkeys [--all|--virtual]\n");
+ fprintf(stderr, "OPTIONS:\n");
+ fprintf(stderr, " --all Grab all devices.\n");
+ fprintf(stderr, " --virtual Grab all virtual devices only.\n");
}
-#define KEY_CODE_EV_TO_XKB(key) ((key) + 8)
-
-static int print_key_event(struct libinput_event *event, key_mapper *mapper) {
- struct libinput_event_keyboard *keyboard = libinput_event_get_keyboard_event(event);
- const uint32_t key_code = libinput_event_keyboard_get_key(keyboard);
- enum libinput_key_state state_code = libinput_event_keyboard_get_key_state(keyboard);
-
- const xkb_keycode_t xkb_key_code = KEY_CODE_EV_TO_XKB(key_code);
- xkb_state_update_key(mapper->xkb_state, xkb_key_code, state_code == LIBINPUT_KEY_STATE_PRESSED ? XKB_KEY_DOWN : XKB_KEY_UP);
- xkb_keysym_t xkb_key_sym = xkb_state_key_get_one_sym(mapper->xkb_state, xkb_key_code);
- // char main_key[128];
- // main_key[0] = '\0';
-
- // if(xkb_state_mod_name_is_active(mapper->xkb_state, XKB_MOD_NAME_LOGO, XKB_STATE_MODS_EFFECTIVE) > 0)
- // strcat(main_key, "Super+");
- // if(xkb_state_mod_name_is_active(mapper->xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE) > 0)
- // strcat(main_key, "Ctrl+");
- // if(xkb_state_mod_name_is_active(mapper->xkb_state, XKB_MOD_NAME_ALT, XKB_STATE_MODS_EFFECTIVE) > 0 && strcmp(main_key, "Meta") != 0)
- // strcat(main_key, "Alt+");
- // if(xkb_state_mod_name_is_active(mapper->xkb_state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE) > 0)
- // strcat(main_key, "Shift+");
-
- // if(!is_mod_key(xkb_key_sym)) {
- // char reg_key[64];
- // reg_key[0] = '\0';
- // xkb_keysym_get_name(xkb_key_sym, reg_key, sizeof(reg_key));
- // strcat(main_key, reg_key);
- // }
-
- if(state_code != LIBINPUT_KEY_STATE_PRESSED)
- return 0;
+static bool is_gsr_global_hotkeys_already_running(void) {
+ FILE *f = fopen("/proc/bus/input/devices", "rb");
+ if(!f)
+ return false;
- const uint32_t current_modifiers = xkb_state_to_modifiers(mapper->xkb_state);
- for(int i = 0; i < NUM_GLOBAL_HOTKEYS; ++i) {
- if(xkb_key_sym == global_hotkeys[i].key && current_modifiers == global_hotkeys[i].modifiers) {
- puts(global_hotkeys[i].action);
- fflush(stdout);
+ bool virtual_keyboard_running = false;
+ char line[1024];
+ while(fgets(line, sizeof(line), f)) {
+ if(strstr(line, "gsr-ui virtual keyboard")) {
+ virtual_keyboard_running = true;
break;
}
}
- return 0;
-}
-
-static int handle_events(struct libinput *libinput, key_mapper *mapper) {
- int result = -1;
- struct libinput_event *event;
-
- if(libinput_dispatch(libinput) < 0)
- return result;
-
- while((event = libinput_get_event(libinput)) != NULL) {
- if(libinput_event_get_type(event) == LIBINPUT_EVENT_KEYBOARD_KEY)
- print_key_event(event, mapper);
-
- libinput_event_destroy(event);
- result = 0;
- }
-
- return result;
+ fclose(f);
+ return virtual_keyboard_running;
}
-static int run_mainloop(struct libinput *libinput, key_mapper *mapper) {
- struct pollfd fd;
- fd.fd = libinput_get_fd(libinput);
- fd.events = POLLIN;
- fd.revents = 0;
-
- if(handle_events(libinput, mapper) != 0) {
- fprintf(stderr, "error: didn't receive device added events. Is this program not running as root?\n");
- return -1;
- }
-
- while(poll(&fd, 1, -1) >= 0) {
- handle_events(libinput, mapper);
- }
-
- return 0;
-}
-
-static bool mapper_refresh_keymap(key_mapper *mapper) {
- if(mapper->xkb_keymap != NULL) {
- xkb_keymap_unref(mapper->xkb_keymap);
- mapper->xkb_keymap = NULL;
- }
-
- // TODO:
- struct xkb_rule_names names = {
- NULL, NULL,
- NULL,//keymap_is_default(mapper->layout) ? NULL : mapper->layout,
- NULL,//keymap_is_default(mapper->variant) ? NULL : mapper->variant,
- NULL
- };
- mapper->xkb_keymap = xkb_keymap_new_from_names(mapper->xkb_context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
- if(mapper->xkb_keymap == NULL) {
- fprintf(stderr, "error: failed to create XKB keymap.\n");
- return false;
- }
-
- if(mapper->xkb_state != NULL) {
- xkb_state_unref(mapper->xkb_state);
- mapper->xkb_state = NULL;
- }
-
- mapper->xkb_state = xkb_state_new(mapper->xkb_keymap);
- if(mapper->xkb_state == NULL) {
- fprintf(stderr, "error: failed to create XKB state.\n");
- return false;
- }
-
- return true;
-}
-
-int main(void) {
- if(geteuid() != 0) {
- if(setuid(0) == -1) {
- fprintf(stderr, "error: failed to change user to root\n");
+int main(int argc, char **argv) {
+ setlocale(LC_ALL, "C"); /* Sigh... stupid C */
+
+ keyboard_grab_type grab_type = KEYBOARD_GRAB_TYPE_ALL;
+ if(argc == 2) {
+ const char *grab_type_arg = argv[1];
+ if(strcmp(grab_type_arg, "--all") == 0) {
+ grab_type = KEYBOARD_GRAB_TYPE_ALL;
+ } else if(strcmp(grab_type_arg, "--virtual") == 0) {
+ grab_type = KEYBOARD_GRAB_TYPE_VIRTUAL;
+ } else {
+ fprintf(stderr, "Error: expected --all or --virtual, got %s\n", grab_type_arg);
+ usage();
return 1;
}
- }
-
- struct udev *udev = udev_new();
- if(!udev) {
- fprintf(stderr, "error: udev_new failed\n");
+ } else if(argc != 1) {
+ fprintf(stderr, "Error: expected 0 or 1 arguments, got %d argument(s)\n", argc);
+ usage();
return 1;
}
- struct libinput *libinput = libinput_udev_create_context(&interface, NULL, udev);
- if(!libinput) {
- fprintf(stderr, "error: libinput_udev_create_context failed\n");
+ if(is_gsr_global_hotkeys_already_running()) {
+ fprintf(stderr, "Error: gsr-global-hotkeys is already running\n");
return 1;
}
- if(libinput_udev_assign_seat(libinput, "seat0") != 0) {
- fprintf(stderr, "error: libinput_udev_assign_seat with seat0 failed\n");
- return 1;
+ const uid_t user_id = getuid();
+ if(geteuid() != 0) {
+ if(setuid(0) == -1) {
+ fprintf(stderr, "Error: failed to change user to root\n");
+ return 1;
+ }
}
- key_mapper mapper;
- mapper.xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
- if(!mapper.xkb_context) {
- fprintf(stderr, "error: xkb_context_new failed\n");
+ keyboard_event keyboard_ev;
+ if(!keyboard_event_init(&keyboard_ev, true, grab_type)) {
+ fprintf(stderr, "Error: failed to setup hotplugging and no keyboard input devices were found\n");
+ setuid(user_id);
return 1;
}
- if(!mapper_refresh_keymap(&mapper)) {
- fprintf(stderr, "error: key mapper failed\n");
- return 1;
- }
+ fprintf(stderr, "Info: global hotkeys setup, waiting for hotkeys to be pressed\n");
- if(run_mainloop(libinput, &mapper) < 0) {
- fprintf(stderr, "error: failed to start main loop\n");
- return 1;
+ for(;;) {
+ keyboard_event_poll_events(&keyboard_ev, -1);
+ if(keyboard_event_stdin_has_failed(&keyboard_ev)) {
+ fprintf(stderr, "Info: stdin closed (parent process likely closed this process), exiting...\n");
+ break;
+ }
}
- libinput_unref(libinput);
- udev_unref(udev);
+ keyboard_event_deinit(&keyboard_ev);
+ setuid(user_id);
return 0;
}
diff --git a/tools/gsr-ui-cli/main.c b/tools/gsr-ui-cli/main.c
new file mode 100644
index 0000000..9f1eb03
--- /dev/null
+++ b/tools/gsr-ui-cli/main.c
@@ -0,0 +1,107 @@
+#include <limits.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+static void get_runtime_filepath(char *buffer, size_t buffer_size, const char *filename) {
+ char dir[PATH_MAX];
+
+ const char *runtime_dir = getenv("XDG_RUNTIME_DIR");
+ if(runtime_dir)
+ snprintf(dir, sizeof(dir), "%s", runtime_dir);
+ else
+ snprintf(dir, sizeof(dir), "/run/user/%d", geteuid());
+
+ if(access(dir, F_OK) != 0)
+ snprintf(dir, sizeof(dir), "/tmp");
+
+ snprintf(buffer, buffer_size, "%s/%s", dir, filename);
+}
+
+/* Assumes |str| size is less than 256 */
+static void fifo_write_all(int file_fd, const char *str) {
+ char command[256];
+ const ssize_t command_size = snprintf(command, sizeof(command), "%s\n", str);
+ if(command_size >= (ssize_t)sizeof(command)) {
+ fprintf(stderr, "Error: command too long: %s\n", str);
+ return;
+ }
+
+ ssize_t offset = 0;
+ while(offset < (ssize_t)command_size) {
+ const ssize_t bytes_written = write(file_fd, str + offset, command_size - offset);
+ if(bytes_written > 0)
+ offset += bytes_written;
+ }
+}
+
+static void usage(void) {
+ printf("usage: gsr-ui-cli <command>\n");
+ printf("Run commands on the running gsr-ui instance.\n");
+ printf("\n");
+ printf("COMMANDS:\n");
+ printf(" toggle-show Show/hide the UI.\n");
+ printf(" toggle-record Start/stop recording.\n");
+ printf(" toggle-pause Pause/unpause recording. Only applies to regular recording.\n");
+ printf(" toggle-stream Start/stop streaming.\n");
+ printf(" toggle-replay Start/stop replay.\n");
+ printf(" replay-save Save replay.\n");
+ printf(" take-screenshot Take a screenshot.\n");
+ printf("\n");
+ printf("EXAMPLES:\n");
+ printf(" gsr-ui-cli toggle-show\n");
+ printf(" gsr-ui-cli toggle-record\n");
+ exit(1);
+}
+
+static bool is_valid_command(const char *command) {
+ const char *commands[] = {
+ "toggle-show",
+ "toggle-record",
+ "toggle-pause",
+ "toggle-stream",
+ "toggle-replay",
+ "replay-save",
+ "take-screenshot",
+ NULL
+ };
+
+ for(int i = 0; commands[i]; ++i) {
+ if(strcmp(command, commands[i]) == 0)
+ return true;
+ }
+
+ return false;
+}
+
+int main(int argc, char **argv) {
+ if(argc != 2) {
+ printf("Error: expected 1 argument, %d provided\n", argc - 1);
+ usage();
+ }
+
+ const char *command = argv[1];
+ if(strcmp(command, "-h") == 0 || strcmp(command, "--help") == 0)
+ usage();
+
+ if(!is_valid_command(command)) {
+ fprintf(stderr, "Error: invalid command: \"%s\"\n", command);
+ usage();
+ }
+
+ char fifo_filepath[PATH_MAX];
+ get_runtime_filepath(fifo_filepath, sizeof(fifo_filepath), "gsr-ui");
+ const int fifo_fd = open(fifo_filepath, O_RDWR | O_NONBLOCK);
+ if(fifo_fd <= 0) {
+ fprintf(stderr, "Error: failed to open fifo file %s. Maybe gsr-ui is not running?\n", fifo_filepath);
+ exit(2);
+ }
+
+ fifo_write_all(fifo_fd, command);
+ close(fifo_fd);
+ return 0;
+}
diff --git a/tools/gsr-window-name/main.c b/tools/gsr-window-name/main.c
deleted file mode 100644
index 8ebf1e0..0000000
--- a/tools/gsr-window-name/main.c
+++ /dev/null
@@ -1,187 +0,0 @@
-#include <X11/Xlib.h>
-#include <X11/Xatom.h>
-#include <X11/Xutil.h>
-
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-typedef enum {
- CAPTURE_TYPE_FOCUSED,
- CAPTURE_TYPE_CURSOR
-} capture_type;
-
-static bool window_has_atom(Display *dpy, Window window, Atom atom) {
- Atom type;
- unsigned long len, bytes_left;
- int format;
- unsigned char *properties = NULL;
- if(XGetWindowProperty(dpy, window, atom, 0, 1024, False, AnyPropertyType, &type, &format, &len, &bytes_left, &properties) < Success)
- return false;
-
- if(properties)
- XFree(properties);
-
- return type != None;
-}
-
-static bool window_is_user_program(Display *dpy, Window window) {
- const Atom net_wm_state_atom = XInternAtom(dpy, "_NET_WM_STATE", False);
- const Atom wm_state_atom = XInternAtom(dpy, "WM_STATE", False);
- return window_has_atom(dpy, window, net_wm_state_atom) || window_has_atom(dpy, window, wm_state_atom);
-}
-
-static Window get_window_at_cursor_position(Display *dpy) {
- Window root_window = None;
- Window window = None;
- int dummy_i;
- unsigned int dummy_u;
- int cursor_pos_x = 0;
- int cursor_pos_y = 0;
- XQueryPointer(dpy, DefaultRootWindow(dpy), &root_window, &window, &dummy_i, &dummy_i, &cursor_pos_x, &cursor_pos_y, &dummy_u);
- return window;
-}
-
-static Window get_focused_window(Display *dpy, capture_type cap_type) {
- const Atom net_active_window_atom = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
- Window focused_window = None;
-
- if(cap_type == CAPTURE_TYPE_FOCUSED) {
- // Atom type = None;
- // int format = 0;
- // unsigned long num_items = 0;
- // unsigned long bytes_left = 0;
- // unsigned char *data = NULL;
- // XGetWindowProperty(dpy, DefaultRootWindow(dpy), net_active_window_atom, 0, 1, False, XA_WINDOW, &type, &format, &num_items, &bytes_left, &data);
-
- // fprintf(stderr, "focused window: %p\n", (void*)data);
-
- // if(type == XA_WINDOW && num_items == 1 && data)
- // return *(Window*)data;
-
- int revert_to = 0;
- XGetInputFocus(dpy, &focused_window, &revert_to);
- if(focused_window && focused_window != DefaultRootWindow(dpy) && window_is_user_program(dpy, focused_window))
- return focused_window;
- }
-
- focused_window = get_window_at_cursor_position(dpy);
- if(focused_window && focused_window != DefaultRootWindow(dpy) && window_is_user_program(dpy, focused_window))
- return focused_window;
-
- return None;
-}
-
-static char* get_window_title(Display *dpy, Window window) {
- const Atom net_wm_name_atom = XInternAtom(dpy, "_NET_WM_NAME", False);
- const Atom wm_name_atom = XInternAtom(dpy, "_NET_WM_NAME", False);
- const Atom utf8_string_atom = XInternAtom(dpy, "UTF8_STRING", False);
-
- Atom type = None;
- int format = 0;
- unsigned long num_items = 0;
- unsigned long bytes_left = 0;
- unsigned char *data = NULL;
- XGetWindowProperty(dpy, window, net_wm_name_atom, 0, 1024, False, utf8_string_atom, &type, &format, &num_items, &bytes_left, &data);
-
- if(type == utf8_string_atom && format == 8 && data)
- return (char*)data;
-
- type = None;
- format = 0;
- num_items = 0;
- bytes_left = 0;
- data = NULL;
- XGetWindowProperty(dpy, window, wm_name_atom, 0, 1024, False, 0, &type, &format, &num_items, &bytes_left, &data);
-
- if((type == XA_STRING || type == utf8_string_atom) && data)
- return (char*)data;
-
- return NULL;
-}
-
-static const char* strip(const char *str, int *len) {
- int str_len = strlen(str);
- for(int i = 0; i < str_len; ++i) {
- if(str[i] != ' ') {
- str += i;
- str_len -= i;
- break;
- }
- }
-
- for(int i = str_len - 1; i >= 0; --i) {
- if(str[i] != ' ') {
- str_len = i + 1;
- break;
- }
- }
-
- *len = str_len;
- return str;
-}
-
-static void print_str_strip(const char *str) {
- int len = 0;
- str = strip(str, &len);
- printf("%.*s", len, str);
-}
-
-static int x11_ignore_error(Display *dpy, XErrorEvent *error_event) {
- (void)dpy;
- (void)error_event;
- return 0;
-}
-
-static void usage(void) {
- fprintf(stderr, "usage: gsr-window-name <focused|cursor>\n");
- fprintf(stderr, "options:\n");
- fprintf(stderr, " focused The class/name of the focused window is returned. If no window is focused then the window beneath the cursor is returned instead\n");
- fprintf(stderr, " cursor The class/name of the window beneath the cursor is returned\n");
- exit(1);
-}
-
-int main(int argc, char **argv) {
- if(argc != 2)
- usage();
-
- const char *cap_type_str = argv[1];
- capture_type cap_type = CAPTURE_TYPE_FOCUSED;
- if(strcmp(cap_type_str, "focused") == 0) {
- cap_type = CAPTURE_TYPE_FOCUSED;
- } else if(strcmp(cap_type_str, "cursor") == 0) {
- cap_type = CAPTURE_TYPE_CURSOR;
- } else {
- fprintf(stderr, "error: invalid option '%s', expected either 'focused' or 'cursor'\n", cap_type_str);
- usage();
- }
-
- Display *dpy = XOpenDisplay(NULL);
- if(!dpy) {
- fprintf(stderr, "Error: failed to connect to the X11 server\n");
- exit(1);
- }
-
- XSetErrorHandler(x11_ignore_error);
-
- const Window focused_window = get_focused_window(dpy, cap_type);
- if(focused_window == None)
- exit(2);
-
- // Window title is not always ideal (for example for a browser), but for games its pretty much required
- char *window_title = get_window_title(dpy, focused_window);
- if(window_title) {
- print_str_strip(window_title);
- exit(0);
- }
-
- XClassHint class_hint = {0};
- XGetClassHint(dpy, focused_window, &class_hint);
- if(class_hint.res_class) {
- print_str_strip(class_hint.res_class);
- exit(0);
- }
-
- return 2;
-}