display_server_x11.cpp 114 KB

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