2
0

os_x11.cpp 112 KB

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