display_server_x11.cpp 129 KB

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