display_server_x11.cpp 152 KB

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