display_server_x11.cpp 184 KB

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