display_server_x11.cpp 110 KB

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