display_server_x11.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095
  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_fullscreen_check(WindowID p_window) const {
  1523. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1524. const WindowData &wd = windows[p_window];
  1525. // Using EWMH -- Extended Window Manager Hints
  1526. Atom property = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1527. Atom type;
  1528. int format;
  1529. unsigned long len;
  1530. unsigned long remaining;
  1531. unsigned char *data = nullptr;
  1532. bool retval = false;
  1533. if (property == None) {
  1534. return retval;
  1535. }
  1536. int result = XGetWindowProperty(
  1537. x11_display,
  1538. wd.x11_window,
  1539. property,
  1540. 0,
  1541. 1024,
  1542. False,
  1543. XA_ATOM,
  1544. &type,
  1545. &format,
  1546. &len,
  1547. &remaining,
  1548. &data);
  1549. if (result == Success) {
  1550. Atom *atoms = (Atom *)data;
  1551. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  1552. for (uint64_t i = 0; i < len; i++) {
  1553. if (atoms[i] == wm_fullscreen) {
  1554. retval = true;
  1555. break;
  1556. }
  1557. }
  1558. XFree(data);
  1559. }
  1560. return retval;
  1561. }
  1562. bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const {
  1563. _THREAD_SAFE_METHOD_
  1564. return _window_maximize_check(p_window, "_NET_WM_ALLOWED_ACTIONS");
  1565. }
  1566. void DisplayServerX11::_set_wm_maximized(WindowID p_window, bool p_enabled) {
  1567. ERR_FAIL_COND(!windows.has(p_window));
  1568. WindowData &wd = windows[p_window];
  1569. // Using EWMH -- Extended Window Manager Hints
  1570. XEvent xev;
  1571. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1572. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1573. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1574. memset(&xev, 0, sizeof(xev));
  1575. xev.type = ClientMessage;
  1576. xev.xclient.window = wd.x11_window;
  1577. xev.xclient.message_type = wm_state;
  1578. xev.xclient.format = 32;
  1579. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1580. xev.xclient.data.l[1] = wm_max_horz;
  1581. xev.xclient.data.l[2] = wm_max_vert;
  1582. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1583. if (p_enabled && window_is_maximize_allowed(p_window)) {
  1584. // Wait for effective resizing (so the GLX context is too).
  1585. // Give up after 0.5s, it's not going to happen on this WM.
  1586. // https://github.com/godotengine/godot/issues/19978
  1587. for (int attempt = 0; window_get_mode(p_window) != WINDOW_MODE_MAXIMIZED && attempt < 50; attempt++) {
  1588. usleep(10000);
  1589. }
  1590. }
  1591. }
  1592. void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) {
  1593. ERR_FAIL_COND(!windows.has(p_window));
  1594. WindowData &wd = windows[p_window];
  1595. if (p_enabled && !window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
  1596. // remove decorations if the window is not already borderless
  1597. Hints hints;
  1598. Atom property;
  1599. hints.flags = 2;
  1600. hints.decorations = 0;
  1601. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1602. if (property != None) {
  1603. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1604. }
  1605. }
  1606. if (p_enabled) {
  1607. // Set the window as resizable to prevent window managers to ignore the fullscreen state flag.
  1608. _update_size_hints(p_window);
  1609. }
  1610. // Using EWMH -- Extended Window Manager Hints
  1611. XEvent xev;
  1612. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1613. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  1614. memset(&xev, 0, sizeof(xev));
  1615. xev.type = ClientMessage;
  1616. xev.xclient.window = wd.x11_window;
  1617. xev.xclient.message_type = wm_state;
  1618. xev.xclient.format = 32;
  1619. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1620. xev.xclient.data.l[1] = wm_fullscreen;
  1621. xev.xclient.data.l[2] = 0;
  1622. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1623. // set bypass compositor hint
  1624. Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
  1625. unsigned long compositing_disable_on = p_enabled ? 1 : 0;
  1626. if (bypass_compositor != None) {
  1627. XChangeProperty(x11_display, wd.x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
  1628. }
  1629. XFlush(x11_display);
  1630. if (!p_enabled) {
  1631. // Reset the non-resizable flags if we un-set these before.
  1632. _update_size_hints(p_window);
  1633. // put back or remove decorations according to the last set borderless state
  1634. Hints hints;
  1635. Atom property;
  1636. hints.flags = 2;
  1637. hints.decorations = wd.borderless ? 0 : 1;
  1638. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1639. if (property != None) {
  1640. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1641. }
  1642. }
  1643. }
  1644. void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) {
  1645. _THREAD_SAFE_METHOD_
  1646. ERR_FAIL_COND(!windows.has(p_window));
  1647. WindowData &wd = windows[p_window];
  1648. WindowMode old_mode = window_get_mode(p_window);
  1649. if (old_mode == p_mode) {
  1650. return; // do nothing
  1651. }
  1652. //remove all "extra" modes
  1653. switch (old_mode) {
  1654. case WINDOW_MODE_WINDOWED: {
  1655. //do nothing
  1656. } break;
  1657. case WINDOW_MODE_MINIMIZED: {
  1658. //Un-Minimize
  1659. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1660. XEvent xev;
  1661. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  1662. memset(&xev, 0, sizeof(xev));
  1663. xev.type = ClientMessage;
  1664. xev.xclient.window = wd.x11_window;
  1665. xev.xclient.message_type = wm_change;
  1666. xev.xclient.format = 32;
  1667. xev.xclient.data.l[0] = WM_NormalState;
  1668. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1669. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1670. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  1671. memset(&xev, 0, sizeof(xev));
  1672. xev.type = ClientMessage;
  1673. xev.xclient.window = wd.x11_window;
  1674. xev.xclient.message_type = wm_state;
  1675. xev.xclient.format = 32;
  1676. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1677. xev.xclient.data.l[1] = wm_hidden;
  1678. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1679. } break;
  1680. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  1681. case WINDOW_MODE_FULLSCREEN: {
  1682. //Remove full-screen
  1683. wd.fullscreen = false;
  1684. _set_wm_fullscreen(p_window, false);
  1685. //un-maximize required for always on top
  1686. bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window);
  1687. window_set_position(wd.last_position_before_fs, p_window);
  1688. if (on_top) {
  1689. _set_wm_maximized(p_window, false);
  1690. }
  1691. } break;
  1692. case WINDOW_MODE_MAXIMIZED: {
  1693. _set_wm_maximized(p_window, false);
  1694. } break;
  1695. }
  1696. switch (p_mode) {
  1697. case WINDOW_MODE_WINDOWED: {
  1698. //do nothing
  1699. } break;
  1700. case WINDOW_MODE_MINIMIZED: {
  1701. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1702. XEvent xev;
  1703. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  1704. memset(&xev, 0, sizeof(xev));
  1705. xev.type = ClientMessage;
  1706. xev.xclient.window = wd.x11_window;
  1707. xev.xclient.message_type = wm_change;
  1708. xev.xclient.format = 32;
  1709. xev.xclient.data.l[0] = WM_IconicState;
  1710. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1711. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1712. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  1713. memset(&xev, 0, sizeof(xev));
  1714. xev.type = ClientMessage;
  1715. xev.xclient.window = wd.x11_window;
  1716. xev.xclient.message_type = wm_state;
  1717. xev.xclient.format = 32;
  1718. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1719. xev.xclient.data.l[1] = wm_hidden;
  1720. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1721. } break;
  1722. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  1723. case WINDOW_MODE_FULLSCREEN: {
  1724. wd.last_position_before_fs = wd.position;
  1725. if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) {
  1726. _set_wm_maximized(p_window, true);
  1727. }
  1728. wd.fullscreen = true;
  1729. _set_wm_fullscreen(p_window, true);
  1730. } break;
  1731. case WINDOW_MODE_MAXIMIZED: {
  1732. _set_wm_maximized(p_window, true);
  1733. } break;
  1734. }
  1735. }
  1736. DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) const {
  1737. _THREAD_SAFE_METHOD_
  1738. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  1739. const WindowData &wd = windows[p_window];
  1740. if (wd.fullscreen) { //if fullscreen, it's not in another mode
  1741. return WINDOW_MODE_FULLSCREEN;
  1742. }
  1743. // Test maximized.
  1744. // Using EWMH -- Extended Window Manager Hints
  1745. if (_window_maximize_check(p_window, "_NET_WM_STATE")) {
  1746. return WINDOW_MODE_MAXIMIZED;
  1747. }
  1748. { // Test minimized.
  1749. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1750. Atom property = XInternAtom(x11_display, "WM_STATE", True);
  1751. if (property == None) {
  1752. return WINDOW_MODE_WINDOWED;
  1753. }
  1754. Atom type;
  1755. int format;
  1756. unsigned long len;
  1757. unsigned long remaining;
  1758. unsigned char *data = nullptr;
  1759. int result = XGetWindowProperty(
  1760. x11_display,
  1761. wd.x11_window,
  1762. property,
  1763. 0,
  1764. 32,
  1765. False,
  1766. AnyPropertyType,
  1767. &type,
  1768. &format,
  1769. &len,
  1770. &remaining,
  1771. &data);
  1772. if (result == Success && data) {
  1773. long *state = (long *)data;
  1774. if (state[0] == WM_IconicState) {
  1775. XFree(data);
  1776. return WINDOW_MODE_MINIMIZED;
  1777. }
  1778. XFree(data);
  1779. }
  1780. }
  1781. // All other discarded, return windowed.
  1782. return WINDOW_MODE_WINDOWED;
  1783. }
  1784. void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  1785. _THREAD_SAFE_METHOD_
  1786. ERR_FAIL_COND(!windows.has(p_window));
  1787. WindowData &wd = windows[p_window];
  1788. switch (p_flag) {
  1789. case WINDOW_FLAG_RESIZE_DISABLED: {
  1790. wd.resize_disabled = p_enabled;
  1791. _update_size_hints(p_window);
  1792. XFlush(x11_display);
  1793. } break;
  1794. case WINDOW_FLAG_BORDERLESS: {
  1795. Hints hints;
  1796. Atom property;
  1797. hints.flags = 2;
  1798. hints.decorations = p_enabled ? 0 : 1;
  1799. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1800. if (property != None) {
  1801. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1802. }
  1803. // Preserve window size
  1804. window_set_size(window_get_size(p_window), p_window);
  1805. wd.borderless = p_enabled;
  1806. } break;
  1807. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1808. ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID, "Can't make a window transient if the 'on top' flag is active.");
  1809. if (p_enabled && wd.fullscreen) {
  1810. _set_wm_maximized(p_window, true);
  1811. }
  1812. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1813. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  1814. XClientMessageEvent xev;
  1815. memset(&xev, 0, sizeof(xev));
  1816. xev.type = ClientMessage;
  1817. xev.window = wd.x11_window;
  1818. xev.message_type = wm_state;
  1819. xev.format = 32;
  1820. xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1821. xev.data.l[1] = wm_above;
  1822. xev.data.l[3] = 1;
  1823. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  1824. if (!p_enabled && !wd.fullscreen) {
  1825. _set_wm_maximized(p_window, false);
  1826. }
  1827. wd.on_top = p_enabled;
  1828. } break;
  1829. case WINDOW_FLAG_TRANSPARENT: {
  1830. //todo reimplement
  1831. } break;
  1832. case WINDOW_FLAG_NO_FOCUS: {
  1833. wd.no_focus = p_enabled;
  1834. } break;
  1835. case WINDOW_FLAG_POPUP: {
  1836. XWindowAttributes xwa;
  1837. XSync(x11_display, False);
  1838. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1839. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  1840. ERR_FAIL_COND_MSG((xwa.map_state == IsViewable) && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  1841. wd.is_popup = p_enabled;
  1842. } break;
  1843. default: {
  1844. }
  1845. }
  1846. }
  1847. bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  1848. _THREAD_SAFE_METHOD_
  1849. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1850. const WindowData &wd = windows[p_window];
  1851. switch (p_flag) {
  1852. case WINDOW_FLAG_RESIZE_DISABLED: {
  1853. return wd.resize_disabled;
  1854. } break;
  1855. case WINDOW_FLAG_BORDERLESS: {
  1856. bool borderless = wd.borderless;
  1857. Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1858. if (prop != None) {
  1859. Atom type;
  1860. int format;
  1861. unsigned long len;
  1862. unsigned long remaining;
  1863. unsigned char *data = nullptr;
  1864. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1865. if (data && (format == 32) && (len >= 5)) {
  1866. borderless = !(reinterpret_cast<Hints *>(data)->decorations);
  1867. }
  1868. if (data) {
  1869. XFree(data);
  1870. }
  1871. }
  1872. }
  1873. return borderless;
  1874. } break;
  1875. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1876. return wd.on_top;
  1877. } break;
  1878. case WINDOW_FLAG_TRANSPARENT: {
  1879. //todo reimplement
  1880. } break;
  1881. case WINDOW_FLAG_NO_FOCUS: {
  1882. return wd.no_focus;
  1883. } break;
  1884. case WINDOW_FLAG_POPUP: {
  1885. return wd.is_popup;
  1886. } break;
  1887. default: {
  1888. }
  1889. }
  1890. return false;
  1891. }
  1892. void DisplayServerX11::window_request_attention(WindowID p_window) {
  1893. _THREAD_SAFE_METHOD_
  1894. ERR_FAIL_COND(!windows.has(p_window));
  1895. const WindowData &wd = windows[p_window];
  1896. // Using EWMH -- Extended Window Manager Hints
  1897. //
  1898. // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
  1899. // Will be unset by the window manager after user react on the request for attention
  1900. XEvent xev;
  1901. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1902. Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
  1903. memset(&xev, 0, sizeof(xev));
  1904. xev.type = ClientMessage;
  1905. xev.xclient.window = wd.x11_window;
  1906. xev.xclient.message_type = wm_state;
  1907. xev.xclient.format = 32;
  1908. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1909. xev.xclient.data.l[1] = wm_attention;
  1910. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1911. XFlush(x11_display);
  1912. }
  1913. void DisplayServerX11::window_move_to_foreground(WindowID p_window) {
  1914. _THREAD_SAFE_METHOD_
  1915. ERR_FAIL_COND(!windows.has(p_window));
  1916. const WindowData &wd = windows[p_window];
  1917. XEvent xev;
  1918. Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
  1919. memset(&xev, 0, sizeof(xev));
  1920. xev.type = ClientMessage;
  1921. xev.xclient.window = wd.x11_window;
  1922. xev.xclient.message_type = net_active_window;
  1923. xev.xclient.format = 32;
  1924. xev.xclient.data.l[0] = 1;
  1925. xev.xclient.data.l[1] = CurrentTime;
  1926. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1927. XFlush(x11_display);
  1928. }
  1929. bool DisplayServerX11::window_can_draw(WindowID p_window) const {
  1930. //this seems to be all that is provided by X11
  1931. return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED;
  1932. }
  1933. bool DisplayServerX11::can_any_window_draw() const {
  1934. _THREAD_SAFE_METHOD_
  1935. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1936. if (window_get_mode(E.key) != WINDOW_MODE_MINIMIZED) {
  1937. return true;
  1938. }
  1939. }
  1940. return false;
  1941. }
  1942. void DisplayServerX11::window_set_ime_active(const bool p_active, WindowID p_window) {
  1943. _THREAD_SAFE_METHOD_
  1944. ERR_FAIL_COND(!windows.has(p_window));
  1945. WindowData &wd = windows[p_window];
  1946. wd.im_active = p_active;
  1947. if (!wd.xic) {
  1948. return;
  1949. }
  1950. // Block events polling while changing input focus
  1951. // because it triggers some event polling internally.
  1952. if (p_active) {
  1953. {
  1954. MutexLock mutex_lock(events_mutex);
  1955. XSetICFocus(wd.xic);
  1956. }
  1957. window_set_ime_position(wd.im_position, p_window);
  1958. } else {
  1959. MutexLock mutex_lock(events_mutex);
  1960. XUnsetICFocus(wd.xic);
  1961. }
  1962. }
  1963. void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  1964. _THREAD_SAFE_METHOD_
  1965. ERR_FAIL_COND(!windows.has(p_window));
  1966. WindowData &wd = windows[p_window];
  1967. wd.im_position = p_pos;
  1968. if (!wd.xic) {
  1969. return;
  1970. }
  1971. ::XPoint spot;
  1972. spot.x = short(p_pos.x);
  1973. spot.y = short(p_pos.y);
  1974. XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, nullptr);
  1975. {
  1976. // Block events polling during this call
  1977. // because it triggers some event polling internally.
  1978. MutexLock mutex_lock(events_mutex);
  1979. XSetICValues(wd.xic, XNPreeditAttributes, preedit_attr, nullptr);
  1980. }
  1981. XFree(preedit_attr);
  1982. }
  1983. void DisplayServerX11::cursor_set_shape(CursorShape p_shape) {
  1984. _THREAD_SAFE_METHOD_
  1985. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1986. if (p_shape == current_cursor) {
  1987. return;
  1988. }
  1989. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1990. if (cursors[p_shape] != None) {
  1991. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1992. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  1993. }
  1994. } else if (cursors[CURSOR_ARROW] != None) {
  1995. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1996. XDefineCursor(x11_display, E.value.x11_window, cursors[CURSOR_ARROW]);
  1997. }
  1998. }
  1999. }
  2000. current_cursor = p_shape;
  2001. }
  2002. DisplayServerX11::CursorShape DisplayServerX11::cursor_get_shape() const {
  2003. return current_cursor;
  2004. }
  2005. void DisplayServerX11::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2006. _THREAD_SAFE_METHOD_
  2007. if (p_cursor.is_valid()) {
  2008. HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
  2009. if (cursor_c) {
  2010. if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
  2011. cursor_set_shape(p_shape);
  2012. return;
  2013. }
  2014. cursors_cache.erase(p_shape);
  2015. }
  2016. Ref<Texture2D> texture = p_cursor;
  2017. Ref<AtlasTexture> atlas_texture = p_cursor;
  2018. Ref<Image> image;
  2019. Size2i texture_size;
  2020. Rect2i atlas_rect;
  2021. if (texture.is_valid()) {
  2022. image = texture->get_image();
  2023. }
  2024. if (!image.is_valid() && atlas_texture.is_valid()) {
  2025. texture = atlas_texture->get_atlas();
  2026. atlas_rect.size.width = texture->get_width();
  2027. atlas_rect.size.height = texture->get_height();
  2028. atlas_rect.position.x = atlas_texture->get_region().position.x;
  2029. atlas_rect.position.y = atlas_texture->get_region().position.y;
  2030. texture_size.width = atlas_texture->get_region().size.x;
  2031. texture_size.height = atlas_texture->get_region().size.y;
  2032. } else if (image.is_valid()) {
  2033. texture_size.width = texture->get_width();
  2034. texture_size.height = texture->get_height();
  2035. }
  2036. ERR_FAIL_COND(!texture.is_valid());
  2037. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  2038. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  2039. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  2040. image = texture->get_image();
  2041. ERR_FAIL_COND(!image.is_valid());
  2042. // Create the cursor structure
  2043. XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
  2044. XcursorUInt image_size = texture_size.width * texture_size.height;
  2045. XcursorDim size = sizeof(XcursorPixel) * image_size;
  2046. cursor_image->version = 1;
  2047. cursor_image->size = size;
  2048. cursor_image->xhot = p_hotspot.x;
  2049. cursor_image->yhot = p_hotspot.y;
  2050. // allocate memory to contain the whole file
  2051. cursor_image->pixels = (XcursorPixel *)memalloc(size);
  2052. for (XcursorPixel index = 0; index < image_size; index++) {
  2053. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  2054. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  2055. if (atlas_texture.is_valid()) {
  2056. column_index = MIN(column_index, atlas_rect.size.width - 1);
  2057. row_index = MIN(row_index, atlas_rect.size.height - 1);
  2058. }
  2059. *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
  2060. }
  2061. ERR_FAIL_COND(cursor_image->pixels == nullptr);
  2062. // Save it for a further usage
  2063. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
  2064. Vector<Variant> params;
  2065. params.push_back(p_cursor);
  2066. params.push_back(p_hotspot);
  2067. cursors_cache.insert(p_shape, params);
  2068. if (p_shape == current_cursor) {
  2069. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2070. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2071. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  2072. }
  2073. }
  2074. }
  2075. memfree(cursor_image->pixels);
  2076. XcursorImageDestroy(cursor_image);
  2077. } else {
  2078. // Reset to default system cursor
  2079. if (img[p_shape]) {
  2080. cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]);
  2081. }
  2082. CursorShape c = current_cursor;
  2083. current_cursor = CURSOR_MAX;
  2084. cursor_set_shape(c);
  2085. cursors_cache.erase(p_shape);
  2086. }
  2087. }
  2088. int DisplayServerX11::keyboard_get_layout_count() const {
  2089. int _group_count = 0;
  2090. XkbDescRec *kbd = XkbAllocKeyboard();
  2091. if (kbd) {
  2092. kbd->dpy = x11_display;
  2093. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2094. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2095. const Atom *groups = kbd->names->groups;
  2096. if (kbd->ctrls != nullptr) {
  2097. _group_count = kbd->ctrls->num_groups;
  2098. } else {
  2099. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2100. _group_count++;
  2101. }
  2102. }
  2103. XkbFreeKeyboard(kbd, 0, true);
  2104. }
  2105. return _group_count;
  2106. }
  2107. int DisplayServerX11::keyboard_get_current_layout() const {
  2108. XkbStateRec state;
  2109. XkbGetState(x11_display, XkbUseCoreKbd, &state);
  2110. return state.group;
  2111. }
  2112. void DisplayServerX11::keyboard_set_current_layout(int p_index) {
  2113. ERR_FAIL_INDEX(p_index, keyboard_get_layout_count());
  2114. XkbLockGroup(x11_display, XkbUseCoreKbd, p_index);
  2115. }
  2116. String DisplayServerX11::keyboard_get_layout_language(int p_index) const {
  2117. String ret;
  2118. XkbDescRec *kbd = XkbAllocKeyboard();
  2119. if (kbd) {
  2120. kbd->dpy = x11_display;
  2121. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2122. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2123. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  2124. int _group_count = 0;
  2125. const Atom *groups = kbd->names->groups;
  2126. if (kbd->ctrls != nullptr) {
  2127. _group_count = kbd->ctrls->num_groups;
  2128. } else {
  2129. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2130. _group_count++;
  2131. }
  2132. }
  2133. Atom names = kbd->names->symbols;
  2134. if (names != None) {
  2135. Vector<String> info = get_atom_name(x11_display, names).split("+");
  2136. if (p_index >= 0 && p_index < _group_count) {
  2137. if (p_index + 1 < info.size()) {
  2138. ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols.
  2139. } else {
  2140. ret = "en"; // No symbol for layout fallback to "en".
  2141. }
  2142. } else {
  2143. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  2144. }
  2145. }
  2146. XkbFreeKeyboard(kbd, 0, true);
  2147. }
  2148. return ret.substr(0, 2);
  2149. }
  2150. String DisplayServerX11::keyboard_get_layout_name(int p_index) const {
  2151. String ret;
  2152. XkbDescRec *kbd = XkbAllocKeyboard();
  2153. if (kbd) {
  2154. kbd->dpy = x11_display;
  2155. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2156. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2157. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  2158. int _group_count = 0;
  2159. const Atom *groups = kbd->names->groups;
  2160. if (kbd->ctrls != nullptr) {
  2161. _group_count = kbd->ctrls->num_groups;
  2162. } else {
  2163. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2164. _group_count++;
  2165. }
  2166. }
  2167. if (p_index >= 0 && p_index < _group_count) {
  2168. ret = get_atom_name(x11_display, groups[p_index]);
  2169. } else {
  2170. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  2171. }
  2172. XkbFreeKeyboard(kbd, 0, true);
  2173. }
  2174. return ret;
  2175. }
  2176. Key DisplayServerX11::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2177. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2178. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2179. unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
  2180. KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, 0, 0);
  2181. if (is_ascii_lower_case(xkeysym)) {
  2182. xkeysym -= ('a' - 'A');
  2183. }
  2184. Key key = KeyMappingX11::get_keycode(xkeysym);
  2185. // If not found, fallback to QWERTY.
  2186. // This should match the behavior of the event pump
  2187. if (key == Key::NONE) {
  2188. return p_keycode;
  2189. }
  2190. return (Key)(key | modifiers);
  2191. }
  2192. DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, Window p_window, Atom p_property) {
  2193. Atom actual_type = None;
  2194. int actual_format = 0;
  2195. unsigned long nitems = 0;
  2196. unsigned long bytes_after = 0;
  2197. unsigned char *ret = nullptr;
  2198. // Keep trying to read the property until there are no bytes unread.
  2199. if (p_property != None) {
  2200. int read_bytes = 1024;
  2201. do {
  2202. if (ret != nullptr) {
  2203. XFree(ret);
  2204. }
  2205. XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
  2206. &actual_type, &actual_format, &nitems, &bytes_after,
  2207. &ret);
  2208. read_bytes *= 2;
  2209. } while (bytes_after != 0);
  2210. }
  2211. Property p = { ret, actual_format, (int)nitems, actual_type };
  2212. return p;
  2213. }
  2214. static Atom pick_target_from_list(Display *p_display, const Atom *p_list, int p_count) {
  2215. static const char *target_type = "text/uri-list";
  2216. for (int i = 0; i < p_count; i++) {
  2217. Atom atom = p_list[i];
  2218. if (atom != None && get_atom_name(p_display, atom) == target_type) {
  2219. return atom;
  2220. }
  2221. }
  2222. return None;
  2223. }
  2224. static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
  2225. static const char *target_type = "text/uri-list";
  2226. if (p_t1 != None && get_atom_name(p_disp, p_t1) == target_type) {
  2227. return p_t1;
  2228. }
  2229. if (p_t2 != None && get_atom_name(p_disp, p_t2) == target_type) {
  2230. return p_t2;
  2231. }
  2232. if (p_t3 != None && get_atom_name(p_disp, p_t3) == target_type) {
  2233. return p_t3;
  2234. }
  2235. return None;
  2236. }
  2237. void DisplayServerX11::_get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
  2238. state->set_shift_pressed((p_x11_state & ShiftMask));
  2239. state->set_ctrl_pressed((p_x11_state & ControlMask));
  2240. state->set_alt_pressed((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt
  2241. state->set_meta_pressed((p_x11_state & Mod4Mask));
  2242. }
  2243. MouseButton DisplayServerX11::_get_mouse_button_state(MouseButton p_x11_button, int p_x11_type) {
  2244. MouseButton mask = mouse_button_to_mask(p_x11_button);
  2245. if (p_x11_type == ButtonPress) {
  2246. last_button_state |= mask;
  2247. } else {
  2248. last_button_state &= ~mask;
  2249. }
  2250. return last_button_state;
  2251. }
  2252. void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) {
  2253. WindowData wd = windows[p_window];
  2254. // X11 functions don't know what const is
  2255. XKeyEvent *xkeyevent = p_event;
  2256. // This code was pretty difficult to write.
  2257. // The docs stink and every toolkit seems to
  2258. // do it in a different way.
  2259. /* Phase 1, obtain a proper keysym */
  2260. // This was also very difficult to figure out.
  2261. // You'd expect you could just use Keysym provided by
  2262. // XKeycodeToKeysym to obtain internationalized
  2263. // input.. WRONG!!
  2264. // you must use XLookupString (???) which not only wastes
  2265. // cycles generating an unnecessary string, but also
  2266. // still works in half the cases. (won't handle deadkeys)
  2267. // For more complex input methods (deadkeys and more advanced)
  2268. // you have to use XmbLookupString (??).
  2269. // So then you have to choose which of both results
  2270. // you want to keep.
  2271. // This is a real bizarreness and cpu waster.
  2272. KeySym keysym_keycode = 0; // keysym used to find a keycode
  2273. KeySym keysym_unicode = 0; // keysym used to find unicode
  2274. // XLookupString returns keysyms usable as nice keycodes.
  2275. char str[256 + 1];
  2276. XKeyEvent xkeyevent_no_mod = *xkeyevent;
  2277. xkeyevent_no_mod.state &= ~ShiftMask;
  2278. xkeyevent_no_mod.state &= ~ControlMask;
  2279. XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr);
  2280. XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr);
  2281. // Meanwhile, XLookupString returns keysyms useful for unicode.
  2282. if (!xmbstring) {
  2283. // keep a temporary buffer for the string
  2284. xmbstring = (char *)memalloc(sizeof(char) * 8);
  2285. xmblen = 8;
  2286. }
  2287. if (xkeyevent->type == KeyPress && wd.xic) {
  2288. Status status;
  2289. #ifdef X_HAVE_UTF8_STRING
  2290. int utf8len = 8;
  2291. char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
  2292. int utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2293. utf8len - 1, &keysym_unicode, &status);
  2294. if (status == XBufferOverflow) {
  2295. utf8len = utf8bytes + 1;
  2296. utf8string = (char *)memrealloc(utf8string, utf8len);
  2297. utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2298. utf8len - 1, &keysym_unicode, &status);
  2299. }
  2300. utf8string[utf8bytes] = '\0';
  2301. if (status == XLookupChars) {
  2302. bool keypress = xkeyevent->type == KeyPress;
  2303. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2304. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2305. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2306. keycode -= 'a' - 'A';
  2307. }
  2308. String tmp;
  2309. tmp.parse_utf8(utf8string, utf8bytes);
  2310. for (int i = 0; i < tmp.length(); i++) {
  2311. Ref<InputEventKey> k;
  2312. k.instantiate();
  2313. if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
  2314. continue;
  2315. }
  2316. if (keycode == Key::NONE) {
  2317. keycode = (Key)physical_keycode;
  2318. }
  2319. _get_key_modifier_state(xkeyevent->state, k);
  2320. k->set_window_id(p_window);
  2321. k->set_unicode(tmp[i]);
  2322. k->set_pressed(keypress);
  2323. k->set_keycode(keycode);
  2324. k->set_physical_keycode((Key)physical_keycode);
  2325. k->set_echo(false);
  2326. if (k->get_keycode() == Key::BACKTAB) {
  2327. //make it consistent across platforms.
  2328. k->set_keycode(Key::TAB);
  2329. k->set_physical_keycode(Key::TAB);
  2330. k->set_shift_pressed(true);
  2331. }
  2332. Input::get_singleton()->parse_input_event(k);
  2333. }
  2334. memfree(utf8string);
  2335. return;
  2336. }
  2337. memfree(utf8string);
  2338. #else
  2339. do {
  2340. int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
  2341. xmbstring[mnbytes] = '\0';
  2342. if (status == XBufferOverflow) {
  2343. xmblen = mnbytes + 1;
  2344. xmbstring = (char *)memrealloc(xmbstring, xmblen);
  2345. }
  2346. } while (status == XBufferOverflow);
  2347. #endif
  2348. }
  2349. /* Phase 2, obtain a Godot keycode from the keysym */
  2350. // KeyMappingX11 just translated the X11 keysym to a PIGUI
  2351. // keysym, so it works in all platforms the same.
  2352. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2353. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2354. /* Phase 3, obtain a unicode character from the keysym */
  2355. // KeyMappingX11 also translates keysym to unicode.
  2356. // It does a binary search on a table to translate
  2357. // most properly.
  2358. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
  2359. /* Phase 4, determine if event must be filtered */
  2360. // This seems to be a side-effect of using XIM.
  2361. // XFilterEvent looks like a core X11 function,
  2362. // but it's actually just used to see if we must
  2363. // ignore a deadkey, or events XIM determines
  2364. // must not reach the actual gui.
  2365. // Guess it was a design problem of the extension
  2366. bool keypress = xkeyevent->type == KeyPress;
  2367. if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {
  2368. return;
  2369. }
  2370. if (keycode == Key::NONE) {
  2371. keycode = (Key)physical_keycode;
  2372. }
  2373. /* Phase 5, determine modifier mask */
  2374. // No problems here, except I had no way to
  2375. // know Mod1 was ALT and Mod4 was META (applekey/winkey)
  2376. // just tried Mods until i found them.
  2377. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask));
  2378. Ref<InputEventKey> k;
  2379. k.instantiate();
  2380. k->set_window_id(p_window);
  2381. _get_key_modifier_state(xkeyevent->state, k);
  2382. /* Phase 6, determine echo character */
  2383. // Echo characters in X11 are a keyrelease and a keypress
  2384. // one after the other with the (almot) same timestamp.
  2385. // To detect them, i compare to the next event in list and
  2386. // check that their difference in time is below a threshold.
  2387. if (xkeyevent->type != KeyPress) {
  2388. p_echo = false;
  2389. // make sure there are events pending,
  2390. // so this call won't block.
  2391. if (p_event_index + 1 < p_events.size()) {
  2392. XEvent &peek_event = p_events[p_event_index + 1];
  2393. // I'm using a threshold of 5 msecs,
  2394. // since sometimes there seems to be a little
  2395. // jitter. I'm still not convinced that all this approach
  2396. // is correct, but the xorg developers are
  2397. // not very helpful today.
  2398. #define ABSDIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y)))
  2399. ::Time threshold = ABSDIFF(peek_event.xkey.time, xkeyevent->time);
  2400. #undef ABSDIFF
  2401. if (peek_event.type == KeyPress && threshold < 5) {
  2402. KeySym rk;
  2403. XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr);
  2404. if (rk == keysym_keycode) {
  2405. // Consume to next event.
  2406. ++p_event_index;
  2407. _handle_key_event(p_window, (XKeyEvent *)&peek_event, p_events, p_event_index, true);
  2408. return; //ignore current, echo next
  2409. }
  2410. }
  2411. // use the time from peek_event so it always works
  2412. }
  2413. // save the time to check for echo when keypress happens
  2414. }
  2415. /* Phase 7, send event to Window */
  2416. k->set_pressed(keypress);
  2417. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2418. keycode -= int('a' - 'A');
  2419. }
  2420. k->set_keycode(keycode);
  2421. k->set_physical_keycode((Key)physical_keycode);
  2422. k->set_unicode(unicode);
  2423. k->set_echo(p_echo);
  2424. if (k->get_keycode() == Key::BACKTAB) {
  2425. //make it consistent across platforms.
  2426. k->set_keycode(Key::TAB);
  2427. k->set_physical_keycode(Key::TAB);
  2428. k->set_shift_pressed(true);
  2429. }
  2430. //don't set mod state if modifier keys are released by themselves
  2431. //else event.is_action() will not work correctly here
  2432. if (!k->is_pressed()) {
  2433. if (k->get_keycode() == Key::SHIFT) {
  2434. k->set_shift_pressed(false);
  2435. } else if (k->get_keycode() == Key::CTRL) {
  2436. k->set_ctrl_pressed(false);
  2437. } else if (k->get_keycode() == Key::ALT) {
  2438. k->set_alt_pressed(false);
  2439. } else if (k->get_keycode() == Key::META) {
  2440. k->set_meta_pressed(false);
  2441. }
  2442. }
  2443. bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_keycode());
  2444. if (k->is_pressed()) {
  2445. if (last_is_pressed) {
  2446. k->set_echo(true);
  2447. }
  2448. }
  2449. Input::get_singleton()->parse_input_event(k);
  2450. }
  2451. Atom DisplayServerX11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property, Atom p_selection) const {
  2452. if (p_target == XInternAtom(x11_display, "TARGETS", 0)) {
  2453. // Request to list all supported targets.
  2454. Atom data[9];
  2455. data[0] = XInternAtom(x11_display, "TARGETS", 0);
  2456. data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0);
  2457. data[2] = XInternAtom(x11_display, "MULTIPLE", 0);
  2458. data[3] = XInternAtom(x11_display, "UTF8_STRING", 0);
  2459. data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
  2460. data[5] = XInternAtom(x11_display, "TEXT", 0);
  2461. data[6] = XA_STRING;
  2462. data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
  2463. data[8] = XInternAtom(x11_display, "text/plain", 0);
  2464. XChangeProperty(x11_display,
  2465. p_requestor,
  2466. p_property,
  2467. XA_ATOM,
  2468. 32,
  2469. PropModeReplace,
  2470. (unsigned char *)&data,
  2471. sizeof(data) / sizeof(data[0]));
  2472. return p_property;
  2473. } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) {
  2474. // Request to check if SAVE_TARGETS is supported, nothing special to do.
  2475. XChangeProperty(x11_display,
  2476. p_requestor,
  2477. p_property,
  2478. XInternAtom(x11_display, "NULL", False),
  2479. 32,
  2480. PropModeReplace,
  2481. nullptr,
  2482. 0);
  2483. return p_property;
  2484. } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
  2485. p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
  2486. p_target == XInternAtom(x11_display, "TEXT", 0) ||
  2487. p_target == XA_STRING ||
  2488. p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
  2489. p_target == XInternAtom(x11_display, "text/plain", 0)) {
  2490. // Directly using internal clipboard because we know our window
  2491. // is the owner during a selection request.
  2492. CharString clip;
  2493. static const char *target_type = "PRIMARY";
  2494. if (p_selection != None && get_atom_name(x11_display, p_selection) == target_type) {
  2495. clip = internal_clipboard_primary.utf8();
  2496. } else {
  2497. clip = internal_clipboard.utf8();
  2498. }
  2499. XChangeProperty(x11_display,
  2500. p_requestor,
  2501. p_property,
  2502. p_target,
  2503. 8,
  2504. PropModeReplace,
  2505. (unsigned char *)clip.get_data(),
  2506. clip.length());
  2507. return p_property;
  2508. } else {
  2509. char *target_name = XGetAtomName(x11_display, p_target);
  2510. printf("Target '%s' not supported.\n", target_name);
  2511. if (target_name) {
  2512. XFree(target_name);
  2513. }
  2514. return None;
  2515. }
  2516. }
  2517. void DisplayServerX11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const {
  2518. XEvent respond;
  2519. if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) {
  2520. // Request for multiple target conversions at once.
  2521. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False);
  2522. respond.xselection.property = None;
  2523. Atom type;
  2524. int format;
  2525. unsigned long len;
  2526. unsigned long remaining;
  2527. unsigned char *data = nullptr;
  2528. if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) {
  2529. if ((len >= 2) && data) {
  2530. Atom *targets = (Atom *)data;
  2531. for (uint64_t i = 0; i < len; i += 2) {
  2532. Atom target = targets[i];
  2533. Atom &property = targets[i + 1];
  2534. property = _process_selection_request_target(target, p_event->requestor, property, p_event->selection);
  2535. }
  2536. XChangeProperty(x11_display,
  2537. p_event->requestor,
  2538. p_event->property,
  2539. atom_pair,
  2540. 32,
  2541. PropModeReplace,
  2542. (unsigned char *)targets,
  2543. len);
  2544. respond.xselection.property = p_event->property;
  2545. }
  2546. XFree(data);
  2547. }
  2548. } else {
  2549. // Request for target conversion.
  2550. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property, p_event->selection);
  2551. }
  2552. respond.xselection.type = SelectionNotify;
  2553. respond.xselection.display = p_event->display;
  2554. respond.xselection.requestor = p_event->requestor;
  2555. respond.xselection.selection = p_event->selection;
  2556. respond.xselection.target = p_event->target;
  2557. respond.xselection.time = p_event->time;
  2558. XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond);
  2559. XFlush(x11_display);
  2560. }
  2561. void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data,
  2562. ::XPointer call_data) {
  2563. WARN_PRINT("Input method stopped");
  2564. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  2565. ds->xim = nullptr;
  2566. for (KeyValue<WindowID, WindowData> &E : ds->windows) {
  2567. E.value.xic = nullptr;
  2568. }
  2569. }
  2570. void DisplayServerX11::_window_changed(XEvent *event) {
  2571. WindowID window_id = MAIN_WINDOW_ID;
  2572. // Assign the event to the relevant window
  2573. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2574. if (event->xany.window == E.value.x11_window) {
  2575. window_id = E.key;
  2576. break;
  2577. }
  2578. }
  2579. Rect2i new_rect;
  2580. WindowData &wd = windows[window_id];
  2581. if (wd.x11_window != event->xany.window) { // Check if the correct window, in case it was not main window or anything else
  2582. return;
  2583. }
  2584. {
  2585. //the position in xconfigure is not useful here, obtain it manually
  2586. int x, y;
  2587. Window child;
  2588. XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  2589. new_rect.position.x = x;
  2590. new_rect.position.y = y;
  2591. new_rect.size.width = event->xconfigure.width;
  2592. new_rect.size.height = event->xconfigure.height;
  2593. }
  2594. if (new_rect == Rect2i(wd.position, wd.size)) {
  2595. return;
  2596. }
  2597. if (wd.xic) {
  2598. // Not portable.
  2599. window_set_ime_position(Point2(0, 1));
  2600. }
  2601. wd.position = new_rect.position;
  2602. wd.size = new_rect.size;
  2603. #if defined(VULKAN_ENABLED)
  2604. if (context_vulkan) {
  2605. context_vulkan->window_resize(window_id, wd.size.width, wd.size.height);
  2606. }
  2607. #endif
  2608. #if defined(GLES3_ENABLED)
  2609. if (gl_manager) {
  2610. gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
  2611. }
  2612. #endif
  2613. if (!wd.rect_changed_callback.is_null()) {
  2614. Rect2i r = new_rect;
  2615. Variant rect = r;
  2616. Variant *rectp = &rect;
  2617. Variant ret;
  2618. Callable::CallError ce;
  2619. wd.rect_changed_callback.callp((const Variant **)&rectp, 1, ret, ce);
  2620. }
  2621. }
  2622. void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  2623. static_cast<DisplayServerX11 *>(get_singleton())->_dispatch_input_event(p_event);
  2624. }
  2625. void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  2626. Variant ev = p_event;
  2627. Variant *evp = &ev;
  2628. Variant ret;
  2629. Callable::CallError ce;
  2630. {
  2631. List<WindowID>::Element *E = popup_list.back();
  2632. if (E && Object::cast_to<InputEventKey>(*p_event)) {
  2633. // Redirect keyboard input to active popup.
  2634. if (windows.has(E->get())) {
  2635. Callable callable = windows[E->get()].input_event_callback;
  2636. if (callable.is_valid()) {
  2637. callable.callp((const Variant **)&evp, 1, ret, ce);
  2638. }
  2639. }
  2640. return;
  2641. }
  2642. }
  2643. Ref<InputEventFromWindow> event_from_window = p_event;
  2644. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  2645. // Send to a single window.
  2646. if (windows.has(event_from_window->get_window_id())) {
  2647. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  2648. if (callable.is_valid()) {
  2649. callable.callp((const Variant **)&evp, 1, ret, ce);
  2650. }
  2651. }
  2652. } else {
  2653. // Send to all windows.
  2654. for (KeyValue<WindowID, WindowData> &E : windows) {
  2655. Callable callable = E.value.input_event_callback;
  2656. if (callable.is_valid()) {
  2657. callable.callp((const Variant **)&evp, 1, ret, ce);
  2658. }
  2659. }
  2660. }
  2661. }
  2662. void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  2663. if (!wd.event_callback.is_null()) {
  2664. Variant event = int(p_event);
  2665. Variant *eventp = &event;
  2666. Variant ret;
  2667. Callable::CallError ce;
  2668. wd.event_callback.callp((const Variant **)&eventp, 1, ret, ce);
  2669. }
  2670. }
  2671. void DisplayServerX11::_poll_events_thread(void *ud) {
  2672. DisplayServerX11 *display_server = static_cast<DisplayServerX11 *>(ud);
  2673. display_server->_poll_events();
  2674. }
  2675. Bool DisplayServerX11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) {
  2676. // Just accept all events.
  2677. return True;
  2678. }
  2679. bool DisplayServerX11::_wait_for_events() const {
  2680. int x11_fd = ConnectionNumber(x11_display);
  2681. fd_set in_fds;
  2682. XFlush(x11_display);
  2683. FD_ZERO(&in_fds);
  2684. FD_SET(x11_fd, &in_fds);
  2685. struct timeval tv;
  2686. tv.tv_usec = 0;
  2687. tv.tv_sec = 1;
  2688. // Wait for next event or timeout.
  2689. int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv);
  2690. if (num_ready_fds > 0) {
  2691. // Event received.
  2692. return true;
  2693. } else {
  2694. // Error or timeout.
  2695. if (num_ready_fds < 0) {
  2696. ERR_PRINT("_wait_for_events: select error: " + itos(errno));
  2697. }
  2698. return false;
  2699. }
  2700. }
  2701. void DisplayServerX11::_poll_events() {
  2702. while (!events_thread_done.is_set()) {
  2703. _wait_for_events();
  2704. // Process events from the queue.
  2705. {
  2706. MutexLock mutex_lock(events_mutex);
  2707. _check_pending_events(polled_events);
  2708. }
  2709. }
  2710. }
  2711. void DisplayServerX11::_check_pending_events(LocalVector<XEvent> &r_events) {
  2712. // Flush to make sure to gather all pending events.
  2713. XFlush(x11_display);
  2714. // Non-blocking wait for next event and remove it from the queue.
  2715. XEvent ev;
  2716. while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) {
  2717. // Check if the input manager wants to process the event.
  2718. if (XFilterEvent(&ev, None)) {
  2719. // Event has been filtered by the Input Manager,
  2720. // it has to be ignored and a new one will be received.
  2721. continue;
  2722. }
  2723. // Handle selection request events directly in the event thread, because
  2724. // communication through the x server takes several events sent back and forth
  2725. // and we don't want to block other programs while processing only one each frame.
  2726. if (ev.type == SelectionRequest) {
  2727. _handle_selection_request_event(&(ev.xselectionrequest));
  2728. continue;
  2729. }
  2730. r_events.push_back(ev);
  2731. }
  2732. }
  2733. DisplayServer::WindowID DisplayServerX11::window_get_active_popup() const {
  2734. const List<WindowID>::Element *E = popup_list.back();
  2735. if (E) {
  2736. return E->get();
  2737. } else {
  2738. return INVALID_WINDOW_ID;
  2739. }
  2740. }
  2741. void DisplayServerX11::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  2742. _THREAD_SAFE_METHOD_
  2743. ERR_FAIL_COND(!windows.has(p_window));
  2744. WindowData &wd = windows[p_window];
  2745. wd.parent_safe_rect = p_rect;
  2746. }
  2747. Rect2i DisplayServerX11::window_get_popup_safe_rect(WindowID p_window) const {
  2748. _THREAD_SAFE_METHOD_
  2749. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  2750. const WindowData &wd = windows[p_window];
  2751. return wd.parent_safe_rect;
  2752. }
  2753. void DisplayServerX11::popup_open(WindowID p_window) {
  2754. _THREAD_SAFE_METHOD_
  2755. WindowData &wd = windows[p_window];
  2756. if (wd.is_popup) {
  2757. // Find current popup parent, or root popup if new window is not transient.
  2758. List<WindowID>::Element *C = nullptr;
  2759. List<WindowID>::Element *E = popup_list.back();
  2760. while (E) {
  2761. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  2762. C = E;
  2763. E = E->prev();
  2764. } else {
  2765. break;
  2766. }
  2767. }
  2768. if (C) {
  2769. _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  2770. }
  2771. time_since_popup = OS::get_singleton()->get_ticks_msec();
  2772. popup_list.push_back(p_window);
  2773. }
  2774. }
  2775. void DisplayServerX11::popup_close(WindowID p_window) {
  2776. _THREAD_SAFE_METHOD_
  2777. List<WindowID>::Element *E = popup_list.find(p_window);
  2778. while (E) {
  2779. List<WindowID>::Element *F = E->next();
  2780. WindowID win_id = E->get();
  2781. popup_list.erase(E);
  2782. _send_window_event(windows[win_id], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  2783. E = F;
  2784. }
  2785. }
  2786. bool DisplayServerX11::mouse_process_popups() {
  2787. _THREAD_SAFE_METHOD_
  2788. if (popup_list.is_empty()) {
  2789. return false;
  2790. }
  2791. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  2792. if (delta < 250) {
  2793. return false;
  2794. }
  2795. int number_of_screens = XScreenCount(x11_display);
  2796. bool closed = false;
  2797. for (int i = 0; i < number_of_screens; i++) {
  2798. Window root, child;
  2799. int root_x, root_y, win_x, win_y;
  2800. unsigned int mask;
  2801. if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
  2802. XWindowAttributes root_attrs;
  2803. XGetWindowAttributes(x11_display, root, &root_attrs);
  2804. Vector2i pos = Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
  2805. if ((pos != last_mouse_monitor_pos) || (mask != last_mouse_monitor_mask)) {
  2806. if (((mask & Button1Mask) || (mask & Button2Mask) || (mask & Button3Mask) || (mask & Button4Mask) || (mask & Button5Mask))) {
  2807. List<WindowID>::Element *C = nullptr;
  2808. List<WindowID>::Element *E = popup_list.back();
  2809. // Find top popup to close.
  2810. while (E) {
  2811. // Popup window area.
  2812. Rect2i win_rect = Rect2i(window_get_position(E->get()), window_get_size(E->get()));
  2813. // Area of the parent window, which responsible for opening sub-menu.
  2814. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  2815. if (win_rect.has_point(pos)) {
  2816. break;
  2817. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  2818. break;
  2819. } else {
  2820. C = E;
  2821. E = E->prev();
  2822. }
  2823. }
  2824. if (C) {
  2825. _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  2826. closed = true;
  2827. }
  2828. }
  2829. }
  2830. last_mouse_monitor_mask = mask;
  2831. last_mouse_monitor_pos = pos;
  2832. }
  2833. }
  2834. return closed;
  2835. }
  2836. void DisplayServerX11::process_events() {
  2837. _THREAD_SAFE_METHOD_
  2838. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  2839. static int frame = 0;
  2840. ++frame;
  2841. #endif
  2842. bool ignore_events = mouse_process_popups();
  2843. if (app_focused) {
  2844. //verify that one of the windows has focus, else send focus out notification
  2845. bool focus_found = false;
  2846. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2847. if (E.value.focused) {
  2848. focus_found = true;
  2849. break;
  2850. }
  2851. }
  2852. if (!focus_found) {
  2853. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_no_focus;
  2854. if (delta > 250) {
  2855. //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.
  2856. if (OS::get_singleton()->get_main_loop()) {
  2857. DEBUG_LOG_X11("All focus lost, triggering NOTIFICATION_APPLICATION_FOCUS_OUT\n");
  2858. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  2859. }
  2860. app_focused = false;
  2861. }
  2862. } else {
  2863. time_since_no_focus = OS::get_singleton()->get_ticks_msec();
  2864. }
  2865. }
  2866. do_mouse_warp = false;
  2867. // Is the current mouse mode one where it needs to be grabbed.
  2868. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN;
  2869. xi.pressure = 0;
  2870. xi.tilt = Vector2();
  2871. xi.pressure_supported = false;
  2872. LocalVector<XEvent> events;
  2873. {
  2874. // Block events polling while flushing events.
  2875. MutexLock mutex_lock(events_mutex);
  2876. events = polled_events;
  2877. polled_events.clear();
  2878. // Check for more pending events to avoid an extra frame delay.
  2879. _check_pending_events(events);
  2880. }
  2881. for (uint32_t event_index = 0; event_index < events.size(); ++event_index) {
  2882. XEvent &event = events[event_index];
  2883. if (ignore_events) {
  2884. XFreeEventData(x11_display, &event.xcookie);
  2885. continue;
  2886. }
  2887. WindowID window_id = MAIN_WINDOW_ID;
  2888. // Assign the event to the relevant window
  2889. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2890. if (event.xany.window == E.value.x11_window) {
  2891. window_id = E.key;
  2892. break;
  2893. }
  2894. }
  2895. if (XGetEventData(x11_display, &event.xcookie)) {
  2896. if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  2897. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  2898. int index = event_data->detail;
  2899. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  2900. switch (event_data->evtype) {
  2901. case XI_HierarchyChanged:
  2902. case XI_DeviceChanged: {
  2903. _refresh_device_info();
  2904. } break;
  2905. case XI_RawMotion: {
  2906. XIRawEvent *raw_event = (XIRawEvent *)event_data;
  2907. int device_id = raw_event->sourceid;
  2908. // Determine the axis used (called valuators in XInput for some forsaken reason)
  2909. // Mask is a bitmask indicating which axes are involved.
  2910. // We are interested in the values of axes 0 and 1.
  2911. if (raw_event->valuators.mask_len <= 0) {
  2912. break;
  2913. }
  2914. const double *values = raw_event->raw_values;
  2915. double rel_x = 0.0;
  2916. double rel_y = 0.0;
  2917. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) {
  2918. rel_x = *values;
  2919. values++;
  2920. }
  2921. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) {
  2922. rel_y = *values;
  2923. values++;
  2924. }
  2925. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) {
  2926. HashMap<int, Vector2>::Iterator pen_pressure = xi.pen_pressure_range.find(device_id);
  2927. if (pen_pressure) {
  2928. Vector2 pen_pressure_range = pen_pressure->value;
  2929. if (pen_pressure_range != Vector2()) {
  2930. xi.pressure_supported = true;
  2931. xi.pressure = (*values - pen_pressure_range[0]) /
  2932. (pen_pressure_range[1] - pen_pressure_range[0]);
  2933. }
  2934. }
  2935. values++;
  2936. }
  2937. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) {
  2938. HashMap<int, Vector2>::Iterator pen_tilt_x = xi.pen_tilt_x_range.find(device_id);
  2939. if (pen_tilt_x) {
  2940. Vector2 pen_tilt_x_range = pen_tilt_x->value;
  2941. if (pen_tilt_x_range[0] != 0 && *values < 0) {
  2942. xi.tilt.x = *values / -pen_tilt_x_range[0];
  2943. } else if (pen_tilt_x_range[1] != 0) {
  2944. xi.tilt.x = *values / pen_tilt_x_range[1];
  2945. }
  2946. }
  2947. values++;
  2948. }
  2949. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) {
  2950. HashMap<int, Vector2>::Iterator pen_tilt_y = xi.pen_tilt_y_range.find(device_id);
  2951. if (pen_tilt_y) {
  2952. Vector2 pen_tilt_y_range = pen_tilt_y->value;
  2953. if (pen_tilt_y_range[0] != 0 && *values < 0) {
  2954. xi.tilt.y = *values / -pen_tilt_y_range[0];
  2955. } else if (pen_tilt_y_range[1] != 0) {
  2956. xi.tilt.y = *values / pen_tilt_y_range[1];
  2957. }
  2958. }
  2959. values++;
  2960. }
  2961. HashMap<int, bool>::Iterator pen_inverted = xi.pen_inverted_devices.find(device_id);
  2962. if (pen_inverted) {
  2963. xi.pen_inverted = pen_inverted->value;
  2964. }
  2965. // https://bugs.freedesktop.org/show_bug.cgi?id=71609
  2966. // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html
  2967. if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) {
  2968. break; // Flush duplicate to avoid overly fast motion
  2969. }
  2970. xi.old_raw_pos.x = xi.raw_pos.x;
  2971. xi.old_raw_pos.y = xi.raw_pos.y;
  2972. xi.raw_pos.x = rel_x;
  2973. xi.raw_pos.y = rel_y;
  2974. HashMap<int, Vector2>::Iterator abs_info = xi.absolute_devices.find(device_id);
  2975. if (abs_info) {
  2976. // Absolute mode device
  2977. Vector2 mult = abs_info->value;
  2978. xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x;
  2979. xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y;
  2980. } else {
  2981. // Relative mode device
  2982. xi.relative_motion.x = xi.raw_pos.x;
  2983. xi.relative_motion.y = xi.raw_pos.y;
  2984. }
  2985. xi.last_relative_time = raw_event->time;
  2986. } break;
  2987. #ifdef TOUCH_ENABLED
  2988. case XI_TouchBegin:
  2989. case XI_TouchEnd: {
  2990. bool is_begin = event_data->evtype == XI_TouchBegin;
  2991. Ref<InputEventScreenTouch> st;
  2992. st.instantiate();
  2993. st->set_window_id(window_id);
  2994. st->set_index(index);
  2995. st->set_position(pos);
  2996. st->set_pressed(is_begin);
  2997. if (is_begin) {
  2998. if (xi.state.has(index)) { // Defensive
  2999. break;
  3000. }
  3001. xi.state[index] = pos;
  3002. if (xi.state.size() == 1) {
  3003. // X11 may send a motion event when a touch gesture begins, that would result
  3004. // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out
  3005. xi.mouse_pos_to_filter = pos;
  3006. }
  3007. Input::get_singleton()->parse_input_event(st);
  3008. } else {
  3009. if (!xi.state.has(index)) { // Defensive
  3010. break;
  3011. }
  3012. xi.state.erase(index);
  3013. Input::get_singleton()->parse_input_event(st);
  3014. }
  3015. } break;
  3016. case XI_TouchUpdate: {
  3017. HashMap<int, Vector2>::Iterator curr_pos_elem = xi.state.find(index);
  3018. if (!curr_pos_elem) { // Defensive
  3019. break;
  3020. }
  3021. if (curr_pos_elem->value != pos) {
  3022. Ref<InputEventScreenDrag> sd;
  3023. sd.instantiate();
  3024. sd->set_window_id(window_id);
  3025. sd->set_index(index);
  3026. sd->set_position(pos);
  3027. sd->set_relative(pos - curr_pos_elem->value);
  3028. Input::get_singleton()->parse_input_event(sd);
  3029. curr_pos_elem->value = pos;
  3030. }
  3031. } break;
  3032. #endif
  3033. }
  3034. }
  3035. }
  3036. XFreeEventData(x11_display, &event.xcookie);
  3037. switch (event.type) {
  3038. case MapNotify: {
  3039. DEBUG_LOG_X11("[%u] MapNotify window=%lu (%u) \n", frame, event.xmap.window, window_id);
  3040. const WindowData &wd = windows[window_id];
  3041. XWindowAttributes xwa;
  3042. XSync(x11_display, False);
  3043. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3044. // Set focus when menu window is started.
  3045. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  3046. // a subwindow and its parent are both destroyed.
  3047. if ((xwa.map_state == IsViewable) && !wd.no_focus && !wd.is_popup) {
  3048. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  3049. }
  3050. } break;
  3051. case Expose: {
  3052. DEBUG_LOG_X11("[%u] Expose window=%lu (%u), count='%u' \n", frame, event.xexpose.window, window_id, event.xexpose.count);
  3053. windows[window_id].fullscreen = _window_fullscreen_check(window_id);
  3054. Main::force_redraw();
  3055. } break;
  3056. case NoExpose: {
  3057. DEBUG_LOG_X11("[%u] NoExpose drawable=%lu (%u) \n", frame, event.xnoexpose.drawable, window_id);
  3058. windows[window_id].minimized = true;
  3059. } break;
  3060. case VisibilityNotify: {
  3061. DEBUG_LOG_X11("[%u] VisibilityNotify window=%lu (%u), state=%u \n", frame, event.xvisibility.window, window_id, event.xvisibility.state);
  3062. XVisibilityEvent *visibility = (XVisibilityEvent *)&event;
  3063. windows[window_id].minimized = (visibility->state == VisibilityFullyObscured);
  3064. } break;
  3065. case LeaveNotify: {
  3066. DEBUG_LOG_X11("[%u] LeaveNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  3067. if (!mouse_mode_grab) {
  3068. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  3069. }
  3070. } break;
  3071. case EnterNotify: {
  3072. DEBUG_LOG_X11("[%u] EnterNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  3073. if (!mouse_mode_grab) {
  3074. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  3075. }
  3076. } break;
  3077. case FocusIn: {
  3078. DEBUG_LOG_X11("[%u] FocusIn window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  3079. WindowData &wd = windows[window_id];
  3080. last_focused_window = window_id;
  3081. wd.focused = true;
  3082. if (wd.xic) {
  3083. // Block events polling while changing input focus
  3084. // because it triggers some event polling internally.
  3085. MutexLock mutex_lock(events_mutex);
  3086. XSetICFocus(wd.xic);
  3087. }
  3088. // Keep track of focus order for overlapping windows.
  3089. static unsigned int focus_order = 0;
  3090. wd.focus_order = ++focus_order;
  3091. _send_window_event(wd, WINDOW_EVENT_FOCUS_IN);
  3092. if (mouse_mode_grab) {
  3093. // Show and update the cursor if confined and the window regained focus.
  3094. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3095. if (mouse_mode == MOUSE_MODE_CONFINED) {
  3096. XUndefineCursor(x11_display, E.value.x11_window);
  3097. } else if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { // Or re-hide it.
  3098. XDefineCursor(x11_display, E.value.x11_window, null_cursor);
  3099. }
  3100. XGrabPointer(
  3101. x11_display, E.value.x11_window, True,
  3102. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  3103. GrabModeAsync, GrabModeAsync, E.value.x11_window, None, CurrentTime);
  3104. }
  3105. }
  3106. #ifdef TOUCH_ENABLED
  3107. // Grab touch devices to avoid OS gesture interference
  3108. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  3109. XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask);
  3110. }*/
  3111. #endif
  3112. if (!app_focused) {
  3113. if (OS::get_singleton()->get_main_loop()) {
  3114. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  3115. }
  3116. app_focused = true;
  3117. }
  3118. } break;
  3119. case FocusOut: {
  3120. DEBUG_LOG_X11("[%u] FocusOut window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  3121. WindowData &wd = windows[window_id];
  3122. wd.focused = false;
  3123. if (wd.xic) {
  3124. // Block events polling while changing input focus
  3125. // because it triggers some event polling internally.
  3126. MutexLock mutex_lock(events_mutex);
  3127. XUnsetICFocus(wd.xic);
  3128. }
  3129. Input::get_singleton()->release_pressed_events();
  3130. _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT);
  3131. if (mouse_mode_grab) {
  3132. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3133. //dear X11, I try, I really try, but you never work, you do whatever you want.
  3134. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3135. // Show the cursor if we're in captured mode so it doesn't look weird.
  3136. XUndefineCursor(x11_display, E.value.x11_window);
  3137. }
  3138. }
  3139. XUngrabPointer(x11_display, CurrentTime);
  3140. }
  3141. #ifdef TOUCH_ENABLED
  3142. // Ungrab touch devices so input works as usual while we are unfocused
  3143. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  3144. XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime);
  3145. }*/
  3146. // Release every pointer to avoid sticky points
  3147. for (const KeyValue<int, Vector2> &E : xi.state) {
  3148. Ref<InputEventScreenTouch> st;
  3149. st.instantiate();
  3150. st->set_index(E.key);
  3151. st->set_window_id(window_id);
  3152. st->set_position(E.value);
  3153. Input::get_singleton()->parse_input_event(st);
  3154. }
  3155. xi.state.clear();
  3156. #endif
  3157. } break;
  3158. case ConfigureNotify: {
  3159. 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);
  3160. const WindowData &wd = windows[window_id];
  3161. XWindowAttributes xwa;
  3162. XSync(x11_display, False);
  3163. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3164. // Set focus when menu window is re-used.
  3165. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  3166. // a subwindow and its parent are both destroyed.
  3167. if ((xwa.map_state == IsViewable) && !wd.no_focus && !wd.is_popup) {
  3168. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  3169. }
  3170. _window_changed(&event);
  3171. } break;
  3172. case ButtonPress:
  3173. case ButtonRelease: {
  3174. /* exit in case of a mouse button press */
  3175. last_timestamp = event.xbutton.time;
  3176. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3177. event.xbutton.x = last_mouse_pos.x;
  3178. event.xbutton.y = last_mouse_pos.y;
  3179. }
  3180. Ref<InputEventMouseButton> mb;
  3181. mb.instantiate();
  3182. mb->set_window_id(window_id);
  3183. _get_key_modifier_state(event.xbutton.state, mb);
  3184. mb->set_button_index((MouseButton)event.xbutton.button);
  3185. if (mb->get_button_index() == MouseButton::RIGHT) {
  3186. mb->set_button_index(MouseButton::MIDDLE);
  3187. } else if (mb->get_button_index() == MouseButton::MIDDLE) {
  3188. mb->set_button_index(MouseButton::RIGHT);
  3189. }
  3190. mb->set_button_mask(_get_mouse_button_state(mb->get_button_index(), event.xbutton.type));
  3191. mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
  3192. mb->set_global_position(mb->get_position());
  3193. mb->set_pressed((event.type == ButtonPress));
  3194. const WindowData &wd = windows[window_id];
  3195. if (event.type == ButtonPress) {
  3196. DEBUG_LOG_X11("[%u] ButtonPress window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  3197. // Ensure window focus on click.
  3198. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  3199. // a subwindow and its parent are both destroyed.
  3200. if (!wd.no_focus && !wd.is_popup) {
  3201. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  3202. }
  3203. uint64_t diff = OS::get_singleton()->get_ticks_usec() / 1000 - last_click_ms;
  3204. if (mb->get_button_index() == last_click_button_index) {
  3205. if (diff < 400 && Vector2(last_click_pos).distance_to(Vector2(event.xbutton.x, event.xbutton.y)) < 5) {
  3206. last_click_ms = 0;
  3207. last_click_pos = Point2i(-100, -100);
  3208. last_click_button_index = MouseButton::NONE;
  3209. mb->set_double_click(true);
  3210. }
  3211. } else if (mb->get_button_index() < MouseButton::WHEEL_UP || mb->get_button_index() > MouseButton::WHEEL_RIGHT) {
  3212. last_click_button_index = mb->get_button_index();
  3213. }
  3214. if (!mb->is_double_click()) {
  3215. last_click_ms += diff;
  3216. last_click_pos = Point2i(event.xbutton.x, event.xbutton.y);
  3217. }
  3218. } else {
  3219. DEBUG_LOG_X11("[%u] ButtonRelease window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  3220. if (!wd.focused) {
  3221. // Propagate the event to the focused window,
  3222. // because it's received only on the topmost window.
  3223. // Note: This is needed for drag & drop to work between windows,
  3224. // because the engine expects events to keep being processed
  3225. // on the same window dragging started.
  3226. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3227. const WindowData &wd_other = E.value;
  3228. WindowID window_id_other = E.key;
  3229. if (wd_other.focused) {
  3230. if (window_id_other != window_id) {
  3231. int x, y;
  3232. Window child;
  3233. XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xbutton.x, event.xbutton.y, &x, &y, &child);
  3234. mb->set_window_id(window_id_other);
  3235. mb->set_position(Vector2(x, y));
  3236. mb->set_global_position(mb->get_position());
  3237. Input::get_singleton()->parse_input_event(mb);
  3238. }
  3239. break;
  3240. }
  3241. }
  3242. }
  3243. }
  3244. Input::get_singleton()->parse_input_event(mb);
  3245. } break;
  3246. case MotionNotify: {
  3247. // The X11 API requires filtering one-by-one through the motion
  3248. // notify events, in order to figure out which event is the one
  3249. // generated by warping the mouse pointer.
  3250. WindowID focused_window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID;
  3251. while (true) {
  3252. 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) {
  3253. //this is likely the warp event since it was warped here
  3254. center = Vector2(event.xmotion.x, event.xmotion.y);
  3255. break;
  3256. }
  3257. if (event_index + 1 < events.size()) {
  3258. const XEvent &next_event = events[event_index + 1];
  3259. if (next_event.type == MotionNotify) {
  3260. ++event_index;
  3261. event = next_event;
  3262. } else {
  3263. break;
  3264. }
  3265. } else {
  3266. break;
  3267. }
  3268. }
  3269. last_timestamp = event.xmotion.time;
  3270. // Motion is also simple.
  3271. // A little hack is in order
  3272. // to be able to send relative motion events.
  3273. Point2i pos(event.xmotion.x, event.xmotion.y);
  3274. // Avoidance of spurious mouse motion (see handling of touch)
  3275. bool filter = false;
  3276. // Adding some tolerance to match better Point2i to Vector2
  3277. if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) {
  3278. filter = true;
  3279. }
  3280. // Invalidate to avoid filtering a possible legitimate similar event coming later
  3281. xi.mouse_pos_to_filter = Vector2(1e10, 1e10);
  3282. if (filter) {
  3283. break;
  3284. }
  3285. const WindowData &wd = windows[window_id];
  3286. bool focused = wd.focused;
  3287. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3288. if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) {
  3289. break;
  3290. }
  3291. Point2i new_center = pos;
  3292. pos = last_mouse_pos + xi.relative_motion;
  3293. center = new_center;
  3294. do_mouse_warp = focused; // warp the cursor if we're focused in
  3295. }
  3296. if (!last_mouse_pos_valid) {
  3297. last_mouse_pos = pos;
  3298. last_mouse_pos_valid = true;
  3299. }
  3300. // Hackish but relative mouse motion is already handled in the RawMotion event.
  3301. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does).
  3302. // Therefore, RawMotion cannot be the authority on absolute mouse position.
  3303. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion.
  3304. // Therefore, MotionNotify cannot be the authority on relative mouse motion.
  3305. // This means we need to take a combined approach...
  3306. Point2i rel;
  3307. // Only use raw input if in capture mode. Otherwise use the classic behavior.
  3308. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3309. rel = xi.relative_motion;
  3310. } else {
  3311. rel = pos - last_mouse_pos;
  3312. }
  3313. // Reset to prevent lingering motion
  3314. xi.relative_motion.x = 0;
  3315. xi.relative_motion.y = 0;
  3316. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3317. pos = Point2i(windows[focused_window_id].size.width / 2, windows[focused_window_id].size.height / 2);
  3318. }
  3319. Ref<InputEventMouseMotion> mm;
  3320. mm.instantiate();
  3321. mm->set_window_id(window_id);
  3322. if (xi.pressure_supported) {
  3323. mm->set_pressure(xi.pressure);
  3324. } else {
  3325. mm->set_pressure(bool(mouse_get_button_state() & MouseButton::MASK_LEFT) ? 1.0f : 0.0f);
  3326. }
  3327. mm->set_tilt(xi.tilt);
  3328. mm->set_pen_inverted(xi.pen_inverted);
  3329. _get_key_modifier_state(event.xmotion.state, mm);
  3330. mm->set_button_mask((MouseButton)mouse_get_button_state());
  3331. mm->set_position(pos);
  3332. mm->set_global_position(pos);
  3333. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  3334. mm->set_relative(rel);
  3335. last_mouse_pos = pos;
  3336. // printf("rel: %d,%d\n", rel.x, rel.y );
  3337. // Don't propagate the motion event unless we have focus
  3338. // this is so that the relative motion doesn't get messed up
  3339. // after we regain focus.
  3340. if (focused) {
  3341. Input::get_singleton()->parse_input_event(mm);
  3342. } else {
  3343. // Propagate the event to the focused window,
  3344. // because it's received only on the topmost window.
  3345. // Note: This is needed for drag & drop to work between windows,
  3346. // because the engine expects events to keep being processed
  3347. // on the same window dragging started.
  3348. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3349. const WindowData &wd_other = E.value;
  3350. if (wd_other.focused) {
  3351. int x, y;
  3352. Window child;
  3353. XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xmotion.x, event.xmotion.y, &x, &y, &child);
  3354. Point2i pos_focused(x, y);
  3355. mm->set_window_id(E.key);
  3356. mm->set_position(pos_focused);
  3357. mm->set_global_position(pos_focused);
  3358. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  3359. Input::get_singleton()->parse_input_event(mm);
  3360. break;
  3361. }
  3362. }
  3363. }
  3364. } break;
  3365. case KeyPress:
  3366. case KeyRelease: {
  3367. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  3368. if (event.type == KeyPress) {
  3369. 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);
  3370. } else {
  3371. 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);
  3372. }
  3373. #endif
  3374. last_timestamp = event.xkey.time;
  3375. // key event is a little complex, so
  3376. // it will be handled in its own function.
  3377. _handle_key_event(window_id, &event.xkey, events, event_index);
  3378. } break;
  3379. case SelectionNotify:
  3380. if (event.xselection.target == requested) {
  3381. Property p = _read_property(x11_display, windows[window_id].x11_window, XInternAtom(x11_display, "PRIMARY", 0));
  3382. Vector<String> files = String((char *)p.data).split("\n", false);
  3383. XFree(p.data);
  3384. for (int i = 0; i < files.size(); i++) {
  3385. files.write[i] = files[i].replace("file://", "").uri_decode().strip_edges();
  3386. }
  3387. if (!windows[window_id].drop_files_callback.is_null()) {
  3388. Variant v = files;
  3389. Variant *vp = &v;
  3390. Variant ret;
  3391. Callable::CallError ce;
  3392. windows[window_id].drop_files_callback.callp((const Variant **)&vp, 1, ret, ce);
  3393. }
  3394. //Reply that all is well.
  3395. XClientMessageEvent m;
  3396. memset(&m, 0, sizeof(m));
  3397. m.type = ClientMessage;
  3398. m.display = x11_display;
  3399. m.window = xdnd_source_window;
  3400. m.message_type = xdnd_finished;
  3401. m.format = 32;
  3402. m.data.l[0] = windows[window_id].x11_window;
  3403. m.data.l[1] = 1;
  3404. m.data.l[2] = xdnd_action_copy; //We only ever copy.
  3405. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
  3406. }
  3407. break;
  3408. case ClientMessage:
  3409. if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) {
  3410. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  3411. }
  3412. else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
  3413. //File(s) have been dragged over the window, check for supported target (text/uri-list)
  3414. xdnd_version = (event.xclient.data.l[1] >> 24);
  3415. Window source = event.xclient.data.l[0];
  3416. bool more_than_3 = event.xclient.data.l[1] & 1;
  3417. if (more_than_3) {
  3418. Property p = _read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
  3419. requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
  3420. XFree(p.data);
  3421. } else {
  3422. requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
  3423. }
  3424. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
  3425. //xdnd position event, reply with an XDND status message
  3426. //just depending on type of data for now
  3427. XClientMessageEvent m;
  3428. memset(&m, 0, sizeof(m));
  3429. m.type = ClientMessage;
  3430. m.display = event.xclient.display;
  3431. m.window = event.xclient.data.l[0];
  3432. m.message_type = xdnd_status;
  3433. m.format = 32;
  3434. m.data.l[0] = windows[window_id].x11_window;
  3435. m.data.l[1] = (requested != None);
  3436. m.data.l[2] = 0; //empty rectangle
  3437. m.data.l[3] = 0;
  3438. m.data.l[4] = xdnd_action_copy;
  3439. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  3440. XFlush(x11_display);
  3441. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
  3442. if (requested != None) {
  3443. xdnd_source_window = event.xclient.data.l[0];
  3444. if (xdnd_version >= 1) {
  3445. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, event.xclient.data.l[2]);
  3446. } else {
  3447. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, CurrentTime);
  3448. }
  3449. } else {
  3450. //Reply that we're not interested.
  3451. XClientMessageEvent m;
  3452. memset(&m, 0, sizeof(m));
  3453. m.type = ClientMessage;
  3454. m.display = event.xclient.display;
  3455. m.window = event.xclient.data.l[0];
  3456. m.message_type = xdnd_finished;
  3457. m.format = 32;
  3458. m.data.l[0] = windows[window_id].x11_window;
  3459. m.data.l[1] = 0;
  3460. m.data.l[2] = None; //Failed.
  3461. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  3462. }
  3463. }
  3464. break;
  3465. default:
  3466. break;
  3467. }
  3468. }
  3469. XFlush(x11_display);
  3470. if (do_mouse_warp) {
  3471. XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window,
  3472. 0, 0, 0, 0, (int)windows[MAIN_WINDOW_ID].size.width / 2, (int)windows[MAIN_WINDOW_ID].size.height / 2);
  3473. /*
  3474. Window root, child;
  3475. int root_x, root_y;
  3476. int win_x, win_y;
  3477. unsigned int mask;
  3478. XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );
  3479. printf("Root: %d,%d\n", root_x, root_y);
  3480. printf("Win: %d,%d\n", win_x, win_y);
  3481. */
  3482. }
  3483. Input::get_singleton()->flush_buffered_events();
  3484. }
  3485. void DisplayServerX11::release_rendering_thread() {
  3486. #if defined(GLES3_ENABLED)
  3487. if (gl_manager) {
  3488. gl_manager->release_current();
  3489. }
  3490. #endif
  3491. }
  3492. void DisplayServerX11::make_rendering_thread() {
  3493. #if defined(GLES3_ENABLED)
  3494. if (gl_manager) {
  3495. gl_manager->make_current();
  3496. }
  3497. #endif
  3498. }
  3499. void DisplayServerX11::swap_buffers() {
  3500. #if defined(GLES3_ENABLED)
  3501. if (gl_manager) {
  3502. gl_manager->swap_buffers();
  3503. }
  3504. #endif
  3505. }
  3506. void DisplayServerX11::_update_context(WindowData &wd) {
  3507. XClassHint *classHint = XAllocClassHint();
  3508. if (classHint) {
  3509. CharString name_str;
  3510. switch (context) {
  3511. case CONTEXT_EDITOR:
  3512. name_str = "Godot_Editor";
  3513. break;
  3514. case CONTEXT_PROJECTMAN:
  3515. name_str = "Godot_ProjectList";
  3516. break;
  3517. case CONTEXT_ENGINE:
  3518. name_str = "Godot_Engine";
  3519. break;
  3520. }
  3521. CharString class_str;
  3522. if (context == CONTEXT_ENGINE) {
  3523. String config_name = GLOBAL_GET("application/config/name");
  3524. if (config_name.length() == 0) {
  3525. class_str = "Godot_Engine";
  3526. } else {
  3527. class_str = config_name.utf8();
  3528. }
  3529. } else {
  3530. class_str = "Godot";
  3531. }
  3532. classHint->res_class = class_str.ptrw();
  3533. classHint->res_name = name_str.ptrw();
  3534. XSetClassHint(x11_display, wd.x11_window, classHint);
  3535. XFree(classHint);
  3536. }
  3537. }
  3538. void DisplayServerX11::set_context(Context p_context) {
  3539. _THREAD_SAFE_METHOD_
  3540. context = p_context;
  3541. for (KeyValue<WindowID, WindowData> &E : windows) {
  3542. _update_context(E.value);
  3543. }
  3544. }
  3545. void DisplayServerX11::set_native_icon(const String &p_filename) {
  3546. WARN_PRINT("Native icon not supported by this display server.");
  3547. }
  3548. bool g_set_icon_error = false;
  3549. int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
  3550. g_set_icon_error = true;
  3551. return 0;
  3552. }
  3553. void DisplayServerX11::set_icon(const Ref<Image> &p_icon) {
  3554. _THREAD_SAFE_METHOD_
  3555. WindowData &wd = windows[MAIN_WINDOW_ID];
  3556. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
  3557. Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
  3558. if (p_icon.is_valid()) {
  3559. Ref<Image> img = p_icon->duplicate();
  3560. img->convert(Image::FORMAT_RGBA8);
  3561. while (true) {
  3562. int w = img->get_width();
  3563. int h = img->get_height();
  3564. if (g_set_icon_error) {
  3565. g_set_icon_error = false;
  3566. WARN_PRINT("Icon too large, attempting to resize icon.");
  3567. int new_width, new_height;
  3568. if (w > h) {
  3569. new_width = w / 2;
  3570. new_height = h * new_width / w;
  3571. } else {
  3572. new_height = h / 2;
  3573. new_width = w * new_height / h;
  3574. }
  3575. w = new_width;
  3576. h = new_height;
  3577. if (!w || !h) {
  3578. WARN_PRINT("Unable to set icon.");
  3579. break;
  3580. }
  3581. img->resize(w, h, Image::INTERPOLATE_CUBIC);
  3582. }
  3583. // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
  3584. Vector<long> pd;
  3585. pd.resize(2 + w * h);
  3586. pd.write[0] = w;
  3587. pd.write[1] = h;
  3588. const uint8_t *r = img->get_data().ptr();
  3589. long *wr = &pd.write[2];
  3590. uint8_t const *pr = r;
  3591. for (int i = 0; i < w * h; i++) {
  3592. long v = 0;
  3593. // A R G B
  3594. v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
  3595. *wr++ = v;
  3596. pr += 4;
  3597. }
  3598. if (net_wm_icon != None) {
  3599. XChangeProperty(x11_display, wd.x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
  3600. }
  3601. if (!g_set_icon_error) {
  3602. break;
  3603. }
  3604. }
  3605. } else {
  3606. XDeleteProperty(x11_display, wd.x11_window, net_wm_icon);
  3607. }
  3608. XFlush(x11_display);
  3609. XSetErrorHandler(oldHandler);
  3610. }
  3611. void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  3612. _THREAD_SAFE_METHOD_
  3613. #if defined(VULKAN_ENABLED)
  3614. if (context_vulkan) {
  3615. context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
  3616. }
  3617. #endif
  3618. #if defined(GLES3_ENABLED)
  3619. if (gl_manager) {
  3620. gl_manager->set_use_vsync(p_vsync_mode == DisplayServer::VSYNC_ENABLED);
  3621. }
  3622. #endif
  3623. }
  3624. DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const {
  3625. _THREAD_SAFE_METHOD_
  3626. #if defined(VULKAN_ENABLED)
  3627. if (context_vulkan) {
  3628. return context_vulkan->get_vsync_mode(p_window);
  3629. }
  3630. #endif
  3631. #if defined(GLES3_ENABLED)
  3632. if (gl_manager) {
  3633. return gl_manager->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  3634. }
  3635. #endif
  3636. return DisplayServer::VSYNC_ENABLED;
  3637. }
  3638. Vector<String> DisplayServerX11::get_rendering_drivers_func() {
  3639. Vector<String> drivers;
  3640. #ifdef VULKAN_ENABLED
  3641. drivers.push_back("vulkan");
  3642. #endif
  3643. #ifdef GLES3_ENABLED
  3644. drivers.push_back("opengl3");
  3645. #endif
  3646. return drivers;
  3647. }
  3648. 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) {
  3649. DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  3650. if (r_error != OK) {
  3651. OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.\n"
  3652. "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n"
  3653. "If you have updated your graphics drivers recently, try rebooting.",
  3654. "Unable to initialize Video driver");
  3655. }
  3656. return ds;
  3657. }
  3658. DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  3659. //Create window
  3660. long visualMask = VisualScreenMask;
  3661. int numberOfVisuals;
  3662. XVisualInfo vInfoTemplate = {};
  3663. vInfoTemplate.screen = DefaultScreen(x11_display);
  3664. XVisualInfo *visualInfo = XGetVisualInfo(x11_display, visualMask, &vInfoTemplate, &numberOfVisuals);
  3665. Colormap colormap = XCreateColormap(x11_display, RootWindow(x11_display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
  3666. XSetWindowAttributes windowAttributes = {};
  3667. windowAttributes.colormap = colormap;
  3668. windowAttributes.background_pixel = 0xFFFFFFFF;
  3669. windowAttributes.border_pixel = 0;
  3670. windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
  3671. unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;
  3672. WindowID id = window_id_counter++;
  3673. WindowData &wd = windows[id];
  3674. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  3675. wd.no_focus = true;
  3676. }
  3677. if (p_flags & WINDOW_FLAG_POPUP_BIT) {
  3678. wd.is_popup = true;
  3679. }
  3680. // Setup for menu subwindows:
  3681. // - override_redirect forces the WM not to interfere with the window, to avoid delays due to
  3682. // handling decorations and placement.
  3683. // On the other hand, focus changes need to be handled manually when this is set.
  3684. // - save_under is a hint for the WM to keep the content of windows behind to avoid repaint.
  3685. if (wd.is_popup || wd.no_focus) {
  3686. windowAttributes.override_redirect = True;
  3687. windowAttributes.save_under = True;
  3688. valuemask |= CWOverrideRedirect | CWSaveUnder;
  3689. }
  3690. {
  3691. 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);
  3692. // Enable receiving notification when the window is initialized (MapNotify)
  3693. // so the focus can be set at the right time.
  3694. if (!wd.no_focus && !wd.is_popup) {
  3695. XSelectInput(x11_display, wd.x11_window, StructureNotifyMask);
  3696. }
  3697. //associate PID
  3698. // make PID known to X11
  3699. {
  3700. const long pid = OS::get_singleton()->get_process_id();
  3701. Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False);
  3702. if (net_wm_pid != None) {
  3703. XChangeProperty(x11_display, wd.x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
  3704. }
  3705. }
  3706. long im_event_mask = 0;
  3707. {
  3708. XIEventMask all_event_mask;
  3709. XSetWindowAttributes new_attr;
  3710. new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
  3711. ButtonReleaseMask | EnterWindowMask |
  3712. LeaveWindowMask | PointerMotionMask |
  3713. Button1MotionMask |
  3714. Button2MotionMask | Button3MotionMask |
  3715. Button4MotionMask | Button5MotionMask |
  3716. ButtonMotionMask | KeymapStateMask |
  3717. ExposureMask | VisibilityChangeMask |
  3718. StructureNotifyMask |
  3719. SubstructureNotifyMask | SubstructureRedirectMask |
  3720. FocusChangeMask | PropertyChangeMask |
  3721. ColormapChangeMask | OwnerGrabButtonMask |
  3722. im_event_mask;
  3723. XChangeWindowAttributes(x11_display, wd.x11_window, CWEventMask, &new_attr);
  3724. static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  3725. all_event_mask.deviceid = XIAllDevices;
  3726. all_event_mask.mask_len = sizeof(all_mask_data);
  3727. all_event_mask.mask = all_mask_data;
  3728. XISetMask(all_event_mask.mask, XI_HierarchyChanged);
  3729. #ifdef TOUCH_ENABLED
  3730. if (xi.touch_devices.size()) {
  3731. XISetMask(all_event_mask.mask, XI_TouchBegin);
  3732. XISetMask(all_event_mask.mask, XI_TouchUpdate);
  3733. XISetMask(all_event_mask.mask, XI_TouchEnd);
  3734. XISetMask(all_event_mask.mask, XI_TouchOwnership);
  3735. }
  3736. #endif
  3737. XISelectEvents(x11_display, wd.x11_window, &all_event_mask, 1);
  3738. }
  3739. /* set the titlebar name */
  3740. XStoreName(x11_display, wd.x11_window, "Godot");
  3741. XSetWMProtocols(x11_display, wd.x11_window, &wm_delete, 1);
  3742. if (xdnd_aware != None) {
  3743. XChangeProperty(x11_display, wd.x11_window, xdnd_aware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdnd_version, 1);
  3744. }
  3745. if (xim && xim_style) {
  3746. // Block events polling while changing input focus
  3747. // because it triggers some event polling internally.
  3748. MutexLock mutex_lock(events_mutex);
  3749. wd.xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, wd.x11_window, XNFocusWindow, wd.x11_window, (char *)nullptr);
  3750. if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) {
  3751. WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
  3752. XDestroyIC(wd.xic);
  3753. wd.xic = nullptr;
  3754. }
  3755. if (wd.xic) {
  3756. XUnsetICFocus(wd.xic);
  3757. } else {
  3758. WARN_PRINT("XCreateIC couldn't create wd.xic");
  3759. }
  3760. } else {
  3761. wd.xic = nullptr;
  3762. WARN_PRINT("XCreateIC couldn't create wd.xic");
  3763. }
  3764. _update_context(wd);
  3765. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  3766. Hints hints;
  3767. Atom property;
  3768. hints.flags = 2;
  3769. hints.decorations = 0;
  3770. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  3771. if (property != None) {
  3772. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  3773. }
  3774. }
  3775. if (wd.is_popup || wd.no_focus) {
  3776. // Set Utility type to disable fade animations.
  3777. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
  3778. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  3779. if (wt_atom != None && type_atom != None) {
  3780. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  3781. }
  3782. } else {
  3783. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
  3784. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  3785. if (wt_atom != None && type_atom != None) {
  3786. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  3787. }
  3788. }
  3789. _update_size_hints(id);
  3790. #if defined(VULKAN_ENABLED)
  3791. if (context_vulkan) {
  3792. Error err = context_vulkan->window_create(id, p_vsync_mode, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height);
  3793. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan window");
  3794. }
  3795. #endif
  3796. #ifdef GLES3_ENABLED
  3797. if (gl_manager) {
  3798. Error err = gl_manager->window_create(id, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height);
  3799. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL window");
  3800. }
  3801. #endif
  3802. //set_class_hint(x11_display, wd.x11_window);
  3803. XFlush(x11_display);
  3804. XSync(x11_display, False);
  3805. //XSetErrorHandler(oldHandler);
  3806. XFree(visualInfo);
  3807. }
  3808. window_set_mode(p_mode, id);
  3809. //sync size
  3810. {
  3811. XWindowAttributes xwa;
  3812. XSync(x11_display, False);
  3813. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3814. wd.position.x = xwa.x;
  3815. wd.position.y = xwa.y;
  3816. wd.size.width = xwa.width;
  3817. wd.size.height = xwa.height;
  3818. }
  3819. //set cursor
  3820. if (cursors[current_cursor] != None) {
  3821. XDefineCursor(x11_display, wd.x11_window, cursors[current_cursor]);
  3822. }
  3823. return id;
  3824. }
  3825. 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) {
  3826. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3827. r_error = OK;
  3828. for (int i = 0; i < CURSOR_MAX; i++) {
  3829. cursors[i] = None;
  3830. img[i] = nullptr;
  3831. }
  3832. XInitThreads(); //always use threads
  3833. /** XLIB INITIALIZATION **/
  3834. x11_display = XOpenDisplay(nullptr);
  3835. if (!x11_display) {
  3836. ERR_PRINT("X11 Display is not available");
  3837. r_error = ERR_UNAVAILABLE;
  3838. return;
  3839. }
  3840. char *modifiers = nullptr;
  3841. Bool xkb_dar = False;
  3842. XAutoRepeatOn(x11_display);
  3843. xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr);
  3844. // Try to support IME if detectable auto-repeat is supported
  3845. if (xkb_dar == True) {
  3846. #ifdef X_HAVE_UTF8_STRING
  3847. // Xutf8LookupString will be used later instead of XmbLookupString before
  3848. // the multibyte sequences can be converted to unicode string.
  3849. modifiers = XSetLocaleModifiers("");
  3850. #endif
  3851. }
  3852. if (modifiers == nullptr) {
  3853. if (OS::get_singleton()->is_stdout_verbose()) {
  3854. WARN_PRINT("IME is disabled");
  3855. }
  3856. XSetLocaleModifiers("@im=none");
  3857. WARN_PRINT("Error setting locale modifiers");
  3858. }
  3859. const char *err;
  3860. int xrandr_major = 0;
  3861. int xrandr_minor = 0;
  3862. int event_base, error_base;
  3863. xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
  3864. xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
  3865. if (!xrandr_handle) {
  3866. err = dlerror();
  3867. // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2...
  3868. // In case this happens for other X11 platforms in the future, let's give it a try too before failing.
  3869. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY);
  3870. if (!xrandr_handle) {
  3871. fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
  3872. }
  3873. } else {
  3874. XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
  3875. if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
  3876. xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
  3877. if (!xrr_get_monitors) {
  3878. err = dlerror();
  3879. fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
  3880. } else {
  3881. xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
  3882. if (!xrr_free_monitors) {
  3883. err = dlerror();
  3884. fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
  3885. xrr_get_monitors = nullptr;
  3886. }
  3887. }
  3888. }
  3889. }
  3890. if (!_refresh_device_info()) {
  3891. OS::get_singleton()->alert("Your system does not support XInput 2.\n"
  3892. "Please upgrade your distribution.",
  3893. "Unable to initialize XInput");
  3894. r_error = ERR_UNAVAILABLE;
  3895. return;
  3896. }
  3897. xim = XOpenIM(x11_display, nullptr, nullptr, nullptr);
  3898. if (xim == nullptr) {
  3899. WARN_PRINT("XOpenIM failed");
  3900. xim_style = 0L;
  3901. } else {
  3902. ::XIMCallback im_destroy_callback;
  3903. im_destroy_callback.client_data = (::XPointer)(this);
  3904. im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback);
  3905. if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
  3906. nullptr) != nullptr) {
  3907. WARN_PRINT("Error setting XIM destroy callback");
  3908. }
  3909. ::XIMStyles *xim_styles = nullptr;
  3910. xim_style = 0L;
  3911. char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr);
  3912. if (imvalret != nullptr || xim_styles == nullptr) {
  3913. fprintf(stderr, "Input method doesn't support any styles\n");
  3914. }
  3915. if (xim_styles) {
  3916. xim_style = 0L;
  3917. for (int i = 0; i < xim_styles->count_styles; i++) {
  3918. if (xim_styles->supported_styles[i] ==
  3919. (XIMPreeditNothing | XIMStatusNothing)) {
  3920. xim_style = xim_styles->supported_styles[i];
  3921. break;
  3922. }
  3923. }
  3924. XFree(xim_styles);
  3925. }
  3926. XFree(imvalret);
  3927. }
  3928. /* Atom internment */
  3929. wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
  3930. // Set Xdnd (drag & drop) support.
  3931. xdnd_aware = XInternAtom(x11_display, "XdndAware", False);
  3932. xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
  3933. xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
  3934. xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
  3935. xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
  3936. xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
  3937. xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
  3938. xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
  3939. #ifdef SPEECHD_ENABLED
  3940. // Init TTS
  3941. tts = memnew(TTS_Linux);
  3942. #endif
  3943. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3944. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3945. rendering_driver = p_rendering_driver;
  3946. bool driver_found = false;
  3947. #if defined(VULKAN_ENABLED)
  3948. if (rendering_driver == "vulkan") {
  3949. context_vulkan = memnew(VulkanContextX11);
  3950. if (context_vulkan->initialize() != OK) {
  3951. memdelete(context_vulkan);
  3952. context_vulkan = nullptr;
  3953. r_error = ERR_CANT_CREATE;
  3954. ERR_FAIL_MSG("Could not initialize Vulkan");
  3955. }
  3956. driver_found = true;
  3957. }
  3958. #endif
  3959. // Initialize context and rendering device.
  3960. #if defined(GLES3_ENABLED)
  3961. if (rendering_driver == "opengl3") {
  3962. if (getenv("DRI_PRIME") == nullptr) {
  3963. int use_prime = -1;
  3964. if (getenv("PRIMUS_DISPLAY") ||
  3965. getenv("PRIMUS_libGLd") ||
  3966. getenv("PRIMUS_libGLa") ||
  3967. getenv("PRIMUS_libGL") ||
  3968. getenv("PRIMUS_LOAD_GLOBAL") ||
  3969. getenv("BUMBLEBEE_SOCKET")) {
  3970. print_verbose("Optirun/primusrun detected. Skipping GPU detection");
  3971. use_prime = 0;
  3972. }
  3973. // Some tools use fake libGL libraries and have them override the real one using
  3974. // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its
  3975. // runtime and includes system `/lib` and `/lib64`... so ignore Steam.
  3976. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) {
  3977. String ld_library_path(getenv("LD_LIBRARY_PATH"));
  3978. Vector<String> libraries = ld_library_path.split(":");
  3979. for (int i = 0; i < libraries.size(); ++i) {
  3980. if (FileAccess::exists(libraries[i] + "/libGL.so.1") ||
  3981. FileAccess::exists(libraries[i] + "/libGL.so")) {
  3982. print_verbose("Custom libGL override detected. Skipping GPU detection");
  3983. use_prime = 0;
  3984. }
  3985. }
  3986. }
  3987. if (use_prime == -1) {
  3988. print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic.");
  3989. use_prime = detect_prime();
  3990. }
  3991. if (use_prime) {
  3992. print_line("Found discrete GPU, setting DRI_PRIME=1 to use it.");
  3993. print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU.");
  3994. setenv("DRI_PRIME", "1", 1);
  3995. }
  3996. }
  3997. GLManager_X11::ContextType opengl_api_type = GLManager_X11::GLES_3_0_COMPATIBLE;
  3998. gl_manager = memnew(GLManager_X11(p_resolution, opengl_api_type));
  3999. if (gl_manager->initialize() != OK) {
  4000. memdelete(gl_manager);
  4001. gl_manager = nullptr;
  4002. r_error = ERR_UNAVAILABLE;
  4003. return;
  4004. }
  4005. driver_found = true;
  4006. if (true) {
  4007. RasterizerGLES3::make_current();
  4008. } else {
  4009. memdelete(gl_manager);
  4010. gl_manager = nullptr;
  4011. r_error = ERR_UNAVAILABLE;
  4012. return;
  4013. }
  4014. }
  4015. #endif
  4016. if (!driver_found) {
  4017. r_error = ERR_UNAVAILABLE;
  4018. ERR_FAIL_MSG("Video driver not found");
  4019. }
  4020. Point2i window_position(
  4021. (screen_get_size(0).width - p_resolution.width) / 2,
  4022. (screen_get_size(0).height - p_resolution.height) / 2);
  4023. WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution));
  4024. if (main_window == INVALID_WINDOW_ID) {
  4025. r_error = ERR_CANT_CREATE;
  4026. return;
  4027. }
  4028. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  4029. if (p_flags & (1 << i)) {
  4030. window_set_flag(WindowFlags(i), true, main_window);
  4031. }
  4032. }
  4033. show_window(main_window);
  4034. #if defined(VULKAN_ENABLED)
  4035. if (rendering_driver == "vulkan") {
  4036. //temporary
  4037. rendering_device_vulkan = memnew(RenderingDeviceVulkan);
  4038. rendering_device_vulkan->initialize(context_vulkan);
  4039. RendererCompositorRD::make_current();
  4040. }
  4041. #endif
  4042. {
  4043. //set all event master mask
  4044. XIEventMask all_master_event_mask;
  4045. static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  4046. all_master_event_mask.deviceid = XIAllMasterDevices;
  4047. all_master_event_mask.mask_len = sizeof(all_master_mask_data);
  4048. all_master_event_mask.mask = all_master_mask_data;
  4049. XISetMask(all_master_event_mask.mask, XI_DeviceChanged);
  4050. XISetMask(all_master_event_mask.mask, XI_RawMotion);
  4051. XISelectEvents(x11_display, DefaultRootWindow(x11_display), &all_master_event_mask, 1);
  4052. }
  4053. cursor_size = XcursorGetDefaultSize(x11_display);
  4054. cursor_theme = XcursorGetTheme(x11_display);
  4055. if (!cursor_theme) {
  4056. print_verbose("XcursorGetTheme could not get cursor theme");
  4057. cursor_theme = "default";
  4058. }
  4059. for (int i = 0; i < CURSOR_MAX; i++) {
  4060. static const char *cursor_file[] = {
  4061. "left_ptr",
  4062. "xterm",
  4063. "hand2",
  4064. "cross",
  4065. "watch",
  4066. "left_ptr_watch",
  4067. "fleur",
  4068. "dnd-move",
  4069. "crossed_circle",
  4070. "v_double_arrow",
  4071. "h_double_arrow",
  4072. "size_bdiag",
  4073. "size_fdiag",
  4074. "move",
  4075. "row_resize",
  4076. "col_resize",
  4077. "question_arrow"
  4078. };
  4079. img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
  4080. if (!img[i]) {
  4081. const char *fallback = nullptr;
  4082. switch (i) {
  4083. case CURSOR_POINTING_HAND:
  4084. fallback = "pointer";
  4085. break;
  4086. case CURSOR_CROSS:
  4087. fallback = "crosshair";
  4088. break;
  4089. case CURSOR_WAIT:
  4090. fallback = "wait";
  4091. break;
  4092. case CURSOR_BUSY:
  4093. fallback = "progress";
  4094. break;
  4095. case CURSOR_DRAG:
  4096. fallback = "grabbing";
  4097. break;
  4098. case CURSOR_CAN_DROP:
  4099. fallback = "hand1";
  4100. break;
  4101. case CURSOR_FORBIDDEN:
  4102. fallback = "forbidden";
  4103. break;
  4104. case CURSOR_VSIZE:
  4105. fallback = "ns-resize";
  4106. break;
  4107. case CURSOR_HSIZE:
  4108. fallback = "ew-resize";
  4109. break;
  4110. case CURSOR_BDIAGSIZE:
  4111. fallback = "fd_double_arrow";
  4112. break;
  4113. case CURSOR_FDIAGSIZE:
  4114. fallback = "bd_double_arrow";
  4115. break;
  4116. case CURSOR_MOVE:
  4117. img[i] = img[CURSOR_DRAG];
  4118. break;
  4119. case CURSOR_VSPLIT:
  4120. fallback = "sb_v_double_arrow";
  4121. break;
  4122. case CURSOR_HSPLIT:
  4123. fallback = "sb_h_double_arrow";
  4124. break;
  4125. case CURSOR_HELP:
  4126. fallback = "help";
  4127. break;
  4128. }
  4129. if (fallback != nullptr) {
  4130. img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size);
  4131. }
  4132. }
  4133. if (img[i]) {
  4134. cursors[i] = XcursorImageLoadCursor(x11_display, img[i]);
  4135. } else {
  4136. print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
  4137. }
  4138. }
  4139. {
  4140. // Creating an empty/transparent cursor
  4141. // Create 1x1 bitmap
  4142. Pixmap cursormask = XCreatePixmap(x11_display,
  4143. RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
  4144. // Fill with zero
  4145. XGCValues xgc;
  4146. xgc.function = GXclear;
  4147. GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
  4148. XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
  4149. // Color value doesn't matter. Mask zero means no foreground or background will be drawn
  4150. XColor col = {};
  4151. Cursor cursor = XCreatePixmapCursor(x11_display,
  4152. cursormask, // source (using cursor mask as placeholder, since it'll all be ignored)
  4153. cursormask, // mask
  4154. &col, &col, 0, 0);
  4155. XFreePixmap(x11_display, cursormask);
  4156. XFreeGC(x11_display, gc);
  4157. if (cursor == None) {
  4158. ERR_PRINT("FAILED CREATING CURSOR");
  4159. }
  4160. null_cursor = cursor;
  4161. }
  4162. cursor_set_shape(CURSOR_BUSY);
  4163. XEvent xevent;
  4164. while (XPending(x11_display) > 0) {
  4165. XNextEvent(x11_display, &xevent);
  4166. if (xevent.type == ConfigureNotify) {
  4167. _window_changed(&xevent);
  4168. }
  4169. }
  4170. events_thread.start(_poll_events_thread, this);
  4171. _update_real_mouse_position(windows[MAIN_WINDOW_ID]);
  4172. #ifdef DBUS_ENABLED
  4173. screensaver = memnew(FreeDesktopScreenSaver);
  4174. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  4175. #endif
  4176. r_error = OK;
  4177. }
  4178. DisplayServerX11::~DisplayServerX11() {
  4179. // Send owned clipboard data to clipboard manager before exit.
  4180. Window x11_main_window = windows[MAIN_WINDOW_ID].x11_window;
  4181. _clipboard_transfer_ownership(XA_PRIMARY, x11_main_window);
  4182. _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_main_window);
  4183. events_thread_done.set();
  4184. events_thread.wait_to_finish();
  4185. //destroy all windows
  4186. for (KeyValue<WindowID, WindowData> &E : windows) {
  4187. #ifdef VULKAN_ENABLED
  4188. if (context_vulkan) {
  4189. context_vulkan->window_destroy(E.key);
  4190. }
  4191. #endif
  4192. #ifdef GLES3_ENABLED
  4193. if (gl_manager) {
  4194. gl_manager->window_destroy(E.key);
  4195. }
  4196. #endif
  4197. WindowData &wd = E.value;
  4198. if (wd.xic) {
  4199. XDestroyIC(wd.xic);
  4200. wd.xic = nullptr;
  4201. }
  4202. XUnmapWindow(x11_display, wd.x11_window);
  4203. XDestroyWindow(x11_display, wd.x11_window);
  4204. }
  4205. //destroy drivers
  4206. #if defined(VULKAN_ENABLED)
  4207. if (rendering_device_vulkan) {
  4208. rendering_device_vulkan->finalize();
  4209. memdelete(rendering_device_vulkan);
  4210. rendering_device_vulkan = nullptr;
  4211. }
  4212. if (context_vulkan) {
  4213. memdelete(context_vulkan);
  4214. context_vulkan = nullptr;
  4215. }
  4216. #endif
  4217. #ifdef GLES3_ENABLED
  4218. if (gl_manager) {
  4219. memdelete(gl_manager);
  4220. gl_manager = nullptr;
  4221. }
  4222. #endif
  4223. if (xrandr_handle) {
  4224. dlclose(xrandr_handle);
  4225. }
  4226. for (int i = 0; i < CURSOR_MAX; i++) {
  4227. if (cursors[i] != None) {
  4228. XFreeCursor(x11_display, cursors[i]);
  4229. }
  4230. if (img[i] != nullptr) {
  4231. XcursorImageDestroy(img[i]);
  4232. }
  4233. }
  4234. if (xim) {
  4235. XCloseIM(xim);
  4236. }
  4237. XCloseDisplay(x11_display);
  4238. if (xmbstring) {
  4239. memfree(xmbstring);
  4240. }
  4241. #ifdef SPEECHD_ENABLED
  4242. memdelete(tts);
  4243. #endif
  4244. #ifdef DBUS_ENABLED
  4245. memdelete(screensaver);
  4246. #endif
  4247. }
  4248. void DisplayServerX11::register_x11_driver() {
  4249. register_create_function("x11", create_func, get_rendering_drivers_func);
  4250. }
  4251. #endif // X11 enabled