display_server_x11.cpp 105 KB

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