display_server_x11.cpp 132 KB

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