display_server_x11.cpp 184 KB

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