display_server_x11.cpp 131 KB

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