display_server_x11.cpp 154 KB

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