WallpaperApplication.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564
  1. #include "WallpaperApplication.h"
  2. #include <cstdlib>
  3. #include "Steam/FileSystem/FileSystem.h"
  4. #include "WallpaperEngine/Application/ApplicationState.h"
  5. #include "WallpaperEngine/Assets/AssetLoadException.h"
  6. #include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
  7. #include "WallpaperEngine/FileSystem/Container.h"
  8. #include "WallpaperEngine/Logging/Log.h"
  9. #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
  10. #include "WallpaperEngine/Render/RenderContext.h"
  11. #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
  12. #include "WallpaperEngine/Data/Dumpers/StringPrinter.h"
  13. #include "WallpaperEngine/Data/Parsers/ProjectParser.h"
  14. #include "WallpaperEngine/Data/Utils/AudioSensitivity.h"
  15. #include "WallpaperEngine/Data/Model/Property.h"
  16. #include "WallpaperEngine/Data/Model/Wallpaper.h"
  17. #include "WallpaperEngine/Debugging/CallStack.h"
  18. #include "WallpaperEngine/FileSystem/Adapters/MediaCover.h"
  19. #include "WallpaperEngine/Media/DBusMediaSource.h"
  20. #include "WallpaperEngine/WebBrowser/CEF/BrowserClient.h"
  21. #include "WallpaperEngine/WebBrowser/CEF/PageBridge.h"
  22. #include "WallpaperEngine/WebBrowser/CEF/SharedMemoryRenderHandler.h"
  23. #include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
  24. #include "include/cef_browser.h"
  25. #if DEMOMODE
  26. #include "recording.h"
  27. #endif /* DEMOMODE */
  28. #include <algorithm>
  29. #include <cctype>
  30. #include <chrono>
  31. #include <climits>
  32. #include <csignal>
  33. #include <ctime>
  34. #include <fstream>
  35. #include <numeric>
  36. #include <string_view>
  37. #include <unistd.h>
  38. #define STB_IMAGE_WRITE_IMPLEMENTATION
  39. #include <stb_image_write.h>
  40. #include <thread>
  41. #define FULLSCREEN_CHECK_WAIT_TIME 250
  42. float g_Time;
  43. float g_TimeLast;
  44. /** Unscaled wall-clock time, unaffected by --speed */
  45. float g_RealTime;
  46. float g_Daytime;
  47. using namespace WallpaperEngine::Assets;
  48. using namespace WallpaperEngine::Application;
  49. using namespace WallpaperEngine::Data::Model;
  50. using namespace WallpaperEngine::FileSystem;
  51. void CustomGLDebugCallback (
  52. GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam
  53. ) {
  54. // Widened from HIGH-only to catch MEDIUM/LOW too, while chasing the reload-corruption bug
  55. // (bloom-enabled scenes going black after an in-process wallpaper reload) - HIGH-only produced
  56. // nothing even with the driver's debug output confirmed reachable, so the failure isn't a GL
  57. // API validity error at all; it's a logic bug somewhere in scene reconstruction. Safe to narrow
  58. // back to HIGH-only once that's found, but low-severity output costs little in the meantime.
  59. if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
  60. return;
  61. }
  62. // libmpv's own internal renderer (not our code - shows up as libmpv.so/libgallium.so frames in
  63. // the call stack below) reuses a GL_STATIC_DRAW buffer with glBufferSubData every frame during
  64. // video playback, which the driver flags as a performance hint, not a correctness problem. It
  65. // fires on every single frame of every video wallpaper, drowning out anything else in this
  66. // (already widened) severity range.
  67. if (type == GL_DEBUG_TYPE_PERFORMANCE) {
  68. return;
  69. }
  70. sLog.error ("OpenGL error: ", message, ", type: ", type, ", id: ", id, ", severity: ", severity);
  71. std::vector<WallpaperEngine::Debugging::CallStack::CallInfo> callInfo;
  72. WallpaperEngine::Debugging::CallStack::GetCalls (callInfo);
  73. for (std::vector<WallpaperEngine::Debugging::CallStack::CallInfo>::size_type i = 0; i < callInfo.size (); ++i) {
  74. fprintf (
  75. stderr, "[%3lu] %15lu: %s in %s\n", callInfo.size () - i, callInfo[i].offset, callInfo[i].function.c_str (),
  76. callInfo[i].module.c_str ()
  77. );
  78. }
  79. }
  80. bool WallpaperApplication::isCefSubprocess () const {
  81. for (int i = 1; i < this->m_context.getArgc (); i++) {
  82. if (std::string_view (this->m_context.getArgv ()[i]).starts_with ("--type=")) {
  83. return true;
  84. }
  85. }
  86. return false;
  87. }
  88. WallpaperApplication::WallpaperApplication (ApplicationContext& context) : m_context (context) {
  89. this->initializeSubsystems ();
  90. try {
  91. this->loadBackgrounds ();
  92. } catch (const std::exception& e) {
  93. if (!this->isCefSubprocess ()) {
  94. throw;
  95. }
  96. // CEF re-execs this binary for its own subprocesses with a reconstructed argv that doesn't
  97. // always resolve to a loadable background. Must still reach setupBrowser() below regardless
  98. // - that's what calls CefExecuteProcess() to hand off into Chromium's subprocess entrypoint;
  99. // skipping it here leaves CEF's IPC handshake incomplete, which reads as a crashed subprocess
  100. // and gets retried, turning one web wallpaper into several stray processes.
  101. sLog.error ("Skipping background load for CEF subprocess re-exec: ", e.what ());
  102. }
  103. this->setupProperties ();
  104. this->setupAudioSensitivity ();
  105. this->setupSoundVolume ();
  106. this->listObjects ();
  107. this->listEffects ();
  108. this->listAudioObjects ();
  109. this->setupBrowser ();
  110. this->initializePlaylists ();
  111. }
  112. void WallpaperApplication::initializeSubsystems () {
  113. m_mediaSource = std::make_unique<WallpaperEngine::Media::DBusMediaSource> (std::chrono::milliseconds (2000));
  114. }
  115. AssetLocatorUniquePtr
  116. WallpaperApplication::setupAssetLocator (const std::string& bg, const std::filesystem::path& overlay) const {
  117. auto container = std::make_unique<Container> ();
  118. const std::filesystem::path path = bg;
  119. container->registerAdapterFactory (std::make_unique<MediaCoverFactory> (*this->m_mediaSource));
  120. container->mount ("$mediaThumbnail", "$mediaThumbnail");
  121. container->mount (path, "/");
  122. try {
  123. container->mount (path / "scene.pkg", "/");
  124. } catch (std::runtime_error&) { }
  125. try {
  126. container->mount (path / "gifscene.pkg", "/");
  127. } catch (std::runtime_error&) { }
  128. if (!overlay.empty ()) {
  129. container->mount (overlay, "/");
  130. }
  131. try {
  132. container->mount (this->m_context.settings.general.assets, "/");
  133. } catch (std::runtime_error&) {
  134. sLog.exception ("Cannot find a valid assets folder, resolved to ", this->m_context.settings.general.assets);
  135. }
  136. try {
  137. container->mount (std::filesystem::current_path (), "/");
  138. } catch (std::runtime_error&) { }
  139. auto& vfs = container->getVFS ();
  140. // Had to get a little creative with the effects to achieve the same bloom effect without any custom code:
  141. // these virtual files are loaded by an image in the scene that takes the current _rt_FullFrameBuffer and
  142. // applies the bloom effect to render it out to the screen.
  143. vfs.add (
  144. "effects/wpenginelinux/bloomeffect.json",
  145. { { "name", "camerabloom_wpengine_linux" },
  146. { "group", "wpengine_linux_camera" },
  147. { "dependencies", JSON::array () },
  148. {
  149. "passes",
  150. JSON::array (
  151. { { { "material", "materials/util/downsample_quarter_bloom.json" },
  152. { "target", "_rt_4FrameBuffer" },
  153. { "bind", JSON::array ({ { { "name", "_rt_FullFrameBuffer" }, { "index", 0 } } }) } },
  154. { { "material", "materials/util/downsample_eighth_blur_v.json" },
  155. { "target", "_rt_8FrameBuffer" },
  156. { "bind", JSON::array ({ { { "name", "_rt_4FrameBuffer" }, { "index", 0 } } }) } },
  157. { { "material", "materials/util/blur_h_bloom.json" },
  158. { "target", "_rt_Bloom" },
  159. { "bind", JSON::array ({ { { "name", "_rt_8FrameBuffer" }, { "index", 0 } } }) } },
  160. { { "material", "materials/util/combine.json" },
  161. { "target", "_rt_FullFrameBuffer" },
  162. { "bind",
  163. JSON::array (
  164. { { { "name", "_rt_imageLayerComposite_-1_a" }, { "index", 0 } },
  165. { { "name", "_rt_Bloom" }, { "index", 1 } } }
  166. ) } } }
  167. ),
  168. } }
  169. );
  170. // Wastes a render pass on an image element that exists only to host the bloom material above
  171. // fullscreen, so it covers the whole scene buffer whatever part of the scene the output shows
  172. vfs.add ("models/wpenginelinux.json", { { "material", "materials/wpenginelinux.json" }, { "fullscreen", true } });
  173. vfs.add (
  174. "materials/wpenginelinux.json",
  175. { { "passes",
  176. JSON::array (
  177. { { { "blending", "normal" },
  178. { "cullmode", "nocull" },
  179. { "depthtest", "disabled" },
  180. { "depthwrite", "disabled" },
  181. { "shader", "genericimage2" },
  182. { "textures", JSON::array ({ "_rt_FullFrameBuffer" }) } } }
  183. ) } }
  184. );
  185. vfs.add (
  186. "shaders/commands/copy.frag",
  187. "uniform sampler2D g_Texture0;\n"
  188. "in vec2 v_TexCoord;\n"
  189. "void main () {\n"
  190. "out_FragColor = texture (g_Texture0, v_TexCoord);\n"
  191. "}"
  192. );
  193. vfs.add (
  194. "shaders/commands/copy.vert",
  195. "in vec3 a_Position;\n"
  196. "in vec2 a_TexCoord;\n"
  197. "out vec2 v_TexCoord;\n"
  198. "void main () {\n"
  199. "gl_Position = vec4 (a_Position, 1.0);\n"
  200. "v_TexCoord = a_TexCoord;\n"
  201. "}"
  202. );
  203. return std::make_unique<AssetLocator> (std::move (container));
  204. }
  205. void WallpaperApplication::loadBackgrounds () {
  206. if (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  207. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW) {
  208. auto path = this->m_context.settings.general.defaultBackground;
  209. if (this->m_context.settings.general.defaultPlaylist.has_value ()
  210. && !this->m_context.settings.general.defaultPlaylist->items.empty ()) {
  211. path = this->m_context.settings.general.defaultPlaylist->items.front ();
  212. }
  213. this->m_backgrounds["default"] = this->loadBackground (path);
  214. return;
  215. }
  216. for (const auto& [screen, path] : this->m_context.settings.general.screenBackgrounds) {
  217. // skip span group synthetic keys here, they're handled below
  218. if (screen.rfind ("span:", 0) == 0) {
  219. continue;
  220. }
  221. if (path.empty ()) {
  222. this->m_backgrounds[screen] = this->loadBackground (this->m_context.settings.general.defaultBackground);
  223. } else {
  224. this->m_backgrounds[screen] = this->loadBackground (path);
  225. }
  226. }
  227. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  228. if (spanGroup.screens.empty ()) {
  229. continue;
  230. }
  231. std::filesystem::path bgPath = spanGroup.background;
  232. if (bgPath.empty ()) {
  233. bgPath = this->m_context.settings.general.defaultBackground;
  234. }
  235. // "span:" + first screen's name is the convention used as the group key
  236. const std::string groupKey = "span:" + spanGroup.screens.front ();
  237. this->m_backgrounds[groupKey] = this->loadBackground (bgPath);
  238. }
  239. }
  240. WallpaperApplication::ProjectSource WallpaperApplication::openProjectSource (const std::string& path) const {
  241. auto container = this->setupAssetLocator (path);
  242. auto json = WallpaperEngine::Data::JSON::JSON::parseAsset (container->readString ("project.json"));
  243. if (json.contains ("file") || !json.contains ("dependency")) {
  244. return { std::move (container), std::move (json), std::nullopt };
  245. }
  246. const auto dependency = json.at ("dependency");
  247. const auto dependencyId = dependency.is_string () ? dependency.get<std::string> () : dependency.dump ();
  248. std::filesystem::path presetDir = path;
  249. if (!presetDir.has_filename ()) {
  250. presetDir = presetDir.parent_path ();
  251. }
  252. const auto baseDir = presetDir.parent_path () / dependencyId;
  253. if (!std::filesystem::exists (baseDir / "project.json")) {
  254. sLog.exception ("Preset ", path, " requires wallpaper ", dependencyId, " which is not installed");
  255. }
  256. auto baseContainer = this->setupAssetLocator (baseDir.string (), presetDir);
  257. auto baseJson = WallpaperEngine::Data::JSON::JSON::parseAsset (baseContainer->readString ("project.json"));
  258. return { std::move (baseContainer), std::move (baseJson), json.optional ("preset") };
  259. }
  260. namespace {
  261. std::optional<float> presetNumber (const WallpaperEngine::Data::JSON::JSON& preset, const char* key) {
  262. const auto it = preset.find (key);
  263. if (it == preset.end ()) {
  264. return std::nullopt;
  265. }
  266. if (it->is_number ()) {
  267. return it->get<float> ();
  268. }
  269. if (it->is_string ()) {
  270. try {
  271. return std::stof (it->get<std::string> ());
  272. } catch (const std::exception&) { }
  273. }
  274. return std::nullopt;
  275. }
  276. std::optional<bool> presetBool (const WallpaperEngine::Data::JSON::JSON& preset, const char* key) {
  277. const auto it = preset.find (key);
  278. if (it == preset.end ()) {
  279. return std::nullopt;
  280. }
  281. if (it->is_boolean ()) {
  282. return it->get<bool> ();
  283. }
  284. if (it->is_number ()) {
  285. return it->get<float> () != 0.0f;
  286. }
  287. if (it->is_string ()) {
  288. return it->get<std::string> () == "true" || it->get<std::string> () == "1";
  289. }
  290. return std::nullopt;
  291. }
  292. /** Wallpaper Engine's own settings a preset can carry, see wallpaper64.exe sub_140181F30 */
  293. ImageAdjustments parseImageAdjustments (const WallpaperEngine::Data::JSON::JSON& preset) {
  294. ImageAdjustments result {
  295. .colorEnabled = presetBool (preset, "wec_e"),
  296. .brightness = presetNumber (preset, "wec_brs"),
  297. .contrast = presetNumber (preset, "wec_con"),
  298. .saturation = presetNumber (preset, "wec_sa"),
  299. .hue = presetNumber (preset, "wec_hue"),
  300. .filter = std::nullopt,
  301. .filterStrength = presetNumber (preset, "wcc_amt"),
  302. .flipHorizontal = presetBool (preset, "alignmentfliph"),
  303. };
  304. if (const auto it = preset.find ("wcc_v"); it != preset.end () && it->is_string ()) {
  305. result.filter = it->get<std::string> ();
  306. }
  307. return result;
  308. }
  309. } // namespace
  310. void WallpaperApplication::applyPreset (
  311. Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir
  312. ) {
  313. project.imageAdjustments = parseImageAdjustments (preset);
  314. for (const auto& entry : preset.items ()) {
  315. const auto property = project.properties.find (entry.key ());
  316. // wec_* and friends are Wallpaper Engine's own settings (read above), not wallpaper properties
  317. if (property == project.properties.end () || entry.value ().is_null ()) {
  318. continue;
  319. }
  320. const auto& value = entry.value ();
  321. std::string text;
  322. if (value.is_string ()) {
  323. text = value.get<std::string> ();
  324. } else if (value.is_boolean ()) {
  325. text = value.get<bool> () ? "true" : "false";
  326. } else {
  327. text = value.dump ();
  328. }
  329. // file and directory properties hold paths relative to the preset folder, pages expect an absolute one
  330. if (const auto* file = dynamic_cast<const PropertyFile*> (property->second.get ());
  331. file != nullptr && !text.empty () && std::filesystem::path (text).is_relative ()) {
  332. const auto candidate = presetDir / text;
  333. if (file->isDirectory () ? std::filesystem::is_directory (candidate)
  334. : std::filesystem::is_regular_file (candidate)) {
  335. text = candidate.string ();
  336. }
  337. }
  338. // a preset is someone else's content, only the user assigns what a shortcut opens
  339. if (property->second->is<PropertyUserShortcut> ()) {
  340. continue;
  341. }
  342. if (auto* combo = dynamic_cast<PropertyCombo*> (property->second.get ()); combo != nullptr) {
  343. combo->allowValue (text);
  344. }
  345. try {
  346. property->second->update (text, DynamicValue::UpdateSource::User);
  347. } catch (const std::exception& e) {
  348. sLog.error ("Cannot apply preset value for ", entry.key (), ": ", e.what ());
  349. }
  350. }
  351. }
  352. ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
  353. auto [container, json, preset] = this->openProjectSource (bg);
  354. // reset screenshot state so a background change (e.g. playlist advance) can screenshot again
  355. if (this->m_context.settings.screenshot.take) {
  356. this->m_nextFrameScreenshot = this->m_context.settings.screenshot.delay;
  357. if (this->m_videoDriver != nullptr) {
  358. this->m_nextFrameScreenshot += this->m_videoDriver->getFrameCounter ();
  359. }
  360. this->m_screenShotTaken = false;
  361. }
  362. auto project = WallpaperEngine::Data::Parsers::ProjectParser::parse (json, std::move (container));
  363. if (preset.has_value ()) {
  364. std::filesystem::path presetDir = bg;
  365. if (!presetDir.has_filename ()) {
  366. presetDir = presetDir.parent_path ();
  367. }
  368. applyPreset (*project, *preset, presetDir);
  369. }
  370. return project;
  371. }
  372. std::vector<std::size_t>
  373. WallpaperApplication::buildPlaylistOrder (const ApplicationContext::PlaylistDefinition& definition) {
  374. std::vector<std::size_t> order (definition.items.size ());
  375. std::iota (order.begin (), order.end (), 0);
  376. if (definition.settings.order == "random") {
  377. std::shuffle (order.begin (), order.end (), this->m_playlistRng);
  378. }
  379. return order;
  380. }
  381. void WallpaperApplication::initializePlaylists () {
  382. const bool hasDefaultPlaylist = this->m_context.settings.general.defaultPlaylist.has_value ();
  383. const bool hasScreenPlaylists = !this->m_context.settings.general.screenPlaylists.empty ();
  384. if (!hasDefaultPlaylist && !hasScreenPlaylists) {
  385. return;
  386. }
  387. const auto now = std::chrono::steady_clock::now ();
  388. auto registerPlaylist = [this, now] (
  389. const std::string& key, const ApplicationContext::PlaylistDefinition& playlist,
  390. std::optional<std::filesystem::path> currentPath
  391. ) {
  392. if (playlist.items.empty ()) {
  393. return;
  394. }
  395. ActivePlaylist state;
  396. state.definition = playlist;
  397. state.order = this->buildPlaylistOrder (playlist);
  398. if (state.order.empty ()) {
  399. return;
  400. }
  401. if (currentPath.has_value ()) {
  402. state.orderIndex = 0;
  403. for (std::size_t i = 0; i < state.order.size (); i++) {
  404. if (playlist.items[state.order[i]] == currentPath.value ()) {
  405. state.orderIndex = i;
  406. break;
  407. }
  408. }
  409. }
  410. const uint32_t delayMinutes = std::max<uint32_t> (1, state.definition.settings.delayMinutes);
  411. state.nextSwitch = now + std::chrono::minutes (delayMinutes);
  412. state.lastUpdate = now;
  413. this->m_activePlaylists.insert_or_assign (key, std::move (state));
  414. };
  415. if (hasDefaultPlaylist
  416. && (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  417. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW)) {
  418. const auto& playlist = this->m_context.settings.general.defaultPlaylist.value ();
  419. const auto currentPath = playlist.items.empty ()
  420. ? std::optional<std::filesystem::path> { this->m_context.settings.general.defaultBackground }
  421. : std::optional<std::filesystem::path> { playlist.items.front () };
  422. registerPlaylist ("default", playlist, currentPath);
  423. }
  424. for (const auto& [screen, playlist] : this->m_context.settings.general.screenPlaylists) {
  425. const auto current = this->m_context.settings.general.screenBackgrounds.find (screen);
  426. const auto currentPath = current != this->m_context.settings.general.screenBackgrounds.end ()
  427. ? std::optional<std::filesystem::path> { current->second }
  428. : std::nullopt;
  429. registerPlaylist (screen, playlist, currentPath);
  430. }
  431. }
  432. bool WallpaperApplication::makeAnyViewportCurrent () const {
  433. if (!this->m_renderContext) {
  434. return false;
  435. }
  436. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  437. if (viewports.empty ()) {
  438. return false;
  439. }
  440. viewports.begin ()->second->makeCurrent ();
  441. return true;
  442. }
  443. bool WallpaperApplication::preflightWallpaper (const std::string& path) {
  444. try {
  445. // avoid mutating state, just ensure project.json parses
  446. const auto source = this->openProjectSource (path);
  447. const auto& json = source.json;
  448. if (!json.contains ("type") || !json.contains ("file")) {
  449. sLog.error ("Preflight failed for ", path, ": missing required fields");
  450. return false;
  451. }
  452. return true;
  453. } catch (const std::exception& e) {
  454. sLog.error ("Preflight failed for ", path, ": ", e.what ());
  455. return false;
  456. }
  457. }
  458. bool WallpaperApplication::selectNextCandidate (ActivePlaylist& playlist, std::size_t& outOrderIndex) {
  459. if (playlist.order.empty ()) {
  460. return false;
  461. }
  462. std::size_t attempts = 0;
  463. std::size_t candidateOrderIndex = outOrderIndex;
  464. while (attempts < playlist.order.size ()) {
  465. const auto candidateIndex = playlist.order[candidateOrderIndex];
  466. if (!playlist.failedIndices.contains (candidateIndex)) {
  467. outOrderIndex = candidateOrderIndex;
  468. return true;
  469. }
  470. attempts++;
  471. candidateOrderIndex = (candidateOrderIndex + 1) % playlist.order.size ();
  472. }
  473. return false;
  474. }
  475. void WallpaperApplication::advancePlaylist (
  476. const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
  477. ) {
  478. if (playlist.order.empty ()) {
  479. return;
  480. }
  481. playlist.orderIndex = (playlist.orderIndex + 1) % playlist.order.size ();
  482. if (playlist.orderIndex == 0 && playlist.definition.settings.order == "random") {
  483. std::shuffle (playlist.order.begin (), playlist.order.end (), this->m_playlistRng);
  484. }
  485. std::size_t candidateOrderIndex = playlist.orderIndex;
  486. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  487. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  488. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  489. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  490. return;
  491. }
  492. const auto candidateIndex = playlist.order[candidateOrderIndex];
  493. const auto& candidatePath = playlist.definition.items[candidateIndex];
  494. if (!this->preflightWallpaper (candidatePath.string ())) {
  495. playlist.failedIndices.insert (candidateIndex);
  496. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  497. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  498. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  499. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  500. return;
  501. }
  502. }
  503. playlist.orderIndex = candidateOrderIndex;
  504. const auto& nextPath = playlist.definition.items[playlist.order[playlist.orderIndex]];
  505. bool loaded = false;
  506. try {
  507. if (!this->makeAnyViewportCurrent ()) {
  508. sLog.error ("Cannot switch playlist on ", screen, ": no active viewport");
  509. throw std::runtime_error ("No viewport available");
  510. }
  511. auto project = this->loadBackground (nextPath.string ());
  512. this->setupPropertiesForProject (*project);
  513. this->ensureAudioCapture (*project);
  514. // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
  515. auto outgoing = std::move (this->m_backgrounds[screen]);
  516. this->m_backgrounds[screen] = std::move (project);
  517. try {
  518. const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
  519. const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
  520. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  521. ? scalingIt->second
  522. : this->m_context.settings.render.window.scalingMode;
  523. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  524. ? clampIt->second
  525. : this->m_context.settings.render.window.clamp;
  526. if (this->m_renderContext) {
  527. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  528. *this->m_backgrounds[screen]->wallpaper, *this->m_renderContext, *this->m_audioContext, nextPath,
  529. scaling, clamp, this->resolveScreenRenderSize (screen)
  530. );
  531. wallpaper->setZoom (this->resolveScreenZoom (screen));
  532. const auto offset = this->resolveScreenOffset (screen);
  533. wallpaper->setOffset (offset.x, offset.y);
  534. wallpaper->setAlignment (this->resolveScreenAlignment (screen));
  535. wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
  536. wallpaper->setImageAdjustments (
  537. this->resolveScreenImageAdjustments (screen, *this->m_backgrounds[screen])
  538. );
  539. this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
  540. this->applyAudioPolicy ();
  541. }
  542. } catch (...) {
  543. project = std::move (this->m_backgrounds[screen]);
  544. this->m_backgrounds[screen] = std::move (outgoing);
  545. if (this->m_renderContext) {
  546. this->m_renderContext->pruneTextures ();
  547. }
  548. throw;
  549. }
  550. this->m_context.settings.general.screenBackgrounds[screen] = nextPath;
  551. loaded = true;
  552. } catch (const std::exception& e) {
  553. sLog.error ("Failed to advance playlist on ", screen, ": ", e.what ());
  554. }
  555. if (!loaded) {
  556. playlist.failedIndices.insert (playlist.order[playlist.orderIndex]);
  557. // Keep current position; next timer tick will retry advancement
  558. sLog.error ("Failed to load wallpaper for ", screen, ", will retry on next cycle");
  559. }
  560. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  561. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  562. }
  563. void WallpaperApplication::updatePlaylists () {
  564. if (this->m_activePlaylists.empty ()) {
  565. return;
  566. }
  567. const auto now = std::chrono::steady_clock::now ();
  568. for (auto& [screen, playlist] : this->m_activePlaylists) {
  569. playlist.lastUpdate = now;
  570. if (playlist.definition.settings.mode != "timer") {
  571. continue;
  572. }
  573. if (playlist.definition.items.size () <= 1) {
  574. continue;
  575. }
  576. if (now < playlist.nextSwitch) {
  577. continue;
  578. }
  579. this->advancePlaylist (screen, playlist, now);
  580. }
  581. }
  582. namespace {
  583. /** Everything a control-file request can carry; any field left unset means "don't touch this" */
  584. struct HotswapRequest {
  585. std::optional<std::string> path;
  586. /** True once a "layers=1" line was seen, meaning disabledObjects/enabledObjects below are a full replacement */
  587. bool layersProvided = false;
  588. std::vector<std::string> disabledObjects;
  589. std::vector<std::string> enabledObjects;
  590. /** True once at least one "property=name=value" line was seen */
  591. bool propertiesProvided = false;
  592. std::map<std::string, std::string> properties;
  593. std::optional<int> volume;
  594. /** frame rate limit, see --fps */
  595. std::optional<int> fps;
  596. /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
  597. std::optional<std::string> xray;
  598. /** "stretch"/"fit"/"fill"/"center"/"default" */
  599. std::optional<std::string> scaling;
  600. /** floating-point zoom factor layered on top of scaling, e.g. "1.5" */
  601. std::optional<std::string> zoom;
  602. /** "X,Y" offset re-center, each axis in [-1, 1], e.g. "0.5,-1" */
  603. std::optional<std::string> offset;
  604. std::optional<std::string> alignment;
  605. /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
  606. std::optional<std::string> disableParallax;
  607. /** "on"/"off" (also "1"/"0"/"true"/"false"), see --expand-canvas. Baked in at scene build, so it reloads */
  608. std::optional<std::string> expandCanvas;
  609. /** hex RGB/RGBA color, e.g. "000000" or "#1a1a1aff" */
  610. std::optional<std::string> cornerColor;
  611. /** image-filter/image-filter-strength/brightness/contrast/saturation/hue/color-options/flip, see --image-filter */
  612. ImageAdjustments imageAdjustments;
  613. bool imageAdjustmentsProvided = false;
  614. /** floating-point playback speed multiplier, e.g. "0.5" */
  615. std::optional<std::string> speed;
  616. /** screen name to restrict audio to, or "" to clear the restriction, see --audio-screen */
  617. std::optional<std::string> audioScreen;
  618. /** 0-128, see --ambient-volume */
  619. std::optional<std::string> ambientVolume;
  620. /** True once at least one "audio-sensitivity=id=multiplier" line was seen */
  621. bool audioSensitivityProvided = false;
  622. std::map<std::string, std::string> audioSensitivity;
  623. /** True once at least one "sound-volume=id=volume" line was seen */
  624. bool soundVolumeProvided = false;
  625. std::map<std::string, std::string> soundVolume;
  626. };
  627. std::string trimHotswapToken (const std::string& value) {
  628. std::size_t begin = 0;
  629. std::size_t end = value.size ();
  630. while (begin < end && std::isspace (static_cast<unsigned char> (value[begin]))) {
  631. begin++;
  632. }
  633. while (end > begin && std::isspace (static_cast<unsigned char> (value[end - 1]))) {
  634. end--;
  635. }
  636. return value.substr (begin, end - begin);
  637. }
  638. /**
  639. * Parses the control file. Supports the original bare-path-on-one-line format for backwards
  640. * compatibility, plus key=value lines (path/layers/disable-object/enable-object/volume/xray/scaling/zoom/
  641. * offset/disable-parallax/corner-color/image-filter/image-filter-strength/brightness/contrast/saturation/hue/
  642. * color-options/flip/speed/audio-screen/ambient-volume/property) so a single request can
  643. * carry more than just the background path. "property=name=value" (repeatable) carries
  644. * --set-property-equivalent overrides.
  645. */
  646. HotswapRequest parseHotswapRequest (std::istream& file) {
  647. HotswapRequest request;
  648. std::string rawLine;
  649. while (std::getline (file, rawLine)) {
  650. const std::string line = trimHotswapToken (rawLine);
  651. if (line.empty ()) {
  652. continue;
  653. }
  654. const auto separator = line.find ('=');
  655. if (separator == std::string::npos) {
  656. // legacy format: the whole line is the new background path
  657. if (!request.path.has_value ()) {
  658. request.path = line;
  659. }
  660. continue;
  661. }
  662. const std::string key = trimHotswapToken (line.substr (0, separator));
  663. const std::string value = trimHotswapToken (line.substr (separator + 1));
  664. if (key == "path") {
  665. request.path = value;
  666. } else if (key == "layers") {
  667. request.layersProvided = true;
  668. } else if (key == "disable-object") {
  669. request.layersProvided = true;
  670. request.disabledObjects.push_back (value);
  671. } else if (key == "enable-object") {
  672. request.layersProvided = true;
  673. request.enabledObjects.push_back (value);
  674. } else if (key == "volume") {
  675. try {
  676. request.volume = std::stoi (value);
  677. } catch (const std::exception&) {
  678. sLog.error ("Hotswap: ignoring invalid volume value: ", value);
  679. }
  680. } else if (key == "fps") {
  681. try {
  682. request.fps = std::stoi (value);
  683. } catch (const std::exception&) {
  684. sLog.error ("Hotswap: ignoring invalid fps value: ", value);
  685. }
  686. } else if (key == "xray") {
  687. request.xray = value;
  688. } else if (key == "scaling") {
  689. request.scaling = value;
  690. } else if (key == "zoom") {
  691. request.zoom = value;
  692. } else if (key == "offset") {
  693. request.offset = value;
  694. } else if (key == "alignment") {
  695. request.alignment = value;
  696. } else if (key == "disable-parallax") {
  697. request.disableParallax = value;
  698. } else if (key == "expand-canvas") {
  699. request.expandCanvas = value;
  700. } else if (key == "corner-color") {
  701. request.cornerColor = value;
  702. } else if (key == "image-filter") {
  703. request.imageAdjustments.filter = value == "none" ? "" : value;
  704. request.imageAdjustmentsProvided = true;
  705. } else if (key == "color-options" || key == "flip") {
  706. const bool enable = value == "on" || value == "1" || value == "true";
  707. if (!enable && value != "off" && value != "0" && value != "false") {
  708. sLog.error ("Hotswap: ignoring invalid ", key, " value: ", value);
  709. } else {
  710. (key == "flip" ? request.imageAdjustments.flipHorizontal : request.imageAdjustments.colorEnabled)
  711. = enable;
  712. request.imageAdjustmentsProvided = true;
  713. }
  714. } else if (
  715. key == "image-filter-strength" || key == "brightness" || key == "contrast" || key == "saturation"
  716. || key == "hue"
  717. ) {
  718. float amount;
  719. try {
  720. amount = std::clamp (std::stof (value), 0.0f, 100.0f);
  721. } catch (const std::exception&) {
  722. sLog.error ("Hotswap: ignoring invalid ", key, " value: ", value);
  723. continue;
  724. }
  725. auto& adjustments = request.imageAdjustments;
  726. if (key == "image-filter-strength") {
  727. adjustments.filterStrength = amount;
  728. } else if (key == "brightness") {
  729. adjustments.brightness = amount;
  730. } else if (key == "contrast") {
  731. adjustments.contrast = amount;
  732. } else if (key == "saturation") {
  733. adjustments.saturation = amount;
  734. } else {
  735. adjustments.hue = amount;
  736. }
  737. request.imageAdjustmentsProvided = true;
  738. } else if (key == "speed") {
  739. request.speed = value;
  740. } else if (key == "audio-screen") {
  741. request.audioScreen = value;
  742. } else if (key == "ambient-volume") {
  743. request.ambientVolume = value;
  744. } else if (key == "property") {
  745. const auto propSeparator = value.find ('=');
  746. if (propSeparator == std::string::npos) {
  747. sLog.error ("Hotswap: ignoring malformed property line: ", value);
  748. } else {
  749. request.propertiesProvided = true;
  750. request.properties[value.substr (0, propSeparator)] = value.substr (propSeparator + 1);
  751. }
  752. } else if (key == "audio-sensitivity") {
  753. const auto sensSeparator = value.find ('=');
  754. if (sensSeparator == std::string::npos) {
  755. sLog.error ("Hotswap: ignoring malformed audio-sensitivity line: ", value);
  756. } else {
  757. request.audioSensitivityProvided = true;
  758. request.audioSensitivity[value.substr (0, sensSeparator)] = value.substr (sensSeparator + 1);
  759. }
  760. } else if (key == "sound-volume") {
  761. const auto volSeparator = value.find ('=');
  762. if (volSeparator == std::string::npos) {
  763. sLog.error ("Hotswap: ignoring malformed sound-volume line: ", value);
  764. } else {
  765. request.soundVolumeProvided = true;
  766. request.soundVolume[value.substr (0, volSeparator)] = value.substr (volSeparator + 1);
  767. }
  768. } else {
  769. sLog.error ("Hotswap: ignoring unknown control file key: ", key);
  770. }
  771. }
  772. return request;
  773. }
  774. } // namespace
  775. void WallpaperApplication::checkHotswapRequest () {
  776. if (!this->m_hotswapRequested.exchange (false)) {
  777. return;
  778. }
  779. const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
  780. const auto controlFile = this->m_context.settings.general.controlFile.value_or (
  781. std::filesystem::path (runtimeDir != nullptr ? runtimeDir : "/tmp") / "lwe-control"
  782. );
  783. std::ifstream file (controlFile);
  784. if (!file.is_open ()) {
  785. sLog.error ("Hotswap requested but control file could not be read: ", controlFile.string ());
  786. return;
  787. }
  788. const auto request = parseHotswapRequest (file);
  789. if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
  790. && !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
  791. && !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
  792. && !request.expandCanvas.has_value () && !request.cornerColor.has_value () && !request.imageAdjustmentsProvided
  793. && !request.speed.has_value () && !request.audioScreen.has_value () && !request.ambientVolume.has_value ()
  794. && !request.propertiesProvided && !request.audioSensitivityProvided && !request.soundVolumeProvided) {
  795. sLog.error ("Hotswap requested but control file was empty");
  796. return;
  797. }
  798. // overrides belong to the wallpaper they were set for, object ids and generic property names
  799. // ("newproperty1") collide across wallpapers, so a new wallpaper starts without the old ones and
  800. // only gets whatever this same request carries for it
  801. if (request.path.has_value ()) {
  802. auto& general = this->m_context.settings.general;
  803. general.disabledObjects.clear ();
  804. general.enabledObjects.clear ();
  805. general.disabledEffects.clear ();
  806. general.enabledEffects.clear ();
  807. general.properties.clear ();
  808. general.audioSensitivity.clear ();
  809. general.soundVolume.clear ();
  810. // Wallpaper Engine keeps these per wallpaper too
  811. this->m_context.settings.render.window.imageAdjustments = {};
  812. general.screenImageAdjustments.clear ();
  813. for (auto& spanGroup : general.spanGroups) {
  814. spanGroup.imageAdjustments = {};
  815. }
  816. }
  817. if (request.volume.has_value ()) {
  818. this->applyVolumeHotswap (*request.volume);
  819. }
  820. if (request.fps.has_value ()) {
  821. this->applyFpsHotswap (*request.fps);
  822. }
  823. if (request.xray.has_value ()) {
  824. this->applyXrayHotswap (*request.xray);
  825. }
  826. if (request.scaling.has_value ()) {
  827. this->applyScalingHotswap (*request.scaling);
  828. }
  829. if (request.zoom.has_value ()) {
  830. this->applyZoomHotswap (*request.zoom);
  831. }
  832. if (request.offset.has_value ()) {
  833. this->applyOffsetHotswap (*request.offset);
  834. }
  835. if (request.alignment.has_value ()) {
  836. this->applyAlignmentHotswap (*request.alignment);
  837. }
  838. if (request.disableParallax.has_value ()) {
  839. this->applyParallaxHotswap (*request.disableParallax);
  840. }
  841. if (request.cornerColor.has_value ()) {
  842. this->applyCornerColorHotswap (*request.cornerColor);
  843. }
  844. if (request.imageAdjustmentsProvided) {
  845. this->applyImageAdjustmentsHotswap (request.imageAdjustments);
  846. }
  847. if (request.speed.has_value ()) {
  848. this->applySpeedHotswap (*request.speed);
  849. }
  850. if (request.audioScreen.has_value ()) {
  851. this->applyAudioScreenHotswap (*request.audioScreen);
  852. }
  853. if (request.ambientVolume.has_value ()) {
  854. this->applyAmbientVolumeHotswap (*request.ambientVolume);
  855. }
  856. if (request.soundVolumeProvided) {
  857. this->applySoundVolumeHotswap (request.soundVolume);
  858. }
  859. bool expandCanvasChanged = false;
  860. if (request.expandCanvas.has_value ()) {
  861. const auto& value = *request.expandCanvas;
  862. const bool enable = value == "on" || value == "1" || value == "true";
  863. if (!enable && value != "off" && value != "0" && value != "false") {
  864. sLog.error ("Hotswap: ignoring invalid expand-canvas value: ", value);
  865. } else {
  866. expandCanvasChanged = this->m_context.settings.general.expandCanvas != enable;
  867. this->m_context.settings.general.expandCanvas = enable;
  868. }
  869. }
  870. if (request.layersProvided) {
  871. this->m_context.settings.general.disabledObjects = request.disabledObjects;
  872. this->m_context.settings.general.enabledObjects = request.enabledObjects;
  873. }
  874. if (request.propertiesProvided) {
  875. for (const auto& [name, value] : request.properties) {
  876. this->m_context.settings.general.properties[name] = value;
  877. }
  878. }
  879. if (request.audioSensitivityProvided) {
  880. for (const auto& [target, value] : request.audioSensitivity) {
  881. try {
  882. this->m_context.settings.general.audioSensitivity[target] = std::stof (value);
  883. } catch (const std::exception&) {
  884. sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", value);
  885. }
  886. }
  887. }
  888. // volume/xray/speed-only requests are pure live setters with nothing to reload. Properties
  889. // and audio sensitivity, like layers, are baked into the scene graph at parse time, so they
  890. // need the same reload, as does the expanded canvas (it sizes the scene's framebuffers).
  891. if (!request.path.has_value () && !request.layersProvided && !request.propertiesProvided
  892. && !request.audioSensitivityProvided && !expandCanvasChanged) {
  893. return;
  894. }
  895. if (request.path.has_value () && !this->preflightWallpaper (*request.path)) {
  896. sLog.error ("Hotswap failed, invalid wallpaper at ", *request.path);
  897. return;
  898. }
  899. if (!this->makeAnyViewportCurrent ()) {
  900. sLog.error ("Hotswap failed, no active viewport");
  901. return;
  902. }
  903. if (request.path.has_value ()) {
  904. sLog.out ("Hotswapping wallpaper to ", *request.path);
  905. } else {
  906. sLog.out ("Hotswapping wallpaper layers");
  907. }
  908. // the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
  909. for (auto& [screen, background] : this->m_backgrounds) {
  910. const std::string targetPath = request.path.value_or (this->resolveScreenBackgroundPath (screen));
  911. try {
  912. auto project = this->loadBackground (targetPath);
  913. this->setupPropertiesForProject (*project);
  914. this->setupAudioSensitivityForProject (*project);
  915. this->setupSoundVolumeForProject (*project);
  916. this->ensureAudioCapture (*project);
  917. auto outgoing = std::move (background);
  918. background = std::move (project);
  919. try {
  920. const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
  921. const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
  922. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  923. ? scalingIt->second
  924. : this->m_context.settings.render.window.scalingMode;
  925. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  926. ? clampIt->second
  927. : this->m_context.settings.render.window.clamp;
  928. if (this->m_renderContext) {
  929. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  930. *background->wallpaper, *this->m_renderContext, *this->m_audioContext, targetPath, scaling,
  931. clamp, this->resolveScreenRenderSize (screen)
  932. );
  933. wallpaper->setZoom (this->resolveScreenZoom (screen));
  934. const auto offset = this->resolveScreenOffset (screen);
  935. wallpaper->setOffset (offset.x, offset.y);
  936. wallpaper->setAlignment (this->resolveScreenAlignment (screen));
  937. wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
  938. wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, *background));
  939. this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
  940. }
  941. } catch (...) {
  942. project = std::move (background);
  943. background = std::move (outgoing);
  944. if (this->m_renderContext) {
  945. this->m_renderContext->pruneTextures ();
  946. }
  947. throw;
  948. }
  949. if (request.path.has_value ()) {
  950. if (screen.starts_with ("span:")) {
  951. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  952. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  953. spanGroup.background = *request.path;
  954. }
  955. }
  956. } else {
  957. this->m_context.settings.general.screenBackgrounds[screen] = *request.path;
  958. }
  959. }
  960. } catch (const std::exception& e) {
  961. sLog.error ("Hotswap failed for screen ", screen, ": ", e.what ());
  962. }
  963. }
  964. this->applyAudioPolicy ();
  965. if (request.path.has_value ()) {
  966. this->m_context.settings.general.defaultBackground = *request.path;
  967. }
  968. }
  969. std::string WallpaperApplication::resolveScreenBackgroundPath (const std::string& screen) const {
  970. if (screen.starts_with ("span:")) {
  971. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  972. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  973. return spanGroup.background.empty () ? this->m_context.settings.general.defaultBackground.string ()
  974. : spanGroup.background.string ();
  975. }
  976. }
  977. return this->m_context.settings.general.defaultBackground.string ();
  978. }
  979. const auto it = this->m_context.settings.general.screenBackgrounds.find (screen);
  980. if (it != this->m_context.settings.general.screenBackgrounds.end () && !it->second.empty ()) {
  981. return it->second.string ();
  982. }
  983. return this->m_context.settings.general.defaultBackground.string ();
  984. }
  985. float WallpaperApplication::resolveScreenZoom (const std::string& screen) const {
  986. const auto it = this->m_context.settings.general.screenZooms.find (screen);
  987. return it != this->m_context.settings.general.screenZooms.end () ? it->second
  988. : this->m_context.settings.render.window.zoom;
  989. }
  990. glm::vec2 WallpaperApplication::resolveScreenOffset (const std::string& screen) const {
  991. const auto it = this->m_context.settings.general.screenOffsets.find (screen);
  992. return it != this->m_context.settings.general.screenOffsets.end () ? it->second
  993. : this->m_context.settings.render.window.offset;
  994. }
  995. WallpaperEngine::Render::WallpaperState::Alignment
  996. WallpaperApplication::resolveScreenAlignment (const std::string& screen) const {
  997. const auto it = this->m_context.settings.general.screenAlignments.find (screen);
  998. return it != this->m_context.settings.general.screenAlignments.end ()
  999. ? it->second
  1000. : this->m_context.settings.render.window.alignment;
  1001. }
  1002. glm::vec4 WallpaperApplication::resolveScreenCornerColor (const std::string& screen) const {
  1003. const auto it = this->m_context.settings.general.screenCornerColors.find (screen);
  1004. return it != this->m_context.settings.general.screenCornerColors.end ()
  1005. ? it->second
  1006. : this->m_context.settings.render.window.cornerColor;
  1007. }
  1008. ImageAdjustments
  1009. WallpaperApplication::resolveScreenImageAdjustments (const std::string& screen, const Project& project) const {
  1010. const auto fallback = this->m_context.settings.render.window.imageAdjustments.over (project.imageAdjustments);
  1011. // span groups render under every member screen's name and are loaded as "span:<first screen>"
  1012. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1013. if (spanGroup.screens.empty ()) {
  1014. continue;
  1015. }
  1016. if ("span:" + spanGroup.screens.front () == screen
  1017. || std::find (spanGroup.screens.begin (), spanGroup.screens.end (), screen) != spanGroup.screens.end ()) {
  1018. return spanGroup.imageAdjustments.over (fallback);
  1019. }
  1020. }
  1021. const auto it = this->m_context.settings.general.screenImageAdjustments.find (screen);
  1022. return it != this->m_context.settings.general.screenImageAdjustments.end () ? it->second.over (fallback) : fallback;
  1023. }
  1024. glm::ivec2 WallpaperApplication::resolveScreenRenderSize (const std::string& screen) const {
  1025. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  1026. const auto it = viewports.find (screen);
  1027. if (it != viewports.end ()) {
  1028. return { it->second->viewport.z, it->second->viewport.w };
  1029. }
  1030. return { this->m_renderContext->getOutput ().getFullWidth (),
  1031. this->m_renderContext->getOutput ().getFullHeight () };
  1032. }
  1033. void WallpaperApplication::applyVolumeHotswap (int volume) {
  1034. volume = std::max (0, std::min (volume, 128));
  1035. this->m_context.settings.audio.volume = volume;
  1036. this->m_context.state.audio.volume = volume;
  1037. if (!this->m_renderContext) {
  1038. return;
  1039. }
  1040. const double scaledVolume = this->m_context.settings.audio.enabled ? volume * 100.0 / 128.0 : 0.0;
  1041. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1042. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  1043. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setVolume (scaledVolume);
  1044. }
  1045. }
  1046. sLog.out ("Hotswap: applied volume ", volume, " live");
  1047. }
  1048. void WallpaperApplication::applyFpsHotswap (int fps) {
  1049. fps = std::max (1, fps);
  1050. this->m_context.settings.render.maximumFPS = fps;
  1051. sLog.out ("Hotswap: applied fps limit ", fps, " live");
  1052. }
  1053. void WallpaperApplication::applyXrayHotswap (const std::string& value) {
  1054. bool newState;
  1055. if (value == "toggle") {
  1056. newState = !this->m_context.state.xray.fullReveal;
  1057. } else if (value == "on" || value == "1" || value == "true") {
  1058. newState = true;
  1059. } else if (value == "off" || value == "0" || value == "false") {
  1060. newState = false;
  1061. } else {
  1062. sLog.error ("Hotswap: ignoring invalid xray value: ", value);
  1063. return;
  1064. }
  1065. this->m_context.state.xray.fullReveal = newState;
  1066. sLog.out ("Hotswap: full xray ", newState ? "enabled" : "disabled", " live");
  1067. }
  1068. void WallpaperApplication::applyScalingHotswap (const std::string& value) {
  1069. const auto mode = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
  1070. if (!mode.has_value ()) {
  1071. sLog.error ("Hotswap: ignoring invalid scaling value: ", value);
  1072. return;
  1073. }
  1074. this->m_context.settings.render.window.scalingMode = *mode;
  1075. for (auto& [screen, scaling] : this->m_context.settings.general.screenScalings) {
  1076. scaling = *mode;
  1077. }
  1078. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1079. spanGroup.scaling = *mode;
  1080. }
  1081. if (this->m_renderContext) {
  1082. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1083. wallpaper->setScalingMode (*mode);
  1084. }
  1085. }
  1086. sLog.out ("Hotswap: applied scaling mode ", value, " live");
  1087. }
  1088. void WallpaperApplication::applyZoomHotswap (const std::string& value) {
  1089. float zoom;
  1090. try {
  1091. zoom = std::stof (value);
  1092. } catch (const std::exception&) {
  1093. sLog.error ("Hotswap: ignoring invalid zoom value: ", value);
  1094. return;
  1095. }
  1096. this->m_context.settings.render.window.zoom = zoom;
  1097. for (auto& [screen, screenZoom] : this->m_context.settings.general.screenZooms) {
  1098. screenZoom = zoom;
  1099. }
  1100. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1101. spanGroup.zoom = zoom;
  1102. }
  1103. if (this->m_renderContext) {
  1104. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1105. wallpaper->setZoom (zoom);
  1106. }
  1107. }
  1108. sLog.out ("Hotswap: applied zoom ", zoom, " live");
  1109. }
  1110. void WallpaperApplication::applyOffsetHotswap (const std::string& value) {
  1111. const auto comma = value.find (',');
  1112. if (comma == std::string::npos) {
  1113. sLog.error ("Hotswap: ignoring malformed offset value (expected X,Y): ", value);
  1114. return;
  1115. }
  1116. glm::vec2 offset;
  1117. try {
  1118. offset.x = std::stof (value.substr (0, comma));
  1119. offset.y = std::stof (value.substr (comma + 1));
  1120. } catch (const std::exception&) {
  1121. sLog.error ("Hotswap: ignoring invalid offset value: ", value);
  1122. return;
  1123. }
  1124. this->m_context.settings.render.window.offset = offset;
  1125. for (auto& [screen, screenOffset] : this->m_context.settings.general.screenOffsets) {
  1126. screenOffset = offset;
  1127. }
  1128. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1129. spanGroup.offset = offset;
  1130. }
  1131. if (this->m_renderContext) {
  1132. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1133. wallpaper->setOffset (offset.x, offset.y);
  1134. }
  1135. }
  1136. sLog.out ("Hotswap: applied offset ", offset.x, ",", offset.y, " live");
  1137. }
  1138. void WallpaperApplication::applyAlignmentHotswap (const std::string& value) {
  1139. // "position,x,y,zoom" in WE's units (0-100, zoom 0-200)
  1140. std::array<float, 4> values {};
  1141. std::stringstream stream (value);
  1142. std::string part;
  1143. size_t count = 0;
  1144. try {
  1145. while (count < values.size () && std::getline (stream, part, ',')) {
  1146. values[count++] = std::stof (part);
  1147. }
  1148. } catch (const std::exception&) {
  1149. count = 0;
  1150. }
  1151. if (count != values.size ()) {
  1152. sLog.error ("Hotswap: ignoring malformed alignment value (expected position,x,y,zoom): ", value);
  1153. return;
  1154. }
  1155. const WallpaperEngine::Render::WallpaperState::Alignment alignment {
  1156. .position = std::clamp (values[0], 0.0f, 100.0f) / 100.0f,
  1157. .x = std::clamp (values[1], 0.0f, 100.0f) / 100.0f,
  1158. .y = std::clamp (values[2], 0.0f, 100.0f) / 100.0f,
  1159. .zoom = std::clamp (values[3], 0.0f, 200.0f) / 100.0f,
  1160. };
  1161. this->m_context.settings.render.window.alignment = alignment;
  1162. for (auto& [screen, screenAlignment] : this->m_context.settings.general.screenAlignments) {
  1163. screenAlignment = alignment;
  1164. }
  1165. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1166. spanGroup.alignment = alignment;
  1167. }
  1168. if (this->m_renderContext) {
  1169. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1170. wallpaper->setAlignment (alignment);
  1171. }
  1172. }
  1173. sLog.out ("Hotswap: applied alignment ", value, " live");
  1174. }
  1175. void WallpaperApplication::applyParallaxHotswap (const std::string& value) {
  1176. bool newState;
  1177. if (value == "toggle") {
  1178. newState = !this->m_context.settings.mouse.disableparallax;
  1179. } else if (value == "on" || value == "1" || value == "true") {
  1180. newState = true;
  1181. } else if (value == "off" || value == "0" || value == "false") {
  1182. newState = false;
  1183. } else {
  1184. sLog.error ("Hotswap: ignoring invalid disable-parallax value: ", value);
  1185. return;
  1186. }
  1187. this->m_context.settings.mouse.disableparallax = newState;
  1188. sLog.out ("Hotswap: parallax ", newState ? "force-disabled" : "enabled", " live");
  1189. }
  1190. void WallpaperApplication::applyCornerColorHotswap (const std::string& value) {
  1191. const auto color = WallpaperEngine::Render::CFBO::parseColor (value);
  1192. if (!color.has_value ()) {
  1193. sLog.error ("Hotswap: ignoring invalid corner color: ", value);
  1194. return;
  1195. }
  1196. this->m_context.settings.render.window.cornerColor = *color;
  1197. for (auto& [screen, screenColor] : this->m_context.settings.general.screenCornerColors) {
  1198. screenColor = *color;
  1199. }
  1200. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1201. spanGroup.cornerColor = *color;
  1202. }
  1203. if (this->m_renderContext) {
  1204. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1205. wallpaper->setCornerColor (*color);
  1206. }
  1207. }
  1208. sLog.out ("Hotswap: applied corner color ", value, " live");
  1209. }
  1210. void WallpaperApplication::applyImageAdjustmentsHotswap (const ImageAdjustments& request) {
  1211. auto& window = this->m_context.settings.render.window.imageAdjustments;
  1212. window = request.over (window);
  1213. for (auto& [screen, adjustments] : this->m_context.settings.general.screenImageAdjustments) {
  1214. adjustments = request.over (adjustments);
  1215. }
  1216. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1217. spanGroup.imageAdjustments = request.over (spanGroup.imageAdjustments);
  1218. }
  1219. if (this->m_renderContext) {
  1220. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1221. wallpaper->setImageAdjustments (
  1222. this->resolveScreenImageAdjustments (screen, wallpaper->getWallpaperData ().project)
  1223. );
  1224. }
  1225. }
  1226. sLog.out ("Hotswap: applied image filter and color options live");
  1227. }
  1228. void WallpaperApplication::applySpeedHotswap (const std::string& value) {
  1229. float speed;
  1230. try {
  1231. speed = std::stof (value);
  1232. } catch (const std::exception&) {
  1233. sLog.error ("Hotswap: ignoring invalid speed value: ", value);
  1234. return;
  1235. }
  1236. if (speed <= 0.0f) {
  1237. sLog.error ("Hotswap: ignoring non-positive speed value: ", value);
  1238. return;
  1239. }
  1240. this->m_context.settings.render.playbackSpeed = speed;
  1241. // Particles/effects/scripts read settings.render.playbackSpeed directly every frame, but
  1242. // video wallpapers are driven by mpv's own clock and need the change pushed explicitly.
  1243. if (this->m_renderContext) {
  1244. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1245. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  1246. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSpeed (speed);
  1247. }
  1248. }
  1249. }
  1250. sLog.out ("Hotswap: applied speed ", speed, " live");
  1251. }
  1252. void WallpaperApplication::applyAudioScreenHotswap (const std::string& value) {
  1253. this->m_context.settings.audio.audioScreen = value.empty () ? std::nullopt : std::optional<std::string> (value);
  1254. this->applyAudioPolicy ();
  1255. sLog.out ("Hotswap: applied audio screen '", value, "' live");
  1256. }
  1257. void WallpaperApplication::applyAmbientVolumeHotswap (const std::string& value) {
  1258. int volume;
  1259. try {
  1260. volume = std::stoi (value);
  1261. } catch (const std::exception&) {
  1262. sLog.error ("Hotswap: ignoring invalid ambient volume value: ", value);
  1263. return;
  1264. }
  1265. this->m_context.settings.audio.ambientVolume = std::max (0, std::min (volume, 128));
  1266. this->applyAudioPolicy ();
  1267. sLog.out ("Hotswap: applied ambient volume ", volume, " live");
  1268. }
  1269. void WallpaperApplication::applyAudioPolicy () {
  1270. if (!this->m_renderContext) {
  1271. return;
  1272. }
  1273. const auto& audioScreen = this->m_context.settings.audio.audioScreen;
  1274. const auto& ambientVolume = this->m_context.settings.audio.ambientVolume;
  1275. std::map<WallpaperEngine::Render::CWallpaper*, bool> wantMuted;
  1276. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1277. const bool screenMuted = audioScreen.has_value () && screen != *audioScreen;
  1278. auto [it, inserted] = wantMuted.try_emplace (wallpaper.get (), screenMuted);
  1279. if (!inserted) {
  1280. it->second = it->second && screenMuted;
  1281. }
  1282. }
  1283. for (const auto& [wallpaper, muted] : wantMuted) {
  1284. wallpaper->setAudioPolicy (muted, ambientVolume);
  1285. }
  1286. }
  1287. void WallpaperApplication::setupPropertiesForProject (const Project& project) {
  1288. for (const auto& [key, cur] : project.properties) {
  1289. auto override = this->m_context.settings.general.properties.find (key);
  1290. if (override != this->m_context.settings.general.properties.end ()) {
  1291. sLog.out ("Applying override value for ", key);
  1292. cur->update (override->second, DynamicValue::UpdateSource::User);
  1293. }
  1294. if (this->m_context.settings.general.onlyListProperties) {
  1295. sLog.out (cur->dump ());
  1296. }
  1297. }
  1298. }
  1299. void WallpaperApplication::setupProperties () {
  1300. for (const auto& [background, info] : this->m_backgrounds) {
  1301. this->setupPropertiesForProject (*info);
  1302. }
  1303. }
  1304. void WallpaperApplication::listObjectsForProject (const std::string& background, const Project& project) const {
  1305. if (!project.wallpaper->is<Scene> ()) {
  1306. return;
  1307. }
  1308. const auto scene = project.wallpaper->as<Scene> ();
  1309. sLog.out ("Objects for ", background, ":");
  1310. for (const auto& object : scene->objects) {
  1311. std::string type = "unknown";
  1312. if (object->is<Image> ()) {
  1313. type = "image";
  1314. } else if (object->is<Particle> ()) {
  1315. type = "particle";
  1316. } else if (object->is<Text> ()) {
  1317. type = "text";
  1318. } else if (object->is<Sound> ()) {
  1319. type = "sound";
  1320. }
  1321. sLog.out (" ", object->id, " - ", object->name, " (", type, ")");
  1322. }
  1323. }
  1324. void WallpaperApplication::listObjects () const {
  1325. if (!this->m_context.settings.general.onlyListObjects) {
  1326. return;
  1327. }
  1328. for (const auto& [background, info] : this->m_backgrounds) {
  1329. this->listObjectsForProject (background, *info);
  1330. }
  1331. }
  1332. void WallpaperApplication::listEffectsForProject (const std::string& background, const Project& project) const {
  1333. if (!project.wallpaper->is<Scene> ()) {
  1334. return;
  1335. }
  1336. const auto scene = project.wallpaper->as<Scene> ();
  1337. sLog.out ("Effects for ", background, ":");
  1338. for (const auto& object : scene->objects) {
  1339. if (!object->is<Image> ()) {
  1340. continue;
  1341. }
  1342. const auto* image = object->as<Image> ();
  1343. for (const auto& effect : image->effects) {
  1344. sLog.out (
  1345. " ", effect->id, " - ", effect->name, " (object=", object->id, " objectName=\"", object->name,
  1346. "\" group=\"", effect->effect->group, "\")"
  1347. );
  1348. }
  1349. }
  1350. }
  1351. void WallpaperApplication::listEffects () const {
  1352. if (!this->m_context.settings.general.onlyListEffects) {
  1353. return;
  1354. }
  1355. for (const auto& [background, info] : this->m_backgrounds) {
  1356. this->listEffectsForProject (background, *info);
  1357. }
  1358. }
  1359. namespace {
  1360. struct AudioReactiveProperty {
  1361. std::string name;
  1362. DynamicValue* value;
  1363. };
  1364. void considerAudioReactive (
  1365. std::vector<AudioReactiveProperty>& result, const std::string& name, const UserSettingUniquePtr& setting
  1366. ) {
  1367. if (!setting || !setting->value) {
  1368. return;
  1369. }
  1370. const auto& source = setting->value->getScriptSource ();
  1371. if (source.has_value () && source->find ("registerAudioBuffers") != std::string::npos) {
  1372. result.push_back ({ name, setting->value.get () });
  1373. }
  1374. }
  1375. // Mirrors exactly the set of fields ScriptableObject/CImage/CText/CParticle register with the
  1376. // script engine (see Scripting/ScriptableObject.cpp, Render/Objects/CImage.cpp, CText.cpp,
  1377. // CParticle.cpp) - "origin" is always the base object's own field (never overridden per-type),
  1378. // while scale/angles/visible fall back to the generic group* fields only for object types that
  1379. // don't provide their own (Sound, Light, plain groups).
  1380. std::vector<AudioReactiveProperty> collectAudioReactiveProperties (const Object& object) {
  1381. std::vector<AudioReactiveProperty> result;
  1382. considerAudioReactive (result, "origin", object.origin);
  1383. if (object.is<Image> ()) {
  1384. const auto* image = object.as<Image> ();
  1385. considerAudioReactive (result, "scale", image->scale);
  1386. considerAudioReactive (result, "angles", image->angles);
  1387. considerAudioReactive (result, "visible", image->visible);
  1388. considerAudioReactive (result, "alpha", image->alpha);
  1389. considerAudioReactive (result, "color", image->color);
  1390. considerAudioReactive (result, "parallaxDepth", image->parallaxDepth);
  1391. } else if (object.is<Text> ()) {
  1392. const auto* text = object.as<Text> ();
  1393. considerAudioReactive (result, "scale", text->scale);
  1394. considerAudioReactive (result, "color", text->color);
  1395. considerAudioReactive (result, "alpha", text->alpha);
  1396. considerAudioReactive (result, "visible", text->visible);
  1397. considerAudioReactive (result, "pointSize", text->pointSize);
  1398. considerAudioReactive (result, "text", text->text);
  1399. considerAudioReactive (result, "parallaxDepth", text->parallaxDepth);
  1400. } else if (object.is<Particle> ()) {
  1401. const auto* particle = object.as<Particle> ();
  1402. considerAudioReactive (result, "scale", particle->scale);
  1403. considerAudioReactive (result, "angles", particle->angles);
  1404. considerAudioReactive (result, "visible", particle->visible);
  1405. considerAudioReactive (result, "parallaxDepth", particle->parallaxDepth);
  1406. } else {
  1407. considerAudioReactive (result, "scale", object.groupScale);
  1408. considerAudioReactive (result, "angles", object.groupAngles);
  1409. considerAudioReactive (result, "visible", object.groupVisible);
  1410. }
  1411. return result;
  1412. }
  1413. float readScriptPropertyFloat (DynamicValue& value, const std::string& key) {
  1414. auto& properties = value.getProperties ();
  1415. const auto it = properties.find (key);
  1416. return it != properties.end () && it->second && it->second->value ? it->second->value->getFloat () : 0.0f;
  1417. }
  1418. } // namespace
  1419. void WallpaperApplication::listAudioObjectsForProject (const std::string& background, const Project& project) const {
  1420. if (!project.wallpaper->is<Scene> ()) {
  1421. return;
  1422. }
  1423. const auto scene = project.wallpaper->as<Scene> ();
  1424. sLog.out ("Audio-reactive objects for ", background, ":");
  1425. for (const auto& object : scene->objects) {
  1426. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1427. sLog.out (
  1428. " ", object->id, " - ", object->name, " (", reactive.name,
  1429. "): minvalue=", readScriptPropertyFloat (*reactive.value, "minvalue"),
  1430. " maxvalue=", readScriptPropertyFloat (*reactive.value, "maxvalue"),
  1431. " frequency=", readScriptPropertyFloat (*reactive.value, "frequency"),
  1432. " smoothing=", readScriptPropertyFloat (*reactive.value, "smoothing")
  1433. );
  1434. }
  1435. }
  1436. }
  1437. void WallpaperApplication::listAudioObjects () const {
  1438. if (!this->m_context.settings.general.onlyListAudioObjects) {
  1439. return;
  1440. }
  1441. for (const auto& [background, info] : this->m_backgrounds) {
  1442. this->listAudioObjectsForProject (background, *info);
  1443. }
  1444. }
  1445. void WallpaperApplication::setupAudioSensitivityForProject (const Project& project) const {
  1446. if (!project.wallpaper->is<Scene> ()) {
  1447. return;
  1448. }
  1449. const auto scene = project.wallpaper->as<Scene> ();
  1450. for (const auto& object : scene->objects) {
  1451. const auto sensitivity = this->m_context.resolveAudioSensitivity (object->id, object->name);
  1452. if (!sensitivity.has_value ()) {
  1453. continue;
  1454. }
  1455. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1456. auto& scriptProps = reactive.value->getProperties ();
  1457. const auto minIt = scriptProps.find ("minvalue");
  1458. const auto maxIt = scriptProps.find ("maxvalue");
  1459. if (minIt == scriptProps.end () || maxIt == scriptProps.end () || !minIt->second->value
  1460. || !maxIt->second->value) {
  1461. continue;
  1462. }
  1463. const auto [newMin, newMax] = WallpaperEngine::Data::Utils::scaleAudioRange (
  1464. minIt->second->value->getFloat (), maxIt->second->value->getFloat (), sensitivity.value ()
  1465. );
  1466. minIt->second->value->update (newMin, DynamicValue::UpdateSource::User);
  1467. maxIt->second->value->update (newMax, DynamicValue::UpdateSource::User);
  1468. sLog.debug (
  1469. "Applying audio sensitivity ", sensitivity.value (), " to ", object->id, " - ", object->name, " (",
  1470. reactive.name, ")"
  1471. );
  1472. }
  1473. }
  1474. }
  1475. void WallpaperApplication::setupAudioSensitivity () {
  1476. for (const auto& [background, info] : this->m_backgrounds) {
  1477. this->setupAudioSensitivityForProject (*info);
  1478. }
  1479. }
  1480. void WallpaperApplication::setupSoundVolumeForProject (const Project& project) const {
  1481. if (!project.wallpaper->is<Scene> ()) {
  1482. return;
  1483. }
  1484. const auto scene = project.wallpaper->as<Scene> ();
  1485. for (const auto& object : scene->objects) {
  1486. if (!object->is<Sound> ()) {
  1487. continue;
  1488. }
  1489. const auto* sound = object->as<Sound> ();
  1490. const auto volume = this->m_context.resolveSoundVolume (object->id, object->name);
  1491. if (!volume.has_value () || !sound->volume || !sound->volume->value) {
  1492. continue;
  1493. }
  1494. sound->volume->value->update (std::clamp (volume.value (), 0.0f, 1.0f), DynamicValue::UpdateSource::User);
  1495. sLog.debug ("Applying sound volume ", volume.value (), " to ", object->id, " - ", object->name);
  1496. }
  1497. }
  1498. void WallpaperApplication::setupSoundVolume () {
  1499. for (const auto& [background, info] : this->m_backgrounds) {
  1500. this->setupSoundVolumeForProject (*info);
  1501. }
  1502. }
  1503. void WallpaperApplication::applySoundVolumeHotswap (const std::map<std::string, std::string>& targets) {
  1504. for (const auto& [target, value] : targets) {
  1505. try {
  1506. this->m_context.settings.general.soundVolume[target] = std::stof (value);
  1507. } catch (const std::exception&) {
  1508. sLog.error ("Hotswap: ignoring invalid sound-volume value: ", value);
  1509. }
  1510. }
  1511. // Sound objects already read their own DynamicValue live every frame (see
  1512. // CSound::applyEffectiveVolume), so re-resolving and pushing the new value straight into the
  1513. // currently loaded projects' live objects is enough - no reload needed, unlike properties/
  1514. // audio-sensitivity which are baked into the scene graph at parse time.
  1515. for (const auto& [background, info] : this->m_backgrounds) {
  1516. this->setupSoundVolumeForProject (*info);
  1517. }
  1518. sLog.out ("Hotswap: applied sound volume live");
  1519. }
  1520. void WallpaperApplication::setupBrowser () {
  1521. // The main engine process never hosts CEF directly - CEF only supports one
  1522. // CefInitialize()/CefShutdown() pair per process, so a process that might later need to stop
  1523. // and restart hosting a web wallpaper can't safely do it in place. Only two roles reach here:
  1524. // CEF's own subprocess re-execs (--type=zygote/gpu-process/renderer/utility), which must
  1525. // always reach WebBrowserContext even if loadBackgrounds() found nothing to load, and this
  1526. // process's own --web-host role.
  1527. if ((!this->isCefSubprocess () && !this->m_context.settings.general.webHost) || this->m_browserContext) {
  1528. return;
  1529. }
  1530. this->m_browserContext = std::make_unique<WebBrowser::WebBrowserContext> (*this);
  1531. }
  1532. void WallpaperApplication::runWebHost () {
  1533. using namespace WallpaperEngine::WebBrowser;
  1534. using namespace WallpaperEngine::WebBrowser::IPC;
  1535. const auto backgroundIt = this->m_backgrounds.find ("default");
  1536. if (backgroundIt == this->m_backgrounds.end () || !backgroundIt->second->wallpaper->is<Web> ()) {
  1537. sLog.error ("--web-host requires a single Web wallpaper background, none found");
  1538. return;
  1539. }
  1540. if (!this->m_browserContext) {
  1541. sLog.error ("--web-host: CEF was not initialized (setupBrowser() found no Web project?)");
  1542. return;
  1543. }
  1544. const Project& project = *backgroundIt->second;
  1545. const Web& web = *project.wallpaper->as<Web> ();
  1546. const int width = static_cast<int> (this->m_context.settings.general.webHostWidth);
  1547. const int height = static_cast<int> (this->m_context.settings.general.webHostHeight);
  1548. if (width <= 0 || height <= 0) {
  1549. sLog.error ("--web-host: invalid --web-host-width/--web-host-height");
  1550. return;
  1551. }
  1552. auto* shm = attachSharedMemory (this->m_context.settings.general.webHostShm, width, height);
  1553. if (shm == nullptr) {
  1554. sLog.error ("--web-host: failed to attach shared memory ", this->m_context.settings.general.webHostShm);
  1555. return;
  1556. }
  1557. CefWindowInfo windowInfo;
  1558. windowInfo.SetAsWindowless (0);
  1559. // frames are produced when the main process asks for them (see the loop below), so they line up with what it
  1560. // presents instead of drifting against a free running 60Hz timer
  1561. windowInfo.external_begin_frame_enabled = true;
  1562. CefBrowserSettings browserSettings;
  1563. // only a ceiling while external begin frames are on, the main process decides when a frame is produced
  1564. browserSettings.windowless_frame_rate = std::max (60, this->m_context.settings.render.maximumFPS);
  1565. const CefRefPtr<CEF::SharedMemoryRenderHandler> renderHandler = new CEF::SharedMemoryRenderHandler (shm);
  1566. const CefRefPtr<CEF::BrowserClient> client = new CEF::BrowserClient (renderHandler, project.properties);
  1567. // the "w" prefix + workshop id host must match what the scheme handler factory expects to resolve
  1568. const std::string htmlURL = std::string (WPENGINE_SCHEME) + "://w" + project.workshopId + "/" + web.filename;
  1569. sLog.out ("--web-host: creating browser for ", htmlURL, " (pid ", static_cast<long> (getpid ()), ")");
  1570. const CefRefPtr<CefBrowser> browser
  1571. = CefBrowserHost::CreateBrowserSync (windowInfo, client, htmlURL, browserSettings, nullptr, nullptr);
  1572. if (!browser) {
  1573. sLog.error ("--web-host: failed to create the CEF browser");
  1574. shm->helperFailed.store (true, std::memory_order_release);
  1575. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  1576. return;
  1577. }
  1578. // a windowless browser is treated as backgrounded by default, which freezes the page's own timers and rAF
  1579. browser->GetHost ()->WasHidden (false);
  1580. shm->helperReady.store (true, std::memory_order_release);
  1581. Input::MouseClickStatus lastLeft = Input::Released;
  1582. Input::MouseClickStatus lastRight = Input::Released;
  1583. uint32_t lastFrameRequest = shm->frameRequestSeq.load (std::memory_order_acquire);
  1584. auto lastBeginFrame = std::chrono::steady_clock::now ();
  1585. int lastMouseX = -1;
  1586. int lastMouseY = -1;
  1587. uint32_t lastDesiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  1588. uint32_t lastDesiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  1589. bool lastAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  1590. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  1591. CEF::PageBridge bridge (browser, *shm, project.properties, *client);
  1592. while (!shm->quitRequested.load (std::memory_order_acquire)) {
  1593. // The heartbeat keeps the page alive (timers, videos, first paint) when the main process isn't rendering, for
  1594. // example while the surface is fully covered and the compositor stops sending frame callbacks.
  1595. const auto now = std::chrono::steady_clock::now ();
  1596. const uint32_t frameRequest = shm->frameRequestSeq.load (std::memory_order_acquire);
  1597. if (frameRequest != lastFrameRequest || now - lastBeginFrame > std::chrono::milliseconds (100)) {
  1598. lastFrameRequest = frameRequest;
  1599. lastBeginFrame = now;
  1600. browser->GetHost ()->SendExternalBeginFrame ();
  1601. }
  1602. CefDoMessageLoopWork ();
  1603. const uint32_t desiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  1604. const uint32_t desiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  1605. if (desiredWidth != lastDesiredWidth || desiredHeight != lastDesiredHeight) {
  1606. lastDesiredWidth = desiredWidth;
  1607. lastDesiredHeight = desiredHeight;
  1608. browser->GetHost ()->WasResized ();
  1609. }
  1610. const bool desiredAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  1611. if (desiredAudioMuted != lastAudioMuted) {
  1612. lastAudioMuted = desiredAudioMuted;
  1613. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  1614. }
  1615. bridge.update ();
  1616. CefMouseEvent evt;
  1617. evt.x = static_cast<int> (shm->mouseX.load (std::memory_order_relaxed));
  1618. evt.y = static_cast<int> (shm->mouseY.load (std::memory_order_relaxed));
  1619. // every event wakes the page's input handling, so only tell it when the pointer actually moved
  1620. if (evt.x != lastMouseX || evt.y != lastMouseY) {
  1621. lastMouseX = evt.x;
  1622. lastMouseY = evt.y;
  1623. browser->GetHost ()->SendMouseMoveEvent (evt, false);
  1624. }
  1625. const auto left = static_cast<Input::MouseClickStatus> (shm->leftClick.load (std::memory_order_relaxed));
  1626. const auto right = static_cast<Input::MouseClickStatus> (shm->rightClick.load (std::memory_order_relaxed));
  1627. if (left != lastLeft) {
  1628. browser->GetHost ()->SendMouseClickEvent (
  1629. evt, CefBrowserHost::MouseButtonType::MBT_LEFT, left == Input::Released, 1
  1630. );
  1631. lastLeft = left;
  1632. }
  1633. if (right != lastRight) {
  1634. browser->GetHost ()->SendMouseClickEvent (
  1635. evt, CefBrowserHost::MouseButtonType::MBT_RIGHT, right == Input::Released, 1
  1636. );
  1637. lastRight = right;
  1638. }
  1639. // Short, this is also how often input and audio get a chance to be handed to the page and how soon a painted
  1640. // frame gets picked up. A frame request from the main process cuts the wait short.
  1641. shm->waitForFrameRequest (lastFrameRequest, 1);
  1642. }
  1643. browser->GetHost ()->CloseBrowser (true);
  1644. // CloseBrowser() only requests an async close - wait briefly for it to finish before
  1645. // CefShutdown() below tears everything down out from under it
  1646. for (int i = 0; i < 500 && !client->isClosed (); i++) {
  1647. CefDoMessageLoopWork ();
  1648. }
  1649. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  1650. }
  1651. void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename) const {
  1652. const int width = this->m_renderContext->getOutput ().getFullWidth ();
  1653. const int height = this->m_renderContext->getOutput ().getFullHeight ();
  1654. const bool vflip = this->m_renderContext->getOutput ().renderVFlip ();
  1655. const auto& wallpapers = this->m_renderContext->getWallpapers ();
  1656. struct ViewportCapture {
  1657. uint8_t* buffer;
  1658. int readWidth;
  1659. int readHeight;
  1660. int vpWidth;
  1661. int vpHeight;
  1662. int xoffset;
  1663. float ustart, uend, vstart, vend;
  1664. };
  1665. std::vector<ViewportCapture> captures;
  1666. int currentXOffset = 0;
  1667. for (const auto& [screen, viewport] : this->m_renderContext->getOutput ().getViewports ()) {
  1668. viewport->makeCurrent ();
  1669. const auto wallpaperIt = wallpapers.find (screen);
  1670. if (wallpaperIt == wallpapers.end ()) {
  1671. sLog.error ("Cannot find wallpaper for screen ", screen);
  1672. continue;
  1673. }
  1674. const auto& wallpaper = wallpaperIt->second;
  1675. const int vpWidth = viewport->viewport.z - viewport->viewport.x;
  1676. const int vpHeight = viewport->viewport.w - viewport->viewport.y;
  1677. // bind the wallpaper's FBO to read from it directly
  1678. // this is more reliable than the default framebuffer on some drivers (NVIDIA/Wayland)
  1679. glBindFramebuffer (GL_FRAMEBUFFER, wallpaper->renderAdjustedFramebuffer ());
  1680. glFinish ();
  1681. // errors left over from rendering (e.g. a uniform type mismatch) would otherwise fail the readback below
  1682. while (glGetError () != GL_NO_ERROR) { }
  1683. const int readWidth = wallpaper->getFramebufferWidth ();
  1684. const int readHeight = wallpaper->getFramebufferHeight ();
  1685. const auto bufferSize = readWidth * readHeight * 3;
  1686. auto* buffer = new uint8_t[bufferSize];
  1687. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  1688. if (GLEW_VERSION_4_5) {
  1689. glReadnPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer);
  1690. } else {
  1691. glReadPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, buffer);
  1692. }
  1693. glBindFramebuffer (GL_FRAMEBUFFER, 0);
  1694. if (const GLenum error = glGetError (); error != GL_NO_ERROR) {
  1695. sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error);
  1696. delete[] buffer;
  1697. continue;
  1698. }
  1699. // Get the UV coordinates which define the visible portion based on scaling mode
  1700. const glm::vec4 uvs = wallpaper->getOutputUVs ();
  1701. captures.push_back (
  1702. { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset, uvs.x, uvs.y, uvs.z, uvs.w }
  1703. );
  1704. if (viewport->single) {
  1705. currentXOffset += vpWidth;
  1706. }
  1707. }
  1708. const auto extension = filename.extension ();
  1709. const std::string extStr = extension.string ();
  1710. // Offload pixel processing and saving to a background thread to avoid hitches
  1711. std::thread ([captures, width, height, vflip, extStr, filename] () {
  1712. auto* bitmap = new uint8_t[width * height * 3] { 0 };
  1713. for (const auto& capture : captures) {
  1714. // sample the bitmap from the UV-defined visible region
  1715. for (int y = 0; y < capture.vpHeight; y++) {
  1716. for (int x = 0; x < capture.vpWidth; x++) {
  1717. const float u
  1718. = capture.ustart + (static_cast<float> (x) / capture.vpWidth) * (capture.uend - capture.ustart);
  1719. const float v = capture.vstart
  1720. + (static_cast<float> (y) / capture.vpHeight) * (capture.vend - capture.vstart);
  1721. const int srcX = std::clamp (static_cast<int> (u * capture.readWidth), 0, capture.readWidth - 1);
  1722. const int srcY = std::clamp (static_cast<int> (v * capture.readHeight), 0, capture.readHeight - 1);
  1723. const int srcIdx = (srcY * capture.readWidth + srcX) * 3;
  1724. const int xfinal = x + capture.xoffset;
  1725. // FBO content is not flipped like default framebuffer, so invert vflip logic
  1726. const int yfinal = vflip ? y : (capture.vpHeight - y - 1);
  1727. if (yfinal >= 0 && yfinal < height && xfinal >= 0 && xfinal < width) {
  1728. bitmap[yfinal * width * 3 + xfinal * 3] = capture.buffer[srcIdx];
  1729. bitmap[yfinal * width * 3 + xfinal * 3 + 1] = capture.buffer[srcIdx + 1];
  1730. bitmap[yfinal * width * 3 + xfinal * 3 + 2] = capture.buffer[srcIdx + 2];
  1731. }
  1732. }
  1733. }
  1734. delete[] capture.buffer;
  1735. }
  1736. if (extStr == ".bmp") {
  1737. stbi_write_bmp (filename.c_str (), width, height, 3, bitmap);
  1738. } else if (extStr == ".png") {
  1739. stbi_write_png (filename.c_str (), width, height, 3, bitmap, width * 3);
  1740. } else if (extStr == ".jpg" || extStr == ".jpeg") {
  1741. stbi_write_jpg (filename.c_str (), width, height, 3, bitmap, 100);
  1742. }
  1743. delete[] bitmap;
  1744. }).detach ();
  1745. }
  1746. void WallpaperApplication::setupOutput () {
  1747. const char* XDG_SESSION_TYPE = getenv ("XDG_SESSION_TYPE");
  1748. if (!XDG_SESSION_TYPE) {
  1749. sLog.exception (
  1750. "Cannot read environment variable XDG_SESSION_TYPE, window server detection failed. Please ensure proper "
  1751. "values are set"
  1752. );
  1753. }
  1754. sLog.debug ("Checking for window servers: ");
  1755. for (const auto& windowServer : sVideoFactories.getRegisteredDrivers ()) {
  1756. sLog.debug ("\t", windowServer);
  1757. }
  1758. this->m_videoDriver = sVideoFactories.createVideoDriver (
  1759. this->m_context.settings.render.mode, XDG_SESSION_TYPE, this->m_context, *this
  1760. );
  1761. this->m_fullScreenDetector
  1762. = sVideoFactories.createFullscreenDetector (XDG_SESSION_TYPE, this->m_context, *this->m_videoDriver);
  1763. }
  1764. void WallpaperApplication::setupAudio () {
  1765. const bool audioProcessingRequired = std::ranges::any_of (
  1766. this->m_backgrounds, [] (const std::pair<const std::string, ProjectUniquePtr>& pair) -> bool {
  1767. return pair.second->supportsAudioProcessing;
  1768. }
  1769. );
  1770. if (audioProcessingRequired && this->m_context.settings.audio.audioprocessing) {
  1771. this->m_audioRecorder
  1772. = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
  1773. this->m_audioCapturing = true;
  1774. } else {
  1775. this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PlaybackRecorder> ();
  1776. }
  1777. if (this->m_context.settings.audio.automute) {
  1778. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::PulseAudioPlayingDetector> (
  1779. this->m_context, *this->m_fullScreenDetector
  1780. );
  1781. } else {
  1782. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::AudioPlayingDetector> (
  1783. this->m_context, *this->m_fullScreenDetector
  1784. );
  1785. }
  1786. m_audioDriver = std::make_unique<WallpaperEngine::Audio::Drivers::SDLAudioDriver> (
  1787. this->m_context, *this->m_audioDetector, *this->m_audioRecorder
  1788. );
  1789. m_audioContext = std::make_unique<WallpaperEngine::Audio::AudioContext> (*m_audioDriver);
  1790. }
  1791. void WallpaperApplication::ensureAudioCapture (const Project& project) {
  1792. if (this->m_audioCapturing || !project.supportsAudioProcessing || !this->m_context.settings.audio.audioprocessing
  1793. || !this->m_audioDriver) {
  1794. return;
  1795. }
  1796. sLog.out ("Starting audio capture for ", project.title);
  1797. this->m_previousAudioRecorder = std::move (this->m_audioRecorder);
  1798. this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
  1799. this->m_audioDriver->setRecorder (*this->m_audioRecorder);
  1800. this->m_audioCapturing = true;
  1801. }
  1802. void WallpaperApplication::prepareOutputs () {
  1803. m_renderContext
  1804. = std::make_unique<WallpaperEngine::Render::RenderContext> (*m_videoDriver, *this, *this->m_mediaSource);
  1805. // set all the specific wallpapers required (skip span group synthetic keys)
  1806. for (const auto& [background, info] : this->m_backgrounds) {
  1807. if (background.rfind ("span:", 0) == 0) {
  1808. continue;
  1809. }
  1810. const auto scalingIt = this->m_context.settings.general.screenScalings.find (background);
  1811. const auto clampIt = this->m_context.settings.general.screenClamps.find (background);
  1812. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  1813. ? scalingIt->second
  1814. : this->m_context.settings.render.window.scalingMode;
  1815. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  1816. ? clampIt->second
  1817. : this->m_context.settings.render.window.clamp;
  1818. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  1819. *info->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (background),
  1820. scaling, clamp, this->resolveScreenRenderSize (background)
  1821. );
  1822. wallpaper->setZoom (this->resolveScreenZoom (background));
  1823. const auto offset = this->resolveScreenOffset (background);
  1824. wallpaper->setOffset (offset.x, offset.y);
  1825. wallpaper->setAlignment (this->resolveScreenAlignment (background));
  1826. wallpaper->setCornerColor (this->resolveScreenCornerColor (background));
  1827. wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (background, *info));
  1828. m_renderContext->setWallpaper (background, std::move (wallpaper));
  1829. }
  1830. // Set up span groups: one shared wallpaper per group, registered for each viewport
  1831. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1832. if (spanGroup.screens.empty ()) {
  1833. continue;
  1834. }
  1835. const std::string groupKey = "span:" + spanGroup.screens.front ();
  1836. const auto bgIt = this->m_backgrounds.find (groupKey);
  1837. if (bgIt == this->m_backgrounds.end ()) {
  1838. continue;
  1839. }
  1840. // bounding box of all viewports in this span group
  1841. const auto& viewports = m_renderContext->getOutput ().getViewports ();
  1842. int minX = INT_MAX, minY = INT_MAX, maxX = INT_MIN, maxY = INT_MIN;
  1843. bool anyFound = false;
  1844. for (const auto& screenName : spanGroup.screens) {
  1845. const auto vpIt = viewports.find (screenName);
  1846. if (vpIt == viewports.end ()) {
  1847. sLog.error ("Span group screen not found: ", screenName);
  1848. continue;
  1849. }
  1850. anyFound = true;
  1851. const auto& vp = vpIt->second;
  1852. const int x = vp->globalPosition.x;
  1853. const int y = vp->globalPosition.y;
  1854. const int w = vp->logicalSize.x;
  1855. const int h = vp->logicalSize.y;
  1856. sLog.debug (
  1857. "SPAN DEBUG prepareOutputs: screen '", screenName, "' globalPos=(", x, ",", y, ") logicalSize=", w, "x",
  1858. h
  1859. );
  1860. minX = std::min (minX, x);
  1861. minY = std::min (minY, y);
  1862. maxX = std::max (maxX, x + w);
  1863. maxY = std::max (maxY, y + h);
  1864. }
  1865. if (!anyFound) {
  1866. sLog.error ("No viewports found for span group, skipping");
  1867. continue;
  1868. }
  1869. sLog.debug (
  1870. "SPAN DEBUG prepareOutputs: bounding box=(", minX, ",", minY, ",", maxX - minX, ",", maxY - minY, ")"
  1871. );
  1872. WallpaperEngine::Render::CWallpaper::SpanInfo spanInfo;
  1873. spanInfo.totalBounds = { minX, minY, maxX - minX, maxY - minY };
  1874. auto sharedWallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  1875. *bgIt->second->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (groupKey),
  1876. spanGroup.scaling, spanGroup.clamp, glm::ivec2 { maxX - minX, maxY - minY }
  1877. );
  1878. sharedWallpaper->setZoom (spanGroup.zoom);
  1879. sharedWallpaper->setOffset (spanGroup.offset.x, spanGroup.offset.y);
  1880. sharedWallpaper->setAlignment (spanGroup.alignment);
  1881. sharedWallpaper->setCornerColor (spanGroup.cornerColor);
  1882. sharedWallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (groupKey, *bgIt->second));
  1883. // Convert to shared_ptr so it can be registered for multiple viewports
  1884. std::shared_ptr<WallpaperEngine::Render::CWallpaper> shared (std::move (sharedWallpaper));
  1885. shared->setSpanInfo (spanInfo);
  1886. for (const auto& screenName : spanGroup.screens) {
  1887. m_renderContext->setWallpaper (screenName, shared);
  1888. }
  1889. }
  1890. this->applyAudioPolicy ();
  1891. }
  1892. void WallpaperApplication::setupOpenGLDebugging () {
  1893. // Not gated behind NDEBUG: GL_DEBUG_OUTPUT has near-zero cost when nothing goes wrong, and a
  1894. // Release build silently swallowing driver errors is exactly what's masking the in-process
  1895. // reload corruption bug - see CustomGLDebugCallback() above and the "layer toggle blackens the
  1896. // wallpaper" investigation.
  1897. glDebugMessageCallback (CustomGLDebugCallback, nullptr);
  1898. glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1899. }
  1900. void WallpaperApplication::setup () {
  1901. this->setupOutput ();
  1902. // we_manager launches us with LD_PRELOAD forcing the system's libEGL, because CEF's own
  1903. // bundled libEGL sits next to us on LD_LIBRARY_PATH and would otherwise shadow it and break
  1904. // our own Wayland/EGL output. That preload has already done its job for our own process by
  1905. // this point (setupOutput() above just created our GL context with it) - but it stays in the
  1906. // environment we inherit, and CEF's own subprocesses (spawned lazily, e.g. the GPU process
  1907. // the moment a web wallpaper's WebGL content first needs one) would inherit it too, forcing
  1908. // Mesa's system EGL onto CEF's ANGLE stack instead of the bundled EGL it actually expects.
  1909. // That silently breaks WebGL - no crash, no error, just a canvas that never paints anything.
  1910. // Unsetting it here only affects processes we fork+exec after this point; it doesn't undo
  1911. // anything already loaded into our own process by the dynamic linker at our own startup.
  1912. unsetenv ("LD_PRELOAD");
  1913. this->setupAudio ();
  1914. this->prepareOutputs ();
  1915. this->setupOpenGLDebugging ();
  1916. if (this->m_context.settings.general.dumpStructure) {
  1917. auto prettyPrinter = Data::Dumpers::StringPrinter ();
  1918. for (const auto& [background, info] : this->m_renderContext->getWallpapers ()) {
  1919. prettyPrinter.printWallpaper (info->getWallpaperData ());
  1920. }
  1921. std::cout << prettyPrinter.str () << std::endl;
  1922. }
  1923. #if DEMOMODE
  1924. // ensure only one background is running so everything can be properly caught
  1925. if (this->m_renderContext->getWallpapers ().size () > 1) {
  1926. sLog.exception ("Demo mode only supports one background");
  1927. }
  1928. int width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
  1929. int height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
  1930. std::vector<uint8_t> pixels (width * height * 3);
  1931. bool initialized = false;
  1932. int frame = 0;
  1933. #endif /* DEMOMODE */
  1934. }
  1935. void WallpaperApplication::render () {
  1936. static time_t seconds;
  1937. static struct tm* timeinfo;
  1938. static float rawTimeLast = 0.0f;
  1939. if (this->m_isPaused) {
  1940. usleep (FULLSCREEN_CHECK_WAIT_TIME);
  1941. if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
  1942. return;
  1943. }
  1944. m_renderContext->setPause (false);
  1945. // account for paused duration in playlist timers
  1946. const auto pausedNow = std::chrono::steady_clock::now ();
  1947. const auto pausedDuration = pausedNow - this->m_pauseStart;
  1948. for (auto& [_, playlist] : this->m_activePlaylists) {
  1949. if (!playlist.definition.settings.updateOnPause) {
  1950. playlist.nextSwitch += pausedDuration;
  1951. playlist.lastUpdate += pausedDuration;
  1952. }
  1953. }
  1954. this->m_isPaused = false;
  1955. } else {
  1956. time (&seconds);
  1957. timeinfo = localtime (&seconds);
  1958. g_Daytime = static_cast<float> ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0f * 60.0f);
  1959. // LWE_FIXED_TIMESTEP=<seconds> advances animations by the same step every frame no matter how
  1960. // long the frame really took, so frame N always shows the same moment (regression renders)
  1961. static const float fixedTimestep = [] {
  1962. const char* value = std::getenv ("LWE_FIXED_TIMESTEP");
  1963. return value != nullptr ? std::max (0.0f, std::strtof (value, nullptr)) : 0.0f;
  1964. }();
  1965. const float rawTimeNow = m_videoDriver->getRenderTime ();
  1966. const float rawDelta = fixedTimestep > 0.0f ? fixedTimestep : rawTimeNow - rawTimeLast;
  1967. rawTimeLast = rawTimeNow;
  1968. g_TimeLast = g_Time;
  1969. if (!this->m_context.settings.render.freezeAnimations) {
  1970. g_Time += rawDelta * this->m_context.settings.render.playbackSpeed;
  1971. }
  1972. g_RealTime = fixedTimestep > 0.0f ? g_RealTime + fixedTimestep : rawTimeNow;
  1973. m_audioDriver->update (rawDelta * this->m_context.settings.render.playbackSpeed);
  1974. m_mediaSource->update ();
  1975. m_videoDriver->getInputContext ().update ();
  1976. m_videoDriver->dispatchEventQueue ();
  1977. // read every frame, --fps can change with a hotswap
  1978. const float minimumTime = 1.0f / std::max (1, this->m_context.settings.render.maximumFPS);
  1979. const float frameTime = m_videoDriver->getRenderTime () - rawTimeNow;
  1980. if (frameTime < minimumTime) {
  1981. std::this_thread::sleep_for (std::chrono::duration<float> (minimumTime - frameTime));
  1982. }
  1983. if (m_videoDriver->closeRequested ()) {
  1984. sLog.out ("Stop requested by driver");
  1985. this->m_context.state.general.keepRunning = false;
  1986. }
  1987. #if DEMOMODE
  1988. // wait a full render cycle before starting, giving video/web decoders time to set up
  1989. if (m_videoDriver->getFrameCounter () > (uint32_t)this->m_context.settings.render.maximumFPS) {
  1990. if (!initialized) {
  1991. width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
  1992. height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
  1993. pixels.reserve (width * height * 3);
  1994. init_encoder ("output.webm", width, height);
  1995. initialized = true;
  1996. }
  1997. glBindFramebuffer (
  1998. GL_FRAMEBUFFER, this->m_renderContext->getWallpapers ().begin ()->second->getWallpaperFramebuffer ()
  1999. );
  2000. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  2001. glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data ());
  2002. write_video_frame (pixels.data ());
  2003. frame++;
  2004. if (frame >= FRAME_COUNT) {
  2005. this->m_context.state.general.keepRunning = false;
  2006. }
  2007. }
  2008. #endif /* DEMOMODE */
  2009. if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
  2010. this->m_isPaused = true;
  2011. this->m_pauseStart = std::chrono::steady_clock::now ();
  2012. m_renderContext->setPause (true);
  2013. return;
  2014. }
  2015. }
  2016. this->checkHotswapRequest ();
  2017. this->updatePlaylists ();
  2018. if (!this->m_context.settings.screenshot.take || this->m_screenShotTaken == true) {
  2019. return;
  2020. }
  2021. if (this->m_videoDriver->getFrameCounter () < this->m_nextFrameScreenshot) {
  2022. return;
  2023. }
  2024. this->takeScreenshot (this->m_context.settings.screenshot.path);
  2025. this->m_screenShotTaken = true;
  2026. }
  2027. void WallpaperApplication::cleanup () {
  2028. sLog.out ("Stopping");
  2029. #if DEMOMODE
  2030. close_encoder ();
  2031. #endif /* DEMOMODE */
  2032. SDL_Quit ();
  2033. }
  2034. void WallpaperApplication::show () {
  2035. setup ();
  2036. while (this->m_context.state.general.keepRunning) {
  2037. render ();
  2038. }
  2039. cleanup ();
  2040. }
  2041. void WallpaperApplication::update (Render::Drivers::Output::OutputViewport* viewport) {
  2042. m_renderContext->render (viewport);
  2043. }
  2044. void WallpaperApplication::signal (int signal) {
  2045. if (signal == SIGUSR1) {
  2046. // keep the handler itself trivial, the actual reload happens on the render thread
  2047. this->m_hotswapRequested = true;
  2048. return;
  2049. }
  2050. sLog.out ("Stop requested by signal ", signal);
  2051. this->m_context.state.general.keepRunning = false;
  2052. }
  2053. const std::map<std::string, ProjectUniquePtr>& WallpaperApplication::getBackgrounds () const {
  2054. return this->m_backgrounds;
  2055. }
  2056. ApplicationContext& WallpaperApplication::getContext () const { return this->m_context; }
  2057. const WallpaperEngine::Render::Drivers::Output::Output& WallpaperApplication::getOutput () const {
  2058. return this->m_renderContext->getOutput ();
  2059. }
  2060. void WallpaperApplication::setDestinationFramebuffer (GLuint framebuffer) {
  2061. this->m_destinationFramebuffer = framebuffer;
  2062. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  2063. wallpaper->setDestinationFramebuffer (framebuffer);
  2064. };
  2065. }
  2066. GLuint WallpaperApplication::getDestinationFramebuffer () const { return this->m_destinationFramebuffer; }