display_server_x11.cpp 122 KB

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