display_server_x11.cpp 150 KB

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