WallpaperApplication.cpp 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348
  1. #include "WallpaperApplication.h"
  2. #include "ControlFileOwner.h"
  3. #include "WallpaperEngine/Render/Transition.h"
  4. #include <cstdlib>
  5. #include "Steam/FileSystem/FileSystem.h"
  6. #include "WallpaperEngine/Application/ApplicationState.h"
  7. #include "WallpaperEngine/Assets/AssetLoadException.h"
  8. #include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
  9. #include "WallpaperEngine/Data/Utils/FiniteFloat.h"
  10. #ifdef ENABLE_WAYLAND
  11. #include "WallpaperEngine/Desktop/HostWayland.h"
  12. #endif
  13. #include "WallpaperEngine/FileSystem/Container.h"
  14. #include "WallpaperEngine/Led/LedHub.h"
  15. #include "WallpaperEngine/Logging/Log.h"
  16. #include "WallpaperEngine/Logging/ThreadGuard.h"
  17. #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
  18. #include "WallpaperEngine/Render/Fonts/SystemFonts.h"
  19. #include "WallpaperEngine/Render/RenderContext.h"
  20. #include "WallpaperEngine/Render/Shaders/ShaderCache.h"
  21. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  22. #include "WallpaperEngine/Render/Wallpapers/CSplat.h"
  23. #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
  24. #include "WallpaperEngine/Render/Wallpapers/CWeb.h"
  25. #include "WallpaperEngine/Scripting/LocalStorage.h"
  26. #include "WallpaperEngine/Data/Dumpers/StringPrinter.h"
  27. #include "WallpaperEngine/Data/Parsers/ProjectParser.h"
  28. #include "WallpaperEngine/Data/Utils/AudioSensitivity.h"
  29. #include "WallpaperEngine/Data/Model/Property.h"
  30. #include "WallpaperEngine/Data/Model/Wallpaper.h"
  31. #include "WallpaperEngine/Debugging/CallStack.h"
  32. #include "WallpaperEngine/FileSystem/Adapters/MediaCover.h"
  33. #include "WallpaperEngine/Media/DBusMediaSource.h"
  34. #include "WallpaperEngine/WebBrowser/CEF/BrowserClient.h"
  35. #include "WallpaperEngine/WebBrowser/CEF/PageBridge.h"
  36. #include "WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.h"
  37. #include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
  38. #include "include/cef_browser.h"
  39. #if DEMOMODE
  40. #include "recording.h"
  41. #endif
  42. #include <algorithm>
  43. #include <cctype>
  44. #include <chrono>
  45. #include <climits>
  46. #include <csignal>
  47. #include <ctime>
  48. #include <fstream>
  49. #include <numeric>
  50. #include <ranges>
  51. #include <string_view>
  52. #include <sys/stat.h>
  53. #include <unistd.h>
  54. #define STB_IMAGE_WRITE_IMPLEMENTATION
  55. #include <stb_image_write.h>
  56. #include <thread>
  57. #include <utility>
  58. using WallpaperEngine::Data::Utils::parseFiniteFloat;
  59. #define FULLSCREEN_CHECK_WAIT_TIME 250000
  60. float g_Time;
  61. float g_TimeLast;
  62. float g_RealTime;
  63. float g_Daytime;
  64. using namespace WallpaperEngine::Assets;
  65. using namespace WallpaperEngine::Application;
  66. using namespace WallpaperEngine::Data::Model;
  67. using namespace WallpaperEngine::FileSystem;
  68. void CustomGLDebugCallback (
  69. GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam
  70. ) {
  71. if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
  72. return;
  73. }
  74. // libmpv rebuffers a GL_STATIC_DRAW buffer every video frame, that hint would drown out everything else
  75. if (type == GL_DEBUG_TYPE_PERFORMANCE) {
  76. return;
  77. }
  78. sLog.error ("OpenGL error: ", message, ", type: ", type, ", id: ", id, ", severity: ", severity);
  79. std::vector<WallpaperEngine::Debugging::CallStack::CallInfo> callInfo;
  80. WallpaperEngine::Debugging::CallStack::GetCalls (callInfo);
  81. for (std::vector<WallpaperEngine::Debugging::CallStack::CallInfo>::size_type i = 0; i < callInfo.size (); ++i) {
  82. fprintf (
  83. stderr, "[%3lu] %15lu: %s in %s\n", callInfo.size () - i, callInfo[i].offset, callInfo[i].function.c_str (),
  84. callInfo[i].module.c_str ()
  85. );
  86. }
  87. }
  88. WallpaperApplication::WallpaperApplication (ApplicationContext& context) : m_context (context) {
  89. Render::Shaders::ShaderCache::get ().setEnabled (!this->m_context.settings.general.noShaderCache);
  90. this->initializeSubsystems ();
  91. this->loadBackgrounds ();
  92. this->setupProperties ();
  93. this->setupAudioSensitivity ();
  94. this->setupSoundVolume ();
  95. this->listObjects ();
  96. this->listEffects ();
  97. this->listFonts ();
  98. this->listAudioObjects ();
  99. this->setupBrowser ();
  100. this->initializePlaylists ();
  101. }
  102. void WallpaperApplication::initializeSubsystems () {
  103. m_mediaSource = std::make_unique<WallpaperEngine::Media::DBusMediaSource> (std::chrono::milliseconds (2000));
  104. }
  105. AssetLocatorUniquePtr
  106. WallpaperApplication::setupAssetLocator (const std::string& bg, const std::filesystem::path& overlay) const {
  107. auto container = std::make_unique<Container> ();
  108. const std::filesystem::path path = bg;
  109. container->registerAdapterFactory (std::make_unique<MediaCoverFactory> (*this->m_mediaSource));
  110. container->mount ("$mediaThumbnail", "$mediaThumbnail");
  111. container->mount (path, "/");
  112. try {
  113. container->mount (path / "scene.pkg", "/");
  114. } catch (std::runtime_error&) { }
  115. try {
  116. container->mount (path / "gifscene.pkg", "/");
  117. } catch (std::runtime_error&) { }
  118. if (!overlay.empty ()) {
  119. container->mount (overlay, "/");
  120. }
  121. try {
  122. container->mount (this->m_context.settings.general.assets, "/");
  123. } catch (std::runtime_error&) {
  124. sLog.exception ("Cannot find a valid assets folder, resolved to ", this->m_context.settings.general.assets);
  125. }
  126. try {
  127. container->mount (std::filesystem::current_path (), "/");
  128. } catch (std::runtime_error&) { }
  129. auto& vfs = container->getVFS ();
  130. vfs.add (
  131. "shaders/commands/copy.frag",
  132. "uniform sampler2D g_Texture0;\n"
  133. "in vec2 v_TexCoord;\n"
  134. "void main () {\n"
  135. "out_FragColor = texture (g_Texture0, v_TexCoord);\n"
  136. "}"
  137. );
  138. vfs.add (
  139. "shaders/commands/copy.vert",
  140. "in vec3 a_Position;\n"
  141. "in vec2 a_TexCoord;\n"
  142. "out vec2 v_TexCoord;\n"
  143. "void main () {\n"
  144. "gl_Position = vec4 (a_Position, 1.0);\n"
  145. "v_TexCoord = a_TexCoord;\n"
  146. "}"
  147. );
  148. return std::make_unique<AssetLocator> (std::move (container));
  149. }
  150. void WallpaperApplication::loadBackgrounds () {
  151. if (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  152. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW) {
  153. auto path = this->m_context.settings.general.defaultBackground;
  154. if (this->m_context.settings.general.defaultPlaylist.has_value ()
  155. && !this->m_context.settings.general.defaultPlaylist->items.empty ()) {
  156. path = this->m_context.settings.general.defaultPlaylist->items.front ();
  157. }
  158. this->m_backgrounds["default"] = this->loadBackground (path);
  159. return;
  160. }
  161. for (const auto& [screen, path] : this->m_context.settings.general.screenBackgrounds) {
  162. if (screen.rfind ("span:", 0) == 0) {
  163. continue;
  164. }
  165. if (path.empty ()) {
  166. this->m_backgrounds[screen] = this->loadBackground (this->m_context.settings.general.defaultBackground);
  167. } else {
  168. this->m_backgrounds[screen] = this->loadBackground (path);
  169. }
  170. }
  171. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  172. if (spanGroup.screens.empty ()) {
  173. continue;
  174. }
  175. std::filesystem::path bgPath = spanGroup.background;
  176. if (bgPath.empty ()) {
  177. bgPath = this->m_context.settings.general.defaultBackground;
  178. }
  179. const std::string groupKey = "span:" + spanGroup.screens.front ();
  180. this->m_backgrounds[groupKey] = this->loadBackground (bgPath);
  181. }
  182. }
  183. WallpaperApplication::ProjectSource WallpaperApplication::openProjectSource (const std::string& path) const {
  184. auto container = this->setupAssetLocator (path);
  185. auto json = WallpaperEngine::Data::JSON::JSON::parseAsset (container->readString ("project.json"));
  186. if (json.contains ("file") || !json.contains ("dependency")) {
  187. return { std::move (container), std::move (json), std::nullopt, path };
  188. }
  189. const auto dependency = json.at ("dependency");
  190. const auto dependencyId = dependency.is_string () ? dependency.get<std::string> () : dependency.dump ();
  191. if (dependencyId.empty () || dependencyId == "." || dependencyId == ".."
  192. || dependencyId.find ('/') != std::string::npos) {
  193. sLog.exception ("Preset ", path, " has an invalid dependency '", dependencyId, "'");
  194. }
  195. std::filesystem::path presetDir = path;
  196. if (!presetDir.has_filename ()) {
  197. presetDir = presetDir.parent_path ();
  198. }
  199. const auto baseDir = presetDir.parent_path () / dependencyId;
  200. if (!std::filesystem::exists (baseDir / "project.json")) {
  201. sLog.exception ("Preset ", path, " requires wallpaper ", dependencyId, " which is not installed");
  202. }
  203. auto baseContainer = this->setupAssetLocator (baseDir.string (), presetDir);
  204. auto baseJson = WallpaperEngine::Data::JSON::JSON::parseAsset (baseContainer->readString ("project.json"));
  205. return { std::move (baseContainer), std::move (baseJson), json.optional ("preset"), baseDir };
  206. }
  207. namespace {
  208. std::optional<float> presetNumber (const WallpaperEngine::Data::JSON::JSON& preset, const char* key) {
  209. const auto it = preset.find (key);
  210. if (it == preset.end ()) {
  211. return std::nullopt;
  212. }
  213. if (it->is_number ()) {
  214. return it->get<float> ();
  215. }
  216. if (it->is_string ()) {
  217. try {
  218. return parseFiniteFloat (it->get<std::string> ());
  219. } catch (const std::exception&) { }
  220. }
  221. return std::nullopt;
  222. }
  223. std::optional<bool> presetBool (const WallpaperEngine::Data::JSON::JSON& preset, const char* key) {
  224. const auto it = preset.find (key);
  225. if (it == preset.end ()) {
  226. return std::nullopt;
  227. }
  228. if (it->is_boolean ()) {
  229. return it->get<bool> ();
  230. }
  231. if (it->is_number ()) {
  232. return it->get<float> () != 0.0f;
  233. }
  234. if (it->is_string ()) {
  235. return it->get<std::string> () == "true" || it->get<std::string> () == "1";
  236. }
  237. return std::nullopt;
  238. }
  239. /** Wallpaper Engine's own settings a preset can carry, see wallpaper64.exe sub_140181F30 */
  240. ImageAdjustments parseImageAdjustments (const WallpaperEngine::Data::JSON::JSON& preset) {
  241. ImageAdjustments result {
  242. .colorEnabled = presetBool (preset, "wec_e"),
  243. .brightness = presetNumber (preset, "wec_brs"),
  244. .contrast = presetNumber (preset, "wec_con"),
  245. .saturation = presetNumber (preset, "wec_sa"),
  246. .hue = presetNumber (preset, "wec_hue"),
  247. .filter = std::nullopt,
  248. .filterStrength = presetNumber (preset, "wcc_amt"),
  249. .flipHorizontal = presetBool (preset, "alignmentfliph"),
  250. };
  251. if (const auto it = preset.find ("wcc_v"); it != preset.end () && it->is_string ()) {
  252. result.filter = it->get<std::string> ();
  253. }
  254. return result;
  255. }
  256. }
  257. void WallpaperApplication::applyPreset (
  258. Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir
  259. ) {
  260. project.imageAdjustments = parseImageAdjustments (preset);
  261. for (const auto& entry : preset.items ()) {
  262. const auto property = project.properties.find (entry.key ());
  263. // wec_* and friends are Wallpaper Engine's own settings (read above), not wallpaper properties
  264. if (property == project.properties.end () || entry.value ().is_null ()) {
  265. continue;
  266. }
  267. const auto& value = entry.value ();
  268. std::string text;
  269. if (value.is_string ()) {
  270. text = value.get<std::string> ();
  271. } else if (value.is_boolean ()) {
  272. text = value.get<bool> () ? "true" : "false";
  273. } else {
  274. text = value.dump ();
  275. }
  276. // file and directory properties hold paths relative to the preset folder, pages expect an absolute one
  277. if (const auto* file = dynamic_cast<const PropertyFile*> (property->second.get ());
  278. file != nullptr && !text.empty ()) {
  279. std::error_code pathError;
  280. const auto folder = std::filesystem::weakly_canonical (presetDir, pathError);
  281. const auto candidate = std::filesystem::weakly_canonical (folder / text, pathError);
  282. const auto inside = candidate.lexically_relative (folder);
  283. // a preset is someone else's content, its files are in its own folder: "/" or "../.." must not open the
  284. // user's disk to a web page
  285. if (pathError || inside.empty () || *inside.begin () == "..") {
  286. sLog.error ("Preset value for ", entry.key (), " is outside the preset's folder, ignored: ", text);
  287. continue;
  288. }
  289. if (file->isDirectory () ? std::filesystem::is_directory (candidate)
  290. : std::filesystem::is_regular_file (candidate)) {
  291. text = candidate.string ();
  292. }
  293. }
  294. // a preset is someone else's content, only the user assigns what a shortcut opens
  295. if (property->second->is<PropertyUserShortcut> ()) {
  296. continue;
  297. }
  298. if (auto* combo = dynamic_cast<PropertyCombo*> (property->second.get ()); combo != nullptr) {
  299. combo->allowValue (text);
  300. }
  301. try {
  302. property->second->update (text, DynamicValue::UpdateSource::User);
  303. } catch (const std::exception& e) {
  304. sLog.error ("Cannot apply preset value for ", entry.key (), ": ", e.what ());
  305. }
  306. }
  307. }
  308. ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) try {
  309. auto [container, json, preset, directory] = this->openProjectSource (bg);
  310. if (this->m_context.settings.screenshot.take) {
  311. this->m_nextFrameScreenshot = this->m_context.settings.screenshot.delay;
  312. if (this->m_videoDriver != nullptr) {
  313. this->m_nextFrameScreenshot += this->m_videoDriver->getFrameCounter ();
  314. }
  315. this->m_screenShotTaken = false;
  316. }
  317. const std::string sceneFileName = json.contains ("file") && json.at ("file").is_string ()
  318. ? json.at ("file").get<std::string> ()
  319. : std::string ();
  320. auto project = WallpaperEngine::Data::Parsers::ProjectParser::parse (json, std::move (container));
  321. std::error_code error;
  322. auto folder = std::filesystem::weakly_canonical (std::filesystem::absolute (directory), error);
  323. if (error || folder.empty ()) {
  324. folder = std::filesystem::absolute (directory).lexically_normal ();
  325. }
  326. if (!folder.has_filename ()) {
  327. folder = folder.parent_path ();
  328. }
  329. // WE opens scene.pkg when there is one
  330. project->sceneFile = std::filesystem::exists (folder / "scene.pkg") ? folder / "scene.pkg" : folder / sceneFileName;
  331. if (preset.has_value ()) {
  332. std::filesystem::path presetDir = bg;
  333. if (!presetDir.has_filename ()) {
  334. presetDir = presetDir.parent_path ();
  335. }
  336. applyPreset (*project, *preset, presetDir);
  337. }
  338. return project;
  339. } catch (const std::exception& e) {
  340. throw std::runtime_error ("Cannot load wallpaper '" + bg + "': " + e.what ());
  341. }
  342. std::vector<std::size_t>
  343. WallpaperApplication::buildPlaylistOrder (const ApplicationContext::PlaylistDefinition& definition) {
  344. std::vector<std::size_t> order (definition.items.size ());
  345. std::iota (order.begin (), order.end (), 0);
  346. if (definition.settings.order == "random") {
  347. std::shuffle (
  348. order.begin () + (definition.settings.hasIntro () && order.size () > 1 ? 1 : 0), order.end (),
  349. this->m_playlistRng
  350. );
  351. }
  352. return order;
  353. }
  354. void WallpaperApplication::initializePlaylists () {
  355. const bool hasDefaultPlaylist = this->m_context.settings.general.defaultPlaylist.has_value ();
  356. const bool hasScreenPlaylists = !this->m_context.settings.general.screenPlaylists.empty ();
  357. if (!hasDefaultPlaylist && !hasScreenPlaylists) {
  358. return;
  359. }
  360. const auto now = std::chrono::steady_clock::now ();
  361. auto registerPlaylist = [this, now] (
  362. const std::string& key, const ApplicationContext::PlaylistDefinition& playlist,
  363. std::optional<std::filesystem::path> currentPath
  364. ) {
  365. if (playlist.items.empty ()) {
  366. return;
  367. }
  368. ActivePlaylist state;
  369. state.definition = playlist;
  370. state.order = this->buildPlaylistOrder (playlist);
  371. state.introPlaying = playlist.settings.hasIntro () && playlist.items.size () > 1;
  372. if (state.order.empty ()) {
  373. return;
  374. }
  375. if (currentPath.has_value ()) {
  376. state.orderIndex = 0;
  377. for (std::size_t i = 0; i < state.order.size (); i++) {
  378. if (playlist.items[state.order[i]] == currentPath.value ()) {
  379. state.orderIndex = i;
  380. break;
  381. }
  382. }
  383. }
  384. const uint32_t delayMinutes = std::max<uint32_t> (1, state.definition.settings.delayMinutes);
  385. state.nextSwitch = now + std::chrono::minutes (delayMinutes);
  386. state.lastUpdate = now;
  387. this->m_activePlaylists.insert_or_assign (key, std::move (state));
  388. };
  389. if (hasDefaultPlaylist
  390. && (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  391. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW)) {
  392. const auto& playlist = this->m_context.settings.general.defaultPlaylist.value ();
  393. const auto currentPath = playlist.items.empty ()
  394. ? std::optional<std::filesystem::path> { this->m_context.settings.general.defaultBackground }
  395. : std::optional<std::filesystem::path> { playlist.items.front () };
  396. registerPlaylist ("default", playlist, currentPath);
  397. }
  398. for (const auto& [screen, playlist] : this->m_context.settings.general.screenPlaylists) {
  399. const auto current = this->m_context.settings.general.screenBackgrounds.find (screen);
  400. const auto currentPath = current != this->m_context.settings.general.screenBackgrounds.end ()
  401. ? std::optional<std::filesystem::path> { current->second }
  402. : std::nullopt;
  403. registerPlaylist (screen, playlist, currentPath);
  404. }
  405. }
  406. bool WallpaperApplication::makeAnyViewportCurrent () const {
  407. if (!this->m_renderContext) {
  408. return false;
  409. }
  410. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  411. if (viewports.empty ()) {
  412. return false;
  413. }
  414. viewports.begin ()->second->makeCurrent ();
  415. return true;
  416. }
  417. bool WallpaperApplication::preflightWallpaper (const std::string& path) {
  418. try {
  419. const auto source = this->openProjectSource (path);
  420. const auto& json = source.json;
  421. if (!json.contains ("type") || !json.contains ("file")) {
  422. sLog.error ("Preflight failed for ", path, ": missing required fields");
  423. return false;
  424. }
  425. return true;
  426. } catch (const std::exception& e) {
  427. sLog.error ("Preflight failed for ", path, ": ", e.what ());
  428. return false;
  429. }
  430. }
  431. bool WallpaperApplication::selectNextCandidate (ActivePlaylist& playlist, std::size_t& outOrderIndex) {
  432. if (playlist.order.empty ()) {
  433. return false;
  434. }
  435. std::size_t attempts = 0;
  436. std::size_t candidateOrderIndex = outOrderIndex;
  437. while (attempts < playlist.order.size ()) {
  438. const auto candidateIndex = playlist.order[candidateOrderIndex];
  439. const bool skippedIntro = candidateIndex == 0 && playlist.definition.settings.hasIntro ()
  440. && playlist.order.size () > 1 && !playlist.introPlaying;
  441. if (!skippedIntro && !playlist.failedIndices.contains (candidateIndex)) {
  442. outOrderIndex = candidateOrderIndex;
  443. return true;
  444. }
  445. attempts++;
  446. candidateOrderIndex = (candidateOrderIndex + 1) % playlist.order.size ();
  447. }
  448. return false;
  449. }
  450. void WallpaperApplication::advancePlaylist (
  451. const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
  452. ) {
  453. if (playlist.order.empty ()) {
  454. return;
  455. }
  456. playlist.orderIndex = (playlist.orderIndex + 1) % playlist.order.size ();
  457. playlist.introPlaying = false;
  458. const bool intro = playlist.definition.settings.hasIntro () && playlist.order.size () > 1;
  459. if (playlist.orderIndex == 0) {
  460. playlist.failedIndices.clear ();
  461. if (playlist.definition.settings.order == "random") {
  462. std::shuffle (playlist.order.begin () + (intro ? 1 : 0), playlist.order.end (), this->m_playlistRng);
  463. }
  464. if (intro) {
  465. playlist.orderIndex = 1;
  466. }
  467. }
  468. std::size_t candidateOrderIndex = playlist.orderIndex;
  469. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  470. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  471. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  472. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  473. playlist.failedIndices.clear ();
  474. return;
  475. }
  476. const auto candidateIndex = playlist.order[candidateOrderIndex];
  477. const auto& candidatePath = playlist.definition.items[candidateIndex];
  478. if (!this->preflightWallpaper (candidatePath.string ())) {
  479. playlist.failedIndices.insert (candidateIndex);
  480. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  481. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  482. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  483. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  484. playlist.failedIndices.clear ();
  485. return;
  486. }
  487. }
  488. playlist.orderIndex = candidateOrderIndex;
  489. const auto& nextPath = playlist.definition.items[playlist.order[playlist.orderIndex]];
  490. bool loaded = false;
  491. try {
  492. if (!this->makeAnyViewportCurrent ()) {
  493. sLog.error ("Cannot switch playlist on ", screen, ": no active viewport");
  494. throw std::runtime_error ("No viewport available");
  495. }
  496. auto project = this->loadBackground (nextPath.string ());
  497. this->setupPropertiesForProject (*project);
  498. this->ensureAudioCapture (*project);
  499. // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
  500. auto outgoing = std::move (this->m_backgrounds[screen]);
  501. this->m_backgrounds[screen] = std::move (project);
  502. try {
  503. if (this->m_renderContext) {
  504. this->installWallpaper (screen, *this->m_backgrounds[screen], nextPath, true, true);
  505. this->applyAudioPolicy ();
  506. }
  507. } catch (...) {
  508. project = std::move (this->m_backgrounds[screen]);
  509. this->m_backgrounds[screen] = std::move (outgoing);
  510. if (this->m_renderContext) {
  511. this->m_renderContext->pruneTextures ();
  512. }
  513. throw;
  514. }
  515. this->m_context.settings.general.screenBackgrounds[screen] = nextPath;
  516. loaded = true;
  517. } catch (const std::exception& e) {
  518. sLog.error ("Failed to advance playlist on ", screen, ": ", e.what ());
  519. } catch (...) {
  520. sLog.error ("Failed to advance playlist on ", screen, ": unknown error");
  521. }
  522. if (!loaded) {
  523. playlist.failedIndices.insert (playlist.order[playlist.orderIndex]);
  524. sLog.error ("Failed to load wallpaper for ", screen, ", skipping it until the playlist comes round again");
  525. }
  526. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  527. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  528. }
  529. void WallpaperApplication::updatePlaylists () {
  530. if (this->m_activePlaylists.empty ()) {
  531. return;
  532. }
  533. const auto now = std::chrono::steady_clock::now ();
  534. for (auto& [screen, playlist] : this->m_activePlaylists) {
  535. playlist.lastUpdate = now;
  536. if (playlist.definition.settings.mode != "timer") {
  537. continue;
  538. }
  539. // WE only writes a playlist of more than one item into its config (the UI's `1 < items.length`), a single
  540. // wallpaper is a plain selection that loops, so one item keeps looping here too
  541. if (playlist.definition.items.size () <= 1) {
  542. continue;
  543. }
  544. // videosequence (sub_140076BE0, sub_140067720): a video of a timer playlist plays once and the playlist moves
  545. // on when it ends, the timer never takes it away. The playintro item is treated the same while it is the first
  546. // one shown
  547. if ((playlist.definition.settings.videoSequence || playlist.introPlaying) && this->m_renderContext) {
  548. const auto& wallpapers = this->m_renderContext->getWallpapers ();
  549. const auto current = wallpapers.find (screen);
  550. if (current != wallpapers.end () && current->second->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  551. const auto video = current->second->as<WallpaperEngine::Render::Wallpapers::CVideo> ();
  552. video->setLoop (false);
  553. if (video->hasEnded ()) {
  554. this->advancePlaylist (screen, playlist, now);
  555. }
  556. continue;
  557. }
  558. }
  559. if (now < playlist.nextSwitch) {
  560. continue;
  561. }
  562. this->advancePlaylist (screen, playlist, now);
  563. }
  564. }
  565. namespace {
  566. struct HotswapRequest {
  567. std::optional<std::string> path;
  568. std::optional<std::string> screen;
  569. // a layers=1 line makes disabledObjects/enabledObjects a full replacement
  570. bool layersProvided = false;
  571. std::vector<std::string> disabledObjects;
  572. std::vector<std::string> enabledObjects;
  573. /** effects=1 seen, the effect lists replace the current ones */
  574. bool effectsProvided = false;
  575. std::vector<std::string> disabledEffects;
  576. std::vector<std::string> enabledEffects;
  577. std::optional<std::string> disableAnimations;
  578. bool propertiesProvided = false;
  579. std::map<std::string, std::string> properties;
  580. std::optional<int> volume;
  581. std::optional<int> fps;
  582. std::optional<std::string> batteryFps;
  583. std::optional<std::string> idlePause;
  584. std::optional<std::string> xray;
  585. std::optional<std::string> scaling;
  586. std::optional<std::string> zoom;
  587. std::optional<std::string> offset;
  588. std::optional<std::string> alignment;
  589. std::optional<std::string> disableParallax;
  590. std::optional<std::string> expandCanvas;
  591. std::optional<std::string> repairAssets;
  592. std::optional<std::string> cornerColor;
  593. ImageAdjustments imageAdjustments;
  594. bool imageAdjustmentsProvided = false;
  595. std::optional<std::string> speed;
  596. std::optional<std::string> videoStart;
  597. std::optional<std::string> videoEnd;
  598. std::optional<std::string> videoSegments;
  599. std::optional<std::string> hwdec;
  600. std::optional<std::string> hrtf;
  601. std::optional<std::string> transition;
  602. std::optional<std::string> transitionDuration;
  603. std::optional<std::string> videoSeek;
  604. std::optional<std::string> audioScreen;
  605. std::optional<std::string> ambientVolume;
  606. bool audioSensitivityProvided = false;
  607. std::map<std::string, std::string> audioSensitivity;
  608. bool soundVolumeProvided = false;
  609. std::map<std::string, std::string> soundVolume;
  610. };
  611. std::string trimHotswapToken (const std::string& value) {
  612. std::size_t begin = 0;
  613. std::size_t end = value.size ();
  614. while (begin < end && std::isspace (static_cast<unsigned char> (value[begin]))) {
  615. begin++;
  616. }
  617. while (end > begin && std::isspace (static_cast<unsigned char> (value[end - 1]))) {
  618. end--;
  619. }
  620. return value.substr (begin, end - begin);
  621. }
  622. HotswapRequest parseHotswapRequest (std::istream& file) {
  623. HotswapRequest request;
  624. std::string rawLine;
  625. while (std::getline (file, rawLine)) {
  626. const std::string line = trimHotswapToken (rawLine);
  627. if (line.empty ()) {
  628. continue;
  629. }
  630. const auto separator = line.find ('=');
  631. if (separator == std::string::npos) {
  632. if (!request.path.has_value ()) {
  633. request.path = line;
  634. }
  635. continue;
  636. }
  637. const std::string key = trimHotswapToken (line.substr (0, separator));
  638. const std::string value = trimHotswapToken (line.substr (separator + 1));
  639. if (key == "path") {
  640. request.path = value;
  641. } else if (key == "screen") {
  642. request.screen = value.empty () ? std::nullopt : std::optional<std::string> (value);
  643. } else if (key == "layers") {
  644. request.layersProvided = true;
  645. } else if (key == "disable-object") {
  646. request.layersProvided = true;
  647. request.disabledObjects.push_back (value);
  648. } else if (key == "enable-object") {
  649. request.layersProvided = true;
  650. request.enabledObjects.push_back (value);
  651. } else if (key == "effects") {
  652. request.effectsProvided = true;
  653. } else if (key == "disable-effect") {
  654. request.effectsProvided = true;
  655. request.disabledEffects.push_back (value);
  656. } else if (key == "enable-effect") {
  657. request.effectsProvided = true;
  658. request.enabledEffects.push_back (value);
  659. } else if (key == "disable-animations") {
  660. request.disableAnimations = value;
  661. } else if (key == "volume") {
  662. try {
  663. request.volume = std::stoi (value);
  664. } catch (const std::exception&) {
  665. sLog.error ("Hotswap: ignoring invalid volume value: ", value);
  666. }
  667. } else if (key == "fps") {
  668. try {
  669. request.fps = std::stoi (value);
  670. } catch (const std::exception&) {
  671. sLog.error ("Hotswap: ignoring invalid fps value: ", value);
  672. }
  673. } else if (key == "fps-battery") {
  674. request.batteryFps = value;
  675. } else if (key == "idle-pause") {
  676. request.idlePause = value;
  677. } else if (key == "xray") {
  678. request.xray = value;
  679. } else if (key == "scaling") {
  680. request.scaling = value;
  681. } else if (key == "zoom") {
  682. request.zoom = value;
  683. } else if (key == "offset") {
  684. request.offset = value;
  685. } else if (key == "alignment") {
  686. request.alignment = value;
  687. } else if (key == "disable-parallax") {
  688. request.disableParallax = value;
  689. } else if (key == "expand-canvas") {
  690. request.expandCanvas = value;
  691. } else if (key == "repair-assets") {
  692. request.repairAssets = value;
  693. } else if (key == "corner-color") {
  694. request.cornerColor = value;
  695. } else if (key == "image-filter") {
  696. request.imageAdjustments.filter = value == "none" ? "" : value;
  697. request.imageAdjustmentsProvided = true;
  698. } else if (key == "color-options" || key == "flip") {
  699. const bool enable = value == "on" || value == "1" || value == "true";
  700. if (!enable && value != "off" && value != "0" && value != "false") {
  701. sLog.error ("Hotswap: ignoring invalid ", key, " value: ", value);
  702. } else {
  703. (key == "flip" ? request.imageAdjustments.flipHorizontal : request.imageAdjustments.colorEnabled)
  704. = enable;
  705. request.imageAdjustmentsProvided = true;
  706. }
  707. } else if (
  708. key == "image-filter-strength" || key == "brightness" || key == "contrast" || key == "saturation"
  709. || key == "hue"
  710. ) {
  711. float amount;
  712. try {
  713. amount = std::clamp (parseFiniteFloat (value), 0.0f, 100.0f);
  714. } catch (const std::exception&) {
  715. sLog.error ("Hotswap: ignoring invalid ", key, " value: ", value);
  716. continue;
  717. }
  718. auto& adjustments = request.imageAdjustments;
  719. if (key == "image-filter-strength") {
  720. adjustments.filterStrength = amount;
  721. } else if (key == "brightness") {
  722. adjustments.brightness = amount;
  723. } else if (key == "contrast") {
  724. adjustments.contrast = amount;
  725. } else if (key == "saturation") {
  726. adjustments.saturation = amount;
  727. } else {
  728. adjustments.hue = amount;
  729. }
  730. request.imageAdjustmentsProvided = true;
  731. } else if (key == "speed") {
  732. request.speed = value;
  733. } else if (key == "video-start") {
  734. request.videoStart = value;
  735. } else if (key == "video-end") {
  736. request.videoEnd = value;
  737. } else if (key == "video-segments") {
  738. request.videoSegments = value;
  739. } else if (key == "video-seek") {
  740. request.videoSeek = value;
  741. } else if (key == "hwdec") {
  742. request.hwdec = value;
  743. } else if (key == "hrtf") {
  744. request.hrtf = value;
  745. } else if (key == "transition") {
  746. request.transition = value;
  747. } else if (key == "transition-duration") {
  748. request.transitionDuration = value;
  749. } else if (key == "audio-screen") {
  750. request.audioScreen = value;
  751. } else if (key == "ambient-volume") {
  752. request.ambientVolume = value;
  753. } else if (key == "property") {
  754. const auto propSeparator = value.find ('=');
  755. if (propSeparator == std::string::npos) {
  756. sLog.error ("Hotswap: ignoring malformed property line: ", value);
  757. } else {
  758. request.propertiesProvided = true;
  759. request.properties[value.substr (0, propSeparator)] = value.substr (propSeparator + 1);
  760. }
  761. } else if (key == "audio-sensitivity") {
  762. const auto sensSeparator = value.find ('=');
  763. if (sensSeparator == std::string::npos) {
  764. sLog.error ("Hotswap: ignoring malformed audio-sensitivity line: ", value);
  765. } else {
  766. request.audioSensitivityProvided = true;
  767. request.audioSensitivity[value.substr (0, sensSeparator)] = value.substr (sensSeparator + 1);
  768. }
  769. } else if (key == "sound-volume") {
  770. const auto volSeparator = value.find ('=');
  771. if (volSeparator == std::string::npos) {
  772. sLog.error ("Hotswap: ignoring malformed sound-volume line: ", value);
  773. } else {
  774. request.soundVolumeProvided = true;
  775. request.soundVolume[value.substr (0, volSeparator)] = value.substr (volSeparator + 1);
  776. }
  777. } else {
  778. sLog.error ("Hotswap: ignoring unknown control file key: ", key);
  779. }
  780. }
  781. return request;
  782. }
  783. }
  784. void WallpaperApplication::checkHotswapRequest () {
  785. if (!this->m_hotswapRequested.exchange (false)) {
  786. return;
  787. }
  788. const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
  789. const bool sharedTmp
  790. = !this->m_context.settings.general.controlFile.has_value () && (runtimeDir == nullptr || *runtimeDir == '\0');
  791. const auto controlFile = this->m_context.settings.general.controlFile.value_or (
  792. sharedTmp ? std::filesystem::path ("/tmp/lwe-control-" + std::to_string (geteuid ()))
  793. : std::filesystem::path (runtimeDir) / "lwe-control"
  794. );
  795. // /tmp is shared, a file another user left there is not a request
  796. if (sharedTmp && belongsToAnotherUser (controlFile, geteuid ())) {
  797. sLog.error ("Hotswap requested but the control file belongs to another user: ", controlFile.string ());
  798. return;
  799. }
  800. std::ifstream file (controlFile);
  801. if (!file.is_open ()) {
  802. sLog.error ("Hotswap requested but control file could not be read: ", controlFile.string ());
  803. return;
  804. }
  805. const auto request = parseHotswapRequest (file);
  806. HotswapTarget target;
  807. if (request.screen.has_value ()) {
  808. target = this->resolveHotswapScreen (*request.screen);
  809. if (!target.has_value ()) {
  810. sLog.error ("Hotswap: no screen or slot called ", *request.screen);
  811. return;
  812. }
  813. }
  814. if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
  815. && !request.fps.has_value () && !request.batteryFps.has_value () && !request.idlePause.has_value ()
  816. && !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
  817. && !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
  818. && !request.expandCanvas.has_value () && !request.repairAssets.has_value () && !request.cornerColor.has_value ()
  819. && !request.imageAdjustmentsProvided && !request.speed.has_value () && !request.videoStart.has_value ()
  820. && !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
  821. && !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
  822. && !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
  823. && !request.disableAnimations.has_value () && !request.hwdec.has_value () && !request.hrtf.has_value ()
  824. && !request.transition.has_value () && !request.transitionDuration.has_value ()) {
  825. sLog.error ("Hotswap requested but control file was empty");
  826. return;
  827. }
  828. // before anything changes: a wallpaper that can't load leaves the running one with everything it had
  829. if (request.path.has_value () && !this->preflightWallpaper (*request.path)) {
  830. sLog.error ("Hotswap failed, invalid wallpaper at ", *request.path);
  831. return;
  832. }
  833. // before the path below: a switch uses the transition that came with it
  834. if (request.transition.has_value ()) {
  835. if (WallpaperEngine::Render::parseTransition (*request.transition).has_value ()) {
  836. this->m_context.settings.render.transition = *request.transition;
  837. } else {
  838. sLog.error ("Hotswap: ignoring invalid transition value: ", *request.transition);
  839. }
  840. }
  841. if (request.transitionDuration.has_value ()) {
  842. try {
  843. this->m_context.settings.render.transitionMs = std::clamp (
  844. std::stoi (*request.transitionDuration), WallpaperEngine::Render::TRANSITION_MIN_MS,
  845. WallpaperEngine::Render::TRANSITION_MAX_MS
  846. );
  847. } catch (const std::exception&) {
  848. sLog.error ("Hotswap: ignoring invalid transition-duration value: ", *request.transitionDuration);
  849. }
  850. }
  851. struct OverrideSnapshot {
  852. std::vector<std::string> disabledObjects, enabledObjects, disabledEffects, enabledEffects;
  853. std::map<std::string, std::string> properties;
  854. std::map<std::string, float> audioSensitivity, soundVolume;
  855. Data::Model::ImageAdjustments windowImageAdjustments;
  856. VideoPlayback::VideoSegments videoSegments;
  857. std::map<std::string, Data::Model::ImageAdjustments> screenImageAdjustments;
  858. std::map<std::string, VideoPlayback::VideoSegments> screenVideoSegments;
  859. std::vector<Data::Model::ImageAdjustments> spanImageAdjustments;
  860. };
  861. std::optional<OverrideSnapshot> previousOverrides;
  862. // overrides belong to the wallpaper they were set for (ids and generic property names collide), a new one only gets
  863. // what this request carries
  864. if (request.path.has_value ()) {
  865. auto& general = this->m_context.settings.general;
  866. previousOverrides = OverrideSnapshot {
  867. .disabledObjects = general.disabledObjects,
  868. .enabledObjects = general.enabledObjects,
  869. .disabledEffects = general.disabledEffects,
  870. .enabledEffects = general.enabledEffects,
  871. .properties = general.properties,
  872. .audioSensitivity = general.audioSensitivity,
  873. .soundVolume = general.soundVolume,
  874. .windowImageAdjustments = this->m_context.settings.render.window.imageAdjustments,
  875. .videoSegments = this->m_context.settings.render.videoSegments,
  876. .screenImageAdjustments = general.screenImageAdjustments,
  877. .screenVideoSegments = general.screenVideoSegments,
  878. };
  879. for (const auto& spanGroup : general.spanGroups) {
  880. previousOverrides->spanImageAdjustments.push_back (spanGroup.imageAdjustments);
  881. }
  882. general.disabledObjects.clear ();
  883. general.enabledObjects.clear ();
  884. general.disabledEffects.clear ();
  885. general.enabledEffects.clear ();
  886. general.properties.clear ();
  887. general.audioSensitivity.clear ();
  888. general.soundVolume.clear ();
  889. // per wallpaper like WE; an empty entry keeps the global parts off the new one
  890. if (target.has_value ()) {
  891. if (auto* spanGroup = this->findSpanGroup (*target); spanGroup != nullptr) {
  892. spanGroup->imageAdjustments = {};
  893. } else {
  894. general.screenImageAdjustments.erase (*target);
  895. }
  896. general.screenVideoSegments[*target] = {};
  897. } else {
  898. this->m_context.settings.render.window.imageAdjustments = {};
  899. this->m_context.settings.render.videoSegments.clear ();
  900. general.screenImageAdjustments.clear ();
  901. general.screenVideoSegments.clear ();
  902. for (auto& spanGroup : general.spanGroups) {
  903. spanGroup.imageAdjustments = {};
  904. }
  905. }
  906. }
  907. if (request.volume.has_value ()) {
  908. this->applyVolumeHotswap (*request.volume);
  909. }
  910. if (request.fps.has_value ()) {
  911. this->applyFpsHotswap (*request.fps);
  912. }
  913. if (request.batteryFps.has_value ()) {
  914. this->applyBatteryFpsHotswap (*request.batteryFps);
  915. }
  916. if (request.idlePause.has_value ()) {
  917. this->applyIdlePauseHotswap (*request.idlePause);
  918. }
  919. if (request.xray.has_value ()) {
  920. this->applyXrayHotswap (*request.xray);
  921. }
  922. if (request.scaling.has_value ()) {
  923. this->applyScalingHotswap (target, *request.scaling);
  924. }
  925. if (request.zoom.has_value ()) {
  926. this->applyZoomHotswap (target, *request.zoom);
  927. }
  928. if (request.offset.has_value ()) {
  929. this->applyOffsetHotswap (target, *request.offset);
  930. }
  931. if (request.alignment.has_value ()) {
  932. this->applyAlignmentHotswap (target, *request.alignment);
  933. }
  934. if (request.disableParallax.has_value ()) {
  935. this->applyParallaxHotswap (*request.disableParallax);
  936. }
  937. if (request.cornerColor.has_value ()) {
  938. this->applyCornerColorHotswap (target, *request.cornerColor);
  939. }
  940. if (request.imageAdjustmentsProvided) {
  941. this->applyImageAdjustmentsHotswap (target, request.imageAdjustments);
  942. }
  943. if (request.speed.has_value ()) {
  944. this->applySpeedHotswap (*request.speed);
  945. }
  946. if (request.videoStart.has_value () || request.videoEnd.has_value () || request.videoSegments.has_value ()) {
  947. this->applyVideoSegmentsHotswap (target, request.videoStart, request.videoEnd, request.videoSegments);
  948. }
  949. if (request.videoSeek.has_value ()) {
  950. this->applyVideoSeekHotswap (target, *request.videoSeek);
  951. }
  952. if (request.hwdec.has_value ()) {
  953. this->applyHwdecHotswap (*request.hwdec);
  954. }
  955. if (request.hrtf.has_value ()) {
  956. if (const auto mode = ApplicationContext::parseHrtfMode (*request.hrtf); mode.has_value ()) {
  957. this->m_context.settings.audio.hrtf = *mode;
  958. } else {
  959. sLog.error ("Hotswap: ignoring invalid hrtf value: ", *request.hrtf);
  960. }
  961. }
  962. if (request.audioScreen.has_value ()) {
  963. this->applyAudioScreenHotswap (*request.audioScreen);
  964. }
  965. if (request.ambientVolume.has_value ()) {
  966. this->applyAmbientVolumeHotswap (*request.ambientVolume);
  967. }
  968. if (request.soundVolumeProvided) {
  969. this->applySoundVolumeHotswap (request.soundVolume);
  970. }
  971. bool sceneSettingsChanged = false;
  972. if (request.expandCanvas.has_value ()) {
  973. const auto& value = *request.expandCanvas;
  974. const bool enable = value == "on" || value == "1" || value == "true";
  975. if (!enable && value != "off" && value != "0" && value != "false") {
  976. sLog.error ("Hotswap: ignoring invalid expand-canvas value: ", value);
  977. } else {
  978. sceneSettingsChanged = this->m_context.settings.general.expandCanvas != enable;
  979. this->m_context.settings.general.expandCanvas = enable;
  980. }
  981. }
  982. if (request.repairAssets.has_value ()) {
  983. const auto& value = *request.repairAssets;
  984. const bool enable = value == "on" || value == "1" || value == "true";
  985. if (!enable && value != "off" && value != "0" && value != "false") {
  986. sLog.error ("Hotswap: ignoring invalid repair-assets value: ", value);
  987. } else {
  988. sceneSettingsChanged |= this->m_context.settings.general.repairAssets != enable;
  989. this->m_context.settings.general.repairAssets = enable;
  990. }
  991. }
  992. if (request.layersProvided) {
  993. this->m_context.settings.general.disabledObjects = request.disabledObjects;
  994. this->m_context.settings.general.enabledObjects = request.enabledObjects;
  995. }
  996. if (request.effectsProvided) {
  997. this->m_context.settings.general.disabledEffects = request.disabledEffects;
  998. this->m_context.settings.general.enabledEffects = request.enabledEffects;
  999. }
  1000. if (request.disableAnimations.has_value ()) {
  1001. const auto& value = *request.disableAnimations;
  1002. const bool freeze = value == "on" || value == "1" || value == "true";
  1003. if (!freeze && value != "off" && value != "0" && value != "false") {
  1004. sLog.error ("Hotswap: ignoring invalid disable-animations value: ", value);
  1005. } else {
  1006. this->m_context.settings.render.freezeAnimations = freeze;
  1007. }
  1008. }
  1009. std::vector<std::string> changedProperties;
  1010. if (request.propertiesProvided) {
  1011. auto& properties = this->m_context.settings.general.properties;
  1012. for (const auto& [name, value] : request.properties) {
  1013. if (const auto previous = properties.find (name);
  1014. previous == properties.end () || previous->second != value) {
  1015. changedProperties.push_back (name);
  1016. }
  1017. properties[name] = value;
  1018. }
  1019. }
  1020. if (request.audioSensitivityProvided) {
  1021. for (const auto& [target, value] : request.audioSensitivity) {
  1022. try {
  1023. this->m_context.settings.general.audioSensitivity[target] = parseFiniteFloat (value);
  1024. } catch (const std::exception&) {
  1025. sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", value);
  1026. }
  1027. }
  1028. }
  1029. if (request.propertiesProvided && !request.path.has_value () && !request.layersProvided && !request.effectsProvided
  1030. && !request.audioSensitivityProvided && !sceneSettingsChanged
  1031. && this->applyPropertiesLive (changedProperties)) {
  1032. return;
  1033. }
  1034. // volume/xray/speed are live setters; layers, effects, properties, audio sensitivity, expanded canvas and repaired
  1035. // assets are baked in at load
  1036. if (!request.path.has_value () && !request.layersProvided && !request.effectsProvided && !request.propertiesProvided
  1037. && !request.audioSensitivityProvided && !sceneSettingsChanged) {
  1038. return;
  1039. }
  1040. // the request's own settings are applied by now, a failure from here on puts the old ones back
  1041. const auto restoreOverrides = [&] {
  1042. if (!previousOverrides.has_value ()) {
  1043. return;
  1044. }
  1045. auto& general = this->m_context.settings.general;
  1046. general.disabledObjects = previousOverrides->disabledObjects;
  1047. general.enabledObjects = previousOverrides->enabledObjects;
  1048. general.disabledEffects = previousOverrides->disabledEffects;
  1049. general.enabledEffects = previousOverrides->enabledEffects;
  1050. general.properties = previousOverrides->properties;
  1051. general.audioSensitivity = previousOverrides->audioSensitivity;
  1052. general.soundVolume = previousOverrides->soundVolume;
  1053. this->m_context.settings.render.window.imageAdjustments = previousOverrides->windowImageAdjustments;
  1054. this->m_context.settings.render.videoSegments = previousOverrides->videoSegments;
  1055. general.screenImageAdjustments = previousOverrides->screenImageAdjustments;
  1056. general.screenVideoSegments = previousOverrides->screenVideoSegments;
  1057. for (size_t index = 0;
  1058. index < general.spanGroups.size () && index < previousOverrides->spanImageAdjustments.size (); index++) {
  1059. general.spanGroups[index].imageAdjustments = previousOverrides->spanImageAdjustments[index];
  1060. }
  1061. };
  1062. if (!this->makeAnyViewportCurrent ()) {
  1063. sLog.error ("Hotswap failed, no active viewport");
  1064. restoreOverrides ();
  1065. return;
  1066. }
  1067. if (request.path.has_value ()) {
  1068. sLog.out ("Hotswapping wallpaper to ", *request.path);
  1069. } else {
  1070. sLog.out ("Hotswapping wallpaper layers");
  1071. }
  1072. bool swapped = false;
  1073. // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
  1074. for (auto& [screen, background] : this->m_backgrounds) {
  1075. if (!this->hotswapReaches (target, screen)) {
  1076. continue;
  1077. }
  1078. const std::string currentPath = this->resolveScreenBackgroundPath (screen);
  1079. const std::string targetPath = request.path.value_or (currentPath);
  1080. const bool animate = request.path.has_value () && targetPath != currentPath;
  1081. try {
  1082. auto project = this->loadBackground (targetPath);
  1083. this->setupPropertiesForProject (*project);
  1084. this->setupAudioSensitivityForProject (*project);
  1085. this->setupSoundVolumeForProject (*project);
  1086. this->ensureAudioCapture (*project);
  1087. auto outgoing = std::move (background);
  1088. background = std::move (project);
  1089. try {
  1090. if (this->m_renderContext) {
  1091. this->installWallpaper (screen, *background, targetPath, true, animate);
  1092. }
  1093. } catch (...) {
  1094. project = std::move (background);
  1095. background = std::move (outgoing);
  1096. if (this->m_renderContext) {
  1097. this->m_renderContext->pruneTextures ();
  1098. }
  1099. throw;
  1100. }
  1101. swapped = true;
  1102. if (request.path.has_value ()) {
  1103. if (screen.starts_with ("span:")) {
  1104. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1105. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  1106. spanGroup.background = *request.path;
  1107. }
  1108. }
  1109. } else {
  1110. this->m_context.settings.general.screenBackgrounds[screen] = *request.path;
  1111. }
  1112. }
  1113. } catch (const std::exception& e) {
  1114. sLog.error ("Hotswap failed for screen ", screen, ": ", e.what ());
  1115. } catch (...) {
  1116. sLog.error ("Hotswap failed for screen ", screen, ": unknown error");
  1117. }
  1118. }
  1119. if (!swapped) {
  1120. restoreOverrides ();
  1121. }
  1122. this->applyAudioPolicy ();
  1123. if (swapped && request.path.has_value () && !request.screen.has_value ()) {
  1124. this->m_context.settings.general.defaultBackground = *request.path;
  1125. }
  1126. }
  1127. std::optional<std::string> WallpaperApplication::resolveHotswapScreen (const std::string& name) const {
  1128. if (this->m_backgrounds.contains (name)) {
  1129. return name;
  1130. }
  1131. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1132. if (std::ranges::find (spanGroup.screens, name) != spanGroup.screens.end ()) {
  1133. return "span:" + spanGroup.screens.front ();
  1134. }
  1135. }
  1136. return std::nullopt;
  1137. }
  1138. bool WallpaperApplication::hotswapReaches (const HotswapTarget& target, const std::string& screen) const {
  1139. if (!target.has_value () || *target == screen) {
  1140. return true;
  1141. }
  1142. const auto* spanGroup = this->findSpanGroup (*target);
  1143. return spanGroup != nullptr && std::ranges::find (spanGroup->screens, screen) != spanGroup->screens.end ();
  1144. }
  1145. template <typename T, typename Update>
  1146. void WallpaperApplication::updateScreenSetting (
  1147. const HotswapTarget& target, std::map<std::string, T>& screens, T& window,
  1148. T ApplicationContext::SpanGroup::* spanField, Update update
  1149. ) {
  1150. if (target.has_value ()) {
  1151. if (auto* spanGroup = this->findSpanGroup (*target); spanGroup != nullptr) {
  1152. spanGroup->*spanField = update (spanGroup->*spanField);
  1153. } else {
  1154. auto& value = screens[*target];
  1155. value = update (value);
  1156. }
  1157. return;
  1158. }
  1159. window = update (window);
  1160. for (auto& value : screens | std::views::values) {
  1161. value = update (value);
  1162. }
  1163. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1164. spanGroup.*spanField = update (spanGroup.*spanField);
  1165. }
  1166. }
  1167. template <typename Apply>
  1168. void WallpaperApplication::forEachTargetWallpaper (const HotswapTarget& target, Apply apply) const {
  1169. if (!this->m_renderContext) {
  1170. return;
  1171. }
  1172. std::set<WallpaperEngine::Render::CWallpaper*> done;
  1173. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1174. if (this->hotswapReaches (target, screen) && done.insert (wallpaper.get ()).second) {
  1175. apply (screen, *wallpaper);
  1176. }
  1177. }
  1178. }
  1179. std::string WallpaperApplication::storageScreen (const std::string& screen) const {
  1180. // WE: nothing in a window, "Monitor<index>" on the desktop (sub_14012E710); output names survive reordering
  1181. const auto mode = this->m_context.settings.render.mode;
  1182. return mode == ApplicationContext::NORMAL_WINDOW || mode == ApplicationContext::EXPLICIT_WINDOW ? "" : screen;
  1183. }
  1184. std::string WallpaperApplication::resolveScreenBackgroundPath (const std::string& screen) const {
  1185. if (screen.starts_with ("span:")) {
  1186. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1187. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  1188. return spanGroup.background.empty () ? this->m_context.settings.general.defaultBackground.string ()
  1189. : spanGroup.background.string ();
  1190. }
  1191. }
  1192. return this->m_context.settings.general.defaultBackground.string ();
  1193. }
  1194. const auto it = this->m_context.settings.general.screenBackgrounds.find (screen);
  1195. if (it != this->m_context.settings.general.screenBackgrounds.end () && !it->second.empty ()) {
  1196. return it->second.string ();
  1197. }
  1198. return this->m_context.settings.general.defaultBackground.string ();
  1199. }
  1200. float WallpaperApplication::resolveScreenZoom (const std::string& screen) const {
  1201. const auto it = this->m_context.settings.general.screenZooms.find (screen);
  1202. return it != this->m_context.settings.general.screenZooms.end () ? it->second
  1203. : this->m_context.settings.render.window.zoom;
  1204. }
  1205. glm::vec2 WallpaperApplication::resolveScreenOffset (const std::string& screen) const {
  1206. const auto it = this->m_context.settings.general.screenOffsets.find (screen);
  1207. return it != this->m_context.settings.general.screenOffsets.end () ? it->second
  1208. : this->m_context.settings.render.window.offset;
  1209. }
  1210. WallpaperEngine::Render::WallpaperState::Alignment
  1211. WallpaperApplication::resolveScreenAlignment (const std::string& screen) const {
  1212. const auto it = this->m_context.settings.general.screenAlignments.find (screen);
  1213. return it != this->m_context.settings.general.screenAlignments.end ()
  1214. ? it->second
  1215. : this->m_context.settings.render.window.alignment;
  1216. }
  1217. glm::vec4 WallpaperApplication::resolveScreenCornerColor (const std::string& screen) const {
  1218. const auto it = this->m_context.settings.general.screenCornerColors.find (screen);
  1219. return it != this->m_context.settings.general.screenCornerColors.end ()
  1220. ? it->second
  1221. : this->m_context.settings.render.window.cornerColor;
  1222. }
  1223. ImageAdjustments
  1224. WallpaperApplication::resolveScreenImageAdjustments (const std::string& screen, const Project& project) const {
  1225. const auto fallback = this->m_context.settings.render.window.imageAdjustments.over (project.imageAdjustments);
  1226. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1227. if (spanGroup.screens.empty ()) {
  1228. continue;
  1229. }
  1230. if ("span:" + spanGroup.screens.front () == screen
  1231. || std::find (spanGroup.screens.begin (), spanGroup.screens.end (), screen) != spanGroup.screens.end ()) {
  1232. return spanGroup.imageAdjustments.over (fallback);
  1233. }
  1234. }
  1235. const auto it = this->m_context.settings.general.screenImageAdjustments.find (screen);
  1236. return it != this->m_context.settings.general.screenImageAdjustments.end () ? it->second.over (fallback) : fallback;
  1237. }
  1238. glm::ivec2 WallpaperApplication::resolveScreenRenderSize (const std::string& screen) const {
  1239. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  1240. const auto* split = this->m_context.findSplitScreen (screen);
  1241. const auto it = viewports.find (split != nullptr ? split->screen : screen);
  1242. if (it != viewports.end ()) {
  1243. return { it->second->viewport.z, it->second->viewport.w };
  1244. }
  1245. return { this->m_renderContext->getOutput ().getFullWidth (),
  1246. this->m_renderContext->getOutput ().getFullHeight () };
  1247. }
  1248. void WallpaperApplication::applyVolumeHotswap (int volume) {
  1249. volume = std::max (0, std::min (volume, 128));
  1250. this->m_context.settings.audio.volume = volume;
  1251. this->m_context.state.audio.volume = volume;
  1252. if (!this->m_renderContext) {
  1253. return;
  1254. }
  1255. const double scaledVolume = this->m_context.settings.audio.enabled ? volume * 100.0 / 128.0 : 0.0;
  1256. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1257. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  1258. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setVolume (scaledVolume);
  1259. }
  1260. }
  1261. this->applyAudioPolicy ();
  1262. sLog.out ("Hotswap: applied volume ", volume, " live");
  1263. }
  1264. void WallpaperApplication::applyFpsHotswap (int fps) {
  1265. fps = std::max (1, fps);
  1266. this->m_context.settings.render.maximumFPS = fps;
  1267. sLog.out ("Hotswap: applied fps limit ", fps, " live");
  1268. }
  1269. void WallpaperApplication::applyBatteryFpsHotswap (const std::string& value) {
  1270. auto& batteryFPS = this->m_context.settings.render.batteryFPS;
  1271. if (value == "off" || value == "none" || value.empty ()) {
  1272. batteryFPS = std::nullopt;
  1273. } else if (value == "pause") {
  1274. batteryFPS = 0;
  1275. } else {
  1276. try {
  1277. batteryFPS = std::max (0, std::stoi (value));
  1278. } catch (const std::exception&) {
  1279. sLog.error ("Hotswap: ignoring invalid fps-battery value: ", value);
  1280. return;
  1281. }
  1282. }
  1283. this->updatePowerMonitor ();
  1284. sLog.out ("Hotswap: applied fps-battery ", batteryFPS.has_value () ? std::to_string (*batteryFPS) : "off", " live");
  1285. }
  1286. void WallpaperApplication::applyIdlePauseHotswap (const std::string& value) {
  1287. int minutes = 0;
  1288. if (value != "off" && value != "none" && !value.empty ()) {
  1289. try {
  1290. minutes = std::max (0, std::stoi (value));
  1291. } catch (const std::exception&) {
  1292. sLog.error ("Hotswap: ignoring invalid idle-pause value: ", value);
  1293. return;
  1294. }
  1295. }
  1296. this->m_context.settings.render.idlePauseMinutes = minutes;
  1297. this->updatePowerMonitor ();
  1298. sLog.out ("Hotswap: applied idle-pause ", minutes, " live");
  1299. }
  1300. void WallpaperApplication::updatePowerMonitor () {
  1301. const auto& render = this->m_context.settings.render;
  1302. if (!render.batteryFPS.has_value () && render.idlePauseMinutes <= 0) {
  1303. this->m_powerMonitor.reset ();
  1304. return;
  1305. }
  1306. if (!this->m_powerMonitor) {
  1307. this->m_powerMonitor = std::make_unique<WallpaperEngine::Desktop::PowerMonitor> ();
  1308. sLog.out ("Power: ", this->m_powerMonitor->onBattery () ? "running on battery" : "on external power");
  1309. }
  1310. this->m_powerMonitor->setIdleTimeout (render.idlePauseMinutes);
  1311. }
  1312. int WallpaperApplication::frameRateLimit () const {
  1313. const auto& render = this->m_context.settings.render;
  1314. if (render.batteryFPS.value_or (0) > 0 && this->m_powerMonitor && this->m_powerMonitor->onBattery ()) {
  1315. return std::min (*render.batteryFPS, render.maximumFPS);
  1316. }
  1317. return render.maximumFPS;
  1318. }
  1319. uint32_t WallpaperApplication::pauseReasons () const {
  1320. const auto& render = this->m_context.settings.render;
  1321. uint32_t reasons = 0;
  1322. if (this->m_fullScreenDetector->anythingFullscreen ()) {
  1323. reasons |= PauseWindows;
  1324. }
  1325. if (this->m_powerMonitor) {
  1326. if (render.batteryFPS == 0 && this->m_powerMonitor->onBattery ()) {
  1327. reasons |= PauseBattery;
  1328. }
  1329. if (render.idlePauseMinutes > 0 && this->m_powerMonitor->idle ()) {
  1330. reasons |= PauseIdle;
  1331. }
  1332. }
  1333. return reasons;
  1334. }
  1335. void WallpaperApplication::logPauseReasons (uint32_t reasons) {
  1336. if (reasons == this->m_pauseReasons) {
  1337. return;
  1338. }
  1339. this->m_pauseReasons = reasons;
  1340. if (reasons == 0) {
  1341. sLog.out ("Resumed");
  1342. return;
  1343. }
  1344. std::string names;
  1345. for (const auto& [bit, name] : { std::pair { PauseWindows, "windows" }, std::pair { PauseBattery, "battery" },
  1346. std::pair { PauseIdle, "idle" } }) {
  1347. if (reasons & bit) {
  1348. names += names.empty () ? name : std::string (", ") + name;
  1349. }
  1350. }
  1351. sLog.out ("Paused: ", names);
  1352. }
  1353. void WallpaperApplication::applyXrayHotswap (const std::string& value) {
  1354. auto& mode = this->m_context.state.xray.mode;
  1355. // on/off/toggle predate "disabled" and only switch between full and normal
  1356. if (value == "toggle") {
  1357. mode = mode == XrayMode::Full ? XrayMode::Normal : XrayMode::Full;
  1358. } else if (value == "full" || value == "on" || value == "1" || value == "true") {
  1359. mode = XrayMode::Full;
  1360. } else if (value == "normal" || value == "off" || value == "0" || value == "false") {
  1361. mode = XrayMode::Normal;
  1362. } else if (value == "disabled") {
  1363. mode = XrayMode::Disabled;
  1364. } else {
  1365. sLog.error ("Hotswap: ignoring invalid xray value: ", value);
  1366. return;
  1367. }
  1368. const char* name = mode == XrayMode::Full ? "full" : mode == XrayMode::Disabled ? "disabled" : "normal";
  1369. sLog.out ("Hotswap: xray ", name, " live");
  1370. }
  1371. void WallpaperApplication::applyScalingHotswap (const HotswapTarget& target, const std::string& value) {
  1372. const auto mode = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
  1373. if (!mode.has_value ()) {
  1374. sLog.error ("Hotswap: ignoring invalid scaling value: ", value);
  1375. return;
  1376. }
  1377. this->updateScreenSetting (
  1378. target, this->m_context.settings.general.screenScalings, this->m_context.settings.render.window.scalingMode,
  1379. &ApplicationContext::SpanGroup::scaling, [&] (const auto&) { return *mode; }
  1380. );
  1381. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1382. wallpaper.setScalingMode (*mode);
  1383. });
  1384. sLog.out ("Hotswap: applied scaling mode ", value, " live");
  1385. }
  1386. void WallpaperApplication::applyZoomHotswap (const HotswapTarget& target, const std::string& value) {
  1387. float zoom;
  1388. try {
  1389. zoom = parseFiniteFloat (value);
  1390. } catch (const std::exception&) {
  1391. sLog.error ("Hotswap: ignoring invalid zoom value: ", value);
  1392. return;
  1393. }
  1394. this->updateScreenSetting (
  1395. target, this->m_context.settings.general.screenZooms, this->m_context.settings.render.window.zoom,
  1396. &ApplicationContext::SpanGroup::zoom, [&] (const auto&) { return zoom; }
  1397. );
  1398. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1399. wallpaper.setZoom (zoom);
  1400. });
  1401. sLog.out ("Hotswap: applied zoom ", zoom, " live");
  1402. }
  1403. void WallpaperApplication::applyOffsetHotswap (const HotswapTarget& target, const std::string& value) {
  1404. const auto comma = value.find (',');
  1405. if (comma == std::string::npos) {
  1406. sLog.error ("Hotswap: ignoring malformed offset value (expected X,Y): ", value);
  1407. return;
  1408. }
  1409. glm::vec2 offset;
  1410. try {
  1411. offset.x = parseFiniteFloat (value.substr (0, comma));
  1412. offset.y = parseFiniteFloat (value.substr (comma + 1));
  1413. } catch (const std::exception&) {
  1414. sLog.error ("Hotswap: ignoring invalid offset value: ", value);
  1415. return;
  1416. }
  1417. this->updateScreenSetting (
  1418. target, this->m_context.settings.general.screenOffsets, this->m_context.settings.render.window.offset,
  1419. &ApplicationContext::SpanGroup::offset, [&] (const auto&) { return offset; }
  1420. );
  1421. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1422. wallpaper.setOffset (offset.x, offset.y);
  1423. });
  1424. sLog.out ("Hotswap: applied offset ", offset.x, ",", offset.y, " live");
  1425. }
  1426. void WallpaperApplication::applyAlignmentHotswap (const HotswapTarget& target, const std::string& value) {
  1427. std::array<float, 4> values {};
  1428. std::stringstream stream (value);
  1429. std::string part;
  1430. size_t count = 0;
  1431. try {
  1432. while (count < values.size () && std::getline (stream, part, ',')) {
  1433. values[count++] = parseFiniteFloat (part);
  1434. }
  1435. } catch (const std::exception&) {
  1436. count = 0;
  1437. }
  1438. if (count != values.size ()) {
  1439. sLog.error ("Hotswap: ignoring malformed alignment value (expected position,x,y,zoom): ", value);
  1440. return;
  1441. }
  1442. const WallpaperEngine::Render::WallpaperState::Alignment alignment {
  1443. .position = std::clamp (values[0], 0.0f, 100.0f) / 100.0f,
  1444. .x = std::clamp (values[1], 0.0f, 100.0f) / 100.0f,
  1445. .y = std::clamp (values[2], 0.0f, 100.0f) / 100.0f,
  1446. .zoom = std::clamp (values[3], 0.0f, 200.0f) / 100.0f,
  1447. };
  1448. this->updateScreenSetting (
  1449. target, this->m_context.settings.general.screenAlignments, this->m_context.settings.render.window.alignment,
  1450. &ApplicationContext::SpanGroup::alignment, [&] (const auto&) { return alignment; }
  1451. );
  1452. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1453. wallpaper.setAlignment (alignment);
  1454. });
  1455. sLog.out ("Hotswap: applied alignment ", value, " live");
  1456. }
  1457. void WallpaperApplication::applyParallaxHotswap (const std::string& value) {
  1458. bool newState;
  1459. if (value == "toggle") {
  1460. newState = !this->m_context.settings.mouse.disableparallax;
  1461. } else if (value == "on" || value == "1" || value == "true") {
  1462. newState = true;
  1463. } else if (value == "off" || value == "0" || value == "false") {
  1464. newState = false;
  1465. } else {
  1466. sLog.error ("Hotswap: ignoring invalid disable-parallax value: ", value);
  1467. return;
  1468. }
  1469. this->m_context.settings.mouse.disableparallax = newState;
  1470. sLog.out ("Hotswap: parallax ", newState ? "force-disabled" : "enabled", " live");
  1471. }
  1472. void WallpaperApplication::applyCornerColorHotswap (const HotswapTarget& target, const std::string& value) {
  1473. const auto color = WallpaperEngine::Render::CFBO::parseColor (value);
  1474. if (!color.has_value ()) {
  1475. sLog.error ("Hotswap: ignoring invalid corner color: ", value);
  1476. return;
  1477. }
  1478. this->updateScreenSetting (
  1479. target, this->m_context.settings.general.screenCornerColors, this->m_context.settings.render.window.cornerColor,
  1480. &ApplicationContext::SpanGroup::cornerColor, [&] (const auto&) { return *color; }
  1481. );
  1482. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1483. wallpaper.setCornerColor (*color);
  1484. });
  1485. sLog.out ("Hotswap: applied corner color ", value, " live");
  1486. }
  1487. void WallpaperApplication::applyImageAdjustmentsHotswap (const HotswapTarget& target, const ImageAdjustments& request) {
  1488. this->updateScreenSetting (
  1489. target, this->m_context.settings.general.screenImageAdjustments,
  1490. this->m_context.settings.render.window.imageAdjustments, &ApplicationContext::SpanGroup::imageAdjustments,
  1491. [&] (const ImageAdjustments& adjustments) { return request.over (adjustments); }
  1492. );
  1493. this->forEachTargetWallpaper (
  1494. target, [&] (const std::string& screen, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1495. wallpaper.setImageAdjustments (
  1496. this->resolveScreenImageAdjustments (screen, wallpaper.getWallpaperData ().project)
  1497. );
  1498. }
  1499. );
  1500. sLog.out ("Hotswap: applied image filter and color options live");
  1501. }
  1502. void WallpaperApplication::applySpeedHotswap (const std::string& value) {
  1503. float speed;
  1504. try {
  1505. speed = parseFiniteFloat (value);
  1506. } catch (const std::exception&) {
  1507. sLog.error ("Hotswap: ignoring invalid speed value: ", value);
  1508. return;
  1509. }
  1510. if (speed <= 0.0f) {
  1511. sLog.error ("Hotswap: ignoring non-positive speed value: ", value);
  1512. return;
  1513. }
  1514. this->m_context.settings.render.playbackSpeed = speed;
  1515. // video wallpapers run on mpv's clock and need the speed pushed, everything else reads it every frame
  1516. if (this->m_renderContext) {
  1517. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1518. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  1519. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSpeed (speed);
  1520. }
  1521. }
  1522. }
  1523. sLog.out ("Hotswap: applied speed ", speed, " live");
  1524. }
  1525. void WallpaperApplication::applyVideoSegmentsHotswap (
  1526. const HotswapTarget& target, const std::optional<std::string>& start, const std::optional<std::string>& end,
  1527. const std::optional<std::string>& segments
  1528. ) {
  1529. using WallpaperEngine::Render::Wallpapers::CVideo;
  1530. auto& general = this->m_context.settings.general;
  1531. WallpaperEngine::VideoPlayback::VideoSegments current = target.has_value ()
  1532. ? this->resolveScreenVideoSegments (*target)
  1533. : this->m_context.settings.render.videoSegments;
  1534. const auto clears = [] (const std::string& value) { return value.empty () || value == "none"; };
  1535. if (segments.has_value ()) {
  1536. if (clears (*segments)) {
  1537. current.clear ();
  1538. } else if (const auto parsed = CVideo::parseSegments (*segments)) {
  1539. current = *parsed;
  1540. } else {
  1541. sLog.error ("Hotswap: ignoring invalid video-segments value: ", *segments);
  1542. }
  1543. }
  1544. if (start.has_value () || end.has_value ()) {
  1545. WallpaperEngine::VideoPlayback::VideoSegment segment;
  1546. if (!current.empty ()) {
  1547. segment = { current.front ().start, current.back ().end };
  1548. }
  1549. if (start.has_value ()) {
  1550. if (clears (*start)) {
  1551. segment.start = 0.0;
  1552. } else if (const auto seconds = CVideo::parseTime (*start)) {
  1553. segment.start = *seconds;
  1554. } else {
  1555. sLog.error ("Hotswap: ignoring invalid video-start value: ", *start);
  1556. }
  1557. }
  1558. if (end.has_value ()) {
  1559. if (clears (*end)) {
  1560. segment.end.reset ();
  1561. } else if (const auto seconds = CVideo::parseTime (*end)) {
  1562. segment.end = seconds;
  1563. } else {
  1564. sLog.error ("Hotswap: ignoring invalid video-end value: ", *end);
  1565. }
  1566. }
  1567. current = { segment };
  1568. }
  1569. current = CVideo::normalizeSegments (current);
  1570. if (target.has_value ()) {
  1571. general.screenVideoSegments[*target] = current;
  1572. } else {
  1573. this->m_context.settings.render.videoSegments = current;
  1574. general.screenVideoSegments.clear ();
  1575. }
  1576. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1577. if (wallpaper.is<CVideo> ()) {
  1578. wallpaper.as<CVideo> ()->setSegments (current);
  1579. }
  1580. });
  1581. std::string description = current.empty () ? "whole video" : "";
  1582. for (const auto& segment : current) {
  1583. description += (description.empty () ? "" : ", ") + std::to_string (segment.start) + " - "
  1584. + (segment.end.has_value () ? std::to_string (*segment.end) : "end");
  1585. }
  1586. sLog.out ("Hotswap: applied video parts ", description, " live");
  1587. }
  1588. WallpaperEngine::VideoPlayback::VideoSegments
  1589. WallpaperApplication::resolveScreenVideoSegments (const std::string& screen) const {
  1590. const auto& screens = this->m_context.settings.general.screenVideoSegments;
  1591. const auto it = screens.find (screen);
  1592. return it != screens.end () ? it->second : this->m_context.settings.render.videoSegments;
  1593. }
  1594. void WallpaperApplication::applyVideoSeekHotswap (const HotswapTarget& target, const std::string& value) {
  1595. const auto seconds = WallpaperEngine::Render::Wallpapers::CVideo::parseTime (value);
  1596. if (!seconds.has_value ()) {
  1597. sLog.error ("Hotswap: ignoring invalid video-seek value: ", value);
  1598. return;
  1599. }
  1600. this->forEachTargetWallpaper (target, [&] (const std::string&, WallpaperEngine::Render::CWallpaper& wallpaper) {
  1601. if (wallpaper.is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  1602. wallpaper.as<WallpaperEngine::Render::Wallpapers::CVideo> ()->seek (*seconds);
  1603. }
  1604. });
  1605. }
  1606. void WallpaperApplication::applyHwdecHotswap (const std::string& value) {
  1607. if (!WallpaperEngine::VideoPlayback::MPV::GLPlayer::isValidHwdec (value)) {
  1608. sLog.error ("Hotswap: ignoring invalid hwdec value: ", value);
  1609. return;
  1610. }
  1611. if (this->m_context.settings.render.hwdec == value) {
  1612. return;
  1613. }
  1614. this->m_context.settings.render.hwdec = value;
  1615. WallpaperEngine::VideoPlayback::MPV::GLPlayer::setHwdecForAll (value);
  1616. sLog.out ("Hotswap: applied hwdec ", value, " live");
  1617. }
  1618. void WallpaperApplication::applyAudioScreenHotswap (const std::string& value) {
  1619. this->m_context.settings.audio.audioScreen = value.empty () ? std::nullopt : std::optional<std::string> (value);
  1620. this->applyAudioPolicy ();
  1621. sLog.out ("Hotswap: applied audio screen '", value, "' live");
  1622. }
  1623. void WallpaperApplication::applyAmbientVolumeHotswap (const std::string& value) {
  1624. int volume;
  1625. try {
  1626. volume = std::stoi (value);
  1627. } catch (const std::exception&) {
  1628. sLog.error ("Hotswap: ignoring invalid ambient volume value: ", value);
  1629. return;
  1630. }
  1631. this->m_context.settings.audio.ambientVolume = std::max (0, std::min (volume, 128));
  1632. this->applyAudioPolicy ();
  1633. sLog.out ("Hotswap: applied ambient volume ", volume, " live");
  1634. }
  1635. void WallpaperApplication::applyAudioPolicy () {
  1636. if (!this->m_renderContext) {
  1637. return;
  1638. }
  1639. const auto& audioScreen = this->m_context.settings.audio.audioScreen;
  1640. const auto& ambientVolume = this->m_context.settings.audio.ambientVolume;
  1641. std::map<WallpaperEngine::Render::CWallpaper*, bool> wantMuted;
  1642. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1643. bool screenMuted = audioScreen.has_value () && screen != *audioScreen;
  1644. if (const auto* split = this->m_context.findSplitScreen (screen); split != nullptr) {
  1645. const bool named
  1646. = audioScreen.has_value () && std::ranges::find (split->slots, *audioScreen) != split->slots.end ();
  1647. const std::string& audible = named ? *audioScreen : split->slots.front ();
  1648. screenMuted = screen != audible || (audioScreen.has_value () && !named && *audioScreen != split->screen);
  1649. }
  1650. auto [it, inserted] = wantMuted.try_emplace (wallpaper.get (), screenMuted);
  1651. if (!inserted) {
  1652. it->second = it->second && screenMuted;
  1653. }
  1654. }
  1655. for (const auto& [wallpaper, muted] : wantMuted) {
  1656. wallpaper->setAudioPolicy (muted, ambientVolume);
  1657. }
  1658. }
  1659. void WallpaperApplication::setupPropertiesForProject (const Project& project) {
  1660. for (const auto& [key, cur] : project.properties) {
  1661. auto override = this->m_context.settings.general.properties.find (key);
  1662. if (override != this->m_context.settings.general.properties.end ()) {
  1663. sLog.out ("Applying override value for ", key);
  1664. cur->update (override->second, DynamicValue::UpdateSource::User);
  1665. }
  1666. if (this->m_context.settings.general.onlyListProperties) {
  1667. sLog.out (cur->dump ());
  1668. }
  1669. }
  1670. }
  1671. void WallpaperApplication::setupProperties () {
  1672. for (const auto& [background, info] : this->m_backgrounds) {
  1673. this->setupPropertiesForProject (*info);
  1674. }
  1675. }
  1676. void WallpaperApplication::listObjectsForProject (const std::string& background, const Project& project) const {
  1677. if (!project.wallpaper->is<Scene> ()) {
  1678. return;
  1679. }
  1680. const auto scene = project.wallpaper->as<Scene> ();
  1681. sLog.out ("Objects for ", background, ":");
  1682. for (const auto& object : scene->objects) {
  1683. std::string type = "unknown";
  1684. if (object->is<Image> ()) {
  1685. type = "image";
  1686. } else if (object->is<Particle> ()) {
  1687. type = "particle";
  1688. } else if (object->is<Text> ()) {
  1689. type = "text";
  1690. } else if (object->is<Sound> ()) {
  1691. type = "sound";
  1692. }
  1693. sLog.out (" ", object->id, " - ", object->name, " (", type, ")");
  1694. }
  1695. }
  1696. void WallpaperApplication::listObjects () const {
  1697. if (!this->m_context.settings.general.onlyListObjects) {
  1698. return;
  1699. }
  1700. for (const auto& [background, info] : this->m_backgrounds) {
  1701. this->listObjectsForProject (background, *info);
  1702. }
  1703. }
  1704. void WallpaperApplication::listEffectsForProject (const std::string& background, const Project& project) const {
  1705. if (!project.wallpaper->is<Scene> ()) {
  1706. return;
  1707. }
  1708. const auto scene = project.wallpaper->as<Scene> ();
  1709. sLog.out ("Effects for ", background, ":");
  1710. for (const auto& object : scene->objects) {
  1711. if (!object->is<Image> ()) {
  1712. continue;
  1713. }
  1714. const auto* image = object->as<Image> ();
  1715. for (const auto& effect : image->effects) {
  1716. sLog.out (
  1717. " ", effect->id, " - ", effect->name, " (object=", object->id, " objectName=\"", object->name,
  1718. "\" group=\"", effect->effect->group, "\")"
  1719. );
  1720. }
  1721. }
  1722. }
  1723. void WallpaperApplication::listEffects () const {
  1724. if (!this->m_context.settings.general.onlyListEffects) {
  1725. return;
  1726. }
  1727. for (const auto& [background, info] : this->m_backgrounds) {
  1728. this->listEffectsForProject (background, *info);
  1729. }
  1730. }
  1731. void WallpaperApplication::listFontsForProject (const std::string& background, const Project& project) const {
  1732. if (!project.wallpaper->is<Scene> ()) {
  1733. return;
  1734. }
  1735. struct Need {
  1736. Render::Fonts::FontReport report;
  1737. std::string kind;
  1738. std::vector<std::string> objects;
  1739. };
  1740. std::vector<Need> needs;
  1741. const auto add
  1742. = [&needs] (const std::string& kind, const Render::Fonts::FontReport& report, const std::string& object) {
  1743. for (auto& need : needs) {
  1744. if (need.kind == kind && need.report.family == report.family) {
  1745. if (std::ranges::find (need.objects, object) == need.objects.end ()) {
  1746. need.objects.push_back (object);
  1747. }
  1748. return;
  1749. }
  1750. }
  1751. needs.push_back ({ report, kind, { object } });
  1752. };
  1753. for (const auto& object : project.wallpaper->as<Scene> ()->objects) {
  1754. if (!object->is<Text> ()) {
  1755. continue;
  1756. }
  1757. const auto* text = object->as<Text> ();
  1758. const auto systemFont = Render::Fonts::systemFontReport (text->font);
  1759. if (!systemFont.family.empty ()) {
  1760. add ("font", systemFont, object->name);
  1761. }
  1762. if (text->text != nullptr && text->text->value != nullptr
  1763. && Render::Fonts::containsEmoji (text->text->value->getString ())) {
  1764. add ("emoji", Render::Fonts::emojiReport (), object->name);
  1765. }
  1766. }
  1767. sLog.out ("Fonts for ", background, ":");
  1768. for (const auto& need : needs) {
  1769. const char* status = need.report.status == Render::Fonts::FontStatus::Exact ? "installed"
  1770. : need.report.status == Render::Fonts::FontStatus::Compatible ? "compatible"
  1771. : "missing";
  1772. std::string objects;
  1773. for (const auto& name : need.objects) {
  1774. objects += (objects.empty () ? "" : ", ") + name;
  1775. }
  1776. sLog.out (
  1777. " ", need.kind, " family=\"", need.report.family, "\" status=", status, " using=\"", need.report.using_,
  1778. "\" objects=\"", objects, "\""
  1779. );
  1780. }
  1781. }
  1782. void WallpaperApplication::listFonts () const {
  1783. if (!this->m_context.settings.general.onlyListFonts) {
  1784. return;
  1785. }
  1786. for (const auto& [background, info] : this->m_backgrounds) {
  1787. this->listFontsForProject (background, *info);
  1788. }
  1789. }
  1790. namespace {
  1791. struct AudioReactiveProperty {
  1792. std::string name;
  1793. DynamicValue* value;
  1794. };
  1795. void considerAudioReactive (
  1796. std::vector<AudioReactiveProperty>& result, const std::string& name, const UserSettingUniquePtr& setting
  1797. ) {
  1798. if (!setting || !setting->value) {
  1799. return;
  1800. }
  1801. const auto& source = setting->value->getScriptSource ();
  1802. if (source.has_value () && source->find ("registerAudioBuffers") != std::string::npos) {
  1803. result.push_back ({ name, setting->value.get () });
  1804. }
  1805. }
  1806. std::vector<AudioReactiveProperty> collectAudioReactiveProperties (const Object& object) {
  1807. std::vector<AudioReactiveProperty> result;
  1808. considerAudioReactive (result, "origin", object.origin);
  1809. if (object.is<Image> ()) {
  1810. const auto* image = object.as<Image> ();
  1811. considerAudioReactive (result, "scale", image->scale);
  1812. considerAudioReactive (result, "angles", image->angles);
  1813. considerAudioReactive (result, "visible", image->visible);
  1814. considerAudioReactive (result, "alpha", image->alpha);
  1815. considerAudioReactive (result, "color", image->color);
  1816. considerAudioReactive (result, "parallaxDepth", image->parallaxDepth);
  1817. } else if (object.is<Text> ()) {
  1818. const auto* text = object.as<Text> ();
  1819. considerAudioReactive (result, "scale", text->scale);
  1820. considerAudioReactive (result, "color", text->color);
  1821. considerAudioReactive (result, "alpha", text->alpha);
  1822. considerAudioReactive (result, "visible", text->visible);
  1823. considerAudioReactive (result, "pointSize", text->pointSize);
  1824. considerAudioReactive (result, "text", text->text);
  1825. considerAudioReactive (result, "parallaxDepth", text->parallaxDepth);
  1826. } else if (object.is<Particle> ()) {
  1827. const auto* particle = object.as<Particle> ();
  1828. considerAudioReactive (result, "scale", particle->scale);
  1829. considerAudioReactive (result, "angles", particle->angles);
  1830. considerAudioReactive (result, "visible", particle->visible);
  1831. considerAudioReactive (result, "parallaxDepth", particle->parallaxDepth);
  1832. } else {
  1833. considerAudioReactive (result, "scale", object.groupScale);
  1834. considerAudioReactive (result, "angles", object.groupAngles);
  1835. considerAudioReactive (result, "visible", object.groupVisible);
  1836. }
  1837. return result;
  1838. }
  1839. float readScriptPropertyFloat (DynamicValue& value, const std::string& key) {
  1840. auto& properties = value.getProperties ();
  1841. const auto it = properties.find (key);
  1842. return it != properties.end () && it->second && it->second->value ? it->second->value->getFloat () : 0.0f;
  1843. }
  1844. }
  1845. void WallpaperApplication::listAudioObjectsForProject (const std::string& background, const Project& project) const {
  1846. if (!project.wallpaper->is<Scene> ()) {
  1847. return;
  1848. }
  1849. const auto scene = project.wallpaper->as<Scene> ();
  1850. sLog.out ("Audio-reactive objects for ", background, ":");
  1851. for (const auto& object : scene->objects) {
  1852. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1853. sLog.out (
  1854. " ", object->id, " - ", object->name, " (", reactive.name,
  1855. "): minvalue=", readScriptPropertyFloat (*reactive.value, "minvalue"),
  1856. " maxvalue=", readScriptPropertyFloat (*reactive.value, "maxvalue"),
  1857. " frequency=", readScriptPropertyFloat (*reactive.value, "frequency"),
  1858. " smoothing=", readScriptPropertyFloat (*reactive.value, "smoothing")
  1859. );
  1860. }
  1861. }
  1862. }
  1863. void WallpaperApplication::listAudioObjects () const {
  1864. if (!this->m_context.settings.general.onlyListAudioObjects) {
  1865. return;
  1866. }
  1867. for (const auto& [background, info] : this->m_backgrounds) {
  1868. this->listAudioObjectsForProject (background, *info);
  1869. }
  1870. }
  1871. void WallpaperApplication::setupAudioSensitivityForProject (const Project& project) const {
  1872. if (!project.wallpaper->is<Scene> ()) {
  1873. return;
  1874. }
  1875. const auto scene = project.wallpaper->as<Scene> ();
  1876. for (const auto& object : scene->objects) {
  1877. const auto sensitivity = this->m_context.resolveAudioSensitivity (object->id, object->name);
  1878. if (!sensitivity.has_value ()) {
  1879. continue;
  1880. }
  1881. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1882. auto& scriptProps = reactive.value->getProperties ();
  1883. const auto minIt = scriptProps.find ("minvalue");
  1884. const auto maxIt = scriptProps.find ("maxvalue");
  1885. if (minIt == scriptProps.end () || maxIt == scriptProps.end () || !minIt->second->value
  1886. || !maxIt->second->value) {
  1887. continue;
  1888. }
  1889. const auto [newMin, newMax] = WallpaperEngine::Data::Utils::scaleAudioRange (
  1890. minIt->second->value->getFloat (), maxIt->second->value->getFloat (), sensitivity.value ()
  1891. );
  1892. minIt->second->value->update (newMin, DynamicValue::UpdateSource::User);
  1893. maxIt->second->value->update (newMax, DynamicValue::UpdateSource::User);
  1894. sLog.debug (
  1895. "Applying audio sensitivity ", sensitivity.value (), " to ", object->id, " - ", object->name, " (",
  1896. reactive.name, ")"
  1897. );
  1898. }
  1899. }
  1900. }
  1901. void WallpaperApplication::setupAudioSensitivity () {
  1902. for (const auto& [background, info] : this->m_backgrounds) {
  1903. this->setupAudioSensitivityForProject (*info);
  1904. }
  1905. }
  1906. void WallpaperApplication::setupSoundVolumeForProject (const Project& project) const {
  1907. if (!project.wallpaper->is<Scene> ()) {
  1908. return;
  1909. }
  1910. const auto scene = project.wallpaper->as<Scene> ();
  1911. for (const auto& object : scene->objects) {
  1912. if (!object->is<Sound> ()) {
  1913. continue;
  1914. }
  1915. const auto* sound = object->as<Sound> ();
  1916. const auto volume = this->m_context.resolveSoundVolume (object->id, object->name);
  1917. if (!volume.has_value () || !sound->volume || !sound->volume->value) {
  1918. continue;
  1919. }
  1920. sound->volume->value->update (std::clamp (volume.value (), 0.0f, 1.0f), DynamicValue::UpdateSource::User);
  1921. sLog.debug ("Applying sound volume ", volume.value (), " to ", object->id, " - ", object->name);
  1922. }
  1923. }
  1924. void WallpaperApplication::setupSoundVolume () {
  1925. for (const auto& [background, info] : this->m_backgrounds) {
  1926. this->setupSoundVolumeForProject (*info);
  1927. }
  1928. }
  1929. void WallpaperApplication::applySoundVolumeHotswap (const std::map<std::string, std::string>& targets) {
  1930. for (const auto& [target, value] : targets) {
  1931. try {
  1932. this->m_context.settings.general.soundVolume[target] = parseFiniteFloat (value);
  1933. } catch (const std::exception&) {
  1934. sLog.error ("Hotswap: ignoring invalid sound-volume value: ", value);
  1935. }
  1936. }
  1937. for (const auto& [background, info] : this->m_backgrounds) {
  1938. this->setupSoundVolumeForProject (*info);
  1939. }
  1940. sLog.out ("Hotswap: applied sound volume live");
  1941. }
  1942. bool WallpaperApplication::applyPropertiesLive (const std::vector<std::string>& names) {
  1943. using WallpaperEngine::Render::Wallpapers::CScene;
  1944. using WallpaperEngine::Render::Wallpapers::CWeb;
  1945. const auto wallpaperOf = [this] (const std::string& screen) -> WallpaperEngine::Render::CWallpaper* {
  1946. if (!this->m_renderContext) {
  1947. return nullptr;
  1948. }
  1949. const auto& wallpapers = this->m_renderContext->getWallpapers ();
  1950. const auto it = wallpapers.find (screen);
  1951. return it != wallpapers.end () ? it->second.get () : nullptr;
  1952. };
  1953. for (const auto& name : names) {
  1954. for (const auto& [screen, info] : this->m_backgrounds) {
  1955. const auto property = info->properties.find (name);
  1956. if (property == info->properties.end ()) {
  1957. continue;
  1958. }
  1959. static const bool force = std::getenv ("LWE_FORCE_LIVE_PROPERTIES") != nullptr;
  1960. const auto* wallpaper = wallpaperOf (screen);
  1961. const bool scene = info->wallpaper->is<Scene> () && wallpaper != nullptr && wallpaper->is<CScene> ();
  1962. const bool web = info->wallpaper->is<Web> () && wallpaper != nullptr
  1963. && (wallpaper->is<CWeb> () || wallpaper->is<WallpaperEngine::Render::Wallpapers::CSplat> ());
  1964. if (!(scene || web) || (!force && !property->second->appliesLive ())) {
  1965. return false;
  1966. }
  1967. }
  1968. }
  1969. for (const auto& name : names) {
  1970. const auto& value = this->m_context.settings.general.properties.at (name);
  1971. for (const auto& [background, info] : this->m_backgrounds) {
  1972. if (const auto property = info->properties.find (name); property != info->properties.end ()) {
  1973. try {
  1974. property->second->update (value, DynamicValue::UpdateSource::User);
  1975. } catch (const std::exception& e) {
  1976. sLog.error ("Hotswap: ignoring invalid value for property ", name, ": ", e.what ());
  1977. }
  1978. }
  1979. }
  1980. sLog.out ("Hotswap: applied property ", name, " live");
  1981. }
  1982. if (this->m_renderContext && !names.empty ()) {
  1983. for (const auto& wallpaper : this->m_renderContext->getWallpapers () | std::views::values) {
  1984. if (wallpaper->is<CScene> ()) {
  1985. wallpaper->as<CScene> ()->getScriptEngine ().notifyUserPropertiesChanged (names);
  1986. } else if (wallpaper->is<CWeb> ()) {
  1987. wallpaper->as<CWeb> ()->setPropertyOverrides (this->m_context.settings.general.properties);
  1988. }
  1989. }
  1990. }
  1991. return true;
  1992. }
  1993. void WallpaperApplication::setupBrowser () {
  1994. // CEF allows one CefInitialize/CefShutdown per process, so only the --web-host process hosts it
  1995. if (!this->m_context.settings.general.webHost || this->m_browserContext) {
  1996. return;
  1997. }
  1998. this->m_browserContext = std::make_unique<WebBrowser::WebBrowserContext> (*this);
  1999. }
  2000. void WallpaperApplication::runWebHost () {
  2001. using namespace WallpaperEngine::WebBrowser;
  2002. using namespace WallpaperEngine::WebBrowser::IPC;
  2003. const auto backgroundIt = this->m_backgrounds.find ("default");
  2004. if (backgroundIt == this->m_backgrounds.end () || !backgroundIt->second->wallpaper->is<Web> ()) {
  2005. sLog.error ("--web-host requires a single Web wallpaper background, none found");
  2006. return;
  2007. }
  2008. if (!this->m_browserContext) {
  2009. sLog.error ("--web-host: CEF was not initialized (setupBrowser() found no Web project?)");
  2010. return;
  2011. }
  2012. const Project& project = *backgroundIt->second;
  2013. const Web& web = *project.wallpaper->as<Web> ();
  2014. const int width = static_cast<int> (this->m_context.settings.general.webHostWidth);
  2015. const int height = static_cast<int> (this->m_context.settings.general.webHostHeight);
  2016. if (width <= 0 || height <= 0) {
  2017. sLog.error ("--web-host: invalid --web-host-width/--web-host-height");
  2018. return;
  2019. }
  2020. auto* shm = attachSharedMemory (this->m_context.settings.general.webHostShm, width, height);
  2021. if (shm == nullptr) {
  2022. sLog.error ("--web-host: failed to attach shared memory ", this->m_context.settings.general.webHostShm);
  2023. return;
  2024. }
  2025. CefWindowInfo windowInfo;
  2026. windowInfo.SetAsWindowless (0);
  2027. // frames come when the main process asks, so they line up with what it presents
  2028. windowInfo.external_begin_frame_enabled = true;
  2029. const bool dmabufFrames = this->m_context.settings.general.webHostFrames == "dmabuf"
  2030. && this->m_context.settings.general.webHostSocket >= 0;
  2031. windowInfo.shared_texture_enabled = dmabufFrames;
  2032. CefBrowserSettings browserSettings;
  2033. // only a ceiling while external begin frames are on, the main process decides when a frame is produced
  2034. browserSettings.windowless_frame_rate = std::max (60, this->m_context.settings.render.maximumFPS);
  2035. const CefRefPtr<CEF::SharedMemoryRenderHandler> renderHandler
  2036. = new CEF::SharedMemoryRenderHandler (shm, dmabufFrames ? this->m_context.settings.general.webHostSocket : -1);
  2037. const CefRefPtr<CEF::BrowserClient> client = new CEF::BrowserClient (renderHandler, project.properties);
  2038. // the "w" prefix + workshop id host must match what the scheme handler factory expects to resolve
  2039. const std::string htmlURL = std::string (WPENGINE_SCHEME) + "://w" + project.workshopId + "/" + web.filename;
  2040. sLog.out ("--web-host: creating browser for ", htmlURL, " (pid ", static_cast<long> (getpid ()), ")");
  2041. const CefRefPtr<CefBrowser> browser
  2042. = CefBrowserHost::CreateBrowserSync (windowInfo, client, htmlURL, browserSettings, nullptr, nullptr);
  2043. if (!browser) {
  2044. sLog.error ("--web-host: failed to create the CEF browser");
  2045. shm->helperFailed.store (true, std::memory_order_release);
  2046. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  2047. return;
  2048. }
  2049. // a windowless browser is treated as backgrounded by default, which freezes the page's own timers and rAF
  2050. browser->GetHost ()->WasHidden (false);
  2051. shm->helperReady.store (true, std::memory_order_release);
  2052. Input::MouseClickStatus lastLeft = Input::Released;
  2053. Input::MouseClickStatus lastRight = Input::Released;
  2054. uint32_t lastFrameRequest = shm->frameRequestSeq.load (std::memory_order_acquire);
  2055. auto lastBeginFrame = std::chrono::steady_clock::now ();
  2056. int lastMouseX = -1;
  2057. int lastMouseY = -1;
  2058. uint32_t lastDesiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  2059. uint32_t lastDesiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  2060. bool lastAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  2061. bool resizeRequested = false;
  2062. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  2063. CEF::PageBridge bridge (browser, *shm, project.properties, *client);
  2064. while (!shm->quitRequested.load (std::memory_order_acquire)) {
  2065. // the heartbeat keeps the page alive while the main process isn't rendering (surface covered, no frame
  2066. // callbacks)
  2067. const auto now = std::chrono::steady_clock::now ();
  2068. const uint32_t frameRequest = shm->frameRequestSeq.load (std::memory_order_acquire);
  2069. if (frameRequest != lastFrameRequest || now - lastBeginFrame > std::chrono::milliseconds (100)) {
  2070. lastFrameRequest = frameRequest;
  2071. lastBeginFrame = now;
  2072. browser->GetHost ()->SendExternalBeginFrame ();
  2073. }
  2074. CefDoMessageLoopWork ();
  2075. const uint32_t desiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  2076. const uint32_t desiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  2077. // also compare with what CEF was last told, else a resize during CreateBrowserSync is lost (16x17 page)
  2078. const bool viewDiffers = std::clamp (desiredWidth, 1u, shm->maxWidth) != renderHandler->viewWidth ()
  2079. || std::clamp (desiredHeight, 1u, shm->maxHeight) != renderHandler->viewHeight ();
  2080. if (!viewDiffers) {
  2081. resizeRequested = false;
  2082. }
  2083. if (desiredWidth != lastDesiredWidth || desiredHeight != lastDesiredHeight
  2084. || (viewDiffers && !resizeRequested)) {
  2085. resizeRequested = viewDiffers;
  2086. lastDesiredWidth = desiredWidth;
  2087. lastDesiredHeight = desiredHeight;
  2088. browser->GetHost ()->WasResized ();
  2089. }
  2090. const bool desiredAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  2091. if (desiredAudioMuted != lastAudioMuted) {
  2092. lastAudioMuted = desiredAudioMuted;
  2093. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  2094. }
  2095. bridge.update ();
  2096. CefMouseEvent evt;
  2097. evt.x = static_cast<int> (shm->mouseX.load (std::memory_order_relaxed));
  2098. evt.y = static_cast<int> (shm->mouseY.load (std::memory_order_relaxed));
  2099. if (evt.x != lastMouseX || evt.y != lastMouseY) {
  2100. lastMouseX = evt.x;
  2101. lastMouseY = evt.y;
  2102. browser->GetHost ()->SendMouseMoveEvent (evt, false);
  2103. }
  2104. const auto left = static_cast<Input::MouseClickStatus> (shm->leftClick.load (std::memory_order_relaxed));
  2105. const auto right = static_cast<Input::MouseClickStatus> (shm->rightClick.load (std::memory_order_relaxed));
  2106. if (left != lastLeft) {
  2107. browser->GetHost ()->SendMouseClickEvent (
  2108. evt, CefBrowserHost::MouseButtonType::MBT_LEFT, left == Input::Released, 1
  2109. );
  2110. lastLeft = left;
  2111. }
  2112. if (right != lastRight) {
  2113. browser->GetHost ()->SendMouseClickEvent (
  2114. evt, CefBrowserHost::MouseButtonType::MBT_RIGHT, right == Input::Released, 1
  2115. );
  2116. lastRight = right;
  2117. }
  2118. shm->waitForFrameRequest (lastFrameRequest, 1);
  2119. }
  2120. browser->GetHost ()->CloseBrowser (true);
  2121. // CloseBrowser() is async, give it time to finish before CefShutdown()
  2122. for (int i = 0; i < 500 && !client->isClosed (); i++) {
  2123. CefDoMessageLoopWork ();
  2124. }
  2125. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  2126. }
  2127. void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename) const {
  2128. const int width = this->m_renderContext->getOutput ().getFullWidth ();
  2129. const int height = this->m_renderContext->getOutput ().getFullHeight ();
  2130. const bool vflip = this->m_renderContext->getOutput ().renderVFlip ();
  2131. const auto& wallpapers = this->m_renderContext->getWallpapers ();
  2132. struct ViewportCapture {
  2133. uint8_t* buffer;
  2134. int readWidth;
  2135. int readHeight;
  2136. int vpWidth;
  2137. int vpHeight;
  2138. int xoffset;
  2139. int yoffset;
  2140. float ustart, uend, vstart, vend;
  2141. };
  2142. std::vector<ViewportCapture> captures;
  2143. int currentXOffset = 0;
  2144. for (const auto& [screen, viewport] : this->m_renderContext->getOutput ().getViewports ()) {
  2145. viewport->makeCurrent ();
  2146. const int screenWidth = viewport->viewport.z - viewport->viewport.x;
  2147. std::vector<std::pair<std::string, glm::ivec4>> parts;
  2148. if (const auto* split = this->m_context.findSplitScreen (screen); split != nullptr) {
  2149. const auto& output = viewport->viewport;
  2150. for (const auto& slot : split->slots) {
  2151. const auto rect = this->m_renderContext->getSlotRect (slot);
  2152. if (!rect.has_value ()) {
  2153. continue;
  2154. }
  2155. const int top = vflip ? output.y + output.w - (rect->y + rect->w) : rect->y - output.y;
  2156. parts.emplace_back (slot, glm::ivec4 (rect->x - output.x, top, rect->z, rect->w));
  2157. }
  2158. } else {
  2159. parts.emplace_back (screen, glm::ivec4 (0, 0, screenWidth, viewport->viewport.w - viewport->viewport.y));
  2160. }
  2161. for (const auto& [part, area] : parts) {
  2162. const auto wallpaperIt = wallpapers.find (part);
  2163. if (wallpaperIt == wallpapers.end ()) {
  2164. sLog.error ("Cannot find wallpaper for screen ", part);
  2165. continue;
  2166. }
  2167. const auto& wallpaper = wallpaperIt->second;
  2168. const int vpWidth = area.z;
  2169. const int vpHeight = area.w;
  2170. // the default framebuffer is unreliable on some drivers (NVIDIA/Wayland)
  2171. glBindFramebuffer (GL_FRAMEBUFFER, wallpaper->renderAdjustedFramebuffer ());
  2172. glFinish ();
  2173. while (glGetError () != GL_NO_ERROR) { }
  2174. const int readWidth = wallpaper->getFramebufferWidth ();
  2175. const int readHeight = wallpaper->getFramebufferHeight ();
  2176. const auto bufferSize = readWidth * readHeight * 3;
  2177. auto* buffer = new uint8_t[bufferSize];
  2178. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  2179. if (GLEW_VERSION_4_5) {
  2180. glReadnPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer);
  2181. } else {
  2182. glReadPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, buffer);
  2183. }
  2184. glBindFramebuffer (GL_FRAMEBUFFER, 0);
  2185. if (const GLenum error = glGetError (); error != GL_NO_ERROR) {
  2186. sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error);
  2187. delete[] buffer;
  2188. continue;
  2189. }
  2190. const glm::vec4 uvs = wallpaper->getOutputUVs ();
  2191. captures.push_back (
  2192. { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset + area.x, area.y, uvs.x, uvs.y,
  2193. uvs.z, uvs.w }
  2194. );
  2195. }
  2196. if (viewport->single) {
  2197. currentXOffset += screenWidth;
  2198. }
  2199. }
  2200. const auto extension = filename.extension ();
  2201. const std::string extStr = extension.string ();
  2202. const auto encode = [captures, width, height, vflip, extStr, filename] () {
  2203. auto* bitmap = new uint8_t[width * height * 3] { 0 };
  2204. for (const auto& capture : captures) {
  2205. const float spanX = std::abs (capture.uend - capture.ustart) * capture.readWidth / capture.vpWidth;
  2206. const float spanY = std::abs (capture.vend - capture.vstart) * capture.readHeight / capture.vpHeight;
  2207. const int samplesX = std::max (1, static_cast<int> (std::lround (spanX)));
  2208. const int samplesY = std::max (1, static_cast<int> (std::lround (spanY)));
  2209. // sample from the output pixel's center, its left edge truncated 250/1920*1920 to 249
  2210. const auto firstSample = [] (const int pixel, const int size, const float start, const float end,
  2211. const int readSize, const int samples) {
  2212. const double center = start + (pixel + 0.5) / size * (end - start);
  2213. return static_cast<int> (std::floor (center * readSize - samples * 0.5 + 0.5));
  2214. };
  2215. for (int y = 0; y < capture.vpHeight; y++) {
  2216. for (int x = 0; x < capture.vpWidth; x++) {
  2217. const int srcX
  2218. = firstSample (x, capture.vpWidth, capture.ustart, capture.uend, capture.readWidth, samplesX);
  2219. const int srcY
  2220. = firstSample (y, capture.vpHeight, capture.vstart, capture.vend, capture.readHeight, samplesY);
  2221. int sum[3] = { 0, 0, 0 };
  2222. for (int sy = 0; sy < samplesY; sy++) {
  2223. const int row = std::clamp (srcY + sy, 0, capture.readHeight - 1);
  2224. for (int sx = 0; sx < samplesX; sx++) {
  2225. const int column = std::clamp (srcX + sx, 0, capture.readWidth - 1);
  2226. const int srcIdx = (row * capture.readWidth + column) * 3;
  2227. sum[0] += capture.buffer[srcIdx];
  2228. sum[1] += capture.buffer[srcIdx + 1];
  2229. sum[2] += capture.buffer[srcIdx + 2];
  2230. }
  2231. }
  2232. const int count = samplesX * samplesY;
  2233. const int xfinal = x + capture.xoffset;
  2234. // FBOs aren't flipped like the default framebuffer
  2235. const int yfinal = capture.yoffset + (vflip ? y : (capture.vpHeight - y - 1));
  2236. if (yfinal >= 0 && yfinal < height && xfinal >= 0 && xfinal < width) {
  2237. for (int channel = 0; channel < 3; channel++) {
  2238. bitmap[yfinal * width * 3 + xfinal * 3 + channel]
  2239. = static_cast<uint8_t> ((sum[channel] + count / 2) / count);
  2240. }
  2241. }
  2242. }
  2243. }
  2244. delete[] capture.buffer;
  2245. }
  2246. const auto write = [&] (const std::filesystem::path& target) {
  2247. if (extStr == ".bmp") {
  2248. return stbi_write_bmp (target.c_str (), width, height, 3, bitmap) != 0;
  2249. }
  2250. if (extStr == ".png") {
  2251. return stbi_write_png (target.c_str (), width, height, 3, bitmap, width * 3) != 0;
  2252. }
  2253. if (extStr == ".jpg" || extStr == ".jpeg") {
  2254. return stbi_write_jpg (target.c_str (), width, height, 3, bitmap, 100) != 0;
  2255. }
  2256. return false;
  2257. };
  2258. // whoever waits for the file never sees half of it
  2259. const std::filesystem::path partial = filename.string () + ".partial";
  2260. std::error_code error;
  2261. if (!write (partial) || (std::filesystem::rename (partial, filename, error), error)) {
  2262. std::filesystem::remove (partial, error);
  2263. write (filename);
  2264. }
  2265. delete[] bitmap;
  2266. };
  2267. this->m_screenshotWriter
  2268. = std::jthread ([encode] { WallpaperEngine::Logging::guardThread ("Screenshot writer", encode); });
  2269. }
  2270. void WallpaperApplication::setupOutput () {
  2271. const char* XDG_SESSION_TYPE = getenv ("XDG_SESSION_TYPE");
  2272. if (!XDG_SESSION_TYPE) {
  2273. sLog.exception (
  2274. "Cannot read environment variable XDG_SESSION_TYPE, window server detection failed. Please ensure proper "
  2275. "values are set"
  2276. );
  2277. }
  2278. std::string sessionType = XDG_SESSION_TYPE;
  2279. #ifdef ENABLE_WAYLAND
  2280. const auto drivers = sVideoFactories.getRegisteredDrivers ();
  2281. if (sessionType == "wayland" && this->m_context.settings.render.mode == ApplicationContext::DESKTOP_BACKGROUND
  2282. && getenv ("DISPLAY") != nullptr && std::ranges::find (drivers, "x11") != drivers.end ()
  2283. && WallpaperEngine::Desktop::compositorLacksLayerShell ()) {
  2284. sLog.out ("The compositor has no layer shell, drawing through XWayland into a background window instead");
  2285. setenv ("LWE_X11_BACKGROUND_WINDOW", "1", 0);
  2286. setenv ("LWE_XWAYLAND_FALLBACK", "1", 1);
  2287. unsetenv ("WAYLAND_DISPLAY");
  2288. setenv ("XDG_SESSION_TYPE", "x11", 1);
  2289. sessionType = "x11";
  2290. }
  2291. #endif
  2292. sLog.debug ("Checking for window servers: ");
  2293. for (const auto& windowServer : sVideoFactories.getRegisteredDrivers ()) {
  2294. sLog.debug ("\t", windowServer);
  2295. }
  2296. this->m_videoDriver
  2297. = sVideoFactories.createVideoDriver (this->m_context.settings.render.mode, sessionType, this->m_context, *this);
  2298. this->m_fullScreenDetector
  2299. = sVideoFactories.createFullscreenDetector (sessionType, this->m_context, *this->m_videoDriver);
  2300. }
  2301. void WallpaperApplication::setupAudio () {
  2302. const bool audioProcessingRequired = std::ranges::any_of (
  2303. this->m_backgrounds, [] (const std::pair<const std::string, ProjectUniquePtr>& pair) -> bool {
  2304. return pair.second->supportsAudioProcessing;
  2305. }
  2306. );
  2307. if (audioProcessingRequired && this->m_context.settings.audio.audioprocessing) {
  2308. this->m_audioRecorder
  2309. = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
  2310. this->m_audioCapturing = true;
  2311. } else {
  2312. this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PlaybackRecorder> ();
  2313. }
  2314. if (this->m_context.settings.audio.automute) {
  2315. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::PulseAudioPlayingDetector> (
  2316. this->m_context, *this->m_fullScreenDetector
  2317. );
  2318. } else {
  2319. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::AudioPlayingDetector> (
  2320. this->m_context, *this->m_fullScreenDetector
  2321. );
  2322. }
  2323. m_audioDriver = std::make_unique<WallpaperEngine::Audio::Drivers::SDLAudioDriver> (
  2324. this->m_context, *this->m_audioDetector, *this->m_audioRecorder
  2325. );
  2326. m_audioContext = std::make_unique<WallpaperEngine::Audio::AudioContext> (*m_audioDriver);
  2327. }
  2328. void WallpaperApplication::ensureAudioCapture (const Project& project) {
  2329. if (this->m_audioCapturing || !project.supportsAudioProcessing || !this->m_context.settings.audio.audioprocessing
  2330. || !this->m_audioDriver) {
  2331. return;
  2332. }
  2333. sLog.out ("Starting audio capture for ", project.title);
  2334. this->m_previousAudioRecorder = std::move (this->m_audioRecorder);
  2335. this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
  2336. this->m_audioDriver->setRecorder (*this->m_audioRecorder);
  2337. this->m_audioCapturing = true;
  2338. }
  2339. ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const std::string& screen) {
  2340. return const_cast<ApplicationContext::SpanGroup*> (std::as_const (*this).findSpanGroup (screen));
  2341. }
  2342. const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const std::string& screen) const {
  2343. if (!screen.starts_with ("span:")) {
  2344. return nullptr;
  2345. }
  2346. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  2347. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  2348. return &spanGroup;
  2349. }
  2350. }
  2351. return nullptr;
  2352. }
  2353. void WallpaperApplication::installWallpaper (
  2354. const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious,
  2355. const bool animate
  2356. ) try {
  2357. const auto& general = this->m_context.settings.general;
  2358. const auto& window = this->m_context.settings.render.window;
  2359. const auto* spanGroup = this->findSpanGroup (screen);
  2360. if (spanGroup == nullptr) {
  2361. const auto scalingIt = general.screenScalings.find (screen);
  2362. const auto clampIt = general.screenClamps.find (screen);
  2363. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  2364. *project.wallpaper, *this->m_renderContext, *this->m_audioContext, path,
  2365. scalingIt != general.screenScalings.end () ? scalingIt->second : window.scalingMode,
  2366. clampIt != general.screenClamps.end () ? clampIt->second : window.clamp,
  2367. this->resolveScreenRenderSize (screen)
  2368. );
  2369. wallpaper->setStorageScreen (this->storageScreen (screen));
  2370. wallpaper->setZoom (this->resolveScreenZoom (screen));
  2371. const auto offset = this->resolveScreenOffset (screen);
  2372. wallpaper->setOffset (offset.x, offset.y);
  2373. wallpaper->setAlignment (this->resolveScreenAlignment (screen));
  2374. wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
  2375. wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
  2376. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  2377. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSegments (
  2378. this->resolveScreenVideoSegments (screen)
  2379. );
  2380. }
  2381. this->m_renderContext->setWallpaper (screen, std::move (wallpaper), holdPrevious, animate);
  2382. return;
  2383. }
  2384. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  2385. glm::ivec2 low (INT_MAX);
  2386. glm::ivec2 high (INT_MIN);
  2387. for (const auto& name : spanGroup->screens) {
  2388. const auto it = viewports.find (name);
  2389. if (it == viewports.end ()) {
  2390. sLog.error ("Span group screen not found: ", name);
  2391. continue;
  2392. }
  2393. low = glm::min (low, it->second->globalPosition);
  2394. high = glm::max (high, it->second->globalPosition + it->second->logicalSize);
  2395. }
  2396. if (high.x <= low.x || high.y <= low.y) {
  2397. throw std::runtime_error ("none of the span group's screens is there");
  2398. }
  2399. std::shared_ptr<WallpaperEngine::Render::CWallpaper> wallpaper
  2400. = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  2401. *project.wallpaper, *this->m_renderContext, *this->m_audioContext, path, spanGroup->scaling,
  2402. spanGroup->clamp, high - low
  2403. );
  2404. wallpaper->setStorageScreen (this->storageScreen (screen));
  2405. wallpaper->setZoom (spanGroup->zoom);
  2406. wallpaper->setOffset (spanGroup->offset.x, spanGroup->offset.y);
  2407. wallpaper->setAlignment (spanGroup->alignment);
  2408. wallpaper->setCornerColor (spanGroup->cornerColor);
  2409. wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
  2410. wallpaper->setSpanInfo ({ .screens = spanGroup->screens, .totalBounds = { low, high - low } });
  2411. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  2412. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSegments (
  2413. this->resolveScreenVideoSegments (screen)
  2414. );
  2415. }
  2416. for (const auto& name : spanGroup->screens) {
  2417. this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious, animate);
  2418. }
  2419. } catch (const std::exception& e) {
  2420. throw std::runtime_error ("Cannot set up wallpaper '" + path.string () + "' on " + screen + ": " + e.what ());
  2421. }
  2422. void WallpaperApplication::prepareOutputs () {
  2423. m_renderContext
  2424. = std::make_unique<WallpaperEngine::Render::RenderContext> (*m_videoDriver, *this, *this->m_mediaSource);
  2425. for (const auto& [background, info] : this->m_backgrounds) {
  2426. if (this->findSpanGroup (background) == nullptr) {
  2427. this->installWallpaper (background, *info, this->resolveScreenBackgroundPath (background), false);
  2428. continue;
  2429. }
  2430. try {
  2431. this->installWallpaper (background, *info, this->resolveScreenBackgroundPath (background), false);
  2432. } catch (const std::runtime_error& e) {
  2433. sLog.error ("Skipping span group ", background, ": ", e.what ());
  2434. }
  2435. }
  2436. this->applyAudioPolicy ();
  2437. }
  2438. void WallpaperApplication::setupOpenGLDebugging () {
  2439. glDebugMessageCallback (CustomGLDebugCallback, nullptr);
  2440. glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
  2441. }
  2442. void WallpaperApplication::setup () {
  2443. this->setupOutput ();
  2444. // we_manager's LD_PRELOAD (system libEGL) has done its job here, but CEF's subprocesses would inherit it and WebGL
  2445. // silently stops painting only affects processes started after this point
  2446. unsetenv ("LD_PRELOAD");
  2447. this->setupAudio ();
  2448. this->prepareOutputs ();
  2449. this->setupOpenGLDebugging ();
  2450. this->updatePowerMonitor ();
  2451. if (this->m_context.settings.general.dumpStructure) {
  2452. auto prettyPrinter = Data::Dumpers::StringPrinter ();
  2453. for (const auto& [background, info] : this->m_renderContext->getWallpapers ()) {
  2454. prettyPrinter.printWallpaper (info->getWallpaperData ());
  2455. }
  2456. std::cout << prettyPrinter.str () << std::endl;
  2457. }
  2458. #if DEMOMODE
  2459. if (this->m_renderContext->getWallpapers ().size () > 1) {
  2460. sLog.exception ("Demo mode only supports one background");
  2461. }
  2462. this->m_demo.width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
  2463. this->m_demo.height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
  2464. this->m_demo.pixels.assign (static_cast<size_t> (this->m_demo.width) * this->m_demo.height * 3, 0);
  2465. this->m_demo.initialized = false;
  2466. this->m_demo.frame = 0;
  2467. #endif
  2468. }
  2469. void WallpaperApplication::render () {
  2470. static float rawTimeLast = 0.0f;
  2471. if (this->m_isPaused) {
  2472. usleep (FULLSCREEN_CHECK_WAIT_TIME);
  2473. m_videoDriver->dispatchWhilePaused ();
  2474. // automute keeps following other programs' sound, or the music stays on until the wallpaper resumes
  2475. if (this->m_audioDriver != nullptr) {
  2476. this->m_audioDriver->getAudioDetector ().update ();
  2477. }
  2478. const uint32_t reasons = this->pauseReasons ();
  2479. this->logPauseReasons (reasons);
  2480. // fullscreen pauses delay a hotswap, battery/idle pauses take it at once (it may lift them) and show one frame
  2481. const bool takeHotswap = this->m_hotswapRequested && (reasons & PauseWindows) == 0;
  2482. if (reasons != 0 && !takeHotswap && this->m_context.state.general.keepRunning) {
  2483. return;
  2484. }
  2485. this->m_showFrameWhilePaused = takeHotswap;
  2486. m_renderContext->setPause (false);
  2487. const auto pausedNow = std::chrono::steady_clock::now ();
  2488. const auto pausedDuration = pausedNow - this->m_pauseStart;
  2489. for (auto& [_, playlist] : this->m_activePlaylists) {
  2490. if (!playlist.definition.settings.updateOnPause) {
  2491. playlist.nextSwitch += pausedDuration;
  2492. playlist.lastUpdate += pausedDuration;
  2493. }
  2494. }
  2495. this->m_isPaused = false;
  2496. } else {
  2497. const time_t seconds = time (nullptr);
  2498. struct tm timeinfo {};
  2499. localtime_r (&seconds, &timeinfo);
  2500. g_Daytime = static_cast<float> ((timeinfo.tm_hour * 60) + timeinfo.tm_min) / (24.0f * 60.0f);
  2501. // LWE_FIXED_TIMESTEP=<seconds>: same step every frame so frame N always shows the same moment (regression
  2502. // renders)
  2503. static const float fixedTimestep = [] {
  2504. const char* value = std::getenv ("LWE_FIXED_TIMESTEP");
  2505. return value != nullptr ? std::max (0.0f, std::strtof (value, nullptr)) : 0.0f;
  2506. }();
  2507. const float rawTimeNow = m_videoDriver->getRenderTime ();
  2508. const float rawDelta = fixedTimestep > 0.0f ? fixedTimestep : rawTimeNow - rawTimeLast;
  2509. rawTimeLast = rawTimeNow;
  2510. g_TimeLast = g_Time;
  2511. if (!this->m_context.settings.render.freezeAnimations) {
  2512. // WE clamps a frame's step to [1e-4, 0.25] (2.8.42 sub_140110630), a stall doesn't make scripts catch up at
  2513. // once
  2514. g_Time += std::clamp (
  2515. std::min (rawDelta, 0.25f) * this->m_context.settings.render.playbackSpeed, 0.0001f, 0.25f
  2516. );
  2517. }
  2518. g_RealTime = fixedTimestep > 0.0f ? g_RealTime + fixedTimestep : rawTimeNow;
  2519. m_audioDriver->update (rawDelta * this->m_context.settings.render.playbackSpeed);
  2520. m_mediaSource->update ();
  2521. m_videoDriver->getInputContext ().update ();
  2522. // LWE_HOTSWAP_AT_FRAME=<n>: read the control file before frame n as if SIGUSR1 came in (regression tests)
  2523. static const int64_t hotswapFrame = [] {
  2524. const char* value = std::getenv ("LWE_HOTSWAP_AT_FRAME");
  2525. return value != nullptr ? std::strtoll (value, nullptr, 10) : -1;
  2526. }();
  2527. if (hotswapFrame >= 0 && m_videoDriver->getFrameCounter () == static_cast<uint64_t> (hotswapFrame)) {
  2528. this->m_hotswapRequested = true;
  2529. this->checkHotswapRequest ();
  2530. }
  2531. m_videoDriver->dispatchEventQueue ();
  2532. // spritesheetrefreshsync: sleep until the first image's next sprite frame (sub_140110630)
  2533. if (fixedTimestep <= 0.0f && !this->m_context.settings.render.freezeAnimations) {
  2534. std::optional<float> syncDelay;
  2535. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  2536. if (!wallpaper->is<WallpaperEngine::Render::Wallpapers::CScene> ()) {
  2537. continue;
  2538. }
  2539. if (const auto delay
  2540. = wallpaper->as<WallpaperEngine::Render::Wallpapers::CScene> ()->spriteSheetSyncDelay ();
  2541. delay.has_value ()) {
  2542. syncDelay = std::min (syncDelay.value_or (*delay), *delay);
  2543. }
  2544. }
  2545. if (syncDelay.has_value ()) {
  2546. float wait = *syncDelay;
  2547. const float speed = this->m_context.settings.render.playbackSpeed;
  2548. if (speed > 0.001f) {
  2549. wait /= speed;
  2550. }
  2551. std::this_thread::sleep_for (
  2552. std::chrono::milliseconds (static_cast<int> (std::min (wait, 0.25f) * 1000.0f))
  2553. );
  2554. }
  2555. }
  2556. const auto frameDone = std::chrono::steady_clock::now ();
  2557. const auto pause = this->m_framePacer.beginSleep (
  2558. frameDone - this->m_frameEnd, this->frameRateLimit (),
  2559. this->m_context.settings.render.frameLimiter == "fixed"
  2560. );
  2561. if (pause > std::chrono::nanoseconds::zero ()) {
  2562. std::this_thread::sleep_for (pause);
  2563. }
  2564. this->m_frameEnd = std::chrono::steady_clock::now ();
  2565. this->m_framePacer.endSleep (this->m_frameEnd - frameDone);
  2566. static const bool paceStats = std::getenv ("LWE_FRAME_STATS") != nullptr;
  2567. static auto paceWindowStart = this->m_frameEnd;
  2568. if (paceStats && this->m_frameEnd - paceWindowStart >= std::chrono::seconds (2)) {
  2569. const auto stats = this->m_framePacer.takeStats ();
  2570. const auto millis = [] (std::chrono::nanoseconds time) {
  2571. return std::chrono::duration<double, std::milli> (time).count ();
  2572. };
  2573. const double n = std::max (1, stats.frames);
  2574. sLog.out (
  2575. "FRAME-PACE: limit ", this->frameRateLimit (), " fps, loop ",
  2576. n * 1000.0 / millis (this->m_frameEnd - paceWindowStart), " fps | work avg ", millis (stats.work) / n,
  2577. " max ", millis (stats.workMax), " | sleep asked avg ", millis (stats.asked) / n, " got avg ",
  2578. millis (stats.slept) / n, " (worst overshoot ", millis (stats.overshootMax), ") | no sleep ",
  2579. stats.late, " of ", stats.frames, " frames (ms)"
  2580. );
  2581. paceWindowStart = this->m_frameEnd;
  2582. }
  2583. if (m_videoDriver->closeRequested ()) {
  2584. sLog.out ("Stop requested by driver");
  2585. this->m_context.state.general.keepRunning = false;
  2586. }
  2587. #if DEMOMODE
  2588. // wait a full render cycle before starting, giving video/web decoders time to set up
  2589. if (m_videoDriver->getFrameCounter () > (uint32_t)this->m_context.settings.render.maximumFPS) {
  2590. if (!this->m_demo.initialized) {
  2591. this->m_demo.width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
  2592. this->m_demo.height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
  2593. this->m_demo.pixels.assign (static_cast<size_t> (this->m_demo.width) * this->m_demo.height * 3, 0);
  2594. init_encoder ("output.webm", this->m_demo.width, this->m_demo.height);
  2595. this->m_demo.initialized = true;
  2596. }
  2597. glBindFramebuffer (
  2598. GL_FRAMEBUFFER, this->m_renderContext->getWallpapers ().begin ()->second->getWallpaperFramebuffer ()
  2599. );
  2600. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  2601. glReadPixels (
  2602. 0, 0, this->m_demo.width, this->m_demo.height, GL_RGB, GL_UNSIGNED_BYTE, this->m_demo.pixels.data ()
  2603. );
  2604. write_video_frame (this->m_demo.pixels.data ());
  2605. this->m_demo.frame++;
  2606. if (this->m_demo.frame >= FRAME_COUNT) {
  2607. this->m_context.state.general.keepRunning = false;
  2608. }
  2609. }
  2610. #endif
  2611. const uint32_t reasons = this->pauseReasons ();
  2612. if (reasons != 0 && !this->m_showFrameWhilePaused && this->m_context.state.general.keepRunning) {
  2613. this->logPauseReasons (reasons);
  2614. this->m_isPaused = true;
  2615. this->m_pauseStart = std::chrono::steady_clock::now ();
  2616. m_renderContext->setPause (true);
  2617. return;
  2618. }
  2619. if (reasons == 0) {
  2620. this->logPauseReasons (0);
  2621. }
  2622. this->m_showFrameWhilePaused = false;
  2623. }
  2624. this->checkHotswapRequest ();
  2625. this->updatePlaylists ();
  2626. if (!this->m_context.settings.screenshot.take || this->m_screenShotTaken == true) {
  2627. return;
  2628. }
  2629. if (this->m_videoDriver->getFrameCounter () < this->m_nextFrameScreenshot) {
  2630. return;
  2631. }
  2632. this->takeScreenshot (this->m_context.settings.screenshot.path);
  2633. this->m_screenShotTaken = true;
  2634. }
  2635. void WallpaperApplication::cleanup () {
  2636. sLog.out ("Stopping");
  2637. #if DEMOMODE
  2638. close_encoder ();
  2639. #endif
  2640. }
  2641. void WallpaperApplication::show () {
  2642. setup ();
  2643. if (const auto& leds = this->m_context.settings.leds; leds.enabled) {
  2644. WallpaperEngine::Led::sharedOutput ().start (
  2645. {
  2646. .host = leds.host,
  2647. .port = leds.port,
  2648. .brightness = { .boost = leds.boost, .factor = leds.brightness },
  2649. .reduceFps = leds.reduceFps,
  2650. }
  2651. );
  2652. }
  2653. while (this->m_context.state.general.keepRunning) {
  2654. render ();
  2655. }
  2656. WallpaperEngine::Led::sharedOutput ().stop ();
  2657. WallpaperEngine::Scripting::LocalStorage::flushAll ();
  2658. cleanup ();
  2659. }
  2660. void WallpaperApplication::update (Render::Drivers::Output::OutputViewport* viewport) {
  2661. m_renderContext->render (viewport);
  2662. }
  2663. void WallpaperApplication::signal (int signal) {
  2664. if (signal == SIGUSR1) {
  2665. this->m_hotswapRequested = true;
  2666. return;
  2667. }
  2668. // no logger here, it allocates and a signal mid-malloc would deadlock
  2669. static constexpr char message[] = "Stop requested by signal\n";
  2670. std::ignore = write (STDOUT_FILENO, message, sizeof (message) - 1);
  2671. this->m_context.state.general.keepRunning = false;
  2672. }
  2673. const std::map<std::string, ProjectUniquePtr>& WallpaperApplication::getBackgrounds () const {
  2674. return this->m_backgrounds;
  2675. }
  2676. ApplicationContext& WallpaperApplication::getContext () const { return this->m_context; }
  2677. const WallpaperEngine::Render::Drivers::Output::Output& WallpaperApplication::getOutput () const {
  2678. return this->m_renderContext->getOutput ();
  2679. }
  2680. void WallpaperApplication::setDestinationFramebuffer (GLuint framebuffer) {
  2681. this->m_destinationFramebuffer = framebuffer;
  2682. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  2683. wallpaper->setDestinationFramebuffer (framebuffer);
  2684. };
  2685. }
  2686. GLuint WallpaperApplication::getDestinationFramebuffer () const { return this->m_destinationFramebuffer; }