display_server_x11.cpp 131 KB

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