display_server_x11.cpp 153 KB

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