display_server_x11.cpp 112 KB

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