display_server_x11.cpp 113 KB

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