2
0

os_x11.cpp 95 KB

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