display_server_x11.cpp 111 KB

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