display_server_x11.cpp 155 KB

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