display_server_x11.cpp 104 KB

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