display_server_x11.cpp 143 KB

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