display_server_x11.cpp 110 KB

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