display_server_x11.cpp 150 KB

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