display_server_x11.cpp 123 KB

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