display_server_x11.cpp 122 KB

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