display_server_x11.cpp 149 KB

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