2
0

os_x11.cpp 89 KB

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