display_server_x11.cpp 129 KB

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