os_x11.cpp 88 KB

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