2
0

display_server_x11.cpp 131 KB

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