os_x11.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993
  1. /*************************************************************************/
  2. /* os_x11.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "detect_prime.h"
  34. #include "drivers/gles2/rasterizer_gles2.h"
  35. #include "drivers/gles3/rasterizer_gles3.h"
  36. #include "key_mapping_x11.h"
  37. #include "main/main.h"
  38. #include "servers/visual/visual_server_raster.h"
  39. #include "servers/visual/visual_server_wrap_mt.h"
  40. #ifdef HAVE_MNTENT
  41. #include <mntent.h>
  42. #endif
  43. #include <errno.h>
  44. #include <limits.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <X11/Xatom.h>
  49. #include <X11/Xutil.h>
  50. #include <X11/extensions/Xinerama.h>
  51. #include <X11/extensions/shape.h>
  52. // ICCCM
  53. #define WM_NormalState 1L // window normal state
  54. #define WM_IconicState 3L // window minimized
  55. // EWMH
  56. #define _NET_WM_STATE_REMOVE 0L // remove/unset property
  57. #define _NET_WM_STATE_ADD 1L // add/set property
  58. #define _NET_WM_STATE_TOGGLE 2L // toggle property
  59. #include <dlfcn.h>
  60. #include <fcntl.h>
  61. #include <sys/stat.h>
  62. #include <sys/types.h>
  63. #include <unistd.h>
  64. //stupid linux.h
  65. #ifdef KEY_TAB
  66. #undef KEY_TAB
  67. #endif
  68. #undef CursorShape
  69. #include <X11/XKBlib.h>
  70. // 2.2 is the first release with multitouch
  71. #define XINPUT_CLIENT_VERSION_MAJOR 2
  72. #define XINPUT_CLIENT_VERSION_MINOR 2
  73. #define VALUATOR_ABSX 0
  74. #define VALUATOR_ABSY 1
  75. #define VALUATOR_PRESSURE 2
  76. #define VALUATOR_TILTX 3
  77. #define VALUATOR_TILTY 4
  78. static const double abs_resolution_mult = 10000.0;
  79. static const double abs_resolution_range_mult = 10.0;
  80. void OS_X11::initialize_core() {
  81. crash_handler.initialize();
  82. OS_Unix::initialize_core();
  83. }
  84. int OS_X11::get_current_video_driver() const {
  85. return video_driver_index;
  86. }
  87. Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  88. long im_event_mask = 0;
  89. last_button_state = 0;
  90. xmbstring = NULL;
  91. x11_window = 0;
  92. last_click_ms = 0;
  93. last_click_button_index = -1;
  94. last_click_pos = Point2(-100, -100);
  95. args = OS::get_singleton()->get_cmdline_args();
  96. current_videomode = p_desired;
  97. main_loop = NULL;
  98. last_timestamp = 0;
  99. last_mouse_pos_valid = false;
  100. last_keyrelease_time = 0;
  101. xdnd_version = 0;
  102. XInitThreads();
  103. /** XLIB INITIALIZATION **/
  104. x11_display = XOpenDisplay(NULL);
  105. if (!x11_display) {
  106. ERR_PRINT("X11 Display is not available");
  107. return ERR_UNAVAILABLE;
  108. }
  109. char *modifiers = NULL;
  110. Bool xkb_dar = False;
  111. XAutoRepeatOn(x11_display);
  112. xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, NULL);
  113. // Try to support IME if detectable auto-repeat is supported
  114. if (xkb_dar == True) {
  115. #ifdef X_HAVE_UTF8_STRING
  116. // Xutf8LookupString will be used later instead of XmbLookupString before
  117. // the multibyte sequences can be converted to unicode string.
  118. modifiers = XSetLocaleModifiers("");
  119. #endif
  120. }
  121. if (modifiers == NULL) {
  122. if (is_stdout_verbose()) {
  123. WARN_PRINT("IME is disabled");
  124. }
  125. XSetLocaleModifiers("@im=none");
  126. WARN_PRINT("Error setting locale modifiers");
  127. }
  128. const char *err;
  129. xrr_get_monitors = NULL;
  130. xrr_free_monitors = NULL;
  131. int xrandr_major = 0;
  132. int xrandr_minor = 0;
  133. int event_base, error_base;
  134. xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
  135. xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
  136. if (!xrandr_handle) {
  137. err = dlerror();
  138. // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2...
  139. // In case this happens for other X11 platforms in the future, let's give it a try too before failing.
  140. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY);
  141. if (!xrandr_handle) {
  142. fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
  143. }
  144. } else {
  145. XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
  146. if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
  147. xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
  148. if (!xrr_get_monitors) {
  149. err = dlerror();
  150. fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
  151. } else {
  152. xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
  153. if (!xrr_free_monitors) {
  154. err = dlerror();
  155. fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
  156. xrr_get_monitors = NULL;
  157. }
  158. }
  159. }
  160. }
  161. if (!refresh_device_info()) {
  162. OS::get_singleton()->alert("Your system does not support XInput 2.\n"
  163. "Please upgrade your distribution.",
  164. "Unable to initialize XInput");
  165. return ERR_UNAVAILABLE;
  166. }
  167. xim = XOpenIM(x11_display, NULL, NULL, NULL);
  168. if (xim == NULL) {
  169. WARN_PRINT("XOpenIM failed");
  170. xim_style = 0L;
  171. } else {
  172. ::XIMCallback im_destroy_callback;
  173. im_destroy_callback.client_data = (::XPointer)(this);
  174. im_destroy_callback.callback = (::XIMProc)(xim_destroy_callback);
  175. if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
  176. NULL) != NULL) {
  177. WARN_PRINT("Error setting XIM destroy callback");
  178. }
  179. ::XIMStyles *xim_styles = NULL;
  180. xim_style = 0L;
  181. char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
  182. if (imvalret != NULL || xim_styles == NULL) {
  183. fprintf(stderr, "Input method doesn't support any styles\n");
  184. }
  185. if (xim_styles) {
  186. xim_style = 0L;
  187. for (int i = 0; i < xim_styles->count_styles; i++) {
  188. if (xim_styles->supported_styles[i] ==
  189. (XIMPreeditNothing | XIMStatusNothing)) {
  190. xim_style = xim_styles->supported_styles[i];
  191. break;
  192. }
  193. }
  194. XFree(xim_styles);
  195. }
  196. XFree(imvalret);
  197. }
  198. /*
  199. char* windowid = getenv("GODOT_WINDOWID");
  200. if (windowid) {
  201. //freopen("/home/punto/stdout", "w", stdout);
  202. //reopen("/home/punto/stderr", "w", stderr);
  203. x11_window = atol(windowid);
  204. XWindowAttributes xwa;
  205. XGetWindowAttributes(x11_display,x11_window,&xwa);
  206. current_videomode.width = xwa.width;
  207. current_videomode.height = xwa.height;
  208. };
  209. */
  210. // maybe contextgl wants to be in charge of creating the window
  211. #if defined(OPENGL_ENABLED)
  212. if (getenv("DRI_PRIME") == NULL) {
  213. int use_prime = -1;
  214. if (getenv("PRIMUS_DISPLAY") ||
  215. getenv("PRIMUS_libGLd") ||
  216. getenv("PRIMUS_libGLa") ||
  217. getenv("PRIMUS_libGL") ||
  218. getenv("PRIMUS_LOAD_GLOBAL") ||
  219. getenv("BUMBLEBEE_SOCKET")) {
  220. print_verbose("Optirun/primusrun detected. Skipping GPU detection");
  221. use_prime = 0;
  222. }
  223. // Some tools use fake libGL libraries and have them override the real one using
  224. // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its
  225. // runtime and includes system `/lib` and `/lib64`... so ignore Steam.
  226. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) {
  227. String ld_library_path(getenv("LD_LIBRARY_PATH"));
  228. Vector<String> libraries = ld_library_path.split(":");
  229. for (int i = 0; i < libraries.size(); ++i) {
  230. if (FileAccess::exists(libraries[i] + "/libGL.so.1") ||
  231. FileAccess::exists(libraries[i] + "/libGL.so")) {
  232. print_verbose("Custom libGL override detected. Skipping GPU detection");
  233. use_prime = 0;
  234. }
  235. }
  236. }
  237. if (use_prime == -1) {
  238. print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic.");
  239. use_prime = detect_prime();
  240. }
  241. if (use_prime) {
  242. print_line("Found discrete GPU, setting DRI_PRIME=1 to use it.");
  243. print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU.");
  244. setenv("DRI_PRIME", "1", 1);
  245. }
  246. }
  247. ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE;
  248. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  249. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  250. }
  251. bool editor = Engine::get_singleton()->is_editor_hint();
  252. bool gl_initialization_error = false;
  253. context_gl = NULL;
  254. while (!context_gl) {
  255. context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type));
  256. if (context_gl->initialize() != OK) {
  257. memdelete(context_gl);
  258. context_gl = NULL;
  259. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  260. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  261. gl_initialization_error = true;
  262. break;
  263. }
  264. p_video_driver = VIDEO_DRIVER_GLES2;
  265. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  266. } else {
  267. gl_initialization_error = true;
  268. break;
  269. }
  270. }
  271. }
  272. while (true) {
  273. if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) {
  274. if (RasterizerGLES3::is_viable() == OK) {
  275. RasterizerGLES3::register_config();
  276. RasterizerGLES3::make_current();
  277. break;
  278. } else {
  279. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  280. p_video_driver = VIDEO_DRIVER_GLES2;
  281. opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE;
  282. continue;
  283. } else {
  284. gl_initialization_error = true;
  285. break;
  286. }
  287. }
  288. }
  289. if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) {
  290. if (RasterizerGLES2::is_viable() == OK) {
  291. RasterizerGLES2::register_config();
  292. RasterizerGLES2::make_current();
  293. break;
  294. } else {
  295. gl_initialization_error = true;
  296. break;
  297. }
  298. }
  299. }
  300. if (gl_initialization_error) {
  301. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  302. "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n"
  303. "Alternatively, you can force software rendering by running Godot with the `LIBGL_ALWAYS_SOFTWARE=1`\n"
  304. "environment variable set, but this will be very slow.",
  305. "Unable to initialize Video driver");
  306. return ERR_UNAVAILABLE;
  307. }
  308. video_driver_index = p_video_driver;
  309. context_gl->set_use_vsync(current_videomode.use_vsync);
  310. #endif
  311. visual_server = memnew(VisualServerRaster);
  312. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  313. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  314. }
  315. if (current_videomode.maximized) {
  316. current_videomode.maximized = false;
  317. set_window_maximized(true);
  318. // borderless fullscreen window mode
  319. } else if (current_videomode.fullscreen) {
  320. current_videomode.fullscreen = false;
  321. set_window_fullscreen(true);
  322. } else if (current_videomode.borderless_window) {
  323. Hints hints;
  324. Atom property;
  325. hints.flags = 2;
  326. hints.decorations = 0;
  327. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  328. if (property != None) {
  329. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  330. }
  331. }
  332. // make PID known to X11
  333. {
  334. const long pid = this->get_process_id();
  335. Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False);
  336. if (net_wm_pid != None) {
  337. XChangeProperty(x11_display, x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
  338. }
  339. }
  340. // disable resizable window
  341. if (!current_videomode.resizable && !current_videomode.fullscreen) {
  342. XSizeHints *xsh;
  343. xsh = XAllocSizeHints();
  344. xsh->flags = PMinSize | PMaxSize;
  345. XWindowAttributes xwa;
  346. if (current_videomode.fullscreen) {
  347. XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
  348. } else {
  349. XGetWindowAttributes(x11_display, x11_window, &xwa);
  350. }
  351. xsh->min_width = xwa.width;
  352. xsh->max_width = xwa.width;
  353. xsh->min_height = xwa.height;
  354. xsh->max_height = xwa.height;
  355. XSetWMNormalHints(x11_display, x11_window, xsh);
  356. XFree(xsh);
  357. }
  358. if (current_videomode.always_on_top) {
  359. current_videomode.always_on_top = false;
  360. set_window_always_on_top(true);
  361. }
  362. ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE);
  363. ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE);
  364. XSetWindowAttributes new_attr;
  365. new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
  366. ButtonReleaseMask | EnterWindowMask |
  367. LeaveWindowMask | PointerMotionMask |
  368. Button1MotionMask |
  369. Button2MotionMask | Button3MotionMask |
  370. Button4MotionMask | Button5MotionMask |
  371. ButtonMotionMask | KeymapStateMask |
  372. ExposureMask | VisibilityChangeMask |
  373. StructureNotifyMask |
  374. SubstructureNotifyMask | SubstructureRedirectMask |
  375. FocusChangeMask | PropertyChangeMask |
  376. ColormapChangeMask | OwnerGrabButtonMask |
  377. im_event_mask;
  378. XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr);
  379. static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  380. static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  381. xi.all_event_mask.deviceid = XIAllDevices;
  382. xi.all_event_mask.mask_len = sizeof(all_mask_data);
  383. xi.all_event_mask.mask = all_mask_data;
  384. xi.all_master_event_mask.deviceid = XIAllMasterDevices;
  385. xi.all_master_event_mask.mask_len = sizeof(all_master_mask_data);
  386. xi.all_master_event_mask.mask = all_master_mask_data;
  387. XISetMask(xi.all_event_mask.mask, XI_HierarchyChanged);
  388. XISetMask(xi.all_master_event_mask.mask, XI_DeviceChanged);
  389. XISetMask(xi.all_master_event_mask.mask, XI_RawMotion);
  390. #ifdef TOUCH_ENABLED
  391. if (xi.touch_devices.size()) {
  392. XISetMask(xi.all_event_mask.mask, XI_TouchBegin);
  393. XISetMask(xi.all_event_mask.mask, XI_TouchUpdate);
  394. XISetMask(xi.all_event_mask.mask, XI_TouchEnd);
  395. XISetMask(xi.all_event_mask.mask, XI_TouchOwnership);
  396. }
  397. #endif
  398. XISelectEvents(x11_display, x11_window, &xi.all_event_mask, 1);
  399. XISelectEvents(x11_display, DefaultRootWindow(x11_display), &xi.all_master_event_mask, 1);
  400. // Disabled by now since grabbing also blocks mouse events
  401. // (they are received as extended events instead of standard events)
  402. /*XIClearMask(xi.touch_event_mask.mask, XI_TouchOwnership);
  403. // Grab touch devices to avoid OS gesture interference
  404. for (int i = 0; i < xi.touch_devices.size(); ++i) {
  405. XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask);
  406. }*/
  407. /* set the titlebar name */
  408. XStoreName(x11_display, x11_window, "Godot");
  409. wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
  410. XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);
  411. im_active = false;
  412. im_position = Vector2();
  413. if (xim && xim_style) {
  414. xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)NULL);
  415. if (XGetICValues(xic, XNFilterEvents, &im_event_mask, NULL) != NULL) {
  416. WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
  417. XDestroyIC(xic);
  418. xic = NULL;
  419. }
  420. if (xic) {
  421. XUnsetICFocus(xic);
  422. } else {
  423. WARN_PRINT("XCreateIC couldn't create xic");
  424. }
  425. } else {
  426. xic = NULL;
  427. WARN_PRINT("XCreateIC couldn't create xic");
  428. }
  429. cursor_size = XcursorGetDefaultSize(x11_display);
  430. cursor_theme = XcursorGetTheme(x11_display);
  431. if (!cursor_theme) {
  432. print_verbose("XcursorGetTheme could not get cursor theme");
  433. cursor_theme = "default";
  434. }
  435. for (int i = 0; i < CURSOR_MAX; i++) {
  436. cursors[i] = None;
  437. img[i] = NULL;
  438. }
  439. current_cursor = CURSOR_ARROW;
  440. for (int i = 0; i < CURSOR_MAX; i++) {
  441. static const char *cursor_file[] = {
  442. "left_ptr",
  443. "xterm",
  444. "hand2",
  445. "cross",
  446. "watch",
  447. "left_ptr_watch",
  448. "fleur",
  449. "hand1",
  450. "X_cursor",
  451. "sb_v_double_arrow",
  452. "sb_h_double_arrow",
  453. "size_bdiag",
  454. "size_fdiag",
  455. "hand1",
  456. "sb_v_double_arrow",
  457. "sb_h_double_arrow",
  458. "question_arrow"
  459. };
  460. img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
  461. if (img[i]) {
  462. cursors[i] = XcursorImageLoadCursor(x11_display, img[i]);
  463. } else {
  464. print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
  465. }
  466. }
  467. {
  468. // Creating an empty/transparent cursor
  469. // Create 1x1 bitmap
  470. Pixmap cursormask = XCreatePixmap(x11_display,
  471. RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
  472. // Fill with zero
  473. XGCValues xgc;
  474. xgc.function = GXclear;
  475. GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
  476. XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
  477. // Color value doesn't matter. Mask zero means no foreground or background will be drawn
  478. XColor col = {};
  479. Cursor cursor = XCreatePixmapCursor(x11_display,
  480. cursormask, // source (using cursor mask as placeholder, since it'll all be ignored)
  481. cursormask, // mask
  482. &col, &col, 0, 0);
  483. XFreePixmap(x11_display, cursormask);
  484. XFreeGC(x11_display, gc);
  485. if (cursor == None) {
  486. ERR_PRINT("FAILED CREATING CURSOR");
  487. }
  488. null_cursor = cursor;
  489. }
  490. set_cursor_shape(CURSOR_BUSY);
  491. //Set Xdnd (drag & drop) support
  492. Atom XdndAware = XInternAtom(x11_display, "XdndAware", False);
  493. Atom version = 5;
  494. if (XdndAware != None) {
  495. XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1);
  496. }
  497. xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
  498. xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
  499. xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
  500. xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
  501. xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
  502. xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
  503. xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
  504. requested = None;
  505. visual_server->init();
  506. AudioDriverManager::initialize(p_audio_driver);
  507. input = memnew(InputDefault);
  508. window_has_focus = true; // Set focus to true at init
  509. #ifdef JOYDEV_ENABLED
  510. joypad = memnew(JoypadLinux(input));
  511. #endif
  512. power_manager = memnew(PowerX11);
  513. if (p_desired.layered) {
  514. set_window_per_pixel_transparency_enabled(true);
  515. }
  516. XEvent xevent;
  517. while (XPending(x11_display) > 0) {
  518. XNextEvent(x11_display, &xevent);
  519. if (xevent.type == ConfigureNotify) {
  520. _window_changed(&xevent);
  521. }
  522. }
  523. events_thread.start(_poll_events_thread, this);
  524. update_real_mouse_position();
  525. return OK;
  526. }
  527. bool OS_X11::refresh_device_info() {
  528. int event_base, error_base;
  529. print_verbose("XInput: Refreshing devices.");
  530. if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) {
  531. print_verbose("XInput extension not available. Please upgrade your distribution.");
  532. return false;
  533. }
  534. int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR;
  535. int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR;
  536. if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) {
  537. print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query));
  538. xi.opcode = 0;
  539. return false;
  540. }
  541. if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) {
  542. print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.",
  543. XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query));
  544. }
  545. xi.absolute_devices.clear();
  546. xi.touch_devices.clear();
  547. int dev_count;
  548. XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count);
  549. for (int i = 0; i < dev_count; i++) {
  550. XIDeviceInfo *dev = &info[i];
  551. if (!dev->enabled)
  552. continue;
  553. if (!(dev->use == XIMasterPointer || dev->use == XIFloatingSlave))
  554. continue;
  555. bool direct_touch = false;
  556. bool absolute_mode = false;
  557. int resolution_x = 0;
  558. int resolution_y = 0;
  559. double abs_x_min = 0;
  560. double abs_x_max = 0;
  561. double abs_y_min = 0;
  562. double abs_y_max = 0;
  563. double pressure_min = 0;
  564. double pressure_max = 0;
  565. double tilt_x_min = 0;
  566. double tilt_x_max = 0;
  567. double tilt_y_min = 0;
  568. double tilt_y_max = 0;
  569. for (int j = 0; j < dev->num_classes; j++) {
  570. #ifdef TOUCH_ENABLED
  571. if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) {
  572. direct_touch = true;
  573. }
  574. #endif
  575. if (dev->classes[j]->type == XIValuatorClass) {
  576. XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j];
  577. if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) {
  578. resolution_x = class_info->resolution;
  579. abs_x_min = class_info->min;
  580. abs_y_max = class_info->max;
  581. absolute_mode = true;
  582. } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) {
  583. resolution_y = class_info->resolution;
  584. abs_y_min = class_info->min;
  585. abs_y_max = class_info->max;
  586. absolute_mode = true;
  587. } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) {
  588. pressure_min = class_info->min;
  589. pressure_max = class_info->max;
  590. } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) {
  591. tilt_x_min = class_info->min;
  592. tilt_x_max = class_info->max;
  593. } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) {
  594. tilt_x_min = class_info->min;
  595. tilt_x_max = class_info->max;
  596. }
  597. }
  598. }
  599. if (direct_touch) {
  600. xi.touch_devices.push_back(dev->deviceid);
  601. print_verbose("XInput: Using touch device: " + String(dev->name));
  602. }
  603. if (absolute_mode) {
  604. // If no resolution was reported, use the min/max ranges.
  605. if (resolution_x <= 0) {
  606. resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult;
  607. }
  608. if (resolution_y <= 0) {
  609. resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult;
  610. }
  611. xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y);
  612. print_verbose("XInput: Absolute pointing device: " + String(dev->name));
  613. }
  614. xi.pressure = 0;
  615. xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max);
  616. xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max);
  617. xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max);
  618. }
  619. XIFreeDeviceInfo(info);
  620. #ifdef TOUCH_ENABLED
  621. if (!xi.touch_devices.size()) {
  622. print_verbose("XInput: No touch devices found.");
  623. }
  624. #endif
  625. return true;
  626. }
  627. void OS_X11::xim_destroy_callback(::XIM im, ::XPointer client_data,
  628. ::XPointer call_data) {
  629. WARN_PRINT("Input method stopped");
  630. OS_X11 *os = reinterpret_cast<OS_X11 *>(client_data);
  631. os->xim = NULL;
  632. os->xic = NULL;
  633. }
  634. void OS_X11::set_ime_active(const bool p_active) {
  635. im_active = p_active;
  636. if (!xic) {
  637. return;
  638. }
  639. // Block events polling while changing input focus
  640. // because it triggers some event polling internally.
  641. if (p_active) {
  642. {
  643. MutexLock mutex_lock(events_mutex);
  644. XSetICFocus(xic);
  645. }
  646. set_ime_position(im_position);
  647. } else {
  648. MutexLock mutex_lock(events_mutex);
  649. XUnsetICFocus(xic);
  650. }
  651. }
  652. void OS_X11::set_ime_position(const Point2 &p_pos) {
  653. im_position = p_pos;
  654. if (!xic)
  655. return;
  656. ::XPoint spot;
  657. spot.x = short(p_pos.x);
  658. spot.y = short(p_pos.y);
  659. XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL);
  660. {
  661. // Block events polling during this call
  662. // because it triggers some event polling internally.
  663. MutexLock mutex_lock(events_mutex);
  664. XSetICValues(xic, XNPreeditAttributes, preedit_attr, NULL);
  665. }
  666. XFree(preedit_attr);
  667. }
  668. String OS_X11::get_unique_id() const {
  669. static String machine_id;
  670. if (machine_id.empty()) {
  671. if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) {
  672. while (machine_id.empty() && !f->eof_reached()) {
  673. machine_id = f->get_line().strip_edges();
  674. }
  675. f->close();
  676. memdelete(f);
  677. }
  678. }
  679. return machine_id;
  680. }
  681. void OS_X11::finalize() {
  682. events_thread_done = true;
  683. events_thread.wait_to_finish();
  684. if (main_loop)
  685. memdelete(main_loop);
  686. main_loop = NULL;
  687. /*
  688. if (debugger_connection_console) {
  689. memdelete(debugger_connection_console);
  690. }
  691. */
  692. #ifdef ALSAMIDI_ENABLED
  693. driver_alsamidi.close();
  694. #endif
  695. #ifdef JOYDEV_ENABLED
  696. memdelete(joypad);
  697. #endif
  698. xi.touch_devices.clear();
  699. xi.state.clear();
  700. memdelete(input);
  701. cursors_cache.clear();
  702. visual_server->finish();
  703. memdelete(visual_server);
  704. //memdelete(rasterizer);
  705. memdelete(power_manager);
  706. if (xrandr_handle)
  707. dlclose(xrandr_handle);
  708. if (!OS::get_singleton()->is_no_window_mode_enabled()) {
  709. XUnmapWindow(x11_display, x11_window);
  710. }
  711. XDestroyWindow(x11_display, x11_window);
  712. #if defined(OPENGL_ENABLED)
  713. memdelete(context_gl);
  714. #endif
  715. for (int i = 0; i < CURSOR_MAX; i++) {
  716. if (cursors[i] != None)
  717. XFreeCursor(x11_display, cursors[i]);
  718. if (img[i] != NULL)
  719. XcursorImageDestroy(img[i]);
  720. };
  721. if (xic) {
  722. XDestroyIC(xic);
  723. }
  724. if (xim) {
  725. XCloseIM(xim);
  726. }
  727. XCloseDisplay(x11_display);
  728. if (xmbstring)
  729. memfree(xmbstring);
  730. args.clear();
  731. }
  732. void OS_X11::set_mouse_mode(MouseMode p_mode) {
  733. if (p_mode == mouse_mode)
  734. return;
  735. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED)
  736. XUngrabPointer(x11_display, CurrentTime);
  737. // The only modes that show a cursor are VISIBLE and CONFINED
  738. bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
  739. if (showCursor) {
  740. XDefineCursor(x11_display, x11_window, cursors[current_cursor]); // show cursor
  741. } else {
  742. XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor
  743. }
  744. mouse_mode = p_mode;
  745. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  746. //flush pending motion events
  747. flush_mouse_motion();
  748. if (XGrabPointer(
  749. x11_display, x11_window, True,
  750. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  751. GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) {
  752. ERR_PRINT("NO GRAB");
  753. }
  754. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  755. center.x = current_videomode.width / 2;
  756. center.y = current_videomode.height / 2;
  757. XWarpPointer(x11_display, None, x11_window,
  758. 0, 0, 0, 0, (int)center.x, (int)center.y);
  759. input->set_mouse_position(center);
  760. }
  761. } else {
  762. do_mouse_warp = false;
  763. }
  764. XFlush(x11_display);
  765. }
  766. void OS_X11::warp_mouse_position(const Point2 &p_to) {
  767. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  768. last_mouse_pos = p_to;
  769. } else {
  770. /*XWindowAttributes xwa;
  771. XGetWindowAttributes(x11_display, x11_window, &xwa);
  772. printf("%d %d\n", xwa.x, xwa.y); needed? */
  773. XWarpPointer(x11_display, None, x11_window,
  774. 0, 0, 0, 0, (int)p_to.x, (int)p_to.y);
  775. }
  776. }
  777. void OS_X11::flush_mouse_motion() {
  778. // Block events polling while flushing motion events.
  779. MutexLock mutex_lock(events_mutex);
  780. for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) {
  781. XEvent &event = polled_events[event_index];
  782. if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  783. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  784. if (event_data->evtype == XI_RawMotion) {
  785. XFreeEventData(x11_display, &event.xcookie);
  786. polled_events.remove(event_index--);
  787. continue;
  788. }
  789. XFreeEventData(x11_display, &event.xcookie);
  790. break;
  791. }
  792. }
  793. xi.relative_motion.x = 0;
  794. xi.relative_motion.y = 0;
  795. }
  796. OS::MouseMode OS_X11::get_mouse_mode() const {
  797. return mouse_mode;
  798. }
  799. int OS_X11::get_mouse_button_state() const {
  800. return last_button_state;
  801. }
  802. Point2 OS_X11::get_mouse_position() const {
  803. return last_mouse_pos;
  804. }
  805. bool OS_X11::get_window_per_pixel_transparency_enabled() const {
  806. if (!is_layered_allowed()) return false;
  807. return layered_window;
  808. }
  809. void OS_X11::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  810. if (!is_layered_allowed()) return;
  811. if (layered_window != p_enabled) {
  812. if (p_enabled) {
  813. layered_window = true;
  814. } else {
  815. layered_window = false;
  816. }
  817. }
  818. }
  819. void OS_X11::set_window_title(const String &p_title) {
  820. XStoreName(x11_display, x11_window, p_title.utf8().get_data());
  821. Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
  822. Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
  823. if (_net_wm_name != None && utf8_string != None) {
  824. XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
  825. }
  826. }
  827. void OS_X11::set_window_mouse_passthrough(const PoolVector2Array &p_region) {
  828. int event_base, error_base;
  829. const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base);
  830. if (ext_okay) {
  831. Region region;
  832. if (p_region.size() == 0) {
  833. region = XCreateRegion();
  834. XRectangle rect;
  835. rect.x = 0;
  836. rect.y = 0;
  837. rect.width = get_real_window_size().x;
  838. rect.height = get_real_window_size().y;
  839. XUnionRectWithRegion(&rect, region, region);
  840. } else {
  841. XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size());
  842. for (int i = 0; i < p_region.size(); i++) {
  843. points[i].x = p_region[i].x;
  844. points[i].y = p_region[i].y;
  845. }
  846. region = XPolygonRegion(points, p_region.size(), EvenOddRule);
  847. memfree(points);
  848. }
  849. XShapeCombineRegion(x11_display, x11_window, ShapeInput, 0, 0, region, ShapeSet);
  850. XDestroyRegion(region);
  851. }
  852. }
  853. void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  854. }
  855. OS::VideoMode OS_X11::get_video_mode(int p_screen) const {
  856. return current_videomode;
  857. }
  858. void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  859. }
  860. void OS_X11::set_wm_fullscreen(bool p_enabled) {
  861. if (p_enabled && !get_borderless_window()) {
  862. // remove decorations if the window is not already borderless
  863. Hints hints;
  864. Atom property;
  865. hints.flags = 2;
  866. hints.decorations = 0;
  867. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  868. if (property != None) {
  869. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  870. }
  871. }
  872. if (p_enabled && !is_window_resizable()) {
  873. // Set the window as resizable to prevent window managers to ignore the fullscreen state flag.
  874. XSizeHints *xsh;
  875. xsh = XAllocSizeHints();
  876. xsh->flags = 0L;
  877. XSetWMNormalHints(x11_display, x11_window, xsh);
  878. XFree(xsh);
  879. }
  880. // Using EWMH -- Extended Window Manager Hints
  881. XEvent xev;
  882. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  883. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  884. memset(&xev, 0, sizeof(xev));
  885. xev.type = ClientMessage;
  886. xev.xclient.window = x11_window;
  887. xev.xclient.message_type = wm_state;
  888. xev.xclient.format = 32;
  889. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  890. xev.xclient.data.l[1] = wm_fullscreen;
  891. xev.xclient.data.l[2] = 0;
  892. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  893. // set bypass compositor hint
  894. Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
  895. unsigned long compositing_disable_on = p_enabled ? 1 : 0;
  896. if (bypass_compositor != None) {
  897. XChangeProperty(x11_display, x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
  898. }
  899. XFlush(x11_display);
  900. if (!p_enabled) {
  901. // Reset the non-resizable flags if we un-set these before.
  902. Size2 size = get_window_size();
  903. XSizeHints *xsh;
  904. xsh = XAllocSizeHints();
  905. if (!is_window_resizable()) {
  906. xsh->flags = PMinSize | PMaxSize;
  907. xsh->min_width = size.x;
  908. xsh->max_width = size.x;
  909. xsh->min_height = size.y;
  910. xsh->max_height = size.y;
  911. } else {
  912. xsh->flags = 0L;
  913. if (min_size != Size2()) {
  914. xsh->flags |= PMinSize;
  915. xsh->min_width = min_size.x;
  916. xsh->min_height = min_size.y;
  917. }
  918. if (max_size != Size2()) {
  919. xsh->flags |= PMaxSize;
  920. xsh->max_width = max_size.x;
  921. xsh->max_height = max_size.y;
  922. }
  923. }
  924. XSetWMNormalHints(x11_display, x11_window, xsh);
  925. XFree(xsh);
  926. // put back or remove decorations according to the last set borderless state
  927. Hints hints;
  928. Atom property;
  929. hints.flags = 2;
  930. hints.decorations = current_videomode.borderless_window ? 0 : 1;
  931. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  932. if (property != None) {
  933. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  934. }
  935. }
  936. }
  937. void OS_X11::set_wm_above(bool p_enabled) {
  938. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  939. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  940. XClientMessageEvent xev;
  941. memset(&xev, 0, sizeof(xev));
  942. xev.type = ClientMessage;
  943. xev.window = x11_window;
  944. xev.message_type = wm_state;
  945. xev.format = 32;
  946. xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  947. xev.data.l[1] = wm_above;
  948. xev.data.l[3] = 1;
  949. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  950. }
  951. int OS_X11::get_screen_count() const {
  952. // Using Xinerama Extension
  953. int event_base, error_base;
  954. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  955. if (!ext_okay) return 0;
  956. int count;
  957. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  958. XFree(xsi);
  959. return count;
  960. }
  961. int OS_X11::get_current_screen() const {
  962. int x, y;
  963. Window child;
  964. XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  965. int count = get_screen_count();
  966. for (int i = 0; i < count; i++) {
  967. Point2i pos = get_screen_position(i);
  968. Size2i size = get_screen_size(i);
  969. if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height))
  970. return i;
  971. }
  972. return 0;
  973. }
  974. void OS_X11::set_current_screen(int p_screen) {
  975. if (p_screen == -1) {
  976. p_screen = get_current_screen();
  977. }
  978. // Check if screen is valid
  979. ERR_FAIL_INDEX(p_screen, get_screen_count());
  980. if (current_videomode.fullscreen) {
  981. Point2i position = get_screen_position(p_screen);
  982. Size2i size = get_screen_size(p_screen);
  983. XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y);
  984. } else {
  985. if (p_screen != get_current_screen()) {
  986. Point2i position = get_screen_position(p_screen);
  987. XMoveWindow(x11_display, x11_window, position.x, position.y);
  988. }
  989. }
  990. }
  991. Point2 OS_X11::get_screen_position(int p_screen) const {
  992. if (p_screen == -1) {
  993. p_screen = get_current_screen();
  994. }
  995. // Using Xinerama Extension
  996. int event_base, error_base;
  997. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  998. if (!ext_okay) {
  999. return Point2i(0, 0);
  1000. }
  1001. int count;
  1002. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  1003. // Check if screen is valid
  1004. ERR_FAIL_INDEX_V(p_screen, count, Point2i(0, 0));
  1005. Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org);
  1006. XFree(xsi);
  1007. return position;
  1008. }
  1009. Size2 OS_X11::get_screen_size(int p_screen) const {
  1010. if (p_screen == -1) {
  1011. p_screen = get_current_screen();
  1012. }
  1013. // Using Xinerama Extension
  1014. int event_base, error_base;
  1015. const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
  1016. if (!ext_okay) return Size2i(0, 0);
  1017. int count;
  1018. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  1019. // Check if screen is valid
  1020. ERR_FAIL_INDEX_V(p_screen, count, Size2i(0, 0));
  1021. Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height);
  1022. XFree(xsi);
  1023. return size;
  1024. }
  1025. int OS_X11::get_screen_dpi(int p_screen) const {
  1026. if (p_screen == -1) {
  1027. p_screen = get_current_screen();
  1028. }
  1029. //invalid screen?
  1030. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0);
  1031. //Get physical monitor Dimensions through XRandR and calculate dpi
  1032. Size2 sc = get_screen_size(p_screen);
  1033. if (xrandr_ext_ok) {
  1034. int count = 0;
  1035. if (xrr_get_monitors) {
  1036. xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count);
  1037. if (p_screen < count) {
  1038. double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4;
  1039. double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4;
  1040. xrr_free_monitors(monitors);
  1041. return (xdpi + ydpi) / 2;
  1042. }
  1043. xrr_free_monitors(monitors);
  1044. } else if (p_screen == 0) {
  1045. XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count);
  1046. if (sizes) {
  1047. double xdpi = sc.width / (double)sizes[0].mwidth * 25.4;
  1048. double ydpi = sc.height / (double)sizes[0].mheight * 25.4;
  1049. return (xdpi + ydpi) / 2;
  1050. }
  1051. }
  1052. }
  1053. int width_mm = DisplayWidthMM(x11_display, p_screen);
  1054. int height_mm = DisplayHeightMM(x11_display, p_screen);
  1055. double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0);
  1056. double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0);
  1057. if (xdpi || ydpi)
  1058. return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1);
  1059. //could not get dpi
  1060. return 96;
  1061. }
  1062. Point2 OS_X11::get_window_position() const {
  1063. int x, y;
  1064. Window child;
  1065. XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  1066. return Point2i(x, y);
  1067. }
  1068. void OS_X11::set_window_position(const Point2 &p_position) {
  1069. int x = 0;
  1070. int y = 0;
  1071. if (!get_borderless_window()) {
  1072. //exclude window decorations
  1073. XSync(x11_display, False);
  1074. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1075. if (prop != None) {
  1076. Atom type;
  1077. int format;
  1078. unsigned long len;
  1079. unsigned long remaining;
  1080. unsigned char *data = NULL;
  1081. if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1082. if (format == 32 && len == 4) {
  1083. long *extents = (long *)data;
  1084. x = extents[0];
  1085. y = extents[2];
  1086. }
  1087. XFree(data);
  1088. }
  1089. }
  1090. }
  1091. XMoveWindow(x11_display, x11_window, p_position.x - x, p_position.y - y);
  1092. update_real_mouse_position();
  1093. }
  1094. Size2 OS_X11::get_window_size() const {
  1095. // Use current_videomode width and height instead of XGetWindowAttributes
  1096. // since right after a XResizeWindow the attributes may not be updated yet
  1097. return Size2i(current_videomode.width, current_videomode.height);
  1098. }
  1099. Size2 OS_X11::get_real_window_size() const {
  1100. XWindowAttributes xwa;
  1101. XSync(x11_display, False);
  1102. XGetWindowAttributes(x11_display, x11_window, &xwa);
  1103. int w = xwa.width;
  1104. int h = xwa.height;
  1105. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1106. if (prop != None) {
  1107. Atom type;
  1108. int format;
  1109. unsigned long len;
  1110. unsigned long remaining;
  1111. unsigned char *data = NULL;
  1112. if (XGetWindowProperty(x11_display, x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1113. if (format == 32 && len == 4) {
  1114. long *extents = (long *)data;
  1115. w += extents[0] + extents[1]; // left, right
  1116. h += extents[2] + extents[3]; // top, bottom
  1117. }
  1118. XFree(data);
  1119. }
  1120. }
  1121. return Size2(w, h);
  1122. }
  1123. Size2 OS_X11::get_max_window_size() const {
  1124. return max_size;
  1125. }
  1126. Size2 OS_X11::get_min_window_size() const {
  1127. return min_size;
  1128. }
  1129. void OS_X11::set_min_window_size(const Size2 p_size) {
  1130. if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) {
  1131. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1132. return;
  1133. }
  1134. min_size = p_size;
  1135. if (is_window_resizable()) {
  1136. XSizeHints *xsh;
  1137. xsh = XAllocSizeHints();
  1138. xsh->flags = 0L;
  1139. if (min_size != Size2()) {
  1140. xsh->flags |= PMinSize;
  1141. xsh->min_width = min_size.x;
  1142. xsh->min_height = min_size.y;
  1143. }
  1144. if (max_size != Size2()) {
  1145. xsh->flags |= PMaxSize;
  1146. xsh->max_width = max_size.x;
  1147. xsh->max_height = max_size.y;
  1148. }
  1149. XSetWMNormalHints(x11_display, x11_window, xsh);
  1150. XFree(xsh);
  1151. XFlush(x11_display);
  1152. }
  1153. }
  1154. void OS_X11::set_max_window_size(const Size2 p_size) {
  1155. if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) {
  1156. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1157. return;
  1158. }
  1159. max_size = p_size;
  1160. if (is_window_resizable()) {
  1161. XSizeHints *xsh;
  1162. xsh = XAllocSizeHints();
  1163. xsh->flags = 0L;
  1164. if (min_size != Size2()) {
  1165. xsh->flags |= PMinSize;
  1166. xsh->min_width = min_size.x;
  1167. xsh->min_height = min_size.y;
  1168. }
  1169. if (max_size != Size2()) {
  1170. xsh->flags |= PMaxSize;
  1171. xsh->max_width = max_size.x;
  1172. xsh->max_height = max_size.y;
  1173. }
  1174. XSetWMNormalHints(x11_display, x11_window, xsh);
  1175. XFree(xsh);
  1176. XFlush(x11_display);
  1177. }
  1178. }
  1179. void OS_X11::set_window_size(const Size2 p_size) {
  1180. if (current_videomode.width == p_size.width && current_videomode.height == p_size.height)
  1181. return;
  1182. XWindowAttributes xwa;
  1183. XSync(x11_display, False);
  1184. XGetWindowAttributes(x11_display, x11_window, &xwa);
  1185. int old_w = xwa.width;
  1186. int old_h = xwa.height;
  1187. Size2 size = p_size;
  1188. size.x = MAX(1, size.x);
  1189. size.y = MAX(1, size.y);
  1190. // If window resizable is disabled we need to update the attributes first
  1191. XSizeHints *xsh;
  1192. xsh = XAllocSizeHints();
  1193. if (!is_window_resizable()) {
  1194. xsh->flags = PMinSize | PMaxSize;
  1195. xsh->min_width = size.x;
  1196. xsh->max_width = size.x;
  1197. xsh->min_height = size.y;
  1198. xsh->max_height = size.y;
  1199. } else {
  1200. xsh->flags = 0L;
  1201. if (min_size != Size2()) {
  1202. xsh->flags |= PMinSize;
  1203. xsh->min_width = min_size.x;
  1204. xsh->min_height = min_size.y;
  1205. }
  1206. if (max_size != Size2()) {
  1207. xsh->flags |= PMaxSize;
  1208. xsh->max_width = max_size.x;
  1209. xsh->max_height = max_size.y;
  1210. }
  1211. }
  1212. XSetWMNormalHints(x11_display, x11_window, xsh);
  1213. XFree(xsh);
  1214. // Resize the window
  1215. XResizeWindow(x11_display, x11_window, size.x, size.y);
  1216. // Update our videomode width and height
  1217. current_videomode.width = size.x;
  1218. current_videomode.height = size.y;
  1219. for (int timeout = 0; timeout < 50; ++timeout) {
  1220. XSync(x11_display, False);
  1221. XGetWindowAttributes(x11_display, x11_window, &xwa);
  1222. if (old_w != xwa.width || old_h != xwa.height)
  1223. break;
  1224. usleep(10000);
  1225. }
  1226. }
  1227. void OS_X11::set_window_fullscreen(bool p_enabled) {
  1228. if (current_videomode.fullscreen == p_enabled)
  1229. return;
  1230. if (layered_window)
  1231. set_window_per_pixel_transparency_enabled(false);
  1232. if (p_enabled && current_videomode.always_on_top) {
  1233. // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity)
  1234. set_window_maximized(true);
  1235. }
  1236. set_wm_fullscreen(p_enabled);
  1237. if (!p_enabled && current_videomode.always_on_top) {
  1238. // Restore
  1239. set_window_maximized(false);
  1240. }
  1241. if (!p_enabled) {
  1242. set_window_position(last_position_before_fs);
  1243. } else {
  1244. last_position_before_fs = get_window_position();
  1245. }
  1246. current_videomode.fullscreen = p_enabled;
  1247. }
  1248. bool OS_X11::is_window_fullscreen() const {
  1249. return current_videomode.fullscreen;
  1250. }
  1251. void OS_X11::set_window_resizable(bool p_enabled) {
  1252. XSizeHints *xsh;
  1253. xsh = XAllocSizeHints();
  1254. if (!p_enabled) {
  1255. Size2 size = get_window_size();
  1256. xsh->flags = PMinSize | PMaxSize;
  1257. xsh->min_width = size.x;
  1258. xsh->max_width = size.x;
  1259. xsh->min_height = size.y;
  1260. xsh->max_height = size.y;
  1261. } else {
  1262. xsh->flags = 0L;
  1263. if (min_size != Size2()) {
  1264. xsh->flags |= PMinSize;
  1265. xsh->min_width = min_size.x;
  1266. xsh->min_height = min_size.y;
  1267. }
  1268. if (max_size != Size2()) {
  1269. xsh->flags |= PMaxSize;
  1270. xsh->max_width = max_size.x;
  1271. xsh->max_height = max_size.y;
  1272. }
  1273. }
  1274. XSetWMNormalHints(x11_display, x11_window, xsh);
  1275. XFree(xsh);
  1276. current_videomode.resizable = p_enabled;
  1277. XFlush(x11_display);
  1278. }
  1279. bool OS_X11::is_window_resizable() const {
  1280. return current_videomode.resizable;
  1281. }
  1282. void OS_X11::set_window_minimized(bool p_enabled) {
  1283. if (is_no_window_mode_enabled()) {
  1284. return;
  1285. }
  1286. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1287. XEvent xev;
  1288. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  1289. memset(&xev, 0, sizeof(xev));
  1290. xev.type = ClientMessage;
  1291. xev.xclient.window = x11_window;
  1292. xev.xclient.message_type = wm_change;
  1293. xev.xclient.format = 32;
  1294. xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState;
  1295. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1296. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1297. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  1298. memset(&xev, 0, sizeof(xev));
  1299. xev.type = ClientMessage;
  1300. xev.xclient.window = x11_window;
  1301. xev.xclient.message_type = wm_state;
  1302. xev.xclient.format = 32;
  1303. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1304. xev.xclient.data.l[1] = wm_hidden;
  1305. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1306. }
  1307. bool OS_X11::is_window_minimized() const {
  1308. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1309. Atom property = XInternAtom(x11_display, "WM_STATE", True);
  1310. if (property == None) {
  1311. return false;
  1312. }
  1313. Atom type;
  1314. int format;
  1315. unsigned long len;
  1316. unsigned long remaining;
  1317. unsigned char *data = NULL;
  1318. bool retval = false;
  1319. int result = XGetWindowProperty(
  1320. x11_display,
  1321. x11_window,
  1322. property,
  1323. 0,
  1324. 32,
  1325. False,
  1326. AnyPropertyType,
  1327. &type,
  1328. &format,
  1329. &len,
  1330. &remaining,
  1331. &data);
  1332. if (result == Success) {
  1333. long *state = (long *)data;
  1334. if (state[0] == WM_IconicState) {
  1335. retval = true;
  1336. }
  1337. XFree(data);
  1338. }
  1339. return retval;
  1340. }
  1341. void OS_X11::set_window_maximized(bool p_enabled) {
  1342. if (is_no_window_mode_enabled()) {
  1343. return;
  1344. }
  1345. if (is_window_maximized() == p_enabled)
  1346. return;
  1347. // Using EWMH -- Extended Window Manager Hints
  1348. XEvent xev;
  1349. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1350. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1351. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1352. memset(&xev, 0, sizeof(xev));
  1353. xev.type = ClientMessage;
  1354. xev.xclient.window = x11_window;
  1355. xev.xclient.message_type = wm_state;
  1356. xev.xclient.format = 32;
  1357. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1358. xev.xclient.data.l[1] = wm_max_horz;
  1359. xev.xclient.data.l[2] = wm_max_vert;
  1360. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1361. if (p_enabled && is_window_maximize_allowed()) {
  1362. // Wait for effective resizing (so the GLX context is too).
  1363. // Give up after 0.5s, it's not going to happen on this WM.
  1364. // https://github.com/godotengine/godot/issues/19978
  1365. for (int attempt = 0; !is_window_maximized() && attempt < 50; attempt++) {
  1366. usleep(10000);
  1367. }
  1368. }
  1369. maximized = p_enabled;
  1370. }
  1371. // Just a helper to reduce code duplication in `is_window_maximize_allowed`
  1372. // and `is_window_maximized`.
  1373. bool OS_X11::window_maximize_check(const char *p_atom_name) const {
  1374. Atom property = XInternAtom(x11_display, p_atom_name, False);
  1375. Atom type;
  1376. int format;
  1377. unsigned long len;
  1378. unsigned long remaining;
  1379. unsigned char *data = NULL;
  1380. bool retval = false;
  1381. if (property == None) {
  1382. return false;
  1383. }
  1384. int result = XGetWindowProperty(
  1385. x11_display,
  1386. x11_window,
  1387. property,
  1388. 0,
  1389. 1024,
  1390. False,
  1391. XA_ATOM,
  1392. &type,
  1393. &format,
  1394. &len,
  1395. &remaining,
  1396. &data);
  1397. if (result == Success) {
  1398. Atom *atoms = (Atom *)data;
  1399. Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False);
  1400. Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False);
  1401. bool found_wm_act_max_horz = false;
  1402. bool found_wm_act_max_vert = false;
  1403. for (uint64_t i = 0; i < len; i++) {
  1404. if (atoms[i] == wm_act_max_horz)
  1405. found_wm_act_max_horz = true;
  1406. if (atoms[i] == wm_act_max_vert)
  1407. found_wm_act_max_vert = true;
  1408. if (found_wm_act_max_horz || found_wm_act_max_vert) {
  1409. retval = true;
  1410. break;
  1411. }
  1412. }
  1413. XFree(data);
  1414. }
  1415. return retval;
  1416. }
  1417. bool OS_X11::is_window_maximize_allowed() const {
  1418. return window_maximize_check("_NET_WM_ALLOWED_ACTIONS");
  1419. }
  1420. bool OS_X11::is_window_maximized() const {
  1421. // Using EWMH -- Extended Window Manager Hints
  1422. return window_maximize_check("_NET_WM_STATE");
  1423. }
  1424. void OS_X11::set_window_always_on_top(bool p_enabled) {
  1425. if (is_window_always_on_top() == p_enabled)
  1426. return;
  1427. if (p_enabled && current_videomode.fullscreen) {
  1428. // Fullscreen + Always-on-top requires a maximized window on some window managers (Metacity)
  1429. set_window_maximized(true);
  1430. }
  1431. set_wm_above(p_enabled);
  1432. if (!p_enabled && !current_videomode.fullscreen) {
  1433. // Restore
  1434. set_window_maximized(false);
  1435. }
  1436. current_videomode.always_on_top = p_enabled;
  1437. }
  1438. bool OS_X11::is_window_always_on_top() const {
  1439. return current_videomode.always_on_top;
  1440. }
  1441. bool OS_X11::is_window_focused() const {
  1442. return window_focused;
  1443. }
  1444. void OS_X11::set_borderless_window(bool p_borderless) {
  1445. if (get_borderless_window() == p_borderless)
  1446. return;
  1447. current_videomode.borderless_window = p_borderless;
  1448. Hints hints;
  1449. Atom property;
  1450. hints.flags = 2;
  1451. hints.decorations = current_videomode.borderless_window ? 0 : 1;
  1452. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1453. if (property != None) {
  1454. XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1455. }
  1456. // Preserve window size
  1457. set_window_size(Size2(current_videomode.width, current_videomode.height));
  1458. }
  1459. bool OS_X11::get_borderless_window() {
  1460. bool borderless = current_videomode.borderless_window;
  1461. Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1462. if (prop != None) {
  1463. Atom type;
  1464. int format;
  1465. unsigned long len;
  1466. unsigned long remaining;
  1467. unsigned char *data = NULL;
  1468. if (XGetWindowProperty(x11_display, x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1469. if (data && (format == 32) && (len >= 5)) {
  1470. borderless = !((Hints *)data)->decorations;
  1471. }
  1472. XFree(data);
  1473. }
  1474. }
  1475. return borderless;
  1476. }
  1477. void OS_X11::request_attention() {
  1478. // Using EWMH -- Extended Window Manager Hints
  1479. //
  1480. // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
  1481. // Will be unset by the window manager after user react on the request for attention
  1482. XEvent xev;
  1483. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1484. Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
  1485. memset(&xev, 0, sizeof(xev));
  1486. xev.type = ClientMessage;
  1487. xev.xclient.window = x11_window;
  1488. xev.xclient.message_type = wm_state;
  1489. xev.xclient.format = 32;
  1490. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1491. xev.xclient.data.l[1] = wm_attention;
  1492. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1493. XFlush(x11_display);
  1494. }
  1495. void *OS_X11::get_native_handle(int p_handle_type) {
  1496. switch (p_handle_type) {
  1497. case APPLICATION_HANDLE: return NULL; // Do we have a value to return here?
  1498. case DISPLAY_HANDLE: return (void *)x11_display;
  1499. case WINDOW_HANDLE: return (void *)x11_window;
  1500. case WINDOW_VIEW: return NULL; // Do we have a value to return here?
  1501. case OPENGL_CONTEXT: return context_gl->get_glx_context();
  1502. default: return NULL;
  1503. }
  1504. }
  1505. void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
  1506. state->set_shift((p_x11_state & ShiftMask));
  1507. state->set_control((p_x11_state & ControlMask));
  1508. state->set_alt((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt
  1509. state->set_metakey((p_x11_state & Mod4Mask));
  1510. }
  1511. unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_button, int p_x11_type) {
  1512. unsigned int mask = 1 << (p_x11_button - 1);
  1513. if (p_x11_type == ButtonPress) {
  1514. last_button_state |= mask;
  1515. } else {
  1516. last_button_state &= ~mask;
  1517. }
  1518. return last_button_state;
  1519. }
  1520. void OS_X11::_handle_key_event(XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) {
  1521. // X11 functions don't know what const is
  1522. XKeyEvent *xkeyevent = p_event;
  1523. // This code was pretty difficult to write.
  1524. // The docs stink and every toolkit seems to
  1525. // do it in a different way.
  1526. /* Phase 1, obtain a proper keysym */
  1527. // This was also very difficult to figure out.
  1528. // You'd expect you could just use Keysym provided by
  1529. // XKeycodeToKeysym to obtain internationalized
  1530. // input.. WRONG!!
  1531. // you must use XLookupString (???) which not only wastes
  1532. // cycles generating an unnecessary string, but also
  1533. // still works in half the cases. (won't handle deadkeys)
  1534. // For more complex input methods (deadkeys and more advanced)
  1535. // you have to use XmbLookupString (??).
  1536. // So.. then you have to chosse which of both results
  1537. // you want to keep.
  1538. // This is a real bizarreness and cpu waster.
  1539. KeySym keysym_keycode = 0; // keysym used to find a keycode
  1540. KeySym keysym_unicode = 0; // keysym used to find unicode
  1541. // XLookupString returns keysyms usable as nice scancodes/
  1542. char str[256 + 1];
  1543. XKeyEvent xkeyevent_no_mod = *xkeyevent;
  1544. xkeyevent_no_mod.state &= ~ShiftMask;
  1545. xkeyevent_no_mod.state &= ~ControlMask;
  1546. XLookupString(xkeyevent, str, 256, &keysym_unicode, NULL);
  1547. XLookupString(&xkeyevent_no_mod, NULL, 0, &keysym_keycode, NULL);
  1548. // Meanwhile, XLookupString returns keysyms useful for unicode.
  1549. if (!xmbstring) {
  1550. // keep a temporary buffer for the string
  1551. xmbstring = (char *)memalloc(sizeof(char) * 8);
  1552. xmblen = 8;
  1553. }
  1554. if (xkeyevent->type == KeyPress && xic) {
  1555. Status status;
  1556. #ifdef X_HAVE_UTF8_STRING
  1557. int utf8len = 8;
  1558. char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
  1559. int utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string,
  1560. utf8len - 1, &keysym_unicode, &status);
  1561. if (status == XBufferOverflow) {
  1562. utf8len = utf8bytes + 1;
  1563. utf8string = (char *)memrealloc(utf8string, utf8len);
  1564. utf8bytes = Xutf8LookupString(xic, xkeyevent, utf8string,
  1565. utf8len - 1, &keysym_unicode, &status);
  1566. }
  1567. utf8string[utf8bytes] = '\0';
  1568. if (status == XLookupChars) {
  1569. bool keypress = xkeyevent->type == KeyPress;
  1570. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode);
  1571. if (keycode >= 'a' && keycode <= 'z')
  1572. keycode -= 'a' - 'A';
  1573. String tmp;
  1574. tmp.parse_utf8(utf8string, utf8bytes);
  1575. for (int i = 0; i < tmp.length(); i++) {
  1576. Ref<InputEventKey> k;
  1577. k.instance();
  1578. if (keycode == 0 && tmp[i] == 0) {
  1579. continue;
  1580. }
  1581. get_key_modifier_state(xkeyevent->state, k);
  1582. k->set_unicode(tmp[i]);
  1583. k->set_pressed(keypress);
  1584. k->set_scancode(keycode);
  1585. k->set_echo(false);
  1586. if (k->get_scancode() == KEY_BACKTAB) {
  1587. //make it consistent across platforms.
  1588. k->set_scancode(KEY_TAB);
  1589. k->set_shift(true);
  1590. }
  1591. input->accumulate_input_event(k);
  1592. }
  1593. memfree(utf8string);
  1594. return;
  1595. }
  1596. memfree(utf8string);
  1597. #else
  1598. do {
  1599. int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
  1600. xmbstring[mnbytes] = '\0';
  1601. if (status == XBufferOverflow) {
  1602. xmblen = mnbytes + 1;
  1603. xmbstring = (char *)memrealloc(xmbstring, xmblen);
  1604. }
  1605. } while (status == XBufferOverflow);
  1606. #endif
  1607. }
  1608. /* Phase 2, obtain a pigui keycode from the keysym */
  1609. // KeyMappingX11 just translated the X11 keysym to a PIGUI
  1610. // keysym, so it works in all platforms the same.
  1611. unsigned int keycode = KeyMappingX11::get_keycode(keysym_keycode);
  1612. /* Phase 3, obtain a unicode character from the keysym */
  1613. // KeyMappingX11 also translates keysym to unicode.
  1614. // It does a binary search on a table to translate
  1615. // most properly.
  1616. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
  1617. /* Phase 4, determine if event must be filtered */
  1618. // This seems to be a side-effect of using XIM.
  1619. // XFilterEvent looks like a core X11 function,
  1620. // but it's actually just used to see if we must
  1621. // ignore a deadkey, or events XIM determines
  1622. // must not reach the actual gui.
  1623. // Guess it was a design problem of the extension
  1624. bool keypress = xkeyevent->type == KeyPress;
  1625. if (keycode == 0 && unicode == 0)
  1626. return;
  1627. /* Phase 5, determine modifier mask */
  1628. // No problems here, except I had no way to
  1629. // know Mod1 was ALT and Mod4 was META (applekey/winkey)
  1630. // just tried Mods until i found them.
  1631. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask));
  1632. Ref<InputEventKey> k;
  1633. k.instance();
  1634. get_key_modifier_state(xkeyevent->state, k);
  1635. /* Phase 6, determine echo character */
  1636. // Echo characters in X11 are a keyrelease and a keypress
  1637. // one after the other with the (almot) same timestamp.
  1638. // To detect them, i compare to the next event in list and
  1639. // check that their difference in time is below a threshold.
  1640. if (xkeyevent->type != KeyPress) {
  1641. p_echo = false;
  1642. // make sure there are events pending,
  1643. // so this call won't block.
  1644. if (p_event_index + 1 < p_events.size()) {
  1645. XEvent &peek_event = p_events[p_event_index + 1];
  1646. // I'm using a threshold of 5 msecs,
  1647. // since sometimes there seems to be a little
  1648. // jitter. I'm still not convinced that all this approach
  1649. // is correct, but the xorg developers are
  1650. // not very helpful today.
  1651. ::Time tresh = ABSDIFF(peek_event.xkey.time, xkeyevent->time);
  1652. if (peek_event.type == KeyPress && tresh < 5) {
  1653. KeySym rk;
  1654. XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL);
  1655. if (rk == keysym_keycode) {
  1656. // Consume to next event.
  1657. ++p_event_index;
  1658. _handle_key_event((XKeyEvent *)&peek_event, p_events, p_event_index, true);
  1659. return; //ignore current, echo next
  1660. }
  1661. }
  1662. // use the time from peek_event so it always works
  1663. }
  1664. // save the time to check for echo when keypress happens
  1665. }
  1666. /* Phase 7, send event to Window */
  1667. k->set_pressed(keypress);
  1668. if (keycode >= 'a' && keycode <= 'z')
  1669. keycode -= 'a' - 'A';
  1670. k->set_scancode(keycode);
  1671. k->set_unicode(unicode);
  1672. k->set_echo(p_echo);
  1673. if (k->get_scancode() == KEY_BACKTAB) {
  1674. //make it consistent across platforms.
  1675. k->set_scancode(KEY_TAB);
  1676. k->set_shift(true);
  1677. }
  1678. //don't set mod state if modifier keys are released by themselves
  1679. //else event.is_action() will not work correctly here
  1680. if (!k->is_pressed()) {
  1681. if (k->get_scancode() == KEY_SHIFT)
  1682. k->set_shift(false);
  1683. else if (k->get_scancode() == KEY_CONTROL)
  1684. k->set_control(false);
  1685. else if (k->get_scancode() == KEY_ALT)
  1686. k->set_alt(false);
  1687. else if (k->get_scancode() == KEY_META)
  1688. k->set_metakey(false);
  1689. }
  1690. bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_scancode());
  1691. if (k->is_pressed()) {
  1692. if (last_is_pressed) {
  1693. k->set_echo(true);
  1694. }
  1695. }
  1696. //printf("key: %x\n",k->get_scancode());
  1697. input->accumulate_input_event(k);
  1698. }
  1699. Atom OS_X11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property) const {
  1700. if (p_target == XInternAtom(x11_display, "TARGETS", 0)) {
  1701. // Request to list all supported targets.
  1702. Atom data[9];
  1703. data[0] = XInternAtom(x11_display, "TARGETS", 0);
  1704. data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0);
  1705. data[2] = XInternAtom(x11_display, "MULTIPLE", 0);
  1706. data[3] = XInternAtom(x11_display, "UTF8_STRING", 0);
  1707. data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
  1708. data[5] = XInternAtom(x11_display, "TEXT", 0);
  1709. data[6] = XA_STRING;
  1710. data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
  1711. data[8] = XInternAtom(x11_display, "text/plain", 0);
  1712. XChangeProperty(x11_display,
  1713. p_requestor,
  1714. p_property,
  1715. XA_ATOM,
  1716. 32,
  1717. PropModeReplace,
  1718. (unsigned char *)&data,
  1719. sizeof(data) / sizeof(data[0]));
  1720. return p_property;
  1721. } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) {
  1722. // Request to check if SAVE_TARGETS is supported, nothing special to do.
  1723. XChangeProperty(x11_display,
  1724. p_requestor,
  1725. p_property,
  1726. XInternAtom(x11_display, "NULL", False),
  1727. 32,
  1728. PropModeReplace,
  1729. NULL,
  1730. 0);
  1731. return p_property;
  1732. } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
  1733. p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
  1734. p_target == XInternAtom(x11_display, "TEXT", 0) ||
  1735. p_target == XA_STRING ||
  1736. p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
  1737. p_target == XInternAtom(x11_display, "text/plain", 0)) {
  1738. // Directly using internal clipboard because we know our window
  1739. // is the owner during a selection request.
  1740. CharString clip = OS::get_clipboard().utf8();
  1741. XChangeProperty(x11_display,
  1742. p_requestor,
  1743. p_property,
  1744. p_target,
  1745. 8,
  1746. PropModeReplace,
  1747. (unsigned char *)clip.get_data(),
  1748. clip.length());
  1749. return p_property;
  1750. } else {
  1751. char *target_name = XGetAtomName(x11_display, p_target);
  1752. printf("Target '%s' not supported.\n", target_name);
  1753. if (target_name) {
  1754. XFree(target_name);
  1755. }
  1756. return None;
  1757. }
  1758. }
  1759. void OS_X11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const {
  1760. XEvent respond;
  1761. if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) {
  1762. // Request for multiple target conversions at once.
  1763. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False);
  1764. respond.xselection.property = None;
  1765. Atom type;
  1766. int format;
  1767. unsigned long len;
  1768. unsigned long remaining;
  1769. unsigned char *data = NULL;
  1770. if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) {
  1771. if ((len >= 2) && data) {
  1772. Atom *targets = (Atom *)data;
  1773. for (uint64_t i = 0; i < len; i += 2) {
  1774. Atom target = targets[i];
  1775. Atom &property = targets[i + 1];
  1776. property = _process_selection_request_target(target, p_event->requestor, property);
  1777. }
  1778. XChangeProperty(x11_display,
  1779. p_event->requestor,
  1780. p_event->property,
  1781. atom_pair,
  1782. 32,
  1783. PropModeReplace,
  1784. (unsigned char *)targets,
  1785. len);
  1786. respond.xselection.property = p_event->property;
  1787. }
  1788. XFree(data);
  1789. }
  1790. } else {
  1791. // Request for target conversion.
  1792. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property);
  1793. }
  1794. respond.xselection.type = SelectionNotify;
  1795. respond.xselection.display = p_event->display;
  1796. respond.xselection.requestor = p_event->requestor;
  1797. respond.xselection.selection = p_event->selection;
  1798. respond.xselection.target = p_event->target;
  1799. respond.xselection.time = p_event->time;
  1800. XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond);
  1801. XFlush(x11_display);
  1802. }
  1803. struct Property {
  1804. unsigned char *data;
  1805. int format, nitems;
  1806. Atom type;
  1807. };
  1808. static Property read_property(Display *p_display, Window p_window, Atom p_property) {
  1809. Atom actual_type = None;
  1810. int actual_format = 0;
  1811. unsigned long nitems = 0;
  1812. unsigned long bytes_after = 0;
  1813. unsigned char *ret = 0;
  1814. int read_bytes = 1024;
  1815. //Keep trying to read the property until there are no
  1816. //bytes unread.
  1817. if (p_property != None) {
  1818. do {
  1819. if (ret != 0)
  1820. XFree(ret);
  1821. XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
  1822. &actual_type, &actual_format, &nitems, &bytes_after,
  1823. &ret);
  1824. read_bytes *= 2;
  1825. } while (bytes_after != 0);
  1826. }
  1827. Property p = { ret, actual_format, (int)nitems, actual_type };
  1828. return p;
  1829. }
  1830. static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) {
  1831. static const char *target_type = "text/uri-list";
  1832. for (int i = 0; i < p_count; i++) {
  1833. Atom atom = p_list[i];
  1834. if (atom != None && String(XGetAtomName(p_display, atom)) == target_type)
  1835. return atom;
  1836. }
  1837. return None;
  1838. }
  1839. static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
  1840. static const char *target_type = "text/uri-list";
  1841. if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type)
  1842. return p_t1;
  1843. if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type)
  1844. return p_t2;
  1845. if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type)
  1846. return p_t3;
  1847. return None;
  1848. }
  1849. void OS_X11::_window_changed(XEvent *event) {
  1850. if (xic) {
  1851. // Not portable.
  1852. set_ime_position(Point2(0, 1));
  1853. }
  1854. if ((event->xconfigure.width == current_videomode.width) &&
  1855. (event->xconfigure.height == current_videomode.height))
  1856. return;
  1857. current_videomode.width = event->xconfigure.width;
  1858. current_videomode.height = event->xconfigure.height;
  1859. }
  1860. void OS_X11::_poll_events_thread(void *ud) {
  1861. OS_X11 *os = (OS_X11 *)ud;
  1862. os->_poll_events();
  1863. }
  1864. Bool OS_X11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) {
  1865. // Just accept all events.
  1866. return True;
  1867. }
  1868. bool OS_X11::_wait_for_events() const {
  1869. int x11_fd = ConnectionNumber(x11_display);
  1870. fd_set in_fds;
  1871. XFlush(x11_display);
  1872. FD_ZERO(&in_fds);
  1873. FD_SET(x11_fd, &in_fds);
  1874. struct timeval tv;
  1875. tv.tv_usec = 0;
  1876. tv.tv_sec = 1;
  1877. // Wait for next event or timeout.
  1878. int num_ready_fds = select(x11_fd + 1, &in_fds, NULL, NULL, &tv);
  1879. if (num_ready_fds > 0) {
  1880. // Event received.
  1881. return true;
  1882. } else {
  1883. // Error or timeout.
  1884. if (num_ready_fds < 0) {
  1885. ERR_PRINT("_wait_for_events: select error: " + itos(errno));
  1886. }
  1887. return false;
  1888. }
  1889. }
  1890. void OS_X11::_poll_events() {
  1891. while (!events_thread_done) {
  1892. _wait_for_events();
  1893. // Process events from the queue.
  1894. {
  1895. MutexLock mutex_lock(events_mutex);
  1896. // Non-blocking wait for next event and remove it from the queue.
  1897. XEvent ev;
  1898. while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, NULL)) {
  1899. // Check if the input manager wants to process the event.
  1900. if (XFilterEvent(&ev, None)) {
  1901. // Event has been filtered by the Input Manager,
  1902. // it has to be ignored and a new one will be received.
  1903. continue;
  1904. }
  1905. // Handle selection request events directly in the event thread, because
  1906. // communication through the x server takes several events sent back and forth
  1907. // and we don't want to block other programs while processing only one each frame.
  1908. if (ev.type == SelectionRequest) {
  1909. _handle_selection_request_event(&(ev.xselectionrequest));
  1910. continue;
  1911. }
  1912. polled_events.push_back(ev);
  1913. }
  1914. }
  1915. }
  1916. }
  1917. void OS_X11::process_xevents() {
  1918. //printf("checking events %i\n", XPending(x11_display));
  1919. do_mouse_warp = false;
  1920. // Is the current mouse mode one where it needs to be grabbed.
  1921. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED;
  1922. xi.pressure = 0;
  1923. xi.tilt = Vector2();
  1924. xi.pressure_supported = false;
  1925. LocalVector<XEvent> events;
  1926. {
  1927. // Block events polling while flushing events.
  1928. MutexLock mutex_lock(events_mutex);
  1929. events = polled_events;
  1930. polled_events.clear();
  1931. }
  1932. for (uint32_t event_index = 0; event_index < events.size(); ++event_index) {
  1933. XEvent &event = events[event_index];
  1934. if (XGetEventData(x11_display, &event.xcookie)) {
  1935. if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  1936. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  1937. int index = event_data->detail;
  1938. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  1939. switch (event_data->evtype) {
  1940. case XI_HierarchyChanged:
  1941. case XI_DeviceChanged: {
  1942. refresh_device_info();
  1943. } break;
  1944. case XI_RawMotion: {
  1945. XIRawEvent *raw_event = (XIRawEvent *)event_data;
  1946. int device_id = raw_event->deviceid;
  1947. // Determine the axis used (called valuators in XInput for some forsaken reason)
  1948. // Mask is a bitmask indicating which axes are involved.
  1949. // We are interested in the values of axes 0 and 1.
  1950. if (raw_event->valuators.mask_len <= 0) {
  1951. break;
  1952. }
  1953. const double *values = raw_event->raw_values;
  1954. double rel_x = 0.0;
  1955. double rel_y = 0.0;
  1956. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) {
  1957. rel_x = *values;
  1958. values++;
  1959. }
  1960. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) {
  1961. rel_y = *values;
  1962. values++;
  1963. }
  1964. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) {
  1965. Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id);
  1966. if (pen_pressure) {
  1967. Vector2 pen_pressure_range = pen_pressure->value();
  1968. if (pen_pressure_range != Vector2()) {
  1969. xi.pressure_supported = true;
  1970. xi.pressure = (*values - pen_pressure_range[0]) /
  1971. (pen_pressure_range[1] - pen_pressure_range[0]);
  1972. }
  1973. }
  1974. values++;
  1975. }
  1976. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) {
  1977. Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id);
  1978. if (pen_tilt_x) {
  1979. Vector2 pen_tilt_x_range = pen_tilt_x->value();
  1980. if (pen_tilt_x_range != Vector2()) {
  1981. xi.tilt.x = ((*values - pen_tilt_x_range[0]) / (pen_tilt_x_range[1] - pen_tilt_x_range[0])) * 2 - 1;
  1982. }
  1983. }
  1984. values++;
  1985. }
  1986. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) {
  1987. Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id);
  1988. if (pen_tilt_y) {
  1989. Vector2 pen_tilt_y_range = pen_tilt_y->value();
  1990. if (pen_tilt_y_range != Vector2()) {
  1991. xi.tilt.y = ((*values - pen_tilt_y_range[0]) / (pen_tilt_y_range[1] - pen_tilt_y_range[0])) * 2 - 1;
  1992. }
  1993. }
  1994. values++;
  1995. }
  1996. // https://bugs.freedesktop.org/show_bug.cgi?id=71609
  1997. // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html
  1998. if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) {
  1999. break; // Flush duplicate to avoid overly fast motion
  2000. }
  2001. xi.old_raw_pos.x = xi.raw_pos.x;
  2002. xi.old_raw_pos.y = xi.raw_pos.y;
  2003. xi.raw_pos.x = rel_x;
  2004. xi.raw_pos.y = rel_y;
  2005. Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id);
  2006. if (abs_info) {
  2007. // Absolute mode device
  2008. Vector2 mult = abs_info->value();
  2009. xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x;
  2010. xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y;
  2011. } else {
  2012. // Relative mode device
  2013. xi.relative_motion.x = xi.raw_pos.x;
  2014. xi.relative_motion.y = xi.raw_pos.y;
  2015. }
  2016. xi.last_relative_time = raw_event->time;
  2017. } break;
  2018. #ifdef TOUCH_ENABLED
  2019. case XI_TouchBegin: // Fall-through
  2020. // Disabled hand-in-hand with the grabbing
  2021. //XIAllowTouchEvents(x11_display, event_data->deviceid, event_data->detail, x11_window, XIAcceptTouch);
  2022. case XI_TouchEnd: {
  2023. bool is_begin = event_data->evtype == XI_TouchBegin;
  2024. Ref<InputEventScreenTouch> st;
  2025. st.instance();
  2026. st->set_index(index);
  2027. st->set_position(pos);
  2028. st->set_pressed(is_begin);
  2029. if (is_begin) {
  2030. if (xi.state.has(index)) // Defensive
  2031. break;
  2032. xi.state[index] = pos;
  2033. if (xi.state.size() == 1) {
  2034. // X11 may send a motion event when a touch gesture begins, that would result
  2035. // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out
  2036. xi.mouse_pos_to_filter = pos;
  2037. }
  2038. input->accumulate_input_event(st);
  2039. } else {
  2040. if (!xi.state.has(index)) // Defensive
  2041. break;
  2042. xi.state.erase(index);
  2043. input->accumulate_input_event(st);
  2044. }
  2045. } break;
  2046. case XI_TouchUpdate: {
  2047. Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index);
  2048. if (!curr_pos_elem) { // Defensive
  2049. break;
  2050. }
  2051. if (curr_pos_elem->value() != pos) {
  2052. Ref<InputEventScreenDrag> sd;
  2053. sd.instance();
  2054. sd->set_index(index);
  2055. sd->set_position(pos);
  2056. sd->set_relative(pos - curr_pos_elem->value());
  2057. input->accumulate_input_event(sd);
  2058. curr_pos_elem->value() = pos;
  2059. }
  2060. } break;
  2061. #endif
  2062. }
  2063. }
  2064. }
  2065. XFreeEventData(x11_display, &event.xcookie);
  2066. switch (event.type) {
  2067. case Expose:
  2068. Main::force_redraw();
  2069. break;
  2070. case NoExpose:
  2071. minimized = true;
  2072. break;
  2073. case VisibilityNotify: {
  2074. XVisibilityEvent *visibility = (XVisibilityEvent *)&event;
  2075. minimized = (visibility->state == VisibilityFullyObscured);
  2076. } break;
  2077. case LeaveNotify: {
  2078. if (main_loop && !mouse_mode_grab)
  2079. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  2080. } break;
  2081. case EnterNotify: {
  2082. if (main_loop && !mouse_mode_grab)
  2083. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  2084. } break;
  2085. case FocusIn:
  2086. minimized = false;
  2087. window_has_focus = true;
  2088. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  2089. window_focused = true;
  2090. if (mouse_mode_grab) {
  2091. // Show and update the cursor if confined and the window regained focus.
  2092. if (mouse_mode == MOUSE_MODE_CONFINED)
  2093. XUndefineCursor(x11_display, x11_window);
  2094. else if (mouse_mode == MOUSE_MODE_CAPTURED) // or re-hide it in captured mode
  2095. XDefineCursor(x11_display, x11_window, null_cursor);
  2096. XGrabPointer(
  2097. x11_display, x11_window, True,
  2098. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  2099. GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime);
  2100. }
  2101. #ifdef TOUCH_ENABLED
  2102. // Grab touch devices to avoid OS gesture interference
  2103. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  2104. XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask);
  2105. }*/
  2106. #endif
  2107. if (xic) {
  2108. // Block events polling while changing input focus
  2109. // because it triggers some event polling internally.
  2110. MutexLock mutex_lock(events_mutex);
  2111. XSetICFocus(xic);
  2112. }
  2113. break;
  2114. case FocusOut:
  2115. window_has_focus = false;
  2116. input->release_pressed_events();
  2117. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  2118. window_focused = false;
  2119. if (mouse_mode_grab) {
  2120. //dear X11, I try, I really try, but you never work, you do whathever you want.
  2121. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2122. // Show the cursor if we're in captured mode so it doesn't look weird.
  2123. XUndefineCursor(x11_display, x11_window);
  2124. }
  2125. XUngrabPointer(x11_display, CurrentTime);
  2126. }
  2127. #ifdef TOUCH_ENABLED
  2128. // Ungrab touch devices so input works as usual while we are unfocused
  2129. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  2130. XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime);
  2131. }*/
  2132. // Release every pointer to avoid sticky points
  2133. for (Map<int, Vector2>::Element *E = xi.state.front(); E; E = E->next()) {
  2134. Ref<InputEventScreenTouch> st;
  2135. st.instance();
  2136. st->set_index(E->key());
  2137. st->set_position(E->get());
  2138. input->accumulate_input_event(st);
  2139. }
  2140. xi.state.clear();
  2141. #endif
  2142. if (xic) {
  2143. // Block events polling while changing input focus
  2144. // because it triggers some event polling internally.
  2145. MutexLock mutex_lock(events_mutex);
  2146. XUnsetICFocus(xic);
  2147. }
  2148. break;
  2149. case ConfigureNotify:
  2150. _window_changed(&event);
  2151. break;
  2152. case ButtonPress:
  2153. case ButtonRelease: {
  2154. /* exit in case of a mouse button press */
  2155. last_timestamp = event.xbutton.time;
  2156. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2157. event.xbutton.x = last_mouse_pos.x;
  2158. event.xbutton.y = last_mouse_pos.y;
  2159. }
  2160. Ref<InputEventMouseButton> mb;
  2161. mb.instance();
  2162. get_key_modifier_state(event.xbutton.state, mb);
  2163. mb->set_button_index(event.xbutton.button);
  2164. if (mb->get_button_index() == 2)
  2165. mb->set_button_index(3);
  2166. else if (mb->get_button_index() == 3)
  2167. mb->set_button_index(2);
  2168. mb->set_button_mask(get_mouse_button_state(mb->get_button_index(), event.xbutton.type));
  2169. mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
  2170. mb->set_global_position(mb->get_position());
  2171. mb->set_pressed((event.type == ButtonPress));
  2172. if (event.type == ButtonPress) {
  2173. uint64_t diff = get_ticks_usec() / 1000 - last_click_ms;
  2174. if (mb->get_button_index() == last_click_button_index) {
  2175. if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) {
  2176. last_click_ms = 0;
  2177. last_click_pos = Point2(-100, -100);
  2178. last_click_button_index = -1;
  2179. mb->set_doubleclick(true);
  2180. }
  2181. } else if (mb->get_button_index() < 4 || mb->get_button_index() > 7) {
  2182. last_click_button_index = mb->get_button_index();
  2183. }
  2184. if (!mb->is_doubleclick()) {
  2185. last_click_ms += diff;
  2186. last_click_pos = Point2(event.xbutton.x, event.xbutton.y);
  2187. }
  2188. }
  2189. input->accumulate_input_event(mb);
  2190. } break;
  2191. case MotionNotify: {
  2192. // The X11 API requires filtering one-by-one through the motion
  2193. // notify events, in order to figure out which event is the one
  2194. // generated by warping the mouse pointer.
  2195. while (true) {
  2196. if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) {
  2197. //this is likely the warp event since it was warped here
  2198. center = Vector2(event.xmotion.x, event.xmotion.y);
  2199. break;
  2200. }
  2201. if (event_index + 1 < events.size()) {
  2202. const XEvent &next_event = events[event_index + 1];
  2203. if (next_event.type == MotionNotify) {
  2204. ++event_index;
  2205. event = next_event;
  2206. } else {
  2207. break;
  2208. }
  2209. } else {
  2210. break;
  2211. }
  2212. }
  2213. last_timestamp = event.xmotion.time;
  2214. // Motion is also simple.
  2215. // A little hack is in order
  2216. // to be able to send relative motion events.
  2217. Point2 pos(event.xmotion.x, event.xmotion.y);
  2218. // Avoidance of spurious mouse motion (see handling of touch)
  2219. bool filter = false;
  2220. // Adding some tolerance to match better Point2i to Vector2
  2221. if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) {
  2222. filter = true;
  2223. }
  2224. // Invalidate to avoid filtering a possible legitimate similar event coming later
  2225. xi.mouse_pos_to_filter = Vector2(1e10, 1e10);
  2226. if (filter) {
  2227. break;
  2228. }
  2229. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2230. if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) {
  2231. break;
  2232. }
  2233. Point2i new_center = pos;
  2234. pos = last_mouse_pos + xi.relative_motion;
  2235. center = new_center;
  2236. do_mouse_warp = window_has_focus; // warp the cursor if we're focused in
  2237. }
  2238. if (!last_mouse_pos_valid) {
  2239. last_mouse_pos = pos;
  2240. last_mouse_pos_valid = true;
  2241. }
  2242. // Hackish but relative mouse motion is already handled in the RawMotion event.
  2243. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does).
  2244. // Therefore, RawMotion cannot be the authority on absolute mouse position.
  2245. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion.
  2246. // Therefore, MotionNotify cannot be the authority on relative mouse motion.
  2247. // This means we need to take a combined approach...
  2248. Point2 rel;
  2249. // Only use raw input if in capture mode. Otherwise use the classic behavior.
  2250. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2251. rel = xi.relative_motion;
  2252. } else {
  2253. rel = pos - last_mouse_pos;
  2254. }
  2255. // Reset to prevent lingering motion
  2256. xi.relative_motion.x = 0;
  2257. xi.relative_motion.y = 0;
  2258. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2259. pos = Point2i(current_videomode.width / 2, current_videomode.height / 2);
  2260. }
  2261. Ref<InputEventMouseMotion> mm;
  2262. mm.instance();
  2263. if (xi.pressure_supported) {
  2264. mm->set_pressure(xi.pressure);
  2265. } else {
  2266. mm->set_pressure((get_mouse_button_state() & (1 << (BUTTON_LEFT - 1))) ? 1.0f : 0.0f);
  2267. }
  2268. mm->set_tilt(xi.tilt);
  2269. // Make the absolute position integral so it doesn't look _too_ weird :)
  2270. Point2i posi(pos);
  2271. get_key_modifier_state(event.xmotion.state, mm);
  2272. mm->set_button_mask(get_mouse_button_state());
  2273. mm->set_position(posi);
  2274. mm->set_global_position(posi);
  2275. input->set_mouse_position(posi);
  2276. mm->set_speed(input->get_last_mouse_speed());
  2277. mm->set_relative(rel);
  2278. last_mouse_pos = pos;
  2279. // printf("rel: %d,%d\n", rel.x, rel.y );
  2280. // Don't propagate the motion event unless we have focus
  2281. // this is so that the relative motion doesn't get messed up
  2282. // after we regain focus.
  2283. if (window_has_focus || !mouse_mode_grab)
  2284. input->accumulate_input_event(mm);
  2285. } break;
  2286. case KeyPress:
  2287. case KeyRelease: {
  2288. last_timestamp = event.xkey.time;
  2289. // key event is a little complex, so
  2290. // it will be handled in its own function.
  2291. _handle_key_event((XKeyEvent *)&event, events, event_index);
  2292. } break;
  2293. case SelectionNotify:
  2294. if (event.xselection.target == requested) {
  2295. Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0));
  2296. Vector<String> files = String((char *)p.data).split("\n", false);
  2297. for (int i = 0; i < files.size(); i++) {
  2298. files.write[i] = files[i].replace("file://", "").http_unescape().strip_edges();
  2299. }
  2300. main_loop->drop_files(files);
  2301. //Reply that all is well.
  2302. XClientMessageEvent m;
  2303. memset(&m, 0, sizeof(m));
  2304. m.type = ClientMessage;
  2305. m.display = x11_display;
  2306. m.window = xdnd_source_window;
  2307. m.message_type = xdnd_finished;
  2308. m.format = 32;
  2309. m.data.l[0] = x11_window;
  2310. m.data.l[1] = 1;
  2311. m.data.l[2] = xdnd_action_copy; //We only ever copy.
  2312. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
  2313. }
  2314. break;
  2315. case ClientMessage:
  2316. if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete)
  2317. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  2318. else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
  2319. //File(s) have been dragged over the window, check for supported target (text/uri-list)
  2320. xdnd_version = (event.xclient.data.l[1] >> 24);
  2321. Window source = event.xclient.data.l[0];
  2322. bool more_than_3 = event.xclient.data.l[1] & 1;
  2323. if (more_than_3) {
  2324. Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
  2325. requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
  2326. } else
  2327. requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
  2328. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
  2329. //xdnd position event, reply with an XDND status message
  2330. //just depending on type of data for now
  2331. XClientMessageEvent m;
  2332. memset(&m, 0, sizeof(m));
  2333. m.type = ClientMessage;
  2334. m.display = event.xclient.display;
  2335. m.window = event.xclient.data.l[0];
  2336. m.message_type = xdnd_status;
  2337. m.format = 32;
  2338. m.data.l[0] = x11_window;
  2339. m.data.l[1] = (requested != None);
  2340. m.data.l[2] = 0; //empty rectangle
  2341. m.data.l[3] = 0;
  2342. m.data.l[4] = xdnd_action_copy;
  2343. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  2344. XFlush(x11_display);
  2345. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
  2346. if (requested != None) {
  2347. xdnd_source_window = event.xclient.data.l[0];
  2348. if (xdnd_version >= 1)
  2349. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]);
  2350. else
  2351. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime);
  2352. } else {
  2353. //Reply that we're not interested.
  2354. XClientMessageEvent m;
  2355. memset(&m, 0, sizeof(m));
  2356. m.type = ClientMessage;
  2357. m.display = event.xclient.display;
  2358. m.window = event.xclient.data.l[0];
  2359. m.message_type = xdnd_finished;
  2360. m.format = 32;
  2361. m.data.l[0] = x11_window;
  2362. m.data.l[1] = 0;
  2363. m.data.l[2] = None; //Failed.
  2364. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  2365. }
  2366. }
  2367. break;
  2368. default:
  2369. break;
  2370. }
  2371. }
  2372. XFlush(x11_display);
  2373. if (do_mouse_warp) {
  2374. XWarpPointer(x11_display, None, x11_window,
  2375. 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2);
  2376. /*
  2377. Window root, child;
  2378. int root_x, root_y;
  2379. int win_x, win_y;
  2380. unsigned int mask;
  2381. XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );
  2382. printf("Root: %d,%d\n", root_x, root_y);
  2383. printf("Win: %d,%d\n", win_x, win_y);
  2384. */
  2385. }
  2386. input->flush_accumulated_events();
  2387. }
  2388. MainLoop *OS_X11::get_main_loop() const {
  2389. return main_loop;
  2390. }
  2391. void OS_X11::delete_main_loop() {
  2392. // Send owned clipboard data to clipboard manager before exit.
  2393. // This has to be done here because the clipboard data is cleared before finalize().
  2394. _clipboard_transfer_ownership(XA_PRIMARY, x11_window);
  2395. _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window);
  2396. if (main_loop)
  2397. memdelete(main_loop);
  2398. main_loop = NULL;
  2399. }
  2400. void OS_X11::set_main_loop(MainLoop *p_main_loop) {
  2401. main_loop = p_main_loop;
  2402. input->set_main_loop(p_main_loop);
  2403. }
  2404. bool OS_X11::can_draw() const {
  2405. return !minimized;
  2406. };
  2407. void OS_X11::set_clipboard(const String &p_text) {
  2408. {
  2409. // The clipboard content can be accessed while polling for events.
  2410. MutexLock mutex_lock(events_mutex);
  2411. OS::set_clipboard(p_text);
  2412. }
  2413. XSetSelectionOwner(x11_display, XA_PRIMARY, x11_window, CurrentTime);
  2414. XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime);
  2415. };
  2416. Bool OS_X11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) {
  2417. if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) {
  2418. return True;
  2419. } else {
  2420. return False;
  2421. }
  2422. }
  2423. Bool OS_X11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) {
  2424. if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue) {
  2425. return True;
  2426. } else {
  2427. return False;
  2428. }
  2429. }
  2430. String OS_X11::_get_clipboard_impl(Atom p_source, Window x11_window, Atom target) const {
  2431. String ret;
  2432. Window selection_owner = XGetSelectionOwner(x11_display, p_source);
  2433. if (selection_owner == x11_window) {
  2434. return OS::get_clipboard();
  2435. }
  2436. if (selection_owner != None) {
  2437. // Block events polling while processing selection events.
  2438. MutexLock mutex_lock(events_mutex);
  2439. Atom selection = XA_PRIMARY;
  2440. XConvertSelection(x11_display, p_source, target, selection,
  2441. x11_window, CurrentTime);
  2442. XFlush(x11_display);
  2443. // Blocking wait for predicate to be True and remove the event from the queue.
  2444. XEvent event;
  2445. XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
  2446. // Do not get any data, see how much data is there.
  2447. Atom type;
  2448. int format, result;
  2449. unsigned long len, bytes_left, dummy;
  2450. unsigned char *data;
  2451. XGetWindowProperty(x11_display, x11_window,
  2452. selection, // Tricky..
  2453. 0, 0, // offset - len
  2454. 0, // Delete 0==FALSE
  2455. AnyPropertyType, // flag
  2456. &type, // return type
  2457. &format, // return format
  2458. &len, &bytes_left, // data length
  2459. &data);
  2460. if (data) {
  2461. XFree(data);
  2462. }
  2463. if (type == XInternAtom(x11_display, "INCR", 0)) {
  2464. // Data is going to be received incrementally.
  2465. LocalVector<uint8_t> incr_data;
  2466. uint32_t data_size = 0;
  2467. bool success = false;
  2468. // Delete INCR property to notify the owner.
  2469. XDeleteProperty(x11_display, x11_window, type);
  2470. // Process events from the queue.
  2471. bool done = false;
  2472. while (!done) {
  2473. if (!_wait_for_events()) {
  2474. // Error or timeout, abort.
  2475. break;
  2476. }
  2477. // Non-blocking wait for next event and remove it from the queue.
  2478. XEvent ev;
  2479. while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, NULL)) {
  2480. result = XGetWindowProperty(x11_display, x11_window,
  2481. selection, // selection type
  2482. 0, LONG_MAX, // offset - len
  2483. True, // delete property to notify the owner
  2484. AnyPropertyType, // flag
  2485. &type, // return type
  2486. &format, // return format
  2487. &len, &bytes_left, // data length
  2488. &data);
  2489. if (result == Success) {
  2490. if (data && (len > 0)) {
  2491. uint32_t prev_size = incr_data.size();
  2492. if (prev_size == 0) {
  2493. // First property contains initial data size.
  2494. unsigned long initial_size = *(unsigned long *)data;
  2495. incr_data.resize(initial_size);
  2496. } else {
  2497. // New chunk, resize to be safe and append data.
  2498. incr_data.resize(MAX(data_size + len, prev_size));
  2499. memcpy(incr_data.ptr() + data_size, data, len);
  2500. data_size += len;
  2501. }
  2502. } else {
  2503. // Last chunk, process finished.
  2504. done = true;
  2505. success = true;
  2506. }
  2507. } else {
  2508. printf("Failed to get selection data chunk.\n");
  2509. done = true;
  2510. }
  2511. if (data) {
  2512. XFree(data);
  2513. }
  2514. if (done) {
  2515. break;
  2516. }
  2517. }
  2518. }
  2519. if (success && (data_size > 0)) {
  2520. ret.parse_utf8((const char *)incr_data.ptr(), data_size);
  2521. }
  2522. } else if (bytes_left > 0) {
  2523. // Data is ready and can be processed all at once.
  2524. result = XGetWindowProperty(x11_display, x11_window,
  2525. selection, 0, bytes_left, 0,
  2526. AnyPropertyType, &type, &format,
  2527. &len, &dummy, &data);
  2528. if (result == Success) {
  2529. ret.parse_utf8((const char *)data);
  2530. } else {
  2531. printf("Failed to get selection data.\n");
  2532. }
  2533. if (data) {
  2534. XFree(data);
  2535. }
  2536. }
  2537. }
  2538. return ret;
  2539. }
  2540. String OS_X11::_get_clipboard(Atom p_source, Window x11_window) const {
  2541. String ret;
  2542. Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True);
  2543. if (utf8_atom != None) {
  2544. ret = _get_clipboard_impl(p_source, x11_window, utf8_atom);
  2545. }
  2546. if (ret.empty()) {
  2547. ret = _get_clipboard_impl(p_source, x11_window, XA_STRING);
  2548. }
  2549. return ret;
  2550. }
  2551. String OS_X11::get_clipboard() const {
  2552. String ret;
  2553. ret = _get_clipboard(XInternAtom(x11_display, "CLIPBOARD", 0), x11_window);
  2554. if (ret.empty()) {
  2555. ret = _get_clipboard(XA_PRIMARY, x11_window);
  2556. };
  2557. return ret;
  2558. }
  2559. Bool OS_X11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) {
  2560. if (event->xany.window == *(Window *)arg) {
  2561. return (event->type == SelectionRequest) ||
  2562. (event->type == SelectionNotify);
  2563. } else {
  2564. return False;
  2565. }
  2566. }
  2567. void OS_X11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const {
  2568. Window selection_owner = XGetSelectionOwner(x11_display, p_source);
  2569. if (selection_owner != x11_window) {
  2570. return;
  2571. }
  2572. // Block events polling while processing selection events.
  2573. MutexLock mutex_lock(events_mutex);
  2574. Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False);
  2575. Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False);
  2576. XConvertSelection(x11_display, clipboard_manager, save_targets, None,
  2577. x11_window, CurrentTime);
  2578. // Process events from the queue.
  2579. while (true) {
  2580. if (!_wait_for_events()) {
  2581. // Error or timeout, abort.
  2582. break;
  2583. }
  2584. // Non-blocking wait for next event and remove it from the queue.
  2585. XEvent ev;
  2586. while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) {
  2587. switch (ev.type) {
  2588. case SelectionRequest:
  2589. _handle_selection_request_event(&(ev.xselectionrequest));
  2590. break;
  2591. case SelectionNotify: {
  2592. if (ev.xselection.target == save_targets) {
  2593. // Once SelectionNotify is received, we're done whether it succeeded or not.
  2594. return;
  2595. }
  2596. break;
  2597. }
  2598. }
  2599. }
  2600. }
  2601. }
  2602. String OS_X11::get_name() const {
  2603. return "X11";
  2604. }
  2605. Error OS_X11::shell_open(String p_uri) {
  2606. Error ok;
  2607. int err_code;
  2608. List<String> args;
  2609. args.push_back(p_uri);
  2610. // Agnostic
  2611. ok = execute("xdg-open", args, true, NULL, NULL, &err_code);
  2612. if (ok == OK && !err_code) {
  2613. return OK;
  2614. } else if (err_code == 2) {
  2615. return ERR_FILE_NOT_FOUND;
  2616. }
  2617. // GNOME
  2618. args.push_front("open"); // The command is `gio open`, so we need to add it to args
  2619. ok = execute("gio", args, true, NULL, NULL, &err_code);
  2620. if (ok == OK && !err_code) {
  2621. return OK;
  2622. } else if (err_code == 2) {
  2623. return ERR_FILE_NOT_FOUND;
  2624. }
  2625. args.pop_front();
  2626. ok = execute("gvfs-open", args, true, NULL, NULL, &err_code);
  2627. if (ok == OK && !err_code) {
  2628. return OK;
  2629. } else if (err_code == 2) {
  2630. return ERR_FILE_NOT_FOUND;
  2631. }
  2632. // KDE
  2633. ok = execute("kde-open5", args, true, NULL, NULL, &err_code);
  2634. if (ok == OK && !err_code) {
  2635. return OK;
  2636. }
  2637. ok = execute("kde-open", args, true, NULL, NULL, &err_code);
  2638. return !err_code ? ok : FAILED;
  2639. }
  2640. bool OS_X11::_check_internal_feature_support(const String &p_feature) {
  2641. return p_feature == "pc";
  2642. }
  2643. String OS_X11::get_config_path() const {
  2644. if (has_environment("XDG_CONFIG_HOME")) {
  2645. return get_environment("XDG_CONFIG_HOME");
  2646. } else if (has_environment("HOME")) {
  2647. return get_environment("HOME").plus_file(".config");
  2648. } else {
  2649. return ".";
  2650. }
  2651. }
  2652. String OS_X11::get_data_path() const {
  2653. if (has_environment("XDG_DATA_HOME")) {
  2654. return get_environment("XDG_DATA_HOME");
  2655. } else if (has_environment("HOME")) {
  2656. return get_environment("HOME").plus_file(".local/share");
  2657. } else {
  2658. return get_config_path();
  2659. }
  2660. }
  2661. String OS_X11::get_cache_path() const {
  2662. if (has_environment("XDG_CACHE_HOME")) {
  2663. return get_environment("XDG_CACHE_HOME");
  2664. } else if (has_environment("HOME")) {
  2665. return get_environment("HOME").plus_file(".cache");
  2666. } else {
  2667. return get_config_path();
  2668. }
  2669. }
  2670. String OS_X11::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  2671. String xdgparam;
  2672. switch (p_dir) {
  2673. case SYSTEM_DIR_DESKTOP: {
  2674. xdgparam = "DESKTOP";
  2675. } break;
  2676. case SYSTEM_DIR_DCIM: {
  2677. xdgparam = "PICTURES";
  2678. } break;
  2679. case SYSTEM_DIR_DOCUMENTS: {
  2680. xdgparam = "DOCUMENTS";
  2681. } break;
  2682. case SYSTEM_DIR_DOWNLOADS: {
  2683. xdgparam = "DOWNLOAD";
  2684. } break;
  2685. case SYSTEM_DIR_MOVIES: {
  2686. xdgparam = "VIDEOS";
  2687. } break;
  2688. case SYSTEM_DIR_MUSIC: {
  2689. xdgparam = "MUSIC";
  2690. } break;
  2691. case SYSTEM_DIR_PICTURES: {
  2692. xdgparam = "PICTURES";
  2693. } break;
  2694. case SYSTEM_DIR_RINGTONES: {
  2695. xdgparam = "MUSIC";
  2696. } break;
  2697. }
  2698. String pipe;
  2699. List<String> arg;
  2700. arg.push_back(xdgparam);
  2701. Error err = const_cast<OS_X11 *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe);
  2702. if (err != OK)
  2703. return ".";
  2704. return pipe.strip_edges();
  2705. }
  2706. void OS_X11::move_window_to_foreground() {
  2707. XEvent xev;
  2708. Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
  2709. memset(&xev, 0, sizeof(xev));
  2710. xev.type = ClientMessage;
  2711. xev.xclient.window = x11_window;
  2712. xev.xclient.message_type = net_active_window;
  2713. xev.xclient.format = 32;
  2714. xev.xclient.data.l[0] = 1;
  2715. xev.xclient.data.l[1] = CurrentTime;
  2716. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2717. XFlush(x11_display);
  2718. }
  2719. void OS_X11::set_cursor_shape(CursorShape p_shape) {
  2720. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2721. if (p_shape == current_cursor) {
  2722. return;
  2723. }
  2724. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2725. if (cursors[p_shape] != None) {
  2726. XDefineCursor(x11_display, x11_window, cursors[p_shape]);
  2727. } else if (cursors[CURSOR_ARROW] != None) {
  2728. XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]);
  2729. }
  2730. }
  2731. current_cursor = p_shape;
  2732. }
  2733. OS::CursorShape OS_X11::get_cursor_shape() const {
  2734. return current_cursor;
  2735. }
  2736. void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2737. if (p_cursor.is_valid()) {
  2738. Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape);
  2739. if (cursor_c) {
  2740. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  2741. set_cursor_shape(p_shape);
  2742. return;
  2743. }
  2744. cursors_cache.erase(p_shape);
  2745. }
  2746. Ref<Texture> texture = p_cursor;
  2747. Ref<AtlasTexture> atlas_texture = p_cursor;
  2748. Ref<Image> image;
  2749. Size2 texture_size;
  2750. Rect2 atlas_rect;
  2751. if (texture.is_valid()) {
  2752. image = texture->get_data();
  2753. }
  2754. if (!image.is_valid() && atlas_texture.is_valid()) {
  2755. texture = atlas_texture->get_atlas();
  2756. atlas_rect.size.width = texture->get_width();
  2757. atlas_rect.size.height = texture->get_height();
  2758. atlas_rect.position.x = atlas_texture->get_region().position.x;
  2759. atlas_rect.position.y = atlas_texture->get_region().position.y;
  2760. texture_size.width = atlas_texture->get_region().size.x;
  2761. texture_size.height = atlas_texture->get_region().size.y;
  2762. } else if (image.is_valid()) {
  2763. texture_size.width = texture->get_width();
  2764. texture_size.height = texture->get_height();
  2765. }
  2766. ERR_FAIL_COND(!texture.is_valid());
  2767. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  2768. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  2769. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  2770. image = texture->get_data();
  2771. ERR_FAIL_COND(!image.is_valid());
  2772. // Create the cursor structure
  2773. XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
  2774. XcursorUInt image_size = texture_size.width * texture_size.height;
  2775. XcursorDim size = sizeof(XcursorPixel) * image_size;
  2776. cursor_image->version = 1;
  2777. cursor_image->size = size;
  2778. cursor_image->xhot = p_hotspot.x;
  2779. cursor_image->yhot = p_hotspot.y;
  2780. // allocate memory to contain the whole file
  2781. cursor_image->pixels = (XcursorPixel *)memalloc(size);
  2782. image->lock();
  2783. for (XcursorPixel index = 0; index < image_size; index++) {
  2784. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  2785. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  2786. if (atlas_texture.is_valid()) {
  2787. column_index = MIN(column_index, atlas_rect.size.width - 1);
  2788. row_index = MIN(row_index, atlas_rect.size.height - 1);
  2789. }
  2790. *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
  2791. }
  2792. image->unlock();
  2793. ERR_FAIL_COND(cursor_image->pixels == NULL);
  2794. // Save it for a further usage
  2795. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
  2796. Vector<Variant> params;
  2797. params.push_back(p_cursor);
  2798. params.push_back(p_hotspot);
  2799. cursors_cache.insert(p_shape, params);
  2800. if (p_shape == current_cursor) {
  2801. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2802. XDefineCursor(x11_display, x11_window, cursors[p_shape]);
  2803. }
  2804. }
  2805. memfree(cursor_image->pixels);
  2806. XcursorImageDestroy(cursor_image);
  2807. } else {
  2808. // Reset to default system cursor
  2809. if (img[p_shape]) {
  2810. cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]);
  2811. }
  2812. CursorShape c = current_cursor;
  2813. current_cursor = CURSOR_MAX;
  2814. set_cursor_shape(c);
  2815. cursors_cache.erase(p_shape);
  2816. }
  2817. }
  2818. void OS_X11::release_rendering_thread() {
  2819. #if defined(OPENGL_ENABLED)
  2820. context_gl->release_current();
  2821. #endif
  2822. }
  2823. void OS_X11::make_rendering_thread() {
  2824. #if defined(OPENGL_ENABLED)
  2825. context_gl->make_current();
  2826. #endif
  2827. }
  2828. void OS_X11::swap_buffers() {
  2829. #if defined(OPENGL_ENABLED)
  2830. context_gl->swap_buffers();
  2831. #endif
  2832. }
  2833. void OS_X11::alert(const String &p_alert, const String &p_title) {
  2834. if (is_no_window_mode_enabled()) {
  2835. print_line("ALERT: " + p_title + ": " + p_alert);
  2836. return;
  2837. }
  2838. const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" };
  2839. String path = get_environment("PATH");
  2840. Vector<String> path_elems = path.split(":", false);
  2841. String program;
  2842. for (int i = 0; i < path_elems.size(); i++) {
  2843. for (uint64_t k = 0; k < sizeof(message_programs) / sizeof(char *); k++) {
  2844. String tested_path = path_elems[i].plus_file(message_programs[k]);
  2845. if (FileAccess::exists(tested_path)) {
  2846. program = tested_path;
  2847. break;
  2848. }
  2849. }
  2850. if (program.length())
  2851. break;
  2852. }
  2853. List<String> args;
  2854. if (program.ends_with("zenity")) {
  2855. args.push_back("--error");
  2856. args.push_back("--width");
  2857. args.push_back("500");
  2858. args.push_back("--title");
  2859. args.push_back(p_title);
  2860. args.push_back("--text");
  2861. args.push_back(p_alert);
  2862. }
  2863. if (program.ends_with("kdialog")) {
  2864. args.push_back("--error");
  2865. args.push_back(p_alert);
  2866. args.push_back("--title");
  2867. args.push_back(p_title);
  2868. }
  2869. if (program.ends_with("Xdialog")) {
  2870. args.push_back("--title");
  2871. args.push_back(p_title);
  2872. args.push_back("--msgbox");
  2873. args.push_back(p_alert);
  2874. args.push_back("0");
  2875. args.push_back("0");
  2876. }
  2877. if (program.ends_with("xmessage")) {
  2878. args.push_back("-center");
  2879. args.push_back("-title");
  2880. args.push_back(p_title);
  2881. args.push_back(p_alert);
  2882. }
  2883. if (program.length()) {
  2884. execute(program, args, true);
  2885. } else {
  2886. print_line(p_alert);
  2887. }
  2888. }
  2889. bool g_set_icon_error = false;
  2890. int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
  2891. g_set_icon_error = true;
  2892. return 0;
  2893. }
  2894. void OS_X11::set_icon(const Ref<Image> &p_icon) {
  2895. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
  2896. Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
  2897. if (p_icon.is_valid()) {
  2898. Ref<Image> img = p_icon->duplicate();
  2899. img->convert(Image::FORMAT_RGBA8);
  2900. while (true) {
  2901. int w = img->get_width();
  2902. int h = img->get_height();
  2903. if (g_set_icon_error) {
  2904. g_set_icon_error = false;
  2905. WARN_PRINT("Icon too large, attempting to resize icon.");
  2906. int new_width, new_height;
  2907. if (w > h) {
  2908. new_width = w / 2;
  2909. new_height = h * new_width / w;
  2910. } else {
  2911. new_height = h / 2;
  2912. new_width = w * new_height / h;
  2913. }
  2914. w = new_width;
  2915. h = new_height;
  2916. if (!w || !h) {
  2917. WARN_PRINT("Unable to set icon.");
  2918. break;
  2919. }
  2920. img->resize(w, h, Image::INTERPOLATE_CUBIC);
  2921. }
  2922. // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
  2923. Vector<long> pd;
  2924. pd.resize(2 + w * h);
  2925. pd.write[0] = w;
  2926. pd.write[1] = h;
  2927. PoolVector<uint8_t>::Read r = img->get_data().read();
  2928. long *wr = &pd.write[2];
  2929. uint8_t const *pr = r.ptr();
  2930. for (int i = 0; i < w * h; i++) {
  2931. long v = 0;
  2932. // A R G B
  2933. v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
  2934. *wr++ = v;
  2935. pr += 4;
  2936. }
  2937. if (net_wm_icon != None) {
  2938. XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
  2939. }
  2940. if (!g_set_icon_error)
  2941. break;
  2942. }
  2943. } else {
  2944. XDeleteProperty(x11_display, x11_window, net_wm_icon);
  2945. }
  2946. XFlush(x11_display);
  2947. XSetErrorHandler(oldHandler);
  2948. }
  2949. void OS_X11::force_process_input() {
  2950. process_xevents(); // get rid of pending events
  2951. #ifdef JOYDEV_ENABLED
  2952. joypad->process_joypads();
  2953. #endif
  2954. }
  2955. void OS_X11::run() {
  2956. force_quit = false;
  2957. if (!main_loop)
  2958. return;
  2959. main_loop->init();
  2960. //uint64_t last_ticks=get_ticks_usec();
  2961. //int frames=0;
  2962. //uint64_t frame=0;
  2963. while (!force_quit) {
  2964. process_xevents(); // get rid of pending events
  2965. #ifdef JOYDEV_ENABLED
  2966. joypad->process_joypads();
  2967. #endif
  2968. if (Main::iteration())
  2969. break;
  2970. };
  2971. main_loop->finish();
  2972. }
  2973. bool OS_X11::is_joy_known(int p_device) {
  2974. return input->is_joy_mapped(p_device);
  2975. }
  2976. String OS_X11::get_joy_guid(int p_device) const {
  2977. return input->get_joy_guid_remapped(p_device);
  2978. }
  2979. void OS_X11::_set_use_vsync(bool p_enable) {
  2980. #if defined(OPENGL_ENABLED)
  2981. if (context_gl)
  2982. context_gl->set_use_vsync(p_enable);
  2983. #endif
  2984. }
  2985. /*
  2986. bool OS_X11::is_vsync_enabled() const {
  2987. if (context_gl)
  2988. return context_gl->is_using_vsync();
  2989. return true;
  2990. }
  2991. */
  2992. void OS_X11::set_context(int p_context) {
  2993. XClassHint *classHint = XAllocClassHint();
  2994. if (classHint) {
  2995. CharString name_str;
  2996. switch (p_context) {
  2997. case CONTEXT_EDITOR:
  2998. name_str = "Godot_Editor";
  2999. break;
  3000. case CONTEXT_PROJECTMAN:
  3001. name_str = "Godot_ProjectList";
  3002. break;
  3003. case CONTEXT_ENGINE:
  3004. name_str = "Godot_Engine";
  3005. break;
  3006. }
  3007. CharString class_str;
  3008. if (p_context == CONTEXT_ENGINE) {
  3009. String config_name = GLOBAL_GET("application/config/name");
  3010. if (config_name.length() == 0) {
  3011. class_str = "Godot_Engine";
  3012. } else {
  3013. class_str = config_name.utf8();
  3014. }
  3015. } else {
  3016. class_str = "Godot";
  3017. }
  3018. classHint->res_class = class_str.ptrw();
  3019. classHint->res_name = name_str.ptrw();
  3020. XSetClassHint(x11_display, x11_window, classHint);
  3021. XFree(classHint);
  3022. }
  3023. }
  3024. OS::PowerState OS_X11::get_power_state() {
  3025. return power_manager->get_power_state();
  3026. }
  3027. int OS_X11::get_power_seconds_left() {
  3028. return power_manager->get_power_seconds_left();
  3029. }
  3030. int OS_X11::get_power_percent_left() {
  3031. return power_manager->get_power_percent_left();
  3032. }
  3033. void OS_X11::disable_crash_handler() {
  3034. crash_handler.disable();
  3035. }
  3036. bool OS_X11::is_disable_crash_handler() const {
  3037. return crash_handler.is_disabled();
  3038. }
  3039. static String get_mountpoint(const String &p_path) {
  3040. struct stat s;
  3041. if (stat(p_path.utf8().get_data(), &s)) {
  3042. return "";
  3043. }
  3044. #ifdef HAVE_MNTENT
  3045. dev_t dev = s.st_dev;
  3046. FILE *fd = setmntent("/proc/mounts", "r");
  3047. if (!fd) {
  3048. return "";
  3049. }
  3050. struct mntent mnt;
  3051. char buf[1024];
  3052. size_t buflen = 1024;
  3053. while (getmntent_r(fd, &mnt, buf, buflen)) {
  3054. if (!stat(mnt.mnt_dir, &s) && s.st_dev == dev) {
  3055. endmntent(fd);
  3056. return String(mnt.mnt_dir);
  3057. }
  3058. }
  3059. endmntent(fd);
  3060. #endif
  3061. return "";
  3062. }
  3063. Error OS_X11::move_to_trash(const String &p_path) {
  3064. String trash_can = "";
  3065. String mnt = get_mountpoint(p_path);
  3066. // If there is a directory "[Mountpoint]/.Trash-[UID]/files", use it as the trash can.
  3067. if (mnt != "") {
  3068. String path(mnt + "/.Trash-" + itos(getuid()) + "/files");
  3069. struct stat s;
  3070. if (!stat(path.utf8().get_data(), &s)) {
  3071. trash_can = path;
  3072. }
  3073. }
  3074. // Otherwise, if ${XDG_DATA_HOME} is defined, use "${XDG_DATA_HOME}/Trash/files" as the trash can.
  3075. if (trash_can == "") {
  3076. char *dhome = getenv("XDG_DATA_HOME");
  3077. if (dhome) {
  3078. trash_can = String(dhome) + "/Trash/files";
  3079. }
  3080. }
  3081. // Otherwise, if ${HOME} is defined, use "${HOME}/.local/share/Trash/files" as the trash can.
  3082. if (trash_can == "") {
  3083. char *home = getenv("HOME");
  3084. if (home) {
  3085. trash_can = String(home) + "/.local/share/Trash/files";
  3086. }
  3087. }
  3088. // Issue an error if none of the previous locations is appropriate for the trash can.
  3089. if (trash_can == "") {
  3090. ERR_PRINTS("move_to_trash: Could not determine the trash can location");
  3091. return FAILED;
  3092. }
  3093. // Create needed directories for decided trash can location.
  3094. DirAccess *dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  3095. Error err = dir_access->make_dir_recursive(trash_can);
  3096. memdelete(dir_access);
  3097. // Issue an error if trash can is not created proprely.
  3098. if (err != OK) {
  3099. ERR_PRINTS("move_to_trash: Could not create the trash can \"" + trash_can + "\"");
  3100. return err;
  3101. }
  3102. // The trash can is successfully created, now move the given resource to it.
  3103. // Do not use DirAccess:rename() because it can't move files across multiple mountpoints.
  3104. List<String> mv_args;
  3105. mv_args.push_back(p_path);
  3106. mv_args.push_back(trash_can);
  3107. int retval;
  3108. err = execute("mv", mv_args, true, NULL, NULL, &retval);
  3109. // Issue an error if "mv" failed to move the given resource to the trash can.
  3110. if (err != OK || retval != 0) {
  3111. ERR_PRINTS("move_to_trash: Could not move the resource \"" + p_path + "\" to the trash can \"" + trash_can + "\"");
  3112. return FAILED;
  3113. }
  3114. return OK;
  3115. }
  3116. OS::LatinKeyboardVariant OS_X11::get_latin_keyboard_variant() const {
  3117. XkbDescRec *xkbdesc = XkbAllocKeyboard();
  3118. ERR_FAIL_COND_V(!xkbdesc, LATIN_KEYBOARD_QWERTY);
  3119. XkbGetNames(x11_display, XkbSymbolsNameMask, xkbdesc);
  3120. ERR_FAIL_COND_V(!xkbdesc->names, LATIN_KEYBOARD_QWERTY);
  3121. ERR_FAIL_COND_V(!xkbdesc->names->symbols, LATIN_KEYBOARD_QWERTY);
  3122. char *layout = XGetAtomName(x11_display, xkbdesc->names->symbols);
  3123. ERR_FAIL_COND_V(!layout, LATIN_KEYBOARD_QWERTY);
  3124. Vector<String> info = String(layout).split("+");
  3125. ERR_FAIL_INDEX_V(1, info.size(), LATIN_KEYBOARD_QWERTY);
  3126. if (info[1].find("colemak") != -1) {
  3127. return LATIN_KEYBOARD_COLEMAK;
  3128. } else if (info[1].find("qwertz") != -1) {
  3129. return LATIN_KEYBOARD_QWERTZ;
  3130. } else if (info[1].find("azerty") != -1) {
  3131. return LATIN_KEYBOARD_AZERTY;
  3132. } else if (info[1].find("qzerty") != -1) {
  3133. return LATIN_KEYBOARD_QZERTY;
  3134. } else if (info[1].find("dvorak") != -1) {
  3135. return LATIN_KEYBOARD_DVORAK;
  3136. } else if (info[1].find("neo") != -1) {
  3137. return LATIN_KEYBOARD_NEO;
  3138. }
  3139. return LATIN_KEYBOARD_QWERTY;
  3140. }
  3141. int OS_X11::keyboard_get_layout_count() const {
  3142. int _group_count = 0;
  3143. XkbDescRec *kbd = XkbAllocKeyboard();
  3144. if (kbd) {
  3145. kbd->dpy = x11_display;
  3146. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  3147. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  3148. const Atom *groups = kbd->names->groups;
  3149. if (kbd->ctrls != NULL) {
  3150. _group_count = kbd->ctrls->num_groups;
  3151. } else {
  3152. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  3153. _group_count++;
  3154. }
  3155. }
  3156. XkbFreeKeyboard(kbd, 0, true);
  3157. }
  3158. return _group_count;
  3159. }
  3160. int OS_X11::keyboard_get_current_layout() const {
  3161. XkbStateRec state;
  3162. XkbGetState(x11_display, XkbUseCoreKbd, &state);
  3163. return state.group;
  3164. }
  3165. void OS_X11::keyboard_set_current_layout(int p_index) {
  3166. ERR_FAIL_INDEX(p_index, keyboard_get_layout_count());
  3167. XkbLockGroup(x11_display, XkbUseCoreKbd, p_index);
  3168. }
  3169. String OS_X11::keyboard_get_layout_language(int p_index) const {
  3170. String ret;
  3171. XkbDescRec *kbd = XkbAllocKeyboard();
  3172. if (kbd) {
  3173. kbd->dpy = x11_display;
  3174. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  3175. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  3176. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  3177. int _group_count = 0;
  3178. const Atom *groups = kbd->names->groups;
  3179. if (kbd->ctrls != NULL) {
  3180. _group_count = kbd->ctrls->num_groups;
  3181. } else {
  3182. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  3183. _group_count++;
  3184. }
  3185. }
  3186. Atom names = kbd->names->symbols;
  3187. if (names != None) {
  3188. char *name = XGetAtomName(x11_display, names);
  3189. Vector<String> info = String(name).split("+");
  3190. if (p_index >= 0 && p_index < _group_count) {
  3191. if (p_index + 1 < info.size()) {
  3192. ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols.
  3193. } else {
  3194. ret = "en"; // No symbol for layout fallback to "en".
  3195. }
  3196. } else {
  3197. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  3198. }
  3199. XFree(name);
  3200. }
  3201. XkbFreeKeyboard(kbd, 0, true);
  3202. }
  3203. return ret.substr(0, 2);
  3204. }
  3205. String OS_X11::keyboard_get_layout_name(int p_index) const {
  3206. String ret;
  3207. XkbDescRec *kbd = XkbAllocKeyboard();
  3208. if (kbd) {
  3209. kbd->dpy = x11_display;
  3210. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  3211. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  3212. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  3213. int _group_count = 0;
  3214. const Atom *groups = kbd->names->groups;
  3215. if (kbd->ctrls != NULL) {
  3216. _group_count = kbd->ctrls->num_groups;
  3217. } else {
  3218. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  3219. _group_count++;
  3220. }
  3221. }
  3222. if (p_index >= 0 && p_index < _group_count) {
  3223. char *full_name = XGetAtomName(x11_display, groups[p_index]);
  3224. ret.parse_utf8(full_name);
  3225. XFree(full_name);
  3226. } else {
  3227. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  3228. }
  3229. XkbFreeKeyboard(kbd, 0, true);
  3230. }
  3231. return ret;
  3232. }
  3233. void OS_X11::update_real_mouse_position() {
  3234. Window root_return, child_return;
  3235. int root_x, root_y, win_x, win_y;
  3236. unsigned int mask_return;
  3237. Bool xquerypointer_result = XQueryPointer(x11_display, x11_window, &root_return, &child_return, &root_x, &root_y,
  3238. &win_x, &win_y, &mask_return);
  3239. if (xquerypointer_result) {
  3240. if (win_x > 0 && win_y > 0 && win_x <= current_videomode.width && win_y <= current_videomode.height) {
  3241. last_mouse_pos.x = win_x;
  3242. last_mouse_pos.y = win_y;
  3243. last_mouse_pos_valid = true;
  3244. input->set_mouse_position(last_mouse_pos);
  3245. }
  3246. }
  3247. }
  3248. OS_X11::OS_X11() {
  3249. #ifdef PULSEAUDIO_ENABLED
  3250. AudioDriverManager::add_driver(&driver_pulseaudio);
  3251. #endif
  3252. #ifdef ALSA_ENABLED
  3253. AudioDriverManager::add_driver(&driver_alsa);
  3254. #endif
  3255. xi.opcode = 0;
  3256. xi.last_relative_time = 0;
  3257. layered_window = false;
  3258. minimized = false;
  3259. window_focused = true;
  3260. xim_style = 0L;
  3261. mouse_mode = MOUSE_MODE_VISIBLE;
  3262. last_position_before_fs = Vector2();
  3263. }