wayland_thread.cpp 175 KB

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