display_server_x11.cpp 153 KB

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