display_server_x11.cpp 156 KB

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