display_server_x11.cpp 126 KB

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