os_x11.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042
  1. /*************************************************************************/
  2. /* os_x11.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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. #include "os_x11.h"
  31. #include "core/os/dir_access.h"
  32. #include "core/print_string.h"
  33. #include "drivers/gles2/rasterizer_gles2.h"
  34. #include "drivers/gles3/rasterizer_gles3.h"
  35. #include "errno.h"
  36. #include "key_mapping_x11.h"
  37. #include "servers/visual/visual_server_raster.h"
  38. #include "servers/visual/visual_server_wrap_mt.h"
  39. #ifdef HAVE_MNTENT
  40. #include <mntent.h>
  41. #endif
  42. #include <stdio.h>
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #include "X11/Xutil.h"
  46. #include "X11/Xatom.h"
  47. #include "X11/extensions/Xinerama.h"
  48. // ICCCM
  49. #define WM_NormalState 1L // window normal state
  50. #define WM_IconicState 3L // window minimized
  51. // EWMH
  52. #define _NET_WM_STATE_REMOVE 0L // remove/unset property
  53. #define _NET_WM_STATE_ADD 1L // add/set property
  54. #define _NET_WM_STATE_TOGGLE 2L // toggle property
  55. #include "main/main.h"
  56. #include <dlfcn.h>
  57. #include <fcntl.h>
  58. #include <sys/stat.h>
  59. #include <sys/types.h>
  60. #include <unistd.h>
  61. //stupid linux.h
  62. #ifdef KEY_TAB
  63. #undef KEY_TAB
  64. #endif
  65. #include <X11/Xatom.h>
  66. #undef CursorShape
  67. #include <X11/XKBlib.h>
  68. void OS_X11::initialize_core() {
  69. crash_handler.initialize();
  70. OS_Unix::initialize_core();
  71. }
  72. int OS_X11::get_current_video_driver() const {
  73. return video_driver_index;
  74. }
  75. Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  76. long im_event_mask = 0;
  77. last_button_state = 0;
  78. xmbstring = NULL;
  79. x11_window = 0;
  80. last_click_ms = 0;
  81. args = OS::get_singleton()->get_cmdline_args();
  82. current_videomode = p_desired;
  83. main_loop = NULL;
  84. last_timestamp = 0;
  85. last_mouse_pos_valid = false;
  86. last_keyrelease_time = 0;
  87. xdnd_version = 0;
  88. if (get_render_thread_mode() == RENDER_SEPARATE_THREAD) {
  89. XInitThreads();
  90. }
  91. /** XLIB INITIALIZATION **/
  92. x11_display = XOpenDisplay(NULL);
  93. if (!x11_display) {
  94. ERR_PRINT("X11 Display is not available");
  95. return ERR_UNAVAILABLE;
  96. }
  97. char *modifiers = NULL;
  98. Bool xkb_dar = False;
  99. XAutoRepeatOn(x11_display);
  100. xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, NULL);
  101. // Try to support IME if detectable auto-repeat is supported
  102. if (xkb_dar == True) {
  103. #ifdef X_HAVE_UTF8_STRING
  104. // Xutf8LookupString will be used later instead of XmbLookupString before
  105. // the multibyte sequences can be converted to unicode string.
  106. modifiers = XSetLocaleModifiers("");
  107. #endif
  108. }
  109. if (modifiers == NULL) {
  110. if (is_stdout_verbose()) {
  111. WARN_PRINT("IME is disabled");
  112. }
  113. modifiers = XSetLocaleModifiers("@im=none");
  114. WARN_PRINT("Error setting locale modifiers");
  115. }
  116. const char *err;
  117. xrr_get_monitors = NULL;
  118. xrr_free_monitors = NULL;
  119. int xrandr_major = 0;
  120. int xrandr_minor = 0;
  121. int event_base, error_base;
  122. xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
  123. xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
  124. if (!xrandr_handle) {
  125. err = dlerror();
  126. fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
  127. } else {
  128. XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
  129. if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
  130. xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
  131. if (!xrr_get_monitors) {
  132. err = dlerror();
  133. fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
  134. } else {
  135. xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
  136. if (!xrr_free_monitors) {
  137. err = dlerror();
  138. fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
  139. xrr_get_monitors = NULL;
  140. }
  141. }
  142. }
  143. }
  144. #ifdef TOUCH_ENABLED
  145. if (!XQueryExtension(x11_display, "XInputExtension", &touch.opcode, &event_base, &error_base)) {
  146. print_verbose("XInput extension not available, touch support disabled.");
  147. } else {
  148. // 2.2 is the first release with multitouch
  149. int xi_major = 2;
  150. int xi_minor = 2;
  151. if (XIQueryVersion(x11_display, &xi_major, &xi_minor) != Success) {
  152. print_verbose(vformat("XInput 2.2 not available (server supports %d.%d), touch support disabled.", xi_major, xi_minor));
  153. touch.opcode = 0;
  154. } else {
  155. int dev_count;
  156. XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count);
  157. for (int i = 0; i < dev_count; i++) {
  158. XIDeviceInfo *dev = &info[i];
  159. if (!dev->enabled)
  160. continue;
  161. if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave))
  162. continue;
  163. bool direct_touch = false;
  164. for (int j = 0; j < dev->num_classes; j++) {
  165. if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) {
  166. direct_touch = true;
  167. break;
  168. }
  169. }
  170. if (direct_touch) {
  171. touch.devices.push_back(dev->deviceid);
  172. print_verbose("XInput: Using touch device: " + String(dev->name));
  173. }
  174. }
  175. XIFreeDeviceInfo(info);
  176. if (!touch.devices.size()) {
  177. print_verbose("XInput: No touch devices found.");
  178. }
  179. }
  180. }
  181. #endif
  182. xim = XOpenIM(x11_display, NULL, NULL, NULL);
  183. if (xim == NULL) {
  184. WARN_PRINT("XOpenIM failed");
  185. xim_style = 0L;
  186. } else {
  187. ::XIMCallback im_destroy_callback;
  188. im_destroy_callback.client_data = (::XPointer)(this);
  189. im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback);
  190. if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
  191. NULL) != NULL) {
  192. WARN_PRINT("Error setting XIM destroy callback");
  193. }
  194. ::XIMStyles *xim_styles = NULL;
  195. xim_style = 0L;
  196. char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
  197. if (imvalret != NULL || xim_styles == NULL) {
  198. fprintf(stderr, "Input method doesn't support any styles\n");
  199. }
  200. if (xim_styles) {
  201. xim_style = 0L;
  202. for (int i = 0; i < xim_styles->count_styles; i++) {
  203. if (xim_styles->supported_styles[i] ==
  204. (XIMPreeditNothing | XIMStatusNothing)) {
  205. xim_style = xim_styles->supported_styles[i];
  206. break;
  207. }
  208. }
  209. XFree(xim_styles);
  210. }
  211. XFree(imvalret);
  212. }
  213. /*
  214. char* windowid = getenv("GODOT_WINDOWID");
  215. if (windowid) {
  216. //freopen("/home/punto/stdout", "w", stdout);
  217. //reopen("/home/punto/stderr", "w", stderr);
  218. x11_window = atol(windowid);
  219. XWindowAttributes xwa;
  220. XGetWindowAttributes(x11_display,x11_window,&xwa);
  221. current_videomode.width = xwa.width;
  222. current_videomode.height = xwa.height;
  223. };
  224. */
  225. // maybe contextgl wants to be in charge of creating the window
  226. #if defined(OPENGL_ENABLED)
  227. // Set DRI_PRIME if not set. This means that Godot should default to a higher-power GPU if it exists.
  228. // Note: Due to the final '0' parameter to setenv any existing DRI_PRIME environment variables will not
  229. // be overwritten.
  230. setenv("DRI_PRIME", "1", 0);
  231. ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE;
  232. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  233. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  234. }
  235. bool editor = Engine::get_singleton()->is_editor_hint();
  236. bool gl_initialization_error = false;
  237. context_gl = NULL;
  238. while (!context_gl) {
  239. context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type));
  240. if (context_gl->initialize() != OK) {
  241. memdelete(context_gl);
  242. context_gl = NULL;
  243. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) {
  244. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  245. gl_initialization_error = true;
  246. break;
  247. }
  248. p_video_driver = VIDEO_DRIVER_GLES2;
  249. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  250. } else {
  251. gl_initialization_error = true;
  252. break;
  253. }
  254. }
  255. }
  256. while (true) {
  257. if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) {
  258. if (RasterizerGLES3::is_viable() == OK) {
  259. RasterizerGLES3::register_config();
  260. RasterizerGLES3::make_current();
  261. break;
  262. } else {
  263. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) {
  264. p_video_driver = VIDEO_DRIVER_GLES2;
  265. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  266. continue;
  267. } else {
  268. gl_initialization_error = true;
  269. break;
  270. }
  271. }
  272. }
  273. if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) {
  274. if (RasterizerGLES2::is_viable() == OK) {
  275. RasterizerGLES2::register_config();
  276. RasterizerGLES2::make_current();
  277. break;
  278. } else {
  279. gl_initialization_error = true;
  280. break;
  281. }
  282. }
  283. }
  284. if (gl_initialization_error) {
  285. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  286. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  287. "Unable to initialize Video driver");
  288. return ERR_UNAVAILABLE;
  289. }
  290. video_driver_index = p_video_driver;
  291. context_gl->set_use_vsync(current_videomode.use_vsync);
  292. #endif
  293. visual_server = memnew(VisualServerRaster);
  294. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  295. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  296. }
  297. if (current_videomode.maximized) {
  298. current_videomode.maximized = false;
  299. set_window_maximized(true);
  300. // borderless fullscreen window mode
  301. } else if (current_videomode.fullscreen) {
  302. current_videomode.fullscreen = false;
  303. set_window_fullscreen(true);
  304. } else if (current_videomode.borderless_window) {
  305. Hints hints;
  306. Atom property;
  307. hints.flags = 2;
  308. hints.decorations = 0;
  309. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  310. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  311. }
  312. // disable resizable window
  313. if (!current_videomode.resizable && !current_videomode.fullscreen) {
  314. XSizeHints *xsh;
  315. xsh = XAllocSizeHints();
  316. xsh->flags = PMinSize | PMaxSize;
  317. XWindowAttributes xwa;
  318. if (current_videomode.fullscreen) {
  319. XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
  320. } else {
  321. XGetWindowAttributes(x11_display, x11_window, &xwa);
  322. }
  323. xsh->min_width = xwa.width;
  324. xsh->max_width = xwa.width;
  325. xsh->min_height = xwa.height;
  326. xsh->max_height = xwa.height;
  327. XSetWMNormalHints(x11_display, x11_window, xsh);
  328. XFree(xsh);
  329. }
  330. if (current_videomode.always_on_top) {
  331. current_videomode.always_on_top = false;
  332. set_window_always_on_top(true);
  333. }
  334. ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE);
  335. ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE);
  336. XSetWindowAttributes new_attr;
  337. new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
  338. ButtonReleaseMask | EnterWindowMask |
  339. LeaveWindowMask | PointerMotionMask |
  340. Button1MotionMask |
  341. Button2MotionMask | Button3MotionMask |
  342. Button4MotionMask | Button5MotionMask |
  343. ButtonMotionMask | KeymapStateMask |
  344. ExposureMask | VisibilityChangeMask |
  345. StructureNotifyMask |
  346. SubstructureNotifyMask | SubstructureRedirectMask |
  347. FocusChangeMask | PropertyChangeMask |
  348. ColormapChangeMask | OwnerGrabButtonMask |
  349. im_event_mask;
  350. XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr);
  351. #ifdef TOUCH_ENABLED
  352. if (touch.devices.size()) {
  353. // Must be alive after this block
  354. static unsigned char mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  355. touch.event_mask.deviceid = XIAllDevices;
  356. touch.event_mask.mask_len = sizeof(mask_data);
  357. touch.event_mask.mask = mask_data;
  358. XISetMask(touch.event_mask.mask, XI_TouchBegin);
  359. XISetMask(touch.event_mask.mask, XI_TouchUpdate);
  360. XISetMask(touch.event_mask.mask, XI_TouchEnd);
  361. XISetMask(touch.event_mask.mask, XI_TouchOwnership);
  362. XISelectEvents(x11_display, x11_window, &touch.event_mask, 1);
  363. // Disabled by now since grabbing also blocks mouse events
  364. // (they are received as extended events instead of standard events)
  365. /*XIClearMask(touch.event_mask.mask, XI_TouchOwnership);
  366. // Grab touch devices to avoid OS gesture interference
  367. for (int i = 0; i < touch.devices.size(); ++i) {
  368. XIGrabDevice(x11_display, touch.devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &touch.event_mask);
  369. }*/
  370. }
  371. #endif
  372. /* set the titlebar name */
  373. XStoreName(x11_display, x11_window, "Godot");
  374. wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
  375. XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);
  376. im_active = false;
  377. im_position = Vector2();
  378. if (xim && xim_style) {
  379. xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)NULL);
  380. if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != NULL) {
  381. WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
  382. XDestroyIC(xic);
  383. xic = NULL;
  384. }
  385. if (xic) {
  386. XUnsetICFocus(xic);
  387. } else {
  388. WARN_PRINT("XCreateIC couldn't create xic");
  389. }
  390. } else {
  391. xic = NULL;
  392. WARN_PRINT("XCreateIC couldn't create xic");
  393. }
  394. cursor_size = XcursorGetDefaultSize(x11_display);
  395. cursor_theme = XcursorGetTheme(x11_display);
  396. if (!cursor_theme) {
  397. print_verbose("XcursorGetTheme could not get cursor theme");
  398. cursor_theme = "default";
  399. }
  400. for (int i = 0; i < CURSOR_MAX; i++) {
  401. cursors[i] = None;
  402. img[i] = NULL;
  403. }
  404. current_cursor = CURSOR_ARROW;
  405. if (cursor_theme) {
  406. for (int i = 0; i < CURSOR_MAX; i++) {
  407. static const char *cursor_file[] = {
  408. "left_ptr",
  409. "xterm",
  410. "hand2",
  411. "cross",
  412. "watch",
  413. "left_ptr_watch",
  414. "fleur",
  415. "hand1",
  416. "X_cursor",
  417. "sb_v_double_arrow",
  418. "sb_h_double_arrow",
  419. "size_bdiag",
  420. "size_fdiag",
  421. "hand1",
  422. "sb_v_double_arrow",
  423. "sb_h_double_arrow",
  424. "question_arrow"
  425. };
  426. img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
  427. if (img[i]) {
  428. cursors[i] = XcursorImageLoadCursor(x11_display, img[i]);
  429. } else {
  430. print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
  431. }
  432. }
  433. }
  434. {
  435. Pixmap cursormask;
  436. XGCValues xgc;
  437. GC gc;
  438. XColor col;
  439. Cursor cursor;
  440. cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
  441. xgc.function = GXclear;
  442. gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
  443. XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
  444. col.pixel = 0;
  445. col.red = 0;
  446. col.flags = 4;
  447. cursor = XCreatePixmapCursor(x11_display,
  448. cursormask, cursormask,
  449. &col, &col, 0, 0);
  450. XFreePixmap(x11_display, cursormask);
  451. XFreeGC(x11_display, gc);
  452. if (cursor == None) {
  453. ERR_PRINT("FAILED CREATING CURSOR");
  454. }
  455. null_cursor = cursor;
  456. }
  457. set_cursor_shape(CURSOR_BUSY);
  458. //Set Xdnd (drag & drop) support
  459. Atom XdndAware = XInternAtom(x11_display, "XdndAware", False);
  460. Atom version = 5;
  461. XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1);
  462. xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
  463. xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
  464. xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
  465. xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
  466. xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
  467. xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
  468. xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
  469. requested = None;
  470. visual_server->init();
  471. AudioDriverManager::initialize(p_audio_driver);
  472. input = memnew(InputDefault);
  473. window_has_focus = true; // Set focus to true at init
  474. #ifdef JOYDEV_ENABLED
  475. joypad = memnew(JoypadLinux(input));
  476. #endif
  477. _ensure_user_data_dir();
  478. power_manager = memnew(PowerX11);
  479. if (p_desired.layered_splash) {
  480. set_window_per_pixel_transparency_enabled(true);
  481. }
  482. XEvent xevent;
  483. while (XPending(x11_display) > 0) {
  484. XNextEvent(x11_display, &xevent);
  485. if (xevent.type == ConfigureNotify) {
  486. _window_changed(&xevent);
  487. }
  488. }
  489. update_real_mouse_position();
  490. return OK;
  491. }
  492. void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data,
  493. ::XPointer call_data) {
  494. WARN_PRINT("Input method stopped");
  495. OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data);
  496. os->xim = NULL;
  497. os->xic = NULL;
  498. }
  499. void OS_X11::set_ime_active(const bool p_active) {
  500. im_active = p_active;
  501. if (!xic)
  502. return;
  503. if (p_active) {
  504. XSetICFocus(xic);
  505. set_ime_position(im_position);
  506. } else {
  507. XUnsetICFocus(xic);
  508. }
  509. }
  510. void OS_X11::set_ime_position(const Point2 &p_pos) {
  511. im_position = p_pos;
  512. if (!xic)
  513. return;
  514. ::XPoint spot;
  515. spot.x = short(p_pos.x);
  516. spot.y = short(p_pos.y);
  517. XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL);
  518. XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL);
  519. XFree(preedit_attr);
  520. }
  521. String OS_X11::get_unique_id() const {
  522. static String machine_id;
  523. if (machine_id.empty()) {
  524. if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) {
  525. while (machine_id.empty() && !f->eof_reached()) {
  526. machine_id = f->get_line().strip_edges();
  527. }
  528. f->close();
  529. memdelete(f);
  530. }
  531. }
  532. return machine_id;
  533. }
  534. void OS_X11::finalize() {
  535. if (main_loop)
  536. memdelete(main_loop);
  537. main_loop = NULL;
  538. /*
  539. if (debugger_connection_console) {
  540. memdelete(debugger_connection_console);
  541. }
  542. */
  543. #ifdef ALSAMIDI_ENABLED
  544. driver_alsamidi.close();
  545. #endif
  546. #ifdef JOYDEV_ENABLED
  547. memdelete(joypad);
  548. #endif
  549. #ifdef TOUCH_ENABLED
  550. touch.devices.clear();
  551. touch.state.clear();
  552. #endif
  553. memdelete(input);
  554. visual_server->finish();
  555. memdelete(visual_server);
  556. //memdelete(rasterizer);
  557. memdelete(power_manager);
  558. if (xrandr_handle)
  559. dlclose(xrandr_handle);
  560. XUnmapWindow(x11_display, x11_window);
  561. XDestroyWindow(x11_display, x11_window);
  562. #if defined(OPENGL_ENABLED)
  563. memdelete(context_gl);
  564. #endif
  565. for (int i = 0; i < CURSOR_MAX; i++) {
  566. if (cursors[i] != None)
  567. XFreeCursor(x11_display, cursors[i]);
  568. if (img[i] != NULL)
  569. XcursorImageDestroy(img[i]);
  570. };
  571. if (xic) {
  572. XDestroyIC(xic);
  573. }
  574. if (xim) {
  575. XCloseIM(xim);
  576. }
  577. XCloseDisplay(x11_display);
  578. if (xmbstring)
  579. memfree(xmbstring);
  580. args.clear();
  581. }
  582. void OS_X11::set_mouse_mode(MouseMode p_mode) {
  583. if (p_mode == mouse_mode)
  584. return;
  585. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED)
  586. XUngrabPointer(x11_display, CurrentTime);
  587. // The only modes that show a cursor are VISIBLE and CONFINED
  588. bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
  589. if (showCursor) {
  590. XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor
  591. } else {
  592. XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor
  593. }
  594. mouse_mode = p_mode;
  595. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  596. while (true) {
  597. //flush pending motion events
  598. if (XPending(x11_display) > 0) {
  599. XEvent event;
  600. XPeekEvent(x11_display, &event);
  601. if (event.type == MotionNotify) {
  602. XNextEvent(x11_display, &event);
  603. } else {
  604. break;
  605. }
  606. } else {
  607. break;
  608. }
  609. }
  610. if (XGrabPointer(
  611. x11_display, x11_window, True,
  612. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  613. GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) {
  614. ERR_PRINT("NO GRAB");
  615. }
  616. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  617. center.x = current_videomode.width / 2;
  618. center.y = current_videomode.height / 2;
  619. XWarpPointer(x11_display, None, x11_window,
  620. 0, 0, 0, 0, (int)center.x, (int)center.y);
  621. input->set_mouse_position(center);
  622. }
  623. } else {
  624. do_mouse_warp = false;
  625. }
  626. XFlush(x11_display);
  627. }
  628. void OS_X11::warp_mouse_position(const Point2 &p_to) {
  629. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  630. last_mouse_pos = p_to;
  631. } else {
  632. /*XWindowAttributes xwa;
  633. XGetWindowAttributes(x11_display, x11_window, &xwa);
  634. printf("%d %d\n", xwa.x, xwa.y); needed? */
  635. XWarpPointer(x11_display, None, x11_window,
  636. 0, 0, 0, 0, (int)p_to.x, (int)p_to.y);
  637. }
  638. }
  639. OS::MouseMode OS_X11::get_mouse_mode() const {
  640. return mouse_mode;
  641. }
  642. int OS_X11::get_mouse_button_state() const {
  643. return last_button_state;
  644. }
  645. Point2 OS_X11::get_mouse_position() const {
  646. return last_mouse_pos;
  647. }
  648. bool OS_X11::get_window_per_pixel_transparency_enabled() const {
  649. if (!is_layered_allowed()) return false;
  650. return layered_window;
  651. }
  652. void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  653. if (!is_layered_allowed()) return;
  654. if (layered_window != p_enabled) {
  655. if (p_enabled) {
  656. set_borderless_window(true);
  657. layered_window = true;
  658. } else {
  659. layered_window = false;
  660. }
  661. }
  662. }
  663. void OS_X11::set_window_title(const String &p_title) {
  664. XStoreName(x11_display, x11_window, p_title.utf8().get_data());
  665. Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
  666. Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
  667. XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
  668. }
  669. void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  670. }
  671. OS::VideoMode OS_X11::get_video_mode(int p_screen) const {
  672. return current_videomode;
  673. }
  674. void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  675. }
  676. void OS_X11::set_wm_fullscreen(bool p_enabled) {
  677. if (p_enabled && !get_borderless_window()) {
  678. // remove decorations if the window is not already borderless
  679. Hints hints;
  680. Atom property;
  681. hints.flags = 2;
  682. hints.decorations = 0;
  683. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  684. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  685. }
  686. if (p_enabled && !is_window_resizable()) {
  687. // Set the window as resizable to prevent window managers to ignore the fullscreen state flag.
  688. XSizeHints *xsh;
  689. xsh = XAllocSizeHints();
  690. xsh->flags = 0L;
  691. XSetWMNormalHints(x11_display, x11_window, xsh);
  692. XFree(xsh);
  693. }
  694. // Using EWMH -- Extended Window Manager Hints
  695. XEvent xev;
  696. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  697. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  698. memset(&xev, 0, sizeof(xev));
  699. xev.type = ClientMessage;
  700. xev.xclient.window = x11_window;
  701. xev.xclient.message_type = wm_state;
  702. xev.xclient.format = 32;
  703. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  704. xev.xclient.data.l[1] = wm_fullscreen;
  705. xev.xclient.data.l[2] = 0;
  706. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  707. // set bypass compositor hint
  708. Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
  709. unsigned long compositing_disable_on = p_enabled ? 1 : 0;
  710. XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
  711. XFlush(x11_display);
  712. if (!p_enabled && !is_window_resizable()) {
  713. // Reset the non-resizable flags if we un-set these before.
  714. Size2 size = get_window_size();
  715. XSizeHints *xsh;
  716. xsh = XAllocSizeHints();
  717. xsh->flags = PMinSize | PMaxSize;
  718. xsh->min_width = size.x;
  719. xsh->max_width = size.x;
  720. xsh->min_height = size.y;
  721. xsh->max_height = size.y;
  722. XSetWMNormalHints(x11_display, x11_window, xsh);
  723. XFree(xsh);
  724. }
  725. if (!p_enabled && !get_borderless_window()) {
  726. // put decorations back if the window wasn't suppoesed to be borderless
  727. Hints hints;
  728. Atom property;
  729. hints.flags = 2;
  730. hints.decorations = 1;
  731. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  732. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  733. }
  734. }
  735. void OS_X11::set_wm_above(bool p_enabled) {
  736. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  737. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  738. XClientMessageEvent xev;
  739. memset(&xev, 0, sizeof(xev));
  740. xev.type = ClientMessage;
  741. xev.window = x11_window;
  742. xev.message_type = wm_state;
  743. xev.format = 32;
  744. xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  745. xev.data.l[1] = wm_above;
  746. xev.data.l[3] = 1;
  747. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  748. }
  749. int OS_X11::get_screen_count() const {
  750. // Using Xinerama Extension
  751. int event_base, error_base;
  752. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  753. if (!ext_okay) return 0;
  754. int count;
  755. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  756. XFree(xsi);
  757. return count;
  758. }
  759. int OS_X11::get_current_screen() const {
  760. int x, y;
  761. Window child;
  762. XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  763. int count = get_screen_count();
  764. for (int i = 0; i < count; i++) {
  765. Point2i pos = get_screen_position(i);
  766. Size2i size = get_screen_size(i);
  767. if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height))
  768. return i;
  769. }
  770. return 0;
  771. }
  772. void OS_X11::set_current_screen(int p_screen) {
  773. int count = get_screen_count();
  774. if (p_screen >= count) return;
  775. if (current_videomode.fullscreen) {
  776. Point2i position = get_screen_position(p_screen);
  777. Size2i size = get_screen_size(p_screen);
  778. XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y);
  779. } else {
  780. if (p_screen != get_current_screen()) {
  781. Point2i position = get_screen_position(p_screen);
  782. XMoveWindow(x11_display, x11_window, position.x, position.y);
  783. }
  784. }
  785. }
  786. Point2 OS_X11::get_screen_position(int p_screen) const {
  787. if (p_screen == -1) {
  788. p_screen = get_current_screen();
  789. }
  790. // Using Xinerama Extension
  791. int event_base, error_base;
  792. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  793. if (!ext_okay) {
  794. return Point2i(0, 0);
  795. }
  796. int count;
  797. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  798. if (p_screen >= count) {
  799. return Point2i(0, 0);
  800. }
  801. Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org);
  802. XFree(xsi);
  803. return position;
  804. }
  805. Size2 OS_X11::get_screen_size(int p_screen) const {
  806. if (p_screen == -1) {
  807. p_screen = get_current_screen();
  808. }
  809. // Using Xinerama Extension
  810. int event_base, error_base;
  811. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  812. if (!ext_okay) return Size2i(0, 0);
  813. int count;
  814. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  815. if (p_screen >= count) return Size2i(0, 0);
  816. Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height);
  817. XFree(xsi);
  818. return size;
  819. }
  820. int OS_X11::get_screen_dpi(int p_screen) const {
  821. if (p_screen == -1) {
  822. p_screen = get_current_screen();
  823. }
  824. //invalid screen?
  825. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0);
  826. //Get physical monitor Dimensions through XRandR and calculate dpi
  827. Size2 sc = get_screen_size(p_screen);
  828. if (xrandr_ext_ok) {
  829. int count = 0;
  830. if (xrr_get_monitors) {
  831. xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count);
  832. if (p_screen < count) {
  833. double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4;
  834. double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4;
  835. xrr_free_monitors(monitors);
  836. return (xdpi + ydpi) / 2;
  837. }
  838. xrr_free_monitors(monitors);
  839. } else if (p_screen == 0) {
  840. XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count);
  841. if (sizes) {
  842. double xdpi = sc.width / (double)sizes[0].mwidth * 25.4;
  843. double ydpi = sc.height / (double)sizes[0].mheight * 25.4;
  844. return (xdpi + ydpi) / 2;
  845. }
  846. }
  847. }
  848. int width_mm = DisplayWidthMM(x11_display, p_screen);
  849. int height_mm = DisplayHeightMM(x11_display, p_screen);
  850. double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0);
  851. double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0);
  852. if (xdpi || xdpi)
  853. return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1);
  854. //could not get dpi
  855. return 96;
  856. }
  857. Point2 OS_X11::get_window_position() const {
  858. int x, y;
  859. Window child;
  860. XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  861. int screen = get_current_screen();
  862. Point2i screen_position = get_screen_position(screen);
  863. return Point2i(x - screen_position.x, y - screen_position.y);
  864. }
  865. void OS_X11::set_window_position(const Point2 &p_position) {
  866. XMoveWindow(x11_display, x11_window, p_position.x, p_position.y);
  867. update_real_mouse_position();
  868. }
  869. Size2 OS_X11::get_window_size() const {
  870. // Use current_videomode width and height instead of XGetWindowAttributes
  871. // since right after a XResizeWindow the attributes may not be updated yet
  872. return Size2i(current_videomode.width, current_videomode.height);
  873. }
  874. Size2 OS_X11::get_real_window_size() const {
  875. XWindowAttributes xwa;
  876. XSync(x11_display, False);
  877. XGetWindowAttributes(x11_display, x11_window, &xwa);
  878. int w = xwa.width;
  879. int h = xwa.height;
  880. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  881. Atom type;
  882. int format;
  883. unsigned long len;
  884. unsigned long remaining;
  885. unsigned char *data = NULL;
  886. if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  887. long *extents = (long *)data;
  888. w += extents[0] + extents[1]; // left, right
  889. h += extents[2] + extents[3]; // top, bottom
  890. }
  891. return Size2(w, h);
  892. }
  893. void OS_X11::set_window_size(const Size2 p_size) {
  894. if (current_videomode.width == p_size.width && current_videomode.height == p_size.height)
  895. return;
  896. XWindowAttributes xwa;
  897. XSync(x11_display, False);
  898. XGetWindowAttributes(x11_display, x11_window, &xwa);
  899. int old_w = xwa.width;
  900. int old_h = xwa.height;
  901. // If window resizable is disabled we need to update the attributes first
  902. if (!is_window_resizable()) {
  903. XSizeHints *xsh;
  904. xsh = XAllocSizeHints();
  905. xsh->flags = PMinSize | PMaxSize;
  906. xsh->min_width = p_size.x;
  907. xsh->max_width = p_size.x;
  908. xsh->min_height = p_size.y;
  909. xsh->max_height = p_size.y;
  910. XSetWMNormalHints(x11_display, x11_window, xsh);
  911. XFree(xsh);
  912. }
  913. // Resize the window
  914. XResizeWindow(x11_display, x11_window, p_size.x, p_size.y);
  915. // Update our videomode width and height
  916. current_videomode.width = p_size.x;
  917. current_videomode.height = p_size.y;
  918. for (int timeout = 0; timeout < 50; ++timeout) {
  919. XSync(x11_display, False);
  920. XGetWindowAttributes(x11_display, x11_window, &xwa);
  921. if (old_w != xwa.width || old_h != xwa.height)
  922. break;
  923. usleep(10000);
  924. }
  925. }
  926. void OS_X11::set_window_fullscreen(bool p_enabled) {
  927. if (current_videomode.fullscreen == p_enabled)
  928. return;
  929. if (layered_window)
  930. set_window_per_pixel_transparency_enabled(false);
  931. if (p_enabled && current_videomode.always_on_top) {
  932. // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity)
  933. set_window_maximized(true);
  934. }
  935. set_wm_fullscreen(p_enabled);
  936. if (!p_enabled && !current_videomode.always_on_top) {
  937. // Restore
  938. set_window_maximized(false);
  939. }
  940. current_videomode.fullscreen = p_enabled;
  941. }
  942. bool OS_X11::is_window_fullscreen() const {
  943. return current_videomode.fullscreen;
  944. }
  945. void OS_X11::set_window_resizable(bool p_enabled) {
  946. XSizeHints *xsh;
  947. Size2 size = get_window_size();
  948. xsh = XAllocSizeHints();
  949. xsh->flags = p_enabled ? 0L : PMinSize | PMaxSize;
  950. if (!p_enabled) {
  951. xsh->min_width = size.x;
  952. xsh->max_width = size.x;
  953. xsh->min_height = size.y;
  954. xsh->max_height = size.y;
  955. }
  956. XSetWMNormalHints(x11_display, x11_window, xsh);
  957. XFree(xsh);
  958. current_videomode.resizable = p_enabled;
  959. }
  960. bool OS_X11::is_window_resizable() const {
  961. return current_videomode.resizable;
  962. }
  963. void OS_X11::set_window_minimized(bool p_enabled) {
  964. // Using ICCCM -- Inter-Client Communication Conventions Manual
  965. XEvent xev;
  966. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  967. memset(&xev, 0, sizeof(xev));
  968. xev.type = ClientMessage;
  969. xev.xclient.window = x11_window;
  970. xev.xclient.message_type = wm_change;
  971. xev.xclient.format = 32;
  972. xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState;
  973. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  974. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  975. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  976. memset(&xev, 0, sizeof(xev));
  977. xev.type = ClientMessage;
  978. xev.xclient.window = x11_window;
  979. xev.xclient.message_type = wm_state;
  980. xev.xclient.format = 32;
  981. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  982. xev.xclient.data.l[1] = wm_hidden;
  983. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  984. }
  985. bool OS_X11::is_window_minimized() const {
  986. // Using ICCCM -- Inter-Client Communication Conventions Manual
  987. Atom property = XInternAtom(x11_display, "WM_STATE", True);
  988. Atom type;
  989. int format;
  990. unsigned long len;
  991. unsigned long remaining;
  992. unsigned char *data = NULL;
  993. int result = XGetWindowProperty(
  994. x11_display,
  995. x11_window,
  996. property,
  997. 0,
  998. 32,
  999. False,
  1000. AnyPropertyType,
  1001. &type,
  1002. &format,
  1003. &len,
  1004. &remaining,
  1005. &data);
  1006. if (result == Success) {
  1007. long *state = (long *)data;
  1008. if (state[0] == WM_IconicState)
  1009. return true;
  1010. }
  1011. return false;
  1012. }
  1013. void OS_X11::set_window_maximized(bool p_enabled) {
  1014. if (is_window_maximized() == p_enabled)
  1015. return;
  1016. // Using EWMH -- Extended Window Manager Hints
  1017. XEvent xev;
  1018. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1019. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1020. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1021. memset(&xev, 0, sizeof(xev));
  1022. xev.type = ClientMessage;
  1023. xev.xclient.window = x11_window;
  1024. xev.xclient.message_type = wm_state;
  1025. xev.xclient.format = 32;
  1026. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1027. xev.xclient.data.l[1] = wm_max_horz;
  1028. xev.xclient.data.l[2] = wm_max_vert;
  1029. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1030. if (is_window_maximize_allowed()) {
  1031. while (p_enabled && !is_window_maximized()) {
  1032. // Wait for effective resizing (so the GLX context is too).
  1033. }
  1034. }
  1035. maximized = p_enabled;
  1036. }
  1037. bool OS_X11::is_window_maximize_allowed() {
  1038. Atom property = XInternAtom(x11_display, "_NET_WM_ALLOWED_ACTIONS", False);
  1039. Atom type;
  1040. int format;
  1041. unsigned long len;
  1042. unsigned long remaining;
  1043. unsigned char *data = NULL;
  1044. int result = XGetWindowProperty(
  1045. x11_display,
  1046. x11_window,
  1047. property,
  1048. 0,
  1049. 1024,
  1050. False,
  1051. XA_ATOM,
  1052. &type,
  1053. &format,
  1054. &len,
  1055. &remaining,
  1056. &data);
  1057. if (result == Success) {
  1058. Atom *atoms = (Atom *)data;
  1059. Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False);
  1060. Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False);
  1061. bool found_wm_act_max_horz = false;
  1062. bool found_wm_act_max_vert = false;
  1063. for (unsigned int i = 0; i < len; i++) {
  1064. if (atoms[i] == wm_act_max_horz)
  1065. found_wm_act_max_horz = true;
  1066. if (atoms[i] == wm_act_max_vert)
  1067. found_wm_act_max_vert = true;
  1068. if (found_wm_act_max_horz || found_wm_act_max_vert)
  1069. return true;
  1070. }
  1071. XFree(atoms);
  1072. }
  1073. return false;
  1074. }
  1075. bool OS_X11::is_window_maximized() const {
  1076. // Using EWMH -- Extended Window Manager Hints
  1077. Atom property = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1078. Atom type;
  1079. int format;
  1080. unsigned long len;
  1081. unsigned long remaining;
  1082. unsigned char *data = NULL;
  1083. bool retval = false;
  1084. int result = XGetWindowProperty(
  1085. x11_display,
  1086. x11_window,
  1087. property,
  1088. 0,
  1089. 1024,
  1090. False,
  1091. XA_ATOM,
  1092. &type,
  1093. &format,
  1094. &len,
  1095. &remaining,
  1096. &data);
  1097. if (result == Success) {
  1098. Atom *atoms = (Atom *)data;
  1099. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1100. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1101. bool found_wm_max_horz = false;
  1102. bool found_wm_max_vert = false;
  1103. for (unsigned int i = 0; i < len; i++) {
  1104. if (atoms[i] == wm_max_horz)
  1105. found_wm_max_horz = true;
  1106. if (atoms[i] == wm_max_vert)
  1107. found_wm_max_vert = true;
  1108. if (found_wm_max_horz && found_wm_max_vert) {
  1109. retval = true;
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. XFree(data);
  1115. return retval;
  1116. }
  1117. void OS_X11::set_window_always_on_top(bool p_enabled) {
  1118. if (is_window_always_on_top() == p_enabled)
  1119. return;
  1120. if (p_enabled && current_videomode.fullscreen) {
  1121. // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity)
  1122. set_window_maximized(true);
  1123. }
  1124. set_wm_above(p_enabled);
  1125. if (!p_enabled && !current_videomode.fullscreen) {
  1126. // Restore
  1127. set_window_maximized(false);
  1128. }
  1129. current_videomode.always_on_top = p_enabled;
  1130. }
  1131. bool OS_X11::is_window_always_on_top() const {
  1132. return current_videomode.always_on_top;
  1133. }
  1134. void OS_X11::set_borderless_window(bool p_borderless) {
  1135. if (current_videomode.borderless_window == p_borderless)
  1136. return;
  1137. if (!p_borderless && layered_window)
  1138. set_window_per_pixel_transparency_enabled(false);
  1139. current_videomode.borderless_window = p_borderless;
  1140. Hints hints;
  1141. Atom property;
  1142. hints.flags = 2;
  1143. hints.decorations = current_videomode.borderless_window ? 0 : 1;
  1144. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1145. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1146. // Preserve window size
  1147. set_window_size(Size2(current_videomode.width, current_videomode.height));
  1148. }
  1149. bool OS_X11::get_borderless_window() {
  1150. return current_videomode.borderless_window;
  1151. }
  1152. void OS_X11::request_attention() {
  1153. // Using EWMH -- Extended Window Manager Hints
  1154. //
  1155. // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
  1156. // Will be unset by the window manager after user react on the request for attention
  1157. XEvent xev;
  1158. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1159. Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
  1160. memset(&xev, 0, sizeof(xev));
  1161. xev.type = ClientMessage;
  1162. xev.xclient.window = x11_window;
  1163. xev.xclient.message_type = wm_state;
  1164. xev.xclient.format = 32;
  1165. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1166. xev.xclient.data.l[1] = wm_attention;
  1167. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1168. XFlush(x11_display);
  1169. }
  1170. void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
  1171. state->set_shift((p_x11_state & ShiftMask));
  1172. state->set_control((p_x11_state & ControlMask));
  1173. state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt
  1174. state->set_metakey((p_x11_state & Mod4Mask));
  1175. }
  1176. unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_state) {
  1177. unsigned int state = 0;
  1178. if (p_x11_state & Button1Mask) {
  1179. state |= 1 << 0;
  1180. }
  1181. if (p_x11_state & Button3Mask) {
  1182. state |= 1 << 1;
  1183. }
  1184. if (p_x11_state & Button2Mask) {
  1185. state |= 1 << 2;
  1186. }
  1187. if (p_x11_state & Button4Mask) {
  1188. state |= 1 << 3;
  1189. }
  1190. if (p_x11_state & Button5Mask) {
  1191. state |= 1 << 4;
  1192. }
  1193. last_button_state = state;
  1194. return state;
  1195. }
  1196. void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
  1197. // X11 functions don't know what const is
  1198. XKeyEvent *xkeyevent = p_event;
  1199. // This code was pretty difficult to write.
  1200. // The docs stink and every toolkit seems to
  1201. // do it in a different way.
  1202. /* Phase 1, obtain a proper keysym */
  1203. // This was also very difficult to figure out.
  1204. // You'd expect you could just use Keysym provided by
  1205. // XKeycodeToKeysym to obtain internationalized
  1206. // input.. WRONG!!
  1207. // you must use XLookupString (???) which not only wastes
  1208. // cycles generating an unnecessary string, but also
  1209. // still works in half the cases. (won't handle deadkeys)
  1210. // For more complex input methods (deadkeys and more advanced)
  1211. // you have to use XmbLookupString (??).
  1212. // So.. then you have to chosse which of both results
  1213. // you want to keep.
  1214. // This is a real bizarreness and cpu waster.
  1215. KeySym keysym_keycode = 0; // keysym used to find a keycode
  1216. KeySym keysym_unicode = 0; // keysym used to find unicode
  1217. // XLookupString returns keysyms usable as nice scancodes/
  1218. char str[256 + 1];
  1219. XLookupString(xkeyevent, str, 256, &keysym_keycode, NULL);
  1220. // Meanwhile, XLookupString returns keysyms useful for unicode.
  1221. if (!xmbstring) {
  1222. // keep a temporary buffer for the string
  1223. xmbstring = (char *)memalloc(sizeof(char) * 8);
  1224. xmblen = 8;
  1225. }
  1226. keysym_unicode = keysym_keycode;
  1227. if (xkeyevent->type == KeyPress && xic) {
  1228. Status status;
  1229. #ifdef X_HAVE_UTF8_STRING
  1230. int utf8len = 8;
  1231. char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
  1232. int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string,
  1233. utf8len - 1, &keysym_unicode, &status);
  1234. if (status == XBufferOverflow) {
  1235. utf8len = utf8bytes + 1;
  1236. utf8string = (char *)memrealloc(utf8string, utf8len);
  1237. utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string,
  1238. utf8len - 1, &keysym_unicode, &status);
  1239. }
  1240. utf8string[utf8bytes] = '\0';
  1241. if (status == XLookupChars) {
  1242. bool keypress = xkeyevent->type == KeyPress;
  1243. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode);
  1244. if (keycode >= 'a' && keycode <= 'z')
  1245. keycode -= 'a' - 'A';
  1246. String tmp;
  1247. tmp.parse_utf8(utf8string, utf8bytes);
  1248. for (int i = 0; i < tmp.length(); i++) {
  1249. Ref<InputEventKey> k;
  1250. k.instance();
  1251. if (keycode == 0 && tmp[i] == 0) {
  1252. continue;
  1253. }
  1254. get_key_modifier_state(xkeyevent->state, k);
  1255. k->set_unicode(tmp[i]);
  1256. k->set_pressed(keypress);
  1257. k->set_scancode(keycode);
  1258. k->set_echo(false);
  1259. if (k->get_scancode() == KEY_BACKTAB) {
  1260. //make it consistent across platforms.
  1261. k->set_scancode(KEY_TAB);
  1262. k->set_shift(true);
  1263. }
  1264. input->parse_input_event(k);
  1265. }
  1266. return;
  1267. }
  1268. memfree(utf8string);
  1269. #else
  1270. do {
  1271. int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
  1272. xmbstring[mnbytes] = '\0';
  1273. if (status == XBufferOverflow) {
  1274. xmblen = mnbytes + 1;
  1275. xmbstring = (char *)memrealloc(xmbstring, xmblen);
  1276. }
  1277. } while (status == XBufferOverflow);
  1278. #endif
  1279. }
  1280. /* Phase 2, obtain a pigui keycode from the keysym */
  1281. // KeyMappingX11 just translated the X11 keysym to a PIGUI
  1282. // keysym, so it works in all platforms the same.
  1283. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode);
  1284. /* Phase 3, obtain a unicode character from the keysym */
  1285. // KeyMappingX11 also translates keysym to unicode.
  1286. // It does a binary search on a table to translate
  1287. // most properly.
  1288. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
  1289. /* Phase 4, determine if event must be filtered */
  1290. // This seems to be a side-effect of using XIM.
  1291. // XEventFilter looks like a core X11 function,
  1292. // but it's actually just used to see if we must
  1293. // ignore a deadkey, or events XIM determines
  1294. // must not reach the actual gui.
  1295. // Guess it was a design problem of the extension
  1296. bool keypress = xkeyevent->type == KeyPress;
  1297. if (keycode == 0 && unicode == 0)
  1298. return;
  1299. /* Phase 5, determine modifier mask */
  1300. // No problems here, except I had no way to
  1301. // know Mod1 was ALT and Mod4 was META (applekey/winkey)
  1302. // just tried Mods until i found them.
  1303. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask));
  1304. Ref<InputEventKey> k;
  1305. k.instance();
  1306. get_key_modifier_state(xkeyevent->state, k);
  1307. /* Phase 6, determine echo character */
  1308. // Echo characters in X11 are a keyrelease and a keypress
  1309. // one after the other with the (almot) same timestamp.
  1310. // To detect them, i use XPeekEvent and check that their
  1311. // difference in time is below a threshold.
  1312. if (xkeyevent->type != KeyPress) {
  1313. p_echo = false;
  1314. // make sure there are events pending,
  1315. // so this call won't block.
  1316. if (XPending(x11_display) > 0) {
  1317. XEvent peek_event;
  1318. XPeekEvent(x11_display, &peek_event);
  1319. // I'm using a threshold of 5 msecs,
  1320. // since sometimes there seems to be a little
  1321. // jitter. I'm still not convinced that all this approach
  1322. // is correct, but the xorg developers are
  1323. // not very helpful today.
  1324. ::Time tresh = ABS(peek_event.xkey.time - xkeyevent->time);
  1325. if (peek_event.type == KeyPress && tresh < 5) {
  1326. KeySym rk;
  1327. XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL);
  1328. if (rk == keysym_keycode) {
  1329. XEvent event;
  1330. XNextEvent(x11_display, &event); //erase next event
  1331. handle_key_event((XKeyEvent *)&event, true);
  1332. return; //ignore current, echo next
  1333. }
  1334. }
  1335. // use the time from peek_event so it always works
  1336. }
  1337. // save the time to check for echo when keypress happens
  1338. }
  1339. /* Phase 7, send event to Window */
  1340. k->set_pressed(keypress);
  1341. if (keycode >= 'a' && keycode <= 'z')
  1342. keycode -= 'a' - 'A';
  1343. k->set_scancode(keycode);
  1344. k->set_unicode(unicode);
  1345. k->set_echo(p_echo);
  1346. if (k->get_scancode() == KEY_BACKTAB) {
  1347. //make it consistent across platforms.
  1348. k->set_scancode(KEY_TAB);
  1349. k->set_shift(true);
  1350. }
  1351. //don't set mod state if modifier keys are released by themselves
  1352. //else event.is_action() will not work correctly here
  1353. if (!k->is_pressed()) {
  1354. if (k->get_scancode() == KEY_SHIFT)
  1355. k->set_shift(false);
  1356. else if (k->get_scancode() == KEY_CONTROL)
  1357. k->set_control(false);
  1358. else if (k->get_scancode() == KEY_ALT)
  1359. k->set_alt(false);
  1360. else if (k->get_scancode() == KEY_META)
  1361. k->set_metakey(false);
  1362. }
  1363. bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode());
  1364. if (k->is_pressed()) {
  1365. if (last_is_pressed) {
  1366. k->set_echo(true);
  1367. }
  1368. } else {
  1369. //ignore
  1370. if (!last_is_pressed) {
  1371. return;
  1372. }
  1373. }
  1374. //printf("key: %x\n",k->get_scancode());
  1375. input->parse_input_event(k);
  1376. }
  1377. struct Property {
  1378. unsigned char *data;
  1379. int format, nitems;
  1380. Atom type;
  1381. };
  1382. static Property read_property(Display *p_display, Window p_window, Atom p_property) {
  1383. Atom actual_type;
  1384. int actual_format;
  1385. unsigned long nitems;
  1386. unsigned long bytes_after;
  1387. unsigned char *ret = 0;
  1388. int read_bytes = 1024;
  1389. //Keep trying to read the property until there are no
  1390. //bytes unread.
  1391. do {
  1392. if (ret != 0)
  1393. XFree(ret);
  1394. XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
  1395. &actual_type, &actual_format, &nitems, &bytes_after,
  1396. &ret);
  1397. read_bytes *= 2;
  1398. } while (bytes_after != 0);
  1399. Property p = { ret, actual_format, (int)nitems, actual_type };
  1400. return p;
  1401. }
  1402. static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) {
  1403. static const char *target_type = "text/uri-list";
  1404. for (int i = 0; i < p_count; i++) {
  1405. Atom atom = p_list[i];
  1406. if (atom != None && String(XGetAtomName(p_display, atom)) == target_type)
  1407. return atom;
  1408. }
  1409. return None;
  1410. }
  1411. static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
  1412. static const char *target_type = "text/uri-list";
  1413. if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type)
  1414. return p_t1;
  1415. if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type)
  1416. return p_t2;
  1417. if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type)
  1418. return p_t3;
  1419. return None;
  1420. }
  1421. void OS_X11::_window_changed(XEvent *event) {
  1422. if (xic) {
  1423. // Not portable.
  1424. set_ime_position(Point2(0, 1));
  1425. }
  1426. if ((event->xconfigure.width == current_videomode.width) &&
  1427. (event->xconfigure.height == current_videomode.height))
  1428. return;
  1429. current_videomode.width = event->xconfigure.width;
  1430. current_videomode.height = event->xconfigure.height;
  1431. }
  1432. void OS_X11::process_xevents() {
  1433. //printf("checking events %i\n", XPending(x11_display));
  1434. do_mouse_warp = false;
  1435. // Is the current mouse mode one where it needs to be grabbed.
  1436. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED;
  1437. while (XPending(x11_display) > 0) {
  1438. XEvent event;
  1439. XNextEvent(x11_display, &event);
  1440. if (XFilterEvent(&event, None)) {
  1441. continue;
  1442. }
  1443. #ifdef TOUCH_ENABLED
  1444. if (XGetEventData(x11_display, &event.xcookie)) {
  1445. if (event.xcookie.type == GenericEvent && event.xcookie.extension == touch.opcode) {
  1446. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  1447. int index = event_data->detail;
  1448. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  1449. switch (event_data->evtype) {
  1450. case XI_TouchBegin: // Fall-through
  1451. // Disabled hand-in-hand with the grabbing
  1452. //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch);
  1453. case XI_TouchEnd: {
  1454. bool is_begin = event_data->evtype == XI_TouchBegin;
  1455. Ref<InputEventScreenTouch> st;
  1456. st.instance();
  1457. st->set_index(index);
  1458. st->set_position(pos);
  1459. st->set_pressed(is_begin);
  1460. if (is_begin) {
  1461. if (touch.state.has(index)) // Defensive
  1462. break;
  1463. touch.state[index] = pos;
  1464. if (touch.state.size() == 1) {
  1465. // X11 may send a motion event when a touch gesture begins, that would result
  1466. // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out
  1467. touch.mouse_pos_to_filter = pos;
  1468. }
  1469. input->parse_input_event(st);
  1470. } else {
  1471. if (!touch.state.has(index)) // Defensive
  1472. break;
  1473. touch.state.erase(index);
  1474. input->parse_input_event(st);
  1475. }
  1476. } break;
  1477. case XI_TouchUpdate: {
  1478. Map<int, Vector2>::Element *curr_pos_elem = touch.state.find(index);
  1479. if (!curr_pos_elem) { // Defensive
  1480. break;
  1481. }
  1482. if (curr_pos_elem->value() != pos) {
  1483. Ref<InputEventScreenDrag> sd;
  1484. sd.instance();
  1485. sd->set_index(index);
  1486. sd->set_position(pos);
  1487. sd->set_relative(pos - curr_pos_elem->value());
  1488. input->parse_input_event(sd);
  1489. curr_pos_elem->value() = pos;
  1490. }
  1491. } break;
  1492. }
  1493. }
  1494. }
  1495. XFreeEventData(x11_display, &event.xcookie);
  1496. #endif
  1497. switch (event.type) {
  1498. case Expose:
  1499. Main::force_redraw();
  1500. break;
  1501. case NoExpose:
  1502. minimized = true;
  1503. break;
  1504. case VisibilityNotify: {
  1505. XVisibilityEvent *visibility = (XVisibilityEvent *)&event;
  1506. minimized = (visibility->state == VisibilityFullyObscured);
  1507. } break;
  1508. case LeaveNotify: {
  1509. if (main_loop && !mouse_mode_grab)
  1510. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  1511. if (input)
  1512. input->set_mouse_in_window(false);
  1513. } break;
  1514. case EnterNotify: {
  1515. if (main_loop && !mouse_mode_grab)
  1516. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  1517. if (input)
  1518. input->set_mouse_in_window(true);
  1519. } break;
  1520. case FocusIn:
  1521. minimized = false;
  1522. window_has_focus = true;
  1523. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  1524. if (mouse_mode_grab) {
  1525. // Show and update the cursor if confined and the window regained focus.
  1526. if (mouse_mode == MOUSE_MODE_CONFINED)
  1527. XUndefineCursor(x11_display, x11_window);
  1528. else if (mouse_mode == MOUSE_MODE_CAPTURED) // or re-hide it in captured mode
  1529. XDefineCursor(x11_display, x11_window, null_cursor);
  1530. XGrabPointer(
  1531. x11_display, x11_window, True,
  1532. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  1533. GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime);
  1534. }
  1535. #ifdef TOUCH_ENABLED
  1536. // Grab touch devices to avoid OS gesture interference
  1537. /*for (int i = 0; i < touch.devices.size(); ++i) {
  1538. XIGrabDevice(x11_display, touch.devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &touch.event_mask);
  1539. }*/
  1540. #endif
  1541. if (xic) {
  1542. XSetICFocus(xic);
  1543. }
  1544. break;
  1545. case FocusOut:
  1546. window_has_focus = false;
  1547. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  1548. if (mouse_mode_grab) {
  1549. //dear X11, I try, I really try, but you never work, you do whathever you want.
  1550. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1551. // Show the cursor if we're in captured mode so it doesn't look weird.
  1552. XUndefineCursor(x11_display, x11_window);
  1553. }
  1554. XUngrabPointer(x11_display, CurrentTime);
  1555. }
  1556. #ifdef TOUCH_ENABLED
  1557. // Ungrab touch devices so input works as usual while we are unfocused
  1558. /*for (int i = 0; i < touch.devices.size(); ++i) {
  1559. XIUngrabDevice(x11_display, touch.devices[i], CurrentTime);
  1560. }*/
  1561. // Release every pointer to avoid sticky points
  1562. for (Map<int, Vector2>::Element *E = touch.state.front(); E; E = E->next()) {
  1563. Ref<InputEventScreenTouch> st;
  1564. st.instance();
  1565. st->set_index(E->key());
  1566. st->set_position(E->get());
  1567. input->parse_input_event(st);
  1568. }
  1569. touch.state.clear();
  1570. #endif
  1571. if (xic) {
  1572. XUnsetICFocus(xic);
  1573. }
  1574. break;
  1575. case ConfigureNotify:
  1576. _window_changed(&event);
  1577. break;
  1578. case ButtonPress:
  1579. case ButtonRelease: {
  1580. /* exit in case of a mouse button press */
  1581. last_timestamp = event.xbutton.time;
  1582. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1583. event.xbutton.x = last_mouse_pos.x;
  1584. event.xbutton.y = last_mouse_pos.y;
  1585. }
  1586. Ref<InputEventMouseButton> mb;
  1587. mb.instance();
  1588. get_key_modifier_state(event.xbutton.state, mb);
  1589. mb->set_button_mask(get_mouse_button_state(event.xbutton.state));
  1590. mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
  1591. mb->set_global_position(mb->get_position());
  1592. mb->set_button_index(event.xbutton.button);
  1593. if (mb->get_button_index() == 2)
  1594. mb->set_button_index(3);
  1595. else if (mb->get_button_index() == 3)
  1596. mb->set_button_index(2);
  1597. mb->set_pressed((event.type == ButtonPress));
  1598. if (event.type == ButtonPress && event.xbutton.button == 1) {
  1599. uint64_t diff = get_ticks_usec() / 1000 - last_click_ms;
  1600. if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) {
  1601. last_click_ms = 0;
  1602. last_click_pos = Point2(-100, -100);
  1603. mb->set_doubleclick(true);
  1604. } else {
  1605. last_click_ms += diff;
  1606. last_click_pos = Point2(event.xbutton.x, event.xbutton.y);
  1607. }
  1608. }
  1609. input->parse_input_event(mb);
  1610. } break;
  1611. case MotionNotify: {
  1612. // The X11 API requires filtering one-by-one through the motion
  1613. // notify events, in order to figure out which event is the one
  1614. // generated by warping the mouse pointer.
  1615. while (true) {
  1616. if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) {
  1617. //this is likely the warp event since it was warped here
  1618. center = Vector2(event.xmotion.x, event.xmotion.y);
  1619. break;
  1620. }
  1621. if (XPending(x11_display) > 0) {
  1622. XEvent tevent;
  1623. XPeekEvent(x11_display, &tevent);
  1624. if (tevent.type == MotionNotify) {
  1625. XNextEvent(x11_display, &event);
  1626. } else {
  1627. break;
  1628. }
  1629. } else {
  1630. break;
  1631. }
  1632. }
  1633. last_timestamp = event.xmotion.time;
  1634. // Motion is also simple.
  1635. // A little hack is in order
  1636. // to be able to send relative motion events.
  1637. Point2i pos(event.xmotion.x, event.xmotion.y);
  1638. #ifdef TOUCH_ENABLED
  1639. // Avoidance of spurious mouse motion (see handling of touch)
  1640. bool filter = false;
  1641. // Adding some tolerance to match better Point2i to Vector2
  1642. if (touch.state.size() && Vector2(pos).distance_squared_to(touch.mouse_pos_to_filter) < 2) {
  1643. filter = true;
  1644. }
  1645. // Invalidate to avoid filtering a possible legitimate similar event coming later
  1646. touch.mouse_pos_to_filter = Vector2(1e10, 1e10);
  1647. if (filter) {
  1648. break;
  1649. }
  1650. #endif
  1651. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1652. if (pos == Point2i(current_videomode.width / 2, current_videomode.height / 2)) {
  1653. //this sucks, it's a hack, etc and is a little inaccurate, etc.
  1654. //but nothing I can do, X11 sucks.
  1655. center = pos;
  1656. break;
  1657. }
  1658. Point2i new_center = pos;
  1659. pos = last_mouse_pos + (pos - center);
  1660. center = new_center;
  1661. do_mouse_warp = window_has_focus; // warp the cursor if we're focused in
  1662. }
  1663. if (!last_mouse_pos_valid) {
  1664. last_mouse_pos = pos;
  1665. last_mouse_pos_valid = true;
  1666. }
  1667. Point2i rel = pos - last_mouse_pos;
  1668. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1669. pos = Point2i(current_videomode.width / 2, current_videomode.height / 2);
  1670. }
  1671. Ref<InputEventMouseMotion> mm;
  1672. mm.instance();
  1673. get_key_modifier_state(event.xmotion.state, mm);
  1674. mm->set_button_mask(get_mouse_button_state(event.xmotion.state));
  1675. mm->set_position(pos);
  1676. mm->set_global_position(pos);
  1677. input->set_mouse_position(pos);
  1678. mm->set_speed(input->get_last_mouse_speed());
  1679. mm->set_relative(rel);
  1680. last_mouse_pos = pos;
  1681. // printf("rel: %d,%d\n", rel.x, rel.y );
  1682. // Don't propagate the motion event unless we have focus
  1683. // this is so that the relative motion doesn't get messed up
  1684. // after we regain focus.
  1685. if (window_has_focus || !mouse_mode_grab)
  1686. input->parse_input_event(mm);
  1687. } break;
  1688. case KeyPress:
  1689. case KeyRelease: {
  1690. last_timestamp = event.xkey.time;
  1691. // key event is a little complex, so
  1692. // it will be handled in its own function.
  1693. handle_key_event((XKeyEvent *)&event);
  1694. } break;
  1695. case SelectionRequest: {
  1696. XSelectionRequestEvent *req;
  1697. XEvent e, respond;
  1698. e = event;
  1699. req = &(e.xselectionrequest);
  1700. if (req->target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
  1701. req->target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
  1702. req->target == XInternAtom(x11_display, "TEXT", 0) ||
  1703. req->target == XA_STRING ||
  1704. req->target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
  1705. req->target == XInternAtom(x11_display, "text/plain", 0)) {
  1706. CharString clip = OS::get_clipboard().utf8();
  1707. XChangeProperty(x11_display,
  1708. req->requestor,
  1709. req->property,
  1710. req->target,
  1711. 8,
  1712. PropModeReplace,
  1713. (unsigned char *)clip.get_data(),
  1714. clip.length());
  1715. respond.xselection.property = req->property;
  1716. } else if (req->target == XInternAtom(x11_display, "TARGETS", 0)) {
  1717. Atom data[7];
  1718. data[0] = XInternAtom(x11_display, "TARGETS", 0);
  1719. data[1] = XInternAtom(x11_display, "UTF8_STRING", 0);
  1720. data[2] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
  1721. data[3] = XInternAtom(x11_display, "TEXT", 0);
  1722. data[4] = XA_STRING;
  1723. data[5] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
  1724. data[6] = XInternAtom(x11_display, "text/plain", 0);
  1725. XChangeProperty(x11_display,
  1726. req->requestor,
  1727. req->property,
  1728. XA_ATOM,
  1729. 32,
  1730. PropModeReplace,
  1731. (unsigned char *)&data,
  1732. sizeof(data) / sizeof(data[0]));
  1733. respond.xselection.property = req->property;
  1734. } else {
  1735. char *targetname = XGetAtomName(x11_display, req->target);
  1736. printf("No Target '%s'\n", targetname);
  1737. if (targetname)
  1738. XFree(targetname);
  1739. respond.xselection.property = None;
  1740. }
  1741. respond.xselection.type = SelectionNotify;
  1742. respond.xselection.display = req->display;
  1743. respond.xselection.requestor = req->requestor;
  1744. respond.xselection.selection = req->selection;
  1745. respond.xselection.target = req->target;
  1746. respond.xselection.time = req->time;
  1747. XSendEvent(x11_display, req->requestor, True, NoEventMask, &respond);
  1748. XFlush(x11_display);
  1749. } break;
  1750. case SelectionNotify:
  1751. if (event.xselection.target == requested) {
  1752. Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0));
  1753. Vector<String> files = String((char *)p.data).split("\n", false);
  1754. for (int i = 0; i < files.size(); i++) {
  1755. files.write[i] = files[i].replace("file://", "").replace("%20", " ").strip_escapes();
  1756. }
  1757. main_loop->drop_files(files);
  1758. //Reply that all is well.
  1759. XClientMessageEvent m;
  1760. memset(&m, 0, sizeof(m));
  1761. m.type = ClientMessage;
  1762. m.display = x11_display;
  1763. m.window = xdnd_source_window;
  1764. m.message_type = xdnd_finished;
  1765. m.format = 32;
  1766. m.data.l[0] = x11_window;
  1767. m.data.l[1] = 1;
  1768. m.data.l[2] = xdnd_action_copy; //We only ever copy.
  1769. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
  1770. }
  1771. break;
  1772. case ClientMessage:
  1773. if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete)
  1774. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  1775. else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
  1776. //File(s) have been dragged over the window, check for supported target (text/uri-list)
  1777. xdnd_version = (event.xclient.data.l[1] >> 24);
  1778. Window source = event.xclient.data.l[0];
  1779. bool more_than_3 = event.xclient.data.l[1] & 1;
  1780. if (more_than_3) {
  1781. Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
  1782. requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
  1783. } else
  1784. requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
  1785. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
  1786. //xdnd position event, reply with an XDND status message
  1787. //just depending on type of data for now
  1788. XClientMessageEvent m;
  1789. memset(&m, 0, sizeof(m));
  1790. m.type = ClientMessage;
  1791. m.display = event.xclient.display;
  1792. m.window = event.xclient.data.l[0];
  1793. m.message_type = xdnd_status;
  1794. m.format = 32;
  1795. m.data.l[0] = x11_window;
  1796. m.data.l[1] = (requested != None);
  1797. m.data.l[2] = 0; //empty rectangle
  1798. m.data.l[3] = 0;
  1799. m.data.l[4] = xdnd_action_copy;
  1800. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  1801. XFlush(x11_display);
  1802. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
  1803. if (requested != None) {
  1804. xdnd_source_window = event.xclient.data.l[0];
  1805. if (xdnd_version >= 1)
  1806. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]);
  1807. else
  1808. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime);
  1809. } else {
  1810. //Reply that we're not interested.
  1811. XClientMessageEvent m;
  1812. memset(&m, 0, sizeof(m));
  1813. m.type = ClientMessage;
  1814. m.display = event.xclient.display;
  1815. m.window = event.xclient.data.l[0];
  1816. m.message_type = xdnd_finished;
  1817. m.format = 32;
  1818. m.data.l[0] = x11_window;
  1819. m.data.l[1] = 0;
  1820. m.data.l[2] = None; //Failed.
  1821. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  1822. }
  1823. }
  1824. break;
  1825. default:
  1826. break;
  1827. }
  1828. }
  1829. XFlush(x11_display);
  1830. if (do_mouse_warp) {
  1831. XWarpPointer(x11_display, None, x11_window,
  1832. 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2);
  1833. /*
  1834. Window root, child;
  1835. int root_x, root_y;
  1836. int win_x, win_y;
  1837. unsigned int mask;
  1838. XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );
  1839. printf("Root: %d,%d\n", root_x, root_y);
  1840. printf("Win: %d,%d\n", win_x, win_y);
  1841. */
  1842. }
  1843. }
  1844. MainLoop *OS_X11::get_main_loop() const {
  1845. return main_loop;
  1846. }
  1847. void OS_X11::delete_main_loop() {
  1848. if (main_loop)
  1849. memdelete(main_loop);
  1850. main_loop = NULL;
  1851. }
  1852. void OS_X11::set_main_loop(MainLoop *p_main_loop) {
  1853. main_loop = p_main_loop;
  1854. input->set_main_loop(p_main_loop);
  1855. }
  1856. bool OS_X11::can_draw() const {
  1857. return !minimized;
  1858. };
  1859. void OS_X11::set_clipboard(const String &p_text) {
  1860. OS::set_clipboard(p_text);
  1861. XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime);
  1862. XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime);
  1863. };
  1864. static String _get_clipboard_impl(Atom p_source, Window x11_window, ::Display *x11_display, String p_internal_clipboard, Atom target) {
  1865. String ret;
  1866. Atom type;
  1867. Atom selection = XA_PRIMARY;
  1868. int format, result;
  1869. unsigned long len, bytes_left, dummy;
  1870. unsigned char *data;
  1871. Window Sown = XGetSelectionOwner(x11_display, p_source);
  1872. if (Sown == x11_window) {
  1873. return p_internal_clipboard;
  1874. };
  1875. if (Sown != None) {
  1876. XConvertSelection(x11_display, p_source, target, selection,
  1877. x11_window, CurrentTime);
  1878. XFlush(x11_display);
  1879. while (true) {
  1880. XEvent event;
  1881. XNextEvent(x11_display, &event);
  1882. if (event.type == SelectionNotify && event.xselection.requestor == x11_window) {
  1883. break;
  1884. };
  1885. };
  1886. //
  1887. // Do not get any data, see how much data is there
  1888. //
  1889. XGetWindowProperty(x11_display, x11_window,
  1890. selection, // Tricky..
  1891. 0, 0, // offset - len
  1892. 0, // Delete 0==FALSE
  1893. AnyPropertyType, //flag
  1894. &type, // return type
  1895. &format, // return format
  1896. &len, &bytes_left, //that
  1897. &data);
  1898. // DATA is There
  1899. if (bytes_left > 0) {
  1900. result = XGetWindowProperty(x11_display, x11_window,
  1901. selection, 0, bytes_left, 0,
  1902. AnyPropertyType, &type, &format,
  1903. &len, &dummy, &data);
  1904. if (result == Success) {
  1905. ret.parse_utf8((const char *)data);
  1906. } else
  1907. printf("FAIL\n");
  1908. XFree(data);
  1909. }
  1910. }
  1911. return ret;
  1912. }
  1913. static String _get_clipboard(Atom p_source, Window x11_window, ::Display *x11_display, String p_internal_clipboard) {
  1914. String ret;
  1915. Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True);
  1916. if (utf8_atom != None) {
  1917. ret = _get_clipboard_impl(p_source, x11_window, x11_display, p_internal_clipboard, utf8_atom);
  1918. }
  1919. if (ret == "") {
  1920. ret = _get_clipboard_impl(p_source, x11_window, x11_display, p_internal_clipboard, XA_STRING);
  1921. }
  1922. return ret;
  1923. }
  1924. String OS_X11::get_clipboard() const {
  1925. String ret;
  1926. ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, x11_display, OS::get_clipboard());
  1927. if (ret == "") {
  1928. ret = _get_clipboard(XA_PRIMARY, x11_window, x11_display, OS::get_clipboard());
  1929. };
  1930. return ret;
  1931. }
  1932. String OS_X11::get_name() {
  1933. return "X11";
  1934. }
  1935. Error OS_X11::shell_open(String p_uri) {
  1936. Error ok;
  1937. List<String> args;
  1938. args.push_back(p_uri);
  1939. ok = execute("xdg-open", args, false);
  1940. if (ok == OK)
  1941. return OK;
  1942. ok = execute("gnome-open", args, false);
  1943. if (ok == OK)
  1944. return OK;
  1945. ok = execute("kde-open", args, false);
  1946. return ok;
  1947. }
  1948. bool OS_X11::_check_internal_feature_support(const String &p_feature) {
  1949. return p_feature == "pc" || p_feature == "s3tc" || p_feature == "bptc";
  1950. }
  1951. String OS_X11::get_config_path() const {
  1952. if (has_environment("XDG_CONFIG_HOME")) {
  1953. return get_environment("XDG_CONFIG_HOME");
  1954. } else if (has_environment("HOME")) {
  1955. return get_environment("HOME").plus_file(".config");
  1956. } else {
  1957. return ".";
  1958. }
  1959. }
  1960. String OS_X11::get_data_path() const {
  1961. if (has_environment("XDG_DATA_HOME")) {
  1962. return get_environment("XDG_DATA_HOME");
  1963. } else if (has_environment("HOME")) {
  1964. return get_environment("HOME").plus_file(".local/share");
  1965. } else {
  1966. return get_config_path();
  1967. }
  1968. }
  1969. String OS_X11::get_cache_path() const {
  1970. if (has_environment("XDG_CACHE_HOME")) {
  1971. return get_environment("XDG_CACHE_HOME");
  1972. } else if (has_environment("HOME")) {
  1973. return get_environment("HOME").plus_file(".cache");
  1974. } else {
  1975. return get_config_path();
  1976. }
  1977. }
  1978. String OS_X11::get_system_dir(SystemDir p_dir) const {
  1979. String xdgparam;
  1980. switch (p_dir) {
  1981. case SYSTEM_DIR_DESKTOP: {
  1982. xdgparam = "DESKTOP";
  1983. } break;
  1984. case SYSTEM_DIR_DCIM: {
  1985. xdgparam = "PICTURES";
  1986. } break;
  1987. case SYSTEM_DIR_DOCUMENTS: {
  1988. xdgparam = "DOCUMENTS";
  1989. } break;
  1990. case SYSTEM_DIR_DOWNLOADS: {
  1991. xdgparam = "DOWNLOAD";
  1992. } break;
  1993. case SYSTEM_DIR_MOVIES: {
  1994. xdgparam = "VIDEOS";
  1995. } break;
  1996. case SYSTEM_DIR_MUSIC: {
  1997. xdgparam = "MUSIC";
  1998. } break;
  1999. case SYSTEM_DIR_PICTURES: {
  2000. xdgparam = "PICTURES";
  2001. } break;
  2002. case SYSTEM_DIR_RINGTONES: {
  2003. xdgparam = "MUSIC";
  2004. } break;
  2005. }
  2006. String pipe;
  2007. List<String> arg;
  2008. arg.push_back(xdgparam);
  2009. Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe);
  2010. if (err != OK)
  2011. return ".";
  2012. return pipe.strip_edges();
  2013. }
  2014. void OS_X11::move_window_to_foreground() {
  2015. XEvent xev;
  2016. Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
  2017. memset(&xev, 0, sizeof(xev));
  2018. xev.type = ClientMessage;
  2019. xev.xclient.window = x11_window;
  2020. xev.xclient.message_type = net_active_window;
  2021. xev.xclient.format = 32;
  2022. xev.xclient.data.l[0] = 1;
  2023. xev.xclient.data.l[1] = CurrentTime;
  2024. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2025. XFlush(x11_display);
  2026. }
  2027. void OS_X11::set_cursor_shape(CursorShape p_shape) {
  2028. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2029. if (p_shape == current_cursor) {
  2030. return;
  2031. }
  2032. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2033. if (cursors[p_shape] != None) {
  2034. XDefineCursor(x11_display, x11_window, cursors[p_shape]);
  2035. } else if (cursors[CURSOR_ARROW] != None) {
  2036. XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]);
  2037. }
  2038. }
  2039. current_cursor = p_shape;
  2040. }
  2041. void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2042. if (p_cursor.is_valid()) {
  2043. Ref<Texture> texture = p_cursor;
  2044. Ref<AtlasTexture> atlas_texture = p_cursor;
  2045. Ref<Image> image;
  2046. Size2 texture_size;
  2047. Rect2 atlas_rect;
  2048. if (texture.is_valid()) {
  2049. image = texture->get_data();
  2050. }
  2051. if (!image.is_valid() && atlas_texture.is_valid()) {
  2052. texture = atlas_texture->get_atlas();
  2053. atlas_rect.size.width = texture->get_width();
  2054. atlas_rect.size.height = texture->get_height();
  2055. atlas_rect.position.x = atlas_texture->get_region().position.x;
  2056. atlas_rect.position.y = atlas_texture->get_region().position.y;
  2057. texture_size.width = atlas_texture->get_region().size.x;
  2058. texture_size.height = atlas_texture->get_region().size.y;
  2059. } else if (image.is_valid()) {
  2060. texture_size.width = texture->get_width();
  2061. texture_size.height = texture->get_height();
  2062. }
  2063. ERR_FAIL_COND(!texture.is_valid());
  2064. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  2065. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  2066. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  2067. image = texture->get_data();
  2068. ERR_FAIL_COND(!image.is_valid());
  2069. // Create the cursor structure
  2070. XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
  2071. XcursorUInt image_size = texture_size.width * texture_size.height;
  2072. XcursorDim size = sizeof(XcursorPixel) * image_size;
  2073. cursor_image->version = 1;
  2074. cursor_image->size = size;
  2075. cursor_image->xhot = p_hotspot.x;
  2076. cursor_image->yhot = p_hotspot.y;
  2077. // allocate memory to contain the whole file
  2078. cursor_image->pixels = (XcursorPixel *)memalloc(size);
  2079. image->lock();
  2080. for (XcursorPixel index = 0; index < image_size; index++) {
  2081. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  2082. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  2083. if (atlas_texture.is_valid()) {
  2084. column_index = MIN(column_index, atlas_rect.size.width - 1);
  2085. row_index = MIN(row_index, atlas_rect.size.height - 1);
  2086. }
  2087. *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
  2088. }
  2089. image->unlock();
  2090. ERR_FAIL_COND(cursor_image->pixels == NULL);
  2091. // Save it for a further usage
  2092. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
  2093. if (p_shape == current_cursor) {
  2094. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2095. XDefineCursor(x11_display, x11_window, cursors[p_shape]);
  2096. }
  2097. }
  2098. memfree(cursor_image->pixels);
  2099. XcursorImageDestroy(cursor_image);
  2100. } else {
  2101. // Reset to default system cursor
  2102. if (img[p_shape]) {
  2103. cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]);
  2104. }
  2105. CursorShape c = current_cursor;
  2106. current_cursor = CURSOR_MAX;
  2107. set_cursor_shape(c);
  2108. }
  2109. }
  2110. void OS_X11::release_rendering_thread() {
  2111. #if defined(OPENGL_ENABLED)
  2112. context_gl->release_current();
  2113. #endif
  2114. }
  2115. void OS_X11::make_rendering_thread() {
  2116. #if defined(OPENGL_ENABLED)
  2117. context_gl->make_current();
  2118. #endif
  2119. }
  2120. void OS_X11::swap_buffers() {
  2121. #if defined(OPENGL_ENABLED)
  2122. context_gl->swap_buffers();
  2123. #endif
  2124. }
  2125. void OS_X11::alert(const String &p_alert, const String &p_title) {
  2126. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  2127. String path = get_environment("PATH");
  2128. Vector<String> path_elems = path.split(":", false);
  2129. String program;
  2130. for (int i = 0; i < path_elems.size(); i++) {
  2131. for (unsigned int k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  2132. String tested_path = path_elems[i] + "/" + message_programs[k];
  2133. if (FileAccess::exists(tested_path)) {
  2134. program = tested_path;
  2135. break;
  2136. }
  2137. }
  2138. if (program.length())
  2139. break;
  2140. }
  2141. List<String> args;
  2142. if (program.ends_with("zenity")) {
  2143. args.push_back("--error");
  2144. args.push_back("--width");
  2145. args.push_back("500");
  2146. args.push_back("--title");
  2147. args.push_back(p_title);
  2148. args.push_back("--text");
  2149. args.push_back(p_alert);
  2150. }
  2151. if (program.ends_with("kdialog")) {
  2152. args.push_back("--error");
  2153. args.push_back(p_alert);
  2154. args.push_back("--title");
  2155. args.push_back(p_title);
  2156. }
  2157. if (program.ends_with("Xdialog")) {
  2158. args.push_back("--title");
  2159. args.push_back(p_title);
  2160. args.push_back("--msgbox");
  2161. args.push_back(p_alert);
  2162. args.push_back("0");
  2163. args.push_back("0");
  2164. }
  2165. if (program.ends_with("xmessage")) {
  2166. args.push_back("-center");
  2167. args.push_back("-title");
  2168. args.push_back(p_title);
  2169. args.push_back(p_alert);
  2170. }
  2171. if (program.length()) {
  2172. execute(program, args, true);
  2173. } else {
  2174. print_line(p_alert);
  2175. }
  2176. return;
  2177. }
  2178. bool g_set_icon_error = false;
  2179. int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
  2180. g_set_icon_error = true;
  2181. return 0;
  2182. }
  2183. void OS_X11::set_icon(const Ref<Image> &p_icon) {
  2184. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
  2185. Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
  2186. if (p_icon.is_valid()) {
  2187. Ref<Image> img = p_icon->duplicate();
  2188. img->convert(Image::FORMAT_RGBA8);
  2189. while (true) {
  2190. int w = img->get_width();
  2191. int h = img->get_height();
  2192. if (g_set_icon_error) {
  2193. g_set_icon_error = false;
  2194. WARN_PRINT("Icon too large, attempting to resize icon.");
  2195. int new_width, new_height;
  2196. if (w > h) {
  2197. new_width = w / 2;
  2198. new_height = h * new_width / w;
  2199. } else {
  2200. new_height = h / 2;
  2201. new_width = w * new_height / h;
  2202. }
  2203. w = new_width;
  2204. h = new_height;
  2205. if (!w || !h) {
  2206. WARN_PRINT("Unable to set icon.");
  2207. break;
  2208. }
  2209. img->resize(w, h, Image::INTERPOLATE_CUBIC);
  2210. }
  2211. // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
  2212. Vector<long> pd;
  2213. pd.resize(2 + w * h);
  2214. pd.write[0] = w;
  2215. pd.write[1] = h;
  2216. PoolVector<uint8_t>::Read r = img->get_data().read();
  2217. long *wr = &pd.write[2];
  2218. uint8_t const *pr = r.ptr();
  2219. for (int i = 0; i < w * h; i++) {
  2220. long v = 0;
  2221. // A R G B
  2222. v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
  2223. *wr++ = v;
  2224. pr += 4;
  2225. }
  2226. XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
  2227. if (!g_set_icon_error)
  2228. break;
  2229. }
  2230. } else {
  2231. XDeleteProperty(x11_display, x11_window, net_wm_icon);
  2232. }
  2233. XFlush(x11_display);
  2234. XSetErrorHandler(oldHandler);
  2235. }
  2236. void OS_X11::force_process_input() {
  2237. process_xevents(); // get rid of pending events
  2238. #ifdef JOYDEV_ENABLED
  2239. joypad->process_joypads();
  2240. #endif
  2241. }
  2242. void OS_X11::run() {
  2243. force_quit = false;
  2244. if (!main_loop)
  2245. return;
  2246. main_loop->init();
  2247. //uint64_t last_ticks=get_ticks_usec();
  2248. //int frames=0;
  2249. //uint64_t frame=0;
  2250. while (!force_quit) {
  2251. process_xevents(); // get rid of pending events
  2252. #ifdef JOYDEV_ENABLED
  2253. joypad->process_joypads();
  2254. #endif
  2255. if (Main::iteration())
  2256. break;
  2257. };
  2258. main_loop->finish();
  2259. }
  2260. bool OS_X11::is_joy_known(int p_device) {
  2261. return input->is_joy_mapped(p_device);
  2262. }
  2263. String OS_X11::get_joy_guid(int p_device) const {
  2264. return input->get_joy_guid_remapped(p_device);
  2265. }
  2266. void OS_X11::_set_use_vsync(bool p_enable) {
  2267. #if defined(OPENGL_ENABLED)
  2268. if (context_gl)
  2269. context_gl->set_use_vsync(p_enable);
  2270. #endif
  2271. }
  2272. /*
  2273. bool OS_X11::is_vsync_enabled() const {
  2274. if (context_gl)
  2275. return context_gl->is_using_vsync();
  2276. return true;
  2277. }
  2278. */
  2279. void OS_X11::set_context(int p_context) {
  2280. XClassHint *classHint = XAllocClassHint();
  2281. if (classHint) {
  2282. if (p_context == CONTEXT_EDITOR)
  2283. classHint->res_name = (char *)"Godot_Editor";
  2284. if (p_context == CONTEXT_PROJECTMAN)
  2285. classHint->res_name = (char *)"Godot_ProjectList";
  2286. classHint->res_class = (char *)"Godot";
  2287. XSetClassHint(x11_display, x11_window, classHint);
  2288. XFree(classHint);
  2289. }
  2290. }
  2291. OS::PowerState OS_X11::get_power_state() {
  2292. return power_manager->get_power_state();
  2293. }
  2294. int OS_X11::get_power_seconds_left() {
  2295. return power_manager->get_power_seconds_left();
  2296. }
  2297. int OS_X11::get_power_percent_left() {
  2298. return power_manager->get_power_percent_left();
  2299. }
  2300. void OS_X11::disable_crash_handler() {
  2301. crash_handler.disable();
  2302. }
  2303. bool OS_X11::is_disable_crash_handler() const {
  2304. return crash_handler.is_disabled();
  2305. }
  2306. static String get_mountpoint(const String &p_path) {
  2307. struct stat s;
  2308. if (stat(p_path.utf8().get_data(), &s)) {
  2309. return "";
  2310. }
  2311. #ifdef HAVE_MNTENT
  2312. dev_t dev = s.st_dev;
  2313. FILE *fd = setmntent("/proc/mounts", "r");
  2314. if (!fd) {
  2315. return "";
  2316. }
  2317. struct mntent mnt;
  2318. char buf[1024];
  2319. size_t buflen = 1024;
  2320. while (getmntent_r(fd, &mnt, buf, buflen)) {
  2321. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  2322. endmntent(fd);
  2323. return String(mnt.mnt_dir);
  2324. }
  2325. }
  2326. endmntent(fd);
  2327. #endif
  2328. return "";
  2329. }
  2330. Error OS_X11::move_to_trash(const String &p_path) {
  2331. String trash_can = "";
  2332. String mnt = get_mountpoint(p_path);
  2333. // If there is a directory "[Mountpoint]/.Trash-[UID]/files", use it as the trash can.
  2334. if (mnt != "") {
  2335. String path(mnt + "/.Trash-" + itos(getuid()) + "/files");
  2336. struct stat s;
  2337. if (!stat(path.utf8().get_data(), &s)) {
  2338. trash_can = path;
  2339. }
  2340. }
  2341. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash/files" as the trash can.
  2342. if (trash_can == "") {
  2343. char *dhome = getenv("XDG_DATA_HOME");
  2344. if (dhome) {
  2345. trash_can = String(dhome) + "/Trash/files";
  2346. }
  2347. }
  2348. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash/files" as the trash can.
  2349. if (trash_can == "") {
  2350. char *home = getenv("HOME");
  2351. if (home) {
  2352. trash_can = String(home) + "/.local/share/Trash/files";
  2353. }
  2354. }
  2355. // Issue an error if none of the previous locations is appropriate for the trash can.
  2356. if (trash_can == "") {
  2357. ERR_PRINTS("move_to_trash: Could not determine the trash can location");
  2358. return FAILED;
  2359. }
  2360. // Create needed directories for decided trash can location.
  2361. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  2362. Error err = dir_access->make_dir_recursive(trash_can);
  2363. memdelete(dir_access);
  2364. // Issue an error if trash can is not created proprely.
  2365. if (err != OK) {
  2366. ERR_PRINTS("move_to_trash: Could not create the trash can \"" + trash_can + "\"");
  2367. return err;
  2368. }
  2369. // The trash can is successfully created, now move the given resource to it.
  2370. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  2371. List<String> mv_args;
  2372. mv_args.push_back(p_path);
  2373. mv_args.push_back(trash_can);
  2374. int retval;
  2375. err = execute("mv", mv_args, true, NULL, NULL, &retval);
  2376. // Issue an error if "mv" failed to move the given resource to the trash can.
  2377. if (err != OK || retval != 0) {
  2378. ERR_PRINTS("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_can + "\"");
  2379. return FAILED;
  2380. }
  2381. return OK;
  2382. }
  2383. OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const {
  2384. XkbDescRec *xkbdesc = XkbAllocKeyboard();
  2385. ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY);
  2386. XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc);
  2387. ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY);
  2388. ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY);
  2389. char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols);
  2390. ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY);
  2391. Vector<String> info = String(layout).split("+");
  2392. ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY);
  2393. if (info[1].find("colemak") != -1) {
  2394. return LATIN_KEYBOARD_COLEMAK;
  2395. } else if (info[1].find("qwertz") != -1) {
  2396. return LATIN_KEYBOARD_QWERTZ;
  2397. } else if (info[1].find("azerty") != -1) {
  2398. return LATIN_KEYBOARD_AZERTY;
  2399. } else if (info[1].find("qzerty") != -1) {
  2400. return LATIN_KEYBOARD_QZERTY;
  2401. } else if (info[1].find("dvorak") != -1) {
  2402. return LATIN_KEYBOARD_DVORAK;
  2403. } else if (info[1].find("neo") != -1) {
  2404. return LATIN_KEYBOARD_NEO;
  2405. }
  2406. return LATIN_KEYBOARD_QWERTY;
  2407. }
  2408. void OS_X11::update_real_mouse_position() {
  2409. Window root_return, child_return;
  2410. int root_x, root_y, win_x, win_y;
  2411. unsigned int mask_return;
  2412. Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y,
  2413. &win_x, &win_y, &mask_return);
  2414. if (xquerypointer_result) {
  2415. if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) {
  2416. last_mouse_pos.x = win_x;
  2417. last_mouse_pos.y = win_y;
  2418. last_mouse_pos_valid = true;
  2419. input->set_mouse_position(last_mouse_pos);
  2420. }
  2421. }
  2422. }
  2423. OS_X11::OS_X11() {
  2424. #ifdef PULSEAUDIO_ENABLED
  2425. AudioDriverManager::add_driver(&driver_pulseaudio);
  2426. #endif
  2427. #ifdef ALSA_ENABLED
  2428. AudioDriverManager::add_driver(&driver_alsa);
  2429. #endif
  2430. layered_window = false;
  2431. minimized = false;
  2432. xim_style = 0L;
  2433. mouse_mode = MOUSE_MODE_VISIBLE;
  2434. }