wayland_thread.cpp 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547
  1. /**************************************************************************/
  2. /* wayland_thread.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "wayland_thread.h"
  31. #include "core/config/engine.h"
  32. #ifdef WAYLAND_ENABLED
  33. #ifdef __FreeBSD__
  34. #include <dev/evdev/input-event-codes.h>
  35. #else
  36. // Assume Linux.
  37. #include <linux/input-event-codes.h>
  38. #endif
  39. // For the actual polling thread.
  40. #include <poll.h>
  41. // For shared memory buffer creation.
  42. #include <fcntl.h>
  43. #include <sys/mman.h>
  44. #include <unistd.h>
  45. // Fix the wl_array_for_each macro to work with C++. This is based on the
  46. // original from `wayland-util.h` in the Wayland client library.
  47. #undef wl_array_for_each
  48. #define wl_array_for_each(pos, array) \
  49. for (pos = (decltype(pos))(array)->data; (const char *)pos < ((const char *)(array)->data + (array)->size); (pos)++)
  50. #define WAYLAND_THREAD_DEBUG_LOGS_ENABLED
  51. #ifdef WAYLAND_THREAD_DEBUG_LOGS_ENABLED
  52. #define DEBUG_LOG_WAYLAND_THREAD(...) print_verbose(__VA_ARGS__)
  53. #else
  54. #define DEBUG_LOG_WAYLAND_THREAD(...)
  55. #endif
  56. // Since we're never going to use this interface directly, it's not worth
  57. // generating the whole deal.
  58. #define FIFO_INTERFACE_NAME "wp_fifo_manager_v1"
  59. // Read the content pointed by fd into a Vector<uint8_t>.
  60. Vector<uint8_t> WaylandThread::_read_fd(int fd) {
  61. // This is pretty much an arbitrary size.
  62. uint32_t chunk_size = 2048;
  63. LocalVector<uint8_t> data;
  64. data.resize(chunk_size);
  65. uint32_t bytes_read = 0;
  66. while (true) {
  67. ssize_t last_bytes_read = read(fd, data.ptr() + bytes_read, chunk_size);
  68. if (last_bytes_read < 0) {
  69. ERR_PRINT(vformat("Read error %d.", errno));
  70. data.clear();
  71. break;
  72. }
  73. if (last_bytes_read == 0) {
  74. // We're done, we've reached the EOF.
  75. DEBUG_LOG_WAYLAND_THREAD(vformat("Done reading %d bytes.", bytes_read));
  76. close(fd);
  77. data.resize(bytes_read);
  78. break;
  79. }
  80. DEBUG_LOG_WAYLAND_THREAD(vformat("Read chunk of %d bytes.", last_bytes_read));
  81. bytes_read += last_bytes_read;
  82. // Increase the buffer size by one chunk in preparation of the next read.
  83. data.resize(bytes_read + chunk_size);
  84. }
  85. return Vector<uint8_t>(data);
  86. }
  87. // Based on the wayland book's shared memory boilerplate (PD/CC0).
  88. // See: https://wayland-book.com/surfaces/shared-memory.html
  89. int WaylandThread::_allocate_shm_file(size_t size) {
  90. int retries = 100;
  91. do {
  92. // Generate a random name.
  93. char name[] = "/wl_shm-godot-XXXXXX";
  94. for (long unsigned int i = sizeof(name) - 7; i < sizeof(name) - 1; i++) {
  95. name[i] = Math::random('A', 'Z');
  96. }
  97. // Try to open a shared memory object with that name.
  98. int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
  99. if (fd >= 0) {
  100. // Success, unlink its name as we just need the file descriptor.
  101. shm_unlink(name);
  102. // Resize the file to the requested length.
  103. int ret;
  104. do {
  105. ret = ftruncate(fd, size);
  106. } while (ret < 0 && errno == EINTR);
  107. if (ret < 0) {
  108. close(fd);
  109. return -1;
  110. }
  111. return fd;
  112. }
  113. retries--;
  114. } while (retries > 0 && errno == EEXIST);
  115. return -1;
  116. }
  117. // Return the content of a wl_data_offer.
  118. Vector<uint8_t> WaylandThread::_wl_data_offer_read(struct wl_display *p_display, const char *p_mime, struct wl_data_offer *p_offer) {
  119. if (!p_offer) {
  120. return Vector<uint8_t>();
  121. }
  122. int fds[2];
  123. if (pipe(fds) == 0) {
  124. wl_data_offer_receive(p_offer, p_mime, fds[1]);
  125. // Let the compositor know about the pipe.
  126. // NOTE: It's important to just flush and not roundtrip here as we would risk
  127. // running some cleanup event, like for example `wl_data_device::leave`. We're
  128. // going to wait for the message anyways as the read will probably block if
  129. // the compositor doesn't read from the other end of the pipe.
  130. wl_display_flush(p_display);
  131. // Close the write end of the pipe, which we don't need and would otherwise
  132. // just stall our next `read`s.
  133. close(fds[1]);
  134. return _read_fd(fds[0]);
  135. }
  136. return Vector<uint8_t>();
  137. }
  138. // Read the content of a wp_primary_selection_offer.
  139. Vector<uint8_t> WaylandThread::_wp_primary_selection_offer_read(struct wl_display *p_display, const char *p_mime, struct zwp_primary_selection_offer_v1 *p_offer) {
  140. if (!p_offer) {
  141. return Vector<uint8_t>();
  142. }
  143. int fds[2];
  144. if (pipe(fds) == 0) {
  145. zwp_primary_selection_offer_v1_receive(p_offer, p_mime, fds[1]);
  146. // NOTE: It's important to just flush and not roundtrip here as we would risk
  147. // running some cleanup event, like for example `wl_data_device::leave`. We're
  148. // going to wait for the message anyways as the read will probably block if
  149. // the compositor doesn't read from the other end of the pipe.
  150. wl_display_flush(p_display);
  151. // Close the write end of the pipe, which we don't need and would otherwise
  152. // just stall our next `read`s.
  153. close(fds[1]);
  154. return _read_fd(fds[0]);
  155. }
  156. return Vector<uint8_t>();
  157. }
  158. Ref<InputEventKey> WaylandThread::_seat_state_get_key_event(SeatState *p_ss, xkb_keycode_t p_keycode, bool p_pressed) {
  159. Ref<InputEventKey> event;
  160. ERR_FAIL_NULL_V(p_ss, event);
  161. Key shifted_key = KeyMappingXKB::get_keycode(xkb_state_key_get_one_sym(p_ss->xkb_state, p_keycode));
  162. Key plain_key = Key::NONE;
  163. // NOTE: xkbcommon's API really encourages to apply the modifier state but we
  164. // only want a "plain" symbol so that we can convert it into a godot keycode.
  165. const xkb_keysym_t *syms = nullptr;
  166. int num_sys = xkb_keymap_key_get_syms_by_level(p_ss->xkb_keymap, p_keycode, p_ss->current_layout_index, 0, &syms);
  167. if (num_sys > 0 && syms) {
  168. plain_key = KeyMappingXKB::get_keycode(syms[0]);
  169. }
  170. Key physical_keycode = KeyMappingXKB::get_scancode(p_keycode);
  171. KeyLocation key_location = KeyMappingXKB::get_location(p_keycode);
  172. uint32_t unicode = xkb_state_key_get_utf32(p_ss->xkb_state, p_keycode);
  173. Key keycode = Key::NONE;
  174. if ((shifted_key & Key::SPECIAL) != Key::NONE || (plain_key & Key::SPECIAL) != Key::NONE) {
  175. keycode = shifted_key;
  176. }
  177. if (keycode == Key::NONE) {
  178. keycode = plain_key;
  179. }
  180. if (keycode == Key::NONE) {
  181. keycode = physical_keycode;
  182. }
  183. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  184. keycode -= 'a' - 'A';
  185. }
  186. if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {
  187. return event;
  188. }
  189. event.instantiate();
  190. event->set_window_id(p_ss->focused_id);
  191. // Set all pressed modifiers.
  192. event->set_shift_pressed(p_ss->shift_pressed);
  193. event->set_ctrl_pressed(p_ss->ctrl_pressed);
  194. event->set_alt_pressed(p_ss->alt_pressed);
  195. event->set_meta_pressed(p_ss->meta_pressed);
  196. event->set_pressed(p_pressed);
  197. event->set_keycode(keycode);
  198. event->set_physical_keycode(physical_keycode);
  199. event->set_location(key_location);
  200. if (unicode != 0) {
  201. event->set_key_label(fix_key_label(unicode, keycode));
  202. } else {
  203. event->set_key_label(keycode);
  204. }
  205. if (p_pressed) {
  206. event->set_unicode(fix_unicode(unicode));
  207. }
  208. // Taken from DisplayServerX11.
  209. if (event->get_keycode() == Key::BACKTAB) {
  210. // Make it consistent across platforms.
  211. event->set_keycode(Key::TAB);
  212. event->set_physical_keycode(Key::TAB);
  213. event->set_shift_pressed(true);
  214. }
  215. return event;
  216. }
  217. // NOTE: Due to the nature of the way keys are encoded, there's an ambiguity
  218. // regarding "special" keys. In other words: there's no reliable way of
  219. // switching between a special key and a character key if not marking a
  220. // different Godot keycode, even if we're actually using the same XKB raw
  221. // keycode. This means that, during this switch, the old key will get "stuck",
  222. // as it will never receive a release event. This method returns the necessary
  223. // event to fix this if needed.
  224. Ref<InputEventKey> WaylandThread::_seat_state_get_unstuck_key_event(SeatState *p_ss, xkb_keycode_t p_keycode, bool p_pressed, Key p_key) {
  225. Ref<InputEventKey> event;
  226. if (p_pressed) {
  227. Key *old_key = p_ss->pressed_keycodes.getptr(p_keycode);
  228. if (old_key != nullptr && *old_key != p_key) {
  229. print_verbose(vformat("%s and %s have same keycode. Generating release event for %s", keycode_get_string(*old_key), keycode_get_string(p_key), keycode_get_string(*old_key)));
  230. event = _seat_state_get_key_event(p_ss, p_keycode, false);
  231. if (event.is_valid()) {
  232. event->set_keycode(*old_key);
  233. }
  234. }
  235. p_ss->pressed_keycodes[p_keycode] = p_key;
  236. } else {
  237. p_ss->pressed_keycodes.erase(p_keycode);
  238. }
  239. return event;
  240. }
  241. void WaylandThread::_seat_state_handle_xkb_keycode(SeatState *p_ss, xkb_keycode_t p_xkb_keycode, bool p_pressed, bool p_echo) {
  242. ERR_FAIL_NULL(p_ss);
  243. WaylandThread *wayland_thread = p_ss->wayland_thread;
  244. ERR_FAIL_NULL(wayland_thread);
  245. Key last_key = Key::NONE;
  246. xkb_compose_status compose_status = xkb_compose_state_get_status(p_ss->xkb_compose_state);
  247. if (p_pressed) {
  248. xkb_keysym_t keysym = xkb_state_key_get_one_sym(p_ss->xkb_state, p_xkb_keycode);
  249. xkb_compose_feed_result compose_result = xkb_compose_state_feed(p_ss->xkb_compose_state, keysym);
  250. compose_status = xkb_compose_state_get_status(p_ss->xkb_compose_state);
  251. if (compose_result == XKB_COMPOSE_FEED_ACCEPTED && compose_status == XKB_COMPOSE_COMPOSED) {
  252. // We need to generate multiple key events to report the composed result, One
  253. // per character.
  254. char str_xkb[256] = {};
  255. int str_xkb_size = xkb_compose_state_get_utf8(p_ss->xkb_compose_state, str_xkb, 255);
  256. String decoded_str = String::utf8(str_xkb, str_xkb_size);
  257. for (int i = 0; i < decoded_str.length(); ++i) {
  258. Ref<InputEventKey> k = _seat_state_get_key_event(p_ss, p_xkb_keycode, p_pressed);
  259. if (k.is_null()) {
  260. continue;
  261. }
  262. k->set_unicode(decoded_str[i]);
  263. k->set_echo(p_echo);
  264. Ref<InputEventMessage> msg;
  265. msg.instantiate();
  266. msg->event = k;
  267. wayland_thread->push_message(msg);
  268. last_key = k->get_keycode();
  269. }
  270. }
  271. }
  272. if (last_key == Key::NONE && compose_status == XKB_COMPOSE_NOTHING) {
  273. // If we continued with other compose status (e.g. XKB_COMPOSE_COMPOSING) we
  274. // would get the composing keys _and_ the result.
  275. Ref<InputEventKey> k = _seat_state_get_key_event(p_ss, p_xkb_keycode, p_pressed);
  276. if (k.is_valid()) {
  277. k->set_echo(p_echo);
  278. Ref<InputEventMessage> msg;
  279. msg.instantiate();
  280. msg->event = k;
  281. wayland_thread->push_message(msg);
  282. last_key = k->get_keycode();
  283. }
  284. }
  285. if (last_key != Key::NONE) {
  286. Ref<InputEventKey> uk = _seat_state_get_unstuck_key_event(p_ss, p_xkb_keycode, p_pressed, last_key);
  287. if (uk.is_valid()) {
  288. Ref<InputEventMessage> u_msg;
  289. u_msg.instantiate();
  290. u_msg->event = uk;
  291. wayland_thread->push_message(u_msg);
  292. }
  293. }
  294. }
  295. void WaylandThread::_set_current_seat(struct wl_seat *p_seat) {
  296. if (p_seat == wl_seat_current) {
  297. return;
  298. }
  299. SeatState *old_state = wl_seat_get_seat_state(wl_seat_current);
  300. if (old_state) {
  301. seat_state_unlock_pointer(old_state);
  302. }
  303. SeatState *new_state = wl_seat_get_seat_state(p_seat);
  304. seat_state_unlock_pointer(new_state);
  305. wl_seat_current = p_seat;
  306. pointer_set_constraint(pointer_constraint);
  307. }
  308. // Returns whether it loaded the theme or not.
  309. bool WaylandThread::_load_cursor_theme(int p_cursor_size) {
  310. if (wl_cursor_theme) {
  311. wl_cursor_theme_destroy(wl_cursor_theme);
  312. wl_cursor_theme = nullptr;
  313. }
  314. if (cursor_theme_name.is_empty()) {
  315. cursor_theme_name = "default";
  316. }
  317. print_verbose(vformat("Loading cursor theme \"%s\" size %d.", cursor_theme_name, p_cursor_size));
  318. wl_cursor_theme = wl_cursor_theme_load(cursor_theme_name.utf8().get_data(), p_cursor_size, registry.wl_shm);
  319. ERR_FAIL_NULL_V_MSG(wl_cursor_theme, false, "Can't load any cursor theme.");
  320. static const char *cursor_names[] = {
  321. "left_ptr",
  322. "xterm",
  323. "hand2",
  324. "cross",
  325. "watch",
  326. "left_ptr_watch",
  327. "fleur",
  328. "dnd-move",
  329. "crossed_circle",
  330. "v_double_arrow",
  331. "h_double_arrow",
  332. "size_bdiag",
  333. "size_fdiag",
  334. "move",
  335. "row_resize",
  336. "col_resize",
  337. "question_arrow"
  338. };
  339. static const char *cursor_names_fallback[] = {
  340. nullptr,
  341. nullptr,
  342. "pointer",
  343. "cross",
  344. "wait",
  345. "progress",
  346. "grabbing",
  347. "hand1",
  348. "forbidden",
  349. "ns-resize",
  350. "ew-resize",
  351. "fd_double_arrow",
  352. "bd_double_arrow",
  353. "fleur",
  354. "sb_v_double_arrow",
  355. "sb_h_double_arrow",
  356. "help"
  357. };
  358. for (int i = 0; i < DisplayServer::CURSOR_MAX; i++) {
  359. struct wl_cursor *cursor = wl_cursor_theme_get_cursor(wl_cursor_theme, cursor_names[i]);
  360. if (!cursor && cursor_names_fallback[i]) {
  361. cursor = wl_cursor_theme_get_cursor(wl_cursor_theme, cursor_names_fallback[i]);
  362. }
  363. if (cursor && cursor->image_count > 0) {
  364. wl_cursors[i] = cursor;
  365. } else {
  366. wl_cursors[i] = nullptr;
  367. print_verbose("Failed loading cursor: " + String(cursor_names[i]));
  368. }
  369. }
  370. return true;
  371. }
  372. void WaylandThread::_update_scale(int p_scale) {
  373. if (p_scale <= cursor_scale) {
  374. return;
  375. }
  376. print_verbose(vformat("Bumping cursor scale to %d", p_scale));
  377. // There's some display that's bigger than the cache, let's update it.
  378. cursor_scale = p_scale;
  379. if (wl_cursor_theme == nullptr) {
  380. // Ugh. Either we're still initializing (this must've been called from the
  381. // first roundtrips) or we had some error while doing so. We'll trust that it
  382. // will be updated for us if needed.
  383. return;
  384. }
  385. int cursor_size = unscaled_cursor_size * p_scale;
  386. if (_load_cursor_theme(cursor_size)) {
  387. for (struct wl_seat *wl_seat : registry.wl_seats) {
  388. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  389. ERR_FAIL_NULL(ss);
  390. seat_state_update_cursor(ss);
  391. }
  392. }
  393. }
  394. void WaylandThread::_wl_registry_on_global(void *data, struct wl_registry *wl_registry, uint32_t name, const char *interface, uint32_t version) {
  395. RegistryState *registry = (RegistryState *)data;
  396. ERR_FAIL_NULL(registry);
  397. if (strcmp(interface, wl_shm_interface.name) == 0) {
  398. registry->wl_shm = (struct wl_shm *)wl_registry_bind(wl_registry, name, &wl_shm_interface, 1);
  399. registry->wl_shm_name = name;
  400. return;
  401. }
  402. // NOTE: Deprecated.
  403. if (strcmp(interface, zxdg_exporter_v1_interface.name) == 0) {
  404. registry->xdg_exporter_v1 = (struct zxdg_exporter_v1 *)wl_registry_bind(wl_registry, name, &zxdg_exporter_v1_interface, 1);
  405. registry->xdg_exporter_v1_name = name;
  406. return;
  407. }
  408. if (strcmp(interface, zxdg_exporter_v2_interface.name) == 0) {
  409. registry->xdg_exporter_v2 = (struct zxdg_exporter_v2 *)wl_registry_bind(wl_registry, name, &zxdg_exporter_v2_interface, 1);
  410. registry->xdg_exporter_v2_name = name;
  411. return;
  412. }
  413. if (strcmp(interface, wl_compositor_interface.name) == 0) {
  414. registry->wl_compositor = (struct wl_compositor *)wl_registry_bind(wl_registry, name, &wl_compositor_interface, CLAMP((int)version, 1, 6));
  415. registry->wl_compositor_name = name;
  416. return;
  417. }
  418. if (strcmp(interface, wl_data_device_manager_interface.name) == 0) {
  419. registry->wl_data_device_manager = (struct wl_data_device_manager *)wl_registry_bind(wl_registry, name, &wl_data_device_manager_interface, CLAMP((int)version, 1, 3));
  420. registry->wl_data_device_manager_name = name;
  421. // This global creates some seat data. Let's do that for the ones already available.
  422. for (struct wl_seat *wl_seat : registry->wl_seats) {
  423. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  424. ERR_FAIL_NULL(ss);
  425. if (ss->wl_data_device == nullptr) {
  426. ss->wl_data_device = wl_data_device_manager_get_data_device(registry->wl_data_device_manager, wl_seat);
  427. wl_data_device_add_listener(ss->wl_data_device, &wl_data_device_listener, ss);
  428. }
  429. }
  430. return;
  431. }
  432. if (strcmp(interface, wl_output_interface.name) == 0) {
  433. struct wl_output *wl_output = (struct wl_output *)wl_registry_bind(wl_registry, name, &wl_output_interface, CLAMP((int)version, 1, 4));
  434. wl_proxy_tag_godot((struct wl_proxy *)wl_output);
  435. registry->wl_outputs.push_back(wl_output);
  436. ScreenState *ss = memnew(ScreenState);
  437. ss->wl_output_name = name;
  438. ss->wayland_thread = registry->wayland_thread;
  439. wl_proxy_tag_godot((struct wl_proxy *)wl_output);
  440. wl_output_add_listener(wl_output, &wl_output_listener, ss);
  441. return;
  442. }
  443. if (strcmp(interface, wl_seat_interface.name) == 0) {
  444. struct wl_seat *wl_seat = (struct wl_seat *)wl_registry_bind(wl_registry, name, &wl_seat_interface, CLAMP((int)version, 1, 9));
  445. wl_proxy_tag_godot((struct wl_proxy *)wl_seat);
  446. SeatState *ss = memnew(SeatState);
  447. ss->wl_seat = wl_seat;
  448. ss->wl_seat_name = name;
  449. ss->registry = registry;
  450. ss->wayland_thread = registry->wayland_thread;
  451. // Some extra stuff depends on other globals. We'll initialize them if the
  452. // globals are already there, otherwise we'll have to do that once and if they
  453. // get announced.
  454. //
  455. // NOTE: Don't forget to also bind/destroy with the respective global.
  456. if (!ss->wl_data_device && registry->wl_data_device_manager) {
  457. // Clipboard & DnD.
  458. ss->wl_data_device = wl_data_device_manager_get_data_device(registry->wl_data_device_manager, wl_seat);
  459. wl_data_device_add_listener(ss->wl_data_device, &wl_data_device_listener, ss);
  460. }
  461. if (!ss->wp_primary_selection_device && registry->wp_primary_selection_device_manager) {
  462. // Primary selection.
  463. ss->wp_primary_selection_device = zwp_primary_selection_device_manager_v1_get_device(registry->wp_primary_selection_device_manager, wl_seat);
  464. zwp_primary_selection_device_v1_add_listener(ss->wp_primary_selection_device, &wp_primary_selection_device_listener, ss);
  465. }
  466. if (!ss->wp_tablet_seat && registry->wp_tablet_manager) {
  467. // Tablet.
  468. ss->wp_tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(registry->wp_tablet_manager, wl_seat);
  469. zwp_tablet_seat_v2_add_listener(ss->wp_tablet_seat, &wp_tablet_seat_listener, ss);
  470. }
  471. if (!ss->wp_text_input && registry->wp_text_input_manager) {
  472. // IME.
  473. ss->wp_text_input = zwp_text_input_manager_v3_get_text_input(registry->wp_text_input_manager, wl_seat);
  474. zwp_text_input_v3_add_listener(ss->wp_text_input, &wp_text_input_listener, ss);
  475. }
  476. registry->wl_seats.push_back(wl_seat);
  477. wl_seat_add_listener(wl_seat, &wl_seat_listener, ss);
  478. if (registry->wayland_thread->wl_seat_current == nullptr) {
  479. registry->wayland_thread->_set_current_seat(wl_seat);
  480. }
  481. return;
  482. }
  483. if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
  484. registry->xdg_wm_base = (struct xdg_wm_base *)wl_registry_bind(wl_registry, name, &xdg_wm_base_interface, CLAMP((int)version, 1, 6));
  485. registry->xdg_wm_base_name = name;
  486. xdg_wm_base_add_listener(registry->xdg_wm_base, &xdg_wm_base_listener, nullptr);
  487. return;
  488. }
  489. if (strcmp(interface, wp_viewporter_interface.name) == 0) {
  490. registry->wp_viewporter = (struct wp_viewporter *)wl_registry_bind(wl_registry, name, &wp_viewporter_interface, 1);
  491. registry->wp_viewporter_name = name;
  492. }
  493. if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) {
  494. registry->wp_cursor_shape_manager = (struct wp_cursor_shape_manager_v1 *)wl_registry_bind(wl_registry, name, &wp_cursor_shape_manager_v1_interface, 1);
  495. registry->wp_cursor_shape_manager_name = name;
  496. return;
  497. }
  498. if (strcmp(interface, wp_fractional_scale_manager_v1_interface.name) == 0) {
  499. registry->wp_fractional_scale_manager = (struct wp_fractional_scale_manager_v1 *)wl_registry_bind(wl_registry, name, &wp_fractional_scale_manager_v1_interface, 1);
  500. registry->wp_fractional_scale_manager_name = name;
  501. // NOTE: We're not mapping the fractional scale object here because this is
  502. // supposed to be a "startup global". If for some reason this isn't true (who
  503. // knows), add a conditional branch for creating the add-on object.
  504. }
  505. if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
  506. registry->xdg_decoration_manager = (struct zxdg_decoration_manager_v1 *)wl_registry_bind(wl_registry, name, &zxdg_decoration_manager_v1_interface, 1);
  507. registry->xdg_decoration_manager_name = name;
  508. return;
  509. }
  510. if (strcmp(interface, xdg_system_bell_v1_interface.name) == 0) {
  511. registry->xdg_system_bell = (struct xdg_system_bell_v1 *)wl_registry_bind(wl_registry, name, &xdg_system_bell_v1_interface, 1);
  512. registry->xdg_system_bell_name = name;
  513. return;
  514. }
  515. if (strcmp(interface, xdg_toplevel_icon_manager_v1_interface.name) == 0) {
  516. registry->xdg_toplevel_icon_manager = (struct xdg_toplevel_icon_manager_v1 *)wl_registry_bind(wl_registry, name, &xdg_toplevel_icon_manager_v1_interface, 1);
  517. registry->xdg_toplevel_icon_manager_name = name;
  518. return;
  519. }
  520. if (strcmp(interface, xdg_activation_v1_interface.name) == 0) {
  521. registry->xdg_activation = (struct xdg_activation_v1 *)wl_registry_bind(wl_registry, name, &xdg_activation_v1_interface, 1);
  522. registry->xdg_activation_name = name;
  523. return;
  524. }
  525. if (strcmp(interface, zwp_primary_selection_device_manager_v1_interface.name) == 0) {
  526. registry->wp_primary_selection_device_manager = (struct zwp_primary_selection_device_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_primary_selection_device_manager_v1_interface, 1);
  527. // This global creates some seat data. Let's do that for the ones already available.
  528. for (struct wl_seat *wl_seat : registry->wl_seats) {
  529. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  530. ERR_FAIL_NULL(ss);
  531. if (!ss->wp_primary_selection_device && registry->wp_primary_selection_device_manager) {
  532. ss->wp_primary_selection_device = zwp_primary_selection_device_manager_v1_get_device(registry->wp_primary_selection_device_manager, wl_seat);
  533. zwp_primary_selection_device_v1_add_listener(ss->wp_primary_selection_device, &wp_primary_selection_device_listener, ss);
  534. }
  535. }
  536. }
  537. if (strcmp(interface, zwp_relative_pointer_manager_v1_interface.name) == 0) {
  538. registry->wp_relative_pointer_manager = (struct zwp_relative_pointer_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_relative_pointer_manager_v1_interface, 1);
  539. registry->wp_relative_pointer_manager_name = name;
  540. return;
  541. }
  542. if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) {
  543. registry->wp_pointer_constraints = (struct zwp_pointer_constraints_v1 *)wl_registry_bind(wl_registry, name, &zwp_pointer_constraints_v1_interface, 1);
  544. registry->wp_pointer_constraints_name = name;
  545. return;
  546. }
  547. if (strcmp(interface, zwp_pointer_gestures_v1_interface.name) == 0) {
  548. registry->wp_pointer_gestures = (struct zwp_pointer_gestures_v1 *)wl_registry_bind(wl_registry, name, &zwp_pointer_gestures_v1_interface, 1);
  549. registry->wp_pointer_gestures_name = name;
  550. return;
  551. }
  552. if (strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0) {
  553. registry->wp_idle_inhibit_manager = (struct zwp_idle_inhibit_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_idle_inhibit_manager_v1_interface, 1);
  554. registry->wp_idle_inhibit_manager_name = name;
  555. return;
  556. }
  557. if (strcmp(interface, zwp_tablet_manager_v2_interface.name) == 0) {
  558. registry->wp_tablet_manager = (struct zwp_tablet_manager_v2 *)wl_registry_bind(wl_registry, name, &zwp_tablet_manager_v2_interface, 1);
  559. registry->wp_tablet_manager_name = name;
  560. // This global creates some seat data. Let's do that for the ones already available.
  561. for (struct wl_seat *wl_seat : registry->wl_seats) {
  562. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  563. ERR_FAIL_NULL(ss);
  564. ss->wp_tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(registry->wp_tablet_manager, wl_seat);
  565. zwp_tablet_seat_v2_add_listener(ss->wp_tablet_seat, &wp_tablet_seat_listener, ss);
  566. }
  567. return;
  568. }
  569. if (strcmp(interface, zwp_text_input_manager_v3_interface.name) == 0) {
  570. registry->wp_text_input_manager = (struct zwp_text_input_manager_v3 *)wl_registry_bind(wl_registry, name, &zwp_text_input_manager_v3_interface, 1);
  571. registry->wp_text_input_manager_name = name;
  572. // This global creates some seat data. Let's do that for the ones already available.
  573. for (struct wl_seat *wl_seat : registry->wl_seats) {
  574. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  575. ERR_FAIL_NULL(ss);
  576. ss->wp_text_input = zwp_text_input_manager_v3_get_text_input(registry->wp_text_input_manager, wl_seat);
  577. zwp_text_input_v3_add_listener(ss->wp_text_input, &wp_text_input_listener, ss);
  578. }
  579. return;
  580. }
  581. if (strcmp(interface, FIFO_INTERFACE_NAME) == 0) {
  582. registry->wp_fifo_manager_name = name;
  583. }
  584. if (strcmp(interface, godot_embedding_compositor_interface.name) == 0) {
  585. registry->godot_embedding_compositor = (struct godot_embedding_compositor *)wl_registry_bind(wl_registry, name, &godot_embedding_compositor_interface, 1);
  586. registry->godot_embedding_compositor_name = name;
  587. godot_embedding_compositor_add_listener(registry->godot_embedding_compositor, &godot_embedding_compositor_listener, memnew(EmbeddingCompositorState));
  588. }
  589. }
  590. void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry *wl_registry, uint32_t name) {
  591. RegistryState *registry = (RegistryState *)data;
  592. ERR_FAIL_NULL(registry);
  593. if (name == registry->wl_shm_name) {
  594. if (registry->wl_shm) {
  595. wl_shm_destroy(registry->wl_shm);
  596. registry->wl_shm = nullptr;
  597. }
  598. registry->wl_shm_name = 0;
  599. return;
  600. }
  601. // NOTE: Deprecated.
  602. if (name == registry->xdg_exporter_v1_name) {
  603. if (registry->xdg_exporter_v1) {
  604. zxdg_exporter_v1_destroy(registry->xdg_exporter_v1);
  605. registry->xdg_exporter_v1 = nullptr;
  606. }
  607. registry->xdg_exporter_v1_name = 0;
  608. return;
  609. }
  610. if (name == registry->xdg_exporter_v2_name) {
  611. if (registry->xdg_exporter_v2) {
  612. zxdg_exporter_v2_destroy(registry->xdg_exporter_v2);
  613. registry->xdg_exporter_v2 = nullptr;
  614. }
  615. registry->xdg_exporter_v2_name = 0;
  616. return;
  617. }
  618. if (name == registry->wl_compositor_name) {
  619. if (registry->wl_compositor) {
  620. wl_compositor_destroy(registry->wl_compositor);
  621. registry->wl_compositor = nullptr;
  622. }
  623. registry->wl_compositor_name = 0;
  624. return;
  625. }
  626. if (name == registry->wl_data_device_manager_name) {
  627. if (registry->wl_data_device_manager) {
  628. wl_data_device_manager_destroy(registry->wl_data_device_manager);
  629. registry->wl_data_device_manager = nullptr;
  630. }
  631. registry->wl_data_device_manager_name = 0;
  632. // This global is used to create some seat data. Let's clean it.
  633. for (struct wl_seat *wl_seat : registry->wl_seats) {
  634. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  635. ERR_FAIL_NULL(ss);
  636. if (ss->wl_data_device) {
  637. wl_data_device_destroy(ss->wl_data_device);
  638. ss->wl_data_device = nullptr;
  639. }
  640. ss->wl_data_device = nullptr;
  641. }
  642. return;
  643. }
  644. if (name == registry->xdg_wm_base_name) {
  645. if (registry->xdg_wm_base) {
  646. xdg_wm_base_destroy(registry->xdg_wm_base);
  647. registry->xdg_wm_base = nullptr;
  648. }
  649. registry->xdg_wm_base_name = 0;
  650. return;
  651. }
  652. if (name == registry->wp_viewporter_name) {
  653. for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {
  654. WindowState &ws = pair.value;
  655. if (registry->wp_viewporter) {
  656. wp_viewporter_destroy(registry->wp_viewporter);
  657. registry->wp_viewporter = nullptr;
  658. }
  659. if (ws.wp_viewport) {
  660. wp_viewport_destroy(ws.wp_viewport);
  661. ws.wp_viewport = nullptr;
  662. }
  663. }
  664. registry->wp_viewporter_name = 0;
  665. return;
  666. }
  667. if (name == registry->wp_cursor_shape_manager_name) {
  668. if (registry->wp_cursor_shape_manager) {
  669. wp_cursor_shape_manager_v1_destroy(registry->wp_cursor_shape_manager);
  670. registry->wp_cursor_shape_manager = nullptr;
  671. }
  672. registry->wp_cursor_shape_manager_name = 0;
  673. for (struct wl_seat *wl_seat : registry->wl_seats) {
  674. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  675. ERR_FAIL_NULL(ss);
  676. if (ss->wp_cursor_shape_device) {
  677. wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);
  678. ss->wp_cursor_shape_device = nullptr;
  679. }
  680. }
  681. }
  682. if (name == registry->wp_fractional_scale_manager_name) {
  683. for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {
  684. WindowState &ws = pair.value;
  685. if (registry->wp_fractional_scale_manager) {
  686. wp_fractional_scale_manager_v1_destroy(registry->wp_fractional_scale_manager);
  687. registry->wp_fractional_scale_manager = nullptr;
  688. }
  689. if (ws.wp_fractional_scale) {
  690. wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);
  691. ws.wp_fractional_scale = nullptr;
  692. }
  693. }
  694. registry->wp_fractional_scale_manager_name = 0;
  695. }
  696. if (name == registry->xdg_decoration_manager_name) {
  697. if (registry->xdg_decoration_manager) {
  698. zxdg_decoration_manager_v1_destroy(registry->xdg_decoration_manager);
  699. registry->xdg_decoration_manager = nullptr;
  700. }
  701. registry->xdg_decoration_manager_name = 0;
  702. return;
  703. }
  704. if (name == registry->xdg_system_bell_name) {
  705. if (registry->xdg_system_bell) {
  706. xdg_system_bell_v1_destroy(registry->xdg_system_bell);
  707. registry->xdg_system_bell = nullptr;
  708. }
  709. registry->xdg_system_bell_name = 0;
  710. return;
  711. }
  712. if (name == registry->xdg_toplevel_icon_manager_name) {
  713. if (registry->xdg_toplevel_icon_manager) {
  714. xdg_toplevel_icon_manager_v1_destroy(registry->xdg_toplevel_icon_manager);
  715. registry->xdg_toplevel_icon_manager = nullptr;
  716. }
  717. if (registry->wayland_thread->xdg_icon) {
  718. xdg_toplevel_icon_v1_destroy(registry->wayland_thread->xdg_icon);
  719. }
  720. if (registry->wayland_thread->icon_buffer) {
  721. wl_buffer_destroy(registry->wayland_thread->icon_buffer);
  722. }
  723. registry->xdg_toplevel_icon_manager_name = 0;
  724. return;
  725. }
  726. if (name == registry->xdg_activation_name) {
  727. if (registry->xdg_activation) {
  728. xdg_activation_v1_destroy(registry->xdg_activation);
  729. registry->xdg_activation = nullptr;
  730. }
  731. registry->xdg_activation_name = 0;
  732. return;
  733. }
  734. if (name == registry->wp_primary_selection_device_manager_name) {
  735. if (registry->wp_primary_selection_device_manager) {
  736. zwp_primary_selection_device_manager_v1_destroy(registry->wp_primary_selection_device_manager);
  737. registry->wp_primary_selection_device_manager = nullptr;
  738. }
  739. registry->wp_primary_selection_device_manager_name = 0;
  740. // This global is used to create some seat data. Let's clean it.
  741. for (struct wl_seat *wl_seat : registry->wl_seats) {
  742. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  743. ERR_FAIL_NULL(ss);
  744. if (ss->wp_primary_selection_device) {
  745. zwp_primary_selection_device_v1_destroy(ss->wp_primary_selection_device);
  746. ss->wp_primary_selection_device = nullptr;
  747. }
  748. if (ss->wp_primary_selection_source) {
  749. zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);
  750. ss->wp_primary_selection_source = nullptr;
  751. }
  752. if (ss->wp_primary_selection_offer) {
  753. memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));
  754. zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);
  755. ss->wp_primary_selection_offer = nullptr;
  756. }
  757. }
  758. return;
  759. }
  760. if (name == registry->wp_relative_pointer_manager_name) {
  761. if (registry->wp_relative_pointer_manager) {
  762. zwp_relative_pointer_manager_v1_destroy(registry->wp_relative_pointer_manager);
  763. registry->wp_relative_pointer_manager = nullptr;
  764. }
  765. registry->wp_relative_pointer_manager_name = 0;
  766. // This global is used to create some seat data. Let's clean it.
  767. for (struct wl_seat *wl_seat : registry->wl_seats) {
  768. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  769. ERR_FAIL_NULL(ss);
  770. if (ss->wp_relative_pointer) {
  771. zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);
  772. ss->wp_relative_pointer = nullptr;
  773. }
  774. }
  775. return;
  776. }
  777. if (name == registry->wp_pointer_constraints_name) {
  778. if (registry->wp_pointer_constraints) {
  779. zwp_pointer_constraints_v1_destroy(registry->wp_pointer_constraints);
  780. registry->wp_pointer_constraints = nullptr;
  781. }
  782. registry->wp_pointer_constraints_name = 0;
  783. // This global is used to create some seat data. Let's clean it.
  784. for (struct wl_seat *wl_seat : registry->wl_seats) {
  785. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  786. ERR_FAIL_NULL(ss);
  787. if (ss->wp_relative_pointer) {
  788. zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);
  789. ss->wp_relative_pointer = nullptr;
  790. }
  791. if (ss->wp_locked_pointer) {
  792. zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);
  793. ss->wp_locked_pointer = nullptr;
  794. }
  795. if (ss->wp_confined_pointer) {
  796. zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);
  797. ss->wp_confined_pointer = nullptr;
  798. }
  799. }
  800. return;
  801. }
  802. if (name == registry->wp_pointer_gestures_name) {
  803. if (registry->wp_pointer_gestures) {
  804. zwp_pointer_gestures_v1_destroy(registry->wp_pointer_gestures);
  805. }
  806. registry->wp_pointer_gestures = nullptr;
  807. registry->wp_pointer_gestures_name = 0;
  808. // This global is used to create some seat data. Let's clean it.
  809. for (struct wl_seat *wl_seat : registry->wl_seats) {
  810. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  811. ERR_FAIL_NULL(ss);
  812. if (ss->wp_pointer_gesture_pinch) {
  813. zwp_pointer_gesture_pinch_v1_destroy(ss->wp_pointer_gesture_pinch);
  814. ss->wp_pointer_gesture_pinch = nullptr;
  815. }
  816. }
  817. return;
  818. }
  819. if (name == registry->wp_idle_inhibit_manager_name) {
  820. if (registry->wp_idle_inhibit_manager) {
  821. zwp_idle_inhibit_manager_v1_destroy(registry->wp_idle_inhibit_manager);
  822. registry->wp_idle_inhibit_manager = nullptr;
  823. }
  824. registry->wp_idle_inhibit_manager_name = 0;
  825. return;
  826. }
  827. if (name == registry->wp_tablet_manager_name) {
  828. if (registry->wp_tablet_manager) {
  829. zwp_tablet_manager_v2_destroy(registry->wp_tablet_manager);
  830. registry->wp_tablet_manager = nullptr;
  831. }
  832. registry->wp_tablet_manager_name = 0;
  833. // This global is used to create some seat data. Let's clean it.
  834. for (struct wl_seat *wl_seat : registry->wl_seats) {
  835. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  836. ERR_FAIL_NULL(ss);
  837. for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
  838. TabletToolState *state = wp_tablet_tool_get_state(tool);
  839. if (state) {
  840. memdelete(state);
  841. }
  842. zwp_tablet_tool_v2_destroy(tool);
  843. }
  844. ss->tablet_tools.clear();
  845. }
  846. return;
  847. }
  848. if (name == registry->wp_text_input_manager_name) {
  849. if (registry->wp_text_input_manager) {
  850. zwp_text_input_manager_v3_destroy(registry->wp_text_input_manager);
  851. registry->wp_text_input_manager = nullptr;
  852. }
  853. registry->wp_text_input_manager_name = 0;
  854. for (struct wl_seat *wl_seat : registry->wl_seats) {
  855. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  856. ERR_FAIL_NULL(ss);
  857. zwp_text_input_v3_destroy(ss->wp_text_input);
  858. ss->wp_text_input = nullptr;
  859. }
  860. return;
  861. }
  862. {
  863. // Iterate through all of the seats to find if any got removed.
  864. List<struct wl_seat *>::Element *E = registry->wl_seats.front();
  865. while (E) {
  866. struct wl_seat *wl_seat = E->get();
  867. List<struct wl_seat *>::Element *N = E->next();
  868. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  869. ERR_FAIL_NULL(ss);
  870. if (ss->wl_seat_name == name) {
  871. if (wl_seat) {
  872. wl_seat_destroy(wl_seat);
  873. }
  874. if (ss->wl_data_device) {
  875. wl_data_device_destroy(ss->wl_data_device);
  876. }
  877. if (ss->wp_tablet_seat) {
  878. zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);
  879. for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
  880. TabletToolState *state = wp_tablet_tool_get_state(tool);
  881. if (state) {
  882. memdelete(state);
  883. }
  884. zwp_tablet_tool_v2_destroy(tool);
  885. }
  886. }
  887. memdelete(ss);
  888. registry->wl_seats.erase(E);
  889. return;
  890. }
  891. E = N;
  892. }
  893. }
  894. {
  895. // Iterate through all of the outputs to find if any got removed.
  896. // FIXME: This is a very bruteforce approach.
  897. List<struct wl_output *>::Element *it = registry->wl_outputs.front();
  898. while (it) {
  899. // Iterate through all of the screens to find if any got removed.
  900. struct wl_output *wl_output = it->get();
  901. ERR_FAIL_NULL(wl_output);
  902. ScreenState *ss = wl_output_get_screen_state(wl_output);
  903. if (ss->wl_output_name == name) {
  904. registry->wl_outputs.erase(it);
  905. memdelete(ss);
  906. wl_output_destroy(wl_output);
  907. return;
  908. }
  909. it = it->next();
  910. }
  911. }
  912. if (name == registry->wp_fifo_manager_name) {
  913. registry->wp_fifo_manager_name = 0;
  914. }
  915. if (name == registry->godot_embedding_compositor_name) {
  916. registry->godot_embedding_compositor_name = 0;
  917. EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry->godot_embedding_compositor);
  918. ERR_FAIL_NULL(es);
  919. es->mapped_clients.clear();
  920. for (struct godot_embedded_client *client : es->clients) {
  921. godot_embedded_client_destroy(client);
  922. }
  923. es->clients.clear();
  924. memdelete(es);
  925. godot_embedding_compositor_destroy(registry->godot_embedding_compositor);
  926. registry->godot_embedding_compositor = nullptr;
  927. }
  928. }
  929. void WaylandThread::_wl_surface_on_enter(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {
  930. if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {
  931. // This won't have the right data bound to it. Not worth it and would probably
  932. // just break everything.
  933. return;
  934. }
  935. WindowState *ws = (WindowState *)data;
  936. ERR_FAIL_NULL(ws);
  937. DEBUG_LOG_WAYLAND_THREAD(vformat("Window entered output %x.\n", (size_t)wl_output));
  938. ws->wl_outputs.insert(wl_output);
  939. // Workaround for buffer scaling as there's no guaranteed way of knowing the
  940. // preferred scale.
  941. // TODO: Skip this branch for newer `wl_surface`s once we add support for
  942. // `wl_surface::preferred_buffer_scale`
  943. if (ws->preferred_fractional_scale == 0) {
  944. window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);
  945. }
  946. }
  947. void WaylandThread::_frame_wl_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t callback_data) {
  948. wl_callback_destroy(wl_callback);
  949. WindowState *ws = (WindowState *)data;
  950. ERR_FAIL_NULL(ws);
  951. ERR_FAIL_NULL(ws->wayland_thread);
  952. ERR_FAIL_NULL(ws->wl_surface);
  953. ws->last_frame_time = OS::get_singleton()->get_ticks_usec();
  954. ws->wayland_thread->set_frame();
  955. ws->frame_callback = wl_surface_frame(ws->wl_surface);
  956. wl_callback_add_listener(ws->frame_callback, &frame_wl_callback_listener, ws);
  957. if (ws->wl_surface && ws->buffer_scale_changed) {
  958. // NOTE: We're only now setting the buffer scale as the idea is to get this
  959. // data committed together with the new frame, all by the rendering driver.
  960. // This is important because we might otherwise set an invalid combination of
  961. // buffer size and scale (e.g. odd size and 2x scale). We're pretty much
  962. // guaranteed to get a proper buffer in the next render loop as the rescaling
  963. // method also informs the engine of a "window rect change", triggering
  964. // rendering if needed.
  965. wl_surface_set_buffer_scale(ws->wl_surface, window_state_get_preferred_buffer_scale(ws));
  966. }
  967. }
  968. void WaylandThread::_wl_surface_on_leave(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {
  969. if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {
  970. // This won't have the right data bound to it. Not worth it and would probably
  971. // just break everything.
  972. return;
  973. }
  974. WindowState *ws = (WindowState *)data;
  975. ERR_FAIL_NULL(ws);
  976. ws->wl_outputs.erase(wl_output);
  977. DEBUG_LOG_WAYLAND_THREAD(vformat("Window left output %x.\n", (size_t)wl_output));
  978. }
  979. // TODO: Add support to this event.
  980. void WaylandThread::_wl_surface_on_preferred_buffer_scale(void *data, struct wl_surface *wl_surface, int32_t factor) {
  981. }
  982. // TODO: Add support to this event.
  983. void WaylandThread::_wl_surface_on_preferred_buffer_transform(void *data, struct wl_surface *wl_surface, uint32_t transform) {
  984. }
  985. void WaylandThread::_wl_output_on_geometry(void *data, struct wl_output *wl_output, int32_t x, int32_t y, int32_t physical_width, int32_t physical_height, int32_t subpixel, const char *make, const char *model, int32_t transform) {
  986. ScreenState *ss = (ScreenState *)data;
  987. ERR_FAIL_NULL(ss);
  988. ss->pending_data.position.x = x;
  989. ss->pending_data.position.x = x;
  990. ss->pending_data.position.y = y;
  991. ss->pending_data.physical_size.width = physical_width;
  992. ss->pending_data.physical_size.height = physical_height;
  993. ss->pending_data.make.clear();
  994. ss->pending_data.make.append_utf8(make);
  995. ss->pending_data.model.clear();
  996. ss->pending_data.model.append_utf8(model);
  997. // `wl_output::done` is a version 2 addition. We'll directly update the data
  998. // for compatibility.
  999. if (wl_output_get_version(wl_output) == 1) {
  1000. ss->data = ss->pending_data;
  1001. }
  1002. }
  1003. void WaylandThread::_wl_output_on_mode(void *data, struct wl_output *wl_output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) {
  1004. ScreenState *ss = (ScreenState *)data;
  1005. ERR_FAIL_NULL(ss);
  1006. ss->pending_data.size.width = width;
  1007. ss->pending_data.size.height = height;
  1008. ss->pending_data.refresh_rate = refresh ? refresh / 1000.0f : -1;
  1009. // `wl_output::done` is a version 2 addition. We'll directly update the data
  1010. // for compatibility.
  1011. if (wl_output_get_version(wl_output) == 1) {
  1012. ss->data = ss->pending_data;
  1013. }
  1014. }
  1015. // NOTE: The following `wl_output` events are only for version 2 onwards, so we
  1016. // can assume that they're "atomic" (i.e. rely on the `wl_output::done` event).
  1017. void WaylandThread::_wl_output_on_done(void *data, struct wl_output *wl_output) {
  1018. ScreenState *ss = (ScreenState *)data;
  1019. ERR_FAIL_NULL(ss);
  1020. ss->data = ss->pending_data;
  1021. ss->wayland_thread->_update_scale(ss->data.scale);
  1022. DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x done.", (size_t)wl_output));
  1023. }
  1024. void WaylandThread::_wl_output_on_scale(void *data, struct wl_output *wl_output, int32_t factor) {
  1025. ScreenState *ss = (ScreenState *)data;
  1026. ERR_FAIL_NULL(ss);
  1027. ss->pending_data.scale = factor;
  1028. DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x scale %d", (size_t)wl_output, factor));
  1029. }
  1030. void WaylandThread::_wl_output_on_name(void *data, struct wl_output *wl_output, const char *name) {
  1031. }
  1032. void WaylandThread::_wl_output_on_description(void *data, struct wl_output *wl_output, const char *description) {
  1033. }
  1034. void WaylandThread::_xdg_wm_base_on_ping(void *data, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {
  1035. xdg_wm_base_pong(xdg_wm_base, serial);
  1036. }
  1037. void WaylandThread::_xdg_surface_on_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {
  1038. xdg_surface_ack_configure(xdg_surface, serial);
  1039. WindowState *ws = (WindowState *)data;
  1040. ERR_FAIL_NULL(ws);
  1041. DEBUG_LOG_WAYLAND_THREAD(vformat("xdg surface on configure rect %s", ws->rect));
  1042. }
  1043. void WaylandThread::_xdg_toplevel_on_configure(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height, struct wl_array *states) {
  1044. WindowState *ws = (WindowState *)data;
  1045. ERR_FAIL_NULL(ws);
  1046. // Expect the window to be in a plain state. It will get properly set if the
  1047. // compositor reports otherwise below.
  1048. ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;
  1049. ws->suspended = false;
  1050. uint32_t *state = nullptr;
  1051. wl_array_for_each(state, states) {
  1052. switch (*state) {
  1053. case XDG_TOPLEVEL_STATE_MAXIMIZED: {
  1054. ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1055. } break;
  1056. case XDG_TOPLEVEL_STATE_FULLSCREEN: {
  1057. ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  1058. } break;
  1059. case XDG_TOPLEVEL_STATE_SUSPENDED: {
  1060. ws->suspended = true;
  1061. } break;
  1062. default: {
  1063. // We don't care about the other states (for now).
  1064. } break;
  1065. }
  1066. }
  1067. if (width != 0 && height != 0) {
  1068. window_state_update_size(ws, width, height);
  1069. }
  1070. DEBUG_LOG_WAYLAND_THREAD(vformat("XDG toplevel on configure width %d height %d.", width, height));
  1071. }
  1072. void WaylandThread::_xdg_toplevel_on_close(void *data, struct xdg_toplevel *xdg_toplevel) {
  1073. WindowState *ws = (WindowState *)data;
  1074. ERR_FAIL_NULL(ws);
  1075. Ref<WindowEventMessage> msg;
  1076. msg.instantiate();
  1077. msg->id = ws->id;
  1078. msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;
  1079. ws->wayland_thread->push_message(msg);
  1080. }
  1081. void WaylandThread::_xdg_toplevel_on_configure_bounds(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height) {
  1082. }
  1083. void WaylandThread::_xdg_toplevel_on_wm_capabilities(void *data, struct xdg_toplevel *xdg_toplevel, struct wl_array *capabilities) {
  1084. WindowState *ws = (WindowState *)data;
  1085. ERR_FAIL_NULL(ws);
  1086. ws->can_maximize = false;
  1087. ws->can_fullscreen = false;
  1088. ws->can_minimize = false;
  1089. uint32_t *capability = nullptr;
  1090. wl_array_for_each(capability, capabilities) {
  1091. switch (*capability) {
  1092. case XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE: {
  1093. ws->can_maximize = true;
  1094. } break;
  1095. case XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN: {
  1096. ws->can_fullscreen = true;
  1097. } break;
  1098. case XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE: {
  1099. ws->can_minimize = true;
  1100. } break;
  1101. default: {
  1102. } break;
  1103. }
  1104. }
  1105. }
  1106. void WaylandThread::_xdg_popup_on_configure(void *data, struct xdg_popup *xdg_popup, int32_t x, int32_t y, int32_t width, int32_t height) {
  1107. WindowState *ws = (WindowState *)data;
  1108. ERR_FAIL_NULL(ws);
  1109. if (width != 0 && height != 0) {
  1110. window_state_update_size(ws, width, height);
  1111. }
  1112. WindowState *parent = ws->wayland_thread->window_get_state(ws->parent_id);
  1113. ERR_FAIL_NULL(parent);
  1114. Point2i pos = Point2i(x, y);
  1115. #ifdef LIBDECOR_ENABLED
  1116. if (parent->libdecor_frame) {
  1117. int translated_x = x;
  1118. int translated_y = y;
  1119. libdecor_frame_translate_coordinate(parent->libdecor_frame, x, y, &translated_x, &translated_y);
  1120. pos.x = translated_x;
  1121. pos.y = translated_y;
  1122. }
  1123. #endif
  1124. // Looks like the position returned here is relative to the parent. We have to
  1125. // accumulate it or there's gonna be a lot of confusion godot-side.
  1126. pos += parent->rect.position;
  1127. if (ws->rect.position != pos) {
  1128. DEBUG_LOG_WAYLAND_THREAD(vformat("Repositioning popup %d from %s to %s", ws->id, ws->rect.position, pos));
  1129. double parent_scale = window_state_get_scale_factor(parent);
  1130. ws->rect.position = pos;
  1131. Ref<WindowRectMessage> rect_msg;
  1132. rect_msg.instantiate();
  1133. rect_msg->id = ws->id;
  1134. rect_msg->rect.position = scale_vector2i(ws->rect.position, parent_scale);
  1135. rect_msg->rect.size = scale_vector2i(ws->rect.size, parent_scale);
  1136. ws->wayland_thread->push_message(rect_msg);
  1137. }
  1138. DEBUG_LOG_WAYLAND_THREAD(vformat("xdg popup on configure x%d y%d w%d h%d", x, y, width, height));
  1139. }
  1140. void WaylandThread::_xdg_popup_on_popup_done(void *data, struct xdg_popup *xdg_popup) {
  1141. WindowState *ws = (WindowState *)data;
  1142. ERR_FAIL_NULL(ws);
  1143. Ref<WindowEventMessage> ev_msg;
  1144. ev_msg.instantiate();
  1145. ev_msg->id = ws->id;
  1146. ev_msg->event = DisplayServer::WINDOW_EVENT_FORCE_CLOSE;
  1147. ws->wayland_thread->push_message(ev_msg);
  1148. }
  1149. void WaylandThread::_xdg_popup_on_repositioned(void *data, struct xdg_popup *xdg_popup, uint32_t token) {
  1150. DEBUG_LOG_WAYLAND_THREAD(vformat("stub xdg popup repositioned %x", token));
  1151. }
  1152. // NOTE: Deprecated.
  1153. void WaylandThread::_xdg_exported_v1_on_handle(void *data, zxdg_exported_v1 *exported, const char *handle) {
  1154. WindowState *ws = (WindowState *)data;
  1155. ERR_FAIL_NULL(ws);
  1156. ws->exported_handle = vformat("wayland:%s", String::utf8(handle));
  1157. }
  1158. void WaylandThread::_xdg_exported_v2_on_handle(void *data, zxdg_exported_v2 *exported, const char *handle) {
  1159. WindowState *ws = (WindowState *)data;
  1160. ERR_FAIL_NULL(ws);
  1161. ws->exported_handle = vformat("wayland:%s", String::utf8(handle));
  1162. }
  1163. void WaylandThread::_xdg_toplevel_decoration_on_configure(void *data, struct zxdg_toplevel_decoration_v1 *xdg_toplevel_decoration, uint32_t mode) {
  1164. if (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE) {
  1165. #ifdef LIBDECOR_ENABLED
  1166. WARN_PRINT_ONCE("Native client side decorations are not yet supported without libdecor!");
  1167. #else
  1168. WARN_PRINT_ONCE("Native client side decorations are not yet supported!");
  1169. #endif // LIBDECOR_ENABLED
  1170. }
  1171. }
  1172. #ifdef LIBDECOR_ENABLED
  1173. void WaylandThread::libdecor_on_error(struct libdecor *context, enum libdecor_error error, const char *message) {
  1174. ERR_PRINT(vformat("libdecor error %d: %s", error, message));
  1175. }
  1176. // NOTE: This is pretty much a reimplementation of _xdg_surface_on_configure
  1177. // and _xdg_toplevel_on_configure. Libdecor really likes wrapping everything,
  1178. // forcing us to do stuff like this.
  1179. void WaylandThread::libdecor_frame_on_configure(struct libdecor_frame *frame, struct libdecor_configuration *configuration, void *user_data) {
  1180. WindowState *ws = (WindowState *)user_data;
  1181. ERR_FAIL_NULL(ws);
  1182. int width = 0;
  1183. int height = 0;
  1184. ws->pending_libdecor_configuration = configuration;
  1185. if (!libdecor_configuration_get_content_size(configuration, frame, &width, &height)) {
  1186. // The configuration doesn't have a size. We'll use the one already set in the window.
  1187. width = ws->rect.size.width;
  1188. height = ws->rect.size.height;
  1189. }
  1190. ERR_FAIL_COND_MSG(width == 0 || height == 0, "Window has invalid size.");
  1191. libdecor_window_state window_state = LIBDECOR_WINDOW_STATE_NONE;
  1192. // Expect the window to be in a plain state. It will get properly set if the
  1193. // compositor reports otherwise below.
  1194. ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;
  1195. ws->suspended = false;
  1196. if (libdecor_configuration_get_window_state(configuration, &window_state)) {
  1197. if (window_state & LIBDECOR_WINDOW_STATE_MAXIMIZED) {
  1198. ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1199. }
  1200. if (window_state & LIBDECOR_WINDOW_STATE_FULLSCREEN) {
  1201. ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  1202. }
  1203. if (window_state & LIBDECOR_WINDOW_STATE_SUSPENDED) {
  1204. ws->suspended = true;
  1205. }
  1206. }
  1207. window_state_update_size(ws, width, height);
  1208. DEBUG_LOG_WAYLAND_THREAD(vformat("libdecor frame on configure rect %s", ws->rect));
  1209. }
  1210. void WaylandThread::libdecor_frame_on_close(struct libdecor_frame *frame, void *user_data) {
  1211. WindowState *ws = (WindowState *)user_data;
  1212. ERR_FAIL_NULL(ws);
  1213. Ref<WindowEventMessage> winevent_msg;
  1214. winevent_msg.instantiate();
  1215. winevent_msg->id = ws->id;
  1216. winevent_msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;
  1217. ws->wayland_thread->push_message(winevent_msg);
  1218. DEBUG_LOG_WAYLAND_THREAD("libdecor frame on close");
  1219. }
  1220. void WaylandThread::libdecor_frame_on_commit(struct libdecor_frame *frame, void *user_data) {
  1221. // We're skipping this as we don't really care about libdecor's commit for
  1222. // atomicity reasons. See `_frame_wl_callback_on_done` for more info.
  1223. DEBUG_LOG_WAYLAND_THREAD("libdecor frame on commit");
  1224. }
  1225. void WaylandThread::libdecor_frame_on_dismiss_popup(struct libdecor_frame *frame, const char *seat_name, void *user_data) {
  1226. }
  1227. #endif // LIBDECOR_ENABLED
  1228. void WaylandThread::_wl_seat_on_capabilities(void *data, struct wl_seat *wl_seat, uint32_t capabilities) {
  1229. SeatState *ss = (SeatState *)data;
  1230. ERR_FAIL_NULL(ss);
  1231. // TODO: Handle touch.
  1232. // Pointer handling.
  1233. if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
  1234. if (!ss->wl_pointer) {
  1235. ss->cursor_surface = wl_compositor_create_surface(ss->registry->wl_compositor);
  1236. wl_surface_commit(ss->cursor_surface);
  1237. ss->wl_pointer = wl_seat_get_pointer(wl_seat);
  1238. wl_pointer_add_listener(ss->wl_pointer, &wl_pointer_listener, ss);
  1239. if (ss->registry->wp_cursor_shape_manager) {
  1240. ss->wp_cursor_shape_device = wp_cursor_shape_manager_v1_get_pointer(ss->registry->wp_cursor_shape_manager, ss->wl_pointer);
  1241. }
  1242. if (ss->registry->wp_relative_pointer_manager) {
  1243. ss->wp_relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(ss->registry->wp_relative_pointer_manager, ss->wl_pointer);
  1244. zwp_relative_pointer_v1_add_listener(ss->wp_relative_pointer, &wp_relative_pointer_listener, ss);
  1245. }
  1246. if (ss->registry->wp_pointer_gestures) {
  1247. ss->wp_pointer_gesture_pinch = zwp_pointer_gestures_v1_get_pinch_gesture(ss->registry->wp_pointer_gestures, ss->wl_pointer);
  1248. zwp_pointer_gesture_pinch_v1_add_listener(ss->wp_pointer_gesture_pinch, &wp_pointer_gesture_pinch_listener, ss);
  1249. }
  1250. // TODO: Constrain new pointers if the global mouse mode is constrained.
  1251. }
  1252. } else {
  1253. if (ss->cursor_frame_callback) {
  1254. // Just in case. I got bitten by weird race-like conditions already.
  1255. wl_callback_set_user_data(ss->cursor_frame_callback, nullptr);
  1256. wl_callback_destroy(ss->cursor_frame_callback);
  1257. ss->cursor_frame_callback = nullptr;
  1258. }
  1259. if (ss->cursor_surface) {
  1260. wl_surface_destroy(ss->cursor_surface);
  1261. ss->cursor_surface = nullptr;
  1262. }
  1263. if (ss->wl_pointer) {
  1264. wl_pointer_destroy(ss->wl_pointer);
  1265. ss->wl_pointer = nullptr;
  1266. }
  1267. if (ss->wp_cursor_shape_device) {
  1268. wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);
  1269. ss->wp_cursor_shape_device = nullptr;
  1270. }
  1271. if (ss->wp_relative_pointer) {
  1272. zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);
  1273. ss->wp_relative_pointer = nullptr;
  1274. }
  1275. if (ss->wp_confined_pointer) {
  1276. zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);
  1277. ss->wp_confined_pointer = nullptr;
  1278. }
  1279. if (ss->wp_locked_pointer) {
  1280. zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);
  1281. ss->wp_locked_pointer = nullptr;
  1282. }
  1283. }
  1284. // Keyboard handling.
  1285. if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
  1286. if (!ss->wl_keyboard) {
  1287. ss->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
  1288. ERR_FAIL_NULL(ss->xkb_context);
  1289. ss->wl_keyboard = wl_seat_get_keyboard(wl_seat);
  1290. wl_keyboard_add_listener(ss->wl_keyboard, &wl_keyboard_listener, ss);
  1291. }
  1292. } else {
  1293. if (ss->xkb_context) {
  1294. xkb_context_unref(ss->xkb_context);
  1295. ss->xkb_context = nullptr;
  1296. }
  1297. if (ss->xkb_compose_table) {
  1298. xkb_compose_table_unref(ss->xkb_compose_table);
  1299. ss->xkb_compose_table = nullptr;
  1300. }
  1301. if (ss->xkb_compose_state) {
  1302. xkb_compose_state_unref(ss->xkb_compose_state);
  1303. ss->xkb_compose_state = nullptr;
  1304. }
  1305. if (ss->xkb_keymap) {
  1306. xkb_keymap_unref(ss->xkb_keymap);
  1307. ss->xkb_keymap = nullptr;
  1308. }
  1309. if (ss->xkb_state) {
  1310. xkb_state_unref(ss->xkb_state);
  1311. ss->xkb_state = nullptr;
  1312. }
  1313. if (ss->wl_keyboard) {
  1314. wl_keyboard_destroy(ss->wl_keyboard);
  1315. ss->wl_keyboard = nullptr;
  1316. }
  1317. }
  1318. }
  1319. void WaylandThread::_wl_seat_on_name(void *data, struct wl_seat *wl_seat, const char *name) {
  1320. }
  1321. void WaylandThread::_cursor_frame_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t time_ms) {
  1322. wl_callback_destroy(wl_callback);
  1323. SeatState *ss = (SeatState *)data;
  1324. ERR_FAIL_NULL(ss);
  1325. ss->cursor_frame_callback = nullptr;
  1326. ss->cursor_time_ms = time_ms;
  1327. seat_state_update_cursor(ss);
  1328. }
  1329. void WaylandThread::_wl_pointer_on_enter(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
  1330. WindowState *ws = wl_surface_get_window_state(surface);
  1331. if (!ws) {
  1332. return;
  1333. }
  1334. SeatState *ss = (SeatState *)data;
  1335. ERR_FAIL_NULL(ss);
  1336. ERR_FAIL_NULL(ss->cursor_surface);
  1337. PointerData &pd = ss->pointer_data_buffer;
  1338. ss->pointer_enter_serial = serial;
  1339. pd.pointed_id = ws->id;
  1340. pd.last_pointed_id = ws->id;
  1341. pd.position.x = wl_fixed_to_double(surface_x);
  1342. pd.position.y = wl_fixed_to_double(surface_y);
  1343. seat_state_update_cursor(ss);
  1344. DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer entered window %d.", ws->id));
  1345. if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {
  1346. _wl_pointer_on_frame(data, wl_pointer);
  1347. }
  1348. }
  1349. void WaylandThread::_wl_pointer_on_leave(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface) {
  1350. // NOTE: `surface` will probably be null when the surface is destroyed.
  1351. // See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/366
  1352. // See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/465
  1353. SeatState *ss = (SeatState *)data;
  1354. ERR_FAIL_NULL(ss);
  1355. PointerData &pd = ss->pointer_data_buffer;
  1356. if (pd.pointed_id == DisplayServer::INVALID_WINDOW_ID) {
  1357. // We're probably on a decoration or some other third-party thing.
  1358. return;
  1359. }
  1360. DisplayServer::WindowID id = pd.pointed_id;
  1361. pd.pointed_id = DisplayServer::INVALID_WINDOW_ID;
  1362. pd.pressed_button_mask.clear();
  1363. DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer left window %d.", id));
  1364. if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {
  1365. _wl_pointer_on_frame(data, wl_pointer);
  1366. }
  1367. }
  1368. void WaylandThread::_wl_pointer_on_motion(void *data, struct wl_pointer *wl_pointer, uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y) {
  1369. SeatState *ss = (SeatState *)data;
  1370. ERR_FAIL_NULL(ss);
  1371. PointerData &pd = ss->pointer_data_buffer;
  1372. pd.position.x = wl_fixed_to_double(surface_x);
  1373. pd.position.y = wl_fixed_to_double(surface_y);
  1374. pd.motion_time = time;
  1375. if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {
  1376. _wl_pointer_on_frame(data, wl_pointer);
  1377. }
  1378. }
  1379. void WaylandThread::_wl_pointer_on_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {
  1380. SeatState *ss = (SeatState *)data;
  1381. ERR_FAIL_NULL(ss);
  1382. PointerData &pd = ss->pointer_data_buffer;
  1383. MouseButton button_pressed = MouseButton::NONE;
  1384. switch (button) {
  1385. case BTN_LEFT:
  1386. button_pressed = MouseButton::LEFT;
  1387. break;
  1388. case BTN_MIDDLE:
  1389. button_pressed = MouseButton::MIDDLE;
  1390. break;
  1391. case BTN_RIGHT:
  1392. button_pressed = MouseButton::RIGHT;
  1393. break;
  1394. case BTN_EXTRA:
  1395. button_pressed = MouseButton::MB_XBUTTON1;
  1396. break;
  1397. case BTN_SIDE:
  1398. button_pressed = MouseButton::MB_XBUTTON2;
  1399. break;
  1400. default: {
  1401. }
  1402. }
  1403. MouseButtonMask mask = mouse_button_to_mask(button_pressed);
  1404. if (state & WL_POINTER_BUTTON_STATE_PRESSED) {
  1405. pd.pressed_button_mask.set_flag(mask);
  1406. pd.last_button_pressed = button_pressed;
  1407. pd.double_click_begun = true;
  1408. } else {
  1409. pd.pressed_button_mask.clear_flag(mask);
  1410. }
  1411. pd.button_time = time;
  1412. pd.button_serial = serial;
  1413. if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {
  1414. _wl_pointer_on_frame(data, wl_pointer);
  1415. }
  1416. }
  1417. void WaylandThread::_wl_pointer_on_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {
  1418. SeatState *ss = (SeatState *)data;
  1419. ERR_FAIL_NULL(ss);
  1420. PointerData &pd = ss->pointer_data_buffer;
  1421. switch (axis) {
  1422. case WL_POINTER_AXIS_VERTICAL_SCROLL: {
  1423. pd.scroll_vector.y = wl_fixed_to_double(value);
  1424. } break;
  1425. case WL_POINTER_AXIS_HORIZONTAL_SCROLL: {
  1426. pd.scroll_vector.x = wl_fixed_to_double(value);
  1427. } break;
  1428. }
  1429. pd.button_time = time;
  1430. if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {
  1431. _wl_pointer_on_frame(data, wl_pointer);
  1432. }
  1433. }
  1434. void WaylandThread::_wl_pointer_on_frame(void *data, struct wl_pointer *wl_pointer) {
  1435. SeatState *ss = (SeatState *)data;
  1436. ERR_FAIL_NULL(ss);
  1437. WaylandThread *wayland_thread = ss->wayland_thread;
  1438. ERR_FAIL_NULL(wayland_thread);
  1439. PointerData &old_pd = ss->pointer_data;
  1440. PointerData &pd = ss->pointer_data_buffer;
  1441. if (pd.pointed_id != old_pd.pointed_id) {
  1442. if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {
  1443. Ref<WindowEventMessage> msg;
  1444. msg.instantiate();
  1445. msg->id = old_pd.pointed_id;
  1446. msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;
  1447. wayland_thread->push_message(msg);
  1448. }
  1449. if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {
  1450. Ref<WindowEventMessage> msg;
  1451. msg.instantiate();
  1452. msg->id = pd.pointed_id;
  1453. msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  1454. wayland_thread->push_message(msg);
  1455. }
  1456. }
  1457. WindowState *ws = nullptr;
  1458. // NOTE: At least on sway, with wl_pointer version 5 or greater,
  1459. // wl_pointer::leave might be emitted with other events (like
  1460. // wl_pointer::button) within the same wl_pointer::frame. Because of this, we
  1461. // need to account for when the currently pointed window might be invalid
  1462. // (third-party or even none) and fall back to the old one.
  1463. if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {
  1464. ws = ss->wayland_thread->window_get_state(pd.pointed_id);
  1465. ERR_FAIL_NULL(ws);
  1466. } else if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {
  1467. ws = ss->wayland_thread->window_get_state(old_pd.pointed_id);
  1468. ERR_FAIL_NULL(ws);
  1469. }
  1470. if (ws == nullptr) {
  1471. // We're probably on a decoration or some other third-party thing. Let's
  1472. // "commit" the data and call it a day.
  1473. old_pd = pd;
  1474. return;
  1475. }
  1476. double scale = window_state_get_scale_factor(ws);
  1477. wayland_thread->_set_current_seat(ss->wl_seat);
  1478. if (old_pd.motion_time != pd.motion_time || old_pd.relative_motion_time != pd.relative_motion_time) {
  1479. Ref<InputEventMouseMotion> mm;
  1480. mm.instantiate();
  1481. // Set all pressed modifiers.
  1482. mm->set_shift_pressed(ss->shift_pressed);
  1483. mm->set_ctrl_pressed(ss->ctrl_pressed);
  1484. mm->set_alt_pressed(ss->alt_pressed);
  1485. mm->set_meta_pressed(ss->meta_pressed);
  1486. mm->set_window_id(ws->id);
  1487. mm->set_button_mask(pd.pressed_button_mask);
  1488. mm->set_position(pd.position * scale);
  1489. mm->set_global_position(pd.position * scale);
  1490. Vector2 pos_delta = (pd.position - old_pd.position) * scale;
  1491. if (old_pd.relative_motion_time != pd.relative_motion_time) {
  1492. uint32_t time_delta = pd.relative_motion_time - old_pd.relative_motion_time;
  1493. mm->set_relative(pd.relative_motion * scale);
  1494. mm->set_velocity((Vector2)pos_delta / time_delta);
  1495. } else {
  1496. // The spec includes the possibility of having motion events without an
  1497. // associated relative motion event. If that's the case, fallback to a
  1498. // simple delta of the position. The captured mouse won't report the
  1499. // relative speed anymore though.
  1500. uint32_t time_delta = pd.motion_time - old_pd.motion_time;
  1501. mm->set_relative(pos_delta);
  1502. mm->set_velocity((Vector2)pos_delta / time_delta);
  1503. }
  1504. mm->set_relative_screen_position(mm->get_relative());
  1505. mm->set_screen_velocity(mm->get_velocity());
  1506. Ref<InputEventMessage> msg;
  1507. msg.instantiate();
  1508. msg->event = mm;
  1509. wayland_thread->push_message(msg);
  1510. }
  1511. if (pd.discrete_scroll_vector_120 - old_pd.discrete_scroll_vector_120 != Vector2i()) {
  1512. // This is a discrete scroll (eg. from a scroll wheel), so we'll just emit
  1513. // scroll wheel buttons.
  1514. if (pd.scroll_vector.y != 0) {
  1515. MouseButton button = pd.scroll_vector.y > 0 ? MouseButton::WHEEL_DOWN : MouseButton::WHEEL_UP;
  1516. pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));
  1517. }
  1518. if (pd.scroll_vector.x != 0) {
  1519. MouseButton button = pd.scroll_vector.x > 0 ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT;
  1520. pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));
  1521. }
  1522. } else {
  1523. if (pd.scroll_vector - old_pd.scroll_vector != Vector2()) {
  1524. // This is a continuous scroll, so we'll emit a pan gesture.
  1525. Ref<InputEventPanGesture> pg;
  1526. pg.instantiate();
  1527. // Set all pressed modifiers.
  1528. pg->set_shift_pressed(ss->shift_pressed);
  1529. pg->set_ctrl_pressed(ss->ctrl_pressed);
  1530. pg->set_alt_pressed(ss->alt_pressed);
  1531. pg->set_meta_pressed(ss->meta_pressed);
  1532. pg->set_position(pd.position * scale);
  1533. pg->set_window_id(ws->id);
  1534. pg->set_delta(pd.scroll_vector);
  1535. Ref<InputEventMessage> msg;
  1536. msg.instantiate();
  1537. msg->event = pg;
  1538. wayland_thread->push_message(msg);
  1539. }
  1540. }
  1541. if (old_pd.pressed_button_mask != pd.pressed_button_mask) {
  1542. BitField<MouseButtonMask> pressed_mask_delta = old_pd.pressed_button_mask.get_different(pd.pressed_button_mask);
  1543. const MouseButton buttons_to_test[] = {
  1544. MouseButton::LEFT,
  1545. MouseButton::MIDDLE,
  1546. MouseButton::RIGHT,
  1547. MouseButton::WHEEL_UP,
  1548. MouseButton::WHEEL_DOWN,
  1549. MouseButton::WHEEL_LEFT,
  1550. MouseButton::WHEEL_RIGHT,
  1551. MouseButton::MB_XBUTTON1,
  1552. MouseButton::MB_XBUTTON2,
  1553. };
  1554. for (MouseButton test_button : buttons_to_test) {
  1555. MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);
  1556. if (pressed_mask_delta.has_flag(test_button_mask)) {
  1557. Ref<InputEventMouseButton> mb;
  1558. mb.instantiate();
  1559. // Set all pressed modifiers.
  1560. mb->set_shift_pressed(ss->shift_pressed);
  1561. mb->set_ctrl_pressed(ss->ctrl_pressed);
  1562. mb->set_alt_pressed(ss->alt_pressed);
  1563. mb->set_meta_pressed(ss->meta_pressed);
  1564. mb->set_window_id(ws->id);
  1565. mb->set_position(pd.position * scale);
  1566. mb->set_global_position(pd.position * scale);
  1567. if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN) {
  1568. // If this is a discrete scroll, specify how many "clicks" it did for this
  1569. // pointer frame.
  1570. mb->set_factor(Math::abs(pd.discrete_scroll_vector_120.y / (float)120));
  1571. }
  1572. if (test_button == MouseButton::WHEEL_RIGHT || test_button == MouseButton::WHEEL_LEFT) {
  1573. // If this is a discrete scroll, specify how many "clicks" it did for this
  1574. // pointer frame.
  1575. mb->set_factor(std::abs(pd.discrete_scroll_vector_120.x / (float)120));
  1576. }
  1577. mb->set_button_mask(pd.pressed_button_mask);
  1578. mb->set_button_index(test_button);
  1579. mb->set_pressed(pd.pressed_button_mask.has_flag(test_button_mask));
  1580. // We have to set the last position pressed here as we can't take for
  1581. // granted what the individual events might have seen due to them not having
  1582. // a guaranteed order.
  1583. if (mb->is_pressed()) {
  1584. pd.last_pressed_position = pd.position;
  1585. }
  1586. if (old_pd.double_click_begun && mb->is_pressed() && pd.last_button_pressed == old_pd.last_button_pressed && (pd.button_time - old_pd.button_time) < 400 && Vector2(old_pd.last_pressed_position * scale).distance_to(Vector2(pd.last_pressed_position * scale)) < 5) {
  1587. pd.double_click_begun = false;
  1588. mb->set_double_click(true);
  1589. }
  1590. Ref<InputEventMessage> msg;
  1591. msg.instantiate();
  1592. msg->event = mb;
  1593. wayland_thread->push_message(msg);
  1594. // Send an event resetting immediately the wheel key.
  1595. // Wayland specification defines axis_stop events as optional and says to
  1596. // treat all axis events as unterminated. As such, we have to manually do
  1597. // it ourselves.
  1598. if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN || test_button == MouseButton::WHEEL_LEFT || test_button == MouseButton::WHEEL_RIGHT) {
  1599. // FIXME: This is ugly, I can't find a clean way to clone an InputEvent.
  1600. // This works for now, despite being horrible.
  1601. Ref<InputEventMouseButton> wh_up;
  1602. wh_up.instantiate();
  1603. wh_up->set_window_id(ws->id);
  1604. wh_up->set_position(pd.position * scale);
  1605. wh_up->set_global_position(pd.position * scale);
  1606. // We have to unset the button to avoid it getting stuck.
  1607. pd.pressed_button_mask.clear_flag(test_button_mask);
  1608. wh_up->set_button_mask(pd.pressed_button_mask);
  1609. wh_up->set_button_index(test_button);
  1610. wh_up->set_pressed(false);
  1611. Ref<InputEventMessage> msg_up;
  1612. msg_up.instantiate();
  1613. msg_up->event = wh_up;
  1614. wayland_thread->push_message(msg_up);
  1615. }
  1616. }
  1617. }
  1618. }
  1619. // Reset the scroll vectors as we already handled them.
  1620. pd.scroll_vector = Vector2();
  1621. pd.discrete_scroll_vector_120 = Vector2i();
  1622. // Update the data all getters read. Wayland's specification requires us to do
  1623. // this, since all pointer actions are sent in individual events.
  1624. old_pd = pd;
  1625. }
  1626. void WaylandThread::_wl_pointer_on_axis_source(void *data, struct wl_pointer *wl_pointer, uint32_t axis_source) {
  1627. SeatState *ss = (SeatState *)data;
  1628. ERR_FAIL_NULL(ss);
  1629. ss->pointer_data_buffer.scroll_type = axis_source;
  1630. }
  1631. void WaylandThread::_wl_pointer_on_axis_stop(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis) {
  1632. }
  1633. // NOTE: This event is deprecated since version 8 and superseded by
  1634. // `wl_pointer::axis_value120`. This thus converts the data to its
  1635. // fraction-of-120 format.
  1636. void WaylandThread::_wl_pointer_on_axis_discrete(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t discrete) {
  1637. SeatState *ss = (SeatState *)data;
  1638. ERR_FAIL_NULL(ss);
  1639. PointerData &pd = ss->pointer_data_buffer;
  1640. // NOTE: We can allow ourselves to not accumulate this data (and thus just
  1641. // assign it) as the spec guarantees only one event per axis type.
  1642. if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {
  1643. pd.discrete_scroll_vector_120.y = discrete * 120;
  1644. }
  1645. if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {
  1646. pd.discrete_scroll_vector_120.x = discrete * 120;
  1647. }
  1648. }
  1649. // Supersedes `wl_pointer::axis_discrete` Since version 8.
  1650. void WaylandThread::_wl_pointer_on_axis_value120(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t value120) {
  1651. SeatState *ss = (SeatState *)data;
  1652. ERR_FAIL_NULL(ss);
  1653. PointerData &pd = ss->pointer_data_buffer;
  1654. if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {
  1655. pd.discrete_scroll_vector_120.y += value120;
  1656. }
  1657. if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {
  1658. pd.discrete_scroll_vector_120.x += value120;
  1659. }
  1660. }
  1661. // TODO: Add support to this event.
  1662. void WaylandThread::_wl_pointer_on_axis_relative_direction(void *data, struct wl_pointer *wl_pointer, uint32_t axis, uint32_t direction) {
  1663. }
  1664. void WaylandThread::_wl_keyboard_on_keymap(void *data, struct wl_keyboard *wl_keyboard, uint32_t format, int32_t fd, uint32_t size) {
  1665. ERR_FAIL_COND_MSG(format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, "Unsupported keymap format announced from the Wayland compositor.");
  1666. SeatState *ss = (SeatState *)data;
  1667. ERR_FAIL_NULL(ss);
  1668. if (ss->keymap_buffer) {
  1669. // We have already a mapped buffer, so we unmap it. There's no need to reset
  1670. // its pointer or size, as we're gonna set them below.
  1671. munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);
  1672. ss->keymap_buffer = nullptr;
  1673. }
  1674. ss->keymap_buffer = (const char *)mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
  1675. ss->keymap_buffer_size = size;
  1676. xkb_keymap_unref(ss->xkb_keymap);
  1677. ss->xkb_keymap = xkb_keymap_new_from_string(ss->xkb_context, ss->keymap_buffer,
  1678. XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
  1679. xkb_state_unref(ss->xkb_state);
  1680. ss->xkb_state = xkb_state_new(ss->xkb_keymap);
  1681. xkb_compose_table_unref(ss->xkb_compose_table);
  1682. const char *locale = getenv("LC_ALL");
  1683. if (!locale || !*locale) {
  1684. locale = getenv("LC_CTYPE");
  1685. }
  1686. if (!locale || !*locale) {
  1687. locale = getenv("LANG");
  1688. }
  1689. if (!locale || !*locale) {
  1690. locale = "C";
  1691. }
  1692. ss->xkb_compose_table = xkb_compose_table_new_from_locale(ss->xkb_context, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);
  1693. xkb_compose_state_unref(ss->xkb_compose_state);
  1694. ss->xkb_compose_state = xkb_compose_state_new(ss->xkb_compose_table, XKB_COMPOSE_STATE_NO_FLAGS);
  1695. xkb_state_update_mask(ss->xkb_state, ss->mods_depressed, ss->mods_latched, ss->mods_locked, 0, 0, ss->current_layout_index);
  1696. }
  1697. void WaylandThread::_wl_keyboard_on_enter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {
  1698. WindowState *ws = wl_surface_get_window_state(surface);
  1699. if (!ws) {
  1700. return;
  1701. }
  1702. SeatState *ss = (SeatState *)data;
  1703. ERR_FAIL_NULL(ss);
  1704. WaylandThread *wayland_thread = ss->wayland_thread;
  1705. ERR_FAIL_NULL(wayland_thread);
  1706. ss->focused_id = ws->id;
  1707. wayland_thread->_set_current_seat(ss->wl_seat);
  1708. Ref<WindowEventMessage> msg;
  1709. msg.instantiate();
  1710. msg->id = ws->id;
  1711. msg->event = DisplayServer::WINDOW_EVENT_FOCUS_IN;
  1712. wayland_thread->push_message(msg);
  1713. DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard focused window %d.", ws->id));
  1714. }
  1715. void WaylandThread::_wl_keyboard_on_leave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface) {
  1716. // NOTE: `surface` will probably be null when the surface is destroyed.
  1717. // See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/366
  1718. // See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/465
  1719. if (surface && !wl_proxy_is_godot((struct wl_proxy *)surface)) {
  1720. return;
  1721. }
  1722. SeatState *ss = (SeatState *)data;
  1723. ERR_FAIL_NULL(ss);
  1724. WaylandThread *wayland_thread = ss->wayland_thread;
  1725. ERR_FAIL_NULL(wayland_thread);
  1726. ss->repeating_keycode = XKB_KEYCODE_INVALID;
  1727. if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {
  1728. // We're probably on a decoration or some other third-party thing.
  1729. return;
  1730. }
  1731. WindowState *ws = wayland_thread->window_get_state(ss->focused_id);
  1732. ERR_FAIL_NULL(ws);
  1733. ss->focused_id = DisplayServer::INVALID_WINDOW_ID;
  1734. Ref<WindowEventMessage> msg;
  1735. msg.instantiate();
  1736. msg->id = ws->id;
  1737. msg->event = DisplayServer::WINDOW_EVENT_FOCUS_OUT;
  1738. wayland_thread->push_message(msg);
  1739. ss->shift_pressed = false;
  1740. ss->ctrl_pressed = false;
  1741. ss->alt_pressed = false;
  1742. ss->meta_pressed = false;
  1743. if (ss->xkb_state != nullptr) {
  1744. xkb_state_update_mask(ss->xkb_state, 0, 0, 0, 0, 0, 0);
  1745. }
  1746. DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard unfocused window %d.", ws->id));
  1747. }
  1748. void WaylandThread::_wl_keyboard_on_key(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
  1749. SeatState *ss = (SeatState *)data;
  1750. ERR_FAIL_NULL(ss);
  1751. if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {
  1752. return;
  1753. }
  1754. // We have to add 8 to the scancode to get an XKB-compatible keycode.
  1755. xkb_keycode_t xkb_keycode = key + 8;
  1756. bool pressed = state & WL_KEYBOARD_KEY_STATE_PRESSED;
  1757. if (pressed) {
  1758. if (xkb_keymap_key_repeats(ss->xkb_keymap, xkb_keycode)) {
  1759. ss->last_repeat_start_msec = OS::get_singleton()->get_ticks_msec();
  1760. ss->repeating_keycode = xkb_keycode;
  1761. }
  1762. ss->last_key_pressed_serial = serial;
  1763. } else if (ss->repeating_keycode == xkb_keycode) {
  1764. ss->repeating_keycode = XKB_KEYCODE_INVALID;
  1765. }
  1766. _seat_state_handle_xkb_keycode(ss, xkb_keycode, pressed);
  1767. }
  1768. void WaylandThread::_wl_keyboard_on_modifiers(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {
  1769. SeatState *ss = (SeatState *)data;
  1770. ERR_FAIL_NULL(ss);
  1771. ss->mods_depressed = mods_depressed;
  1772. ss->mods_latched = mods_latched;
  1773. ss->mods_locked = mods_locked;
  1774. ss->current_layout_index = group;
  1775. if (ss->xkb_state == nullptr) {
  1776. return;
  1777. }
  1778. xkb_state_update_mask(ss->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);
  1779. ss->shift_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE);
  1780. ss->ctrl_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE);
  1781. ss->alt_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_ALT, XKB_STATE_MODS_EFFECTIVE);
  1782. ss->meta_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_LOGO, XKB_STATE_MODS_EFFECTIVE);
  1783. }
  1784. void WaylandThread::_wl_keyboard_on_repeat_info(void *data, struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay) {
  1785. SeatState *ss = (SeatState *)data;
  1786. ERR_FAIL_NULL(ss);
  1787. ss->repeat_key_delay_msec = rate ? 1000 / rate : 0;
  1788. ss->repeat_start_delay_msec = delay;
  1789. }
  1790. // NOTE: Don't forget to `memfree` the offer's state.
  1791. void WaylandThread::_wl_data_device_on_data_offer(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {
  1792. wl_proxy_tag_godot((struct wl_proxy *)id);
  1793. wl_data_offer_add_listener(id, &wl_data_offer_listener, memnew(OfferState));
  1794. }
  1795. void WaylandThread::_wl_data_device_on_enter(void *data, struct wl_data_device *wl_data_device, uint32_t serial, struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y, struct wl_data_offer *id) {
  1796. WindowState *ws = wl_surface_get_window_state(surface);
  1797. if (!ws) {
  1798. return;
  1799. }
  1800. SeatState *ss = (SeatState *)data;
  1801. ERR_FAIL_NULL(ss);
  1802. ss->dnd_id = ws->id;
  1803. ss->dnd_enter_serial = serial;
  1804. ss->wl_data_offer_dnd = id;
  1805. // Godot only supports DnD file copying for now.
  1806. wl_data_offer_accept(id, serial, "text/uri-list");
  1807. wl_data_offer_set_actions(id, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);
  1808. }
  1809. void WaylandThread::_wl_data_device_on_leave(void *data, struct wl_data_device *wl_data_device) {
  1810. SeatState *ss = (SeatState *)data;
  1811. ERR_FAIL_NULL(ss);
  1812. if (ss->wl_data_offer_dnd) {
  1813. memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));
  1814. wl_data_offer_destroy(ss->wl_data_offer_dnd);
  1815. ss->wl_data_offer_dnd = nullptr;
  1816. ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;
  1817. }
  1818. }
  1819. void WaylandThread::_wl_data_device_on_motion(void *data, struct wl_data_device *wl_data_device, uint32_t time, wl_fixed_t x, wl_fixed_t y) {
  1820. }
  1821. void WaylandThread::_wl_data_device_on_drop(void *data, struct wl_data_device *wl_data_device) {
  1822. SeatState *ss = (SeatState *)data;
  1823. ERR_FAIL_NULL(ss);
  1824. WaylandThread *wayland_thread = ss->wayland_thread;
  1825. ERR_FAIL_NULL(wayland_thread);
  1826. OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_dnd);
  1827. ERR_FAIL_NULL(os);
  1828. if (os) {
  1829. Ref<DropFilesEventMessage> msg;
  1830. msg.instantiate();
  1831. msg->id = ss->dnd_id;
  1832. Vector<uint8_t> list_data = _wl_data_offer_read(wayland_thread->wl_display, "text/uri-list", ss->wl_data_offer_dnd);
  1833. msg->files = String::utf8((const char *)list_data.ptr(), list_data.size()).split("\r\n", false);
  1834. for (int i = 0; i < msg->files.size(); i++) {
  1835. msg->files.write[i] = msg->files[i].replace("file://", "").uri_file_decode();
  1836. }
  1837. wayland_thread->push_message(msg);
  1838. wl_data_offer_finish(ss->wl_data_offer_dnd);
  1839. }
  1840. memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));
  1841. wl_data_offer_destroy(ss->wl_data_offer_dnd);
  1842. ss->wl_data_offer_dnd = nullptr;
  1843. ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;
  1844. }
  1845. void WaylandThread::_wl_data_device_on_selection(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {
  1846. SeatState *ss = (SeatState *)data;
  1847. ERR_FAIL_NULL(ss);
  1848. if (ss->wl_data_offer_selection) {
  1849. memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_selection));
  1850. wl_data_offer_destroy(ss->wl_data_offer_selection);
  1851. }
  1852. ss->wl_data_offer_selection = id;
  1853. }
  1854. void WaylandThread::_wl_data_offer_on_offer(void *data, struct wl_data_offer *wl_data_offer, const char *mime_type) {
  1855. OfferState *os = (OfferState *)data;
  1856. ERR_FAIL_NULL(os);
  1857. if (os) {
  1858. os->mime_types.insert(String::utf8(mime_type));
  1859. }
  1860. }
  1861. void WaylandThread::_wl_data_offer_on_source_actions(void *data, struct wl_data_offer *wl_data_offer, uint32_t source_actions) {
  1862. }
  1863. void WaylandThread::_wl_data_offer_on_action(void *data, struct wl_data_offer *wl_data_offer, uint32_t dnd_action) {
  1864. }
  1865. void WaylandThread::_wl_data_source_on_target(void *data, struct wl_data_source *wl_data_source, const char *mime_type) {
  1866. }
  1867. void WaylandThread::_wl_data_source_on_send(void *data, struct wl_data_source *wl_data_source, const char *mime_type, int32_t fd) {
  1868. SeatState *ss = (SeatState *)data;
  1869. ERR_FAIL_NULL(ss);
  1870. Vector<uint8_t> *data_to_send = nullptr;
  1871. if (wl_data_source == ss->wl_data_source_selection) {
  1872. data_to_send = &ss->selection_data;
  1873. DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested selection.");
  1874. }
  1875. if (data_to_send) {
  1876. ssize_t written_bytes = 0;
  1877. bool valid_mime = false;
  1878. if (strcmp(mime_type, "text/plain;charset=utf-8") == 0) {
  1879. valid_mime = true;
  1880. } else if (strcmp(mime_type, "text/plain") == 0) {
  1881. valid_mime = true;
  1882. }
  1883. if (valid_mime) {
  1884. written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());
  1885. }
  1886. if (written_bytes > 0) {
  1887. DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));
  1888. } else if (written_bytes == 0) {
  1889. DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");
  1890. } else {
  1891. ERR_PRINT(vformat("Clipboard: write error %d.", errno));
  1892. }
  1893. }
  1894. close(fd);
  1895. }
  1896. void WaylandThread::_wl_data_source_on_cancelled(void *data, struct wl_data_source *wl_data_source) {
  1897. SeatState *ss = (SeatState *)data;
  1898. ERR_FAIL_NULL(ss);
  1899. wl_data_source_destroy(wl_data_source);
  1900. if (wl_data_source == ss->wl_data_source_selection) {
  1901. ss->wl_data_source_selection = nullptr;
  1902. ss->selection_data.clear();
  1903. DEBUG_LOG_WAYLAND_THREAD("Clipboard: selection set by another program.");
  1904. return;
  1905. }
  1906. }
  1907. void WaylandThread::_wl_data_source_on_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source) {
  1908. }
  1909. void WaylandThread::_wl_data_source_on_dnd_finished(void *data, struct wl_data_source *wl_data_source) {
  1910. }
  1911. void WaylandThread::_wl_data_source_on_action(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action) {
  1912. }
  1913. void WaylandThread::_wp_fractional_scale_on_preferred_scale(void *data, struct wp_fractional_scale_v1 *wp_fractional_scale_v1, uint32_t scale) {
  1914. WindowState *ws = (WindowState *)data;
  1915. ERR_FAIL_NULL(ws);
  1916. ws->preferred_fractional_scale = (double)scale / 120;
  1917. window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);
  1918. }
  1919. void WaylandThread::_wp_relative_pointer_on_relative_motion(void *data, struct zwp_relative_pointer_v1 *wp_relative_pointer, uint32_t uptime_hi, uint32_t uptime_lo, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_unaccel, wl_fixed_t dy_unaccel) {
  1920. SeatState *ss = (SeatState *)data;
  1921. ERR_FAIL_NULL(ss);
  1922. PointerData &pd = ss->pointer_data_buffer;
  1923. pd.relative_motion.x = wl_fixed_to_double(dx);
  1924. pd.relative_motion.y = wl_fixed_to_double(dy);
  1925. pd.relative_motion_time = uptime_lo;
  1926. }
  1927. void WaylandThread::_wp_pointer_gesture_pinch_on_begin(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, struct wl_surface *surface, uint32_t fingers) {
  1928. SeatState *ss = (SeatState *)data;
  1929. ERR_FAIL_NULL(ss);
  1930. if (fingers == 2) {
  1931. ss->old_pinch_scale = wl_fixed_from_int(1);
  1932. ss->active_gesture = Gesture::MAGNIFY;
  1933. }
  1934. }
  1935. void WaylandThread::_wp_pointer_gesture_pinch_on_update(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) {
  1936. SeatState *ss = (SeatState *)data;
  1937. ERR_FAIL_NULL(ss);
  1938. // NOTE: From what I can tell, this and all other pointer gestures are separate
  1939. // from the "frame" mechanism of regular pointers. Thus, let's just assume we
  1940. // can read from the "committed" state.
  1941. const PointerData &pd = ss->pointer_data;
  1942. WaylandThread *wayland_thread = ss->wayland_thread;
  1943. ERR_FAIL_NULL(wayland_thread);
  1944. WindowState *ws = wayland_thread->window_get_state(pd.pointed_id);
  1945. ERR_FAIL_NULL(ws);
  1946. double win_scale = window_state_get_scale_factor(ws);
  1947. if (ss->active_gesture == Gesture::MAGNIFY) {
  1948. Ref<InputEventMagnifyGesture> mg;
  1949. mg.instantiate();
  1950. mg->set_window_id(pd.pointed_id);
  1951. if (ws) {
  1952. mg->set_window_id(ws->id);
  1953. }
  1954. // Set all pressed modifiers.
  1955. mg->set_shift_pressed(ss->shift_pressed);
  1956. mg->set_ctrl_pressed(ss->ctrl_pressed);
  1957. mg->set_alt_pressed(ss->alt_pressed);
  1958. mg->set_meta_pressed(ss->meta_pressed);
  1959. mg->set_position(pd.position * win_scale);
  1960. wl_fixed_t scale_delta = scale - ss->old_pinch_scale;
  1961. mg->set_factor(1 + wl_fixed_to_double(scale_delta));
  1962. Ref<InputEventMessage> magnify_msg;
  1963. magnify_msg.instantiate();
  1964. magnify_msg->event = mg;
  1965. // Since Wayland allows only one gesture at a time and godot instead expects
  1966. // both of them, we'll have to create two separate input events: one for
  1967. // magnification and one for panning.
  1968. Ref<InputEventPanGesture> pg;
  1969. pg.instantiate();
  1970. // Set all pressed modifiers.
  1971. pg->set_shift_pressed(ss->shift_pressed);
  1972. pg->set_ctrl_pressed(ss->ctrl_pressed);
  1973. pg->set_alt_pressed(ss->alt_pressed);
  1974. pg->set_meta_pressed(ss->meta_pressed);
  1975. pg->set_position(pd.position * win_scale);
  1976. pg->set_delta(Vector2(wl_fixed_to_double(dx), wl_fixed_to_double(dy)));
  1977. Ref<InputEventMessage> pan_msg;
  1978. pan_msg.instantiate();
  1979. pan_msg->event = pg;
  1980. wayland_thread->push_message(magnify_msg);
  1981. wayland_thread->push_message(pan_msg);
  1982. ss->old_pinch_scale = scale;
  1983. }
  1984. }
  1985. void WaylandThread::_wp_pointer_gesture_pinch_on_end(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, int32_t cancelled) {
  1986. SeatState *ss = (SeatState *)data;
  1987. ERR_FAIL_NULL(ss);
  1988. ss->active_gesture = Gesture::NONE;
  1989. }
  1990. // NOTE: Don't forget to `memfree` the offer's state.
  1991. void WaylandThread::_wp_primary_selection_device_on_data_offer(void *data, struct zwp_primary_selection_device_v1 *wp_primary_selection_device_v1, struct zwp_primary_selection_offer_v1 *offer) {
  1992. wl_proxy_tag_godot((struct wl_proxy *)offer);
  1993. zwp_primary_selection_offer_v1_add_listener(offer, &wp_primary_selection_offer_listener, memnew(OfferState));
  1994. }
  1995. void WaylandThread::_wp_primary_selection_device_on_selection(void *data, struct zwp_primary_selection_device_v1 *wp_primary_selection_device_v1, struct zwp_primary_selection_offer_v1 *id) {
  1996. SeatState *ss = (SeatState *)data;
  1997. ERR_FAIL_NULL(ss);
  1998. if (ss->wp_primary_selection_offer) {
  1999. memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));
  2000. zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);
  2001. }
  2002. ss->wp_primary_selection_offer = id;
  2003. }
  2004. void WaylandThread::_wp_primary_selection_offer_on_offer(void *data, struct zwp_primary_selection_offer_v1 *wp_primary_selection_offer_v1, const char *mime_type) {
  2005. OfferState *os = (OfferState *)data;
  2006. ERR_FAIL_NULL(os);
  2007. if (os) {
  2008. os->mime_types.insert(String::utf8(mime_type));
  2009. }
  2010. }
  2011. void WaylandThread::_wp_primary_selection_source_on_send(void *data, struct zwp_primary_selection_source_v1 *wp_primary_selection_source_v1, const char *mime_type, int32_t fd) {
  2012. SeatState *ss = (SeatState *)data;
  2013. ERR_FAIL_NULL(ss);
  2014. Vector<uint8_t> *data_to_send = nullptr;
  2015. if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {
  2016. data_to_send = &ss->primary_data;
  2017. DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested primary selection.");
  2018. }
  2019. if (data_to_send) {
  2020. ssize_t written_bytes = 0;
  2021. if (strcmp(mime_type, "text/plain") == 0) {
  2022. written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());
  2023. }
  2024. if (written_bytes > 0) {
  2025. DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));
  2026. } else if (written_bytes == 0) {
  2027. DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");
  2028. } else {
  2029. ERR_PRINT(vformat("Clipboard: write error %d.", errno));
  2030. }
  2031. }
  2032. close(fd);
  2033. }
  2034. void WaylandThread::_wp_primary_selection_source_on_cancelled(void *data, struct zwp_primary_selection_source_v1 *wp_primary_selection_source_v1) {
  2035. SeatState *ss = (SeatState *)data;
  2036. ERR_FAIL_NULL(ss);
  2037. if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {
  2038. zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);
  2039. ss->wp_primary_selection_source = nullptr;
  2040. ss->primary_data.clear();
  2041. DEBUG_LOG_WAYLAND_THREAD("Clipboard: primary selection set by another program.");
  2042. return;
  2043. }
  2044. }
  2045. void WaylandThread::_wp_tablet_seat_on_tablet_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_v2 *id) {
  2046. }
  2047. void WaylandThread::_wp_tablet_seat_on_tool_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_tool_v2 *id) {
  2048. SeatState *ss = (SeatState *)data;
  2049. ERR_FAIL_NULL(ss);
  2050. TabletToolState *state = memnew(TabletToolState);
  2051. state->wl_seat = ss->wl_seat;
  2052. wl_proxy_tag_godot((struct wl_proxy *)id);
  2053. zwp_tablet_tool_v2_add_listener(id, &wp_tablet_tool_listener, state);
  2054. ss->tablet_tools.push_back(id);
  2055. }
  2056. void WaylandThread::_wp_tablet_seat_on_pad_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_pad_v2 *id) {
  2057. }
  2058. void WaylandThread::_wp_tablet_tool_on_type(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t tool_type) {
  2059. TabletToolState *state = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2060. if (state && tool_type == ZWP_TABLET_TOOL_V2_TYPE_ERASER) {
  2061. state->is_eraser = true;
  2062. }
  2063. }
  2064. void WaylandThread::_wp_tablet_tool_on_hardware_serial(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t hardware_serial_hi, uint32_t hardware_serial_lo) {
  2065. }
  2066. void WaylandThread::_wp_tablet_tool_on_hardware_id_wacom(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t hardware_id_hi, uint32_t hardware_id_lo) {
  2067. }
  2068. void WaylandThread::_wp_tablet_tool_on_capability(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t capability) {
  2069. }
  2070. void WaylandThread::_wp_tablet_tool_on_done(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {
  2071. }
  2072. void WaylandThread::_wp_tablet_tool_on_removed(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {
  2073. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2074. if (!ts) {
  2075. return;
  2076. }
  2077. SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
  2078. if (!ss) {
  2079. return;
  2080. }
  2081. List<struct zwp_tablet_tool_v2 *>::Element *E = ss->tablet_tools.find(wp_tablet_tool_v2);
  2082. if (E && E->get()) {
  2083. struct zwp_tablet_tool_v2 *tool = E->get();
  2084. TabletToolState *state = wp_tablet_tool_get_state(tool);
  2085. if (state) {
  2086. memdelete(state);
  2087. }
  2088. zwp_tablet_tool_v2_destroy(tool);
  2089. ss->tablet_tools.erase(E);
  2090. }
  2091. }
  2092. void WaylandThread::_wp_tablet_tool_on_proximity_in(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial, struct zwp_tablet_v2 *tablet, struct wl_surface *surface) {
  2093. // NOTE: Works pretty much like wl_pointer::enter.
  2094. WindowState *ws = wl_surface_get_window_state(surface);
  2095. if (!ws) {
  2096. return;
  2097. }
  2098. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2099. ERR_FAIL_NULL(ts);
  2100. ts->data_pending.proximity_serial = serial;
  2101. ts->data_pending.proximal_id = ws->id;
  2102. ts->data_pending.last_proximal_id = ws->id;
  2103. DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool entered window %d.", ts->data_pending.proximal_id));
  2104. }
  2105. void WaylandThread::_wp_tablet_tool_on_proximity_out(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {
  2106. // NOTE: Works pretty much like wl_pointer::leave.
  2107. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2108. ERR_FAIL_NULL(ts);
  2109. if (ts->data_pending.proximal_id == DisplayServer::INVALID_WINDOW_ID) {
  2110. // We're probably on a decoration or some other third-party thing.
  2111. return;
  2112. }
  2113. DisplayServer::WindowID id = ts->data_pending.proximal_id;
  2114. ts->data_pending.proximal_id = DisplayServer::INVALID_WINDOW_ID;
  2115. ts->data_pending.pressed_button_mask.clear();
  2116. DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool left window %d.", id));
  2117. }
  2118. void WaylandThread::_wp_tablet_tool_on_down(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial) {
  2119. // NOTE: Works pretty much like wl_pointer::button but only for a pressed left
  2120. // button.
  2121. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2122. ERR_FAIL_NULL(ts);
  2123. TabletToolData &td = ts->data_pending;
  2124. td.pressed_button_mask.set_flag(mouse_button_to_mask(MouseButton::LEFT));
  2125. td.last_button_pressed = MouseButton::LEFT;
  2126. td.double_click_begun = true;
  2127. // The protocol doesn't cover this, but we can use this funky hack to make
  2128. // double clicking work.
  2129. td.button_time = OS::get_singleton()->get_ticks_msec();
  2130. }
  2131. void WaylandThread::_wp_tablet_tool_on_up(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {
  2132. // NOTE: Works pretty much like wl_pointer::button but only for a released left
  2133. // button.
  2134. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2135. ERR_FAIL_NULL(ts);
  2136. TabletToolData &td = ts->data_pending;
  2137. td.pressed_button_mask.clear_flag(mouse_button_to_mask(MouseButton::LEFT));
  2138. // The protocol doesn't cover this, but we can use this funky hack to make
  2139. // double clicking work.
  2140. td.button_time = OS::get_singleton()->get_ticks_msec();
  2141. }
  2142. void WaylandThread::_wp_tablet_tool_on_motion(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t x, wl_fixed_t y) {
  2143. // NOTE: Works pretty much like wl_pointer::motion.
  2144. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2145. ERR_FAIL_NULL(ts);
  2146. TabletToolData &td = ts->data_pending;
  2147. td.position.x = wl_fixed_to_double(x);
  2148. td.position.y = wl_fixed_to_double(y);
  2149. }
  2150. void WaylandThread::_wp_tablet_tool_on_pressure(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t pressure) {
  2151. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2152. ERR_FAIL_NULL(ts);
  2153. ts->data_pending.pressure = pressure;
  2154. }
  2155. void WaylandThread::_wp_tablet_tool_on_distance(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t distance) {
  2156. // Unsupported
  2157. }
  2158. void WaylandThread::_wp_tablet_tool_on_tilt(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t tilt_x, wl_fixed_t tilt_y) {
  2159. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2160. ERR_FAIL_NULL(ts);
  2161. TabletToolData &td = ts->data_pending;
  2162. td.tilt.x = wl_fixed_to_double(tilt_x);
  2163. td.tilt.y = wl_fixed_to_double(tilt_y);
  2164. }
  2165. void WaylandThread::_wp_tablet_tool_on_rotation(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees) {
  2166. // Unsupported.
  2167. }
  2168. void WaylandThread::_wp_tablet_tool_on_slider(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, int32_t position) {
  2169. // Unsupported.
  2170. }
  2171. void WaylandThread::_wp_tablet_tool_on_wheel(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees, int32_t clicks) {
  2172. // TODO
  2173. }
  2174. void WaylandThread::_wp_tablet_tool_on_button(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial, uint32_t button, uint32_t state) {
  2175. // NOTE: Works pretty much like wl_pointer::button.
  2176. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2177. ERR_FAIL_NULL(ts);
  2178. TabletToolData &td = ts->data_pending;
  2179. MouseButton mouse_button = MouseButton::NONE;
  2180. if (button == BTN_STYLUS) {
  2181. mouse_button = MouseButton::LEFT;
  2182. }
  2183. if (button == BTN_STYLUS2) {
  2184. mouse_button = MouseButton::RIGHT;
  2185. }
  2186. if (mouse_button != MouseButton::NONE) {
  2187. MouseButtonMask mask = mouse_button_to_mask(mouse_button);
  2188. if (state == ZWP_TABLET_TOOL_V2_BUTTON_STATE_PRESSED) {
  2189. td.pressed_button_mask.set_flag(mask);
  2190. td.last_button_pressed = mouse_button;
  2191. td.double_click_begun = true;
  2192. } else {
  2193. td.pressed_button_mask.clear_flag(mask);
  2194. }
  2195. // The protocol doesn't cover this, but we can use this funky hack to make
  2196. // double clicking work.
  2197. td.button_time = OS::get_singleton()->get_ticks_msec();
  2198. }
  2199. }
  2200. void WaylandThread::_wp_tablet_tool_on_frame(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t time) {
  2201. // NOTE: Works pretty much like wl_pointer::frame.
  2202. TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);
  2203. ERR_FAIL_NULL(ts);
  2204. SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
  2205. ERR_FAIL_NULL(ss);
  2206. WaylandThread *wayland_thread = ss->wayland_thread;
  2207. ERR_FAIL_NULL(wayland_thread);
  2208. TabletToolData &old_td = ts->data;
  2209. TabletToolData &td = ts->data_pending;
  2210. if (td.proximal_id != old_td.proximal_id) {
  2211. if (old_td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {
  2212. Ref<WindowEventMessage> msg;
  2213. msg.instantiate();
  2214. msg->id = old_td.proximal_id;
  2215. msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;
  2216. wayland_thread->push_message(msg);
  2217. }
  2218. if (td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {
  2219. Ref<WindowEventMessage> msg;
  2220. msg.instantiate();
  2221. msg->id = td.proximal_id;
  2222. msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  2223. wayland_thread->push_message(msg);
  2224. }
  2225. }
  2226. if (td.proximal_id == DisplayServer::INVALID_WINDOW_ID) {
  2227. // We're probably on a decoration or some other third-party thing. Let's
  2228. // "commit" the data and call it a day.
  2229. old_td = td;
  2230. return;
  2231. }
  2232. WindowState *ws = wayland_thread->window_get_state(td.proximal_id);
  2233. ERR_FAIL_NULL(ws);
  2234. double scale = window_state_get_scale_factor(ws);
  2235. if (old_td.position != td.position || old_td.tilt != td.tilt || old_td.pressure != td.pressure) {
  2236. td.motion_time = time;
  2237. Ref<InputEventMouseMotion> mm;
  2238. mm.instantiate();
  2239. mm->set_window_id(td.proximal_id);
  2240. // Set all pressed modifiers.
  2241. mm->set_shift_pressed(ss->shift_pressed);
  2242. mm->set_ctrl_pressed(ss->ctrl_pressed);
  2243. mm->set_alt_pressed(ss->alt_pressed);
  2244. mm->set_meta_pressed(ss->meta_pressed);
  2245. mm->set_button_mask(td.pressed_button_mask);
  2246. mm->set_global_position(td.position * scale);
  2247. mm->set_position(td.position * scale);
  2248. // NOTE: The Godot API expects normalized values and we store them raw,
  2249. // straight from the compositor, so we have to normalize them here.
  2250. // According to the tablet proto spec, tilt is expressed in degrees relative
  2251. // to the Z axis of the tablet, so it shouldn't go over 90 degrees either way,
  2252. // I think. We'll clamp it just in case.
  2253. td.tilt = td.tilt.clampf(-90, 90);
  2254. mm->set_tilt(td.tilt / 90);
  2255. // The tablet proto spec explicitly says that pressure is defined as a value
  2256. // between 0 to 65535.
  2257. mm->set_pressure(td.pressure / (float)65535);
  2258. mm->set_pen_inverted(ts->is_eraser);
  2259. Vector2 pos_delta = (td.position - old_td.position) * scale;
  2260. mm->set_relative(pos_delta);
  2261. mm->set_relative_screen_position(pos_delta);
  2262. uint32_t time_delta = td.motion_time - old_td.motion_time;
  2263. mm->set_velocity((Vector2)pos_delta / time_delta);
  2264. Ref<InputEventMessage> inputev_msg;
  2265. inputev_msg.instantiate();
  2266. inputev_msg->event = mm;
  2267. wayland_thread->push_message(inputev_msg);
  2268. }
  2269. if (old_td.pressed_button_mask != td.pressed_button_mask) {
  2270. td.button_time = time;
  2271. BitField<MouseButtonMask> pressed_mask_delta = old_td.pressed_button_mask.get_different(td.pressed_button_mask);
  2272. for (MouseButton test_button : { MouseButton::LEFT, MouseButton::RIGHT }) {
  2273. MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);
  2274. if (pressed_mask_delta.has_flag(test_button_mask)) {
  2275. Ref<InputEventMouseButton> mb;
  2276. mb.instantiate();
  2277. // Set all pressed modifiers.
  2278. mb->set_shift_pressed(ss->shift_pressed);
  2279. mb->set_ctrl_pressed(ss->ctrl_pressed);
  2280. mb->set_alt_pressed(ss->alt_pressed);
  2281. mb->set_meta_pressed(ss->meta_pressed);
  2282. mb->set_window_id(td.proximal_id);
  2283. mb->set_position(td.position * scale);
  2284. mb->set_global_position(td.position * scale);
  2285. mb->set_button_mask(td.pressed_button_mask);
  2286. mb->set_button_index(test_button);
  2287. mb->set_pressed(td.pressed_button_mask.has_flag(test_button_mask));
  2288. // We have to set the last position pressed here as we can't take for
  2289. // granted what the individual events might have seen due to them not having
  2290. // a garaunteed order.
  2291. if (mb->is_pressed()) {
  2292. td.last_pressed_position = td.position;
  2293. }
  2294. if (old_td.double_click_begun && mb->is_pressed() && td.last_button_pressed == old_td.last_button_pressed && (td.button_time - old_td.button_time) < 400 && Vector2(td.last_pressed_position * scale).distance_to(Vector2(old_td.last_pressed_position * scale)) < 5) {
  2295. td.double_click_begun = false;
  2296. mb->set_double_click(true);
  2297. }
  2298. Ref<InputEventMessage> msg;
  2299. msg.instantiate();
  2300. msg->event = mb;
  2301. wayland_thread->push_message(msg);
  2302. }
  2303. }
  2304. }
  2305. old_td = td;
  2306. }
  2307. void WaylandThread::_wp_text_input_on_enter(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {
  2308. SeatState *ss = (SeatState *)data;
  2309. if (!ss) {
  2310. return;
  2311. }
  2312. WindowState *ws = wl_surface_get_window_state(surface);
  2313. if (!ws) {
  2314. return;
  2315. }
  2316. ss->ime_window_id = ws->id;
  2317. ss->ime_enabled = true;
  2318. }
  2319. void WaylandThread::_wp_text_input_on_leave(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {
  2320. SeatState *ss = (SeatState *)data;
  2321. if (!ss) {
  2322. return;
  2323. }
  2324. Ref<IMEUpdateEventMessage> msg;
  2325. msg.instantiate();
  2326. msg->id = ss->ime_window_id;
  2327. msg->text = String();
  2328. msg->selection = Vector2i();
  2329. ss->wayland_thread->push_message(msg);
  2330. ss->ime_window_id = DisplayServer::INVALID_WINDOW_ID;
  2331. ss->ime_enabled = false;
  2332. ss->ime_active = false;
  2333. ss->ime_text = String();
  2334. ss->ime_text_commit = String();
  2335. ss->ime_cursor = Vector2i();
  2336. }
  2337. void WaylandThread::_wp_text_input_on_preedit_string(void *data, struct zwp_text_input_v3 *wp_text_input_v3, const char *text, int32_t cursor_begin, int32_t cursor_end) {
  2338. SeatState *ss = (SeatState *)data;
  2339. if (!ss) {
  2340. return;
  2341. }
  2342. ss->ime_text = String::utf8(text);
  2343. // Convert cursor positions from UTF-8 to UTF-32 offset.
  2344. int32_t cursor_begin_utf32 = 0;
  2345. int32_t cursor_end_utf32 = 0;
  2346. for (int i = 0; i < ss->ime_text.length(); i++) {
  2347. uint32_t c = ss->ime_text[i];
  2348. if (c <= 0x7f) { // 7 bits.
  2349. cursor_begin -= 1;
  2350. cursor_end -= 1;
  2351. } else if (c <= 0x7ff) { // 11 bits
  2352. cursor_begin -= 2;
  2353. cursor_end -= 2;
  2354. } else if (c <= 0xffff) { // 16 bits
  2355. cursor_begin -= 3;
  2356. cursor_end -= 3;
  2357. } else if (c <= 0x001fffff) { // 21 bits
  2358. cursor_begin -= 4;
  2359. cursor_end -= 4;
  2360. } else if (c <= 0x03ffffff) { // 26 bits
  2361. cursor_begin -= 5;
  2362. cursor_end -= 5;
  2363. } else if (c <= 0x7fffffff) { // 31 bits
  2364. cursor_begin -= 6;
  2365. cursor_end -= 6;
  2366. } else {
  2367. cursor_begin -= 1;
  2368. cursor_end -= 1;
  2369. }
  2370. if (cursor_begin == 0) {
  2371. cursor_begin_utf32 = i + 1;
  2372. }
  2373. if (cursor_end == 0) {
  2374. cursor_end_utf32 = i + 1;
  2375. }
  2376. if (cursor_begin <= 0 && cursor_end <= 0) {
  2377. break;
  2378. }
  2379. }
  2380. ss->ime_cursor = Vector2i(cursor_begin_utf32, cursor_end_utf32 - cursor_begin_utf32);
  2381. }
  2382. void WaylandThread::_wp_text_input_on_commit_string(void *data, struct zwp_text_input_v3 *wp_text_input_v3, const char *text) {
  2383. SeatState *ss = (SeatState *)data;
  2384. if (!ss) {
  2385. return;
  2386. }
  2387. ss->ime_text_commit = String::utf8(text);
  2388. }
  2389. void WaylandThread::_wp_text_input_on_delete_surrounding_text(void *data, struct zwp_text_input_v3 *wp_text_input_v3, uint32_t before_length, uint32_t after_length) {
  2390. // Not implemented.
  2391. }
  2392. void WaylandThread::_wp_text_input_on_done(void *data, struct zwp_text_input_v3 *wp_text_input_v3, uint32_t serial) {
  2393. SeatState *ss = (SeatState *)data;
  2394. if (!ss) {
  2395. return;
  2396. }
  2397. if (!ss->ime_text_commit.is_empty()) {
  2398. Ref<IMECommitEventMessage> msg;
  2399. msg.instantiate();
  2400. msg->id = ss->ime_window_id;
  2401. msg->text = ss->ime_text_commit;
  2402. ss->wayland_thread->push_message(msg);
  2403. } else {
  2404. Ref<IMEUpdateEventMessage> msg;
  2405. msg.instantiate();
  2406. msg->id = ss->ime_window_id;
  2407. msg->text = ss->ime_text;
  2408. msg->selection = ss->ime_cursor;
  2409. ss->wayland_thread->push_message(msg);
  2410. }
  2411. ss->ime_text = String();
  2412. ss->ime_text_commit = String();
  2413. ss->ime_cursor = Vector2i();
  2414. }
  2415. void WaylandThread::_xdg_activation_token_on_done(void *data, struct xdg_activation_token_v1 *xdg_activation_token, const char *token) {
  2416. WindowState *ws = (WindowState *)data;
  2417. ERR_FAIL_NULL(ws);
  2418. ERR_FAIL_NULL(ws->wayland_thread);
  2419. ERR_FAIL_NULL(ws->wl_surface);
  2420. xdg_activation_v1_activate(ws->wayland_thread->registry.xdg_activation, token, ws->wl_surface);
  2421. xdg_activation_token_v1_destroy(xdg_activation_token);
  2422. DEBUG_LOG_WAYLAND_THREAD(vformat("Received activation token and requested window activation."));
  2423. }
  2424. void WaylandThread::_godot_embedding_compositor_on_client(void *data, struct godot_embedding_compositor *godot_embedding_compositor, struct godot_embedded_client *godot_embedded_client, int32_t pid) {
  2425. EmbeddingCompositorState *state = (EmbeddingCompositorState *)data;
  2426. ERR_FAIL_NULL(state);
  2427. EmbeddedClientState *client_state = memnew(EmbeddedClientState);
  2428. client_state->embedding_compositor = godot_embedding_compositor;
  2429. client_state->pid = pid;
  2430. godot_embedded_client_add_listener(godot_embedded_client, &godot_embedded_client_listener, client_state);
  2431. DEBUG_LOG_WAYLAND_THREAD(vformat("New client %d.", pid));
  2432. state->clients.push_back(godot_embedded_client);
  2433. }
  2434. void WaylandThread::_godot_embedded_client_on_disconnected(void *data, struct godot_embedded_client *godot_embedded_client) {
  2435. EmbeddedClientState *state = (EmbeddedClientState *)data;
  2436. ERR_FAIL_NULL(state);
  2437. EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);
  2438. ERR_FAIL_NULL(ecomp_state);
  2439. ecomp_state->clients.erase_unordered(godot_embedded_client);
  2440. ecomp_state->mapped_clients.erase(state->pid);
  2441. memfree(state);
  2442. godot_embedded_client_destroy(godot_embedded_client);
  2443. DEBUG_LOG_WAYLAND_THREAD(vformat("Client %d disconnected.", state->pid));
  2444. }
  2445. void WaylandThread::_godot_embedded_client_on_window_embedded(void *data, struct godot_embedded_client *godot_embedded_client) {
  2446. EmbeddedClientState *state = (EmbeddedClientState *)data;
  2447. ERR_FAIL_NULL(state);
  2448. EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);
  2449. ERR_FAIL_NULL(ecomp_state);
  2450. state->window_mapped = true;
  2451. ERR_FAIL_COND_MSG(ecomp_state->mapped_clients.has(state->pid), "More than one Wayland client per PID tried to create a window.");
  2452. ecomp_state->mapped_clients[state->pid] = godot_embedded_client;
  2453. }
  2454. void WaylandThread::_godot_embedded_client_on_window_focus_in(void *data, struct godot_embedded_client *godot_embedded_client) {
  2455. EmbeddedClientState *state = (EmbeddedClientState *)data;
  2456. ERR_FAIL_NULL(state);
  2457. EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);
  2458. ERR_FAIL_NULL(ecomp_state);
  2459. ecomp_state->focused_pid = state->pid;
  2460. DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus in", state->pid));
  2461. }
  2462. void WaylandThread::_godot_embedded_client_on_window_focus_out(void *data, struct godot_embedded_client *godot_embedded_client) {
  2463. EmbeddedClientState *state = (EmbeddedClientState *)data;
  2464. ERR_FAIL_NULL(state);
  2465. EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);
  2466. ERR_FAIL_NULL(ecomp_state);
  2467. ecomp_state->focused_pid = -1;
  2468. DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus out", state->pid));
  2469. }
  2470. // NOTE: This must be started after a valid wl_display is loaded.
  2471. void WaylandThread::_poll_events_thread(void *p_data) {
  2472. Thread::set_name("Wayland Events");
  2473. ThreadData *data = (ThreadData *)p_data;
  2474. ERR_FAIL_NULL(data);
  2475. ERR_FAIL_NULL(data->wl_display);
  2476. struct pollfd poll_fd = {};
  2477. poll_fd.fd = wl_display_get_fd(data->wl_display);
  2478. poll_fd.events = POLLIN;
  2479. while (true) {
  2480. // Empty the event queue while it's full.
  2481. while (wl_display_prepare_read(data->wl_display) != 0) {
  2482. // We aren't using wl_display_dispatch(), instead "manually" handling events
  2483. // through wl_display_dispatch_pending so that we can use a global mutex and
  2484. // be sure that this and the main thread won't race over stuff, as long as
  2485. // the main thread locks it too.
  2486. //
  2487. // Note that the main thread can still call wl_display_roundtrip as that
  2488. // method directly handles all events, effectively bypassing this polling
  2489. // loop and thus the mutex locking, avoiding a deadlock.
  2490. //
  2491. // WARNING: Never call `wl_display_roundtrip` inside event handlers or while
  2492. // this mutex isn't held! `wl_display_roundtrip` manually handles new events
  2493. // and if not properly gated it _will_ cause potentially stall-inducing race
  2494. // conditions. Ask me how I know.
  2495. MutexLock mutex_lock(data->mutex);
  2496. if (wl_display_dispatch_pending(data->wl_display) == -1) {
  2497. // Oh no. We'll check and handle any display error below.
  2498. break;
  2499. }
  2500. }
  2501. int werror = wl_display_get_error(data->wl_display);
  2502. if (werror) {
  2503. if (werror == EPROTO) {
  2504. struct wl_interface *wl_interface = nullptr;
  2505. uint32_t id = 0;
  2506. int error_code = wl_display_get_protocol_error(data->wl_display, (const struct wl_interface **)&wl_interface, &id);
  2507. CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));
  2508. } else {
  2509. CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));
  2510. }
  2511. }
  2512. wl_display_flush(data->wl_display);
  2513. // Wait for the event file descriptor to have new data.
  2514. poll(&poll_fd, 1, -1);
  2515. if (data->thread_done.is_set()) {
  2516. wl_display_cancel_read(data->wl_display);
  2517. break;
  2518. }
  2519. if (poll_fd.revents | POLLIN) {
  2520. // Load the queues with fresh new data.
  2521. wl_display_read_events(data->wl_display);
  2522. } else {
  2523. // Oh well... Stop signaling that we want to read.
  2524. wl_display_cancel_read(data->wl_display);
  2525. }
  2526. // The docs advise to redispatch unconditionally and it looks like that if we
  2527. // don't do this we can't catch protocol errors, which is bad.
  2528. MutexLock mutex_lock(data->mutex);
  2529. wl_display_dispatch_pending(data->wl_display);
  2530. }
  2531. }
  2532. struct wl_display *WaylandThread::get_wl_display() const {
  2533. return wl_display;
  2534. }
  2535. // NOTE: Stuff like libdecor can (and will) register foreign proxies which
  2536. // aren't formatted as we like. This method is needed to detect whether a proxy
  2537. // has our tag. Also, be careful! The proxy has to be manually tagged or it
  2538. // won't be recognized.
  2539. bool WaylandThread::wl_proxy_is_godot(struct wl_proxy *p_proxy) {
  2540. ERR_FAIL_NULL_V(p_proxy, false);
  2541. return wl_proxy_get_tag(p_proxy) == &proxy_tag;
  2542. }
  2543. void WaylandThread::wl_proxy_tag_godot(struct wl_proxy *p_proxy) {
  2544. ERR_FAIL_NULL(p_proxy);
  2545. wl_proxy_set_tag(p_proxy, &proxy_tag);
  2546. }
  2547. // Returns the wl_surface's `WindowState`, otherwise `nullptr`.
  2548. // NOTE: This will fail if the surface isn't tagged as ours.
  2549. WaylandThread::WindowState *WaylandThread::wl_surface_get_window_state(struct wl_surface *p_surface) {
  2550. if (p_surface && wl_proxy_is_godot((wl_proxy *)p_surface)) {
  2551. return (WindowState *)wl_surface_get_user_data(p_surface);
  2552. }
  2553. return nullptr;
  2554. }
  2555. // Returns the wl_outputs's `ScreenState`, otherwise `nullptr`.
  2556. // NOTE: This will fail if the output isn't tagged as ours.
  2557. WaylandThread::ScreenState *WaylandThread::wl_output_get_screen_state(struct wl_output *p_output) {
  2558. if (p_output && wl_proxy_is_godot((wl_proxy *)p_output)) {
  2559. return (ScreenState *)wl_output_get_user_data(p_output);
  2560. }
  2561. return nullptr;
  2562. }
  2563. // Returns the wl_seat's `SeatState`, otherwise `nullptr`.
  2564. // NOTE: This will fail if the output isn't tagged as ours.
  2565. WaylandThread::SeatState *WaylandThread::wl_seat_get_seat_state(struct wl_seat *p_seat) {
  2566. if (p_seat && wl_proxy_is_godot((wl_proxy *)p_seat)) {
  2567. return (SeatState *)wl_seat_get_user_data(p_seat);
  2568. }
  2569. return nullptr;
  2570. }
  2571. // Returns the wp_tablet_tool's `TabletToolState`, otherwise `nullptr`.
  2572. // NOTE: This will fail if the output isn't tagged as ours.
  2573. WaylandThread::TabletToolState *WaylandThread::wp_tablet_tool_get_state(struct zwp_tablet_tool_v2 *p_tool) {
  2574. if (p_tool && wl_proxy_is_godot((wl_proxy *)p_tool)) {
  2575. return (TabletToolState *)zwp_tablet_tool_v2_get_user_data(p_tool);
  2576. }
  2577. return nullptr;
  2578. }
  2579. // Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.
  2580. // NOTE: This will fail if the output isn't tagged as ours.
  2581. WaylandThread::OfferState *WaylandThread::wl_data_offer_get_offer_state(struct wl_data_offer *p_offer) {
  2582. if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {
  2583. return (OfferState *)wl_data_offer_get_user_data(p_offer);
  2584. }
  2585. return nullptr;
  2586. }
  2587. // Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.
  2588. // NOTE: This will fail if the output isn't tagged as ours.
  2589. WaylandThread::OfferState *WaylandThread::wp_primary_selection_offer_get_offer_state(struct zwp_primary_selection_offer_v1 *p_offer) {
  2590. if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {
  2591. return (OfferState *)zwp_primary_selection_offer_v1_get_user_data(p_offer);
  2592. }
  2593. return nullptr;
  2594. }
  2595. WaylandThread::EmbeddingCompositorState *WaylandThread::godot_embedding_compositor_get_state(struct godot_embedding_compositor *p_compositor) {
  2596. // NOTE: No need for tag check as it's a "fake" interface - nothing else exposes it.
  2597. if (p_compositor) {
  2598. return (EmbeddingCompositorState *)godot_embedding_compositor_get_user_data(p_compositor);
  2599. }
  2600. return nullptr;
  2601. }
  2602. // This is implemented as a method because this is the simplest way of
  2603. // accounting for dynamic output scale changes.
  2604. int WaylandThread::window_state_get_preferred_buffer_scale(WindowState *p_ws) {
  2605. ERR_FAIL_NULL_V(p_ws, 1);
  2606. if (p_ws->preferred_fractional_scale > 0) {
  2607. // We're scaling fractionally. Per spec, the buffer scale is always 1.
  2608. return 1;
  2609. }
  2610. if (p_ws->wl_outputs.is_empty()) {
  2611. DEBUG_LOG_WAYLAND_THREAD("Window has no output associated, returning buffer scale of 1.");
  2612. return 1;
  2613. }
  2614. // TODO: Cache value?
  2615. int max_size = 1;
  2616. // ================================ IMPORTANT =================================
  2617. // NOTE: Due to a Godot limitation, we can't really rescale the whole UI yet.
  2618. // Because of this reason, all platforms have resorted to forcing the highest
  2619. // scale possible of a system on any window, despite of what screen it's onto.
  2620. // On this backend everything's already in place for dynamic window scale
  2621. // handling, but in the meantime we'll just select the biggest _global_ output.
  2622. // To restore dynamic scale selection, simply iterate over `p_ws->wl_outputs`
  2623. // instead.
  2624. for (struct wl_output *wl_output : p_ws->registry->wl_outputs) {
  2625. ScreenState *ss = wl_output_get_screen_state(wl_output);
  2626. if (ss && ss->pending_data.scale > max_size) {
  2627. // NOTE: For some mystical reason, wl_output.done is emitted _after_ windows
  2628. // get resized but the scale event gets sent _before_ that. I'm still leaning
  2629. // towards the idea that rescaling when a window gets a resolution change is a
  2630. // pretty good approach, but this means that we'll have to use the screen data
  2631. // before it's "committed".
  2632. // FIXME: Use the committed data. Somehow.
  2633. max_size = ss->pending_data.scale;
  2634. }
  2635. }
  2636. return max_size;
  2637. }
  2638. double WaylandThread::window_state_get_scale_factor(const WindowState *p_ws) {
  2639. ERR_FAIL_NULL_V(p_ws, 1);
  2640. if (p_ws->fractional_scale > 0) {
  2641. // The fractional scale amount takes priority.
  2642. return p_ws->fractional_scale;
  2643. }
  2644. return p_ws->buffer_scale;
  2645. }
  2646. void WaylandThread::window_state_update_size(WindowState *p_ws, int p_width, int p_height) {
  2647. ERR_FAIL_NULL(p_ws);
  2648. int preferred_buffer_scale = window_state_get_preferred_buffer_scale(p_ws);
  2649. bool using_fractional = p_ws->preferred_fractional_scale > 0;
  2650. // If neither is true we no-op.
  2651. bool scale_changed = false;
  2652. bool size_changed = false;
  2653. if (p_ws->rect.size.width != p_width || p_ws->rect.size.height != p_height) {
  2654. p_ws->rect.size.width = p_width;
  2655. p_ws->rect.size.height = p_height;
  2656. size_changed = true;
  2657. }
  2658. if (using_fractional && p_ws->fractional_scale != p_ws->preferred_fractional_scale) {
  2659. p_ws->fractional_scale = p_ws->preferred_fractional_scale;
  2660. scale_changed = true;
  2661. }
  2662. if (p_ws->buffer_scale != preferred_buffer_scale) {
  2663. // The buffer scale is always important, even if we use frac scaling.
  2664. p_ws->buffer_scale = preferred_buffer_scale;
  2665. p_ws->buffer_scale_changed = true;
  2666. if (!using_fractional) {
  2667. // We don't bother updating everything else if it's turned on though.
  2668. scale_changed = true;
  2669. }
  2670. }
  2671. if (p_ws->wl_surface) {
  2672. if (p_ws->wp_viewport) {
  2673. wp_viewport_set_destination(p_ws->wp_viewport, p_width, p_height);
  2674. }
  2675. if (p_ws->xdg_surface) {
  2676. xdg_surface_set_window_geometry(p_ws->xdg_surface, 0, 0, p_width, p_height);
  2677. }
  2678. }
  2679. #ifdef LIBDECOR_ENABLED
  2680. if (p_ws->libdecor_frame) {
  2681. struct libdecor_state *state = libdecor_state_new(p_width, p_height);
  2682. libdecor_frame_commit(p_ws->libdecor_frame, state, p_ws->pending_libdecor_configuration);
  2683. libdecor_state_free(state);
  2684. p_ws->pending_libdecor_configuration = nullptr;
  2685. }
  2686. #endif
  2687. if (size_changed || scale_changed) {
  2688. double win_scale = window_state_get_scale_factor(p_ws);
  2689. Size2i scaled_size = scale_vector2i(p_ws->rect.size, win_scale);
  2690. if (using_fractional) {
  2691. DEBUG_LOG_WAYLAND_THREAD(vformat("Resizing the window from %s to %s (fractional scale x%f).", p_ws->rect.size, scaled_size, p_ws->fractional_scale));
  2692. } else {
  2693. DEBUG_LOG_WAYLAND_THREAD(vformat("Resizing the window from %s to %s (buffer scale x%d).", p_ws->rect.size, scaled_size, p_ws->buffer_scale));
  2694. }
  2695. // FIXME: Actually resize the hint instead of centering it.
  2696. p_ws->wayland_thread->pointer_set_hint(scaled_size / 2);
  2697. Ref<WindowRectMessage> rect_msg;
  2698. rect_msg.instantiate();
  2699. rect_msg->id = p_ws->id;
  2700. rect_msg->rect.position = scale_vector2i(p_ws->rect.position, win_scale);
  2701. rect_msg->rect.size = scaled_size;
  2702. p_ws->wayland_thread->push_message(rect_msg);
  2703. }
  2704. if (scale_changed) {
  2705. Ref<WindowEventMessage> dpi_msg;
  2706. dpi_msg.instantiate();
  2707. dpi_msg->id = p_ws->id;
  2708. dpi_msg->event = DisplayServer::WINDOW_EVENT_DPI_CHANGE;
  2709. p_ws->wayland_thread->push_message(dpi_msg);
  2710. }
  2711. }
  2712. // Scales a vector according to wp_fractional_scale's rules, where coordinates
  2713. // must be scaled with away from zero half-rounding.
  2714. Vector2i WaylandThread::scale_vector2i(const Vector2i &p_vector, double p_amount) {
  2715. // This snippet is tiny, I know, but this is done a lot.
  2716. int x = std::round(p_vector.x * p_amount);
  2717. int y = std::round(p_vector.y * p_amount);
  2718. return Vector2i(x, y);
  2719. }
  2720. void WaylandThread::seat_state_unlock_pointer(SeatState *p_ss) {
  2721. ERR_FAIL_NULL(p_ss);
  2722. if (p_ss->wl_pointer == nullptr) {
  2723. return;
  2724. }
  2725. if (p_ss->wp_locked_pointer) {
  2726. zwp_locked_pointer_v1_destroy(p_ss->wp_locked_pointer);
  2727. p_ss->wp_locked_pointer = nullptr;
  2728. }
  2729. if (p_ss->wp_confined_pointer) {
  2730. zwp_confined_pointer_v1_destroy(p_ss->wp_confined_pointer);
  2731. p_ss->wp_confined_pointer = nullptr;
  2732. }
  2733. }
  2734. void WaylandThread::seat_state_lock_pointer(SeatState *p_ss) {
  2735. ERR_FAIL_NULL(p_ss);
  2736. if (p_ss->wl_pointer == nullptr) {
  2737. WARN_PRINT("Can't lock - no pointer?");
  2738. return;
  2739. }
  2740. if (registry.wp_pointer_constraints == nullptr) {
  2741. WARN_PRINT("Can't lock - no constraints global.");
  2742. return;
  2743. }
  2744. if (p_ss->wp_locked_pointer == nullptr) {
  2745. struct wl_surface *locked_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);
  2746. if (locked_surface == nullptr) {
  2747. locked_surface = window_get_wl_surface(DisplayServer::MAIN_WINDOW_ID);
  2748. }
  2749. ERR_FAIL_NULL(locked_surface);
  2750. p_ss->wp_locked_pointer = zwp_pointer_constraints_v1_lock_pointer(registry.wp_pointer_constraints, locked_surface, p_ss->wl_pointer, nullptr, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
  2751. }
  2752. }
  2753. void WaylandThread::seat_state_set_hint(SeatState *p_ss, int p_x, int p_y) {
  2754. if (p_ss->wp_locked_pointer == nullptr) {
  2755. return;
  2756. }
  2757. zwp_locked_pointer_v1_set_cursor_position_hint(p_ss->wp_locked_pointer, wl_fixed_from_int(p_x), wl_fixed_from_int(p_y));
  2758. }
  2759. void WaylandThread::seat_state_confine_pointer(SeatState *p_ss) {
  2760. ERR_FAIL_NULL(p_ss);
  2761. if (p_ss->wl_pointer == nullptr) {
  2762. return;
  2763. }
  2764. if (registry.wp_pointer_constraints == nullptr) {
  2765. return;
  2766. }
  2767. if (p_ss->wp_confined_pointer == nullptr) {
  2768. struct wl_surface *confined_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);
  2769. ERR_FAIL_NULL(confined_surface);
  2770. p_ss->wp_confined_pointer = zwp_pointer_constraints_v1_confine_pointer(registry.wp_pointer_constraints, confined_surface, p_ss->wl_pointer, nullptr, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
  2771. }
  2772. }
  2773. void WaylandThread::seat_state_update_cursor(SeatState *p_ss) {
  2774. ERR_FAIL_NULL(p_ss);
  2775. WaylandThread *thread = p_ss->wayland_thread;
  2776. ERR_FAIL_NULL(p_ss->wayland_thread);
  2777. if (!p_ss->wl_pointer || !p_ss->cursor_surface) {
  2778. return;
  2779. }
  2780. // NOTE: Those values are valid by default and will hide the cursor when
  2781. // unchanged.
  2782. struct wl_buffer *cursor_buffer = nullptr;
  2783. uint32_t hotspot_x = 0;
  2784. uint32_t hotspot_y = 0;
  2785. int scale = 1;
  2786. if (thread->cursor_visible) {
  2787. DisplayServer::CursorShape shape = thread->cursor_shape;
  2788. struct CustomCursor *custom_cursor = thread->custom_cursors.getptr(shape);
  2789. if (custom_cursor) {
  2790. cursor_buffer = custom_cursor->wl_buffer;
  2791. hotspot_x = custom_cursor->hotspot.x;
  2792. hotspot_y = custom_cursor->hotspot.y;
  2793. // We can't really reasonably scale custom cursors, so we'll let the
  2794. // compositor do it for us (badly).
  2795. scale = 1;
  2796. } else if (thread->registry.wp_cursor_shape_manager) {
  2797. wp_cursor_shape_device_v1_shape wp_shape = thread->standard_cursors[shape];
  2798. wp_cursor_shape_device_v1_set_shape(p_ss->wp_cursor_shape_device, p_ss->pointer_enter_serial, wp_shape);
  2799. // We should avoid calling the `wl_pointer_set_cursor` at the end of this method.
  2800. return;
  2801. } else {
  2802. struct wl_cursor *wl_cursor = thread->wl_cursors[shape];
  2803. if (!wl_cursor) {
  2804. return;
  2805. }
  2806. int frame_idx = 0;
  2807. if (wl_cursor->image_count > 1) {
  2808. // The cursor is animated.
  2809. frame_idx = wl_cursor_frame(wl_cursor, p_ss->cursor_time_ms);
  2810. if (!p_ss->cursor_frame_callback) {
  2811. // Since it's animated, we'll re-update it the next frame.
  2812. p_ss->cursor_frame_callback = wl_surface_frame(p_ss->cursor_surface);
  2813. wl_callback_add_listener(p_ss->cursor_frame_callback, &cursor_frame_callback_listener, p_ss);
  2814. }
  2815. }
  2816. struct wl_cursor_image *wl_cursor_image = wl_cursor->images[frame_idx];
  2817. scale = thread->cursor_scale;
  2818. cursor_buffer = wl_cursor_image_get_buffer(wl_cursor_image);
  2819. // As the surface's buffer is scaled (thus the surface is smaller) and the
  2820. // hotspot must be expressed in surface-local coordinates, we need to scale
  2821. // it down accordingly.
  2822. hotspot_x = wl_cursor_image->hotspot_x / scale;
  2823. hotspot_y = wl_cursor_image->hotspot_y / scale;
  2824. }
  2825. }
  2826. wl_pointer_set_cursor(p_ss->wl_pointer, p_ss->pointer_enter_serial, p_ss->cursor_surface, hotspot_x, hotspot_y);
  2827. wl_surface_set_buffer_scale(p_ss->cursor_surface, scale);
  2828. wl_surface_attach(p_ss->cursor_surface, cursor_buffer, 0, 0);
  2829. wl_surface_damage_buffer(p_ss->cursor_surface, 0, 0, INT_MAX, INT_MAX);
  2830. wl_surface_commit(p_ss->cursor_surface);
  2831. }
  2832. void WaylandThread::seat_state_echo_keys(SeatState *p_ss) {
  2833. ERR_FAIL_NULL(p_ss);
  2834. if (p_ss->wl_keyboard == nullptr) {
  2835. return;
  2836. }
  2837. // TODO: Comment and document out properly this block of code.
  2838. // In short, this implements key repeating.
  2839. if (p_ss->repeat_key_delay_msec && p_ss->repeating_keycode != XKB_KEYCODE_INVALID) {
  2840. uint64_t current_ticks = OS::get_singleton()->get_ticks_msec();
  2841. uint64_t delayed_start_ticks = p_ss->last_repeat_start_msec + p_ss->repeat_start_delay_msec;
  2842. if (p_ss->last_repeat_msec < delayed_start_ticks) {
  2843. p_ss->last_repeat_msec = delayed_start_ticks;
  2844. }
  2845. if (current_ticks >= delayed_start_ticks) {
  2846. uint64_t ticks_delta = current_ticks - p_ss->last_repeat_msec;
  2847. int keys_amount = (ticks_delta / p_ss->repeat_key_delay_msec);
  2848. for (int i = 0; i < keys_amount; i++) {
  2849. _seat_state_handle_xkb_keycode(p_ss, p_ss->repeating_keycode, true, true);
  2850. }
  2851. p_ss->last_repeat_msec += ticks_delta - (ticks_delta % p_ss->repeat_key_delay_msec);
  2852. }
  2853. }
  2854. }
  2855. void WaylandThread::push_message(Ref<Message> message) {
  2856. messages.push_back(message);
  2857. }
  2858. bool WaylandThread::has_message() {
  2859. return messages.front() != nullptr;
  2860. }
  2861. Ref<WaylandThread::Message> WaylandThread::pop_message() {
  2862. if (messages.front() != nullptr) {
  2863. Ref<Message> msg = messages.front()->get();
  2864. messages.pop_front();
  2865. return msg;
  2866. }
  2867. // This method should only be called if `has_messages` returns true but if
  2868. // that isn't the case we'll just return an invalid `Ref`. After all, due to
  2869. // its `InputEvent`-like interface, we still have to dynamically cast and check
  2870. // the `Ref`'s validity anyways.
  2871. return Ref<Message>();
  2872. }
  2873. void WaylandThread::window_create(DisplayServer::WindowID p_window_id, const Size2i &p_size, DisplayServer::WindowID p_parent_id) {
  2874. ERR_FAIL_COND(windows.has(p_window_id));
  2875. WindowState &ws = windows[p_window_id];
  2876. ws.id = p_window_id;
  2877. ws.registry = &registry;
  2878. ws.wayland_thread = this;
  2879. ws.rect.size = p_size;
  2880. ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);
  2881. wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);
  2882. wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);
  2883. if (registry.wp_viewporter) {
  2884. ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);
  2885. if (registry.wp_fractional_scale_manager) {
  2886. ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);
  2887. wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);
  2888. }
  2889. }
  2890. bool decorated = false;
  2891. #ifdef LIBDECOR_ENABLED
  2892. if (!decorated && libdecor_context) {
  2893. ws.libdecor_frame = libdecor_decorate(libdecor_context, ws.wl_surface, (struct libdecor_frame_interface *)&libdecor_frame_interface, &ws);
  2894. libdecor_frame_map(ws.libdecor_frame);
  2895. if (registry.xdg_toplevel_icon_manager) {
  2896. xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);
  2897. if (toplevel != nullptr) {
  2898. xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);
  2899. }
  2900. }
  2901. decorated = true;
  2902. }
  2903. #endif
  2904. if (!decorated) {
  2905. // libdecor has failed loading or is disabled, we shall handle xdg_toplevel
  2906. // creation and decoration ourselves (and by decorating for now I just mean
  2907. // asking for SSDs and hoping for the best).
  2908. ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);
  2909. xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);
  2910. ws.xdg_toplevel = xdg_surface_get_toplevel(ws.xdg_surface);
  2911. xdg_toplevel_add_listener(ws.xdg_toplevel, &xdg_toplevel_listener, &ws);
  2912. if (registry.xdg_decoration_manager) {
  2913. ws.xdg_toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(registry.xdg_decoration_manager, ws.xdg_toplevel);
  2914. zxdg_toplevel_decoration_v1_add_listener(ws.xdg_toplevel_decoration, &xdg_toplevel_decoration_listener, &ws);
  2915. decorated = true;
  2916. }
  2917. if (registry.xdg_toplevel_icon_manager) {
  2918. xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);
  2919. }
  2920. }
  2921. if (p_parent_id != DisplayServer::INVALID_WINDOW_ID) {
  2922. // NOTE: It's important to set the parent ASAP to avoid misunderstandings with
  2923. // the compositor. For example, niri immediately resizes the window to full
  2924. // size as soon as it's configured if it's not parented to another toplevel.
  2925. window_set_parent(p_window_id, p_parent_id);
  2926. }
  2927. ws.frame_callback = wl_surface_frame(ws.wl_surface);
  2928. wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);
  2929. if (registry.xdg_exporter_v2) {
  2930. ws.xdg_exported_v2 = zxdg_exporter_v2_export_toplevel(registry.xdg_exporter_v2, ws.wl_surface);
  2931. zxdg_exported_v2_add_listener(ws.xdg_exported_v2, &xdg_exported_v2_listener, &ws);
  2932. } else if (registry.xdg_exporter_v1) {
  2933. ws.xdg_exported_v1 = zxdg_exporter_v1_export(registry.xdg_exporter_v1, ws.wl_surface);
  2934. zxdg_exported_v1_add_listener(ws.xdg_exported_v1, &xdg_exported_v1_listener, &ws);
  2935. }
  2936. wl_surface_commit(ws.wl_surface);
  2937. // Wait for the surface to be configured before continuing.
  2938. wl_display_roundtrip(wl_display);
  2939. window_state_update_size(&ws, ws.rect.size.width, ws.rect.size.height);
  2940. }
  2941. void WaylandThread::window_create_popup(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id, Rect2i p_rect) {
  2942. ERR_FAIL_COND(windows.has(p_window_id));
  2943. ERR_FAIL_COND(!windows.has(p_parent_id));
  2944. WindowState &ws = windows[p_window_id];
  2945. WindowState &parent = windows[p_parent_id];
  2946. double parent_scale = window_state_get_scale_factor(&parent);
  2947. p_rect.position = scale_vector2i(p_rect.position, 1.0 / parent_scale);
  2948. p_rect.size = scale_vector2i(p_rect.size, 1.0 / parent_scale);
  2949. ws.id = p_window_id;
  2950. ws.parent_id = p_parent_id;
  2951. ws.registry = &registry;
  2952. ws.wayland_thread = this;
  2953. ws.rect = p_rect;
  2954. ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);
  2955. wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);
  2956. wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);
  2957. if (registry.wp_viewporter) {
  2958. ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);
  2959. if (registry.wp_fractional_scale_manager) {
  2960. ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);
  2961. wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);
  2962. }
  2963. }
  2964. ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);
  2965. xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);
  2966. Rect2i positioner_rect;
  2967. positioner_rect.size = parent.rect.size;
  2968. struct xdg_surface *parent_xdg_surface = parent.xdg_surface;
  2969. Point2i offset = ws.rect.position - parent.rect.position;
  2970. #ifdef LIBDECOR_ENABLED
  2971. if (!parent_xdg_surface && parent.libdecor_frame) {
  2972. parent_xdg_surface = libdecor_frame_get_xdg_surface(parent.libdecor_frame);
  2973. int corner_x = 0;
  2974. int corner_y = 0;
  2975. libdecor_frame_translate_coordinate(parent.libdecor_frame, 0, 0, &corner_x, &corner_y);
  2976. positioner_rect.position.x = corner_x;
  2977. positioner_rect.position.y = corner_y;
  2978. positioner_rect.size.width -= corner_x;
  2979. positioner_rect.size.height -= corner_y;
  2980. }
  2981. #endif
  2982. ERR_FAIL_NULL(parent_xdg_surface);
  2983. struct xdg_positioner *xdg_positioner = xdg_wm_base_create_positioner(registry.xdg_wm_base);
  2984. xdg_positioner_set_size(xdg_positioner, ws.rect.size.width, ws.rect.size.height);
  2985. xdg_positioner_set_anchor(xdg_positioner, XDG_POSITIONER_ANCHOR_TOP_LEFT);
  2986. xdg_positioner_set_gravity(xdg_positioner, XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT);
  2987. xdg_positioner_set_constraint_adjustment(xdg_positioner, XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y);
  2988. xdg_positioner_set_anchor_rect(xdg_positioner, positioner_rect.position.x, positioner_rect.position.y, positioner_rect.size.width, positioner_rect.size.height);
  2989. xdg_positioner_set_offset(xdg_positioner, offset.x, offset.y);
  2990. ws.xdg_popup = xdg_surface_get_popup(ws.xdg_surface, parent_xdg_surface, xdg_positioner);
  2991. xdg_popup_add_listener(ws.xdg_popup, &xdg_popup_listener, &ws);
  2992. xdg_positioner_destroy(xdg_positioner);
  2993. ws.frame_callback = wl_surface_frame(ws.wl_surface);
  2994. wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);
  2995. wl_surface_commit(ws.wl_surface);
  2996. // Wait for the surface to be configured before continuing.
  2997. wl_display_roundtrip(wl_display);
  2998. }
  2999. void WaylandThread::window_destroy(DisplayServer::WindowID p_window_id) {
  3000. ERR_FAIL_COND(!windows.has(p_window_id));
  3001. WindowState &ws = windows[p_window_id];
  3002. if (ws.xdg_popup) {
  3003. xdg_popup_destroy(ws.xdg_popup);
  3004. }
  3005. if (ws.xdg_toplevel_decoration) {
  3006. zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);
  3007. }
  3008. if (ws.xdg_toplevel) {
  3009. xdg_toplevel_destroy(ws.xdg_toplevel);
  3010. }
  3011. #ifdef LIBDECOR_ENABLED
  3012. if (ws.libdecor_frame) {
  3013. libdecor_frame_unref(ws.libdecor_frame);
  3014. }
  3015. #endif // LIBDECOR_ENABLED
  3016. if (ws.wp_fractional_scale) {
  3017. wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);
  3018. }
  3019. if (ws.wp_viewport) {
  3020. wp_viewport_destroy(ws.wp_viewport);
  3021. }
  3022. if (ws.frame_callback) {
  3023. wl_callback_destroy(ws.frame_callback);
  3024. }
  3025. if (ws.xdg_surface) {
  3026. xdg_surface_destroy(ws.xdg_surface);
  3027. }
  3028. if (ws.wl_surface) {
  3029. wl_surface_destroy(ws.wl_surface);
  3030. }
  3031. // Before continuing, let's handle any leftover event that might still refer to
  3032. // this window.
  3033. wl_display_roundtrip(wl_display);
  3034. // We can already clean up here, we're done.
  3035. windows.erase(p_window_id);
  3036. }
  3037. struct wl_surface *WaylandThread::window_get_wl_surface(DisplayServer::WindowID p_window_id) const {
  3038. const WindowState *ws = windows.getptr(p_window_id);
  3039. if (ws) {
  3040. return ws->wl_surface;
  3041. }
  3042. return nullptr;
  3043. }
  3044. WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) {
  3045. return windows.getptr(p_window_id);
  3046. }
  3047. const WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) const {
  3048. return windows.getptr(p_window_id);
  3049. }
  3050. void WaylandThread::beep() const {
  3051. if (registry.xdg_system_bell) {
  3052. xdg_system_bell_v1_ring(registry.xdg_system_bell, nullptr);
  3053. }
  3054. }
  3055. void WaylandThread::window_start_drag(DisplayServer::WindowID p_window_id) {
  3056. ERR_FAIL_COND(!windows.has(p_window_id));
  3057. WindowState &ws = windows[p_window_id];
  3058. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3059. if (ss && ws.xdg_toplevel) {
  3060. xdg_toplevel_move(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial);
  3061. }
  3062. #ifdef LIBDECOR_ENABLED
  3063. if (ws.libdecor_frame) {
  3064. libdecor_frame_move(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial);
  3065. }
  3066. #endif
  3067. }
  3068. void WaylandThread::window_start_resize(DisplayServer::WindowResizeEdge p_edge, DisplayServer::WindowID p_window) {
  3069. ERR_FAIL_COND(!windows.has(p_window));
  3070. WindowState &ws = windows[p_window];
  3071. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3072. if (ss && ws.xdg_toplevel) {
  3073. xdg_toplevel_resize_edge edge = XDG_TOPLEVEL_RESIZE_EDGE_NONE;
  3074. switch (p_edge) {
  3075. case DisplayServer::WINDOW_EDGE_TOP_LEFT: {
  3076. edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;
  3077. } break;
  3078. case DisplayServer::WINDOW_EDGE_TOP: {
  3079. edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP;
  3080. } break;
  3081. case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {
  3082. edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;
  3083. } break;
  3084. case DisplayServer::WINDOW_EDGE_LEFT: {
  3085. edge = XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
  3086. } break;
  3087. case DisplayServer::WINDOW_EDGE_RIGHT: {
  3088. edge = XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
  3089. } break;
  3090. case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {
  3091. edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;
  3092. } break;
  3093. case DisplayServer::WINDOW_EDGE_BOTTOM: {
  3094. edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
  3095. } break;
  3096. case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {
  3097. edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;
  3098. } break;
  3099. default:
  3100. break;
  3101. }
  3102. xdg_toplevel_resize(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial, edge);
  3103. }
  3104. #ifdef LIBDECOR_ENABLED
  3105. if (ws.libdecor_frame) {
  3106. libdecor_resize_edge edge = LIBDECOR_RESIZE_EDGE_NONE;
  3107. switch (p_edge) {
  3108. case DisplayServer::WINDOW_EDGE_TOP_LEFT: {
  3109. edge = LIBDECOR_RESIZE_EDGE_TOP_LEFT;
  3110. } break;
  3111. case DisplayServer::WINDOW_EDGE_TOP: {
  3112. edge = LIBDECOR_RESIZE_EDGE_TOP;
  3113. } break;
  3114. case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {
  3115. edge = LIBDECOR_RESIZE_EDGE_TOP_RIGHT;
  3116. } break;
  3117. case DisplayServer::WINDOW_EDGE_LEFT: {
  3118. edge = LIBDECOR_RESIZE_EDGE_LEFT;
  3119. } break;
  3120. case DisplayServer::WINDOW_EDGE_RIGHT: {
  3121. edge = LIBDECOR_RESIZE_EDGE_RIGHT;
  3122. } break;
  3123. case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {
  3124. edge = LIBDECOR_RESIZE_EDGE_BOTTOM_LEFT;
  3125. } break;
  3126. case DisplayServer::WINDOW_EDGE_BOTTOM: {
  3127. edge = LIBDECOR_RESIZE_EDGE_BOTTOM;
  3128. } break;
  3129. case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {
  3130. edge = LIBDECOR_RESIZE_EDGE_BOTTOM_RIGHT;
  3131. } break;
  3132. default:
  3133. break;
  3134. }
  3135. libdecor_frame_resize(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial, edge);
  3136. }
  3137. #endif
  3138. }
  3139. void WaylandThread::window_set_parent(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id) {
  3140. ERR_FAIL_COND(!windows.has(p_window_id));
  3141. ERR_FAIL_COND(!windows.has(p_parent_id));
  3142. WindowState &child = windows[p_window_id];
  3143. child.parent_id = p_parent_id;
  3144. WindowState &parent = windows[p_parent_id];
  3145. // NOTE: We can't really unparent as, at the time of writing, libdecor
  3146. // segfaults when trying to set a null parent. Hopefully unparenting is not
  3147. // that common. Bummer.
  3148. #ifdef LIBDECOR_ENABLED
  3149. if (child.libdecor_frame && parent.libdecor_frame) {
  3150. libdecor_frame_set_parent(child.libdecor_frame, parent.libdecor_frame);
  3151. return;
  3152. }
  3153. #endif
  3154. if (child.xdg_toplevel && parent.xdg_toplevel) {
  3155. xdg_toplevel_set_parent(child.xdg_toplevel, parent.xdg_toplevel);
  3156. }
  3157. }
  3158. void WaylandThread::window_set_max_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {
  3159. ERR_FAIL_COND(!windows.has(p_window_id));
  3160. WindowState &ws = windows[p_window_id];
  3161. Vector2i logical_max_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));
  3162. if (ws.wl_surface && ws.xdg_toplevel) {
  3163. xdg_toplevel_set_max_size(ws.xdg_toplevel, logical_max_size.width, logical_max_size.height);
  3164. }
  3165. #ifdef LIBDECOR_ENABLED
  3166. if (ws.libdecor_frame) {
  3167. libdecor_frame_set_max_content_size(ws.libdecor_frame, logical_max_size.width, logical_max_size.height);
  3168. }
  3169. // FIXME: I'm not sure whether we have to commit the surface for this to apply.
  3170. #endif
  3171. }
  3172. void WaylandThread::window_set_min_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {
  3173. ERR_FAIL_COND(!windows.has(p_window_id));
  3174. WindowState &ws = windows[p_window_id];
  3175. Size2i logical_min_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));
  3176. if (ws.wl_surface && ws.xdg_toplevel) {
  3177. xdg_toplevel_set_min_size(ws.xdg_toplevel, logical_min_size.width, logical_min_size.height);
  3178. }
  3179. #ifdef LIBDECOR_ENABLED
  3180. if (ws.libdecor_frame) {
  3181. libdecor_frame_set_min_content_size(ws.libdecor_frame, logical_min_size.width, logical_min_size.height);
  3182. }
  3183. // FIXME: I'm not sure whether we have to commit the surface for this to apply.
  3184. #endif
  3185. }
  3186. bool WaylandThread::window_can_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) const {
  3187. ERR_FAIL_COND_V(!windows.has(p_window_id), false);
  3188. const WindowState &ws = windows[p_window_id];
  3189. switch (p_window_mode) {
  3190. case DisplayServer::WINDOW_MODE_WINDOWED: {
  3191. // Looks like it's guaranteed.
  3192. return true;
  3193. };
  3194. case DisplayServer::WINDOW_MODE_MINIMIZED: {
  3195. #ifdef LIBDECOR_ENABLED
  3196. if (ws.libdecor_frame) {
  3197. return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_MINIMIZE);
  3198. }
  3199. #endif // LIBDECOR_ENABLED
  3200. return ws.can_minimize;
  3201. };
  3202. case DisplayServer::WINDOW_MODE_MAXIMIZED: {
  3203. // NOTE: libdecor doesn't seem to have a maximize capability query?
  3204. // The fact that there's a fullscreen one makes me suspicious.
  3205. return ws.can_maximize;
  3206. };
  3207. case DisplayServer::WINDOW_MODE_FULLSCREEN:
  3208. case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {
  3209. #ifdef LIBDECOR_ENABLED
  3210. if (ws.libdecor_frame) {
  3211. return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_FULLSCREEN);
  3212. }
  3213. #endif // LIBDECOR_ENABLED
  3214. return ws.can_fullscreen;
  3215. };
  3216. }
  3217. return false;
  3218. }
  3219. void WaylandThread::window_try_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) {
  3220. ERR_FAIL_COND(!windows.has(p_window_id));
  3221. WindowState &ws = windows[p_window_id];
  3222. if (ws.mode == p_window_mode) {
  3223. return;
  3224. }
  3225. // Don't waste time with hidden windows and whatnot. Behave like it worked.
  3226. #ifdef LIBDECOR_ENABLED
  3227. if ((!ws.wl_surface || !ws.xdg_toplevel) && !ws.libdecor_frame) {
  3228. #else
  3229. if (!ws.wl_surface || !ws.xdg_toplevel) {
  3230. #endif // LIBDECOR_ENABLED
  3231. ws.mode = p_window_mode;
  3232. return;
  3233. }
  3234. // Return back to a windowed state so that we can apply what the user asked.
  3235. switch (ws.mode) {
  3236. case DisplayServer::WINDOW_MODE_WINDOWED: {
  3237. // Do nothing.
  3238. } break;
  3239. case DisplayServer::WINDOW_MODE_MINIMIZED: {
  3240. // We can't do much according to the xdg_shell protocol. I have no idea
  3241. // whether this implies that we should return or who knows what. For now
  3242. // we'll do nothing.
  3243. // TODO: Test this properly.
  3244. } break;
  3245. case DisplayServer::WINDOW_MODE_MAXIMIZED: {
  3246. // Try to unmaximize. This isn't garaunteed to work actually, so we'll have
  3247. // to check whether something changed.
  3248. if (ws.xdg_toplevel) {
  3249. xdg_toplevel_unset_maximized(ws.xdg_toplevel);
  3250. }
  3251. #ifdef LIBDECOR_ENABLED
  3252. if (ws.libdecor_frame) {
  3253. libdecor_frame_unset_maximized(ws.libdecor_frame);
  3254. }
  3255. #endif // LIBDECOR_ENABLED
  3256. } break;
  3257. case DisplayServer::WINDOW_MODE_FULLSCREEN:
  3258. case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {
  3259. // Same thing as above, unset fullscreen and check later if it worked.
  3260. if (ws.xdg_toplevel) {
  3261. xdg_toplevel_unset_fullscreen(ws.xdg_toplevel);
  3262. }
  3263. #ifdef LIBDECOR_ENABLED
  3264. if (ws.libdecor_frame) {
  3265. libdecor_frame_unset_fullscreen(ws.libdecor_frame);
  3266. }
  3267. #endif // LIBDECOR_ENABLED
  3268. } break;
  3269. }
  3270. // Wait for a configure event and hope that something changed.
  3271. wl_display_roundtrip(wl_display);
  3272. if (ws.mode != DisplayServer::WINDOW_MODE_WINDOWED) {
  3273. // The compositor refused our "normalization" request. It'd be useless or
  3274. // unpredictable to attempt setting a new state. We're done.
  3275. return;
  3276. }
  3277. // Ask the compositor to set the state indicated by the new mode.
  3278. switch (p_window_mode) {
  3279. case DisplayServer::WINDOW_MODE_WINDOWED: {
  3280. // Do nothing. We're already windowed.
  3281. } break;
  3282. case DisplayServer::WINDOW_MODE_MINIMIZED: {
  3283. if (!window_can_set_mode(p_window_id, p_window_mode)) {
  3284. // Minimization is special (read below). Better not mess with it if the
  3285. // compositor explicitly announces that it doesn't support it.
  3286. break;
  3287. }
  3288. if (ws.xdg_toplevel) {
  3289. xdg_toplevel_set_minimized(ws.xdg_toplevel);
  3290. }
  3291. #ifdef LIBDECOR_ENABLED
  3292. if (ws.libdecor_frame) {
  3293. libdecor_frame_set_minimized(ws.libdecor_frame);
  3294. }
  3295. #endif // LIBDECOR_ENABLED
  3296. // We have no way to actually detect this state, so we'll have to report it
  3297. // manually to the engine (hoping that it worked). In the worst case it'll
  3298. // get reset by the next configure event.
  3299. ws.mode = DisplayServer::WINDOW_MODE_MINIMIZED;
  3300. } break;
  3301. case DisplayServer::WINDOW_MODE_MAXIMIZED: {
  3302. if (ws.xdg_toplevel) {
  3303. xdg_toplevel_set_maximized(ws.xdg_toplevel);
  3304. }
  3305. #ifdef LIBDECOR_ENABLED
  3306. if (ws.libdecor_frame) {
  3307. libdecor_frame_set_maximized(ws.libdecor_frame);
  3308. }
  3309. #endif // LIBDECOR_ENABLED
  3310. } break;
  3311. case DisplayServer::WINDOW_MODE_FULLSCREEN:
  3312. case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {
  3313. if (ws.xdg_toplevel) {
  3314. xdg_toplevel_set_fullscreen(ws.xdg_toplevel, nullptr);
  3315. }
  3316. #ifdef LIBDECOR_ENABLED
  3317. if (ws.libdecor_frame) {
  3318. libdecor_frame_set_fullscreen(ws.libdecor_frame, nullptr);
  3319. }
  3320. #endif // LIBDECOR_ENABLED
  3321. } break;
  3322. default: {
  3323. } break;
  3324. }
  3325. }
  3326. void WaylandThread::window_set_borderless(DisplayServer::WindowID p_window_id, bool p_borderless) {
  3327. ERR_FAIL_COND(!windows.has(p_window_id));
  3328. WindowState &ws = windows[p_window_id];
  3329. if (ws.xdg_toplevel_decoration) {
  3330. if (p_borderless) {
  3331. // We implement borderless windows by simply asking the compositor to let
  3332. // us handle decorations (we don't).
  3333. zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);
  3334. } else {
  3335. zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
  3336. }
  3337. }
  3338. #ifdef LIBDECOR_ENABLED
  3339. if (ws.libdecor_frame) {
  3340. bool visible_current = libdecor_frame_is_visible(ws.libdecor_frame);
  3341. bool visible_target = !p_borderless;
  3342. // NOTE: We have to do this otherwise we trip on a libdecor bug where it's
  3343. // possible to destroy the frame more than once, by setting the visibility
  3344. // to false multiple times and thus crashing.
  3345. if (visible_current != visible_target) {
  3346. print_verbose(vformat("Setting libdecor frame visibility to %s", visible_target));
  3347. libdecor_frame_set_visibility(ws.libdecor_frame, visible_target);
  3348. }
  3349. }
  3350. #endif // LIBDECOR_ENABLED
  3351. }
  3352. void WaylandThread::window_set_title(DisplayServer::WindowID p_window_id, const String &p_title) {
  3353. ERR_FAIL_COND(!windows.has(p_window_id));
  3354. WindowState &ws = windows[p_window_id];
  3355. #ifdef LIBDECOR_ENABLED
  3356. if (ws.libdecor_frame) {
  3357. libdecor_frame_set_title(ws.libdecor_frame, p_title.utf8().get_data());
  3358. }
  3359. #endif // LIBDECOR_ENABLE
  3360. if (ws.xdg_toplevel) {
  3361. xdg_toplevel_set_title(ws.xdg_toplevel, p_title.utf8().get_data());
  3362. }
  3363. }
  3364. void WaylandThread::window_set_app_id(DisplayServer::WindowID p_window_id, const String &p_app_id) {
  3365. ERR_FAIL_COND(!windows.has(p_window_id));
  3366. WindowState &ws = windows[p_window_id];
  3367. #ifdef LIBDECOR_ENABLED
  3368. if (ws.libdecor_frame) {
  3369. libdecor_frame_set_app_id(ws.libdecor_frame, p_app_id.utf8().get_data());
  3370. return;
  3371. }
  3372. #endif // LIBDECOR_ENABLED
  3373. if (ws.xdg_toplevel) {
  3374. xdg_toplevel_set_app_id(ws.xdg_toplevel, p_app_id.utf8().get_data());
  3375. return;
  3376. }
  3377. }
  3378. void WaylandThread::set_icon(const Ref<Image> &p_icon) {
  3379. ERR_FAIL_COND(p_icon.is_null());
  3380. Size2i icon_size = p_icon->get_size();
  3381. ERR_FAIL_COND(icon_size.width != icon_size.height);
  3382. if (!registry.xdg_toplevel_icon_manager) {
  3383. return;
  3384. }
  3385. if (xdg_icon) {
  3386. xdg_toplevel_icon_v1_destroy(xdg_icon);
  3387. }
  3388. if (icon_buffer) {
  3389. wl_buffer_destroy(icon_buffer);
  3390. }
  3391. // NOTE: The stride is the width of the icon in bytes.
  3392. uint32_t icon_stride = icon_size.width * 4;
  3393. uint32_t data_size = icon_stride * icon_size.height;
  3394. // We need a shared memory object file descriptor in order to create a
  3395. // wl_buffer through wl_shm.
  3396. int fd = WaylandThread::_allocate_shm_file(data_size);
  3397. ERR_FAIL_COND(fd == -1);
  3398. uint32_t *buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  3399. // Create the Wayland buffer.
  3400. struct wl_shm_pool *shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);
  3401. icon_buffer = wl_shm_pool_create_buffer(shm_pool, 0, icon_size.width, icon_size.height, icon_stride, WL_SHM_FORMAT_ARGB8888);
  3402. wl_shm_pool_destroy(shm_pool);
  3403. // Fill the cursor buffer with the image data.
  3404. for (uint32_t index = 0; index < (uint32_t)(icon_size.width * icon_size.height); index++) {
  3405. int row_index = index / icon_size.width;
  3406. int column_index = (index % icon_size.width);
  3407. buffer_data[index] = p_icon->get_pixel(column_index, row_index).to_argb32();
  3408. // Wayland buffers, unless specified, require associated alpha, so we'll just
  3409. // associate the alpha in-place.
  3410. uint8_t *pixel_data = (uint8_t *)&buffer_data[index];
  3411. pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;
  3412. pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;
  3413. pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;
  3414. }
  3415. xdg_icon = xdg_toplevel_icon_manager_v1_create_icon(registry.xdg_toplevel_icon_manager);
  3416. xdg_toplevel_icon_v1_add_buffer(xdg_icon, icon_buffer, icon_size.width);
  3417. if (Engine::get_singleton()->is_editor_hint() || Engine::get_singleton()->is_project_manager_hint()) {
  3418. // Setting a name allows the godot icon to be overridden by a system theme.
  3419. // We only want the project manager and editor to get themed,
  3420. // Games will get icons with the protocol and themed icons with .desktop entries.
  3421. // NOTE: should be synced with the icon name in misc/dist/linuxbsd/Godot.desktop
  3422. xdg_toplevel_icon_v1_set_name(xdg_icon, "godot");
  3423. }
  3424. for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {
  3425. WindowState &ws = pair.value;
  3426. #ifdef LIBDECOR_ENABLED
  3427. if (ws.libdecor_frame) {
  3428. xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);
  3429. ERR_FAIL_NULL(toplevel);
  3430. xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);
  3431. }
  3432. #endif
  3433. if (ws.xdg_toplevel) {
  3434. xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);
  3435. }
  3436. }
  3437. }
  3438. DisplayServer::WindowMode WaylandThread::window_get_mode(DisplayServer::WindowID p_window_id) const {
  3439. ERR_FAIL_COND_V(!windows.has(p_window_id), DisplayServer::WINDOW_MODE_WINDOWED);
  3440. const WindowState &ws = windows[p_window_id];
  3441. return ws.mode;
  3442. }
  3443. void WaylandThread::window_request_attention(DisplayServer::WindowID p_window_id) {
  3444. ERR_FAIL_COND(!windows.has(p_window_id));
  3445. WindowState &ws = windows[p_window_id];
  3446. if (registry.xdg_activation) {
  3447. // Window attention requests are done through the XDG activation protocol.
  3448. xdg_activation_token_v1 *xdg_activation_token = xdg_activation_v1_get_activation_token(registry.xdg_activation);
  3449. xdg_activation_token_v1_add_listener(xdg_activation_token, &xdg_activation_token_listener, &ws);
  3450. xdg_activation_token_v1_commit(xdg_activation_token);
  3451. }
  3452. }
  3453. void WaylandThread::window_set_idle_inhibition(DisplayServer::WindowID p_window_id, bool p_enable) {
  3454. ERR_FAIL_COND(!windows.has(p_window_id));
  3455. WindowState &ws = windows[p_window_id];
  3456. if (p_enable) {
  3457. if (ws.registry->wp_idle_inhibit_manager && !ws.wp_idle_inhibitor) {
  3458. ERR_FAIL_NULL(ws.wl_surface);
  3459. ws.wp_idle_inhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor(ws.registry->wp_idle_inhibit_manager, ws.wl_surface);
  3460. }
  3461. } else {
  3462. if (ws.wp_idle_inhibitor) {
  3463. zwp_idle_inhibitor_v1_destroy(ws.wp_idle_inhibitor);
  3464. ws.wp_idle_inhibitor = nullptr;
  3465. }
  3466. }
  3467. }
  3468. bool WaylandThread::window_get_idle_inhibition(DisplayServer::WindowID p_window_id) const {
  3469. ERR_FAIL_COND_V(!windows.has(p_window_id), false);
  3470. const WindowState &ws = windows[p_window_id];
  3471. return ws.wp_idle_inhibitor != nullptr;
  3472. }
  3473. WaylandThread::ScreenData WaylandThread::screen_get_data(int p_screen) const {
  3474. ERR_FAIL_INDEX_V(p_screen, registry.wl_outputs.size(), ScreenData());
  3475. return wl_output_get_screen_state(registry.wl_outputs.get(p_screen))->data;
  3476. }
  3477. int WaylandThread::get_screen_count() const {
  3478. return registry.wl_outputs.size();
  3479. }
  3480. DisplayServer::WindowID WaylandThread::pointer_get_pointed_window_id() const {
  3481. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3482. if (ss) {
  3483. // Let's determine the most recently used tablet tool.
  3484. TabletToolState *max_ts = nullptr;
  3485. for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
  3486. TabletToolState *ts = wp_tablet_tool_get_state(tool);
  3487. ERR_CONTINUE(ts == nullptr);
  3488. TabletToolData &td = ts->data;
  3489. if (!max_ts) {
  3490. max_ts = ts;
  3491. continue;
  3492. }
  3493. if (MAX(td.button_time, td.motion_time) > MAX(max_ts->data.button_time, max_ts->data.motion_time)) {
  3494. max_ts = ts;
  3495. }
  3496. }
  3497. const PointerData &pd = ss->pointer_data;
  3498. if (max_ts) {
  3499. TabletToolData &td = max_ts->data;
  3500. if (MAX(td.button_time, td.motion_time) > MAX(pd.button_time, pd.motion_time)) {
  3501. return td.proximal_id;
  3502. }
  3503. }
  3504. return ss->pointer_data.pointed_id;
  3505. }
  3506. return DisplayServer::INVALID_WINDOW_ID;
  3507. }
  3508. DisplayServer::WindowID WaylandThread::pointer_get_last_pointed_window_id() const {
  3509. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3510. if (ss) {
  3511. // Let's determine the most recently used tablet tool.
  3512. TabletToolState *max_ts = nullptr;
  3513. for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
  3514. TabletToolState *ts = wp_tablet_tool_get_state(tool);
  3515. ERR_CONTINUE(ts == nullptr);
  3516. TabletToolData &td = ts->data;
  3517. if (!max_ts) {
  3518. max_ts = ts;
  3519. continue;
  3520. }
  3521. if (MAX(td.button_time, td.motion_time) > MAX(max_ts->data.button_time, max_ts->data.motion_time)) {
  3522. max_ts = ts;
  3523. }
  3524. }
  3525. const PointerData &pd = ss->pointer_data;
  3526. if (max_ts) {
  3527. TabletToolData &td = max_ts->data;
  3528. if (MAX(td.button_time, td.motion_time) > MAX(pd.button_time, pd.motion_time)) {
  3529. return td.last_proximal_id;
  3530. }
  3531. }
  3532. return ss->pointer_data.last_pointed_id;
  3533. }
  3534. return DisplayServer::INVALID_WINDOW_ID;
  3535. }
  3536. void WaylandThread::pointer_set_constraint(PointerConstraint p_constraint) {
  3537. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3538. if (ss) {
  3539. seat_state_unlock_pointer(ss);
  3540. if (p_constraint == PointerConstraint::LOCKED) {
  3541. seat_state_lock_pointer(ss);
  3542. } else if (p_constraint == PointerConstraint::CONFINED) {
  3543. seat_state_confine_pointer(ss);
  3544. }
  3545. }
  3546. pointer_constraint = p_constraint;
  3547. }
  3548. void WaylandThread::pointer_set_hint(const Point2i &p_hint) {
  3549. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3550. if (!ss) {
  3551. return;
  3552. }
  3553. WindowState *ws = window_get_state(ss->pointer_data.pointed_id);
  3554. int hint_x = 0;
  3555. int hint_y = 0;
  3556. if (ws) {
  3557. // NOTE: It looks like it's not really recommended to convert from
  3558. // "godot-space" to "wayland-space" and in general I received mixed feelings
  3559. // discussing about this. I'm not really sure about the maths behind this but,
  3560. // oh well, we're setting a cursor hint. ¯\_(ツ)_/¯
  3561. // See: https://oftc.irclog.whitequark.org/wayland/2023-08-23#1692756914-1692816818
  3562. hint_x = std::round(p_hint.x / window_state_get_scale_factor(ws));
  3563. hint_y = std::round(p_hint.y / window_state_get_scale_factor(ws));
  3564. }
  3565. if (ss) {
  3566. seat_state_set_hint(ss, hint_x, hint_y);
  3567. }
  3568. }
  3569. WaylandThread::PointerConstraint WaylandThread::pointer_get_constraint() const {
  3570. return pointer_constraint;
  3571. }
  3572. BitField<MouseButtonMask> WaylandThread::pointer_get_button_mask() const {
  3573. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3574. if (ss) {
  3575. return ss->pointer_data.pressed_button_mask;
  3576. }
  3577. return BitField<MouseButtonMask>();
  3578. }
  3579. Error WaylandThread::init() {
  3580. #ifdef SOWRAP_ENABLED
  3581. #ifdef DEBUG_ENABLED
  3582. int dylibloader_verbose = 1;
  3583. #else
  3584. int dylibloader_verbose = 0;
  3585. #endif // DEBUG_ENABLED
  3586. if (initialize_wayland_client(dylibloader_verbose) != 0) {
  3587. WARN_PRINT("Can't load the Wayland client library.");
  3588. return ERR_CANT_CREATE;
  3589. }
  3590. if (initialize_wayland_cursor(dylibloader_verbose) != 0) {
  3591. WARN_PRINT("Can't load the Wayland cursor library.");
  3592. return ERR_CANT_CREATE;
  3593. }
  3594. if (initialize_xkbcommon(dylibloader_verbose) != 0) {
  3595. WARN_PRINT("Can't load the XKBcommon library.");
  3596. return ERR_CANT_CREATE;
  3597. }
  3598. #endif // SOWRAP_ENABLED
  3599. KeyMappingXKB::initialize();
  3600. String embedder_socket_path;
  3601. #ifdef TOOLS_ENABLED
  3602. bool embedder_enabled = true;
  3603. if (OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_EMBEDDER") == "1") {
  3604. print_verbose("Disabling Wayland embedder as per GODOT_WAYLAND_DISABLE_EMBEDDER.");
  3605. embedder_enabled = false;
  3606. }
  3607. if (embedder_enabled && Engine::get_singleton()->is_editor_hint() && !Engine::get_singleton()->is_project_manager_hint()) {
  3608. print_verbose("Initializing Wayland embedder.");
  3609. Error embedder_status = embedder.init();
  3610. ERR_FAIL_COND_V_MSG(embedder_status != OK, ERR_CANT_CREATE, "Can't initialize Wayland embedder.");
  3611. embedder_socket_path = embedder.get_socket_path();
  3612. ERR_FAIL_COND_V_MSG(embedder_socket_path.is_empty(), ERR_CANT_CREATE, "Wayland embedder returned invalid path.");
  3613. OS::get_singleton()->set_environment("GODOT_WAYLAND_DISPLAY", embedder_socket_path);
  3614. // Debug
  3615. if (OS::get_singleton()->get_environment("GODOT_DEBUG_EMBEDDER_SINGLE_INSTANCE") == "1") {
  3616. print_line("Pausing as per GODOT_DEBUG_EMBEDDER_SINGLE_INSTANCE.");
  3617. pause();
  3618. }
  3619. }
  3620. #endif // TOOLS_ENABLED
  3621. if (Engine::get_singleton()->is_embedded_in_editor()) {
  3622. embedder_socket_path = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISPLAY");
  3623. #if 0
  3624. // Debug
  3625. OS::get_singleton()->set_environment("WAYLAND_DEBUG", "1");
  3626. int fd = open("/tmp/gdembedded.log", O_CREAT | O_RDWR, 0666);
  3627. dup2(fd, 1);
  3628. dup2(fd, 2);
  3629. #endif
  3630. }
  3631. if (embedder_socket_path.is_empty()) {
  3632. print_verbose("Connecting to the default Wayland display.");
  3633. wl_display = wl_display_connect(nullptr);
  3634. } else {
  3635. print_verbose("Connecting to the Wayland embedder display.");
  3636. wl_display = wl_display_connect(embedder_socket_path.utf8().get_data());
  3637. }
  3638. ERR_FAIL_NULL_V_MSG(wl_display, ERR_CANT_CREATE, "Can't connect to a Wayland display.");
  3639. thread_data.wl_display = wl_display;
  3640. wl_registry = wl_display_get_registry(wl_display);
  3641. ERR_FAIL_NULL_V_MSG(wl_registry, ERR_UNAVAILABLE, "Can't obtain the Wayland registry global.");
  3642. registry.wayland_thread = this;
  3643. wl_registry_add_listener(wl_registry, &wl_registry_listener, &registry);
  3644. // Wait for registry to get notified from the compositor.
  3645. wl_display_roundtrip(wl_display);
  3646. ERR_FAIL_NULL_V_MSG(registry.wl_shm, ERR_UNAVAILABLE, "Can't obtain the Wayland shared memory global.");
  3647. ERR_FAIL_NULL_V_MSG(registry.wl_compositor, ERR_UNAVAILABLE, "Can't obtain the Wayland compositor global.");
  3648. ERR_FAIL_NULL_V_MSG(registry.xdg_wm_base, ERR_UNAVAILABLE, "Can't obtain the Wayland XDG shell global.");
  3649. // Embedded games can't access the decoration and icon protocol.
  3650. if (!Engine::get_singleton()->is_embedded_in_editor()) {
  3651. if (!registry.xdg_decoration_manager) {
  3652. #ifdef LIBDECOR_ENABLED
  3653. WARN_PRINT("Can't obtain the XDG decoration manager. Libdecor will be used for drawing CSDs, if available.");
  3654. #else
  3655. WARN_PRINT("Can't obtain the XDG decoration manager. Decorations won't show up.");
  3656. #endif // LIBDECOR_ENABLED
  3657. }
  3658. if (!registry.xdg_toplevel_icon_manager_name) {
  3659. WARN_PRINT("xdg-toplevel-icon protocol not found! Cannot set window icon.");
  3660. }
  3661. }
  3662. if (!registry.xdg_activation) {
  3663. WARN_PRINT("Can't obtain the XDG activation global. Attention requesting won't work!");
  3664. }
  3665. #ifndef DBUS_ENABLED
  3666. if (!registry.wp_idle_inhibit_manager) {
  3667. WARN_PRINT("Can't obtain the idle inhibition manager. The screen might turn off even after calling screen_set_keep_on()!");
  3668. }
  3669. #endif // DBUS_ENABLED
  3670. if (!registry.wp_fifo_manager_name) {
  3671. WARN_PRINT("FIFO protocol not found! Frame pacing will be degraded.");
  3672. }
  3673. // Wait for seat capabilities.
  3674. wl_display_roundtrip(wl_display);
  3675. #ifdef LIBDECOR_ENABLED
  3676. bool libdecor_found = true;
  3677. bool skip_libdecor = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_LIBDECOR") == "1";
  3678. #ifdef SOWRAP_ENABLED
  3679. if (!skip_libdecor && initialize_libdecor(dylibloader_verbose) != 0) {
  3680. libdecor_found = false;
  3681. }
  3682. #endif // SOWRAP_ENABLED
  3683. if (skip_libdecor) {
  3684. print_verbose("Skipping libdecor check because GODOT_WAYLAND_DISABLE_LIBDECOR is set to 1.");
  3685. } else {
  3686. if (libdecor_found) {
  3687. libdecor_context = libdecor_new(wl_display, (struct libdecor_interface *)&libdecor_interface);
  3688. } else {
  3689. print_verbose("libdecor not found. Client-side decorations disabled.");
  3690. }
  3691. }
  3692. #endif // LIBDECOR_ENABLED
  3693. cursor_theme_name = OS::get_singleton()->get_environment("XCURSOR_THEME");
  3694. unscaled_cursor_size = OS::get_singleton()->get_environment("XCURSOR_SIZE").to_int();
  3695. if (unscaled_cursor_size <= 0) {
  3696. print_verbose("Detected invalid cursor size preference, defaulting to 24.");
  3697. unscaled_cursor_size = 24;
  3698. }
  3699. // NOTE: The scale is useful here as it might've been updated by _update_scale.
  3700. bool cursor_theme_loaded = _load_cursor_theme(unscaled_cursor_size * cursor_scale);
  3701. if (!cursor_theme_loaded) {
  3702. return ERR_CANT_CREATE;
  3703. }
  3704. // Update the cursor.
  3705. cursor_set_shape(DisplayServer::CURSOR_ARROW);
  3706. events_thread.start(_poll_events_thread, &thread_data);
  3707. initialized = true;
  3708. return OK;
  3709. }
  3710. void WaylandThread::cursor_set_visible(bool p_visible) {
  3711. cursor_visible = p_visible;
  3712. for (struct wl_seat *wl_seat : registry.wl_seats) {
  3713. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  3714. ERR_FAIL_NULL(ss);
  3715. seat_state_update_cursor(ss);
  3716. }
  3717. }
  3718. void WaylandThread::cursor_set_shape(DisplayServer::CursorShape p_cursor_shape) {
  3719. cursor_shape = p_cursor_shape;
  3720. for (struct wl_seat *wl_seat : registry.wl_seats) {
  3721. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  3722. ERR_FAIL_NULL(ss);
  3723. seat_state_update_cursor(ss);
  3724. }
  3725. }
  3726. void WaylandThread::cursor_shape_set_custom_image(DisplayServer::CursorShape p_cursor_shape, Ref<Image> p_image, const Point2i &p_hotspot) {
  3727. ERR_FAIL_COND(p_image.is_null());
  3728. Size2i image_size = p_image->get_size();
  3729. // NOTE: The stride is the width of the image in bytes.
  3730. unsigned int image_stride = image_size.width * 4;
  3731. unsigned int data_size = image_stride * image_size.height;
  3732. // We need a shared memory object file descriptor in order to create a
  3733. // wl_buffer through wl_shm.
  3734. int fd = WaylandThread::_allocate_shm_file(data_size);
  3735. ERR_FAIL_COND(fd == -1);
  3736. CustomCursor &cursor = custom_cursors[p_cursor_shape];
  3737. cursor.hotspot = p_hotspot;
  3738. if (cursor.wl_buffer) {
  3739. // Clean up the old Wayland buffer.
  3740. wl_buffer_destroy(cursor.wl_buffer);
  3741. }
  3742. if (cursor.buffer_data) {
  3743. // Clean up the old buffer data.
  3744. munmap(cursor.buffer_data, cursor.buffer_data_size);
  3745. }
  3746. cursor.buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  3747. cursor.buffer_data_size = data_size;
  3748. // Create the Wayland buffer.
  3749. struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);
  3750. // TODO: Make sure that WL_SHM_FORMAT_ARGB8888 format is supported. It
  3751. // technically isn't garaunteed to be supported, but I think that'd be a
  3752. // pretty unlikely thing to stumble upon.
  3753. cursor.wl_buffer = wl_shm_pool_create_buffer(wl_shm_pool, 0, image_size.width, image_size.height, image_stride, WL_SHM_FORMAT_ARGB8888);
  3754. wl_shm_pool_destroy(wl_shm_pool);
  3755. // Fill the cursor buffer with the image data.
  3756. for (unsigned int index = 0; index < (unsigned int)(image_size.width * image_size.height); index++) {
  3757. int row_index = std::floor(index / image_size.width);
  3758. int column_index = (index % int(image_size.width));
  3759. cursor.buffer_data[index] = p_image->get_pixel(column_index, row_index).to_argb32();
  3760. // Wayland buffers, unless specified, require associated alpha, so we'll just
  3761. // associate the alpha in-place.
  3762. uint8_t *pixel_data = (uint8_t *)&cursor.buffer_data[index];
  3763. pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;
  3764. pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;
  3765. pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;
  3766. }
  3767. }
  3768. void WaylandThread::cursor_shape_clear_custom_image(DisplayServer::CursorShape p_cursor_shape) {
  3769. if (custom_cursors.has(p_cursor_shape)) {
  3770. CustomCursor cursor = custom_cursors[p_cursor_shape];
  3771. custom_cursors.erase(p_cursor_shape);
  3772. if (cursor.wl_buffer) {
  3773. wl_buffer_destroy(cursor.wl_buffer);
  3774. }
  3775. if (cursor.buffer_data) {
  3776. munmap(cursor.buffer_data, cursor.buffer_data_size);
  3777. }
  3778. }
  3779. }
  3780. void WaylandThread::window_set_ime_active(const bool p_active, DisplayServer::WindowID p_window_id) {
  3781. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3782. if (ss && ss->wp_text_input && ss->ime_enabled) {
  3783. if (p_active) {
  3784. ss->ime_active = true;
  3785. zwp_text_input_v3_enable(ss->wp_text_input);
  3786. zwp_text_input_v3_set_cursor_rectangle(ss->wp_text_input, ss->ime_rect.position.x, ss->ime_rect.position.y, ss->ime_rect.size.x, ss->ime_rect.size.y);
  3787. } else {
  3788. ss->ime_active = false;
  3789. ss->ime_text = String();
  3790. ss->ime_text_commit = String();
  3791. ss->ime_cursor = Vector2i();
  3792. zwp_text_input_v3_disable(ss->wp_text_input);
  3793. }
  3794. zwp_text_input_v3_commit(ss->wp_text_input);
  3795. }
  3796. }
  3797. void WaylandThread::window_set_ime_position(const Point2i &p_pos, DisplayServer::WindowID p_window_id) {
  3798. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3799. if (ss && ss->wp_text_input && ss->ime_enabled) {
  3800. ss->ime_rect = Rect2i(p_pos, Size2i(1, 10));
  3801. zwp_text_input_v3_set_cursor_rectangle(ss->wp_text_input, ss->ime_rect.position.x, ss->ime_rect.position.y, ss->ime_rect.size.x, ss->ime_rect.size.y);
  3802. zwp_text_input_v3_commit(ss->wp_text_input);
  3803. }
  3804. }
  3805. int WaylandThread::keyboard_get_layout_count() const {
  3806. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3807. if (ss && ss->xkb_keymap) {
  3808. return xkb_keymap_num_layouts(ss->xkb_keymap);
  3809. }
  3810. return 0;
  3811. }
  3812. int WaylandThread::keyboard_get_current_layout_index() const {
  3813. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3814. if (ss) {
  3815. return ss->current_layout_index;
  3816. }
  3817. return 0;
  3818. }
  3819. void WaylandThread::keyboard_set_current_layout_index(int p_index) {
  3820. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3821. if (ss) {
  3822. ss->current_layout_index = p_index;
  3823. }
  3824. }
  3825. String WaylandThread::keyboard_get_layout_name(int p_index) const {
  3826. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3827. if (ss && ss->xkb_keymap) {
  3828. return String::utf8(xkb_keymap_layout_get_name(ss->xkb_keymap, p_index));
  3829. }
  3830. return "";
  3831. }
  3832. Key WaylandThread::keyboard_get_key_from_physical(Key p_key) const {
  3833. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3834. if (ss && ss->xkb_state) {
  3835. Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;
  3836. Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;
  3837. xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);
  3838. Key key = KeyMappingXKB::get_keycode(xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode));
  3839. return (Key)(key | modifiers);
  3840. }
  3841. return p_key;
  3842. }
  3843. Key WaylandThread::keyboard_get_label_from_physical(Key p_key) const {
  3844. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3845. if (ss && ss->xkb_state) {
  3846. Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;
  3847. Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;
  3848. xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);
  3849. xkb_keycode_t xkb_keysym = xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode);
  3850. char32_t chr = xkb_keysym_to_utf32(xkb_keysym_to_upper(xkb_keysym));
  3851. if (chr != 0) {
  3852. String keysym = String::chr(chr);
  3853. Key key = fix_key_label(keysym[0], KeyMappingXKB::get_keycode(xkb_keysym));
  3854. return (Key)(key | modifiers);
  3855. }
  3856. }
  3857. return p_key;
  3858. }
  3859. void WaylandThread::keyboard_echo_keys() {
  3860. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3861. if (ss) {
  3862. seat_state_echo_keys(ss);
  3863. }
  3864. }
  3865. void WaylandThread::selection_set_text(const String &p_text) {
  3866. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3867. if (registry.wl_data_device_manager == nullptr) {
  3868. DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, wl_data_device_manager global not available.");
  3869. return;
  3870. }
  3871. if (ss == nullptr) {
  3872. DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, current seat not set.");
  3873. return;
  3874. }
  3875. if (ss->wl_data_device == nullptr) {
  3876. DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, seat doesn't have wl_data_device.");
  3877. return;
  3878. }
  3879. ss->selection_data = p_text.to_utf8_buffer();
  3880. if (ss->wl_data_source_selection == nullptr) {
  3881. ss->wl_data_source_selection = wl_data_device_manager_create_data_source(registry.wl_data_device_manager);
  3882. wl_data_source_add_listener(ss->wl_data_source_selection, &wl_data_source_listener, ss);
  3883. wl_data_source_offer(ss->wl_data_source_selection, "text/plain;charset=utf-8");
  3884. wl_data_source_offer(ss->wl_data_source_selection, "text/plain");
  3885. // TODO: Implement a good way of getting the latest serial from the user.
  3886. wl_data_device_set_selection(ss->wl_data_device, ss->wl_data_source_selection, MAX(ss->pointer_data.button_serial, ss->last_key_pressed_serial));
  3887. }
  3888. // Wait for the message to get to the server before continuing, otherwise the
  3889. // clipboard update might come with a delay.
  3890. wl_display_roundtrip(wl_display);
  3891. }
  3892. bool WaylandThread::selection_has_mime(const String &p_mime) const {
  3893. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3894. if (ss == nullptr) {
  3895. DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");
  3896. return false;
  3897. }
  3898. OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);
  3899. if (!os) {
  3900. return false;
  3901. }
  3902. return os->mime_types.has(p_mime);
  3903. }
  3904. Vector<uint8_t> WaylandThread::selection_get_mime(const String &p_mime) const {
  3905. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3906. if (ss == nullptr) {
  3907. DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");
  3908. return Vector<uint8_t>();
  3909. }
  3910. if (ss->wl_data_source_selection) {
  3911. // We have a source so the stuff we're pasting is ours. We'll have to pass the
  3912. // data directly or we'd stall waiting for Godot (ourselves) to send us the
  3913. // data :P
  3914. OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);
  3915. ERR_FAIL_NULL_V(os, Vector<uint8_t>());
  3916. if (os->mime_types.has(p_mime)) {
  3917. // All righty, we're offering this type. Let's just return the data as is.
  3918. return ss->selection_data;
  3919. }
  3920. // ... we don't offer that type. Oh well.
  3921. return Vector<uint8_t>();
  3922. }
  3923. return _wl_data_offer_read(wl_display, p_mime.utf8().get_data(), ss->wl_data_offer_selection);
  3924. }
  3925. bool WaylandThread::primary_has_mime(const String &p_mime) const {
  3926. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3927. if (ss == nullptr) {
  3928. DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");
  3929. return false;
  3930. }
  3931. OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);
  3932. if (!os) {
  3933. return false;
  3934. }
  3935. return os->mime_types.has(p_mime);
  3936. }
  3937. Vector<uint8_t> WaylandThread::primary_get_mime(const String &p_mime) const {
  3938. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3939. if (ss == nullptr) {
  3940. DEBUG_LOG_WAYLAND_THREAD("Couldn't get primary, current seat not set.");
  3941. return Vector<uint8_t>();
  3942. }
  3943. if (ss->wp_primary_selection_source) {
  3944. // We have a source so the stuff we're pasting is ours. We'll have to pass the
  3945. // data directly or we'd stall waiting for Godot (ourselves) to send us the
  3946. // data :P
  3947. OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);
  3948. ERR_FAIL_NULL_V(os, Vector<uint8_t>());
  3949. if (os->mime_types.has(p_mime)) {
  3950. // All righty, we're offering this type. Let's just return the data as is.
  3951. return ss->selection_data;
  3952. }
  3953. // ... we don't offer that type. Oh well.
  3954. return Vector<uint8_t>();
  3955. }
  3956. return _wp_primary_selection_offer_read(wl_display, p_mime.utf8().get_data(), ss->wp_primary_selection_offer);
  3957. }
  3958. void WaylandThread::primary_set_text(const String &p_text) {
  3959. SeatState *ss = wl_seat_get_seat_state(wl_seat_current);
  3960. if (registry.wp_primary_selection_device_manager == nullptr) {
  3961. DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, protocol not available.");
  3962. return;
  3963. }
  3964. if (ss == nullptr) {
  3965. DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, current seat not set.");
  3966. return;
  3967. }
  3968. if (ss->wp_primary_selection_device == nullptr) {
  3969. DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary selection, seat doesn't have wp_primary_selection_device.");
  3970. return;
  3971. }
  3972. ss->primary_data = p_text.to_utf8_buffer();
  3973. if (ss->wp_primary_selection_source == nullptr) {
  3974. ss->wp_primary_selection_source = zwp_primary_selection_device_manager_v1_create_source(registry.wp_primary_selection_device_manager);
  3975. zwp_primary_selection_source_v1_add_listener(ss->wp_primary_selection_source, &wp_primary_selection_source_listener, ss);
  3976. zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain;charset=utf-8");
  3977. zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain");
  3978. // TODO: Implement a good way of getting the latest serial from the user.
  3979. zwp_primary_selection_device_v1_set_selection(ss->wp_primary_selection_device, ss->wp_primary_selection_source, MAX(ss->pointer_data.button_serial, ss->last_key_pressed_serial));
  3980. }
  3981. // Wait for the message to get to the server before continuing, otherwise the
  3982. // clipboard update might come with a delay.
  3983. wl_display_roundtrip(wl_display);
  3984. }
  3985. void WaylandThread::commit_surfaces() {
  3986. for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {
  3987. wl_surface_commit(pair.value.wl_surface);
  3988. }
  3989. }
  3990. void WaylandThread::set_frame() {
  3991. frame = true;
  3992. }
  3993. bool WaylandThread::get_reset_frame() {
  3994. bool old_frame = frame;
  3995. frame = false;
  3996. return old_frame;
  3997. }
  3998. // Dispatches events until a frame event is received, a window is reported as
  3999. // suspended or the timeout expires.
  4000. bool WaylandThread::wait_frame_suspend_ms(int p_timeout) {
  4001. // This is a bit of a chicken and egg thing... Looks like the main event loop
  4002. // has to call its rightfully forever-blocking poll right in between
  4003. // `wl_display_prepare_read` and `wl_display_read`. This means, that it will
  4004. // basically be guaranteed to stay stuck in a "prepare read" state, where it
  4005. // will block any other attempt at reading the display fd, such as ours. The
  4006. // solution? Let's make sure the mutex is locked (it should) and unblock the
  4007. // main thread with a roundtrip!
  4008. MutexLock mutex_lock(mutex);
  4009. wl_display_roundtrip(wl_display);
  4010. if (is_suspended()) {
  4011. // All windows are suspended! The compositor is telling us _explicitly_ that
  4012. // we don't need to draw, without letting us guess through the frame event's
  4013. // timing and stuff like that. Our job here is done.
  4014. return false;
  4015. }
  4016. if (frame) {
  4017. // We already have a frame! Probably it got there while the caller locked :D
  4018. frame = false;
  4019. return true;
  4020. }
  4021. struct pollfd poll_fd;
  4022. poll_fd.fd = wl_display_get_fd(wl_display);
  4023. poll_fd.events = POLLIN | POLLHUP;
  4024. int begin_ms = OS::get_singleton()->get_ticks_msec();
  4025. int remaining_ms = p_timeout;
  4026. while (remaining_ms > 0) {
  4027. // Empty the event queue while it's full.
  4028. while (wl_display_prepare_read(wl_display) != 0) {
  4029. if (wl_display_dispatch_pending(wl_display) == -1) {
  4030. // Oh no. We'll check and handle any display error below.
  4031. break;
  4032. }
  4033. if (is_suspended()) {
  4034. return false;
  4035. }
  4036. if (frame) {
  4037. // We had a frame event in the queue :D
  4038. frame = false;
  4039. return true;
  4040. }
  4041. }
  4042. int werror = wl_display_get_error(wl_display);
  4043. if (werror) {
  4044. if (werror == EPROTO) {
  4045. struct wl_interface *wl_interface = nullptr;
  4046. uint32_t id = 0;
  4047. int error_code = wl_display_get_protocol_error(wl_display, (const struct wl_interface **)&wl_interface, &id);
  4048. CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));
  4049. } else {
  4050. CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));
  4051. }
  4052. }
  4053. wl_display_flush(wl_display);
  4054. // Wait for the event file descriptor to have new data.
  4055. poll(&poll_fd, 1, remaining_ms);
  4056. if (poll_fd.revents | POLLIN) {
  4057. // Load the queues with fresh new data.
  4058. wl_display_read_events(wl_display);
  4059. } else {
  4060. // Oh well... Stop signaling that we want to read.
  4061. wl_display_cancel_read(wl_display);
  4062. // We've got no new events :(
  4063. // We won't even bother with checking the frame flag.
  4064. return false;
  4065. }
  4066. // Let's try dispatching now...
  4067. wl_display_dispatch_pending(wl_display);
  4068. if (is_suspended()) {
  4069. return false;
  4070. }
  4071. if (frame) {
  4072. frame = false;
  4073. return true;
  4074. }
  4075. remaining_ms -= OS::get_singleton()->get_ticks_msec() - begin_ms;
  4076. }
  4077. DEBUG_LOG_WAYLAND_THREAD("Frame timeout.");
  4078. return false;
  4079. }
  4080. uint64_t WaylandThread::window_get_last_frame_time(DisplayServer::WindowID p_window_id) const {
  4081. ERR_FAIL_COND_V(!windows.has(p_window_id), false);
  4082. return windows[p_window_id].last_frame_time;
  4083. }
  4084. bool WaylandThread::window_is_suspended(DisplayServer::WindowID p_window_id) const {
  4085. ERR_FAIL_COND_V(!windows.has(p_window_id), false);
  4086. return windows[p_window_id].suspended;
  4087. }
  4088. bool WaylandThread::is_fifo_available() const {
  4089. return registry.wp_fifo_manager_name != 0;
  4090. }
  4091. bool WaylandThread::is_suspended() const {
  4092. for (const KeyValue<DisplayServer::WindowID, WindowState> &E : windows) {
  4093. if (!E.value.suspended) {
  4094. return false;
  4095. }
  4096. }
  4097. return true;
  4098. }
  4099. struct godot_embedding_compositor *WaylandThread::get_embedding_compositor() {
  4100. return registry.godot_embedding_compositor;
  4101. }
  4102. OS::ProcessID WaylandThread::embedded_compositor_get_focused_pid() {
  4103. EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);
  4104. ERR_FAIL_NULL_V(ecomp_state, -1);
  4105. return ecomp_state->focused_pid;
  4106. }
  4107. void WaylandThread::destroy() {
  4108. if (!initialized) {
  4109. return;
  4110. }
  4111. if (wl_display && events_thread.is_started()) {
  4112. thread_data.thread_done.set();
  4113. // By sending a roundtrip message we're unblocking the polling thread so that
  4114. // it can realize that it's done and also handle every event that's left.
  4115. wl_display_roundtrip(wl_display);
  4116. events_thread.wait_to_finish();
  4117. }
  4118. for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {
  4119. WindowState &ws = pair.value;
  4120. if (ws.wp_fractional_scale) {
  4121. wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);
  4122. }
  4123. if (ws.wp_viewport) {
  4124. wp_viewport_destroy(ws.wp_viewport);
  4125. }
  4126. if (ws.frame_callback) {
  4127. wl_callback_destroy(ws.frame_callback);
  4128. }
  4129. #ifdef LIBDECOR_ENABLED
  4130. if (ws.libdecor_frame) {
  4131. libdecor_frame_close(ws.libdecor_frame);
  4132. }
  4133. #endif // LIBDECOR_ENABLED
  4134. if (ws.xdg_toplevel_decoration) {
  4135. zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);
  4136. }
  4137. if (ws.xdg_toplevel) {
  4138. xdg_toplevel_destroy(ws.xdg_toplevel);
  4139. }
  4140. if (ws.xdg_surface) {
  4141. xdg_surface_destroy(ws.xdg_surface);
  4142. }
  4143. if (ws.wl_surface) {
  4144. wl_surface_destroy(ws.wl_surface);
  4145. }
  4146. }
  4147. for (struct wl_seat *wl_seat : registry.wl_seats) {
  4148. SeatState *ss = wl_seat_get_seat_state(wl_seat);
  4149. ERR_FAIL_NULL(ss);
  4150. wl_seat_destroy(wl_seat);
  4151. xkb_context_unref(ss->xkb_context);
  4152. xkb_state_unref(ss->xkb_state);
  4153. xkb_keymap_unref(ss->xkb_keymap);
  4154. xkb_compose_table_unref(ss->xkb_compose_table);
  4155. xkb_compose_state_unref(ss->xkb_compose_state);
  4156. if (ss->wl_keyboard) {
  4157. wl_keyboard_destroy(ss->wl_keyboard);
  4158. }
  4159. if (ss->keymap_buffer) {
  4160. munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);
  4161. }
  4162. if (ss->wl_pointer) {
  4163. wl_pointer_destroy(ss->wl_pointer);
  4164. }
  4165. if (ss->cursor_frame_callback) {
  4166. // We don't need to set a null userdata for safety as the thread is done.
  4167. wl_callback_destroy(ss->cursor_frame_callback);
  4168. }
  4169. if (ss->cursor_surface) {
  4170. wl_surface_destroy(ss->cursor_surface);
  4171. }
  4172. if (ss->wl_data_device) {
  4173. wl_data_device_destroy(ss->wl_data_device);
  4174. }
  4175. if (ss->wp_cursor_shape_device) {
  4176. wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);
  4177. }
  4178. if (ss->wp_relative_pointer) {
  4179. zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);
  4180. }
  4181. if (ss->wp_locked_pointer) {
  4182. zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);
  4183. }
  4184. if (ss->wp_confined_pointer) {
  4185. zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);
  4186. }
  4187. if (ss->wp_tablet_seat) {
  4188. zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);
  4189. }
  4190. for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
  4191. TabletToolState *state = wp_tablet_tool_get_state(tool);
  4192. if (state) {
  4193. memdelete(state);
  4194. }
  4195. zwp_tablet_tool_v2_destroy(tool);
  4196. }
  4197. zwp_text_input_v3_destroy(ss->wp_text_input);
  4198. memdelete(ss);
  4199. }
  4200. if (registry.wp_tablet_manager) {
  4201. zwp_tablet_manager_v2_destroy(registry.wp_tablet_manager);
  4202. }
  4203. if (registry.wp_text_input_manager) {
  4204. zwp_text_input_manager_v3_destroy(registry.wp_text_input_manager);
  4205. }
  4206. for (struct wl_output *wl_output : registry.wl_outputs) {
  4207. ERR_FAIL_NULL(wl_output);
  4208. memdelete(wl_output_get_screen_state(wl_output));
  4209. wl_output_destroy(wl_output);
  4210. }
  4211. if (registry.godot_embedding_compositor) {
  4212. EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);
  4213. ERR_FAIL_NULL(es);
  4214. es->mapped_clients.clear();
  4215. for (struct godot_embedded_client *client : es->clients) {
  4216. godot_embedded_client_destroy(client);
  4217. }
  4218. es->clients.clear();
  4219. memdelete(es);
  4220. godot_embedding_compositor_destroy(registry.godot_embedding_compositor);
  4221. }
  4222. if (wl_cursor_theme) {
  4223. wl_cursor_theme_destroy(wl_cursor_theme);
  4224. }
  4225. if (registry.wp_idle_inhibit_manager) {
  4226. zwp_idle_inhibit_manager_v1_destroy(registry.wp_idle_inhibit_manager);
  4227. }
  4228. if (registry.wp_pointer_constraints) {
  4229. zwp_pointer_constraints_v1_destroy(registry.wp_pointer_constraints);
  4230. }
  4231. if (registry.wp_pointer_gestures) {
  4232. zwp_pointer_gestures_v1_destroy(registry.wp_pointer_gestures);
  4233. }
  4234. if (registry.wp_relative_pointer_manager) {
  4235. zwp_relative_pointer_manager_v1_destroy(registry.wp_relative_pointer_manager);
  4236. }
  4237. if (registry.xdg_activation) {
  4238. xdg_activation_v1_destroy(registry.xdg_activation);
  4239. }
  4240. if (registry.xdg_system_bell) {
  4241. xdg_system_bell_v1_destroy(registry.xdg_system_bell);
  4242. }
  4243. if (registry.xdg_toplevel_icon_manager) {
  4244. xdg_toplevel_icon_manager_v1_destroy(registry.xdg_toplevel_icon_manager);
  4245. if (xdg_icon) {
  4246. xdg_toplevel_icon_v1_destroy(xdg_icon);
  4247. }
  4248. if (icon_buffer) {
  4249. wl_buffer_destroy(icon_buffer);
  4250. }
  4251. }
  4252. if (registry.xdg_decoration_manager) {
  4253. zxdg_decoration_manager_v1_destroy(registry.xdg_decoration_manager);
  4254. }
  4255. if (registry.wp_cursor_shape_manager) {
  4256. wp_cursor_shape_manager_v1_destroy(registry.wp_cursor_shape_manager);
  4257. }
  4258. if (registry.wp_fractional_scale_manager) {
  4259. wp_fractional_scale_manager_v1_destroy(registry.wp_fractional_scale_manager);
  4260. }
  4261. if (registry.wp_viewporter) {
  4262. wp_viewporter_destroy(registry.wp_viewporter);
  4263. }
  4264. if (registry.xdg_wm_base) {
  4265. xdg_wm_base_destroy(registry.xdg_wm_base);
  4266. }
  4267. // NOTE: Deprecated.
  4268. if (registry.xdg_exporter_v1) {
  4269. zxdg_exporter_v1_destroy(registry.xdg_exporter_v1);
  4270. }
  4271. if (registry.xdg_exporter_v2) {
  4272. zxdg_exporter_v2_destroy(registry.xdg_exporter_v2);
  4273. }
  4274. if (registry.wl_shm) {
  4275. wl_shm_destroy(registry.wl_shm);
  4276. }
  4277. if (registry.wl_compositor) {
  4278. wl_compositor_destroy(registry.wl_compositor);
  4279. }
  4280. if (wl_registry) {
  4281. wl_registry_destroy(wl_registry);
  4282. }
  4283. wl_display_roundtrip(wl_display);
  4284. if (wl_display) {
  4285. wl_display_disconnect(wl_display);
  4286. }
  4287. }
  4288. #endif // WAYLAND_ENABLED