WallpaperApplication.cpp 66 KB

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