display_server_x11.cpp 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753
  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. bool DisplayServerX11::screen_is_touchscreen(int p_screen) const {
  901. _THREAD_SAFE_METHOD_
  902. #ifndef _MSC_VER
  903. #warning Need to get from proper window
  904. #endif
  905. return DisplayServer::screen_is_touchscreen(p_screen);
  906. }
  907. #ifdef DBUS_ENABLED
  908. void DisplayServerX11::screen_set_keep_on(bool p_enable) {
  909. if (screen_is_kept_on() == p_enable) {
  910. return;
  911. }
  912. if (p_enable) {
  913. screensaver->inhibit();
  914. } else {
  915. screensaver->uninhibit();
  916. }
  917. keep_screen_on = p_enable;
  918. }
  919. bool DisplayServerX11::screen_is_kept_on() const {
  920. return keep_screen_on;
  921. }
  922. #endif
  923. Vector<DisplayServer::WindowID> DisplayServerX11::get_window_list() const {
  924. _THREAD_SAFE_METHOD_
  925. Vector<int> ret;
  926. for (const KeyValue<WindowID, WindowData> &E : windows) {
  927. ret.push_back(E.key);
  928. }
  929. return ret;
  930. }
  931. DisplayServer::WindowID DisplayServerX11::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  932. _THREAD_SAFE_METHOD_
  933. WindowID id = _create_window(p_mode, p_vsync_mode, p_flags, p_rect);
  934. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  935. if (p_flags & (1 << i)) {
  936. window_set_flag(WindowFlags(i), true, id);
  937. }
  938. }
  939. return id;
  940. }
  941. void DisplayServerX11::show_window(WindowID p_id) {
  942. _THREAD_SAFE_METHOD_
  943. const WindowData &wd = windows[p_id];
  944. DEBUG_LOG_X11("show_window: %lu (%u) \n", wd.x11_window, p_id);
  945. XMapWindow(x11_display, wd.x11_window);
  946. }
  947. void DisplayServerX11::delete_sub_window(WindowID p_id) {
  948. _THREAD_SAFE_METHOD_
  949. ERR_FAIL_COND(!windows.has(p_id));
  950. ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted"); //ma
  951. WindowData &wd = windows[p_id];
  952. DEBUG_LOG_X11("delete_sub_window: %lu (%u) \n", wd.x11_window, p_id);
  953. while (wd.transient_children.size()) {
  954. window_set_transient(wd.transient_children.front()->get(), INVALID_WINDOW_ID);
  955. }
  956. if (wd.transient_parent != INVALID_WINDOW_ID) {
  957. window_set_transient(p_id, INVALID_WINDOW_ID);
  958. }
  959. #ifdef VULKAN_ENABLED
  960. if (context_vulkan) {
  961. context_vulkan->window_destroy(p_id);
  962. }
  963. #endif
  964. #ifdef GLES3_ENABLED
  965. if (gl_manager) {
  966. gl_manager->window_destroy(p_id);
  967. }
  968. #endif
  969. XUnmapWindow(x11_display, wd.x11_window);
  970. XDestroyWindow(x11_display, wd.x11_window);
  971. if (wd.xic) {
  972. XDestroyIC(wd.xic);
  973. wd.xic = nullptr;
  974. }
  975. windows.erase(p_id);
  976. }
  977. int64_t DisplayServerX11::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  978. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  979. switch (p_handle_type) {
  980. case DISPLAY_HANDLE: {
  981. return (int64_t)x11_display;
  982. }
  983. case WINDOW_HANDLE: {
  984. return (int64_t)windows[p_window].x11_window;
  985. }
  986. case WINDOW_VIEW: {
  987. return 0; // Not supported.
  988. }
  989. default: {
  990. return 0;
  991. }
  992. }
  993. }
  994. void DisplayServerX11::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  995. ERR_FAIL_COND(!windows.has(p_window));
  996. WindowData &wd = windows[p_window];
  997. wd.instance_id = p_instance;
  998. }
  999. ObjectID DisplayServerX11::window_get_attached_instance_id(WindowID p_window) const {
  1000. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  1001. const WindowData &wd = windows[p_window];
  1002. return wd.instance_id;
  1003. }
  1004. DisplayServerX11::WindowID DisplayServerX11::get_window_at_screen_position(const Point2i &p_position) const {
  1005. WindowID found_window = INVALID_WINDOW_ID;
  1006. WindowID parent_window = INVALID_WINDOW_ID;
  1007. unsigned int focus_order = 0;
  1008. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1009. const WindowData &wd = E.value;
  1010. // Discard windows with no focus.
  1011. if (wd.focus_order == 0) {
  1012. continue;
  1013. }
  1014. // Find topmost window which contains the given position.
  1015. WindowID window_id = E.key;
  1016. Rect2i win_rect = Rect2i(window_get_position(window_id), window_get_size(window_id));
  1017. if (win_rect.has_point(p_position)) {
  1018. // For siblings, pick the window which was focused last.
  1019. if ((parent_window != wd.transient_parent) || (wd.focus_order > focus_order)) {
  1020. found_window = window_id;
  1021. parent_window = wd.transient_parent;
  1022. focus_order = wd.focus_order;
  1023. }
  1024. }
  1025. }
  1026. return found_window;
  1027. }
  1028. void DisplayServerX11::window_set_title(const String &p_title, WindowID p_window) {
  1029. _THREAD_SAFE_METHOD_
  1030. ERR_FAIL_COND(!windows.has(p_window));
  1031. WindowData &wd = windows[p_window];
  1032. XStoreName(x11_display, wd.x11_window, p_title.utf8().get_data());
  1033. Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
  1034. Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
  1035. if (_net_wm_name != None && utf8_string != None) {
  1036. XChangeProperty(x11_display, wd.x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
  1037. }
  1038. }
  1039. void DisplayServerX11::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1040. _THREAD_SAFE_METHOD_
  1041. ERR_FAIL_COND(!windows.has(p_window));
  1042. const WindowData &wd = windows[p_window];
  1043. int event_base, error_base;
  1044. const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base);
  1045. if (ext_okay) {
  1046. Region region;
  1047. if (p_region.size() == 0) {
  1048. region = XCreateRegion();
  1049. XRectangle rect;
  1050. rect.x = 0;
  1051. rect.y = 0;
  1052. rect.width = window_get_real_size(p_window).x;
  1053. rect.height = window_get_real_size(p_window).y;
  1054. XUnionRectWithRegion(&rect, region, region);
  1055. } else {
  1056. XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * p_region.size());
  1057. for (int i = 0; i < p_region.size(); i++) {
  1058. points[i].x = p_region[i].x;
  1059. points[i].y = p_region[i].y;
  1060. }
  1061. region = XPolygonRegion(points, p_region.size(), EvenOddRule);
  1062. memfree(points);
  1063. }
  1064. XShapeCombineRegion(x11_display, wd.x11_window, ShapeInput, 0, 0, region, ShapeSet);
  1065. XDestroyRegion(region);
  1066. }
  1067. }
  1068. void DisplayServerX11::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1069. _THREAD_SAFE_METHOD_
  1070. ERR_FAIL_COND(!windows.has(p_window));
  1071. WindowData &wd = windows[p_window];
  1072. wd.rect_changed_callback = p_callable;
  1073. }
  1074. void DisplayServerX11::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1075. _THREAD_SAFE_METHOD_
  1076. ERR_FAIL_COND(!windows.has(p_window));
  1077. WindowData &wd = windows[p_window];
  1078. wd.event_callback = p_callable;
  1079. }
  1080. void DisplayServerX11::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1081. _THREAD_SAFE_METHOD_
  1082. ERR_FAIL_COND(!windows.has(p_window));
  1083. WindowData &wd = windows[p_window];
  1084. wd.input_event_callback = p_callable;
  1085. }
  1086. void DisplayServerX11::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1087. _THREAD_SAFE_METHOD_
  1088. ERR_FAIL_COND(!windows.has(p_window));
  1089. WindowData &wd = windows[p_window];
  1090. wd.input_text_callback = p_callable;
  1091. }
  1092. void DisplayServerX11::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1093. _THREAD_SAFE_METHOD_
  1094. ERR_FAIL_COND(!windows.has(p_window));
  1095. WindowData &wd = windows[p_window];
  1096. wd.drop_files_callback = p_callable;
  1097. }
  1098. int DisplayServerX11::window_get_current_screen(WindowID p_window) const {
  1099. _THREAD_SAFE_METHOD_
  1100. int count = get_screen_count();
  1101. if (count < 2) {
  1102. // Early exit with single monitor.
  1103. return 0;
  1104. }
  1105. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  1106. const WindowData &wd = windows[p_window];
  1107. const Rect2i window_rect(wd.position, wd.size);
  1108. // Find which monitor has the largest overlap with the given window.
  1109. int screen_index = 0;
  1110. int max_area = 0;
  1111. for (int i = 0; i < count; i++) {
  1112. Rect2i screen_rect = _screen_get_rect(i);
  1113. Rect2i intersection = screen_rect.intersection(window_rect);
  1114. int area = intersection.get_area();
  1115. if (area > max_area) {
  1116. max_area = area;
  1117. screen_index = i;
  1118. }
  1119. }
  1120. return screen_index;
  1121. }
  1122. void DisplayServerX11::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  1123. #if defined(GLES3_ENABLED)
  1124. if (gl_manager) {
  1125. gl_manager->window_make_current(p_window_id);
  1126. }
  1127. #endif
  1128. }
  1129. void DisplayServerX11::window_set_current_screen(int p_screen, WindowID p_window) {
  1130. _THREAD_SAFE_METHOD_
  1131. ERR_FAIL_COND(!windows.has(p_window));
  1132. WindowData &wd = windows[p_window];
  1133. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1134. p_screen = window_get_current_screen();
  1135. }
  1136. // Check if screen is valid
  1137. ERR_FAIL_INDEX(p_screen, get_screen_count());
  1138. if (window_get_mode(p_window) == WINDOW_MODE_FULLSCREEN) {
  1139. Point2i position = screen_get_position(p_screen);
  1140. Size2i size = screen_get_size(p_screen);
  1141. XMoveResizeWindow(x11_display, wd.x11_window, position.x, position.y, size.x, size.y);
  1142. } else {
  1143. if (p_screen != window_get_current_screen(p_window)) {
  1144. Point2i position = screen_get_position(p_screen);
  1145. XMoveWindow(x11_display, wd.x11_window, position.x, position.y);
  1146. }
  1147. }
  1148. }
  1149. void DisplayServerX11::window_set_transient(WindowID p_window, WindowID p_parent) {
  1150. _THREAD_SAFE_METHOD_
  1151. ERR_FAIL_COND(p_window == p_parent);
  1152. ERR_FAIL_COND(!windows.has(p_window));
  1153. WindowData &wd_window = windows[p_window];
  1154. WindowID prev_parent = wd_window.transient_parent;
  1155. ERR_FAIL_COND(prev_parent == p_parent);
  1156. DEBUG_LOG_X11("window_set_transient: %lu (%u), prev_parent=%u, parent=%u\n", wd_window.x11_window, p_window, prev_parent, p_parent);
  1157. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  1158. if (p_parent == INVALID_WINDOW_ID) {
  1159. //remove transient
  1160. ERR_FAIL_COND(prev_parent == INVALID_WINDOW_ID);
  1161. ERR_FAIL_COND(!windows.has(prev_parent));
  1162. WindowData &wd_parent = windows[prev_parent];
  1163. wd_window.transient_parent = INVALID_WINDOW_ID;
  1164. wd_parent.transient_children.erase(p_window);
  1165. XSetTransientForHint(x11_display, wd_window.x11_window, None);
  1166. // Set focus to parent sub window to avoid losing all focus when closing a nested sub-menu.
  1167. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  1168. // a subwindow and its parent are both destroyed.
  1169. if (wd_window.menu_type && !wd_window.no_focus && wd_window.focused) {
  1170. if (!wd_parent.no_focus) {
  1171. XSetInputFocus(x11_display, wd_parent.x11_window, RevertToPointerRoot, CurrentTime);
  1172. }
  1173. }
  1174. } else {
  1175. ERR_FAIL_COND(!windows.has(p_parent));
  1176. ERR_FAIL_COND_MSG(prev_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1177. WindowData &wd_parent = windows[p_parent];
  1178. wd_window.transient_parent = p_parent;
  1179. wd_parent.transient_children.insert(p_window);
  1180. XSetTransientForHint(x11_display, wd_window.x11_window, wd_parent.x11_window);
  1181. }
  1182. }
  1183. // Helper method. Assumes that the window id has already been checked and exists.
  1184. void DisplayServerX11::_update_size_hints(WindowID p_window) {
  1185. WindowData &wd = windows[p_window];
  1186. WindowMode window_mode = window_get_mode(p_window);
  1187. XSizeHints *xsh = XAllocSizeHints();
  1188. // Always set the position and size hints - they should be synchronized with the actual values after the window is mapped anyway
  1189. xsh->flags |= PPosition | PSize;
  1190. xsh->x = wd.position.x;
  1191. xsh->y = wd.position.y;
  1192. xsh->width = wd.size.width;
  1193. xsh->height = wd.size.height;
  1194. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  1195. // Do not set any other hints to prevent the window manager from ignoring the fullscreen flags
  1196. } else if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) {
  1197. // If resizing is disabled, use the forced size
  1198. xsh->flags |= PMinSize | PMaxSize;
  1199. xsh->min_width = wd.size.x;
  1200. xsh->max_width = wd.size.x;
  1201. xsh->min_height = wd.size.y;
  1202. xsh->max_height = wd.size.y;
  1203. } else {
  1204. // Otherwise, just respect min_size and max_size
  1205. if (wd.min_size != Size2i()) {
  1206. xsh->flags |= PMinSize;
  1207. xsh->min_width = wd.min_size.x;
  1208. xsh->min_height = wd.min_size.y;
  1209. }
  1210. if (wd.max_size != Size2i()) {
  1211. xsh->flags |= PMaxSize;
  1212. xsh->max_width = wd.max_size.x;
  1213. xsh->max_height = wd.max_size.y;
  1214. }
  1215. }
  1216. XSetWMNormalHints(x11_display, wd.x11_window, xsh);
  1217. XFree(xsh);
  1218. }
  1219. Point2i DisplayServerX11::window_get_position(WindowID p_window) const {
  1220. _THREAD_SAFE_METHOD_
  1221. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1222. const WindowData &wd = windows[p_window];
  1223. return wd.position;
  1224. }
  1225. void DisplayServerX11::window_set_position(const Point2i &p_position, WindowID p_window) {
  1226. _THREAD_SAFE_METHOD_
  1227. ERR_FAIL_COND(!windows.has(p_window));
  1228. WindowData &wd = windows[p_window];
  1229. int x = 0;
  1230. int y = 0;
  1231. if (!window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
  1232. //exclude window decorations
  1233. XSync(x11_display, False);
  1234. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1235. if (prop != None) {
  1236. Atom type;
  1237. int format;
  1238. unsigned long len;
  1239. unsigned long remaining;
  1240. unsigned char *data = nullptr;
  1241. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1242. if (format == 32 && len == 4 && data) {
  1243. long *extents = (long *)data;
  1244. x = extents[0];
  1245. y = extents[2];
  1246. }
  1247. XFree(data);
  1248. }
  1249. }
  1250. }
  1251. XMoveWindow(x11_display, wd.x11_window, p_position.x - x, p_position.y - y);
  1252. _update_real_mouse_position(wd);
  1253. }
  1254. void DisplayServerX11::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1255. _THREAD_SAFE_METHOD_
  1256. ERR_FAIL_COND(!windows.has(p_window));
  1257. WindowData &wd = windows[p_window];
  1258. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1259. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1260. return;
  1261. }
  1262. wd.max_size = p_size;
  1263. _update_size_hints(p_window);
  1264. XFlush(x11_display);
  1265. }
  1266. Size2i DisplayServerX11::window_get_max_size(WindowID p_window) const {
  1267. _THREAD_SAFE_METHOD_
  1268. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1269. const WindowData &wd = windows[p_window];
  1270. return wd.max_size;
  1271. }
  1272. void DisplayServerX11::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1273. _THREAD_SAFE_METHOD_
  1274. ERR_FAIL_COND(!windows.has(p_window));
  1275. WindowData &wd = windows[p_window];
  1276. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1277. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1278. return;
  1279. }
  1280. wd.min_size = p_size;
  1281. _update_size_hints(p_window);
  1282. XFlush(x11_display);
  1283. }
  1284. Size2i DisplayServerX11::window_get_min_size(WindowID p_window) const {
  1285. _THREAD_SAFE_METHOD_
  1286. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1287. const WindowData &wd = windows[p_window];
  1288. return wd.min_size;
  1289. }
  1290. void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) {
  1291. _THREAD_SAFE_METHOD_
  1292. ERR_FAIL_COND(!windows.has(p_window));
  1293. Size2i size = p_size;
  1294. size.x = MAX(1, size.x);
  1295. size.y = MAX(1, size.y);
  1296. WindowData &wd = windows[p_window];
  1297. if (wd.size.width == size.width && wd.size.height == size.height) {
  1298. return;
  1299. }
  1300. XWindowAttributes xwa;
  1301. XSync(x11_display, False);
  1302. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1303. int old_w = xwa.width;
  1304. int old_h = xwa.height;
  1305. // Update our videomode width and height
  1306. wd.size = size;
  1307. // Update the size hints first to make sure the window size can be set
  1308. _update_size_hints(p_window);
  1309. // Resize the window
  1310. XResizeWindow(x11_display, wd.x11_window, size.x, size.y);
  1311. for (int timeout = 0; timeout < 50; ++timeout) {
  1312. XSync(x11_display, False);
  1313. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1314. if (old_w != xwa.width || old_h != xwa.height) {
  1315. break;
  1316. }
  1317. usleep(10000);
  1318. }
  1319. }
  1320. Size2i DisplayServerX11::window_get_size(WindowID p_window) const {
  1321. _THREAD_SAFE_METHOD_
  1322. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1323. const WindowData &wd = windows[p_window];
  1324. return wd.size;
  1325. }
  1326. Size2i DisplayServerX11::window_get_real_size(WindowID p_window) const {
  1327. _THREAD_SAFE_METHOD_
  1328. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1329. const WindowData &wd = windows[p_window];
  1330. XWindowAttributes xwa;
  1331. XSync(x11_display, False);
  1332. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1333. int w = xwa.width;
  1334. int h = xwa.height;
  1335. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1336. if (prop != None) {
  1337. Atom type;
  1338. int format;
  1339. unsigned long len;
  1340. unsigned long remaining;
  1341. unsigned char *data = nullptr;
  1342. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1343. if (format == 32 && len == 4 && data) {
  1344. long *extents = (long *)data;
  1345. w += extents[0] + extents[1]; // left, right
  1346. h += extents[2] + extents[3]; // top, bottom
  1347. }
  1348. XFree(data);
  1349. }
  1350. }
  1351. return Size2i(w, h);
  1352. }
  1353. // Just a helper to reduce code duplication in `window_is_maximize_allowed`
  1354. // and `_set_wm_maximized`.
  1355. bool DisplayServerX11::_window_maximize_check(WindowID p_window, const char *p_atom_name) const {
  1356. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1357. const WindowData &wd = windows[p_window];
  1358. Atom property = XInternAtom(x11_display, p_atom_name, False);
  1359. Atom type;
  1360. int format;
  1361. unsigned long len;
  1362. unsigned long remaining;
  1363. unsigned char *data = nullptr;
  1364. bool retval = false;
  1365. if (property == None) {
  1366. return false;
  1367. }
  1368. int result = XGetWindowProperty(
  1369. x11_display,
  1370. wd.x11_window,
  1371. property,
  1372. 0,
  1373. 1024,
  1374. False,
  1375. XA_ATOM,
  1376. &type,
  1377. &format,
  1378. &len,
  1379. &remaining,
  1380. &data);
  1381. if (result == Success && data) {
  1382. Atom *atoms = (Atom *)data;
  1383. Atom wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False);
  1384. Atom wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False);
  1385. bool found_wm_act_max_horz = false;
  1386. bool found_wm_act_max_vert = false;
  1387. for (uint64_t i = 0; i < len; i++) {
  1388. if (atoms[i] == wm_act_max_horz) {
  1389. found_wm_act_max_horz = true;
  1390. }
  1391. if (atoms[i] == wm_act_max_vert) {
  1392. found_wm_act_max_vert = true;
  1393. }
  1394. if (found_wm_act_max_horz || found_wm_act_max_vert) {
  1395. retval = true;
  1396. break;
  1397. }
  1398. }
  1399. XFree(data);
  1400. }
  1401. return retval;
  1402. }
  1403. bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const {
  1404. _THREAD_SAFE_METHOD_
  1405. return _window_maximize_check(p_window, "_NET_WM_ALLOWED_ACTIONS");
  1406. }
  1407. void DisplayServerX11::_set_wm_maximized(WindowID p_window, bool p_enabled) {
  1408. ERR_FAIL_COND(!windows.has(p_window));
  1409. WindowData &wd = windows[p_window];
  1410. // Using EWMH -- Extended Window Manager Hints
  1411. XEvent xev;
  1412. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1413. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1414. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1415. memset(&xev, 0, sizeof(xev));
  1416. xev.type = ClientMessage;
  1417. xev.xclient.window = wd.x11_window;
  1418. xev.xclient.message_type = wm_state;
  1419. xev.xclient.format = 32;
  1420. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1421. xev.xclient.data.l[1] = wm_max_horz;
  1422. xev.xclient.data.l[2] = wm_max_vert;
  1423. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1424. if (p_enabled && window_is_maximize_allowed(p_window)) {
  1425. // Wait for effective resizing (so the GLX context is too).
  1426. // Give up after 0.5s, it's not going to happen on this WM.
  1427. // https://github.com/godotengine/godot/issues/19978
  1428. for (int attempt = 0; window_get_mode(p_window) != WINDOW_MODE_MAXIMIZED && attempt < 50; attempt++) {
  1429. usleep(10000);
  1430. }
  1431. }
  1432. }
  1433. void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) {
  1434. ERR_FAIL_COND(!windows.has(p_window));
  1435. WindowData &wd = windows[p_window];
  1436. if (p_enabled && !window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
  1437. // remove decorations if the window is not already borderless
  1438. Hints hints;
  1439. Atom property;
  1440. hints.flags = 2;
  1441. hints.decorations = 0;
  1442. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1443. if (property != None) {
  1444. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1445. }
  1446. }
  1447. if (p_enabled) {
  1448. // Set the window as resizable to prevent window managers to ignore the fullscreen state flag.
  1449. _update_size_hints(p_window);
  1450. }
  1451. // Using EWMH -- Extended Window Manager Hints
  1452. XEvent xev;
  1453. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1454. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  1455. memset(&xev, 0, sizeof(xev));
  1456. xev.type = ClientMessage;
  1457. xev.xclient.window = wd.x11_window;
  1458. xev.xclient.message_type = wm_state;
  1459. xev.xclient.format = 32;
  1460. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1461. xev.xclient.data.l[1] = wm_fullscreen;
  1462. xev.xclient.data.l[2] = 0;
  1463. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1464. // set bypass compositor hint
  1465. Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
  1466. unsigned long compositing_disable_on = p_enabled ? 1 : 0;
  1467. if (bypass_compositor != None) {
  1468. XChangeProperty(x11_display, wd.x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
  1469. }
  1470. XFlush(x11_display);
  1471. if (!p_enabled) {
  1472. // Reset the non-resizable flags if we un-set these before.
  1473. _update_size_hints(p_window);
  1474. // put back or remove decorations according to the last set borderless state
  1475. Hints hints;
  1476. Atom property;
  1477. hints.flags = 2;
  1478. hints.decorations = window_get_flag(WINDOW_FLAG_BORDERLESS, p_window) ? 0 : 1;
  1479. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1480. if (property != None) {
  1481. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1482. }
  1483. }
  1484. }
  1485. void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) {
  1486. _THREAD_SAFE_METHOD_
  1487. ERR_FAIL_COND(!windows.has(p_window));
  1488. WindowData &wd = windows[p_window];
  1489. WindowMode old_mode = window_get_mode(p_window);
  1490. if (old_mode == p_mode) {
  1491. return; // do nothing
  1492. }
  1493. //remove all "extra" modes
  1494. switch (old_mode) {
  1495. case WINDOW_MODE_WINDOWED: {
  1496. //do nothing
  1497. } break;
  1498. case WINDOW_MODE_MINIMIZED: {
  1499. //Un-Minimize
  1500. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1501. XEvent xev;
  1502. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  1503. memset(&xev, 0, sizeof(xev));
  1504. xev.type = ClientMessage;
  1505. xev.xclient.window = wd.x11_window;
  1506. xev.xclient.message_type = wm_change;
  1507. xev.xclient.format = 32;
  1508. xev.xclient.data.l[0] = WM_NormalState;
  1509. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1510. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1511. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  1512. memset(&xev, 0, sizeof(xev));
  1513. xev.type = ClientMessage;
  1514. xev.xclient.window = wd.x11_window;
  1515. xev.xclient.message_type = wm_state;
  1516. xev.xclient.format = 32;
  1517. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1518. xev.xclient.data.l[1] = wm_hidden;
  1519. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1520. } break;
  1521. case WINDOW_MODE_FULLSCREEN: {
  1522. //Remove full-screen
  1523. wd.fullscreen = false;
  1524. _set_wm_fullscreen(p_window, false);
  1525. //un-maximize required for always on top
  1526. bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window);
  1527. window_set_position(wd.last_position_before_fs, p_window);
  1528. if (on_top) {
  1529. _set_wm_maximized(p_window, false);
  1530. }
  1531. } break;
  1532. case WINDOW_MODE_MAXIMIZED: {
  1533. _set_wm_maximized(p_window, false);
  1534. } break;
  1535. }
  1536. switch (p_mode) {
  1537. case WINDOW_MODE_WINDOWED: {
  1538. //do nothing
  1539. } break;
  1540. case WINDOW_MODE_MINIMIZED: {
  1541. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1542. XEvent xev;
  1543. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  1544. memset(&xev, 0, sizeof(xev));
  1545. xev.type = ClientMessage;
  1546. xev.xclient.window = wd.x11_window;
  1547. xev.xclient.message_type = wm_change;
  1548. xev.xclient.format = 32;
  1549. xev.xclient.data.l[0] = WM_IconicState;
  1550. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1551. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1552. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  1553. memset(&xev, 0, sizeof(xev));
  1554. xev.type = ClientMessage;
  1555. xev.xclient.window = wd.x11_window;
  1556. xev.xclient.message_type = wm_state;
  1557. xev.xclient.format = 32;
  1558. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1559. xev.xclient.data.l[1] = wm_hidden;
  1560. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1561. } break;
  1562. case WINDOW_MODE_FULLSCREEN: {
  1563. wd.last_position_before_fs = wd.position;
  1564. if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) {
  1565. _set_wm_maximized(p_window, true);
  1566. }
  1567. wd.fullscreen = true;
  1568. _set_wm_fullscreen(p_window, true);
  1569. } break;
  1570. case WINDOW_MODE_MAXIMIZED: {
  1571. _set_wm_maximized(p_window, true);
  1572. } break;
  1573. }
  1574. }
  1575. DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) const {
  1576. _THREAD_SAFE_METHOD_
  1577. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  1578. const WindowData &wd = windows[p_window];
  1579. if (wd.fullscreen) { //if fullscreen, it's not in another mode
  1580. return WINDOW_MODE_FULLSCREEN;
  1581. }
  1582. // Test maximized.
  1583. // Using EWMH -- Extended Window Manager Hints
  1584. if (_window_maximize_check(p_window, "_NET_WM_STATE")) {
  1585. return WINDOW_MODE_MAXIMIZED;
  1586. }
  1587. { // Test minimized.
  1588. // Using ICCCM -- Inter-Client Communication Conventions Manual
  1589. Atom property = XInternAtom(x11_display, "WM_STATE", True);
  1590. if (property == None) {
  1591. return WINDOW_MODE_WINDOWED;
  1592. }
  1593. Atom type;
  1594. int format;
  1595. unsigned long len;
  1596. unsigned long remaining;
  1597. unsigned char *data = nullptr;
  1598. int result = XGetWindowProperty(
  1599. x11_display,
  1600. wd.x11_window,
  1601. property,
  1602. 0,
  1603. 32,
  1604. False,
  1605. AnyPropertyType,
  1606. &type,
  1607. &format,
  1608. &len,
  1609. &remaining,
  1610. &data);
  1611. if (result == Success && data) {
  1612. long *state = (long *)data;
  1613. if (state[0] == WM_IconicState) {
  1614. XFree(data);
  1615. return WINDOW_MODE_MINIMIZED;
  1616. }
  1617. XFree(data);
  1618. }
  1619. }
  1620. // All other discarded, return windowed.
  1621. return WINDOW_MODE_WINDOWED;
  1622. }
  1623. void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  1624. _THREAD_SAFE_METHOD_
  1625. ERR_FAIL_COND(!windows.has(p_window));
  1626. WindowData &wd = windows[p_window];
  1627. switch (p_flag) {
  1628. case WINDOW_FLAG_RESIZE_DISABLED: {
  1629. wd.resize_disabled = p_enabled;
  1630. _update_size_hints(p_window);
  1631. XFlush(x11_display);
  1632. } break;
  1633. case WINDOW_FLAG_BORDERLESS: {
  1634. Hints hints;
  1635. Atom property;
  1636. hints.flags = 2;
  1637. hints.decorations = p_enabled ? 0 : 1;
  1638. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1639. if (property != None) {
  1640. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  1641. }
  1642. // Preserve window size
  1643. window_set_size(window_get_size(p_window), p_window);
  1644. wd.borderless = p_enabled;
  1645. } break;
  1646. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1647. ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID, "Can't make a window transient if the 'on top' flag is active.");
  1648. if (p_enabled && wd.fullscreen) {
  1649. _set_wm_maximized(p_window, true);
  1650. }
  1651. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1652. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  1653. XClientMessageEvent xev;
  1654. memset(&xev, 0, sizeof(xev));
  1655. xev.type = ClientMessage;
  1656. xev.window = wd.x11_window;
  1657. xev.message_type = wm_state;
  1658. xev.format = 32;
  1659. xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  1660. xev.data.l[1] = wm_above;
  1661. xev.data.l[3] = 1;
  1662. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  1663. if (!p_enabled && !wd.fullscreen) {
  1664. _set_wm_maximized(p_window, false);
  1665. }
  1666. wd.on_top = p_enabled;
  1667. } break;
  1668. case WINDOW_FLAG_TRANSPARENT: {
  1669. //todo reimplement
  1670. } break;
  1671. default: {
  1672. }
  1673. }
  1674. }
  1675. bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  1676. _THREAD_SAFE_METHOD_
  1677. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1678. const WindowData &wd = windows[p_window];
  1679. switch (p_flag) {
  1680. case WINDOW_FLAG_RESIZE_DISABLED: {
  1681. return wd.resize_disabled;
  1682. } break;
  1683. case WINDOW_FLAG_BORDERLESS: {
  1684. bool borderless = wd.borderless;
  1685. Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  1686. if (prop != None) {
  1687. Atom type;
  1688. int format;
  1689. unsigned long len;
  1690. unsigned long remaining;
  1691. unsigned char *data = nullptr;
  1692. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1693. if (data && (format == 32) && (len >= 5)) {
  1694. borderless = !((Hints *)data)->decorations;
  1695. }
  1696. if (data) {
  1697. XFree(data);
  1698. }
  1699. }
  1700. }
  1701. return borderless;
  1702. } break;
  1703. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1704. return wd.on_top;
  1705. } break;
  1706. case WINDOW_FLAG_TRANSPARENT: {
  1707. //todo reimplement
  1708. } break;
  1709. default: {
  1710. }
  1711. }
  1712. return false;
  1713. }
  1714. void DisplayServerX11::window_request_attention(WindowID p_window) {
  1715. _THREAD_SAFE_METHOD_
  1716. ERR_FAIL_COND(!windows.has(p_window));
  1717. WindowData &wd = windows[p_window];
  1718. // Using EWMH -- Extended Window Manager Hints
  1719. //
  1720. // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
  1721. // Will be unset by the window manager after user react on the request for attention
  1722. XEvent xev;
  1723. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  1724. Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
  1725. memset(&xev, 0, sizeof(xev));
  1726. xev.type = ClientMessage;
  1727. xev.xclient.window = wd.x11_window;
  1728. xev.xclient.message_type = wm_state;
  1729. xev.xclient.format = 32;
  1730. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  1731. xev.xclient.data.l[1] = wm_attention;
  1732. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1733. XFlush(x11_display);
  1734. }
  1735. void DisplayServerX11::window_move_to_foreground(WindowID p_window) {
  1736. _THREAD_SAFE_METHOD_
  1737. ERR_FAIL_COND(!windows.has(p_window));
  1738. WindowData &wd = windows[p_window];
  1739. XEvent xev;
  1740. Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
  1741. memset(&xev, 0, sizeof(xev));
  1742. xev.type = ClientMessage;
  1743. xev.xclient.window = wd.x11_window;
  1744. xev.xclient.message_type = net_active_window;
  1745. xev.xclient.format = 32;
  1746. xev.xclient.data.l[0] = 1;
  1747. xev.xclient.data.l[1] = CurrentTime;
  1748. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  1749. XFlush(x11_display);
  1750. }
  1751. bool DisplayServerX11::window_can_draw(WindowID p_window) const {
  1752. //this seems to be all that is provided by X11
  1753. return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED;
  1754. }
  1755. bool DisplayServerX11::can_any_window_draw() const {
  1756. _THREAD_SAFE_METHOD_
  1757. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1758. if (window_get_mode(E.key) != WINDOW_MODE_MINIMIZED) {
  1759. return true;
  1760. }
  1761. }
  1762. return false;
  1763. }
  1764. void DisplayServerX11::window_set_ime_active(const bool p_active, WindowID p_window) {
  1765. _THREAD_SAFE_METHOD_
  1766. ERR_FAIL_COND(!windows.has(p_window));
  1767. WindowData &wd = windows[p_window];
  1768. wd.im_active = p_active;
  1769. if (!wd.xic) {
  1770. return;
  1771. }
  1772. // Block events polling while changing input focus
  1773. // because it triggers some event polling internally.
  1774. if (p_active) {
  1775. {
  1776. MutexLock mutex_lock(events_mutex);
  1777. XSetICFocus(wd.xic);
  1778. }
  1779. window_set_ime_position(wd.im_position, p_window);
  1780. } else {
  1781. MutexLock mutex_lock(events_mutex);
  1782. XUnsetICFocus(wd.xic);
  1783. }
  1784. }
  1785. void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  1786. _THREAD_SAFE_METHOD_
  1787. ERR_FAIL_COND(!windows.has(p_window));
  1788. WindowData &wd = windows[p_window];
  1789. wd.im_position = p_pos;
  1790. if (!wd.xic) {
  1791. return;
  1792. }
  1793. ::XPoint spot;
  1794. spot.x = short(p_pos.x);
  1795. spot.y = short(p_pos.y);
  1796. XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, nullptr);
  1797. {
  1798. // Block events polling during this call
  1799. // because it triggers some event polling internally.
  1800. MutexLock mutex_lock(events_mutex);
  1801. XSetICValues(wd.xic, XNPreeditAttributes, preedit_attr, nullptr);
  1802. }
  1803. XFree(preedit_attr);
  1804. }
  1805. void DisplayServerX11::cursor_set_shape(CursorShape p_shape) {
  1806. _THREAD_SAFE_METHOD_
  1807. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1808. if (p_shape == current_cursor) {
  1809. return;
  1810. }
  1811. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1812. if (cursors[p_shape] != None) {
  1813. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1814. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  1815. }
  1816. } else if (cursors[CURSOR_ARROW] != None) {
  1817. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1818. XDefineCursor(x11_display, E.value.x11_window, cursors[CURSOR_ARROW]);
  1819. }
  1820. }
  1821. }
  1822. current_cursor = p_shape;
  1823. }
  1824. DisplayServerX11::CursorShape DisplayServerX11::cursor_get_shape() const {
  1825. return current_cursor;
  1826. }
  1827. void DisplayServerX11::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1828. _THREAD_SAFE_METHOD_
  1829. if (p_cursor.is_valid()) {
  1830. Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape);
  1831. if (cursor_c) {
  1832. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  1833. cursor_set_shape(p_shape);
  1834. return;
  1835. }
  1836. cursors_cache.erase(p_shape);
  1837. }
  1838. Ref<Texture2D> texture = p_cursor;
  1839. Ref<AtlasTexture> atlas_texture = p_cursor;
  1840. Ref<Image> image;
  1841. Size2i texture_size;
  1842. Rect2i atlas_rect;
  1843. if (texture.is_valid()) {
  1844. image = texture->get_image();
  1845. }
  1846. if (!image.is_valid() && atlas_texture.is_valid()) {
  1847. texture = atlas_texture->get_atlas();
  1848. atlas_rect.size.width = texture->get_width();
  1849. atlas_rect.size.height = texture->get_height();
  1850. atlas_rect.position.x = atlas_texture->get_region().position.x;
  1851. atlas_rect.position.y = atlas_texture->get_region().position.y;
  1852. texture_size.width = atlas_texture->get_region().size.x;
  1853. texture_size.height = atlas_texture->get_region().size.y;
  1854. } else if (image.is_valid()) {
  1855. texture_size.width = texture->get_width();
  1856. texture_size.height = texture->get_height();
  1857. }
  1858. ERR_FAIL_COND(!texture.is_valid());
  1859. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  1860. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  1861. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  1862. image = texture->get_image();
  1863. ERR_FAIL_COND(!image.is_valid());
  1864. // Create the cursor structure
  1865. XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
  1866. XcursorUInt image_size = texture_size.width * texture_size.height;
  1867. XcursorDim size = sizeof(XcursorPixel) * image_size;
  1868. cursor_image->version = 1;
  1869. cursor_image->size = size;
  1870. cursor_image->xhot = p_hotspot.x;
  1871. cursor_image->yhot = p_hotspot.y;
  1872. // allocate memory to contain the whole file
  1873. cursor_image->pixels = (XcursorPixel *)memalloc(size);
  1874. for (XcursorPixel index = 0; index < image_size; index++) {
  1875. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  1876. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  1877. if (atlas_texture.is_valid()) {
  1878. column_index = MIN(column_index, atlas_rect.size.width - 1);
  1879. row_index = MIN(row_index, atlas_rect.size.height - 1);
  1880. }
  1881. *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
  1882. }
  1883. ERR_FAIL_COND(cursor_image->pixels == nullptr);
  1884. // Save it for a further usage
  1885. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
  1886. Vector<Variant> params;
  1887. params.push_back(p_cursor);
  1888. params.push_back(p_hotspot);
  1889. cursors_cache.insert(p_shape, params);
  1890. if (p_shape == current_cursor) {
  1891. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1892. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1893. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  1894. }
  1895. }
  1896. }
  1897. memfree(cursor_image->pixels);
  1898. XcursorImageDestroy(cursor_image);
  1899. } else {
  1900. // Reset to default system cursor
  1901. if (img[p_shape]) {
  1902. cursors[p_shape] = XcursorImageLoadCursor(x11_display, img[p_shape]);
  1903. }
  1904. CursorShape c = current_cursor;
  1905. current_cursor = CURSOR_MAX;
  1906. cursor_set_shape(c);
  1907. cursors_cache.erase(p_shape);
  1908. }
  1909. }
  1910. int DisplayServerX11::keyboard_get_layout_count() const {
  1911. int _group_count = 0;
  1912. XkbDescRec *kbd = XkbAllocKeyboard();
  1913. if (kbd) {
  1914. kbd->dpy = x11_display;
  1915. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  1916. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  1917. const Atom *groups = kbd->names->groups;
  1918. if (kbd->ctrls != nullptr) {
  1919. _group_count = kbd->ctrls->num_groups;
  1920. } else {
  1921. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  1922. _group_count++;
  1923. }
  1924. }
  1925. XkbFreeKeyboard(kbd, 0, true);
  1926. }
  1927. return _group_count;
  1928. }
  1929. int DisplayServerX11::keyboard_get_current_layout() const {
  1930. XkbStateRec state;
  1931. XkbGetState(x11_display, XkbUseCoreKbd, &state);
  1932. return state.group;
  1933. }
  1934. void DisplayServerX11::keyboard_set_current_layout(int p_index) {
  1935. ERR_FAIL_INDEX(p_index, keyboard_get_layout_count());
  1936. XkbLockGroup(x11_display, XkbUseCoreKbd, p_index);
  1937. }
  1938. String DisplayServerX11::keyboard_get_layout_language(int p_index) const {
  1939. String ret;
  1940. XkbDescRec *kbd = XkbAllocKeyboard();
  1941. if (kbd) {
  1942. kbd->dpy = x11_display;
  1943. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  1944. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  1945. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  1946. int _group_count = 0;
  1947. const Atom *groups = kbd->names->groups;
  1948. if (kbd->ctrls != nullptr) {
  1949. _group_count = kbd->ctrls->num_groups;
  1950. } else {
  1951. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  1952. _group_count++;
  1953. }
  1954. }
  1955. Atom names = kbd->names->symbols;
  1956. if (names != None) {
  1957. char *name = XGetAtomName(x11_display, names);
  1958. Vector<String> info = String(name).split("+");
  1959. if (p_index >= 0 && p_index < _group_count) {
  1960. if (p_index + 1 < info.size()) {
  1961. ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols.
  1962. } else {
  1963. ret = "en"; // No symbol for layout fallback to "en".
  1964. }
  1965. } else {
  1966. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  1967. }
  1968. XFree(name);
  1969. }
  1970. XkbFreeKeyboard(kbd, 0, true);
  1971. }
  1972. return ret.substr(0, 2);
  1973. }
  1974. String DisplayServerX11::keyboard_get_layout_name(int p_index) const {
  1975. String ret;
  1976. XkbDescRec *kbd = XkbAllocKeyboard();
  1977. if (kbd) {
  1978. kbd->dpy = x11_display;
  1979. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  1980. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  1981. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  1982. int _group_count = 0;
  1983. const Atom *groups = kbd->names->groups;
  1984. if (kbd->ctrls != nullptr) {
  1985. _group_count = kbd->ctrls->num_groups;
  1986. } else {
  1987. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  1988. _group_count++;
  1989. }
  1990. }
  1991. if (p_index >= 0 && p_index < _group_count) {
  1992. char *full_name = XGetAtomName(x11_display, groups[p_index]);
  1993. ret.parse_utf8(full_name);
  1994. XFree(full_name);
  1995. } else {
  1996. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  1997. }
  1998. XkbFreeKeyboard(kbd, 0, true);
  1999. }
  2000. return ret;
  2001. }
  2002. Key DisplayServerX11::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2003. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2004. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2005. unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
  2006. KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, 0, 0);
  2007. if (xkeysym >= 'a' && xkeysym <= 'z') {
  2008. xkeysym -= ('a' - 'A');
  2009. }
  2010. Key key = KeyMappingX11::get_keycode(xkeysym);
  2011. // If not found, fallback to QWERTY.
  2012. // This should match the behavior of the event pump
  2013. if (key == Key::NONE) {
  2014. return p_keycode;
  2015. }
  2016. return (Key)(key | modifiers);
  2017. }
  2018. DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, Window p_window, Atom p_property) {
  2019. Atom actual_type = None;
  2020. int actual_format = 0;
  2021. unsigned long nitems = 0;
  2022. unsigned long bytes_after = 0;
  2023. unsigned char *ret = nullptr;
  2024. int read_bytes = 1024;
  2025. // Keep trying to read the property until there are no bytes unread.
  2026. if (p_property != None) {
  2027. do {
  2028. if (ret != nullptr) {
  2029. XFree(ret);
  2030. }
  2031. XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
  2032. &actual_type, &actual_format, &nitems, &bytes_after,
  2033. &ret);
  2034. read_bytes *= 2;
  2035. } while (bytes_after != 0);
  2036. }
  2037. Property p = { ret, actual_format, (int)nitems, actual_type };
  2038. return p;
  2039. }
  2040. static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) {
  2041. static const char *target_type = "text/uri-list";
  2042. for (int i = 0; i < p_count; i++) {
  2043. Atom atom = p_list[i];
  2044. if (atom != None && String(XGetAtomName(p_display, atom)) == target_type) {
  2045. return atom;
  2046. }
  2047. }
  2048. return None;
  2049. }
  2050. static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
  2051. static const char *target_type = "text/uri-list";
  2052. if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type) {
  2053. return p_t1;
  2054. }
  2055. if (p_t2 != None && String(XGetAtomName(p_disp, p_t2)) == target_type) {
  2056. return p_t2;
  2057. }
  2058. if (p_t3 != None && String(XGetAtomName(p_disp, p_t3)) == target_type) {
  2059. return p_t3;
  2060. }
  2061. return None;
  2062. }
  2063. void DisplayServerX11::_get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
  2064. state->set_shift_pressed((p_x11_state & ShiftMask));
  2065. state->set_ctrl_pressed((p_x11_state & ControlMask));
  2066. state->set_alt_pressed((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt
  2067. state->set_meta_pressed((p_x11_state & Mod4Mask));
  2068. }
  2069. MouseButton DisplayServerX11::_get_mouse_button_state(MouseButton p_x11_button, int p_x11_type) {
  2070. MouseButton mask = mouse_button_to_mask(p_x11_button);
  2071. if (p_x11_type == ButtonPress) {
  2072. last_button_state |= mask;
  2073. } else {
  2074. last_button_state &= ~mask;
  2075. }
  2076. return last_button_state;
  2077. }
  2078. void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) {
  2079. WindowData wd = windows[p_window];
  2080. // X11 functions don't know what const is
  2081. XKeyEvent *xkeyevent = p_event;
  2082. // This code was pretty difficult to write.
  2083. // The docs stink and every toolkit seems to
  2084. // do it in a different way.
  2085. /* Phase 1, obtain a proper keysym */
  2086. // This was also very difficult to figure out.
  2087. // You'd expect you could just use Keysym provided by
  2088. // XKeycodeToKeysym to obtain internationalized
  2089. // input.. WRONG!!
  2090. // you must use XLookupString (???) which not only wastes
  2091. // cycles generating an unnecessary string, but also
  2092. // still works in half the cases. (won't handle deadkeys)
  2093. // For more complex input methods (deadkeys and more advanced)
  2094. // you have to use XmbLookupString (??).
  2095. // So then you have to choose which of both results
  2096. // you want to keep.
  2097. // This is a real bizarreness and cpu waster.
  2098. KeySym keysym_keycode = 0; // keysym used to find a keycode
  2099. KeySym keysym_unicode = 0; // keysym used to find unicode
  2100. // XLookupString returns keysyms usable as nice keycodes.
  2101. char str[256 + 1];
  2102. XKeyEvent xkeyevent_no_mod = *xkeyevent;
  2103. xkeyevent_no_mod.state &= ~ShiftMask;
  2104. xkeyevent_no_mod.state &= ~ControlMask;
  2105. XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr);
  2106. XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr);
  2107. // Meanwhile, XLookupString returns keysyms useful for unicode.
  2108. if (!xmbstring) {
  2109. // keep a temporary buffer for the string
  2110. xmbstring = (char *)memalloc(sizeof(char) * 8);
  2111. xmblen = 8;
  2112. }
  2113. if (xkeyevent->type == KeyPress && wd.xic) {
  2114. Status status;
  2115. #ifdef X_HAVE_UTF8_STRING
  2116. int utf8len = 8;
  2117. char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
  2118. int utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2119. utf8len - 1, &keysym_unicode, &status);
  2120. if (status == XBufferOverflow) {
  2121. utf8len = utf8bytes + 1;
  2122. utf8string = (char *)memrealloc(utf8string, utf8len);
  2123. utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2124. utf8len - 1, &keysym_unicode, &status);
  2125. }
  2126. utf8string[utf8bytes] = '\0';
  2127. if (status == XLookupChars) {
  2128. bool keypress = xkeyevent->type == KeyPress;
  2129. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2130. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2131. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2132. keycode -= 'a' - 'A';
  2133. }
  2134. String tmp;
  2135. tmp.parse_utf8(utf8string, utf8bytes);
  2136. for (int i = 0; i < tmp.length(); i++) {
  2137. Ref<InputEventKey> k;
  2138. k.instantiate();
  2139. if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
  2140. continue;
  2141. }
  2142. if (keycode == Key::NONE) {
  2143. keycode = (Key)physical_keycode;
  2144. }
  2145. _get_key_modifier_state(xkeyevent->state, k);
  2146. k->set_window_id(p_window);
  2147. k->set_unicode(tmp[i]);
  2148. k->set_pressed(keypress);
  2149. k->set_keycode(keycode);
  2150. k->set_physical_keycode((Key)physical_keycode);
  2151. k->set_echo(false);
  2152. if (k->get_keycode() == Key::BACKTAB) {
  2153. //make it consistent across platforms.
  2154. k->set_keycode(Key::TAB);
  2155. k->set_physical_keycode(Key::TAB);
  2156. k->set_shift_pressed(true);
  2157. }
  2158. Input::get_singleton()->parse_input_event(k);
  2159. }
  2160. memfree(utf8string);
  2161. return;
  2162. }
  2163. memfree(utf8string);
  2164. #else
  2165. do {
  2166. int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
  2167. xmbstring[mnbytes] = '\0';
  2168. if (status == XBufferOverflow) {
  2169. xmblen = mnbytes + 1;
  2170. xmbstring = (char *)memrealloc(xmbstring, xmblen);
  2171. }
  2172. } while (status == XBufferOverflow);
  2173. #endif
  2174. }
  2175. /* Phase 2, obtain a Godot keycode from the keysym */
  2176. // KeyMappingX11 just translated the X11 keysym to a PIGUI
  2177. // keysym, so it works in all platforms the same.
  2178. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2179. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2180. /* Phase 3, obtain a unicode character from the keysym */
  2181. // KeyMappingX11 also translates keysym to unicode.
  2182. // It does a binary search on a table to translate
  2183. // most properly.
  2184. unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
  2185. /* Phase 4, determine if event must be filtered */
  2186. // This seems to be a side-effect of using XIM.
  2187. // XFilterEvent looks like a core X11 function,
  2188. // but it's actually just used to see if we must
  2189. // ignore a deadkey, or events XIM determines
  2190. // must not reach the actual gui.
  2191. // Guess it was a design problem of the extension
  2192. bool keypress = xkeyevent->type == KeyPress;
  2193. if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {
  2194. return;
  2195. }
  2196. if (keycode == Key::NONE) {
  2197. keycode = (Key)physical_keycode;
  2198. }
  2199. /* Phase 5, determine modifier mask */
  2200. // No problems here, except I had no way to
  2201. // know Mod1 was ALT and Mod4 was META (applekey/winkey)
  2202. // just tried Mods until i found them.
  2203. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask));
  2204. Ref<InputEventKey> k;
  2205. k.instantiate();
  2206. k->set_window_id(p_window);
  2207. _get_key_modifier_state(xkeyevent->state, k);
  2208. /* Phase 6, determine echo character */
  2209. // Echo characters in X11 are a keyrelease and a keypress
  2210. // one after the other with the (almot) same timestamp.
  2211. // To detect them, i compare to the next event in list and
  2212. // check that their difference in time is below a threshold.
  2213. if (xkeyevent->type != KeyPress) {
  2214. p_echo = false;
  2215. // make sure there are events pending,
  2216. // so this call won't block.
  2217. if (p_event_index + 1 < p_events.size()) {
  2218. XEvent &peek_event = p_events[p_event_index + 1];
  2219. // I'm using a threshold of 5 msecs,
  2220. // since sometimes there seems to be a little
  2221. // jitter. I'm still not convinced that all this approach
  2222. // is correct, but the xorg developers are
  2223. // not very helpful today.
  2224. #define ABSDIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y)))
  2225. ::Time threshold = ABSDIFF(peek_event.xkey.time, xkeyevent->time);
  2226. #undef ABSDIFF
  2227. if (peek_event.type == KeyPress && threshold < 5) {
  2228. KeySym rk;
  2229. XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr);
  2230. if (rk == keysym_keycode) {
  2231. // Consume to next event.
  2232. ++p_event_index;
  2233. _handle_key_event(p_window, (XKeyEvent *)&peek_event, p_events, p_event_index, true);
  2234. return; //ignore current, echo next
  2235. }
  2236. }
  2237. // use the time from peek_event so it always works
  2238. }
  2239. // save the time to check for echo when keypress happens
  2240. }
  2241. /* Phase 7, send event to Window */
  2242. k->set_pressed(keypress);
  2243. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2244. keycode -= int('a' - 'A');
  2245. }
  2246. k->set_keycode(keycode);
  2247. k->set_physical_keycode((Key)physical_keycode);
  2248. k->set_unicode(unicode);
  2249. k->set_echo(p_echo);
  2250. if (k->get_keycode() == Key::BACKTAB) {
  2251. //make it consistent across platforms.
  2252. k->set_keycode(Key::TAB);
  2253. k->set_physical_keycode(Key::TAB);
  2254. k->set_shift_pressed(true);
  2255. }
  2256. //don't set mod state if modifier keys are released by themselves
  2257. //else event.is_action() will not work correctly here
  2258. if (!k->is_pressed()) {
  2259. if (k->get_keycode() == Key::SHIFT) {
  2260. k->set_shift_pressed(false);
  2261. } else if (k->get_keycode() == Key::CTRL) {
  2262. k->set_ctrl_pressed(false);
  2263. } else if (k->get_keycode() == Key::ALT) {
  2264. k->set_alt_pressed(false);
  2265. } else if (k->get_keycode() == Key::META) {
  2266. k->set_meta_pressed(false);
  2267. }
  2268. }
  2269. bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_keycode());
  2270. if (k->is_pressed()) {
  2271. if (last_is_pressed) {
  2272. k->set_echo(true);
  2273. }
  2274. }
  2275. Input::get_singleton()->parse_input_event(k);
  2276. }
  2277. Atom DisplayServerX11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property, Atom p_selection) const {
  2278. if (p_target == XInternAtom(x11_display, "TARGETS", 0)) {
  2279. // Request to list all supported targets.
  2280. Atom data[9];
  2281. data[0] = XInternAtom(x11_display, "TARGETS", 0);
  2282. data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0);
  2283. data[2] = XInternAtom(x11_display, "MULTIPLE", 0);
  2284. data[3] = XInternAtom(x11_display, "UTF8_STRING", 0);
  2285. data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
  2286. data[5] = XInternAtom(x11_display, "TEXT", 0);
  2287. data[6] = XA_STRING;
  2288. data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
  2289. data[8] = XInternAtom(x11_display, "text/plain", 0);
  2290. XChangeProperty(x11_display,
  2291. p_requestor,
  2292. p_property,
  2293. XA_ATOM,
  2294. 32,
  2295. PropModeReplace,
  2296. (unsigned char *)&data,
  2297. sizeof(data) / sizeof(data[0]));
  2298. return p_property;
  2299. } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) {
  2300. // Request to check if SAVE_TARGETS is supported, nothing special to do.
  2301. XChangeProperty(x11_display,
  2302. p_requestor,
  2303. p_property,
  2304. XInternAtom(x11_display, "NULL", False),
  2305. 32,
  2306. PropModeReplace,
  2307. nullptr,
  2308. 0);
  2309. return p_property;
  2310. } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
  2311. p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
  2312. p_target == XInternAtom(x11_display, "TEXT", 0) ||
  2313. p_target == XA_STRING ||
  2314. p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
  2315. p_target == XInternAtom(x11_display, "text/plain", 0)) {
  2316. // Directly using internal clipboard because we know our window
  2317. // is the owner during a selection request.
  2318. CharString clip;
  2319. static const char *target_type = "PRIMARY";
  2320. if (p_selection != None && String(XGetAtomName(x11_display, p_selection)) == target_type) {
  2321. clip = internal_clipboard_primary.utf8();
  2322. } else {
  2323. clip = internal_clipboard.utf8();
  2324. }
  2325. XChangeProperty(x11_display,
  2326. p_requestor,
  2327. p_property,
  2328. p_target,
  2329. 8,
  2330. PropModeReplace,
  2331. (unsigned char *)clip.get_data(),
  2332. clip.length());
  2333. return p_property;
  2334. } else {
  2335. char *target_name = XGetAtomName(x11_display, p_target);
  2336. printf("Target '%s' not supported.\n", target_name);
  2337. if (target_name) {
  2338. XFree(target_name);
  2339. }
  2340. return None;
  2341. }
  2342. }
  2343. void DisplayServerX11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const {
  2344. XEvent respond;
  2345. if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) {
  2346. // Request for multiple target conversions at once.
  2347. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False);
  2348. respond.xselection.property = None;
  2349. Atom type;
  2350. int format;
  2351. unsigned long len;
  2352. unsigned long remaining;
  2353. unsigned char *data = nullptr;
  2354. if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) {
  2355. if ((len >= 2) && data) {
  2356. Atom *targets = (Atom *)data;
  2357. for (uint64_t i = 0; i < len; i += 2) {
  2358. Atom target = targets[i];
  2359. Atom &property = targets[i + 1];
  2360. property = _process_selection_request_target(target, p_event->requestor, property, p_event->selection);
  2361. }
  2362. XChangeProperty(x11_display,
  2363. p_event->requestor,
  2364. p_event->property,
  2365. atom_pair,
  2366. 32,
  2367. PropModeReplace,
  2368. (unsigned char *)targets,
  2369. len);
  2370. respond.xselection.property = p_event->property;
  2371. }
  2372. XFree(data);
  2373. }
  2374. } else {
  2375. // Request for target conversion.
  2376. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property, p_event->selection);
  2377. }
  2378. respond.xselection.type = SelectionNotify;
  2379. respond.xselection.display = p_event->display;
  2380. respond.xselection.requestor = p_event->requestor;
  2381. respond.xselection.selection = p_event->selection;
  2382. respond.xselection.target = p_event->target;
  2383. respond.xselection.time = p_event->time;
  2384. XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond);
  2385. XFlush(x11_display);
  2386. }
  2387. void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data,
  2388. ::XPointer call_data) {
  2389. WARN_PRINT("Input method stopped");
  2390. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  2391. ds->xim = nullptr;
  2392. for (KeyValue<WindowID, WindowData> &E : ds->windows) {
  2393. E.value.xic = nullptr;
  2394. }
  2395. }
  2396. void DisplayServerX11::_window_changed(XEvent *event) {
  2397. WindowID window_id = MAIN_WINDOW_ID;
  2398. // Assign the event to the relevant window
  2399. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2400. if (event->xany.window == E.value.x11_window) {
  2401. window_id = E.key;
  2402. break;
  2403. }
  2404. }
  2405. Rect2i new_rect;
  2406. WindowData &wd = windows[window_id];
  2407. if (wd.x11_window != event->xany.window) { // Check if the correct window, in case it was not main window or anything else
  2408. return;
  2409. }
  2410. {
  2411. //the position in xconfigure is not useful here, obtain it manually
  2412. int x, y;
  2413. Window child;
  2414. XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  2415. new_rect.position.x = x;
  2416. new_rect.position.y = y;
  2417. new_rect.size.width = event->xconfigure.width;
  2418. new_rect.size.height = event->xconfigure.height;
  2419. }
  2420. if (new_rect == Rect2i(wd.position, wd.size)) {
  2421. return;
  2422. }
  2423. if (wd.xic) {
  2424. // Not portable.
  2425. window_set_ime_position(Point2(0, 1));
  2426. }
  2427. wd.position = new_rect.position;
  2428. wd.size = new_rect.size;
  2429. #if defined(VULKAN_ENABLED)
  2430. if (context_vulkan) {
  2431. context_vulkan->window_resize(window_id, wd.size.width, wd.size.height);
  2432. }
  2433. #endif
  2434. #if defined(GLES3_ENABLED)
  2435. if (gl_manager) {
  2436. gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
  2437. }
  2438. #endif
  2439. if (!wd.rect_changed_callback.is_null()) {
  2440. Rect2i r = new_rect;
  2441. Variant rect = r;
  2442. Variant *rectp = &rect;
  2443. Variant ret;
  2444. Callable::CallError ce;
  2445. wd.rect_changed_callback.call((const Variant **)&rectp, 1, ret, ce);
  2446. }
  2447. }
  2448. void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  2449. ((DisplayServerX11 *)(get_singleton()))->_dispatch_input_event(p_event);
  2450. }
  2451. void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  2452. Variant ev = p_event;
  2453. Variant *evp = &ev;
  2454. Variant ret;
  2455. Callable::CallError ce;
  2456. Ref<InputEventFromWindow> event_from_window = p_event;
  2457. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  2458. //send to a window
  2459. ERR_FAIL_COND(!windows.has(event_from_window->get_window_id()));
  2460. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  2461. if (callable.is_null()) {
  2462. return;
  2463. }
  2464. callable.call((const Variant **)&evp, 1, ret, ce);
  2465. } else {
  2466. //send to all windows
  2467. for (KeyValue<WindowID, WindowData> &E : windows) {
  2468. Callable callable = E.value.input_event_callback;
  2469. if (callable.is_null()) {
  2470. continue;
  2471. }
  2472. callable.call((const Variant **)&evp, 1, ret, ce);
  2473. }
  2474. }
  2475. }
  2476. void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  2477. if (!wd.event_callback.is_null()) {
  2478. Variant event = int(p_event);
  2479. Variant *eventp = &event;
  2480. Variant ret;
  2481. Callable::CallError ce;
  2482. wd.event_callback.call((const Variant **)&eventp, 1, ret, ce);
  2483. }
  2484. }
  2485. void DisplayServerX11::_poll_events_thread(void *ud) {
  2486. DisplayServerX11 *display_server = (DisplayServerX11 *)ud;
  2487. display_server->_poll_events();
  2488. }
  2489. Bool DisplayServerX11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) {
  2490. // Just accept all events.
  2491. return True;
  2492. }
  2493. bool DisplayServerX11::_wait_for_events() const {
  2494. int x11_fd = ConnectionNumber(x11_display);
  2495. fd_set in_fds;
  2496. XFlush(x11_display);
  2497. FD_ZERO(&in_fds);
  2498. FD_SET(x11_fd, &in_fds);
  2499. struct timeval tv;
  2500. tv.tv_usec = 0;
  2501. tv.tv_sec = 1;
  2502. // Wait for next event or timeout.
  2503. int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv);
  2504. if (num_ready_fds > 0) {
  2505. // Event received.
  2506. return true;
  2507. } else {
  2508. // Error or timeout.
  2509. if (num_ready_fds < 0) {
  2510. ERR_PRINT("_wait_for_events: select error: " + itos(errno));
  2511. }
  2512. return false;
  2513. }
  2514. }
  2515. void DisplayServerX11::_poll_events() {
  2516. while (!events_thread_done.is_set()) {
  2517. _wait_for_events();
  2518. // Process events from the queue.
  2519. {
  2520. MutexLock mutex_lock(events_mutex);
  2521. _check_pending_events(polled_events);
  2522. }
  2523. }
  2524. }
  2525. void DisplayServerX11::_check_pending_events(LocalVector<XEvent> &r_events) {
  2526. // Flush to make sure to gather all pending events.
  2527. XFlush(x11_display);
  2528. // Non-blocking wait for next event and remove it from the queue.
  2529. XEvent ev;
  2530. while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) {
  2531. // Check if the input manager wants to process the event.
  2532. if (XFilterEvent(&ev, None)) {
  2533. // Event has been filtered by the Input Manager,
  2534. // it has to be ignored and a new one will be received.
  2535. continue;
  2536. }
  2537. // Handle selection request events directly in the event thread, because
  2538. // communication through the x server takes several events sent back and forth
  2539. // and we don't want to block other programs while processing only one each frame.
  2540. if (ev.type == SelectionRequest) {
  2541. _handle_selection_request_event(&(ev.xselectionrequest));
  2542. continue;
  2543. }
  2544. r_events.push_back(ev);
  2545. }
  2546. }
  2547. void DisplayServerX11::process_events() {
  2548. _THREAD_SAFE_METHOD_
  2549. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  2550. static int frame = 0;
  2551. ++frame;
  2552. #endif
  2553. if (app_focused) {
  2554. //verify that one of the windows has focus, else send focus out notification
  2555. bool focus_found = false;
  2556. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2557. if (E.value.focused) {
  2558. focus_found = true;
  2559. break;
  2560. }
  2561. }
  2562. if (!focus_found) {
  2563. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_no_focus;
  2564. if (delta > 250) {
  2565. //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.
  2566. if (OS::get_singleton()->get_main_loop()) {
  2567. DEBUG_LOG_X11("All focus lost, triggering NOTIFICATION_APPLICATION_FOCUS_OUT\n");
  2568. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  2569. }
  2570. app_focused = false;
  2571. }
  2572. } else {
  2573. time_since_no_focus = OS::get_singleton()->get_ticks_msec();
  2574. }
  2575. }
  2576. do_mouse_warp = false;
  2577. // Is the current mouse mode one where it needs to be grabbed.
  2578. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN;
  2579. xi.pressure = 0;
  2580. xi.tilt = Vector2();
  2581. xi.pressure_supported = false;
  2582. LocalVector<XEvent> events;
  2583. {
  2584. // Block events polling while flushing events.
  2585. MutexLock mutex_lock(events_mutex);
  2586. events = polled_events;
  2587. polled_events.clear();
  2588. // Check for more pending events to avoid an extra frame delay.
  2589. _check_pending_events(events);
  2590. }
  2591. for (uint32_t event_index = 0; event_index < events.size(); ++event_index) {
  2592. XEvent &event = events[event_index];
  2593. WindowID window_id = MAIN_WINDOW_ID;
  2594. // Assign the event to the relevant window
  2595. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2596. if (event.xany.window == E.value.x11_window) {
  2597. window_id = E.key;
  2598. break;
  2599. }
  2600. }
  2601. if (XGetEventData(x11_display, &event.xcookie)) {
  2602. if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  2603. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  2604. int index = event_data->detail;
  2605. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  2606. switch (event_data->evtype) {
  2607. case XI_HierarchyChanged:
  2608. case XI_DeviceChanged: {
  2609. _refresh_device_info();
  2610. } break;
  2611. case XI_RawMotion: {
  2612. XIRawEvent *raw_event = (XIRawEvent *)event_data;
  2613. int device_id = raw_event->deviceid;
  2614. // Determine the axis used (called valuators in XInput for some forsaken reason)
  2615. // Mask is a bitmask indicating which axes are involved.
  2616. // We are interested in the values of axes 0 and 1.
  2617. if (raw_event->valuators.mask_len <= 0) {
  2618. break;
  2619. }
  2620. const double *values = raw_event->raw_values;
  2621. double rel_x = 0.0;
  2622. double rel_y = 0.0;
  2623. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) {
  2624. rel_x = *values;
  2625. values++;
  2626. }
  2627. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) {
  2628. rel_y = *values;
  2629. values++;
  2630. }
  2631. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) {
  2632. Map<int, Vector2>::Element *pen_pressure = xi.pen_pressure_range.find(device_id);
  2633. if (pen_pressure) {
  2634. Vector2 pen_pressure_range = pen_pressure->value();
  2635. if (pen_pressure_range != Vector2()) {
  2636. xi.pressure_supported = true;
  2637. xi.pressure = (*values - pen_pressure_range[0]) /
  2638. (pen_pressure_range[1] - pen_pressure_range[0]);
  2639. }
  2640. }
  2641. values++;
  2642. }
  2643. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) {
  2644. Map<int, Vector2>::Element *pen_tilt_x = xi.pen_tilt_x_range.find(device_id);
  2645. if (pen_tilt_x) {
  2646. Vector2 pen_tilt_x_range = pen_tilt_x->value();
  2647. if (pen_tilt_x_range[0] != 0 && *values < 0) {
  2648. xi.tilt.x = *values / -pen_tilt_x_range[0];
  2649. } else if (pen_tilt_x_range[1] != 0) {
  2650. xi.tilt.x = *values / pen_tilt_x_range[1];
  2651. }
  2652. }
  2653. values++;
  2654. }
  2655. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) {
  2656. Map<int, Vector2>::Element *pen_tilt_y = xi.pen_tilt_y_range.find(device_id);
  2657. if (pen_tilt_y) {
  2658. Vector2 pen_tilt_y_range = pen_tilt_y->value();
  2659. if (pen_tilt_y_range[0] != 0 && *values < 0) {
  2660. xi.tilt.y = *values / -pen_tilt_y_range[0];
  2661. } else if (pen_tilt_y_range[1] != 0) {
  2662. xi.tilt.y = *values / pen_tilt_y_range[1];
  2663. }
  2664. }
  2665. values++;
  2666. }
  2667. // https://bugs.freedesktop.org/show_bug.cgi?id=71609
  2668. // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html
  2669. if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) {
  2670. break; // Flush duplicate to avoid overly fast motion
  2671. }
  2672. xi.old_raw_pos.x = xi.raw_pos.x;
  2673. xi.old_raw_pos.y = xi.raw_pos.y;
  2674. xi.raw_pos.x = rel_x;
  2675. xi.raw_pos.y = rel_y;
  2676. Map<int, Vector2>::Element *abs_info = xi.absolute_devices.find(device_id);
  2677. if (abs_info) {
  2678. // Absolute mode device
  2679. Vector2 mult = abs_info->value();
  2680. xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x;
  2681. xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y;
  2682. } else {
  2683. // Relative mode device
  2684. xi.relative_motion.x = xi.raw_pos.x;
  2685. xi.relative_motion.y = xi.raw_pos.y;
  2686. }
  2687. xi.last_relative_time = raw_event->time;
  2688. } break;
  2689. #ifdef TOUCH_ENABLED
  2690. case XI_TouchBegin:
  2691. case XI_TouchEnd: {
  2692. bool is_begin = event_data->evtype == XI_TouchBegin;
  2693. Ref<InputEventScreenTouch> st;
  2694. st.instantiate();
  2695. st->set_window_id(window_id);
  2696. st->set_index(index);
  2697. st->set_position(pos);
  2698. st->set_pressed(is_begin);
  2699. if (is_begin) {
  2700. if (xi.state.has(index)) { // Defensive
  2701. break;
  2702. }
  2703. xi.state[index] = pos;
  2704. if (xi.state.size() == 1) {
  2705. // X11 may send a motion event when a touch gesture begins, that would result
  2706. // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out
  2707. xi.mouse_pos_to_filter = pos;
  2708. }
  2709. Input::get_singleton()->parse_input_event(st);
  2710. } else {
  2711. if (!xi.state.has(index)) { // Defensive
  2712. break;
  2713. }
  2714. xi.state.erase(index);
  2715. Input::get_singleton()->parse_input_event(st);
  2716. }
  2717. } break;
  2718. case XI_TouchUpdate: {
  2719. Map<int, Vector2>::Element *curr_pos_elem = xi.state.find(index);
  2720. if (!curr_pos_elem) { // Defensive
  2721. break;
  2722. }
  2723. if (curr_pos_elem->value() != pos) {
  2724. Ref<InputEventScreenDrag> sd;
  2725. sd.instantiate();
  2726. sd->set_window_id(window_id);
  2727. sd->set_index(index);
  2728. sd->set_position(pos);
  2729. sd->set_relative(pos - curr_pos_elem->value());
  2730. Input::get_singleton()->parse_input_event(sd);
  2731. curr_pos_elem->value() = pos;
  2732. }
  2733. } break;
  2734. #endif
  2735. }
  2736. }
  2737. }
  2738. XFreeEventData(x11_display, &event.xcookie);
  2739. switch (event.type) {
  2740. case MapNotify: {
  2741. DEBUG_LOG_X11("[%u] MapNotify window=%lu (%u) \n", frame, event.xmap.window, window_id);
  2742. const WindowData &wd = windows[window_id];
  2743. // Set focus when menu window is started.
  2744. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  2745. // a subwindow and its parent are both destroyed.
  2746. if (wd.menu_type && !wd.no_focus) {
  2747. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  2748. }
  2749. } break;
  2750. case Expose: {
  2751. DEBUG_LOG_X11("[%u] Expose window=%lu (%u), count='%u' \n", frame, event.xexpose.window, window_id, event.xexpose.count);
  2752. Main::force_redraw();
  2753. } break;
  2754. case NoExpose: {
  2755. DEBUG_LOG_X11("[%u] NoExpose drawable=%lu (%u) \n", frame, event.xnoexpose.drawable, window_id);
  2756. windows[window_id].minimized = true;
  2757. } break;
  2758. case VisibilityNotify: {
  2759. DEBUG_LOG_X11("[%u] VisibilityNotify window=%lu (%u), state=%u \n", frame, event.xvisibility.window, window_id, event.xvisibility.state);
  2760. XVisibilityEvent *visibility = (XVisibilityEvent *)&event;
  2761. windows[window_id].minimized = (visibility->state == VisibilityFullyObscured);
  2762. } break;
  2763. case LeaveNotify: {
  2764. DEBUG_LOG_X11("[%u] LeaveNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  2765. if (!mouse_mode_grab) {
  2766. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  2767. }
  2768. } break;
  2769. case EnterNotify: {
  2770. DEBUG_LOG_X11("[%u] EnterNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  2771. if (!mouse_mode_grab) {
  2772. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  2773. }
  2774. } break;
  2775. case FocusIn: {
  2776. DEBUG_LOG_X11("[%u] FocusIn window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  2777. WindowData &wd = windows[window_id];
  2778. last_focused_window = window_id;
  2779. wd.focused = true;
  2780. if (wd.xic) {
  2781. // Block events polling while changing input focus
  2782. // because it triggers some event polling internally.
  2783. MutexLock mutex_lock(events_mutex);
  2784. XSetICFocus(wd.xic);
  2785. }
  2786. // Keep track of focus order for overlapping windows.
  2787. static unsigned int focus_order = 0;
  2788. wd.focus_order = ++focus_order;
  2789. _send_window_event(wd, WINDOW_EVENT_FOCUS_IN);
  2790. if (mouse_mode_grab) {
  2791. // Show and update the cursor if confined and the window regained focus.
  2792. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2793. if (mouse_mode == MOUSE_MODE_CONFINED) {
  2794. XUndefineCursor(x11_display, E.value.x11_window);
  2795. } else if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { // Or re-hide it.
  2796. XDefineCursor(x11_display, E.value.x11_window, null_cursor);
  2797. }
  2798. XGrabPointer(
  2799. x11_display, E.value.x11_window, True,
  2800. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  2801. GrabModeAsync, GrabModeAsync, E.value.x11_window, None, CurrentTime);
  2802. }
  2803. }
  2804. #ifdef TOUCH_ENABLED
  2805. // Grab touch devices to avoid OS gesture interference
  2806. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  2807. XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask);
  2808. }*/
  2809. #endif
  2810. if (!app_focused) {
  2811. if (OS::get_singleton()->get_main_loop()) {
  2812. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  2813. }
  2814. app_focused = true;
  2815. }
  2816. } break;
  2817. case FocusOut: {
  2818. DEBUG_LOG_X11("[%u] FocusOut window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  2819. WindowData &wd = windows[window_id];
  2820. wd.focused = false;
  2821. if (wd.xic) {
  2822. // Block events polling while changing input focus
  2823. // because it triggers some event polling internally.
  2824. MutexLock mutex_lock(events_mutex);
  2825. XUnsetICFocus(wd.xic);
  2826. }
  2827. Input::get_singleton()->release_pressed_events();
  2828. _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT);
  2829. if (mouse_mode_grab) {
  2830. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2831. //dear X11, I try, I really try, but you never work, you do whatever you want.
  2832. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2833. // Show the cursor if we're in captured mode so it doesn't look weird.
  2834. XUndefineCursor(x11_display, E.value.x11_window);
  2835. }
  2836. }
  2837. XUngrabPointer(x11_display, CurrentTime);
  2838. }
  2839. #ifdef TOUCH_ENABLED
  2840. // Ungrab touch devices so input works as usual while we are unfocused
  2841. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  2842. XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime);
  2843. }*/
  2844. // Release every pointer to avoid sticky points
  2845. for (const KeyValue<int, Vector2> &E : xi.state) {
  2846. Ref<InputEventScreenTouch> st;
  2847. st.instantiate();
  2848. st->set_index(E.key);
  2849. st->set_window_id(window_id);
  2850. st->set_position(E.value);
  2851. Input::get_singleton()->parse_input_event(st);
  2852. }
  2853. xi.state.clear();
  2854. #endif
  2855. } break;
  2856. case ConfigureNotify: {
  2857. 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);
  2858. const WindowData &wd = windows[window_id];
  2859. // Set focus when menu window is re-used.
  2860. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  2861. // a subwindow and its parent are both destroyed.
  2862. if (wd.menu_type && !wd.no_focus) {
  2863. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  2864. }
  2865. _window_changed(&event);
  2866. } break;
  2867. case ButtonPress:
  2868. case ButtonRelease: {
  2869. /* exit in case of a mouse button press */
  2870. last_timestamp = event.xbutton.time;
  2871. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2872. event.xbutton.x = last_mouse_pos.x;
  2873. event.xbutton.y = last_mouse_pos.y;
  2874. }
  2875. Ref<InputEventMouseButton> mb;
  2876. mb.instantiate();
  2877. mb->set_window_id(window_id);
  2878. _get_key_modifier_state(event.xbutton.state, mb);
  2879. mb->set_button_index((MouseButton)event.xbutton.button);
  2880. if (mb->get_button_index() == MouseButton::RIGHT) {
  2881. mb->set_button_index(MouseButton::MIDDLE);
  2882. } else if (mb->get_button_index() == MouseButton::MIDDLE) {
  2883. mb->set_button_index(MouseButton::RIGHT);
  2884. }
  2885. mb->set_button_mask(_get_mouse_button_state(mb->get_button_index(), event.xbutton.type));
  2886. mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
  2887. mb->set_global_position(mb->get_position());
  2888. mb->set_pressed((event.type == ButtonPress));
  2889. const WindowData &wd = windows[window_id];
  2890. if (event.type == ButtonPress) {
  2891. DEBUG_LOG_X11("[%u] ButtonPress window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  2892. // Ensure window focus on click.
  2893. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  2894. // a subwindow and its parent are both destroyed.
  2895. if (!wd.no_focus) {
  2896. XSetInputFocus(x11_display, wd.x11_window, RevertToPointerRoot, CurrentTime);
  2897. }
  2898. uint64_t diff = OS::get_singleton()->get_ticks_usec() / 1000 - last_click_ms;
  2899. if (mb->get_button_index() == last_click_button_index) {
  2900. if (diff < 400 && Vector2(last_click_pos).distance_to(Vector2(event.xbutton.x, event.xbutton.y)) < 5) {
  2901. last_click_ms = 0;
  2902. last_click_pos = Point2i(-100, -100);
  2903. last_click_button_index = MouseButton::NONE;
  2904. mb->set_double_click(true);
  2905. }
  2906. } else if (mb->get_button_index() < MouseButton::WHEEL_UP || mb->get_button_index() > MouseButton::WHEEL_RIGHT) {
  2907. last_click_button_index = mb->get_button_index();
  2908. }
  2909. if (!mb->is_double_click()) {
  2910. last_click_ms += diff;
  2911. last_click_pos = Point2i(event.xbutton.x, event.xbutton.y);
  2912. }
  2913. } else {
  2914. DEBUG_LOG_X11("[%u] ButtonRelease window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  2915. if (!wd.focused) {
  2916. // Propagate the event to the focused window,
  2917. // because it's received only on the topmost window.
  2918. // Note: This is needed for drag & drop to work between windows,
  2919. // because the engine expects events to keep being processed
  2920. // on the same window dragging started.
  2921. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2922. const WindowData &wd_other = E.value;
  2923. WindowID window_id_other = E.key;
  2924. if (wd_other.focused) {
  2925. if (window_id_other != window_id) {
  2926. int x, y;
  2927. Window child;
  2928. XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xbutton.x, event.xbutton.y, &x, &y, &child);
  2929. mb->set_window_id(window_id_other);
  2930. mb->set_position(Vector2(x, y));
  2931. mb->set_global_position(mb->get_position());
  2932. Input::get_singleton()->parse_input_event(mb);
  2933. }
  2934. break;
  2935. }
  2936. }
  2937. }
  2938. }
  2939. Input::get_singleton()->parse_input_event(mb);
  2940. } break;
  2941. case MotionNotify: {
  2942. // The X11 API requires filtering one-by-one through the motion
  2943. // notify events, in order to figure out which event is the one
  2944. // generated by warping the mouse pointer.
  2945. WindowID focused_window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID;
  2946. while (true) {
  2947. 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) {
  2948. //this is likely the warp event since it was warped here
  2949. center = Vector2(event.xmotion.x, event.xmotion.y);
  2950. break;
  2951. }
  2952. if (event_index + 1 < events.size()) {
  2953. const XEvent &next_event = events[event_index + 1];
  2954. if (next_event.type == MotionNotify) {
  2955. ++event_index;
  2956. event = next_event;
  2957. } else {
  2958. break;
  2959. }
  2960. } else {
  2961. break;
  2962. }
  2963. }
  2964. last_timestamp = event.xmotion.time;
  2965. // Motion is also simple.
  2966. // A little hack is in order
  2967. // to be able to send relative motion events.
  2968. Point2i pos(event.xmotion.x, event.xmotion.y);
  2969. // Avoidance of spurious mouse motion (see handling of touch)
  2970. bool filter = false;
  2971. // Adding some tolerance to match better Point2i to Vector2
  2972. if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) {
  2973. filter = true;
  2974. }
  2975. // Invalidate to avoid filtering a possible legitimate similar event coming later
  2976. xi.mouse_pos_to_filter = Vector2(1e10, 1e10);
  2977. if (filter) {
  2978. break;
  2979. }
  2980. const WindowData &wd = windows[window_id];
  2981. bool focused = wd.focused;
  2982. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2983. if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) {
  2984. break;
  2985. }
  2986. Point2i new_center = pos;
  2987. pos = last_mouse_pos + xi.relative_motion;
  2988. center = new_center;
  2989. do_mouse_warp = focused; // warp the cursor if we're focused in
  2990. }
  2991. if (!last_mouse_pos_valid) {
  2992. last_mouse_pos = pos;
  2993. last_mouse_pos_valid = true;
  2994. }
  2995. // Hackish but relative mouse motion is already handled in the RawMotion event.
  2996. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does).
  2997. // Therefore, RawMotion cannot be the authority on absolute mouse position.
  2998. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion.
  2999. // Therefore, MotionNotify cannot be the authority on relative mouse motion.
  3000. // This means we need to take a combined approach...
  3001. Point2i rel;
  3002. // Only use raw input if in capture mode. Otherwise use the classic behavior.
  3003. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3004. rel = xi.relative_motion;
  3005. } else {
  3006. rel = pos - last_mouse_pos;
  3007. }
  3008. // Reset to prevent lingering motion
  3009. xi.relative_motion.x = 0;
  3010. xi.relative_motion.y = 0;
  3011. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3012. pos = Point2i(windows[focused_window_id].size.width / 2, windows[focused_window_id].size.height / 2);
  3013. }
  3014. Ref<InputEventMouseMotion> mm;
  3015. mm.instantiate();
  3016. mm->set_window_id(window_id);
  3017. if (xi.pressure_supported) {
  3018. mm->set_pressure(xi.pressure);
  3019. } else {
  3020. mm->set_pressure(bool(mouse_get_button_state() & MouseButton::MASK_LEFT) ? 1.0f : 0.0f);
  3021. }
  3022. mm->set_tilt(xi.tilt);
  3023. _get_key_modifier_state(event.xmotion.state, mm);
  3024. mm->set_button_mask((MouseButton)mouse_get_button_state());
  3025. mm->set_position(pos);
  3026. mm->set_global_position(pos);
  3027. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  3028. mm->set_relative(rel);
  3029. last_mouse_pos = pos;
  3030. // printf("rel: %d,%d\n", rel.x, rel.y );
  3031. // Don't propagate the motion event unless we have focus
  3032. // this is so that the relative motion doesn't get messed up
  3033. // after we regain focus.
  3034. if (focused) {
  3035. Input::get_singleton()->parse_input_event(mm);
  3036. } else {
  3037. // Propagate the event to the focused window,
  3038. // because it's received only on the topmost window.
  3039. // Note: This is needed for drag & drop to work between windows,
  3040. // because the engine expects events to keep being processed
  3041. // on the same window dragging started.
  3042. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3043. const WindowData &wd_other = E.value;
  3044. if (wd_other.focused) {
  3045. int x, y;
  3046. Window child;
  3047. XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xmotion.x, event.xmotion.y, &x, &y, &child);
  3048. Point2i pos_focused(x, y);
  3049. mm->set_window_id(E.key);
  3050. mm->set_position(pos_focused);
  3051. mm->set_global_position(pos_focused);
  3052. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  3053. Input::get_singleton()->parse_input_event(mm);
  3054. break;
  3055. }
  3056. }
  3057. }
  3058. } break;
  3059. case KeyPress:
  3060. case KeyRelease: {
  3061. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  3062. if (event.type == KeyPress) {
  3063. 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);
  3064. } else {
  3065. 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);
  3066. }
  3067. #endif
  3068. last_timestamp = event.xkey.time;
  3069. // key event is a little complex, so
  3070. // it will be handled in its own function.
  3071. _handle_key_event(window_id, &event.xkey, events, event_index);
  3072. } break;
  3073. case SelectionNotify:
  3074. if (event.xselection.target == requested) {
  3075. Property p = _read_property(x11_display, windows[window_id].x11_window, XInternAtom(x11_display, "PRIMARY", 0));
  3076. Vector<String> files = String((char *)p.data).split("\n", false);
  3077. for (int i = 0; i < files.size(); i++) {
  3078. files.write[i] = files[i].replace("file://", "").uri_decode().strip_edges();
  3079. }
  3080. if (!windows[window_id].drop_files_callback.is_null()) {
  3081. Variant v = files;
  3082. Variant *vp = &v;
  3083. Variant ret;
  3084. Callable::CallError ce;
  3085. windows[window_id].drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  3086. }
  3087. //Reply that all is well.
  3088. XClientMessageEvent m;
  3089. memset(&m, 0, sizeof(m));
  3090. m.type = ClientMessage;
  3091. m.display = x11_display;
  3092. m.window = xdnd_source_window;
  3093. m.message_type = xdnd_finished;
  3094. m.format = 32;
  3095. m.data.l[0] = windows[window_id].x11_window;
  3096. m.data.l[1] = 1;
  3097. m.data.l[2] = xdnd_action_copy; //We only ever copy.
  3098. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
  3099. }
  3100. break;
  3101. case ClientMessage:
  3102. if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) {
  3103. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  3104. }
  3105. else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
  3106. //File(s) have been dragged over the window, check for supported target (text/uri-list)
  3107. xdnd_version = (event.xclient.data.l[1] >> 24);
  3108. Window source = event.xclient.data.l[0];
  3109. bool more_than_3 = event.xclient.data.l[1] & 1;
  3110. if (more_than_3) {
  3111. Property p = _read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
  3112. requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
  3113. } else {
  3114. requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
  3115. }
  3116. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
  3117. //xdnd position event, reply with an XDND status message
  3118. //just depending on type of data for now
  3119. XClientMessageEvent m;
  3120. memset(&m, 0, sizeof(m));
  3121. m.type = ClientMessage;
  3122. m.display = event.xclient.display;
  3123. m.window = event.xclient.data.l[0];
  3124. m.message_type = xdnd_status;
  3125. m.format = 32;
  3126. m.data.l[0] = windows[window_id].x11_window;
  3127. m.data.l[1] = (requested != None);
  3128. m.data.l[2] = 0; //empty rectangle
  3129. m.data.l[3] = 0;
  3130. m.data.l[4] = xdnd_action_copy;
  3131. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  3132. XFlush(x11_display);
  3133. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
  3134. if (requested != None) {
  3135. xdnd_source_window = event.xclient.data.l[0];
  3136. if (xdnd_version >= 1) {
  3137. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, event.xclient.data.l[2]);
  3138. } else {
  3139. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, CurrentTime);
  3140. }
  3141. } else {
  3142. //Reply that we're not interested.
  3143. XClientMessageEvent m;
  3144. memset(&m, 0, sizeof(m));
  3145. m.type = ClientMessage;
  3146. m.display = event.xclient.display;
  3147. m.window = event.xclient.data.l[0];
  3148. m.message_type = xdnd_finished;
  3149. m.format = 32;
  3150. m.data.l[0] = windows[window_id].x11_window;
  3151. m.data.l[1] = 0;
  3152. m.data.l[2] = None; //Failed.
  3153. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  3154. }
  3155. }
  3156. break;
  3157. default:
  3158. break;
  3159. }
  3160. }
  3161. XFlush(x11_display);
  3162. if (do_mouse_warp) {
  3163. XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window,
  3164. 0, 0, 0, 0, (int)windows[MAIN_WINDOW_ID].size.width / 2, (int)windows[MAIN_WINDOW_ID].size.height / 2);
  3165. /*
  3166. Window root, child;
  3167. int root_x, root_y;
  3168. int win_x, win_y;
  3169. unsigned int mask;
  3170. XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );
  3171. printf("Root: %d,%d\n", root_x, root_y);
  3172. printf("Win: %d,%d\n", win_x, win_y);
  3173. */
  3174. }
  3175. Input::get_singleton()->flush_buffered_events();
  3176. }
  3177. void DisplayServerX11::release_rendering_thread() {
  3178. #if defined(GLES3_ENABLED)
  3179. // gl_manager->release_current();
  3180. #endif
  3181. }
  3182. void DisplayServerX11::make_rendering_thread() {
  3183. #if defined(GLES3_ENABLED)
  3184. // gl_manager->make_current();
  3185. #endif
  3186. }
  3187. void DisplayServerX11::swap_buffers() {
  3188. #if defined(GLES3_ENABLED)
  3189. if (gl_manager) {
  3190. gl_manager->swap_buffers();
  3191. }
  3192. #endif
  3193. }
  3194. void DisplayServerX11::_update_context(WindowData &wd) {
  3195. XClassHint *classHint = XAllocClassHint();
  3196. if (classHint) {
  3197. CharString name_str;
  3198. switch (context) {
  3199. case CONTEXT_EDITOR:
  3200. name_str = "Godot_Editor";
  3201. break;
  3202. case CONTEXT_PROJECTMAN:
  3203. name_str = "Godot_ProjectList";
  3204. break;
  3205. case CONTEXT_ENGINE:
  3206. name_str = "Godot_Engine";
  3207. break;
  3208. }
  3209. CharString class_str;
  3210. if (context == CONTEXT_ENGINE) {
  3211. String config_name = GLOBAL_GET("application/config/name");
  3212. if (config_name.length() == 0) {
  3213. class_str = "Godot_Engine";
  3214. } else {
  3215. class_str = config_name.utf8();
  3216. }
  3217. } else {
  3218. class_str = "Godot";
  3219. }
  3220. classHint->res_class = class_str.ptrw();
  3221. classHint->res_name = name_str.ptrw();
  3222. XSetClassHint(x11_display, wd.x11_window, classHint);
  3223. XFree(classHint);
  3224. }
  3225. }
  3226. void DisplayServerX11::set_context(Context p_context) {
  3227. _THREAD_SAFE_METHOD_
  3228. context = p_context;
  3229. for (KeyValue<WindowID, WindowData> &E : windows) {
  3230. _update_context(E.value);
  3231. }
  3232. }
  3233. void DisplayServerX11::set_native_icon(const String &p_filename) {
  3234. WARN_PRINT("Native icon not supported by this display server.");
  3235. }
  3236. bool g_set_icon_error = false;
  3237. int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
  3238. g_set_icon_error = true;
  3239. return 0;
  3240. }
  3241. void DisplayServerX11::set_icon(const Ref<Image> &p_icon) {
  3242. _THREAD_SAFE_METHOD_
  3243. WindowData &wd = windows[MAIN_WINDOW_ID];
  3244. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
  3245. Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
  3246. if (p_icon.is_valid()) {
  3247. Ref<Image> img = p_icon->duplicate();
  3248. img->convert(Image::FORMAT_RGBA8);
  3249. while (true) {
  3250. int w = img->get_width();
  3251. int h = img->get_height();
  3252. if (g_set_icon_error) {
  3253. g_set_icon_error = false;
  3254. WARN_PRINT("Icon too large, attempting to resize icon.");
  3255. int new_width, new_height;
  3256. if (w > h) {
  3257. new_width = w / 2;
  3258. new_height = h * new_width / w;
  3259. } else {
  3260. new_height = h / 2;
  3261. new_width = w * new_height / h;
  3262. }
  3263. w = new_width;
  3264. h = new_height;
  3265. if (!w || !h) {
  3266. WARN_PRINT("Unable to set icon.");
  3267. break;
  3268. }
  3269. img->resize(w, h, Image::INTERPOLATE_CUBIC);
  3270. }
  3271. // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
  3272. Vector<long> pd;
  3273. pd.resize(2 + w * h);
  3274. pd.write[0] = w;
  3275. pd.write[1] = h;
  3276. const uint8_t *r = img->get_data().ptr();
  3277. long *wr = &pd.write[2];
  3278. uint8_t const *pr = r;
  3279. for (int i = 0; i < w * h; i++) {
  3280. long v = 0;
  3281. // A R G B
  3282. v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
  3283. *wr++ = v;
  3284. pr += 4;
  3285. }
  3286. if (net_wm_icon != None) {
  3287. XChangeProperty(x11_display, wd.x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
  3288. }
  3289. if (!g_set_icon_error) {
  3290. break;
  3291. }
  3292. }
  3293. } else {
  3294. XDeleteProperty(x11_display, wd.x11_window, net_wm_icon);
  3295. }
  3296. XFlush(x11_display);
  3297. XSetErrorHandler(oldHandler);
  3298. }
  3299. void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  3300. _THREAD_SAFE_METHOD_
  3301. #if defined(VULKAN_ENABLED)
  3302. if (context_vulkan) {
  3303. context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
  3304. }
  3305. #endif
  3306. #if defined(GLES3_ENABLED)
  3307. if (gl_manager) {
  3308. gl_manager->set_use_vsync(p_vsync_mode == DisplayServer::VSYNC_ENABLED);
  3309. }
  3310. #endif
  3311. }
  3312. DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const {
  3313. _THREAD_SAFE_METHOD_
  3314. #if defined(VULKAN_ENABLED)
  3315. if (context_vulkan) {
  3316. return context_vulkan->get_vsync_mode(p_window);
  3317. }
  3318. #endif
  3319. #if defined(GLES3_ENABLED)
  3320. if (gl_manager) {
  3321. return gl_manager->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  3322. }
  3323. #endif
  3324. return DisplayServer::VSYNC_ENABLED;
  3325. }
  3326. Vector<String> DisplayServerX11::get_rendering_drivers_func() {
  3327. Vector<String> drivers;
  3328. #ifdef VULKAN_ENABLED
  3329. drivers.push_back("vulkan");
  3330. #endif
  3331. #ifdef GLES3_ENABLED
  3332. drivers.push_back("opengl3");
  3333. #endif
  3334. return drivers;
  3335. }
  3336. 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) {
  3337. DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  3338. if (r_error != OK) {
  3339. OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.\n"
  3340. "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n"
  3341. "If you have updated your graphics drivers recently, try rebooting.",
  3342. "Unable to initialize Video driver");
  3343. }
  3344. return ds;
  3345. }
  3346. DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  3347. //Create window
  3348. long visualMask = VisualScreenMask;
  3349. int numberOfVisuals;
  3350. XVisualInfo vInfoTemplate = {};
  3351. vInfoTemplate.screen = DefaultScreen(x11_display);
  3352. XVisualInfo *visualInfo = XGetVisualInfo(x11_display, visualMask, &vInfoTemplate, &numberOfVisuals);
  3353. Colormap colormap = XCreateColormap(x11_display, RootWindow(x11_display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
  3354. XSetWindowAttributes windowAttributes = {};
  3355. windowAttributes.colormap = colormap;
  3356. windowAttributes.background_pixel = 0xFFFFFFFF;
  3357. windowAttributes.border_pixel = 0;
  3358. windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
  3359. unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;
  3360. WindowID id = window_id_counter++;
  3361. WindowData &wd = windows[id];
  3362. if ((id != MAIN_WINDOW_ID) && (p_flags & WINDOW_FLAG_BORDERLESS_BIT)) {
  3363. wd.menu_type = true;
  3364. }
  3365. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  3366. wd.menu_type = true;
  3367. wd.no_focus = true;
  3368. }
  3369. // Setup for menu subwindows:
  3370. // - override_redirect forces the WM not to interfere with the window, to avoid delays due to
  3371. // handling decorations and placement.
  3372. // On the other hand, focus changes need to be handled manually when this is set.
  3373. // - save_under is a hint for the WM to keep the content of windows behind to avoid repaint.
  3374. if (wd.menu_type) {
  3375. windowAttributes.override_redirect = True;
  3376. windowAttributes.save_under = True;
  3377. valuemask |= CWOverrideRedirect | CWSaveUnder;
  3378. }
  3379. {
  3380. 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);
  3381. // Enable receiving notification when the window is initialized (MapNotify)
  3382. // so the focus can be set at the right time.
  3383. if (wd.menu_type && !wd.no_focus) {
  3384. XSelectInput(x11_display, wd.x11_window, StructureNotifyMask);
  3385. }
  3386. //associate PID
  3387. // make PID known to X11
  3388. {
  3389. const long pid = OS::get_singleton()->get_process_id();
  3390. Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False);
  3391. if (net_wm_pid != None) {
  3392. XChangeProperty(x11_display, wd.x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
  3393. }
  3394. }
  3395. long im_event_mask = 0;
  3396. {
  3397. XIEventMask all_event_mask;
  3398. XSetWindowAttributes new_attr;
  3399. new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
  3400. ButtonReleaseMask | EnterWindowMask |
  3401. LeaveWindowMask | PointerMotionMask |
  3402. Button1MotionMask |
  3403. Button2MotionMask | Button3MotionMask |
  3404. Button4MotionMask | Button5MotionMask |
  3405. ButtonMotionMask | KeymapStateMask |
  3406. ExposureMask | VisibilityChangeMask |
  3407. StructureNotifyMask |
  3408. SubstructureNotifyMask | SubstructureRedirectMask |
  3409. FocusChangeMask | PropertyChangeMask |
  3410. ColormapChangeMask | OwnerGrabButtonMask |
  3411. im_event_mask;
  3412. XChangeWindowAttributes(x11_display, wd.x11_window, CWEventMask, &new_attr);
  3413. static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  3414. all_event_mask.deviceid = XIAllDevices;
  3415. all_event_mask.mask_len = sizeof(all_mask_data);
  3416. all_event_mask.mask = all_mask_data;
  3417. XISetMask(all_event_mask.mask, XI_HierarchyChanged);
  3418. #ifdef TOUCH_ENABLED
  3419. if (xi.touch_devices.size()) {
  3420. XISetMask(all_event_mask.mask, XI_TouchBegin);
  3421. XISetMask(all_event_mask.mask, XI_TouchUpdate);
  3422. XISetMask(all_event_mask.mask, XI_TouchEnd);
  3423. XISetMask(all_event_mask.mask, XI_TouchOwnership);
  3424. }
  3425. #endif
  3426. XISelectEvents(x11_display, wd.x11_window, &all_event_mask, 1);
  3427. }
  3428. /* set the titlebar name */
  3429. XStoreName(x11_display, wd.x11_window, "Godot");
  3430. XSetWMProtocols(x11_display, wd.x11_window, &wm_delete, 1);
  3431. if (xdnd_aware != None) {
  3432. XChangeProperty(x11_display, wd.x11_window, xdnd_aware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdnd_version, 1);
  3433. }
  3434. if (xim && xim_style) {
  3435. // Block events polling while changing input focus
  3436. // because it triggers some event polling internally.
  3437. MutexLock mutex_lock(events_mutex);
  3438. wd.xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, wd.x11_window, XNFocusWindow, wd.x11_window, (char *)nullptr);
  3439. if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) {
  3440. WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
  3441. XDestroyIC(wd.xic);
  3442. wd.xic = nullptr;
  3443. }
  3444. if (wd.xic) {
  3445. XUnsetICFocus(wd.xic);
  3446. } else {
  3447. WARN_PRINT("XCreateIC couldn't create wd.xic");
  3448. }
  3449. } else {
  3450. wd.xic = nullptr;
  3451. WARN_PRINT("XCreateIC couldn't create wd.xic");
  3452. }
  3453. _update_context(wd);
  3454. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  3455. Hints hints;
  3456. Atom property;
  3457. hints.flags = 2;
  3458. hints.decorations = 0;
  3459. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  3460. if (property != None) {
  3461. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  3462. }
  3463. }
  3464. if (wd.menu_type) {
  3465. // Set Utility type to disable fade animations.
  3466. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
  3467. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  3468. if (wt_atom != None && type_atom != None) {
  3469. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  3470. }
  3471. } else {
  3472. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
  3473. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  3474. if (wt_atom != None && type_atom != None) {
  3475. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  3476. }
  3477. }
  3478. _update_size_hints(id);
  3479. #if defined(VULKAN_ENABLED)
  3480. if (context_vulkan) {
  3481. Error err = context_vulkan->window_create(id, p_vsync_mode, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height);
  3482. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan window");
  3483. }
  3484. #endif
  3485. #ifdef GLES3_ENABLED
  3486. if (gl_manager) {
  3487. Error err = gl_manager->window_create(id, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height);
  3488. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL window");
  3489. }
  3490. #endif
  3491. //set_class_hint(x11_display, wd.x11_window);
  3492. XFlush(x11_display);
  3493. XSync(x11_display, False);
  3494. //XSetErrorHandler(oldHandler);
  3495. XFree(visualInfo);
  3496. }
  3497. window_set_mode(p_mode, id);
  3498. //sync size
  3499. {
  3500. XWindowAttributes xwa;
  3501. XSync(x11_display, False);
  3502. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3503. wd.position.x = xwa.x;
  3504. wd.position.y = xwa.y;
  3505. wd.size.width = xwa.width;
  3506. wd.size.height = xwa.height;
  3507. }
  3508. //set cursor
  3509. if (cursors[current_cursor] != None) {
  3510. XDefineCursor(x11_display, wd.x11_window, cursors[current_cursor]);
  3511. }
  3512. return id;
  3513. }
  3514. 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) {
  3515. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3516. r_error = OK;
  3517. current_cursor = CURSOR_ARROW;
  3518. mouse_mode = MOUSE_MODE_VISIBLE;
  3519. for (int i = 0; i < CURSOR_MAX; i++) {
  3520. cursors[i] = None;
  3521. img[i] = nullptr;
  3522. }
  3523. xmbstring = nullptr;
  3524. last_click_ms = 0;
  3525. last_click_button_index = MouseButton::NONE;
  3526. last_click_pos = Point2i(-100, -100);
  3527. last_timestamp = 0;
  3528. last_mouse_pos_valid = false;
  3529. last_keyrelease_time = 0;
  3530. XInitThreads(); //always use threads
  3531. /** XLIB INITIALIZATION **/
  3532. x11_display = XOpenDisplay(nullptr);
  3533. if (!x11_display) {
  3534. ERR_PRINT("X11 Display is not available");
  3535. r_error = ERR_UNAVAILABLE;
  3536. return;
  3537. }
  3538. char *modifiers = nullptr;
  3539. Bool xkb_dar = False;
  3540. XAutoRepeatOn(x11_display);
  3541. xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr);
  3542. // Try to support IME if detectable auto-repeat is supported
  3543. if (xkb_dar == True) {
  3544. #ifdef X_HAVE_UTF8_STRING
  3545. // Xutf8LookupString will be used later instead of XmbLookupString before
  3546. // the multibyte sequences can be converted to unicode string.
  3547. modifiers = XSetLocaleModifiers("");
  3548. #endif
  3549. }
  3550. if (modifiers == nullptr) {
  3551. if (OS::get_singleton()->is_stdout_verbose()) {
  3552. WARN_PRINT("IME is disabled");
  3553. }
  3554. XSetLocaleModifiers("@im=none");
  3555. WARN_PRINT("Error setting locale modifiers");
  3556. }
  3557. const char *err;
  3558. xrr_get_monitors = nullptr;
  3559. xrr_free_monitors = nullptr;
  3560. int xrandr_major = 0;
  3561. int xrandr_minor = 0;
  3562. int event_base, error_base;
  3563. xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
  3564. xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
  3565. if (!xrandr_handle) {
  3566. err = dlerror();
  3567. // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2...
  3568. // In case this happens for other X11 platforms in the future, let's give it a try too before failing.
  3569. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY);
  3570. if (!xrandr_handle) {
  3571. fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
  3572. }
  3573. } else {
  3574. XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
  3575. if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
  3576. xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
  3577. if (!xrr_get_monitors) {
  3578. err = dlerror();
  3579. fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
  3580. } else {
  3581. xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
  3582. if (!xrr_free_monitors) {
  3583. err = dlerror();
  3584. fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
  3585. xrr_get_monitors = nullptr;
  3586. }
  3587. }
  3588. }
  3589. }
  3590. if (!_refresh_device_info()) {
  3591. OS::get_singleton()->alert("Your system does not support XInput 2.\n"
  3592. "Please upgrade your distribution.",
  3593. "Unable to initialize XInput");
  3594. r_error = ERR_UNAVAILABLE;
  3595. return;
  3596. }
  3597. xim = XOpenIM(x11_display, nullptr, nullptr, nullptr);
  3598. if (xim == nullptr) {
  3599. WARN_PRINT("XOpenIM failed");
  3600. xim_style = 0L;
  3601. } else {
  3602. ::XIMCallback im_destroy_callback;
  3603. im_destroy_callback.client_data = (::XPointer)(this);
  3604. im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback);
  3605. if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
  3606. nullptr) != nullptr) {
  3607. WARN_PRINT("Error setting XIM destroy callback");
  3608. }
  3609. ::XIMStyles *xim_styles = nullptr;
  3610. xim_style = 0L;
  3611. char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr);
  3612. if (imvalret != nullptr || xim_styles == nullptr) {
  3613. fprintf(stderr, "Input method doesn't support any styles\n");
  3614. }
  3615. if (xim_styles) {
  3616. xim_style = 0L;
  3617. for (int i = 0; i < xim_styles->count_styles; i++) {
  3618. if (xim_styles->supported_styles[i] ==
  3619. (XIMPreeditNothing | XIMStatusNothing)) {
  3620. xim_style = xim_styles->supported_styles[i];
  3621. break;
  3622. }
  3623. }
  3624. XFree(xim_styles);
  3625. }
  3626. XFree(imvalret);
  3627. }
  3628. /* Atorm internment */
  3629. wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
  3630. //Set Xdnd (drag & drop) support
  3631. xdnd_aware = XInternAtom(x11_display, "XdndAware", False);
  3632. xdnd_version = 5;
  3633. xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
  3634. xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
  3635. xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
  3636. xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
  3637. xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
  3638. xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
  3639. xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
  3640. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3641. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3642. rendering_driver = p_rendering_driver;
  3643. bool driver_found = false;
  3644. #if defined(VULKAN_ENABLED)
  3645. if (rendering_driver == "vulkan") {
  3646. context_vulkan = memnew(VulkanContextX11);
  3647. if (context_vulkan->initialize() != OK) {
  3648. memdelete(context_vulkan);
  3649. context_vulkan = nullptr;
  3650. r_error = ERR_CANT_CREATE;
  3651. ERR_FAIL_MSG("Could not initialize Vulkan");
  3652. }
  3653. driver_found = true;
  3654. }
  3655. #endif
  3656. // Initialize context and rendering device.
  3657. #if defined(GLES3_ENABLED)
  3658. if (rendering_driver == "opengl3") {
  3659. if (getenv("DRI_PRIME") == nullptr) {
  3660. int use_prime = -1;
  3661. if (getenv("PRIMUS_DISPLAY") ||
  3662. getenv("PRIMUS_libGLd") ||
  3663. getenv("PRIMUS_libGLa") ||
  3664. getenv("PRIMUS_libGL") ||
  3665. getenv("PRIMUS_LOAD_GLOBAL") ||
  3666. getenv("BUMBLEBEE_SOCKET")) {
  3667. print_verbose("Optirun/primusrun detected. Skipping GPU detection");
  3668. use_prime = 0;
  3669. }
  3670. // Some tools use fake libGL libraries and have them override the real one using
  3671. // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its
  3672. // runtime and includes system `/lib` and `/lib64`... so ignore Steam.
  3673. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) {
  3674. String ld_library_path(getenv("LD_LIBRARY_PATH"));
  3675. Vector<String> libraries = ld_library_path.split(":");
  3676. for (int i = 0; i < libraries.size(); ++i) {
  3677. if (FileAccess::exists(libraries[i] + "/libGL.so.1") ||
  3678. FileAccess::exists(libraries[i] + "/libGL.so")) {
  3679. print_verbose("Custom libGL override detected. Skipping GPU detection");
  3680. use_prime = 0;
  3681. }
  3682. }
  3683. }
  3684. if (use_prime == -1) {
  3685. print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic.");
  3686. use_prime = detect_prime();
  3687. }
  3688. if (use_prime) {
  3689. print_line("Found discrete GPU, setting DRI_PRIME=1 to use it.");
  3690. print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU.");
  3691. setenv("DRI_PRIME", "1", 1);
  3692. }
  3693. }
  3694. GLManager_X11::ContextType opengl_api_type = GLManager_X11::GLES_3_0_COMPATIBLE;
  3695. gl_manager = memnew(GLManager_X11(p_resolution, opengl_api_type));
  3696. if (gl_manager->initialize() != OK) {
  3697. memdelete(gl_manager);
  3698. gl_manager = nullptr;
  3699. r_error = ERR_UNAVAILABLE;
  3700. return;
  3701. }
  3702. driver_found = true;
  3703. // gl_manager->set_use_vsync(current_videomode.use_vsync);
  3704. if (true) {
  3705. // if (RasterizerGLES3::is_viable() == OK) {
  3706. // RasterizerGLES3::register_config();
  3707. RasterizerGLES3::make_current();
  3708. } else {
  3709. memdelete(gl_manager);
  3710. gl_manager = nullptr;
  3711. r_error = ERR_UNAVAILABLE;
  3712. return;
  3713. }
  3714. }
  3715. #endif
  3716. if (!driver_found) {
  3717. r_error = ERR_UNAVAILABLE;
  3718. ERR_FAIL_MSG("Video driver not found");
  3719. }
  3720. Point2i window_position(
  3721. (screen_get_size(0).width - p_resolution.width) / 2,
  3722. (screen_get_size(0).height - p_resolution.height) / 2);
  3723. WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution));
  3724. if (main_window == INVALID_WINDOW_ID) {
  3725. r_error = ERR_CANT_CREATE;
  3726. return;
  3727. }
  3728. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3729. if (p_flags & (1 << i)) {
  3730. window_set_flag(WindowFlags(i), true, main_window);
  3731. }
  3732. }
  3733. show_window(main_window);
  3734. #if defined(VULKAN_ENABLED)
  3735. if (rendering_driver == "vulkan") {
  3736. //temporary
  3737. rendering_device_vulkan = memnew(RenderingDeviceVulkan);
  3738. rendering_device_vulkan->initialize(context_vulkan);
  3739. RendererCompositorRD::make_current();
  3740. }
  3741. #endif
  3742. {
  3743. //set all event master mask
  3744. XIEventMask all_master_event_mask;
  3745. static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  3746. all_master_event_mask.deviceid = XIAllMasterDevices;
  3747. all_master_event_mask.mask_len = sizeof(all_master_mask_data);
  3748. all_master_event_mask.mask = all_master_mask_data;
  3749. XISetMask(all_master_event_mask.mask, XI_DeviceChanged);
  3750. XISetMask(all_master_event_mask.mask, XI_RawMotion);
  3751. XISelectEvents(x11_display, DefaultRootWindow(x11_display), &all_master_event_mask, 1);
  3752. }
  3753. cursor_size = XcursorGetDefaultSize(x11_display);
  3754. cursor_theme = XcursorGetTheme(x11_display);
  3755. if (!cursor_theme) {
  3756. print_verbose("XcursorGetTheme could not get cursor theme");
  3757. cursor_theme = "default";
  3758. }
  3759. for (int i = 0; i < CURSOR_MAX; i++) {
  3760. static const char *cursor_file[] = {
  3761. "left_ptr",
  3762. "xterm",
  3763. "hand2",
  3764. "cross",
  3765. "watch",
  3766. "left_ptr_watch",
  3767. "fleur",
  3768. "dnd-move",
  3769. "crossed_circle",
  3770. "v_double_arrow",
  3771. "h_double_arrow",
  3772. "size_bdiag",
  3773. "size_fdiag",
  3774. "move",
  3775. "row_resize",
  3776. "col_resize",
  3777. "question_arrow"
  3778. };
  3779. img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
  3780. if (!img[i]) {
  3781. const char *fallback = nullptr;
  3782. switch (i) {
  3783. case CURSOR_POINTING_HAND:
  3784. fallback = "pointer";
  3785. break;
  3786. case CURSOR_CROSS:
  3787. fallback = "crosshair";
  3788. break;
  3789. case CURSOR_WAIT:
  3790. fallback = "wait";
  3791. break;
  3792. case CURSOR_BUSY:
  3793. fallback = "progress";
  3794. break;
  3795. case CURSOR_DRAG:
  3796. fallback = "grabbing";
  3797. break;
  3798. case CURSOR_CAN_DROP:
  3799. fallback = "hand1";
  3800. break;
  3801. case CURSOR_FORBIDDEN:
  3802. fallback = "forbidden";
  3803. break;
  3804. case CURSOR_VSIZE:
  3805. fallback = "ns-resize";
  3806. break;
  3807. case CURSOR_HSIZE:
  3808. fallback = "ew-resize";
  3809. break;
  3810. case CURSOR_BDIAGSIZE:
  3811. fallback = "fd_double_arrow";
  3812. break;
  3813. case CURSOR_FDIAGSIZE:
  3814. fallback = "bd_double_arrow";
  3815. break;
  3816. case CURSOR_MOVE:
  3817. img[i] = img[CURSOR_DRAG];
  3818. break;
  3819. case CURSOR_VSPLIT:
  3820. fallback = "sb_v_double_arrow";
  3821. break;
  3822. case CURSOR_HSPLIT:
  3823. fallback = "sb_h_double_arrow";
  3824. break;
  3825. case CURSOR_HELP:
  3826. fallback = "help";
  3827. break;
  3828. }
  3829. if (fallback != nullptr) {
  3830. img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size);
  3831. }
  3832. }
  3833. if (img[i]) {
  3834. cursors[i] = XcursorImageLoadCursor(x11_display, img[i]);
  3835. } else {
  3836. print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
  3837. }
  3838. }
  3839. {
  3840. // Creating an empty/transparent cursor
  3841. // Create 1x1 bitmap
  3842. Pixmap cursormask = XCreatePixmap(x11_display,
  3843. RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
  3844. // Fill with zero
  3845. XGCValues xgc;
  3846. xgc.function = GXclear;
  3847. GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
  3848. XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
  3849. // Color value doesn't matter. Mask zero means no foreground or background will be drawn
  3850. XColor col = {};
  3851. Cursor cursor = XCreatePixmapCursor(x11_display,
  3852. cursormask, // source (using cursor mask as placeholder, since it'll all be ignored)
  3853. cursormask, // mask
  3854. &col, &col, 0, 0);
  3855. XFreePixmap(x11_display, cursormask);
  3856. XFreeGC(x11_display, gc);
  3857. if (cursor == None) {
  3858. ERR_PRINT("FAILED CREATING CURSOR");
  3859. }
  3860. null_cursor = cursor;
  3861. }
  3862. cursor_set_shape(CURSOR_BUSY);
  3863. requested = None;
  3864. /*if (p_desired.layered) {
  3865. set_window_per_pixel_transparency_enabled(true);
  3866. }*/
  3867. XEvent xevent;
  3868. while (XPending(x11_display) > 0) {
  3869. XNextEvent(x11_display, &xevent);
  3870. if (xevent.type == ConfigureNotify) {
  3871. _window_changed(&xevent);
  3872. }
  3873. }
  3874. events_thread.start(_poll_events_thread, this);
  3875. _update_real_mouse_position(windows[MAIN_WINDOW_ID]);
  3876. #ifdef DBUS_ENABLED
  3877. screensaver = memnew(FreeDesktopScreenSaver);
  3878. screen_set_keep_on(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true));
  3879. #endif
  3880. r_error = OK;
  3881. }
  3882. DisplayServerX11::~DisplayServerX11() {
  3883. // Send owned clipboard data to clipboard manager before exit.
  3884. Window x11_main_window = windows[MAIN_WINDOW_ID].x11_window;
  3885. _clipboard_transfer_ownership(XA_PRIMARY, x11_main_window);
  3886. _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_main_window);
  3887. events_thread_done.set();
  3888. events_thread.wait_to_finish();
  3889. //destroy all windows
  3890. for (KeyValue<WindowID, WindowData> &E : windows) {
  3891. #ifdef VULKAN_ENABLED
  3892. if (context_vulkan) {
  3893. context_vulkan->window_destroy(E.key);
  3894. }
  3895. #endif
  3896. #ifdef GLES3_ENABLED
  3897. if (gl_manager) {
  3898. gl_manager->window_destroy(E.key);
  3899. }
  3900. #endif
  3901. WindowData &wd = E.value;
  3902. if (wd.xic) {
  3903. XDestroyIC(wd.xic);
  3904. wd.xic = nullptr;
  3905. }
  3906. XUnmapWindow(x11_display, wd.x11_window);
  3907. XDestroyWindow(x11_display, wd.x11_window);
  3908. }
  3909. //destroy drivers
  3910. #if defined(VULKAN_ENABLED)
  3911. if (rendering_device_vulkan) {
  3912. rendering_device_vulkan->finalize();
  3913. memdelete(rendering_device_vulkan);
  3914. rendering_device_vulkan = nullptr;
  3915. }
  3916. if (context_vulkan) {
  3917. memdelete(context_vulkan);
  3918. context_vulkan = nullptr;
  3919. }
  3920. #endif
  3921. #ifdef GLES3_ENABLED
  3922. if (gl_manager) {
  3923. memdelete(gl_manager);
  3924. gl_manager = nullptr;
  3925. }
  3926. #endif
  3927. if (xrandr_handle) {
  3928. dlclose(xrandr_handle);
  3929. }
  3930. for (int i = 0; i < CURSOR_MAX; i++) {
  3931. if (cursors[i] != None) {
  3932. XFreeCursor(x11_display, cursors[i]);
  3933. }
  3934. if (img[i] != nullptr) {
  3935. XcursorImageDestroy(img[i]);
  3936. }
  3937. };
  3938. if (xim) {
  3939. XCloseIM(xim);
  3940. }
  3941. XCloseDisplay(x11_display);
  3942. if (xmbstring) {
  3943. memfree(xmbstring);
  3944. }
  3945. #ifdef DBUS_ENABLED
  3946. memdelete(screensaver);
  3947. #endif
  3948. }
  3949. void DisplayServerX11::register_x11_driver() {
  3950. register_create_function("x11", create_func, get_rendering_drivers_func);
  3951. }
  3952. #endif // X11 enabled