main_linux.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. /*
  2. * Copyright (c) 2012-2023 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #if CROWN_PLATFORM_LINUX
  7. #include "core/command_line.h"
  8. #include "core/containers/array.inl"
  9. #include "core/guid.h"
  10. #include "core/memory/globals.h"
  11. #include "core/memory/memory.inl"
  12. #include "core/option.inl"
  13. #include "core/os.h"
  14. #include "core/thread/spsc_queue.inl"
  15. #include "core/thread/thread.h"
  16. #include "core/unit_tests.h"
  17. #include "device/device.h"
  18. #include "device/device_event_queue.inl"
  19. #include "device/display.h"
  20. #include "device/window.h"
  21. #include "resource/data_compiler.h"
  22. #include <bgfx/platform.h>
  23. #include <fcntl.h> // O_RDONLY, ...
  24. #include <stdlib.h>
  25. #include <string.h> // memset
  26. #include <unistd.h> // close
  27. #include <X11/cursorfont.h>
  28. #include <X11/extensions/Xrandr.h>
  29. #include <X11/Xatom.h>
  30. #include <X11/XKBlib.h>
  31. #include <X11/Xlib.h>
  32. #include <X11/Xutil.h>
  33. #define STB_SPRINTF_IMPLEMENTATION
  34. #define STB_SPRINTF_NOUNALIGNED
  35. #include <stb_sprintf.h>
  36. #include <signal.h>
  37. #include <errno.h>
  38. namespace crown
  39. {
  40. static KeyboardButton::Enum x11_translate_key(KeySym x11_key)
  41. {
  42. switch (x11_key) {
  43. case XK_BackSpace: return KeyboardButton::BACKSPACE;
  44. case XK_Tab: return KeyboardButton::TAB;
  45. case XK_space: return KeyboardButton::SPACE;
  46. case XK_Escape: return KeyboardButton::ESCAPE;
  47. case XK_Return: return KeyboardButton::ENTER;
  48. case XK_F1: return KeyboardButton::F1;
  49. case XK_F2: return KeyboardButton::F2;
  50. case XK_F3: return KeyboardButton::F3;
  51. case XK_F4: return KeyboardButton::F4;
  52. case XK_F5: return KeyboardButton::F5;
  53. case XK_F6: return KeyboardButton::F6;
  54. case XK_F7: return KeyboardButton::F7;
  55. case XK_F8: return KeyboardButton::F8;
  56. case XK_F9: return KeyboardButton::F9;
  57. case XK_F10: return KeyboardButton::F10;
  58. case XK_F11: return KeyboardButton::F11;
  59. case XK_F12: return KeyboardButton::F12;
  60. case XK_Home: return KeyboardButton::HOME;
  61. case XK_Left: return KeyboardButton::LEFT;
  62. case XK_Up: return KeyboardButton::UP;
  63. case XK_Right: return KeyboardButton::RIGHT;
  64. case XK_Down: return KeyboardButton::DOWN;
  65. case XK_Page_Up: return KeyboardButton::PAGE_UP;
  66. case XK_Page_Down: return KeyboardButton::PAGE_DOWN;
  67. case XK_Insert: return KeyboardButton::INS;
  68. case XK_Delete: return KeyboardButton::DEL;
  69. case XK_End: return KeyboardButton::END;
  70. case XK_Shift_L: return KeyboardButton::SHIFT_LEFT;
  71. case XK_Shift_R: return KeyboardButton::SHIFT_RIGHT;
  72. case XK_Control_L: return KeyboardButton::CTRL_LEFT;
  73. case XK_Control_R: return KeyboardButton::CTRL_RIGHT;
  74. case XK_Caps_Lock: return KeyboardButton::CAPS_LOCK;
  75. case XK_Alt_L: return KeyboardButton::ALT_LEFT;
  76. case XK_Alt_R: return KeyboardButton::ALT_RIGHT;
  77. case XK_Super_L: return KeyboardButton::SUPER_LEFT;
  78. case XK_Super_R: return KeyboardButton::SUPER_RIGHT;
  79. case XK_Num_Lock: return KeyboardButton::NUM_LOCK;
  80. case XK_KP_Enter: return KeyboardButton::NUMPAD_ENTER;
  81. case XK_KP_Delete: return KeyboardButton::NUMPAD_DELETE;
  82. case XK_KP_Multiply: return KeyboardButton::NUMPAD_MULTIPLY;
  83. case XK_KP_Add: return KeyboardButton::NUMPAD_ADD;
  84. case XK_KP_Subtract: return KeyboardButton::NUMPAD_SUBTRACT;
  85. case XK_KP_Divide: return KeyboardButton::NUMPAD_DIVIDE;
  86. case XK_KP_Insert:
  87. case XK_KP_0: return KeyboardButton::NUMPAD_0;
  88. case XK_KP_End:
  89. case XK_KP_1: return KeyboardButton::NUMPAD_1;
  90. case XK_KP_Down:
  91. case XK_KP_2: return KeyboardButton::NUMPAD_2;
  92. case XK_KP_Page_Down: // or XK_KP_Next
  93. case XK_KP_3: return KeyboardButton::NUMPAD_3;
  94. case XK_KP_Left:
  95. case XK_KP_4: return KeyboardButton::NUMPAD_4;
  96. case XK_KP_Begin:
  97. case XK_KP_5: return KeyboardButton::NUMPAD_5;
  98. case XK_KP_Right:
  99. case XK_KP_6: return KeyboardButton::NUMPAD_6;
  100. case XK_KP_Home:
  101. case XK_KP_7: return KeyboardButton::NUMPAD_7;
  102. case XK_KP_Up:
  103. case XK_KP_8: return KeyboardButton::NUMPAD_8;
  104. case XK_KP_Page_Up: // or XK_KP_Prior
  105. case XK_KP_9: return KeyboardButton::NUMPAD_9;
  106. case '0': return KeyboardButton::NUMBER_0;
  107. case '1': return KeyboardButton::NUMBER_1;
  108. case '2': return KeyboardButton::NUMBER_2;
  109. case '3': return KeyboardButton::NUMBER_3;
  110. case '4': return KeyboardButton::NUMBER_4;
  111. case '5': return KeyboardButton::NUMBER_5;
  112. case '6': return KeyboardButton::NUMBER_6;
  113. case '7': return KeyboardButton::NUMBER_7;
  114. case '8': return KeyboardButton::NUMBER_8;
  115. case '9': return KeyboardButton::NUMBER_9;
  116. case 'a': return KeyboardButton::A;
  117. case 'b': return KeyboardButton::B;
  118. case 'c': return KeyboardButton::C;
  119. case 'd': return KeyboardButton::D;
  120. case 'e': return KeyboardButton::E;
  121. case 'f': return KeyboardButton::F;
  122. case 'g': return KeyboardButton::G;
  123. case 'h': return KeyboardButton::H;
  124. case 'i': return KeyboardButton::I;
  125. case 'j': return KeyboardButton::J;
  126. case 'k': return KeyboardButton::K;
  127. case 'l': return KeyboardButton::L;
  128. case 'm': return KeyboardButton::M;
  129. case 'n': return KeyboardButton::N;
  130. case 'o': return KeyboardButton::O;
  131. case 'p': return KeyboardButton::P;
  132. case 'q': return KeyboardButton::Q;
  133. case 'r': return KeyboardButton::R;
  134. case 's': return KeyboardButton::S;
  135. case 't': return KeyboardButton::T;
  136. case 'u': return KeyboardButton::U;
  137. case 'v': return KeyboardButton::V;
  138. case 'w': return KeyboardButton::W;
  139. case 'x': return KeyboardButton::X;
  140. case 'y': return KeyboardButton::Y;
  141. case 'z': return KeyboardButton::Z;
  142. default: return KeyboardButton::COUNT;
  143. }
  144. }
  145. #define JS_EVENT_BUTTON 0x01 /* button pressed/released */
  146. #define JS_EVENT_AXIS 0x02 /* joystick moved */
  147. #define JS_EVENT_INIT 0x80 /* initial state of device */
  148. static u8 s_button[] =
  149. {
  150. JoypadButton::A,
  151. JoypadButton::B,
  152. JoypadButton::X,
  153. JoypadButton::Y,
  154. JoypadButton::SHOULDER_LEFT,
  155. JoypadButton::SHOULDER_RIGHT,
  156. JoypadButton::BACK,
  157. JoypadButton::START,
  158. JoypadButton::GUIDE,
  159. JoypadButton::THUMB_LEFT,
  160. JoypadButton::THUMB_RIGHT,
  161. JoypadButton::UP, // FIXME (reported as axis...)
  162. JoypadButton::DOWN,
  163. JoypadButton::LEFT,
  164. JoypadButton::RIGHT
  165. };
  166. struct JoypadEvent
  167. {
  168. u32 time; /* event timestamp in milliseconds */
  169. s16 value; /* value */
  170. u8 type; /* event type */
  171. u8 number; /* axis/button number */
  172. };
  173. struct Joypad
  174. {
  175. struct AxisData
  176. {
  177. s16 left[3];
  178. s16 right[3];
  179. };
  180. DeviceEventQueue *_queue;
  181. int _fd[CROWN_MAX_JOYPADS];
  182. AxisData _axis[CROWN_MAX_JOYPADS];
  183. explicit Joypad(DeviceEventQueue &queue)
  184. : _queue(&queue)
  185. {
  186. memset(&_fd, 0, sizeof(_fd));
  187. memset(&_axis, 0, sizeof(_axis));
  188. }
  189. void open()
  190. {
  191. char jspath[] = "/dev/input/jsX";
  192. char *num = strchr(jspath, 'X');
  193. for (u32 ii = 0; ii < CROWN_MAX_JOYPADS; ++ii) {
  194. *num = '0' + ii;
  195. _fd[ii] = ::open(jspath, O_RDONLY);
  196. _queue->push_status_event(InputDeviceType::JOYPAD, ii, _fd[ii] >= 0);
  197. }
  198. }
  199. void close()
  200. {
  201. for (u32 ii = 0; ii < CROWN_MAX_JOYPADS; ++ii) {
  202. if (_fd[ii] != -1) {
  203. ::close(_fd[ii]);
  204. _fd[ii] = -1;
  205. _queue->push_status_event(InputDeviceType::JOYPAD, ii, false);
  206. }
  207. }
  208. }
  209. void process_events(u32 joypad_id, const JoypadEvent *events, u32 num_events)
  210. {
  211. for (u32 ii = 0; ii < num_events; ++ii) {
  212. JoypadEvent ev = events[ii];
  213. switch (ev.type &= ~JS_EVENT_INIT) {
  214. case JS_EVENT_AXIS: {
  215. // Indices into axis.left/right respectively
  216. const u8 axis_idx[] = { 0, 1, 2, 0, 1, 2 };
  217. const u8 axis_map[] =
  218. {
  219. JoypadAxis::LEFT,
  220. JoypadAxis::LEFT,
  221. JoypadAxis::TRIGGER_LEFT,
  222. JoypadAxis::RIGHT,
  223. JoypadAxis::RIGHT,
  224. JoypadAxis::TRIGGER_RIGHT
  225. };
  226. // Remap triggers to [0, INT16_MAX]
  227. s16 value = ev.value;
  228. if (ev.number == 2 || ev.number == 5)
  229. value = (ev.value + INT16_MAX) >> 1;
  230. s16 *values = ev.number > 2 ? _axis[joypad_id].right : _axis[joypad_id].left;
  231. values[axis_idx[ev.number]] = value;
  232. if (ev.number == 2 || ev.number == 5) {
  233. _queue->push_axis_event(InputDeviceType::JOYPAD
  234. , joypad_id
  235. , axis_map[ev.number]
  236. , 0
  237. , 0
  238. , values[2]
  239. );
  240. } else if (ev.number < countof(axis_map)) {
  241. _queue->push_axis_event(InputDeviceType::JOYPAD
  242. , joypad_id
  243. , axis_map[ev.number]
  244. , values[0]
  245. , -values[1]
  246. , 0
  247. );
  248. }
  249. break;
  250. }
  251. case JS_EVENT_BUTTON:
  252. if (ev.number < countof(s_button)) {
  253. _queue->push_button_event(InputDeviceType::JOYPAD
  254. , joypad_id
  255. , s_button[ev.number]
  256. , ev.value == 1
  257. );
  258. }
  259. break;
  260. default:
  261. break;
  262. }
  263. }
  264. }
  265. void update(fd_set *fdset)
  266. {
  267. for (u8 ii = 0; ii < CROWN_MAX_JOYPADS; ++ii) {
  268. if (_fd[ii] == -1 || !FD_ISSET(_fd[ii], fdset))
  269. continue;
  270. // Read all events.
  271. JoypadEvent events[64];
  272. ssize_t num_bytes = read(_fd[ii], &events, sizeof(events));
  273. if (num_bytes > 0) {
  274. process_events(ii, events, num_bytes/ssize_t(sizeof(events[0])));
  275. } else {
  276. ::close(_fd[ii]);
  277. _fd[ii] = -1;
  278. _queue->push_status_event(InputDeviceType::JOYPAD, ii, false);
  279. }
  280. }
  281. }
  282. };
  283. static bool s_exit = false;
  284. static int exit_pipe[2];
  285. static Cursor _x11_cursors[MouseCursor::COUNT];
  286. static bool push_event(const OsEvent &ev);
  287. struct LinuxDevice
  288. {
  289. ::Display *_x11_display;
  290. Atom _wm_delete_window;
  291. Atom _net_wm_state;
  292. Atom _net_wm_state_maximized_horz;
  293. Atom _net_wm_state_maximized_vert;
  294. Atom _net_wm_state_fullscreen;
  295. Cursor _x11_hidden_cursor;
  296. bool _x11_detectable_autorepeat;
  297. XRRScreenConfiguration *_screen_config;
  298. SPSCQueue<OsEvent, CROWN_MAX_OS_EVENTS> _events;
  299. DeviceEventQueue _queue;
  300. Joypad _joypad;
  301. ::Window _x11_window;
  302. s16 _mouse_last_x;
  303. s16 _mouse_last_y;
  304. CursorMode::Enum _cursor_mode;
  305. explicit LinuxDevice(Allocator &a)
  306. : _x11_display(NULL)
  307. , _wm_delete_window(None)
  308. , _net_wm_state(None)
  309. , _net_wm_state_maximized_horz(None)
  310. , _net_wm_state_maximized_vert(None)
  311. , _net_wm_state_fullscreen(None)
  312. , _x11_hidden_cursor(None)
  313. , _x11_detectable_autorepeat(false)
  314. , _screen_config(NULL)
  315. , _events(a)
  316. , _queue(push_event)
  317. , _joypad(_queue)
  318. , _x11_window(None)
  319. , _mouse_last_x(INT16_MAX)
  320. , _mouse_last_y(INT16_MAX)
  321. , _cursor_mode(CursorMode::NORMAL)
  322. {
  323. }
  324. int run(DeviceOptions *opts)
  325. {
  326. int err = pipe(exit_pipe);
  327. CE_ASSERT(err != -1, "pipe: errno = %d", errno);
  328. CE_UNUSED(err);
  329. // http://tronche.com/gui/x/xlib/display/XInitThreads.html
  330. Status xs = XInitThreads();
  331. CE_ASSERT(xs != 0, "XInitThreads: error");
  332. CE_UNUSED(xs);
  333. _x11_display = XOpenDisplay(NULL);
  334. CE_ASSERT(_x11_display != NULL, "XOpenDisplay: error");
  335. ::Window root_window = RootWindow(_x11_display, DefaultScreen(_x11_display));
  336. // Do we have detectable autorepeat?
  337. Bool detectable;
  338. _x11_detectable_autorepeat = (bool)XkbSetDetectableAutoRepeat(_x11_display, true, &detectable);
  339. _wm_delete_window = XInternAtom(_x11_display, "WM_DELETE_WINDOW", False);
  340. _net_wm_state = XInternAtom(_x11_display, "_NET_WM_STATE", False);
  341. _net_wm_state_maximized_horz = XInternAtom(_x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  342. _net_wm_state_maximized_vert = XInternAtom(_x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  343. _net_wm_state_fullscreen = XInternAtom(_x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  344. // Save screen configuration
  345. _screen_config = XRRGetScreenInfo(_x11_display, root_window);
  346. Rotation rr_old_rot;
  347. const SizeID rr_old_sizeid = XRRConfigCurrentConfiguration(_screen_config, &rr_old_rot);
  348. XIM im;
  349. im = XOpenIM(_x11_display, NULL, NULL, NULL);
  350. CE_ASSERT(im != NULL, "XOpenIM: error");
  351. XIC ic;
  352. ic = XCreateIC(im
  353. , XNInputStyle
  354. , 0
  355. | XIMPreeditNothing
  356. | XIMStatusNothing
  357. , XNClientWindow
  358. , root_window
  359. , NULL
  360. );
  361. CE_ASSERT(ic != NULL, "XCreateIC: error");
  362. // Create hidden cursor
  363. Pixmap bitmap;
  364. const char data[8] = { 0 };
  365. XColor dummy;
  366. bitmap = XCreateBitmapFromData(_x11_display, root_window, data, 8, 8);
  367. _x11_hidden_cursor = XCreatePixmapCursor(_x11_display, bitmap, bitmap, &dummy, &dummy, 0, 0);
  368. // Create standard cursors
  369. _x11_cursors[MouseCursor::ARROW] = XCreateFontCursor(_x11_display, XC_top_left_arrow);
  370. _x11_cursors[MouseCursor::HAND] = XCreateFontCursor(_x11_display, XC_hand2);
  371. _x11_cursors[MouseCursor::TEXT_INPUT] = XCreateFontCursor(_x11_display, XC_xterm);
  372. _x11_cursors[MouseCursor::CORNER_TOP_LEFT] = XCreateFontCursor(_x11_display, XC_top_left_corner);
  373. _x11_cursors[MouseCursor::CORNER_TOP_RIGHT] = XCreateFontCursor(_x11_display, XC_top_right_corner);
  374. _x11_cursors[MouseCursor::CORNER_BOTTOM_LEFT] = XCreateFontCursor(_x11_display, XC_bottom_left_corner);
  375. _x11_cursors[MouseCursor::CORNER_BOTTOM_RIGHT] = XCreateFontCursor(_x11_display, XC_bottom_right_corner);
  376. _x11_cursors[MouseCursor::SIZE_HORIZONTAL] = XCreateFontCursor(_x11_display, XC_sb_h_double_arrow);
  377. _x11_cursors[MouseCursor::SIZE_VERTICAL] = XCreateFontCursor(_x11_display, XC_sb_v_double_arrow);
  378. _x11_cursors[MouseCursor::WAIT] = XCreateFontCursor(_x11_display, XC_watch);
  379. // Start main thread
  380. Thread main_thread;
  381. main_thread.start([](void *user_data) {
  382. crown::run(*((DeviceOptions *)user_data));
  383. s_exit = true;
  384. // Write something just to unlock the listening select().
  385. write(exit_pipe[1], &s_exit, sizeof(s_exit));
  386. return EXIT_SUCCESS;
  387. }
  388. , opts
  389. );
  390. _joypad.open();
  391. // Input events loop.
  392. fd_set fdset;
  393. int x11_fd = ConnectionNumber(_x11_display);
  394. while (!s_exit) {
  395. FD_ZERO(&fdset);
  396. FD_SET(x11_fd, &fdset);
  397. FD_SET(exit_pipe[0], &fdset);
  398. int maxfd = max(x11_fd, exit_pipe[0]);
  399. for (int i = 0; i < CROWN_MAX_JOYPADS; ++i) {
  400. if (_joypad._fd[i] != -1) {
  401. FD_SET(_joypad._fd[i], &fdset);
  402. maxfd = max(maxfd, _joypad._fd[i]);
  403. }
  404. }
  405. if (select(maxfd + 1, &fdset, NULL, NULL, NULL) <= 0)
  406. continue;
  407. if (FD_ISSET(exit_pipe[0], &fdset)) {
  408. break;
  409. } else if (FD_ISSET(x11_fd, &fdset)) {
  410. while (XEventsQueued(_x11_display, QueuedAfterFlush) > 0) {
  411. XEvent event;
  412. XNextEvent(_x11_display, &event);
  413. switch (event.type) {
  414. case EnterNotify:
  415. _mouse_last_x = (s16)event.xcrossing.x;
  416. _mouse_last_y = (s16)event.xcrossing.y;
  417. _queue.push_axis_event(InputDeviceType::MOUSE
  418. , 0
  419. , MouseAxis::CURSOR
  420. , event.xcrossing.x
  421. , event.xcrossing.y
  422. , 0
  423. );
  424. break;
  425. case ClientMessage:
  426. if ((Atom)event.xclient.data.l[0] == _wm_delete_window)
  427. _queue.push_exit_event();
  428. break;
  429. case ConfigureNotify:
  430. _queue.push_resolution_event(event.xconfigure.width
  431. , event.xconfigure.height
  432. );
  433. break;
  434. case ButtonPress:
  435. case ButtonRelease: {
  436. if (event.xbutton.button == Button4 || event.xbutton.button == Button5) {
  437. _queue.push_axis_event(InputDeviceType::MOUSE
  438. , 0
  439. , MouseAxis::WHEEL
  440. , 0
  441. , event.xbutton.button == Button4 ? 1 : -1
  442. , 0
  443. );
  444. break;
  445. }
  446. MouseButton::Enum mb;
  447. switch (event.xbutton.button) {
  448. case Button1: mb = MouseButton::LEFT; break;
  449. case Button2: mb = MouseButton::MIDDLE; break;
  450. case Button3: mb = MouseButton::RIGHT; break;
  451. default: mb = MouseButton::COUNT; break;
  452. }
  453. if (mb != MouseButton::COUNT) {
  454. _queue.push_button_event(InputDeviceType::MOUSE
  455. , 0
  456. , mb
  457. , event.type == ButtonPress
  458. );
  459. }
  460. break;
  461. }
  462. case MotionNotify: {
  463. const s32 mx = event.xmotion.x;
  464. const s32 my = event.xmotion.y;
  465. s16 deltax = mx - _mouse_last_x;
  466. s16 deltay = my - _mouse_last_y;
  467. if (_cursor_mode == CursorMode::DISABLED) {
  468. XWindowAttributes window_attribs;
  469. XGetWindowAttributes(_x11_display, _x11_window, &window_attribs);
  470. unsigned width = window_attribs.width;
  471. unsigned height = window_attribs.height;
  472. if (mx != (s32)width/2 || my != (s32)height/2) {
  473. _queue.push_axis_event(InputDeviceType::MOUSE
  474. , 0
  475. , MouseAxis::CURSOR_DELTA
  476. , deltax
  477. , deltay
  478. , 0
  479. );
  480. XWarpPointer(_x11_display
  481. , None
  482. , _x11_window
  483. , 0
  484. , 0
  485. , 0
  486. , 0
  487. , width/2
  488. , height/2
  489. );
  490. XFlush(_x11_display);
  491. }
  492. } else if (_cursor_mode == CursorMode::NORMAL) {
  493. _queue.push_axis_event(InputDeviceType::MOUSE
  494. , 0
  495. , MouseAxis::CURSOR_DELTA
  496. , deltax
  497. , deltay
  498. , 0
  499. );
  500. }
  501. _queue.push_axis_event(InputDeviceType::MOUSE
  502. , 0
  503. , MouseAxis::CURSOR
  504. , (s16)mx
  505. , (s16)my
  506. , 0
  507. );
  508. _mouse_last_x = (s16)mx;
  509. _mouse_last_y = (s16)my;
  510. break;
  511. }
  512. case KeyPress:
  513. case KeyRelease: {
  514. KeySym keysym = XLookupKeysym(&event.xkey, 0);
  515. KeyboardButton::Enum kb = x11_translate_key(keysym);
  516. if (kb != KeyboardButton::COUNT) {
  517. _queue.push_button_event(InputDeviceType::KEYBOARD
  518. , 0
  519. , kb
  520. , event.type == KeyPress
  521. );
  522. }
  523. if (event.type == KeyPress) {
  524. Status status = 0;
  525. u8 utf8[4] = { 0 };
  526. int len = Xutf8LookupString(ic
  527. , &event.xkey
  528. , (char *)utf8
  529. , sizeof(utf8)
  530. , NULL
  531. , &status
  532. );
  533. if (status == XLookupChars || status == XLookupBoth) {
  534. if (len)
  535. _queue.push_text_event(len, utf8);
  536. }
  537. }
  538. break;
  539. }
  540. case KeymapNotify:
  541. XRefreshKeyboardMapping(&event.xmapping);
  542. break;
  543. default:
  544. break;
  545. }
  546. }
  547. } else {
  548. _joypad.update(&fdset);
  549. }
  550. }
  551. _joypad.close();
  552. main_thread.stop();
  553. // Free standard cursors
  554. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::WAIT]);
  555. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::SIZE_VERTICAL]);
  556. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::SIZE_HORIZONTAL]);
  557. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::CORNER_BOTTOM_RIGHT]);
  558. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::CORNER_BOTTOM_LEFT]);
  559. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::CORNER_TOP_RIGHT]);
  560. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::CORNER_TOP_LEFT]);
  561. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::TEXT_INPUT]);
  562. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::HAND]);
  563. XFreeCursor(_x11_display, _x11_cursors[MouseCursor::ARROW]);
  564. // Free hidden cursor
  565. XFreeCursor(_x11_display, _x11_hidden_cursor);
  566. XFreePixmap(_x11_display, bitmap);
  567. XDestroyIC(ic);
  568. XCloseIM(im);
  569. // Restore previous screen configuration
  570. Rotation rr_rot;
  571. const SizeID rr_sizeid = XRRConfigCurrentConfiguration(_screen_config, &rr_rot);
  572. if (rr_rot != rr_old_rot || rr_sizeid != rr_old_sizeid) {
  573. XRRSetScreenConfig(_x11_display
  574. , _screen_config
  575. , root_window
  576. , rr_old_sizeid
  577. , rr_old_rot
  578. , CurrentTime
  579. );
  580. }
  581. XRRFreeScreenConfigInfo(_screen_config);
  582. XCloseDisplay(_x11_display);
  583. ::close(exit_pipe[0]);
  584. ::close(exit_pipe[1]);
  585. return EXIT_SUCCESS;
  586. }
  587. };
  588. static LinuxDevice *s_linux_device;
  589. struct WindowX11 : public Window
  590. {
  591. WindowX11()
  592. {
  593. }
  594. void open(u16 x, u16 y, u16 width, u16 height, u32 parent) override
  595. {
  596. int screen = DefaultScreen(s_linux_device->_x11_display);
  597. int depth = DefaultDepth(s_linux_device->_x11_display, screen);
  598. Visual *visual = DefaultVisual(s_linux_device->_x11_display, screen);
  599. ::Window root_window = RootWindow(s_linux_device->_x11_display, screen);
  600. ::Window parent_window = (parent == 0) ? root_window : (::Window)parent;
  601. // Create main window
  602. XSetWindowAttributes win_attribs;
  603. win_attribs.background_pixmap = 0;
  604. win_attribs.border_pixel = 0;
  605. win_attribs.event_mask = FocusChangeMask
  606. | StructureNotifyMask
  607. ;
  608. if (!parent) {
  609. win_attribs.event_mask |= KeyPressMask
  610. | KeyReleaseMask
  611. | ButtonPressMask
  612. | ButtonReleaseMask
  613. | PointerMotionMask
  614. | EnterWindowMask
  615. ;
  616. } else {
  617. XWindowAttributes parent_attrs;
  618. XGetWindowAttributes(s_linux_device->_x11_display, parent_window, &parent_attrs);
  619. depth = parent_attrs.depth;
  620. visual = parent_attrs.visual;
  621. }
  622. s_linux_device->_x11_window = XCreateWindow(s_linux_device->_x11_display
  623. , parent_window
  624. , x
  625. , y
  626. , width
  627. , height
  628. , 0
  629. , depth
  630. , InputOutput
  631. , visual
  632. , CWBorderPixel | CWEventMask
  633. , &win_attribs
  634. );
  635. CE_ASSERT(s_linux_device->_x11_window != None, "XCreateWindow: error");
  636. XSetWMProtocols(s_linux_device->_x11_display, s_linux_device->_x11_window, &s_linux_device->_wm_delete_window, 1);
  637. XMapRaised(s_linux_device->_x11_display, s_linux_device->_x11_window);
  638. }
  639. void close() override
  640. {
  641. XDestroyWindow(s_linux_device->_x11_display, s_linux_device->_x11_window);
  642. }
  643. void bgfx_setup() override
  644. {
  645. bgfx::PlatformData pd;
  646. pd.ndt = s_linux_device->_x11_display;
  647. pd.nwh = (void *)(uintptr_t)s_linux_device->_x11_window;
  648. pd.context = NULL;
  649. pd.backBuffer = NULL;
  650. pd.backBufferDS = NULL;
  651. bgfx::setPlatformData(pd);
  652. }
  653. void show() override
  654. {
  655. XMapRaised(s_linux_device->_x11_display, s_linux_device->_x11_window);
  656. }
  657. void hide() override
  658. {
  659. XUnmapWindow(s_linux_device->_x11_display, s_linux_device->_x11_window);
  660. }
  661. void resize(u16 width, u16 height) override
  662. {
  663. XResizeWindow(s_linux_device->_x11_display, s_linux_device->_x11_window, width, height);
  664. XFlush(s_linux_device->_x11_display);
  665. }
  666. void move(u16 x, u16 y) override
  667. {
  668. XMoveWindow(s_linux_device->_x11_display, s_linux_device->_x11_window, x, y);
  669. }
  670. void maximize_or_restore(bool maximize)
  671. {
  672. XEvent xev;
  673. xev.type = ClientMessage;
  674. xev.xclient.window = s_linux_device->_x11_window;
  675. xev.xclient.message_type = s_linux_device->_net_wm_state;
  676. xev.xclient.format = 32;
  677. xev.xclient.data.l[0] = maximize ? 1 : 0; // 0 = remove property, 1 = set property
  678. xev.xclient.data.l[1] = s_linux_device->_net_wm_state_maximized_horz;
  679. xev.xclient.data.l[2] = s_linux_device->_net_wm_state_maximized_vert;
  680. XSendEvent(s_linux_device->_x11_display
  681. , DefaultRootWindow(s_linux_device->_x11_display)
  682. , False
  683. , SubstructureNotifyMask | SubstructureRedirectMask
  684. , &xev
  685. );
  686. }
  687. void minimize() override
  688. {
  689. XIconifyWindow(s_linux_device->_x11_display, s_linux_device->_x11_window, DefaultScreen(s_linux_device->_x11_display));
  690. }
  691. void maximize() override
  692. {
  693. maximize_or_restore(true);
  694. }
  695. void restore() override
  696. {
  697. maximize_or_restore(false);
  698. }
  699. const char *title() override
  700. {
  701. static char buf[512];
  702. memset(buf, 0, sizeof(buf));
  703. char *name;
  704. XFetchName(s_linux_device->_x11_display, s_linux_device->_x11_window, &name);
  705. strncpy(buf, name, sizeof(buf) - 1);
  706. XFree(name);
  707. return buf;
  708. }
  709. void set_title(const char *title) override
  710. {
  711. XStoreName(s_linux_device->_x11_display, s_linux_device->_x11_window, title);
  712. }
  713. void *handle() override
  714. {
  715. return (void *)(uintptr_t)s_linux_device->_x11_window;
  716. }
  717. void show_cursor(bool show) override
  718. {
  719. XDefineCursor(s_linux_device->_x11_display
  720. , s_linux_device->_x11_window
  721. , show ? None : s_linux_device->_x11_hidden_cursor
  722. );
  723. }
  724. void set_fullscreen(bool full) override
  725. {
  726. XEvent xev;
  727. xev.xclient.type = ClientMessage;
  728. xev.xclient.window = s_linux_device->_x11_window;
  729. xev.xclient.message_type = s_linux_device->_net_wm_state;
  730. xev.xclient.format = 32;
  731. xev.xclient.data.l[0] = full ? 1 : 0;
  732. xev.xclient.data.l[1] = s_linux_device->_net_wm_state_fullscreen;
  733. XSendEvent(s_linux_device->_x11_display, DefaultRootWindow(s_linux_device->_x11_display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
  734. }
  735. void set_cursor(MouseCursor::Enum cursor) override
  736. {
  737. XDefineCursor(s_linux_device->_x11_display, s_linux_device->_x11_window, _x11_cursors[cursor]);
  738. }
  739. void set_cursor_mode(CursorMode::Enum mode) override
  740. {
  741. if (mode == s_linux_device->_cursor_mode)
  742. return;
  743. s_linux_device->_cursor_mode = mode;
  744. if (mode == CursorMode::DISABLED) {
  745. XWindowAttributes window_attribs;
  746. XGetWindowAttributes(s_linux_device->_x11_display, s_linux_device->_x11_window, &window_attribs);
  747. unsigned width = window_attribs.width;
  748. unsigned height = window_attribs.height;
  749. s_linux_device->_mouse_last_x = width/2;
  750. s_linux_device->_mouse_last_y = height/2;
  751. XWarpPointer(s_linux_device->_x11_display
  752. , None
  753. , s_linux_device->_x11_window
  754. , 0
  755. , 0
  756. , 0
  757. , 0
  758. , width/2
  759. , height/2
  760. );
  761. XGrabPointer(s_linux_device->_x11_display
  762. , s_linux_device->_x11_window
  763. , True
  764. , ButtonPressMask | ButtonReleaseMask | PointerMotionMask
  765. , GrabModeAsync
  766. , GrabModeAsync
  767. , s_linux_device->_x11_window
  768. , s_linux_device->_x11_hidden_cursor
  769. , CurrentTime
  770. );
  771. XFlush(s_linux_device->_x11_display);
  772. } else if (mode == CursorMode::NORMAL) {
  773. XUngrabPointer(s_linux_device->_x11_display, CurrentTime);
  774. XFlush(s_linux_device->_x11_display);
  775. }
  776. }
  777. };
  778. namespace window
  779. {
  780. Window *create(Allocator &a)
  781. {
  782. return CE_NEW(a, WindowX11)();
  783. }
  784. void destroy(Allocator &a, Window &w)
  785. {
  786. CE_DELETE(a, &w);
  787. }
  788. } // namespace window
  789. struct DisplayXRandr : public Display
  790. {
  791. void modes(Array<DisplayMode> &modes) override
  792. {
  793. int num = 0;
  794. XRRScreenSize *sizes = XRRConfigSizes(s_linux_device->_screen_config, &num);
  795. if (!sizes)
  796. return;
  797. for (int i = 0; i < num; ++i) {
  798. DisplayMode dm;
  799. dm.id = (u32)i;
  800. dm.width = sizes[i].width;
  801. dm.height = sizes[i].height;
  802. array::push_back(modes, dm);
  803. }
  804. }
  805. void set_mode(u32 id) override
  806. {
  807. int num = 0;
  808. XRRScreenSize *sizes = XRRConfigSizes(s_linux_device->_screen_config, &num);
  809. if (!sizes || (int)id >= num)
  810. return;
  811. XRRSetScreenConfig(s_linux_device->_x11_display
  812. , s_linux_device->_screen_config
  813. , RootWindow(s_linux_device->_x11_display, DefaultScreen(s_linux_device->_x11_display))
  814. , (int)id
  815. , RR_Rotate_0
  816. , CurrentTime
  817. );
  818. }
  819. };
  820. namespace display
  821. {
  822. Display *create(Allocator &a)
  823. {
  824. return CE_NEW(a, DisplayXRandr)();
  825. }
  826. void destroy(Allocator &a, Display &d)
  827. {
  828. CE_DELETE(a, &d);
  829. }
  830. } // namespace display
  831. static bool push_event(const OsEvent &ev)
  832. {
  833. return s_linux_device->_events.push(ev);
  834. }
  835. bool next_event(OsEvent &ev)
  836. {
  837. return s_linux_device->_events.pop(ev);
  838. }
  839. struct InitGlobals
  840. {
  841. InitGlobals()
  842. {
  843. memory_globals::init();
  844. guid_globals::init();
  845. }
  846. ~InitGlobals()
  847. {
  848. guid_globals::shutdown();
  849. memory_globals::shutdown();
  850. }
  851. };
  852. } // namespace crown
  853. int main(int argc, char **argv)
  854. {
  855. using namespace crown;
  856. struct sigaction old_SIGINT;
  857. struct sigaction old_SIGTERM;
  858. struct sigaction act;
  859. // code-format off
  860. act.sa_handler = [](int signum) {
  861. switch (signum)
  862. {
  863. case SIGINT:
  864. case SIGTERM:
  865. if (device())
  866. device()->quit();
  867. break;
  868. default:
  869. break;
  870. }
  871. };
  872. // code-format on
  873. sigemptyset(&act.sa_mask);
  874. act.sa_flags = 0;
  875. sigaction(SIGINT, NULL, &old_SIGINT);
  876. sigaction(SIGINT, &act, NULL);
  877. sigaction(SIGTERM, NULL, &old_SIGTERM);
  878. sigaction(SIGTERM, &act, NULL);
  879. #if CROWN_BUILD_UNIT_TESTS
  880. CommandLine cl(argc, (const char **)argv);
  881. if (cl.has_option("run-unit-tests")) {
  882. return main_unit_tests();
  883. }
  884. #endif
  885. InitGlobals m;
  886. CE_UNUSED(m);
  887. DeviceOptions opts(default_allocator(), argc, (const char **)argv);
  888. bool quit = false;
  889. int ec = opts.parse(&quit);
  890. if (quit)
  891. return ec;
  892. #if CROWN_CAN_COMPILE
  893. if (ec == EXIT_SUCCESS && (opts._do_compile || opts._server)) {
  894. ec = main_data_compiler(opts);
  895. if (!opts._do_continue)
  896. return ec;
  897. }
  898. #endif
  899. if (ec == EXIT_SUCCESS) {
  900. s_linux_device = CE_NEW(default_allocator(), LinuxDevice)(default_allocator());
  901. ec = s_linux_device->run(&opts);
  902. CE_DELETE(default_allocator(), s_linux_device);
  903. }
  904. // Restore original signal handlers.
  905. sigaction(SIGINT, &old_SIGINT, NULL);
  906. sigaction(SIGTERM, &old_SIGTERM, NULL);
  907. return ec;
  908. }
  909. #endif // if CROWN_PLATFORM_LINUX