display_server_x11.cpp 145 KB

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