display_server_x11.cpp 161 KB

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