display_server_x11.cpp 155 KB

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