display_server_x11.cpp 113 KB

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