display_server_x11.cpp 142 KB

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