display_server_x11.cpp 221 KB

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