display_server_x11.cpp 131 KB

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