display_server_x11.cpp 111 KB

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