display_server_x11.cpp 145 KB

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