joypad_linux.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*************************************************************************/
  2. /* joypad_linux.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef JOYDEV_ENABLED
  31. #include "joypad_linux.h"
  32. #include <dirent.h>
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #include <linux/input.h>
  36. #include <unistd.h>
  37. #ifdef UDEV_ENABLED
  38. #include "libudev-so_wrap.h"
  39. #endif
  40. #define LONG_BITS (sizeof(long) * 8)
  41. #define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
  42. #define NBITS(x) ((((x)-1) / LONG_BITS) + 1)
  43. #ifdef UDEV_ENABLED
  44. static const char *ignore_str = "/dev/input/js";
  45. #endif
  46. JoypadLinux::Joypad::~Joypad() {
  47. for (int i = 0; i < MAX_ABS; i++) {
  48. if (abs_info[i]) {
  49. memdelete(abs_info[i]);
  50. }
  51. }
  52. }
  53. void JoypadLinux::Joypad::reset() {
  54. dpad = HatMask::CENTER;
  55. fd = -1;
  56. for (int i = 0; i < MAX_ABS; i++) {
  57. abs_map[i] = -1;
  58. curr_axis[i] = 0;
  59. }
  60. }
  61. JoypadLinux::JoypadLinux(Input *in) {
  62. #ifdef UDEV_ENABLED
  63. #ifdef DEBUG_ENABLED
  64. int dylibloader_verbose = 1;
  65. #else
  66. int dylibloader_verbose = 0;
  67. #endif
  68. use_udev = initialize_libudev(dylibloader_verbose) == 0;
  69. if (use_udev) {
  70. print_verbose("JoypadLinux: udev enabled and loaded successfully.");
  71. } else {
  72. print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads.");
  73. }
  74. #else
  75. print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads.");
  76. #endif
  77. input = in;
  78. joy_thread.start(joy_thread_func, this);
  79. }
  80. JoypadLinux::~JoypadLinux() {
  81. exit_monitor.set();
  82. joy_thread.wait_to_finish();
  83. close_joypad();
  84. }
  85. void JoypadLinux::joy_thread_func(void *p_user) {
  86. if (p_user) {
  87. JoypadLinux *joy = (JoypadLinux *)p_user;
  88. joy->run_joypad_thread();
  89. }
  90. }
  91. void JoypadLinux::run_joypad_thread() {
  92. #ifdef UDEV_ENABLED
  93. if (use_udev) {
  94. udev *_udev = udev_new();
  95. if (!_udev) {
  96. use_udev = false;
  97. ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input.");
  98. monitor_joypads();
  99. } else {
  100. enumerate_joypads(_udev);
  101. monitor_joypads(_udev);
  102. udev_unref(_udev);
  103. }
  104. } else {
  105. monitor_joypads();
  106. }
  107. #else
  108. monitor_joypads();
  109. #endif
  110. }
  111. #ifdef UDEV_ENABLED
  112. void JoypadLinux::enumerate_joypads(udev *p_udev) {
  113. udev_enumerate *enumerate;
  114. udev_list_entry *devices, *dev_list_entry;
  115. udev_device *dev;
  116. enumerate = udev_enumerate_new(p_udev);
  117. udev_enumerate_add_match_subsystem(enumerate, "input");
  118. udev_enumerate_scan_devices(enumerate);
  119. devices = udev_enumerate_get_list_entry(enumerate);
  120. udev_list_entry_foreach(dev_list_entry, devices) {
  121. const char *path = udev_list_entry_get_name(dev_list_entry);
  122. dev = udev_device_new_from_syspath(p_udev, path);
  123. const char *devnode = udev_device_get_devnode(dev);
  124. if (devnode) {
  125. String devnode_str = devnode;
  126. if (devnode_str.find(ignore_str) == -1) {
  127. MutexLock lock(joy_mutex);
  128. open_joypad(devnode);
  129. }
  130. }
  131. udev_device_unref(dev);
  132. }
  133. udev_enumerate_unref(enumerate);
  134. }
  135. void JoypadLinux::monitor_joypads(udev *p_udev) {
  136. udev_device *dev = nullptr;
  137. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  138. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr);
  139. udev_monitor_enable_receiving(mon);
  140. int fd = udev_monitor_get_fd(mon);
  141. while (!exit_monitor.is_set()) {
  142. fd_set fds;
  143. struct timeval tv;
  144. int ret;
  145. FD_ZERO(&fds);
  146. FD_SET(fd, &fds);
  147. tv.tv_sec = 0;
  148. tv.tv_usec = 0;
  149. ret = select(fd + 1, &fds, nullptr, nullptr, &tv);
  150. /* Check if our file descriptor has received data. */
  151. if (ret > 0 && FD_ISSET(fd, &fds)) {
  152. /* Make the call to receive the device.
  153. select() ensured that this will not block. */
  154. dev = udev_monitor_receive_device(mon);
  155. if (dev && udev_device_get_devnode(dev) != nullptr) {
  156. MutexLock lock(joy_mutex);
  157. String action = udev_device_get_action(dev);
  158. const char *devnode = udev_device_get_devnode(dev);
  159. if (devnode) {
  160. String devnode_str = devnode;
  161. if (devnode_str.find(ignore_str) == -1) {
  162. if (action == "add") {
  163. open_joypad(devnode);
  164. } else if (String(action) == "remove") {
  165. close_joypad(get_joy_from_path(devnode));
  166. }
  167. }
  168. }
  169. udev_device_unref(dev);
  170. }
  171. }
  172. usleep(50000);
  173. }
  174. udev_monitor_unref(mon);
  175. }
  176. #endif
  177. void JoypadLinux::monitor_joypads() {
  178. while (!exit_monitor.is_set()) {
  179. {
  180. MutexLock lock(joy_mutex);
  181. DIR *input_directory;
  182. input_directory = opendir("/dev/input");
  183. if (input_directory) {
  184. struct dirent *current;
  185. char fname[64];
  186. while ((current = readdir(input_directory)) != nullptr) {
  187. if (strncmp(current->d_name, "event", 5) != 0) {
  188. continue;
  189. }
  190. sprintf(fname, "/dev/input/%.*s", 16, current->d_name);
  191. if (attached_devices.find(fname) == -1) {
  192. open_joypad(fname);
  193. }
  194. }
  195. }
  196. closedir(input_directory);
  197. }
  198. usleep(1000000); // 1s
  199. }
  200. }
  201. int JoypadLinux::get_joy_from_path(String p_path) const {
  202. for (int i = 0; i < JOYPADS_MAX; i++) {
  203. if (joypads[i].devpath == p_path) {
  204. return i;
  205. }
  206. }
  207. return -2;
  208. }
  209. void JoypadLinux::close_joypad(int p_id) {
  210. if (p_id == -1) {
  211. for (int i = 0; i < JOYPADS_MAX; i++) {
  212. close_joypad(i);
  213. }
  214. return;
  215. } else if (p_id < 0) {
  216. return;
  217. }
  218. Joypad &joy = joypads[p_id];
  219. if (joy.fd != -1) {
  220. close(joy.fd);
  221. joy.fd = -1;
  222. attached_devices.remove_at(attached_devices.find(joy.devpath));
  223. input->joy_connection_changed(p_id, false, "");
  224. }
  225. }
  226. static String _hex_str(uint8_t p_byte) {
  227. static const char *dict = "0123456789abcdef";
  228. char ret[3];
  229. ret[2] = 0;
  230. ret[0] = dict[p_byte >> 4];
  231. ret[1] = dict[p_byte & 0xF];
  232. return ret;
  233. }
  234. void JoypadLinux::setup_joypad_properties(int p_id) {
  235. Joypad *joy = &joypads[p_id];
  236. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  237. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  238. int num_buttons = 0;
  239. int num_axes = 0;
  240. if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  241. (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  242. return;
  243. }
  244. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  245. if (test_bit(i, keybit)) {
  246. joy->key_map[i] = num_buttons++;
  247. }
  248. }
  249. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  250. if (test_bit(i, keybit)) {
  251. joy->key_map[i] = num_buttons++;
  252. }
  253. }
  254. for (int i = 0; i < ABS_MISC; ++i) {
  255. /* Skip hats */
  256. if (i == ABS_HAT0X) {
  257. i = ABS_HAT3Y;
  258. continue;
  259. }
  260. if (test_bit(i, absbit)) {
  261. joy->abs_map[i] = num_axes++;
  262. joy->abs_info[i] = memnew(input_absinfo);
  263. if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) {
  264. memdelete(joy->abs_info[i]);
  265. joy->abs_info[i] = nullptr;
  266. }
  267. }
  268. }
  269. joy->force_feedback = false;
  270. joy->ff_effect_timestamp = 0;
  271. unsigned long ffbit[NBITS(FF_CNT)];
  272. if (ioctl(joy->fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
  273. if (test_bit(FF_RUMBLE, ffbit)) {
  274. joy->force_feedback = true;
  275. }
  276. }
  277. }
  278. void JoypadLinux::open_joypad(const char *p_path) {
  279. int joy_num = input->get_unused_joy_id();
  280. int fd = open(p_path, O_RDWR | O_NONBLOCK);
  281. if (fd != -1 && joy_num != -1) {
  282. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  283. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  284. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  285. // add to attached devices so we don't try to open it again
  286. attached_devices.push_back(String(p_path));
  287. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  288. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  289. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  290. close(fd);
  291. return;
  292. }
  293. // Check if the device supports basic gamepad events
  294. bool has_abs_left = (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit));
  295. bool has_abs_right = (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit));
  296. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && (has_abs_left || has_abs_right))) {
  297. close(fd);
  298. return;
  299. }
  300. char uid[128];
  301. char namebuf[128];
  302. String name = "";
  303. input_id inpid;
  304. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  305. name = namebuf;
  306. }
  307. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  308. close(fd);
  309. return;
  310. }
  311. joypads[joy_num].reset();
  312. Joypad &joy = joypads[joy_num];
  313. joy.fd = fd;
  314. joy.devpath = String(p_path);
  315. setup_joypad_properties(joy_num);
  316. sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
  317. if (inpid.vendor && inpid.product && inpid.version) {
  318. uint16_t vendor = BSWAP16(inpid.vendor);
  319. uint16_t product = BSWAP16(inpid.product);
  320. uint16_t version = BSWAP16(inpid.version);
  321. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
  322. input->joy_connection_changed(joy_num, true, name, uid);
  323. } else {
  324. String uidname = uid;
  325. int uidlen = MIN(name.length(), 11);
  326. for (int i = 0; i < uidlen; i++) {
  327. uidname = uidname + _hex_str(name[i]);
  328. }
  329. uidname += "00";
  330. input->joy_connection_changed(joy_num, true, name, uidname);
  331. }
  332. }
  333. }
  334. void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  335. Joypad &joy = joypads[p_id];
  336. if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  337. return;
  338. }
  339. if (joy.ff_effect_id != -1) {
  340. joypad_vibration_stop(p_id, p_timestamp);
  341. }
  342. struct ff_effect effect;
  343. effect.type = FF_RUMBLE;
  344. effect.id = -1;
  345. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  346. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  347. effect.replay.length = floor(p_duration * 1000);
  348. effect.replay.delay = 0;
  349. if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) {
  350. return;
  351. }
  352. struct input_event play;
  353. play.type = EV_FF;
  354. play.code = effect.id;
  355. play.value = 1;
  356. if (write(joy.fd, (const void *)&play, sizeof(play)) == -1) {
  357. print_verbose("Couldn't write to Joypad device.");
  358. }
  359. joy.ff_effect_id = effect.id;
  360. joy.ff_effect_timestamp = p_timestamp;
  361. }
  362. void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
  363. Joypad &joy = joypads[p_id];
  364. if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
  365. return;
  366. }
  367. if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) {
  368. return;
  369. }
  370. joy.ff_effect_id = -1;
  371. joy.ff_effect_timestamp = p_timestamp;
  372. }
  373. float JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  374. int min = p_abs->minimum;
  375. int max = p_abs->maximum;
  376. // Convert to a value between -1.0f and 1.0f.
  377. return 2.0f * (p_value - min) / (max - min) - 1.0f;
  378. }
  379. void JoypadLinux::process_joypads() {
  380. if (joy_mutex.try_lock() != OK) {
  381. return;
  382. }
  383. for (int i = 0; i < JOYPADS_MAX; i++) {
  384. if (joypads[i].fd == -1) {
  385. continue;
  386. }
  387. input_event events[32];
  388. Joypad *joy = &joypads[i];
  389. int len;
  390. while ((len = read(joy->fd, events, (sizeof events))) > 0) {
  391. len /= sizeof(events[0]);
  392. for (int j = 0; j < len; j++) {
  393. input_event &ev = events[j];
  394. // ev may be tainted and out of MAX_KEY range, which will cause
  395. // joy->key_map[ev.code] to crash
  396. if (ev.code >= MAX_KEY) {
  397. return;
  398. }
  399. switch (ev.type) {
  400. case EV_KEY:
  401. input->joy_button(i, (JoyButton)joy->key_map[ev.code], ev.value);
  402. break;
  403. case EV_ABS:
  404. switch (ev.code) {
  405. case ABS_HAT0X:
  406. if (ev.value != 0) {
  407. if (ev.value < 0) {
  408. joy->dpad = (HatMask)((joy->dpad | HatMask::LEFT) & ~HatMask::RIGHT);
  409. } else {
  410. joy->dpad = (HatMask)((joy->dpad | HatMask::RIGHT) & ~HatMask::LEFT);
  411. }
  412. } else {
  413. joy->dpad &= ~(HatMask::LEFT | HatMask::RIGHT);
  414. }
  415. input->joy_hat(i, (HatMask)joy->dpad);
  416. break;
  417. case ABS_HAT0Y:
  418. if (ev.value != 0) {
  419. if (ev.value < 0) {
  420. joy->dpad = (HatMask)((joy->dpad | HatMask::UP) & ~HatMask::DOWN);
  421. } else {
  422. joy->dpad = (HatMask)((joy->dpad | HatMask::DOWN) & ~HatMask::UP);
  423. }
  424. } else {
  425. joy->dpad &= ~(HatMask::UP | HatMask::DOWN);
  426. }
  427. input->joy_hat(i, (HatMask)joy->dpad);
  428. break;
  429. default:
  430. if (ev.code >= MAX_ABS) {
  431. return;
  432. }
  433. if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
  434. float value = axis_correct(joy->abs_info[ev.code], ev.value);
  435. joy->curr_axis[joy->abs_map[ev.code]] = value;
  436. }
  437. break;
  438. }
  439. break;
  440. }
  441. }
  442. }
  443. for (int j = 0; j < MAX_ABS; j++) {
  444. int index = joy->abs_map[j];
  445. if (index != -1) {
  446. input->joy_axis(i, (JoyAxis)index, joy->curr_axis[index]);
  447. }
  448. }
  449. if (len == 0 || (len < 0 && errno != EAGAIN)) {
  450. close_joypad(i);
  451. }
  452. if (joy->force_feedback) {
  453. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  454. if (timestamp > joy->ff_effect_timestamp) {
  455. Vector2 strength = input->get_joy_vibration_strength(i);
  456. float duration = input->get_joy_vibration_duration(i);
  457. if (strength.x == 0 && strength.y == 0) {
  458. joypad_vibration_stop(i, timestamp);
  459. } else {
  460. joypad_vibration_start(i, strength.x, strength.y, duration, timestamp);
  461. }
  462. }
  463. }
  464. }
  465. joy_mutex.unlock();
  466. }
  467. #endif