display_server_x11.cpp 161 KB

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