display_server_x11.cpp 114 KB

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