main_linux.cpp 27 KB

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