display_server_x11.cpp 130 KB

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