WallpaperApplication.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  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/SharedMemoryRenderHandler.h"
  22. #include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
  23. #include "include/cef_browser.h"
  24. #if DEMOMODE
  25. #include "recording.h"
  26. #endif /* DEMOMODE */
  27. #include <algorithm>
  28. #include <cctype>
  29. #include <chrono>
  30. #include <climits>
  31. #include <csignal>
  32. #include <ctime>
  33. #include <fstream>
  34. #include <numeric>
  35. #include <string_view>
  36. #include <unistd.h>
  37. #define STB_IMAGE_WRITE_IMPLEMENTATION
  38. #include <stb_image_write.h>
  39. #include <thread>
  40. #define FULLSCREEN_CHECK_WAIT_TIME 250
  41. float g_Time;
  42. float g_TimeLast;
  43. /** Unscaled wall-clock time, unaffected by --speed */
  44. float g_RealTime;
  45. float g_Daytime;
  46. using namespace WallpaperEngine::Assets;
  47. using namespace WallpaperEngine::Application;
  48. using namespace WallpaperEngine::Data::Model;
  49. using namespace WallpaperEngine::FileSystem;
  50. void CustomGLDebugCallback (
  51. GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam
  52. ) {
  53. // Widened from HIGH-only to catch MEDIUM/LOW too, while chasing the reload-corruption bug
  54. // (bloom-enabled scenes going black after an in-process wallpaper reload) - HIGH-only produced
  55. // nothing even with the driver's debug output confirmed reachable, so the failure isn't a GL
  56. // API validity error at all; it's a logic bug somewhere in scene reconstruction. Safe to narrow
  57. // back to HIGH-only once that's found, but low-severity output costs little in the meantime.
  58. if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
  59. return;
  60. }
  61. // libmpv's own internal renderer (not our code - shows up as libmpv.so/libgallium.so frames in
  62. // the call stack below) reuses a GL_STATIC_DRAW buffer with glBufferSubData every frame during
  63. // video playback, which the driver flags as a performance hint, not a correctness problem. It
  64. // fires on every single frame of every video wallpaper, drowning out anything else in this
  65. // (already widened) severity range.
  66. if (type == GL_DEBUG_TYPE_PERFORMANCE) {
  67. return;
  68. }
  69. sLog.error ("OpenGL error: ", message, ", type: ", type, ", id: ", id, ", severity: ", severity);
  70. std::vector<WallpaperEngine::Debugging::CallStack::CallInfo> callInfo;
  71. WallpaperEngine::Debugging::CallStack::GetCalls (callInfo);
  72. for (std::vector<WallpaperEngine::Debugging::CallStack::CallInfo>::size_type i = 0; i < callInfo.size (); ++i) {
  73. fprintf (
  74. stderr, "[%3lu] %15lu: %s in %s\n", callInfo.size () - i, callInfo[i].offset, callInfo[i].function.c_str (),
  75. callInfo[i].module.c_str ()
  76. );
  77. }
  78. }
  79. bool WallpaperApplication::isCefSubprocess () const {
  80. for (int i = 1; i < this->m_context.getArgc (); i++) {
  81. if (std::string_view (this->m_context.getArgv ()[i]).starts_with ("--type=")) {
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. WallpaperApplication::WallpaperApplication (ApplicationContext& context) : m_context (context) {
  88. this->initializeSubsystems ();
  89. try {
  90. this->loadBackgrounds ();
  91. } catch (const std::exception& e) {
  92. if (!this->isCefSubprocess ()) {
  93. throw;
  94. }
  95. // CEF re-execs this binary for its own subprocesses with a reconstructed argv that doesn't
  96. // always resolve to a loadable background. Must still reach setupBrowser() below regardless
  97. // - that's what calls CefExecuteProcess() to hand off into Chromium's subprocess entrypoint;
  98. // skipping it here leaves CEF's IPC handshake incomplete, which reads as a crashed subprocess
  99. // and gets retried, turning one web wallpaper into several stray processes.
  100. sLog.error ("Skipping background load for CEF subprocess re-exec: ", e.what ());
  101. }
  102. this->setupProperties ();
  103. this->setupAudioSensitivity ();
  104. this->setupSoundVolume ();
  105. this->listObjects ();
  106. this->listAudioObjects ();
  107. this->setupBrowser ();
  108. this->initializePlaylists ();
  109. }
  110. void WallpaperApplication::initializeSubsystems () {
  111. m_mediaSource = std::make_unique<WallpaperEngine::Media::DBusMediaSource> (std::chrono::milliseconds (2000));
  112. }
  113. AssetLocatorUniquePtr WallpaperApplication::setupAssetLocator (const std::string& bg) const {
  114. auto container = std::make_unique<Container> ();
  115. const std::filesystem::path path = bg;
  116. container->registerAdapterFactory (std::make_unique<MediaCoverFactory> (*this->m_mediaSource));
  117. container->mount ("$mediaThumbnail", "$mediaThumbnail");
  118. container->mount (path, "/");
  119. try {
  120. container->mount (path / "scene.pkg", "/");
  121. } catch (std::runtime_error&) { }
  122. try {
  123. container->mount (path / "gifscene.pkg", "/");
  124. } catch (std::runtime_error&) { }
  125. try {
  126. container->mount (this->m_context.settings.general.assets, "/");
  127. } catch (std::runtime_error&) {
  128. sLog.exception ("Cannot find a valid assets folder, resolved to ", this->m_context.settings.general.assets);
  129. }
  130. try {
  131. container->mount (std::filesystem::current_path (), "/");
  132. } catch (std::runtime_error&) { }
  133. auto& vfs = container->getVFS ();
  134. // Had to get a little creative with the effects to achieve the same bloom effect without any custom code:
  135. // these virtual files are loaded by an image in the scene that takes the current _rt_FullFrameBuffer and
  136. // applies the bloom effect to render it out to the screen.
  137. vfs.add (
  138. "effects/wpenginelinux/bloomeffect.json",
  139. { { "name", "camerabloom_wpengine_linux" },
  140. { "group", "wpengine_linux_camera" },
  141. { "dependencies", JSON::array () },
  142. {
  143. "passes",
  144. JSON::array (
  145. { { { "material", "materials/util/downsample_quarter_bloom.json" },
  146. { "target", "_rt_4FrameBuffer" },
  147. { "bind", JSON::array ({ { { "name", "_rt_FullFrameBuffer" }, { "index", 0 } } }) } },
  148. { { "material", "materials/util/downsample_eighth_blur_v.json" },
  149. { "target", "_rt_8FrameBuffer" },
  150. { "bind", JSON::array ({ { { "name", "_rt_4FrameBuffer" }, { "index", 0 } } }) } },
  151. { { "material", "materials/util/blur_h_bloom.json" },
  152. { "target", "_rt_Bloom" },
  153. { "bind", JSON::array ({ { { "name", "_rt_8FrameBuffer" }, { "index", 0 } } }) } },
  154. { { "material", "materials/util/combine.json" },
  155. { "target", "_rt_FullFrameBuffer" },
  156. { "bind",
  157. JSON::array (
  158. { { { "name", "_rt_imageLayerComposite_-1_a" }, { "index", 0 } },
  159. { { "name", "_rt_Bloom" }, { "index", 1 } } }
  160. ) } } }
  161. ),
  162. } }
  163. );
  164. // Wastes a render pass on an image element that exists only to host the bloom material above
  165. vfs.add ("models/wpenginelinux.json", { { "material", "materials/wpenginelinux.json" } });
  166. vfs.add (
  167. "materials/wpenginelinux.json",
  168. { { "passes",
  169. JSON::array (
  170. { { { "blending", "normal" },
  171. { "cullmode", "nocull" },
  172. { "depthtest", "disabled" },
  173. { "depthwrite", "disabled" },
  174. { "shader", "genericimage2" },
  175. { "textures", JSON::array ({ "_rt_FullFrameBuffer" }) } } }
  176. ) } }
  177. );
  178. vfs.add (
  179. "shaders/commands/copy.frag",
  180. "uniform sampler2D g_Texture0;\n"
  181. "in vec2 v_TexCoord;\n"
  182. "void main () {\n"
  183. "out_FragColor = texture (g_Texture0, v_TexCoord);\n"
  184. "}"
  185. );
  186. vfs.add (
  187. "shaders/commands/copy.vert",
  188. "in vec3 a_Position;\n"
  189. "in vec2 a_TexCoord;\n"
  190. "out vec2 v_TexCoord;\n"
  191. "void main () {\n"
  192. "gl_Position = vec4 (a_Position, 1.0);\n"
  193. "v_TexCoord = a_TexCoord;\n"
  194. "}"
  195. );
  196. return std::make_unique<AssetLocator> (std::move (container));
  197. }
  198. void WallpaperApplication::loadBackgrounds () {
  199. if (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  200. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW) {
  201. auto path = this->m_context.settings.general.defaultBackground;
  202. if (this->m_context.settings.general.defaultPlaylist.has_value ()
  203. && !this->m_context.settings.general.defaultPlaylist->items.empty ()) {
  204. path = this->m_context.settings.general.defaultPlaylist->items.front ();
  205. }
  206. this->m_backgrounds["default"] = this->loadBackground (path);
  207. return;
  208. }
  209. for (const auto& [screen, path] : this->m_context.settings.general.screenBackgrounds) {
  210. // skip span group synthetic keys here, they're handled below
  211. if (screen.rfind ("span:", 0) == 0) {
  212. continue;
  213. }
  214. if (path.empty ()) {
  215. this->m_backgrounds[screen] = this->loadBackground (this->m_context.settings.general.defaultBackground);
  216. } else {
  217. this->m_backgrounds[screen] = this->loadBackground (path);
  218. }
  219. }
  220. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  221. if (spanGroup.screens.empty ()) {
  222. continue;
  223. }
  224. std::filesystem::path bgPath = spanGroup.background;
  225. if (bgPath.empty ()) {
  226. bgPath = this->m_context.settings.general.defaultBackground;
  227. }
  228. // "span:" + first screen's name is the convention used as the group key
  229. const std::string groupKey = "span:" + spanGroup.screens.front ();
  230. this->m_backgrounds[groupKey] = this->loadBackground (bgPath);
  231. }
  232. }
  233. ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
  234. auto container = this->setupAssetLocator (bg);
  235. auto json = WallpaperEngine::Data::JSON::JSON::parse (container->readString ("project.json"));
  236. // reset screenshot state so a background change (e.g. playlist advance) can screenshot again
  237. if (this->m_context.settings.screenshot.take) {
  238. this->m_nextFrameScreenshot = this->m_context.settings.screenshot.delay;
  239. if (this->m_videoDriver != nullptr) {
  240. this->m_nextFrameScreenshot += this->m_videoDriver->getFrameCounter ();
  241. }
  242. this->m_screenShotTaken = false;
  243. }
  244. return WallpaperEngine::Data::Parsers::ProjectParser::parse (json, std::move (container));
  245. }
  246. std::vector<std::size_t>
  247. WallpaperApplication::buildPlaylistOrder (const ApplicationContext::PlaylistDefinition& definition) {
  248. std::vector<std::size_t> order (definition.items.size ());
  249. std::iota (order.begin (), order.end (), 0);
  250. if (definition.settings.order == "random") {
  251. std::shuffle (order.begin (), order.end (), this->m_playlistRng);
  252. }
  253. return order;
  254. }
  255. void WallpaperApplication::initializePlaylists () {
  256. const bool hasDefaultPlaylist = this->m_context.settings.general.defaultPlaylist.has_value ();
  257. const bool hasScreenPlaylists = !this->m_context.settings.general.screenPlaylists.empty ();
  258. if (!hasDefaultPlaylist && !hasScreenPlaylists) {
  259. return;
  260. }
  261. const auto now = std::chrono::steady_clock::now ();
  262. auto registerPlaylist = [this, now] (
  263. const std::string& key, const ApplicationContext::PlaylistDefinition& playlist,
  264. std::optional<std::filesystem::path> currentPath
  265. ) {
  266. if (playlist.items.empty ()) {
  267. return;
  268. }
  269. ActivePlaylist state;
  270. state.definition = playlist;
  271. state.order = this->buildPlaylistOrder (playlist);
  272. if (state.order.empty ()) {
  273. return;
  274. }
  275. if (currentPath.has_value ()) {
  276. state.orderIndex = 0;
  277. for (std::size_t i = 0; i < state.order.size (); i++) {
  278. if (playlist.items[state.order[i]] == currentPath.value ()) {
  279. state.orderIndex = i;
  280. break;
  281. }
  282. }
  283. }
  284. const uint32_t delayMinutes = std::max<uint32_t> (1, state.definition.settings.delayMinutes);
  285. state.nextSwitch = now + std::chrono::minutes (delayMinutes);
  286. state.lastUpdate = now;
  287. this->m_activePlaylists.insert_or_assign (key, std::move (state));
  288. };
  289. if (hasDefaultPlaylist
  290. && (this->m_context.settings.render.mode == ApplicationContext::NORMAL_WINDOW
  291. || this->m_context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW)) {
  292. const auto& playlist = this->m_context.settings.general.defaultPlaylist.value ();
  293. const auto currentPath = playlist.items.empty ()
  294. ? std::optional<std::filesystem::path> { this->m_context.settings.general.defaultBackground }
  295. : std::optional<std::filesystem::path> { playlist.items.front () };
  296. registerPlaylist ("default", playlist, currentPath);
  297. }
  298. for (const auto& [screen, playlist] : this->m_context.settings.general.screenPlaylists) {
  299. const auto current = this->m_context.settings.general.screenBackgrounds.find (screen);
  300. const auto currentPath = current != this->m_context.settings.general.screenBackgrounds.end ()
  301. ? std::optional<std::filesystem::path> { current->second }
  302. : std::nullopt;
  303. registerPlaylist (screen, playlist, currentPath);
  304. }
  305. }
  306. bool WallpaperApplication::makeAnyViewportCurrent () const {
  307. if (!this->m_renderContext) {
  308. return false;
  309. }
  310. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  311. if (viewports.empty ()) {
  312. return false;
  313. }
  314. viewports.begin ()->second->makeCurrent ();
  315. return true;
  316. }
  317. bool WallpaperApplication::preflightWallpaper (const std::string& path) {
  318. try {
  319. // avoid mutating state, just ensure project.json parses
  320. auto container = this->setupAssetLocator (path);
  321. const auto json = WallpaperEngine::Data::JSON::JSON::parse (container->readString ("project.json"));
  322. if (!json.contains ("type") || !json.contains ("file")) {
  323. sLog.error ("Preflight failed for ", path, ": missing required fields");
  324. return false;
  325. }
  326. return true;
  327. } catch (const std::exception& e) {
  328. sLog.error ("Preflight failed for ", path, ": ", e.what ());
  329. return false;
  330. }
  331. }
  332. bool WallpaperApplication::selectNextCandidate (ActivePlaylist& playlist, std::size_t& outOrderIndex) {
  333. if (playlist.order.empty ()) {
  334. return false;
  335. }
  336. std::size_t attempts = 0;
  337. std::size_t candidateOrderIndex = outOrderIndex;
  338. while (attempts < playlist.order.size ()) {
  339. const auto candidateIndex = playlist.order[candidateOrderIndex];
  340. if (!playlist.failedIndices.contains (candidateIndex)) {
  341. outOrderIndex = candidateOrderIndex;
  342. return true;
  343. }
  344. attempts++;
  345. candidateOrderIndex = (candidateOrderIndex + 1) % playlist.order.size ();
  346. }
  347. return false;
  348. }
  349. void WallpaperApplication::advancePlaylist (
  350. const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
  351. ) {
  352. if (playlist.order.empty ()) {
  353. return;
  354. }
  355. playlist.orderIndex = (playlist.orderIndex + 1) % playlist.order.size ();
  356. if (playlist.orderIndex == 0 && playlist.definition.settings.order == "random") {
  357. std::shuffle (playlist.order.begin (), playlist.order.end (), this->m_playlistRng);
  358. }
  359. std::size_t candidateOrderIndex = playlist.orderIndex;
  360. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  361. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  362. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  363. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  364. return;
  365. }
  366. const auto candidateIndex = playlist.order[candidateOrderIndex];
  367. const auto& candidatePath = playlist.definition.items[candidateIndex];
  368. if (!this->preflightWallpaper (candidatePath.string ())) {
  369. playlist.failedIndices.insert (candidateIndex);
  370. if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
  371. sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
  372. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  373. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  374. return;
  375. }
  376. }
  377. playlist.orderIndex = candidateOrderIndex;
  378. const auto& nextPath = playlist.definition.items[playlist.order[playlist.orderIndex]];
  379. bool loaded = false;
  380. try {
  381. if (!this->makeAnyViewportCurrent ()) {
  382. sLog.error ("Cannot switch playlist on ", screen, ": no active viewport");
  383. throw std::runtime_error ("No viewport available");
  384. }
  385. auto project = this->loadBackground (nextPath.string ());
  386. this->setupPropertiesForProject (*project);
  387. this->m_backgrounds[screen] = std::move (project);
  388. const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
  389. const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
  390. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  391. ? scalingIt->second
  392. : this->m_context.settings.render.window.scalingMode;
  393. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  394. ? clampIt->second
  395. : this->m_context.settings.render.window.clamp;
  396. if (this->m_renderContext) {
  397. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  398. *this->m_backgrounds[screen]->wallpaper, *this->m_renderContext, *this->m_audioContext, nextPath,
  399. scaling, clamp, this->resolveScreenRenderSize (screen)
  400. );
  401. wallpaper->setZoom (this->resolveScreenZoom (screen));
  402. wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
  403. this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
  404. this->applyAudioPolicy ();
  405. }
  406. this->m_context.settings.general.screenBackgrounds[screen] = nextPath;
  407. loaded = true;
  408. } catch (const std::exception& e) {
  409. sLog.error ("Failed to advance playlist on ", screen, ": ", e.what ());
  410. }
  411. if (!loaded) {
  412. playlist.failedIndices.insert (playlist.order[playlist.orderIndex]);
  413. // Keep current position; next timer tick will retry advancement
  414. sLog.error ("Failed to load wallpaper for ", screen, ", will retry on next cycle");
  415. }
  416. const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
  417. playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
  418. }
  419. void WallpaperApplication::updatePlaylists () {
  420. if (this->m_activePlaylists.empty ()) {
  421. return;
  422. }
  423. const auto now = std::chrono::steady_clock::now ();
  424. for (auto& [screen, playlist] : this->m_activePlaylists) {
  425. playlist.lastUpdate = now;
  426. if (playlist.definition.settings.mode != "timer") {
  427. continue;
  428. }
  429. if (playlist.definition.items.size () <= 1) {
  430. continue;
  431. }
  432. if (now < playlist.nextSwitch) {
  433. continue;
  434. }
  435. this->advancePlaylist (screen, playlist, now);
  436. }
  437. }
  438. namespace {
  439. /** Everything a control-file request can carry; any field left unset means "don't touch this" */
  440. struct HotswapRequest {
  441. std::optional<std::string> path;
  442. /** True once a "layers=1" line was seen, meaning disabledObjects/enabledObjects below are a full replacement */
  443. bool layersProvided = false;
  444. std::vector<std::string> disabledObjects;
  445. std::vector<std::string> enabledObjects;
  446. /** True once at least one "property=name=value" line was seen */
  447. bool propertiesProvided = false;
  448. std::map<std::string, std::string> properties;
  449. std::optional<int> volume;
  450. /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
  451. std::optional<std::string> xray;
  452. /** "stretch"/"fit"/"fill"/"center"/"default" */
  453. std::optional<std::string> scaling;
  454. /** floating-point zoom factor layered on top of scaling, e.g. "1.5" */
  455. std::optional<std::string> zoom;
  456. /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
  457. std::optional<std::string> disableParallax;
  458. /** hex RGB/RGBA color, e.g. "000000" or "#1a1a1aff" */
  459. std::optional<std::string> cornerColor;
  460. /** floating-point playback speed multiplier, e.g. "0.5" */
  461. std::optional<std::string> speed;
  462. /** screen name to restrict audio to, or "" to clear the restriction, see --audio-screen */
  463. std::optional<std::string> audioScreen;
  464. /** 0-128, see --ambient-volume */
  465. std::optional<std::string> ambientVolume;
  466. /** True once at least one "audio-sensitivity=id=multiplier" line was seen */
  467. bool audioSensitivityProvided = false;
  468. std::map<std::string, std::string> audioSensitivity;
  469. /** True once at least one "sound-volume=id=volume" line was seen */
  470. bool soundVolumeProvided = false;
  471. std::map<std::string, std::string> soundVolume;
  472. };
  473. std::string trimHotswapToken (const std::string& value) {
  474. std::size_t begin = 0;
  475. std::size_t end = value.size ();
  476. while (begin < end && std::isspace (static_cast<unsigned char> (value[begin]))) {
  477. begin++;
  478. }
  479. while (end > begin && std::isspace (static_cast<unsigned char> (value[end - 1]))) {
  480. end--;
  481. }
  482. return value.substr (begin, end - begin);
  483. }
  484. /**
  485. * Parses the control file. Supports the original bare-path-on-one-line format for backwards
  486. * compatibility, plus key=value lines (path/layers/disable-object/enable-object/volume/xray/scaling/zoom/
  487. * disable-parallax/corner-color/speed/audio-screen/ambient-volume/property) so a single request can carry
  488. * more than just the background path. "property=name=value" (repeatable) carries --set-property-equivalent
  489. * overrides.
  490. */
  491. HotswapRequest parseHotswapRequest (std::istream& file) {
  492. HotswapRequest request;
  493. std::string rawLine;
  494. while (std::getline (file, rawLine)) {
  495. const std::string line = trimHotswapToken (rawLine);
  496. if (line.empty ()) {
  497. continue;
  498. }
  499. const auto separator = line.find ('=');
  500. if (separator == std::string::npos) {
  501. // legacy format: the whole line is the new background path
  502. if (!request.path.has_value ()) {
  503. request.path = line;
  504. }
  505. continue;
  506. }
  507. const std::string key = trimHotswapToken (line.substr (0, separator));
  508. const std::string value = trimHotswapToken (line.substr (separator + 1));
  509. if (key == "path") {
  510. request.path = value;
  511. } else if (key == "layers") {
  512. request.layersProvided = true;
  513. } else if (key == "disable-object") {
  514. request.layersProvided = true;
  515. request.disabledObjects.push_back (value);
  516. } else if (key == "enable-object") {
  517. request.layersProvided = true;
  518. request.enabledObjects.push_back (value);
  519. } else if (key == "volume") {
  520. try {
  521. request.volume = std::stoi (value);
  522. } catch (const std::exception&) {
  523. sLog.error ("Hotswap: ignoring invalid volume value: ", value);
  524. }
  525. } else if (key == "xray") {
  526. request.xray = value;
  527. } else if (key == "scaling") {
  528. request.scaling = value;
  529. } else if (key == "zoom") {
  530. request.zoom = value;
  531. } else if (key == "disable-parallax") {
  532. request.disableParallax = value;
  533. } else if (key == "corner-color") {
  534. request.cornerColor = value;
  535. } else if (key == "speed") {
  536. request.speed = value;
  537. } else if (key == "audio-screen") {
  538. request.audioScreen = value;
  539. } else if (key == "ambient-volume") {
  540. request.ambientVolume = value;
  541. } else if (key == "property") {
  542. const auto propSeparator = value.find ('=');
  543. if (propSeparator == std::string::npos) {
  544. sLog.error ("Hotswap: ignoring malformed property line: ", value);
  545. } else {
  546. request.propertiesProvided = true;
  547. request.properties[value.substr (0, propSeparator)] = value.substr (propSeparator + 1);
  548. }
  549. } else if (key == "audio-sensitivity") {
  550. const auto sensSeparator = value.find ('=');
  551. if (sensSeparator == std::string::npos) {
  552. sLog.error ("Hotswap: ignoring malformed audio-sensitivity line: ", value);
  553. } else {
  554. request.audioSensitivityProvided = true;
  555. request.audioSensitivity[value.substr (0, sensSeparator)] = value.substr (sensSeparator + 1);
  556. }
  557. } else if (key == "sound-volume") {
  558. const auto volSeparator = value.find ('=');
  559. if (volSeparator == std::string::npos) {
  560. sLog.error ("Hotswap: ignoring malformed sound-volume line: ", value);
  561. } else {
  562. request.soundVolumeProvided = true;
  563. request.soundVolume[value.substr (0, volSeparator)] = value.substr (volSeparator + 1);
  564. }
  565. } else {
  566. sLog.error ("Hotswap: ignoring unknown control file key: ", key);
  567. }
  568. }
  569. return request;
  570. }
  571. } // namespace
  572. void WallpaperApplication::checkHotswapRequest () {
  573. if (!this->m_hotswapRequested.exchange (false)) {
  574. return;
  575. }
  576. const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
  577. const auto controlFile = std::filesystem::path (runtimeDir != nullptr ? runtimeDir : "/tmp") / "lwe-control";
  578. std::ifstream file (controlFile);
  579. if (!file.is_open ()) {
  580. sLog.error ("Hotswap requested but control file could not be read: ", controlFile.string ());
  581. return;
  582. }
  583. const auto request = parseHotswapRequest (file);
  584. if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
  585. && !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
  586. && !request.disableParallax.has_value () && !request.cornerColor.has_value ()
  587. && !request.speed.has_value () && !request.audioScreen.has_value () && !request.ambientVolume.has_value ()
  588. && !request.propertiesProvided && !request.audioSensitivityProvided && !request.soundVolumeProvided) {
  589. sLog.error ("Hotswap requested but control file was empty");
  590. return;
  591. }
  592. if (request.volume.has_value ()) {
  593. this->applyVolumeHotswap (*request.volume);
  594. }
  595. if (request.xray.has_value ()) {
  596. this->applyXrayHotswap (*request.xray);
  597. }
  598. if (request.scaling.has_value ()) {
  599. this->applyScalingHotswap (*request.scaling);
  600. }
  601. if (request.zoom.has_value ()) {
  602. this->applyZoomHotswap (*request.zoom);
  603. }
  604. if (request.disableParallax.has_value ()) {
  605. this->applyParallaxHotswap (*request.disableParallax);
  606. }
  607. if (request.cornerColor.has_value ()) {
  608. this->applyCornerColorHotswap (*request.cornerColor);
  609. }
  610. if (request.speed.has_value ()) {
  611. this->applySpeedHotswap (*request.speed);
  612. }
  613. if (request.audioScreen.has_value ()) {
  614. this->applyAudioScreenHotswap (*request.audioScreen);
  615. }
  616. if (request.ambientVolume.has_value ()) {
  617. this->applyAmbientVolumeHotswap (*request.ambientVolume);
  618. }
  619. if (request.soundVolumeProvided) {
  620. this->applySoundVolumeHotswap (request.soundVolume);
  621. }
  622. if (request.layersProvided) {
  623. this->m_context.settings.general.disabledObjects = request.disabledObjects;
  624. this->m_context.settings.general.enabledObjects = request.enabledObjects;
  625. }
  626. if (request.propertiesProvided) {
  627. for (const auto& [name, value] : request.properties) {
  628. this->m_context.settings.general.properties[name] = value;
  629. }
  630. }
  631. if (request.audioSensitivityProvided) {
  632. for (const auto& [target, value] : request.audioSensitivity) {
  633. try {
  634. this->m_context.settings.general.audioSensitivity[target] = std::stof (value);
  635. } catch (const std::exception&) {
  636. sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", value);
  637. }
  638. }
  639. }
  640. // volume/xray/speed-only requests are pure live setters with nothing to reload. Properties
  641. // and audio sensitivity, like layers, are baked into the scene graph at parse time, so they
  642. // need the same reload.
  643. if (!request.path.has_value () && !request.layersProvided && !request.propertiesProvided
  644. && !request.audioSensitivityProvided) {
  645. return;
  646. }
  647. if (request.path.has_value () && !this->preflightWallpaper (*request.path)) {
  648. sLog.error ("Hotswap failed, invalid wallpaper at ", *request.path);
  649. return;
  650. }
  651. if (!this->makeAnyViewportCurrent ()) {
  652. sLog.error ("Hotswap failed, no active viewport");
  653. return;
  654. }
  655. if (request.path.has_value ()) {
  656. sLog.out ("Hotswapping wallpaper to ", *request.path);
  657. } else {
  658. sLog.out ("Hotswapping wallpaper layers");
  659. }
  660. for (auto& [screen, background] : this->m_backgrounds) {
  661. const std::string targetPath = request.path.value_or (this->resolveScreenBackgroundPath (screen));
  662. try {
  663. auto project = this->loadBackground (targetPath);
  664. this->setupPropertiesForProject (*project);
  665. this->setupAudioSensitivityForProject (*project);
  666. this->setupSoundVolumeForProject (*project);
  667. background = std::move (project);
  668. const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
  669. const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
  670. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  671. ? scalingIt->second
  672. : this->m_context.settings.render.window.scalingMode;
  673. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  674. ? clampIt->second
  675. : this->m_context.settings.render.window.clamp;
  676. if (this->m_renderContext) {
  677. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  678. *background->wallpaper, *this->m_renderContext, *this->m_audioContext, targetPath, scaling, clamp,
  679. this->resolveScreenRenderSize (screen)
  680. );
  681. wallpaper->setZoom (this->resolveScreenZoom (screen));
  682. wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
  683. this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
  684. }
  685. if (request.path.has_value ()) {
  686. if (screen.starts_with ("span:")) {
  687. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  688. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  689. spanGroup.background = *request.path;
  690. }
  691. }
  692. } else {
  693. this->m_context.settings.general.screenBackgrounds[screen] = *request.path;
  694. }
  695. }
  696. } catch (const std::exception& e) {
  697. sLog.error ("Hotswap failed for screen ", screen, ": ", e.what ());
  698. }
  699. }
  700. this->applyAudioPolicy ();
  701. if (request.path.has_value ()) {
  702. this->m_context.settings.general.defaultBackground = *request.path;
  703. }
  704. }
  705. std::string WallpaperApplication::resolveScreenBackgroundPath (const std::string& screen) const {
  706. if (screen.starts_with ("span:")) {
  707. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  708. if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
  709. return spanGroup.background.empty () ? this->m_context.settings.general.defaultBackground.string ()
  710. : spanGroup.background.string ();
  711. }
  712. }
  713. return this->m_context.settings.general.defaultBackground.string ();
  714. }
  715. const auto it = this->m_context.settings.general.screenBackgrounds.find (screen);
  716. if (it != this->m_context.settings.general.screenBackgrounds.end () && !it->second.empty ()) {
  717. return it->second.string ();
  718. }
  719. return this->m_context.settings.general.defaultBackground.string ();
  720. }
  721. float WallpaperApplication::resolveScreenZoom (const std::string& screen) const {
  722. const auto it = this->m_context.settings.general.screenZooms.find (screen);
  723. return it != this->m_context.settings.general.screenZooms.end () ? it->second
  724. : this->m_context.settings.render.window.zoom;
  725. }
  726. glm::vec4 WallpaperApplication::resolveScreenCornerColor (const std::string& screen) const {
  727. const auto it = this->m_context.settings.general.screenCornerColors.find (screen);
  728. return it != this->m_context.settings.general.screenCornerColors.end ()
  729. ? it->second
  730. : this->m_context.settings.render.window.cornerColor;
  731. }
  732. glm::ivec2 WallpaperApplication::resolveScreenRenderSize (const std::string& screen) const {
  733. const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
  734. const auto it = viewports.find (screen);
  735. if (it != viewports.end ()) {
  736. return { it->second->viewport.z, it->second->viewport.w };
  737. }
  738. return { this->m_renderContext->getOutput ().getFullWidth (), this->m_renderContext->getOutput ().getFullHeight () };
  739. }
  740. void WallpaperApplication::applyVolumeHotswap (int volume) {
  741. volume = std::max (0, std::min (volume, 128));
  742. this->m_context.settings.audio.volume = volume;
  743. this->m_context.state.audio.volume = volume;
  744. if (!this->m_renderContext) {
  745. return;
  746. }
  747. const double scaledVolume = this->m_context.settings.audio.enabled ? volume * 100.0 / 128.0 : 0.0;
  748. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  749. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  750. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setVolume (scaledVolume);
  751. }
  752. }
  753. sLog.out ("Hotswap: applied volume ", volume, " live");
  754. }
  755. void WallpaperApplication::applyXrayHotswap (const std::string& value) {
  756. bool newState;
  757. if (value == "toggle") {
  758. newState = !this->m_context.state.xray.fullReveal;
  759. } else if (value == "on" || value == "1" || value == "true") {
  760. newState = true;
  761. } else if (value == "off" || value == "0" || value == "false") {
  762. newState = false;
  763. } else {
  764. sLog.error ("Hotswap: ignoring invalid xray value: ", value);
  765. return;
  766. }
  767. this->m_context.state.xray.fullReveal = newState;
  768. sLog.out ("Hotswap: full xray ", newState ? "enabled" : "disabled", " live");
  769. }
  770. void WallpaperApplication::applyScalingHotswap (const std::string& value) {
  771. const auto mode = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
  772. if (!mode.has_value ()) {
  773. sLog.error ("Hotswap: ignoring invalid scaling value: ", value);
  774. return;
  775. }
  776. this->m_context.settings.render.window.scalingMode = *mode;
  777. for (auto& [screen, scaling] : this->m_context.settings.general.screenScalings) {
  778. scaling = *mode;
  779. }
  780. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  781. spanGroup.scaling = *mode;
  782. }
  783. if (this->m_renderContext) {
  784. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  785. wallpaper->setScalingMode (*mode);
  786. }
  787. }
  788. sLog.out ("Hotswap: applied scaling mode ", value, " live");
  789. }
  790. void WallpaperApplication::applyZoomHotswap (const std::string& value) {
  791. float zoom;
  792. try {
  793. zoom = std::stof (value);
  794. } catch (const std::exception&) {
  795. sLog.error ("Hotswap: ignoring invalid zoom value: ", value);
  796. return;
  797. }
  798. this->m_context.settings.render.window.zoom = zoom;
  799. for (auto& [screen, screenZoom] : this->m_context.settings.general.screenZooms) {
  800. screenZoom = zoom;
  801. }
  802. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  803. spanGroup.zoom = zoom;
  804. }
  805. if (this->m_renderContext) {
  806. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  807. wallpaper->setZoom (zoom);
  808. }
  809. }
  810. sLog.out ("Hotswap: applied zoom ", zoom, " live");
  811. }
  812. void WallpaperApplication::applyParallaxHotswap (const std::string& value) {
  813. bool newState;
  814. if (value == "toggle") {
  815. newState = !this->m_context.settings.mouse.disableparallax;
  816. } else if (value == "on" || value == "1" || value == "true") {
  817. newState = true;
  818. } else if (value == "off" || value == "0" || value == "false") {
  819. newState = false;
  820. } else {
  821. sLog.error ("Hotswap: ignoring invalid disable-parallax value: ", value);
  822. return;
  823. }
  824. this->m_context.settings.mouse.disableparallax = newState;
  825. sLog.out ("Hotswap: parallax ", newState ? "force-disabled" : "enabled", " live");
  826. }
  827. void WallpaperApplication::applyCornerColorHotswap (const std::string& value) {
  828. const auto color = WallpaperEngine::Render::CFBO::parseColor (value);
  829. if (!color.has_value ()) {
  830. sLog.error ("Hotswap: ignoring invalid corner color: ", value);
  831. return;
  832. }
  833. this->m_context.settings.render.window.cornerColor = *color;
  834. for (auto& [screen, screenColor] : this->m_context.settings.general.screenCornerColors) {
  835. screenColor = *color;
  836. }
  837. for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
  838. spanGroup.cornerColor = *color;
  839. }
  840. if (this->m_renderContext) {
  841. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  842. wallpaper->setCornerColor (*color);
  843. }
  844. }
  845. sLog.out ("Hotswap: applied corner color ", value, " live");
  846. }
  847. void WallpaperApplication::applySpeedHotswap (const std::string& value) {
  848. float speed;
  849. try {
  850. speed = std::stof (value);
  851. } catch (const std::exception&) {
  852. sLog.error ("Hotswap: ignoring invalid speed value: ", value);
  853. return;
  854. }
  855. if (speed <= 0.0f) {
  856. sLog.error ("Hotswap: ignoring non-positive speed value: ", value);
  857. return;
  858. }
  859. this->m_context.settings.render.playbackSpeed = speed;
  860. // Particles/effects/scripts read settings.render.playbackSpeed directly every frame, but
  861. // video wallpapers are driven by mpv's own clock and need the change pushed explicitly.
  862. if (this->m_renderContext) {
  863. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  864. if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
  865. wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setSpeed (speed);
  866. }
  867. }
  868. }
  869. sLog.out ("Hotswap: applied speed ", speed, " live");
  870. }
  871. void WallpaperApplication::applyAudioScreenHotswap (const std::string& value) {
  872. this->m_context.settings.audio.audioScreen = value.empty () ? std::nullopt : std::optional<std::string> (value);
  873. this->applyAudioPolicy ();
  874. sLog.out ("Hotswap: applied audio screen '", value, "' live");
  875. }
  876. void WallpaperApplication::applyAmbientVolumeHotswap (const std::string& value) {
  877. int volume;
  878. try {
  879. volume = std::stoi (value);
  880. } catch (const std::exception&) {
  881. sLog.error ("Hotswap: ignoring invalid ambient volume value: ", value);
  882. return;
  883. }
  884. this->m_context.settings.audio.ambientVolume = std::max (0, std::min (volume, 128));
  885. this->applyAudioPolicy ();
  886. sLog.out ("Hotswap: applied ambient volume ", volume, " live");
  887. }
  888. void WallpaperApplication::applyAudioPolicy () {
  889. if (!this->m_renderContext) {
  890. return;
  891. }
  892. const auto& audioScreen = this->m_context.settings.audio.audioScreen;
  893. const auto& ambientVolume = this->m_context.settings.audio.ambientVolume;
  894. std::map<WallpaperEngine::Render::CWallpaper*, bool> wantMuted;
  895. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  896. const bool screenMuted = audioScreen.has_value () && screen != *audioScreen;
  897. auto [it, inserted] = wantMuted.try_emplace (wallpaper.get (), screenMuted);
  898. if (!inserted) {
  899. it->second = it->second && screenMuted;
  900. }
  901. }
  902. for (const auto& [wallpaper, muted] : wantMuted) {
  903. wallpaper->setAudioPolicy (muted, ambientVolume);
  904. }
  905. }
  906. void WallpaperApplication::setupPropertiesForProject (const Project& project) {
  907. for (const auto& [key, cur] : project.properties) {
  908. auto override = this->m_context.settings.general.properties.find (key);
  909. if (override != this->m_context.settings.general.properties.end ()) {
  910. sLog.out ("Applying override value for ", key);
  911. cur->update (override->second, DynamicValue::UpdateSource::User);
  912. }
  913. if (this->m_context.settings.general.onlyListProperties) {
  914. sLog.out (cur->dump ());
  915. }
  916. }
  917. }
  918. void WallpaperApplication::setupProperties () {
  919. for (const auto& [background, info] : this->m_backgrounds) {
  920. this->setupPropertiesForProject (*info);
  921. }
  922. }
  923. void WallpaperApplication::listObjectsForProject (const std::string& background, const Project& project) const {
  924. if (!project.wallpaper->is<Scene> ()) {
  925. return;
  926. }
  927. const auto scene = project.wallpaper->as<Scene> ();
  928. sLog.out ("Objects for ", background, ":");
  929. for (const auto& object : scene->objects) {
  930. std::string type = "unknown";
  931. if (object->is<Image> ()) {
  932. type = "image";
  933. } else if (object->is<Particle> ()) {
  934. type = "particle";
  935. } else if (object->is<Text> ()) {
  936. type = "text";
  937. } else if (object->is<Sound> ()) {
  938. type = "sound";
  939. }
  940. sLog.out (" ", object->id, " - ", object->name, " (", type, ")");
  941. }
  942. }
  943. void WallpaperApplication::listObjects () const {
  944. if (!this->m_context.settings.general.onlyListObjects) {
  945. return;
  946. }
  947. for (const auto& [background, info] : this->m_backgrounds) {
  948. this->listObjectsForProject (background, *info);
  949. }
  950. }
  951. namespace {
  952. struct AudioReactiveProperty {
  953. std::string name;
  954. DynamicValue* value;
  955. };
  956. void considerAudioReactive (
  957. std::vector<AudioReactiveProperty>& result, const std::string& name, const UserSettingUniquePtr& setting
  958. ) {
  959. if (!setting || !setting->value) {
  960. return;
  961. }
  962. const auto& source = setting->value->getScriptSource ();
  963. if (source.has_value () && source->find ("registerAudioBuffers") != std::string::npos) {
  964. result.push_back ({ name, setting->value.get () });
  965. }
  966. }
  967. // Mirrors exactly the set of fields ScriptableObject/CImage/CText/CParticle register with the
  968. // script engine (see Scripting/ScriptableObject.cpp, Render/Objects/CImage.cpp, CText.cpp,
  969. // CParticle.cpp) - "origin" is always the base object's own field (never overridden per-type),
  970. // while scale/angles/visible fall back to the generic group* fields only for object types that
  971. // don't provide their own (Sound, Light, plain groups).
  972. std::vector<AudioReactiveProperty> collectAudioReactiveProperties (const Object& object) {
  973. std::vector<AudioReactiveProperty> result;
  974. considerAudioReactive (result, "origin", object.origin);
  975. if (object.is<Image> ()) {
  976. const auto* image = object.as<Image> ();
  977. considerAudioReactive (result, "scale", image->scale);
  978. considerAudioReactive (result, "angles", image->angles);
  979. considerAudioReactive (result, "visible", image->visible);
  980. considerAudioReactive (result, "alpha", image->alpha);
  981. considerAudioReactive (result, "color", image->color);
  982. considerAudioReactive (result, "parallaxDepth", image->parallaxDepth);
  983. } else if (object.is<Text> ()) {
  984. const auto* text = object.as<Text> ();
  985. considerAudioReactive (result, "scale", text->scale);
  986. considerAudioReactive (result, "color", text->color);
  987. considerAudioReactive (result, "alpha", text->alpha);
  988. considerAudioReactive (result, "visible", text->visible);
  989. considerAudioReactive (result, "pointSize", text->pointSize);
  990. considerAudioReactive (result, "text", text->text);
  991. considerAudioReactive (result, "parallaxDepth", text->parallaxDepth);
  992. } else if (object.is<Particle> ()) {
  993. const auto* particle = object.as<Particle> ();
  994. considerAudioReactive (result, "scale", particle->scale);
  995. considerAudioReactive (result, "angles", particle->angles);
  996. considerAudioReactive (result, "visible", particle->visible);
  997. considerAudioReactive (result, "parallaxDepth", particle->parallaxDepth);
  998. } else {
  999. considerAudioReactive (result, "scale", object.groupScale);
  1000. considerAudioReactive (result, "angles", object.groupAngles);
  1001. considerAudioReactive (result, "visible", object.groupVisible);
  1002. }
  1003. return result;
  1004. }
  1005. float readScriptPropertyFloat (DynamicValue& value, const std::string& key) {
  1006. auto& properties = value.getProperties ();
  1007. const auto it = properties.find (key);
  1008. return it != properties.end () && it->second && it->second->value ? it->second->value->getFloat () : 0.0f;
  1009. }
  1010. } // namespace
  1011. void WallpaperApplication::listAudioObjectsForProject (const std::string& background, const Project& project) const {
  1012. if (!project.wallpaper->is<Scene> ()) {
  1013. return;
  1014. }
  1015. const auto scene = project.wallpaper->as<Scene> ();
  1016. sLog.out ("Audio-reactive objects for ", background, ":");
  1017. for (const auto& object : scene->objects) {
  1018. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1019. sLog.out (
  1020. " ", object->id, " - ", object->name, " (", reactive.name, "): minvalue=",
  1021. readScriptPropertyFloat (*reactive.value, "minvalue"), " maxvalue=",
  1022. readScriptPropertyFloat (*reactive.value, "maxvalue"), " frequency=",
  1023. readScriptPropertyFloat (*reactive.value, "frequency"), " smoothing=",
  1024. readScriptPropertyFloat (*reactive.value, "smoothing")
  1025. );
  1026. }
  1027. }
  1028. }
  1029. void WallpaperApplication::listAudioObjects () const {
  1030. if (!this->m_context.settings.general.onlyListAudioObjects) {
  1031. return;
  1032. }
  1033. for (const auto& [background, info] : this->m_backgrounds) {
  1034. this->listAudioObjectsForProject (background, *info);
  1035. }
  1036. }
  1037. void WallpaperApplication::setupAudioSensitivityForProject (const Project& project) const {
  1038. if (!project.wallpaper->is<Scene> ()) {
  1039. return;
  1040. }
  1041. const auto scene = project.wallpaper->as<Scene> ();
  1042. for (const auto& object : scene->objects) {
  1043. const auto sensitivity = this->m_context.resolveAudioSensitivity (object->id, object->name);
  1044. if (!sensitivity.has_value ()) {
  1045. continue;
  1046. }
  1047. for (const auto& reactive : collectAudioReactiveProperties (*object)) {
  1048. auto& scriptProps = reactive.value->getProperties ();
  1049. const auto minIt = scriptProps.find ("minvalue");
  1050. const auto maxIt = scriptProps.find ("maxvalue");
  1051. if (minIt == scriptProps.end () || maxIt == scriptProps.end () || !minIt->second->value
  1052. || !maxIt->second->value) {
  1053. continue;
  1054. }
  1055. const auto [newMin, newMax] = WallpaperEngine::Data::Utils::scaleAudioRange (
  1056. minIt->second->value->getFloat (), maxIt->second->value->getFloat (), sensitivity.value ()
  1057. );
  1058. minIt->second->value->update (newMin, DynamicValue::UpdateSource::User);
  1059. maxIt->second->value->update (newMax, DynamicValue::UpdateSource::User);
  1060. sLog.debug (
  1061. "Applying audio sensitivity ", sensitivity.value (), " to ", object->id, " - ", object->name, " (",
  1062. reactive.name, ")"
  1063. );
  1064. }
  1065. }
  1066. }
  1067. void WallpaperApplication::setupAudioSensitivity () {
  1068. for (const auto& [background, info] : this->m_backgrounds) {
  1069. this->setupAudioSensitivityForProject (*info);
  1070. }
  1071. }
  1072. void WallpaperApplication::setupSoundVolumeForProject (const Project& project) const {
  1073. if (!project.wallpaper->is<Scene> ()) {
  1074. return;
  1075. }
  1076. const auto scene = project.wallpaper->as<Scene> ();
  1077. for (const auto& object : scene->objects) {
  1078. if (!object->is<Sound> ()) {
  1079. continue;
  1080. }
  1081. const auto* sound = object->as<Sound> ();
  1082. const auto volume = this->m_context.resolveSoundVolume (object->id, object->name);
  1083. if (!volume.has_value () || !sound->volume || !sound->volume->value) {
  1084. continue;
  1085. }
  1086. sound->volume->value->update (std::clamp (volume.value (), 0.0f, 1.0f), DynamicValue::UpdateSource::User);
  1087. sLog.debug ("Applying sound volume ", volume.value (), " to ", object->id, " - ", object->name);
  1088. }
  1089. }
  1090. void WallpaperApplication::setupSoundVolume () {
  1091. for (const auto& [background, info] : this->m_backgrounds) {
  1092. this->setupSoundVolumeForProject (*info);
  1093. }
  1094. }
  1095. void WallpaperApplication::applySoundVolumeHotswap (const std::map<std::string, std::string>& targets) {
  1096. for (const auto& [target, value] : targets) {
  1097. try {
  1098. this->m_context.settings.general.soundVolume[target] = std::stof (value);
  1099. } catch (const std::exception&) {
  1100. sLog.error ("Hotswap: ignoring invalid sound-volume value: ", value);
  1101. }
  1102. }
  1103. // Sound objects already read their own DynamicValue live every frame (see
  1104. // CSound::applyEffectiveVolume), so re-resolving and pushing the new value straight into the
  1105. // currently loaded projects' live objects is enough - no reload needed, unlike properties/
  1106. // audio-sensitivity which are baked into the scene graph at parse time.
  1107. for (const auto& [background, info] : this->m_backgrounds) {
  1108. this->setupSoundVolumeForProject (*info);
  1109. }
  1110. sLog.out ("Hotswap: applied sound volume live");
  1111. }
  1112. void WallpaperApplication::setupBrowser () {
  1113. // The main engine process never hosts CEF directly - CEF only supports one
  1114. // CefInitialize()/CefShutdown() pair per process, so a process that might later need to stop
  1115. // and restart hosting a web wallpaper can't safely do it in place. Only two roles reach here:
  1116. // CEF's own subprocess re-execs (--type=zygote/gpu-process/renderer/utility), which must
  1117. // always reach WebBrowserContext even if loadBackgrounds() found nothing to load, and this
  1118. // process's own --web-host role.
  1119. if ((!this->isCefSubprocess () && !this->m_context.settings.general.webHost) || this->m_browserContext) {
  1120. return;
  1121. }
  1122. this->m_browserContext = std::make_unique<WebBrowser::WebBrowserContext> (*this);
  1123. }
  1124. void WallpaperApplication::runWebHost () {
  1125. using namespace WallpaperEngine::WebBrowser;
  1126. using namespace WallpaperEngine::WebBrowser::IPC;
  1127. const auto backgroundIt = this->m_backgrounds.find ("default");
  1128. if (backgroundIt == this->m_backgrounds.end () || !backgroundIt->second->wallpaper->is<Web> ()) {
  1129. sLog.error ("--web-host requires a single Web wallpaper background, none found");
  1130. return;
  1131. }
  1132. if (!this->m_browserContext) {
  1133. sLog.error ("--web-host: CEF was not initialized (setupBrowser() found no Web project?)");
  1134. return;
  1135. }
  1136. const Project& project = *backgroundIt->second;
  1137. const Web& web = *project.wallpaper->as<Web> ();
  1138. const int width = static_cast<int> (this->m_context.settings.general.webHostWidth);
  1139. const int height = static_cast<int> (this->m_context.settings.general.webHostHeight);
  1140. if (width <= 0 || height <= 0) {
  1141. sLog.error ("--web-host: invalid --web-host-width/--web-host-height");
  1142. return;
  1143. }
  1144. auto* shm = attachSharedMemory (this->m_context.settings.general.webHostShm, width, height);
  1145. if (shm == nullptr) {
  1146. sLog.error ("--web-host: failed to attach shared memory ", this->m_context.settings.general.webHostShm);
  1147. return;
  1148. }
  1149. CefWindowInfo windowInfo;
  1150. windowInfo.SetAsWindowless (0);
  1151. CefBrowserSettings browserSettings;
  1152. browserSettings.windowless_frame_rate = std::max (60, this->m_context.settings.render.maximumFPS);
  1153. const CefRefPtr<CEF::SharedMemoryRenderHandler> renderHandler = new CEF::SharedMemoryRenderHandler (shm);
  1154. const CefRefPtr<CEF::BrowserClient> client = new CEF::BrowserClient (renderHandler, project.properties);
  1155. // the "w" prefix + workshop id host must match what the scheme handler factory expects to resolve
  1156. const std::string htmlURL = std::string (WPENGINE_SCHEME) + "://w" + project.workshopId + "/" + web.filename;
  1157. sLog.out ("--web-host: creating browser for ", htmlURL, " (pid ", static_cast<long> (getpid ()), ")");
  1158. const CefRefPtr<CefBrowser> browser
  1159. = CefBrowserHost::CreateBrowserSync (windowInfo, client, htmlURL, browserSettings, nullptr, nullptr);
  1160. if (!browser) {
  1161. sLog.error ("--web-host: failed to create the CEF browser");
  1162. shm->helperFailed.store (true, std::memory_order_release);
  1163. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  1164. return;
  1165. }
  1166. shm->helperReady.store (true, std::memory_order_release);
  1167. Input::MouseClickStatus lastLeft = Input::Released;
  1168. Input::MouseClickStatus lastRight = Input::Released;
  1169. uint32_t lastDesiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  1170. uint32_t lastDesiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  1171. bool lastAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  1172. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  1173. while (!shm->quitRequested.load (std::memory_order_acquire)) {
  1174. CefDoMessageLoopWork ();
  1175. const uint32_t desiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
  1176. const uint32_t desiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
  1177. if (desiredWidth != lastDesiredWidth || desiredHeight != lastDesiredHeight) {
  1178. lastDesiredWidth = desiredWidth;
  1179. lastDesiredHeight = desiredHeight;
  1180. browser->GetHost ()->WasResized ();
  1181. }
  1182. const bool desiredAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
  1183. if (desiredAudioMuted != lastAudioMuted) {
  1184. lastAudioMuted = desiredAudioMuted;
  1185. browser->GetHost ()->SetAudioMuted (lastAudioMuted);
  1186. }
  1187. CefMouseEvent evt;
  1188. evt.x = static_cast<int> (shm->mouseX.load (std::memory_order_relaxed));
  1189. evt.y = static_cast<int> (shm->mouseY.load (std::memory_order_relaxed));
  1190. browser->GetHost ()->SendMouseMoveEvent (evt, false);
  1191. const auto left = static_cast<Input::MouseClickStatus> (shm->leftClick.load (std::memory_order_relaxed));
  1192. const auto right = static_cast<Input::MouseClickStatus> (shm->rightClick.load (std::memory_order_relaxed));
  1193. if (left != lastLeft) {
  1194. browser->GetHost ()->SendMouseClickEvent (
  1195. evt, CefBrowserHost::MouseButtonType::MBT_LEFT, left == Input::Released, 1
  1196. );
  1197. lastLeft = left;
  1198. }
  1199. if (right != lastRight) {
  1200. browser->GetHost ()->SendMouseClickEvent (
  1201. evt, CefBrowserHost::MouseButtonType::MBT_RIGHT, right == Input::Released, 1
  1202. );
  1203. lastRight = right;
  1204. }
  1205. std::this_thread::sleep_for (std::chrono::milliseconds (4));
  1206. }
  1207. browser->GetHost ()->CloseBrowser (true);
  1208. // CloseBrowser() only requests an async close - wait briefly for it to finish before
  1209. // CefShutdown() below tears everything down out from under it
  1210. for (int i = 0; i < 500 && !client->isClosed (); i++) {
  1211. CefDoMessageLoopWork ();
  1212. }
  1213. closeSharedMemory (shm, this->m_context.settings.general.webHostShm, width, height, false);
  1214. }
  1215. void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename) const {
  1216. const int width = this->m_renderContext->getOutput ().getFullWidth ();
  1217. const int height = this->m_renderContext->getOutput ().getFullHeight ();
  1218. const bool vflip = this->m_renderContext->getOutput ().renderVFlip ();
  1219. const auto& wallpapers = this->m_renderContext->getWallpapers ();
  1220. struct ViewportCapture {
  1221. uint8_t* buffer;
  1222. int readWidth;
  1223. int readHeight;
  1224. int vpWidth;
  1225. int vpHeight;
  1226. int xoffset;
  1227. float ustart, uend, vstart, vend;
  1228. };
  1229. std::vector<ViewportCapture> captures;
  1230. int currentXOffset = 0;
  1231. for (const auto& [screen, viewport] : this->m_renderContext->getOutput ().getViewports ()) {
  1232. viewport->makeCurrent ();
  1233. const auto wallpaperIt = wallpapers.find (screen);
  1234. if (wallpaperIt == wallpapers.end ()) {
  1235. sLog.error ("Cannot find wallpaper for screen ", screen);
  1236. continue;
  1237. }
  1238. const auto& wallpaper = wallpaperIt->second;
  1239. const int vpWidth = viewport->viewport.z - viewport->viewport.x;
  1240. const int vpHeight = viewport->viewport.w - viewport->viewport.y;
  1241. // bind the wallpaper's FBO to read from it directly
  1242. // this is more reliable than the default framebuffer on some drivers (NVIDIA/Wayland)
  1243. glBindFramebuffer (GL_FRAMEBUFFER, wallpaper->getWallpaperFramebuffer ());
  1244. glFinish ();
  1245. const int readWidth = wallpaper->getWidth ();
  1246. const int readHeight = wallpaper->getHeight ();
  1247. const auto bufferSize = readWidth * readHeight * 3;
  1248. auto* buffer = new uint8_t[bufferSize];
  1249. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  1250. if (GLEW_VERSION_4_5) {
  1251. glReadnPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer);
  1252. } else {
  1253. glReadPixels (0, 0, readWidth, readHeight, GL_RGB, GL_UNSIGNED_BYTE, buffer);
  1254. }
  1255. glBindFramebuffer (GL_FRAMEBUFFER, 0);
  1256. if (const GLenum error = glGetError (); error != GL_NO_ERROR) {
  1257. sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error);
  1258. delete[] buffer;
  1259. continue;
  1260. }
  1261. // Get the UV coordinates which define the visible portion based on scaling mode
  1262. const auto [ustart, uend, vstart, vend] = wallpaper->getState ().getTextureUVs ();
  1263. captures.push_back (
  1264. { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset, ustart, uend, vstart, vend }
  1265. );
  1266. if (viewport->single) {
  1267. currentXOffset += vpWidth;
  1268. }
  1269. }
  1270. const auto extension = filename.extension ();
  1271. const std::string extStr = extension.string ();
  1272. // Offload pixel processing and saving to a background thread to avoid hitches
  1273. std::thread ([captures, width, height, vflip, extStr, filename] () {
  1274. auto* bitmap = new uint8_t[width * height * 3] { 0 };
  1275. for (const auto& capture : captures) {
  1276. // sample the bitmap from the UV-defined visible region
  1277. for (int y = 0; y < capture.vpHeight; y++) {
  1278. for (int x = 0; x < capture.vpWidth; x++) {
  1279. const float u
  1280. = capture.ustart + (static_cast<float> (x) / capture.vpWidth) * (capture.uend - capture.ustart);
  1281. const float v = capture.vstart
  1282. + (static_cast<float> (y) / capture.vpHeight) * (capture.vend - capture.vstart);
  1283. const int srcX = std::clamp (static_cast<int> (u * capture.readWidth), 0, capture.readWidth - 1);
  1284. const int srcY = std::clamp (static_cast<int> (v * capture.readHeight), 0, capture.readHeight - 1);
  1285. const int srcIdx = (srcY * capture.readWidth + srcX) * 3;
  1286. const int xfinal = x + capture.xoffset;
  1287. // FBO content is not flipped like default framebuffer, so invert vflip logic
  1288. const int yfinal = vflip ? y : (capture.vpHeight - y - 1);
  1289. if (yfinal >= 0 && yfinal < height && xfinal >= 0 && xfinal < width) {
  1290. bitmap[yfinal * width * 3 + xfinal * 3] = capture.buffer[srcIdx];
  1291. bitmap[yfinal * width * 3 + xfinal * 3 + 1] = capture.buffer[srcIdx + 1];
  1292. bitmap[yfinal * width * 3 + xfinal * 3 + 2] = capture.buffer[srcIdx + 2];
  1293. }
  1294. }
  1295. }
  1296. delete[] capture.buffer;
  1297. }
  1298. if (extStr == ".bmp") {
  1299. stbi_write_bmp (filename.c_str (), width, height, 3, bitmap);
  1300. } else if (extStr == ".png") {
  1301. stbi_write_png (filename.c_str (), width, height, 3, bitmap, width * 3);
  1302. } else if (extStr == ".jpg" || extStr == ".jpeg") {
  1303. stbi_write_jpg (filename.c_str (), width, height, 3, bitmap, 100);
  1304. }
  1305. delete[] bitmap;
  1306. }).detach ();
  1307. }
  1308. void WallpaperApplication::setupOutput () {
  1309. const char* XDG_SESSION_TYPE = getenv ("XDG_SESSION_TYPE");
  1310. if (!XDG_SESSION_TYPE) {
  1311. sLog.exception (
  1312. "Cannot read environment variable XDG_SESSION_TYPE, window server detection failed. Please ensure proper "
  1313. "values are set"
  1314. );
  1315. }
  1316. sLog.debug ("Checking for window servers: ");
  1317. for (const auto& windowServer : sVideoFactories.getRegisteredDrivers ()) {
  1318. sLog.debug ("\t", windowServer);
  1319. }
  1320. this->m_videoDriver = sVideoFactories.createVideoDriver (
  1321. this->m_context.settings.render.mode, XDG_SESSION_TYPE, this->m_context, *this
  1322. );
  1323. this->m_fullScreenDetector
  1324. = sVideoFactories.createFullscreenDetector (XDG_SESSION_TYPE, this->m_context, *this->m_videoDriver);
  1325. }
  1326. void WallpaperApplication::setupAudio () {
  1327. const bool audioProcessingRequired = std::ranges::any_of (
  1328. this->m_backgrounds, [] (const std::pair<const std::string, ProjectUniquePtr>& pair) -> bool {
  1329. return pair.second->supportsAudioProcessing;
  1330. }
  1331. );
  1332. if (audioProcessingRequired && this->m_context.settings.audio.audioprocessing) {
  1333. this->m_audioRecorder
  1334. = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
  1335. } else {
  1336. this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PlaybackRecorder> ();
  1337. }
  1338. if (this->m_context.settings.audio.automute) {
  1339. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::PulseAudioPlayingDetector> (
  1340. this->m_context, *this->m_fullScreenDetector
  1341. );
  1342. } else {
  1343. m_audioDetector = std::make_unique<WallpaperEngine::Audio::Drivers::Detectors::AudioPlayingDetector> (
  1344. this->m_context, *this->m_fullScreenDetector
  1345. );
  1346. }
  1347. m_audioDriver = std::make_unique<WallpaperEngine::Audio::Drivers::SDLAudioDriver> (
  1348. this->m_context, *this->m_audioDetector, *this->m_audioRecorder
  1349. );
  1350. m_audioContext = std::make_unique<WallpaperEngine::Audio::AudioContext> (*m_audioDriver);
  1351. }
  1352. void WallpaperApplication::prepareOutputs () {
  1353. m_renderContext
  1354. = std::make_unique<WallpaperEngine::Render::RenderContext> (*m_videoDriver, *this, *this->m_mediaSource);
  1355. // set all the specific wallpapers required (skip span group synthetic keys)
  1356. for (const auto& [background, info] : this->m_backgrounds) {
  1357. if (background.rfind ("span:", 0) == 0) {
  1358. continue;
  1359. }
  1360. const auto scalingIt = this->m_context.settings.general.screenScalings.find (background);
  1361. const auto clampIt = this->m_context.settings.general.screenClamps.find (background);
  1362. const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
  1363. ? scalingIt->second
  1364. : this->m_context.settings.render.window.scalingMode;
  1365. const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
  1366. ? clampIt->second
  1367. : this->m_context.settings.render.window.clamp;
  1368. auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  1369. *info->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (background),
  1370. scaling, clamp, this->resolveScreenRenderSize (background)
  1371. );
  1372. wallpaper->setZoom (this->resolveScreenZoom (background));
  1373. wallpaper->setCornerColor (this->resolveScreenCornerColor (background));
  1374. m_renderContext->setWallpaper (background, std::move (wallpaper));
  1375. }
  1376. // Set up span groups: one shared wallpaper per group, registered for each viewport
  1377. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  1378. if (spanGroup.screens.empty ()) {
  1379. continue;
  1380. }
  1381. const std::string groupKey = "span:" + spanGroup.screens.front ();
  1382. const auto bgIt = this->m_backgrounds.find (groupKey);
  1383. if (bgIt == this->m_backgrounds.end ()) {
  1384. continue;
  1385. }
  1386. // bounding box of all viewports in this span group
  1387. const auto& viewports = m_renderContext->getOutput ().getViewports ();
  1388. int minX = INT_MAX, minY = INT_MAX, maxX = INT_MIN, maxY = INT_MIN;
  1389. bool anyFound = false;
  1390. for (const auto& screenName : spanGroup.screens) {
  1391. const auto vpIt = viewports.find (screenName);
  1392. if (vpIt == viewports.end ()) {
  1393. sLog.error ("Span group screen not found: ", screenName);
  1394. continue;
  1395. }
  1396. anyFound = true;
  1397. const auto& vp = vpIt->second;
  1398. const int x = vp->globalPosition.x;
  1399. const int y = vp->globalPosition.y;
  1400. const int w = vp->logicalSize.x;
  1401. const int h = vp->logicalSize.y;
  1402. sLog.debug (
  1403. "SPAN DEBUG prepareOutputs: screen '", screenName, "' globalPos=(", x, ",", y, ") logicalSize=", w, "x",
  1404. h
  1405. );
  1406. minX = std::min (minX, x);
  1407. minY = std::min (minY, y);
  1408. maxX = std::max (maxX, x + w);
  1409. maxY = std::max (maxY, y + h);
  1410. }
  1411. if (!anyFound) {
  1412. sLog.error ("No viewports found for span group, skipping");
  1413. continue;
  1414. }
  1415. sLog.debug (
  1416. "SPAN DEBUG prepareOutputs: bounding box=(", minX, ",", minY, ",", maxX - minX, ",", maxY - minY, ")"
  1417. );
  1418. WallpaperEngine::Render::CWallpaper::SpanInfo spanInfo;
  1419. spanInfo.totalBounds = { minX, minY, maxX - minX, maxY - minY };
  1420. auto sharedWallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
  1421. *bgIt->second->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (groupKey),
  1422. spanGroup.scaling, spanGroup.clamp, glm::ivec2 { maxX - minX, maxY - minY }
  1423. );
  1424. sharedWallpaper->setZoom (spanGroup.zoom);
  1425. sharedWallpaper->setCornerColor (spanGroup.cornerColor);
  1426. // Convert to shared_ptr so it can be registered for multiple viewports
  1427. std::shared_ptr<WallpaperEngine::Render::CWallpaper> shared (std::move (sharedWallpaper));
  1428. shared->setSpanInfo (spanInfo);
  1429. for (const auto& screenName : spanGroup.screens) {
  1430. m_renderContext->setWallpaper (screenName, shared);
  1431. }
  1432. }
  1433. this->applyAudioPolicy ();
  1434. }
  1435. void WallpaperApplication::setupOpenGLDebugging () {
  1436. // Not gated behind NDEBUG: GL_DEBUG_OUTPUT has near-zero cost when nothing goes wrong, and a
  1437. // Release build silently swallowing driver errors is exactly what's masking the in-process
  1438. // reload corruption bug - see CustomGLDebugCallback() above and the "layer toggle blackens the
  1439. // wallpaper" investigation.
  1440. glDebugMessageCallback (CustomGLDebugCallback, nullptr);
  1441. glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1442. }
  1443. void WallpaperApplication::setup () {
  1444. this->setupOutput ();
  1445. // we_manager launches us with LD_PRELOAD forcing the system's libEGL, because CEF's own
  1446. // bundled libEGL sits next to us on LD_LIBRARY_PATH and would otherwise shadow it and break
  1447. // our own Wayland/EGL output. That preload has already done its job for our own process by
  1448. // this point (setupOutput() above just created our GL context with it) - but it stays in the
  1449. // environment we inherit, and CEF's own subprocesses (spawned lazily, e.g. the GPU process
  1450. // the moment a web wallpaper's WebGL content first needs one) would inherit it too, forcing
  1451. // Mesa's system EGL onto CEF's ANGLE stack instead of the bundled EGL it actually expects.
  1452. // That silently breaks WebGL - no crash, no error, just a canvas that never paints anything.
  1453. // Unsetting it here only affects processes we fork+exec after this point; it doesn't undo
  1454. // anything already loaded into our own process by the dynamic linker at our own startup.
  1455. unsetenv ("LD_PRELOAD");
  1456. this->setupAudio ();
  1457. this->prepareOutputs ();
  1458. this->setupOpenGLDebugging ();
  1459. if (this->m_context.settings.general.dumpStructure) {
  1460. auto prettyPrinter = Data::Dumpers::StringPrinter ();
  1461. for (const auto& [background, info] : this->m_renderContext->getWallpapers ()) {
  1462. prettyPrinter.printWallpaper (info->getWallpaperData ());
  1463. }
  1464. std::cout << prettyPrinter.str () << std::endl;
  1465. }
  1466. #if DEMOMODE
  1467. // ensure only one background is running so everything can be properly caught
  1468. if (this->m_renderContext->getWallpapers ().size () > 1) {
  1469. sLog.exception ("Demo mode only supports one background");
  1470. }
  1471. int width = this->m_renderContext->getWallpapers ().begin ()->second->getWidth ();
  1472. int height = this->m_renderContext->getWallpapers ().begin ()->second->getHeight ();
  1473. std::vector<uint8_t> pixels (width * height * 3);
  1474. bool initialized = false;
  1475. int frame = 0;
  1476. #endif /* DEMOMODE */
  1477. }
  1478. void WallpaperApplication::render () {
  1479. static time_t seconds;
  1480. static struct tm* timeinfo;
  1481. static float rawTimeLast = 0.0f;
  1482. if (this->m_isPaused) {
  1483. usleep (FULLSCREEN_CHECK_WAIT_TIME);
  1484. if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
  1485. return;
  1486. }
  1487. m_renderContext->setPause (false);
  1488. // account for paused duration in playlist timers
  1489. const auto pausedNow = std::chrono::steady_clock::now ();
  1490. const auto pausedDuration = pausedNow - this->m_pauseStart;
  1491. for (auto& [_, playlist] : this->m_activePlaylists) {
  1492. if (!playlist.definition.settings.updateOnPause) {
  1493. playlist.nextSwitch += pausedDuration;
  1494. playlist.lastUpdate += pausedDuration;
  1495. }
  1496. }
  1497. this->m_isPaused = false;
  1498. } else {
  1499. time (&seconds);
  1500. timeinfo = localtime (&seconds);
  1501. g_Daytime = static_cast<float> ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0f * 60.0f);
  1502. const float rawTimeNow = m_videoDriver->getRenderTime ();
  1503. const float rawDelta = rawTimeNow - rawTimeLast;
  1504. rawTimeLast = rawTimeNow;
  1505. g_TimeLast = g_Time;
  1506. g_Time += rawDelta * this->m_context.settings.render.playbackSpeed;
  1507. g_RealTime = rawTimeNow;
  1508. m_audioDriver->update ();
  1509. m_mediaSource->update ();
  1510. m_videoDriver->getInputContext ().update ();
  1511. m_videoDriver->dispatchEventQueue ();
  1512. if (m_videoDriver->closeRequested ()) {
  1513. sLog.out ("Stop requested by driver");
  1514. this->m_context.state.general.keepRunning = false;
  1515. }
  1516. #if DEMOMODE
  1517. // wait a full render cycle before starting, giving video/web decoders time to set up
  1518. if (m_videoDriver->getFrameCounter () > (uint32_t)this->m_context.settings.render.maximumFPS) {
  1519. if (!initialized) {
  1520. width = this->m_renderContext->getWallpapers ().begin ()->second->getWidth ();
  1521. height = this->m_renderContext->getWallpapers ().begin ()->second->getHeight ();
  1522. pixels.reserve (width * height * 3);
  1523. init_encoder ("output.webm", width, height);
  1524. initialized = true;
  1525. }
  1526. glBindFramebuffer (
  1527. GL_FRAMEBUFFER, this->m_renderContext->getWallpapers ().begin ()->second->getWallpaperFramebuffer ()
  1528. );
  1529. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  1530. glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data ());
  1531. write_video_frame (pixels.data ());
  1532. frame++;
  1533. if (frame >= FRAME_COUNT) {
  1534. this->m_context.state.general.keepRunning = false;
  1535. }
  1536. }
  1537. #endif /* DEMOMODE */
  1538. if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
  1539. this->m_isPaused = true;
  1540. this->m_pauseStart = std::chrono::steady_clock::now ();
  1541. m_renderContext->setPause (true);
  1542. return;
  1543. }
  1544. }
  1545. this->checkHotswapRequest ();
  1546. this->updatePlaylists ();
  1547. if (!this->m_context.settings.screenshot.take || this->m_screenShotTaken == true) {
  1548. return;
  1549. }
  1550. if (this->m_videoDriver->getFrameCounter () < this->m_nextFrameScreenshot) {
  1551. return;
  1552. }
  1553. this->takeScreenshot (this->m_context.settings.screenshot.path);
  1554. this->m_screenShotTaken = true;
  1555. }
  1556. void WallpaperApplication::cleanup () {
  1557. sLog.out ("Stopping");
  1558. #if DEMOMODE
  1559. close_encoder ();
  1560. #endif /* DEMOMODE */
  1561. SDL_Quit ();
  1562. }
  1563. void WallpaperApplication::show () {
  1564. setup ();
  1565. while (this->m_context.state.general.keepRunning) {
  1566. render ();
  1567. }
  1568. cleanup ();
  1569. }
  1570. void WallpaperApplication::update (Render::Drivers::Output::OutputViewport* viewport) {
  1571. m_renderContext->render (viewport);
  1572. }
  1573. void WallpaperApplication::signal (int signal) {
  1574. if (signal == SIGUSR1) {
  1575. // keep the handler itself trivial, the actual reload happens on the render thread
  1576. this->m_hotswapRequested = true;
  1577. return;
  1578. }
  1579. sLog.out ("Stop requested by signal ", signal);
  1580. this->m_context.state.general.keepRunning = false;
  1581. }
  1582. const std::map<std::string, ProjectUniquePtr>& WallpaperApplication::getBackgrounds () const {
  1583. return this->m_backgrounds;
  1584. }
  1585. ApplicationContext& WallpaperApplication::getContext () const { return this->m_context; }
  1586. const WallpaperEngine::Render::Drivers::Output::Output& WallpaperApplication::getOutput () const {
  1587. return this->m_renderContext->getOutput ();
  1588. }
  1589. void WallpaperApplication::setDestinationFramebuffer (GLuint framebuffer) {
  1590. this->m_destinationFramebuffer = framebuffer;
  1591. for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
  1592. wallpaper->setDestinationFramebuffer (framebuffer);
  1593. };
  1594. }
  1595. GLuint WallpaperApplication::getDestinationFramebuffer () const { return this->m_destinationFramebuffer; }