display_server_x11.cpp 152 KB

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