display_server_x11.cpp 142 KB

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