display_server_x11.cpp 145 KB

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