|
| 1 | +#include <stdio.h> |
| 2 | +#include <errno.h> |
| 3 | +#include <unistd.h> |
| 4 | +#include <libinput.h> |
| 5 | +#include <libudev.h> |
| 6 | +#include <fcntl.h> |
| 7 | +#include <poll.h> |
| 8 | + |
| 9 | +static int open_restricted(const char *path, int flags, void *user_data) { |
| 10 | + int fd = open(path, flags); |
| 11 | + return fd < 0 ? -errno : fd; |
| 12 | +} |
| 13 | + |
| 14 | +static void close_restricted(int fd, void *user_data) { |
| 15 | + close(fd); |
| 16 | +} |
| 17 | + |
| 18 | +int main() { |
| 19 | + if (geteuid()) { |
| 20 | + fprintf(stderr, "Error: this utility requires root privileges (did you forget `sudo`?)\n"); |
| 21 | + return 1; |
| 22 | + } |
| 23 | + |
| 24 | + const static struct libinput_interface file_open_close = { |
| 25 | + .open_restricted = open_restricted, |
| 26 | + .close_restricted = close_restricted, |
| 27 | + }; |
| 28 | + |
| 29 | + struct udev *udev = udev_new(); |
| 30 | + struct libinput *li = libinput_udev_create_context(&file_open_close, 0, udev); |
| 31 | + |
| 32 | + libinput_udev_assign_seat(li, "seat0"); |
| 33 | + |
| 34 | + struct libinput_event *event; |
| 35 | + |
| 36 | + // Exhaust open device events |
| 37 | + libinput_dispatch(li); |
| 38 | + while ((event = libinput_get_event(li))) libinput_event_destroy(event); |
| 39 | + |
| 40 | + struct pollfd pollfd = { |
| 41 | + .fd = libinput_get_fd(li), |
| 42 | + .events = POLLIN, |
| 43 | + .revents = 0 |
| 44 | + }; |
| 45 | + |
| 46 | + while(poll(&pollfd, 1, -1)) { |
| 47 | + libinput_dispatch(li); |
| 48 | + while ((event = libinput_get_event(li))) { |
| 49 | + if (libinput_event_get_type(event) != LIBINPUT_EVENT_SWITCH_TOGGLE) continue; |
| 50 | + struct libinput_event_switch *switch_event = libinput_event_get_switch_event(event); |
| 51 | + if (libinput_event_switch_get_switch(switch_event) != LIBINPUT_SWITCH_TABLET_MODE) continue; |
| 52 | + const char switch_on = libinput_event_switch_get_switch_state(switch_event) == LIBINPUT_SWITCH_STATE_ON; |
| 53 | + printf("%s\n", switch_on ? "TABLET" : "LAPTOP"); |
| 54 | + libinput_event_destroy(event); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + libinput_unref(li); |
| 59 | + udev_unref(udev); |
| 60 | + return 0; |
| 61 | +} |
0 commit comments