display_server_x11.cpp 188 KB

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