platform_linux.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <glib-unix.h>
  4. #include <linux/input.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <sys/ioctl.h>
  8. #include <unistd.h>
  9. #include "platform_linux.h"
  10. static const struct {
  11. unsigned short code;
  12. enum radio_key key;
  13. } keymap[] = {
  14. { KEY_ESC, RK_ESC }, { KEY_NEXTSONG, RK_NEXT }, { KEY_STOPCD, RK_STOP },
  15. { KEY_MENU, RK_MENU }, { KEY_LIST, RK_LIST }, { KEY_UP, RK_UP },
  16. { KEY_PREVIOUSSONG, RK_PREV }, { KEY_RIGHT, RK_RIGHT },
  17. { KEY_DOWN, RK_DOWN }, { KEY_PAUSECD, RK_PAUSE }, { KEY_OK, RK_OK },
  18. { KEY_LEFT, RK_LEFT }, { KEY_PLAYCD, RK_PLAY },
  19. };
  20. static gboolean on_input(gint fd, GIOCondition cond, gpointer data)
  21. {
  22. struct app *app = data;
  23. struct input_event ev;
  24. unsigned int i;
  25. (void)cond;
  26. while (read(fd, &ev, sizeof(ev)) == (ssize_t)sizeof(ev)) {
  27. /* 1 press, 2 autorepeat: app_key() applies the lockout */
  28. if (ev.type != EV_KEY || ev.value == 0)
  29. continue;
  30. for (i = 0; i < G_N_ELEMENTS(keymap); i++)
  31. if (keymap[i].code == ev.code)
  32. app_key(app, keymap[i].key);
  33. }
  34. return G_SOURCE_CONTINUE;
  35. }
  36. static int find_keys_device(void)
  37. {
  38. char path[32], name[64];
  39. int i, fd;
  40. for (i = 0; i < 32; i++) {
  41. snprintf(path, sizeof(path), "/dev/input/event%d", i);
  42. fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
  43. if (fd < 0)
  44. continue;
  45. if (ioctl(fd, EVIOCGNAME(sizeof(name)), name) > 0 &&
  46. !strcmp(name, DEFAULT_KEYS_NAME))
  47. return fd;
  48. close(fd);
  49. }
  50. return -1;
  51. }
  52. bool platform_keys_start(struct app *app, const char *path)
  53. {
  54. int fd = path ? open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) : find_keys_device();
  55. if (fd < 0)
  56. return false;
  57. g_unix_fd_add(fd, G_IO_IN, on_input, app);
  58. return true;
  59. }
  60. void platform_backlight_set(const char *path, bool on)
  61. {
  62. FILE *f;
  63. if (!path)
  64. return;
  65. f = fopen(path, "w");
  66. if (!f)
  67. return;
  68. fputs(on ? "1\n" : "0\n", f);
  69. fclose(f);
  70. }
  71. static gboolean on_signal(gpointer data)
  72. {
  73. g_main_loop_quit(data);
  74. return G_SOURCE_REMOVE;
  75. }
  76. void platform_run(void)
  77. {
  78. GMainLoop *loop = g_main_loop_new(NULL, FALSE);
  79. g_unix_signal_add(SIGINT, on_signal, loop);
  80. g_unix_signal_add(SIGTERM, on_signal, loop);
  81. g_main_loop_run(loop);
  82. g_main_loop_unref(loop);
  83. }