display_server_x11.cpp 129 KB

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