display_server_x11.cpp 129 KB

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