display_server_x11.cpp 114 KB

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