display_server_x11.cpp 140 KB

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