display_server_x11.cpp 151 KB

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