ApplicationContext.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. #include "ApplicationContext.h"
  2. #include "Steam/FileSystem/FileSystem.h"
  3. #include "WallpaperEngine/Data/JSON.h"
  4. #include "WallpaperEngine/Logging/Log.h"
  5. #include "WallpaperEngine/Render/CFBO.h"
  6. #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
  7. #include <algorithm>
  8. #include <charconv>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <fstream>
  12. #include <functional>
  13. #include <iostream>
  14. #include <optional>
  15. #include <sstream>
  16. #include <stdexcept>
  17. #include <string_view>
  18. #include <argparse/argparse.hpp>
  19. #define WORKSHOP_APP_ID 431960
  20. #define APP_DIRECTORY "wallpaper_engine"
  21. using namespace WallpaperEngine::Application;
  22. using WallpaperEngine::Data::Model::ImageAdjustments;
  23. namespace {
  24. // CEF and --web-host children re-run the whole argument parsing, the parent already reported all of it
  25. bool isHelperProcess (int argc, char** argv, bool webHost) {
  26. if (webHost) {
  27. return true;
  28. }
  29. for (int i = 1; i < argc; i++) {
  30. if (std::string_view (argv[i]).starts_with ("--type=")) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. } // namespace
  37. using WallpaperEngine::Data::JSON::JSON;
  38. std::filesystem::path ApplicationContext::resolvePlaylistItemPath (const std::string& raw) const {
  39. if (raw.empty ()) {
  40. return {};
  41. }
  42. std::string cleaned = raw;
  43. constexpr std::string_view windowsPrefix = "\\\\?\\";
  44. if (cleaned.rfind (windowsPrefix, 0) == 0) {
  45. cleaned = cleaned.substr (windowsPrefix.length ());
  46. }
  47. std::replace (cleaned.begin (), cleaned.end (), '\\', '/');
  48. if (cleaned.size () > 1 && cleaned[1] == ':') {
  49. cleaned = cleaned.substr (2);
  50. }
  51. if (!cleaned.empty () && cleaned.front () != '/') {
  52. cleaned.insert (cleaned.begin (), '/');
  53. }
  54. std::filesystem::path path = std::filesystem::path (cleaned).lexically_normal ();
  55. if (std::filesystem::is_regular_file (path)) {
  56. path = path.parent_path ();
  57. }
  58. return path;
  59. }
  60. std::filesystem::path ApplicationContext::configFilePath () const {
  61. try {
  62. return Steam::FileSystem::appDirectory (APP_DIRECTORY, "") / "config.json";
  63. } catch (std::runtime_error&) {
  64. sLog.exception ("Cannot locate wallpaper engine installation to read config.json");
  65. return {};
  66. }
  67. }
  68. std::optional<JSON> ApplicationContext::parseConfigJson (const std::filesystem::path& path) const {
  69. if (path.empty ()) {
  70. return std::nullopt;
  71. }
  72. std::ifstream configFile (path);
  73. if (!configFile.is_open ()) {
  74. sLog.exception ("Cannot open wallpaper engine config file at ", path);
  75. return std::nullopt;
  76. }
  77. try {
  78. return JSON::parse (configFile);
  79. } catch (const std::exception& e) {
  80. sLog.error ("Failed parsing wallpaper engine config.json: ", e.what ());
  81. return std::nullopt;
  82. }
  83. }
  84. std::optional<ApplicationContext::PlaylistDefinition>
  85. ApplicationContext::buildPlaylistDefinition (const JSON& playlistJson, const std::string& fallbackName) const {
  86. PlaylistDefinition definition;
  87. definition.name = playlistJson.optional<std::string> ("name", fallbackName);
  88. definition.settings = this->parsePlaylistSettings (playlistJson);
  89. definition.items
  90. = this->collectPlaylistItems (playlistJson, definition.name.empty () ? fallbackName : definition.name);
  91. if (definition.items.empty ()) {
  92. return std::nullopt;
  93. }
  94. if (definition.name.empty ()) {
  95. if (fallbackName.empty ()) {
  96. sLog.error ("Skipping playlist with no name");
  97. return std::nullopt;
  98. }
  99. definition.name = fallbackName;
  100. }
  101. return definition;
  102. }
  103. ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (const JSON& playlistJson) const {
  104. PlaylistSettings settings;
  105. const auto settingsJson = playlistJson.optional ("settings");
  106. settings.delayMinutes = settingsJson ? settingsJson->optional<uint32_t> ("delay", 60) : 60;
  107. settings.mode = settingsJson ? settingsJson->optional<std::string> ("mode", "timer") : "timer";
  108. settings.order = settingsJson ? settingsJson->optional<std::string> ("order", "sequential") : "sequential";
  109. settings.updateOnPause = settingsJson ? settingsJson->optional<bool> ("updateonpause", false) : false;
  110. settings.videoSequence = settingsJson ? settingsJson->optional<bool> ("videosequence", false) : false;
  111. return settings;
  112. }
  113. std::vector<std::filesystem::path>
  114. ApplicationContext::collectPlaylistItems (const JSON& playlistJson, const std::string& name) const {
  115. std::vector<std::filesystem::path> items;
  116. const auto jsonItems = playlistJson.optional ("items");
  117. if (!jsonItems.has_value () || !jsonItems->is_array ()) {
  118. sLog.error ("Skipping playlist ", name, ": missing items");
  119. return items;
  120. }
  121. for (const auto& rawItem : *jsonItems) {
  122. if (!rawItem.is_string ()) {
  123. continue;
  124. }
  125. auto resolvedPath = this->resolvePlaylistItemPath (rawItem.get<std::string> ());
  126. if (resolvedPath.empty ()) {
  127. continue;
  128. }
  129. if (!std::filesystem::exists (resolvedPath)) {
  130. sLog.error ("Skipping playlist item not found: ", resolvedPath.string ());
  131. continue;
  132. }
  133. items.push_back (resolvedPath);
  134. }
  135. if (items.empty ()) {
  136. sLog.error ("Skipping playlist ", name, ": no usable items found");
  137. }
  138. return items;
  139. }
  140. void ApplicationContext::registerPlaylist (PlaylistDefinition&& definition) {
  141. this->m_configPlaylists.insert_or_assign (definition.name, std::move (definition));
  142. }
  143. void ApplicationContext::loadPlaylistsFromConfig () {
  144. if (this->m_loadedConfigPlaylists) {
  145. return;
  146. }
  147. this->m_loadedConfigPlaylists = true;
  148. const auto configPath = this->configFilePath ();
  149. const auto root = this->parseConfigJson (configPath);
  150. if (!root.has_value ()) {
  151. return;
  152. }
  153. const auto steamUser = root->optional ("steamuser");
  154. if (!steamUser.has_value ()) {
  155. sLog.exception ("Cannot find steamuser section in config.json");
  156. }
  157. auto addPlaylist = [this] (const JSON& playlistJson, const std::string& fallbackName) {
  158. auto definition = this->buildPlaylistDefinition (playlistJson, fallbackName);
  159. if (!definition) {
  160. return;
  161. }
  162. this->registerPlaylist (std::move (*definition));
  163. };
  164. if (const auto general = steamUser->optional ("general")) {
  165. if (const auto playlists = general->optional ("playlists")) {
  166. for (const auto& playlist : *playlists) {
  167. try {
  168. addPlaylist (playlist, playlist.optional<std::string> ("name", ""));
  169. } catch (const std::exception& e) {
  170. sLog.error ("Failed parsing playlist: ", e.what ());
  171. }
  172. }
  173. }
  174. }
  175. if (const auto wallpaperConfig = steamUser->optional ("wallpaperconfig")) {
  176. if (const auto selected = wallpaperConfig->optional ("selectedwallpapers")) {
  177. for (const auto& entry : selected->items ()) {
  178. const auto playlist = entry.value ().optional ("playlist");
  179. if (!playlist.has_value ()) {
  180. continue;
  181. }
  182. try {
  183. addPlaylist (*playlist, entry.key ());
  184. } catch (const std::exception& e) {
  185. sLog.error ("Failed parsing playlist for ", entry.key (), ": ", e.what ());
  186. }
  187. }
  188. }
  189. }
  190. }
  191. const ApplicationContext::PlaylistDefinition& ApplicationContext::getPlaylistFromConfig (const std::string& name) {
  192. if (!this->m_loadedConfigPlaylists) {
  193. this->loadPlaylistsFromConfig ();
  194. }
  195. const auto cur = this->m_configPlaylists.find (name);
  196. if (cur == this->m_configPlaylists.end ()) {
  197. std::string available;
  198. for (auto it = this->m_configPlaylists.begin (); it != this->m_configPlaylists.end (); ++it) {
  199. available += it->first;
  200. if (std::next (it) != this->m_configPlaylists.end ()) {
  201. available += ", ";
  202. }
  203. }
  204. const std::string availableText = available.empty () ? "" : std::string (". Available: ") + available;
  205. sLog.exception ("Playlist not found in config.json: ", name, availableText);
  206. throw std::runtime_error ("Playlist not found: " + name);
  207. }
  208. return cur->second;
  209. }
  210. ApplicationContext::ApplicationContext (int argc, char* argv[]) : m_argc (argc), m_argv (argv) { }
  211. namespace {
  212. bool matchesObjectToken (const std::string& token, int id, const std::string& name) {
  213. if (token == name) {
  214. return true;
  215. }
  216. int parsed = 0;
  217. const auto* end = token.data () + token.size ();
  218. const auto result = std::from_chars (token.data (), end, parsed);
  219. return result.ec == std::errc () && result.ptr == end && parsed == id;
  220. }
  221. } // namespace
  222. std::optional<bool> ApplicationContext::resolveObjectVisibility (int id, const std::string& name) const {
  223. for (const auto& token : this->settings.general.disabledObjects) {
  224. if (matchesObjectToken (token, id, name)) {
  225. return false;
  226. }
  227. }
  228. for (const auto& token : this->settings.general.enabledObjects) {
  229. if (matchesObjectToken (token, id, name)) {
  230. return true;
  231. }
  232. }
  233. return std::nullopt;
  234. }
  235. std::optional<bool> ApplicationContext::resolveEffectVisibility (int id, const std::string& name) const {
  236. for (const auto& token : this->settings.general.disabledEffects) {
  237. if (matchesObjectToken (token, id, name)) {
  238. return false;
  239. }
  240. }
  241. for (const auto& token : this->settings.general.enabledEffects) {
  242. if (matchesObjectToken (token, id, name)) {
  243. return true;
  244. }
  245. }
  246. return std::nullopt;
  247. }
  248. std::optional<float> ApplicationContext::resolveAudioSensitivity (int id, const std::string& name) const {
  249. // "*" is a wildcard default, checked last so a specific id/name match always wins
  250. // regardless of the map's (alphabetically ordered) iteration order.
  251. std::optional<float> wildcard;
  252. for (const auto& [token, multiplier] : this->settings.general.audioSensitivity) {
  253. if (token == "*") {
  254. wildcard = multiplier;
  255. continue;
  256. }
  257. if (matchesObjectToken (token, id, name)) {
  258. return multiplier;
  259. }
  260. }
  261. return wildcard;
  262. }
  263. std::optional<float> ApplicationContext::resolveSoundVolume (int id, const std::string& name) const {
  264. // "*" is a wildcard default, checked last so a specific id/name match always wins (same rule as
  265. // resolveAudioSensitivity).
  266. std::optional<float> wildcard;
  267. for (const auto& [token, volume] : this->settings.general.soundVolume) {
  268. if (token == "*") {
  269. wildcard = volume;
  270. continue;
  271. }
  272. if (matchesObjectToken (token, id, name)) {
  273. return volume;
  274. }
  275. }
  276. return wildcard;
  277. }
  278. void ApplicationContext::loadSettingsFromArgv () {
  279. std::string lastScreen;
  280. argparse::ArgumentParser program ("linux-wallpaperengine", "0.0", argparse::default_arguments::help);
  281. auto& backgroundGroup = program.add_group ("Background options");
  282. auto& backgroundMode = backgroundGroup.add_mutually_exclusive_group (false);
  283. backgroundGroup.add_argument ("background id")
  284. .help ("The background to use as default for screens with no background specified")
  285. .default_value ("")
  286. .action ([this] (const std::string& value) -> void {
  287. if (!value.empty ()) {
  288. this->settings.general.defaultBackground = translateBackground (value);
  289. }
  290. });
  291. // Internal, hidden: appended to CEF subprocess re-execs so they see the current (possibly
  292. // hotswapped) background instead of the launch-time "background id" positional. Registered
  293. // last so it takes precedence.
  294. backgroundGroup.add_argument ("--current-background")
  295. .default_value ("")
  296. .hidden ()
  297. .action ([this] (const std::string& value) -> void {
  298. if (!value.empty ()) {
  299. this->settings.general.defaultBackground = translateBackground (value);
  300. }
  301. });
  302. // Internal, hidden: marks a self-re-exec as a disposable CEF host for one Web wallpaper.
  303. backgroundGroup.add_argument ("--web-host").flag ().hidden ().store_into (this->settings.general.webHost);
  304. backgroundGroup.add_argument ("--web-host-shm")
  305. .default_value ("")
  306. .hidden ()
  307. .store_into (this->settings.general.webHostShm);
  308. backgroundGroup.add_argument ("--web-host-width")
  309. .default_value (0)
  310. .hidden ()
  311. .action ([this] (const std::string& value) -> void {
  312. try {
  313. this->settings.general.webHostWidth = static_cast<uint32_t> (std::stoul (value));
  314. } catch (const std::exception&) {
  315. sLog.exception ("Invalid --web-host-width value: ", value);
  316. }
  317. });
  318. backgroundGroup.add_argument ("--web-host-height")
  319. .default_value (0)
  320. .hidden ()
  321. .action ([this] (const std::string& value) -> void {
  322. try {
  323. this->settings.general.webHostHeight = static_cast<uint32_t> (std::stoul (value));
  324. } catch (const std::exception&) {
  325. sLog.exception ("Invalid --web-host-height value: ", value);
  326. }
  327. });
  328. backgroundMode.add_argument ("-w", "--window")
  329. .help ("Window geometry to use for the given screen")
  330. .action ([this] (const std::string& value) -> void {
  331. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  332. sLog.exception ("Cannot run in both background and window mode");
  333. }
  334. if (this->settings.render.mode == EXPLICIT_WINDOW) {
  335. sLog.exception ("Only one window at a time can be specified in explicit window mode");
  336. }
  337. this->settings.render.mode = EXPLICIT_WINDOW;
  338. if (value.empty ()) {
  339. sLog.exception ("Window geometry cannot be empty");
  340. }
  341. const char* str = value.c_str ();
  342. const char* delim1 = strchr (str, 'x');
  343. const char* delim2 = delim1 ? strchr (delim1 + 1, 'x') : nullptr;
  344. const char* delim3 = delim2 ? strchr (delim2 + 1, 'x') : nullptr;
  345. if (delim1 == nullptr || delim2 == nullptr || delim3 == nullptr) {
  346. sLog.exception ("Window geometry must be in the format: XxYxWxH");
  347. }
  348. this->settings.render.window.geometry.x = strtol (str, nullptr, 10);
  349. this->settings.render.window.geometry.y = strtol (delim1 + 1, nullptr, 10);
  350. this->settings.render.window.geometry.z = strtol (delim2 + 1, nullptr, 10);
  351. this->settings.render.window.geometry.w = strtol (delim3 + 1, nullptr, 10);
  352. })
  353. .append ();
  354. backgroundMode.add_argument ("-r", "--screen-root")
  355. .help ("The screen the following settings will have an effect on")
  356. .action ([this, &lastScreen] (const std::string& value) -> void {
  357. if (this->settings.general.screenBackgrounds.find (value)
  358. != this->settings.general.screenBackgrounds.end ()) {
  359. sLog.exception ("Cannot specify the same screen more than once: ", value);
  360. }
  361. for (const auto& group : this->settings.general.spanGroups) {
  362. if (std::find (group.screens.begin (), group.screens.end (), value) != group.screens.end ()) {
  363. sLog.exception ("--screen-root: screen '", value, "' already belongs to a span group");
  364. }
  365. }
  366. if (this->settings.render.mode == EXPLICIT_WINDOW) {
  367. sLog.exception ("Cannot run in both background and window mode");
  368. }
  369. this->settings.render.mode = DESKTOP_BACKGROUND;
  370. lastScreen = value;
  371. this->settings.general.screenBackgrounds[lastScreen] = "";
  372. this->settings.general.screenScalings[lastScreen] = this->settings.render.window.scalingMode;
  373. this->settings.general.screenClamps[lastScreen] = this->settings.render.window.clamp;
  374. })
  375. .append ();
  376. backgroundGroup.add_argument ("--screen-span")
  377. .help ("Comma-separated list of screens to span a single wallpaper across")
  378. .action ([this, &lastScreen] (const std::string& value) -> void {
  379. if (this->settings.render.mode == EXPLICIT_WINDOW) {
  380. sLog.exception ("Cannot run in both background and window mode");
  381. }
  382. this->settings.render.mode = DESKTOP_BACKGROUND;
  383. SpanGroup group;
  384. std::string screen;
  385. std::istringstream ss (value);
  386. while (std::getline (ss, screen, ',')) {
  387. if (screen.empty ()) {
  388. continue;
  389. }
  390. if (this->settings.general.screenBackgrounds.find (screen)
  391. != this->settings.general.screenBackgrounds.end ()) {
  392. sLog.exception ("--screen-span: screen '", screen, "' is already configured individually");
  393. }
  394. if (std::find (group.screens.begin (), group.screens.end (), screen) != group.screens.end ()) {
  395. sLog.exception ("--screen-span: duplicate screen name '", screen, "'");
  396. }
  397. for (const auto& existing : this->settings.general.spanGroups) {
  398. if (std::find (existing.screens.begin (), existing.screens.end (), screen)
  399. != existing.screens.end ()) {
  400. sLog.exception ("--screen-span: screen '", screen, "' already belongs to another span group");
  401. }
  402. }
  403. group.screens.push_back (screen);
  404. }
  405. if (group.screens.size () < 2) {
  406. sLog.exception ("--screen-span requires at least two comma-separated screen names");
  407. }
  408. group.scaling = this->settings.render.window.scalingMode;
  409. group.clamp = this->settings.render.window.clamp;
  410. group.alignment = this->settings.render.window.alignment;
  411. this->settings.general.spanGroups.push_back (std::move (group));
  412. // synthetic "span:" name lets --bg/--scaling/--clamp target this group
  413. lastScreen = "span:" + value;
  414. this->settings.general.screenBackgrounds[lastScreen] = "";
  415. })
  416. .append ();
  417. backgroundGroup.add_argument ("-b", "--bg")
  418. .help ("After --screen-root or --screen-span, specifies the background to use")
  419. .action ([this, &lastScreen] (const std::string& value) -> void {
  420. this->settings.general.screenBackgrounds[lastScreen] = translateBackground (value);
  421. this->settings.general.defaultBackground = translateBackground (value);
  422. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  423. this->settings.general.spanGroups.back ().background = translateBackground (value);
  424. }
  425. })
  426. .append ();
  427. backgroundGroup.add_argument ("--playlist")
  428. .help (
  429. "Uses a playlist from wallpaper engine's config.json. If used after --screen-root it is applied to that "
  430. "screen, otherwise it is used in window mode."
  431. )
  432. .action ([this, &lastScreen] (const std::string& value) -> void {
  433. const auto& playlist = this->getPlaylistFromConfig (value);
  434. if (lastScreen.empty ()) {
  435. this->settings.general.defaultPlaylist = playlist;
  436. if (this->settings.general.defaultBackground.empty () && !playlist.items.empty ()) {
  437. this->settings.general.defaultBackground = playlist.items.front ();
  438. }
  439. } else {
  440. this->settings.general.screenPlaylists[lastScreen] = playlist;
  441. if (!playlist.items.empty ()) {
  442. this->settings.general.screenBackgrounds[lastScreen] = playlist.items.front ();
  443. }
  444. if (this->settings.general.defaultBackground.empty () && !playlist.items.empty ()) {
  445. this->settings.general.defaultBackground = playlist.items.front ();
  446. }
  447. }
  448. })
  449. .append ();
  450. backgroundGroup.add_argument ("--scaling")
  451. .help (
  452. "Scaling mode to use when rendering the background, this applies to the previous --window, --screen-root, "
  453. "or --screen-span output, or the default background if no other background is specified"
  454. )
  455. .choices ("stretch", "fit", "fill", "center", "free", "default")
  456. .action ([this, &lastScreen] (const std::string& value) -> void {
  457. const auto parsed = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
  458. if (!parsed.has_value ()) {
  459. sLog.exception ("Invalid scaling mode: ", value);
  460. }
  461. const auto mode = *parsed;
  462. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  463. this->settings.general.screenScalings[lastScreen] = mode;
  464. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  465. this->settings.general.spanGroups.back ().scaling = mode;
  466. }
  467. } else {
  468. this->settings.render.window.scalingMode = mode;
  469. }
  470. })
  471. .append ();
  472. backgroundGroup.add_argument ("--clamp")
  473. .help (
  474. "Clamp mode to use when rendering the background, this applies to the previous --window, --screen-root, "
  475. "or --screen-span output, or the default background if no other background is specified"
  476. )
  477. .choices ("clamp", "border", "repeat")
  478. .action ([this, &lastScreen] (const std::string& value) -> void {
  479. TextureFlags flags;
  480. if (value == "clamp") {
  481. flags = TextureFlags_ClampUVs;
  482. } else if (value == "border") {
  483. flags = TextureFlags_ClampUVsBorder;
  484. } else if (value == "repeat") {
  485. flags = TextureFlags_NoFlags;
  486. } else {
  487. sLog.exception ("Invalid clamp mode: ", value);
  488. }
  489. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  490. this->settings.general.screenClamps[lastScreen] = flags;
  491. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  492. this->settings.general.spanGroups.back ().clamp = flags;
  493. }
  494. } else {
  495. this->settings.render.window.clamp = flags;
  496. }
  497. })
  498. .append ();
  499. backgroundGroup.add_argument ("--zoom")
  500. .help (
  501. "Manual zoom factor layered on top of --scaling (e.g. 1.5 zooms in 50%, 0.5 zooms out to half size), "
  502. "this applies to the previous --window, --screen-root, or --screen-span output, or the default "
  503. "background if no other background is specified"
  504. )
  505. .action ([this, &lastScreen] (const std::string& value) -> void {
  506. float zoom;
  507. try {
  508. zoom = std::stof (value);
  509. } catch (const std::exception&) {
  510. sLog.exception ("Invalid zoom value: ", value);
  511. }
  512. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  513. this->settings.general.screenZooms[lastScreen] = zoom;
  514. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  515. this->settings.general.spanGroups.back ().zoom = zoom;
  516. }
  517. } else {
  518. this->settings.render.window.zoom = zoom;
  519. }
  520. })
  521. .append ();
  522. backgroundGroup.add_argument ("--offset")
  523. .help (
  524. "Re-centers the visible crop window a cropping scaling mode (e.g. --scaling fill) or --zoom produces, "
  525. "as \"X,Y\" with each axis in [-1, 1] (0,0 is centered/default, e.g. -1,0 shows as much of the left "
  526. "edge as the crop allows, 0,1 shows as much of the top edge as the crop allows). Has no visible "
  527. "effect where nothing is being cropped. This applies to the previous --window, --screen-root, or "
  528. "--screen-span output, or the default background if no other background is specified"
  529. )
  530. // "-1,0" would otherwise look like another option to argparse
  531. .allow_optional_like_value ()
  532. .action ([this, &lastScreen] (const std::string& value) -> void {
  533. const auto comma = value.find (',');
  534. if (comma == std::string::npos) {
  535. sLog.exception ("Offset must be in the format: X,Y");
  536. }
  537. glm::vec2 offset;
  538. try {
  539. offset.x = std::stof (value.substr (0, comma));
  540. offset.y = std::stof (value.substr (comma + 1));
  541. } catch (const std::exception&) {
  542. sLog.exception ("Invalid offset value: ", value);
  543. }
  544. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  545. this->settings.general.screenOffsets[lastScreen] = offset;
  546. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  547. this->settings.general.spanGroups.back ().offset = offset;
  548. }
  549. } else {
  550. this->settings.render.window.offset = offset;
  551. }
  552. })
  553. .append ();
  554. // WE's alignment settings in its own units (sub_140181F30 divides them by 100)
  555. const auto addAlignmentArgument = [this, &backgroundGroup, &lastScreen] (
  556. const char* name, const char* help, const float maximum,
  557. float WallpaperEngine::Render::WallpaperState::Alignment::* field
  558. ) {
  559. backgroundGroup.add_argument (name)
  560. .help (help)
  561. .action ([this, &lastScreen, name, maximum, field] (const std::string& value) -> void {
  562. float parsed;
  563. try {
  564. parsed = std::stof (value);
  565. } catch (const std::exception&) {
  566. sLog.exception ("Invalid ", name, " value: ", value);
  567. }
  568. if (parsed < 0.0f || parsed > maximum) {
  569. sLog.exception (name, " must be between 0 and ", maximum, ": ", value);
  570. }
  571. parsed /= 100.0f;
  572. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  573. auto& alignment = this->settings.general.screenAlignments
  574. .try_emplace (lastScreen, this->settings.render.window.alignment)
  575. .first->second;
  576. alignment.*field = parsed;
  577. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  578. this->settings.general.spanGroups.back ().alignment.*field = parsed;
  579. }
  580. } else {
  581. this->settings.render.window.alignment.*field = parsed;
  582. }
  583. })
  584. .append ();
  585. };
  586. addAlignmentArgument (
  587. "--alignment-position",
  588. "Wallpaper Engine's alignment position, 0-100 (default 50): where --scaling fill/default crops (0 keeps the "
  589. "right or top edge) and --scaling fit places the letterboxed wallpaper (0 = left or top). This applies to the "
  590. "previous --window, --screen-root, or --screen-span output, or the default background",
  591. 100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::position
  592. );
  593. addAlignmentArgument (
  594. "--alignment-x",
  595. "Wallpaper Engine's horizontal alignment for --scaling center and free, 0-100 (default 50, 0 = left). This "
  596. "applies to the previous --window, --screen-root, or --screen-span output, or the default background",
  597. 100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::x
  598. );
  599. addAlignmentArgument (
  600. "--alignment-y",
  601. "Wallpaper Engine's vertical alignment for --scaling center and free, 0-100 (default 50, 0 = top). This "
  602. "applies to the previous --window, --screen-root, or --screen-span output, or the default background",
  603. 100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::y
  604. );
  605. addAlignmentArgument (
  606. "--alignment-zoom",
  607. "Wallpaper Engine's zoom for --scaling free, 0-200 (default 100 = native size, higher zooms in). This applies "
  608. "to the previous --window, --screen-root, or --screen-span output, or the default background",
  609. 200.0f, &WallpaperEngine::Render::WallpaperState::Alignment::zoom
  610. );
  611. backgroundGroup.add_argument ("--corner-color")
  612. .help (
  613. "Color to show outside the wallpaper's bounds (Center/Fit letterboxing, zoomed-out scaling) when "
  614. "--clamp is border, as a hex RGB or RGBA value (e.g. \"000000\" or \"#1a1a1aff\"). Default: opaque "
  615. "black. This applies to the previous --window, --screen-root, or --screen-span output, or the "
  616. "default background if no other background is specified"
  617. )
  618. .action ([this, &lastScreen] (const std::string& value) -> void {
  619. const auto color = WallpaperEngine::Render::CFBO::parseColor (value);
  620. if (!color.has_value ()) {
  621. sLog.exception ("Invalid corner color: ", value);
  622. }
  623. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  624. this->settings.general.screenCornerColors[lastScreen] = *color;
  625. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  626. this->settings.general.spanGroups.back ().cornerColor = *color;
  627. }
  628. } else {
  629. this->settings.render.window.cornerColor = *color;
  630. }
  631. })
  632. .append ();
  633. // Wallpaper Engine's own image settings (its properties panel), every one of them applies to the previous
  634. // --window, --screen-root or --screen-span output like --zoom does
  635. const auto updateImageAdjustments = [this, &lastScreen] (const std::function<void (ImageAdjustments&)>& update) {
  636. if (this->settings.render.mode == DESKTOP_BACKGROUND) {
  637. update (this->settings.general.screenImageAdjustments[lastScreen]);
  638. if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
  639. update (this->settings.general.spanGroups.back ().imageAdjustments);
  640. }
  641. } else {
  642. update (this->settings.render.window.imageAdjustments);
  643. }
  644. };
  645. const auto parseSlider = [] (const std::string& name, const std::string& value) -> float {
  646. float result;
  647. try {
  648. result = std::stof (value);
  649. } catch (const std::exception&) {
  650. sLog.exception ("Invalid ", name, " value: ", value);
  651. }
  652. if (result < 0.0f || result > 100.0f) {
  653. sLog.exception (name, " must be between 0 and 100: ", value);
  654. }
  655. return result;
  656. };
  657. backgroundGroup.add_argument ("--image-filter")
  658. .help (
  659. "Applies one of Wallpaper Engine's image filters (a color lookup table from the assets' materials/lut "
  660. "folder, e.g. \"lutx32_amber\" or \"k23_b\"), \"none\" removes it. Scene and video wallpapers only. "
  661. "This applies to the previous --window, --screen-root, or --screen-span output, or the default "
  662. "background if no other background is specified"
  663. )
  664. .action ([updateImageAdjustments] (const std::string& value) -> void {
  665. updateImageAdjustments ([&value] (ImageAdjustments& adjustments) {
  666. adjustments.filter = value == "none" ? "" : value;
  667. });
  668. })
  669. .append ();
  670. backgroundGroup.add_argument ("--image-filter-strength")
  671. .help ("How strongly --image-filter applies, 0-100. Default: 100")
  672. .action ([updateImageAdjustments, parseSlider] (const std::string& value) -> void {
  673. const float strength = parseSlider ("image filter strength", value);
  674. updateImageAdjustments ([strength] (ImageAdjustments& adjustments) {
  675. adjustments.filterStrength = strength;
  676. });
  677. })
  678. .append ();
  679. for (const auto& [option, name] : std::initializer_list<std::pair<const char*, const char*>> {
  680. { "--brightness", "brightness" },
  681. { "--contrast", "contrast" },
  682. { "--saturation", "saturation" },
  683. { "--hue", "hue" },
  684. }) {
  685. backgroundGroup.add_argument (option)
  686. .help (
  687. std::string ("Wallpaper Engine's ") + name
  688. + " color option, 0-100 with 50 leaving the image unchanged. Scene and video wallpapers only"
  689. )
  690. .action ([updateImageAdjustments, parseSlider, name] (const std::string& value) -> void {
  691. const float amount = parseSlider (name, value);
  692. const std::string_view which = name;
  693. updateImageAdjustments ([amount, which] (ImageAdjustments& adjustments) {
  694. adjustments.colorEnabled = true;
  695. if (which == "brightness") {
  696. adjustments.brightness = amount;
  697. } else if (which == "contrast") {
  698. adjustments.contrast = amount;
  699. } else if (which == "saturation") {
  700. adjustments.saturation = amount;
  701. } else {
  702. adjustments.hue = amount;
  703. }
  704. });
  705. })
  706. .append ();
  707. }
  708. backgroundGroup.add_argument ("--color-options")
  709. .help (
  710. "Turns Wallpaper Engine's color options (--brightness and friends, or the ones a preset carries) on or "
  711. "off. Giving any of them turns them on"
  712. )
  713. .choices ("on", "off")
  714. .action ([updateImageAdjustments] (const std::string& value) -> void {
  715. updateImageAdjustments ([&value] (ImageAdjustments& adjustments) {
  716. adjustments.colorEnabled = value == "on";
  717. });
  718. })
  719. .append ();
  720. backgroundGroup.add_argument ("--flip")
  721. .help (
  722. "Mirrors the wallpaper horizontally (Wallpaper Engine's \"Flip\" option), \"on\" or \"off\". Scene and "
  723. "video wallpapers only"
  724. )
  725. .choices ("on", "off")
  726. .action ([updateImageAdjustments] (const std::string& value) -> void {
  727. updateImageAdjustments ([&value] (ImageAdjustments& adjustments) {
  728. adjustments.flipHorizontal = value == "on";
  729. });
  730. })
  731. .append ();
  732. backgroundGroup.add_argument ("--hdr")
  733. .help (
  734. "Wayland-only: sends HDR (PQ, BT.2020) to monitors running in HDR mode and plays HDR videos in HDR, "
  735. "like Wallpaper Engine's \"HDR display\" setting. Needs a compositor with the color management "
  736. "protocol (wp_color_manager_v1, recent KDE Plasma); other monitors keep getting the usual SDR image"
  737. )
  738. .flag ()
  739. .store_into (this->settings.render.hdr);
  740. backgroundGroup.add_argument ("--layer")
  741. .help (
  742. "Wayland-only: which wlr-layer-shell layer to anchor the wallpaper to "
  743. "(background, bottom, top, overlay). Default: bottom. On KDE 'background' shares a layer with "
  744. "plasmashell's desktop window, which covers the wallpaper whenever it maps after it (e.g. at login). "
  745. "Use 'background' on niri to pair with the `place-within-backdrop` layer-rule, "
  746. "otherwise the wallpaper will be cloned to every workspace in the overview."
  747. )
  748. .choices ("background", "bottom", "top", "overlay")
  749. .default_value (std::string ("bottom"))
  750. .action ([this] (const std::string& value) -> void {
  751. if (value == "background") {
  752. this->settings.render.wayland.layer = WAYLAND_LAYER_BACKGROUND;
  753. } else if (value == "bottom") {
  754. this->settings.render.wayland.layer = WAYLAND_LAYER_BOTTOM;
  755. } else if (value == "top") {
  756. this->settings.render.wayland.layer = WAYLAND_LAYER_TOP;
  757. } else if (value == "overlay") {
  758. this->settings.render.wayland.layer = WAYLAND_LAYER_OVERLAY;
  759. } else {
  760. sLog.exception ("Invalid wlr-layer-shell layer: ", value);
  761. }
  762. });
  763. auto& performanceGroup = program.add_group ("Performance options");
  764. performanceGroup.add_argument ("-f", "--fps")
  765. .help ("Limits the FPS to the given number, useful to keep battery consumption low")
  766. .default_value (60)
  767. .store_into (this->settings.render.maximumFPS);
  768. performanceGroup.add_argument ("--speed")
  769. .help (
  770. "Global playback speed multiplier for animations, particles and effects (e.g. 0.5 for half speed, "
  771. "2.0 for double speed). Useful to calm down backgrounds with overly fast particle effects"
  772. )
  773. .action ([this] (const std::string& value) -> void {
  774. float speed;
  775. try {
  776. speed = std::stof (value);
  777. } catch (const std::exception&) {
  778. sLog.exception ("Invalid speed value: ", value);
  779. }
  780. if (speed <= 0.0f) {
  781. sLog.exception ("--speed must be a positive number");
  782. }
  783. this->settings.render.playbackSpeed = speed;
  784. });
  785. performanceGroup.add_argument ("--no-fullscreen-pause")
  786. .help ("Prevents the background pausing when an app is fullscreen")
  787. .flag ()
  788. .action ([this] (const std::string& value) -> void { this->settings.render.pauseOnFullscreen = false; });
  789. performanceGroup.add_argument ("--fullscreen-pause-only-active")
  790. .help ("Wayland only: pause only when a fullscreen window is active (activated)")
  791. .flag ()
  792. .action ([this] (const std::string& value) -> void {
  793. this->settings.render.pauseOnFullscreenOnlyWhenActive = true;
  794. });
  795. performanceGroup.add_argument ("--fullscreen-pause-ignore-appid")
  796. .help ("Wayland only: ignore fullscreen windows whose app_id contains this value (repeatable)")
  797. .action ([this] (const std::string& value) -> void {
  798. if (!value.empty ()) {
  799. this->settings.render.fullscreenPauseIgnoreAppIds.push_back (value);
  800. }
  801. })
  802. .append ();
  803. auto& audioGroup = program.add_group ("Sound settings");
  804. auto& audioSettingsGroup = audioGroup.add_mutually_exclusive_group (false);
  805. audioSettingsGroup.add_argument ("-v", "--volume")
  806. .help ("Volume for all the sounds in the background")
  807. .default_value (15)
  808. .store_into (this->settings.audio.volume);
  809. audioSettingsGroup.add_argument ("-s", "--silent")
  810. .help ("Mutes all the sound the wallpaper might produce")
  811. .flag ()
  812. .action ([this] (const std::string& value) -> void { this->settings.audio.enabled = false; });
  813. audioGroup.add_argument ("--automute")
  814. .help ("Mutes the wallpaper's audio when another app is playing sound")
  815. .flag ()
  816. .action ([this] (const std::string& value) -> void { this->settings.audio.automute = true; });
  817. audioGroup.add_argument ("--noautomute")
  818. .help ("Disables the automute when an app is playing sound (default)")
  819. .flag ()
  820. .action ([this] (const std::string& value) -> void { this->settings.audio.automute = false; });
  821. audioGroup.add_argument ("--no-audio-processing")
  822. .help ("Disables audio processing for backgrounds")
  823. .flag ()
  824. .action ([this] (const std::string& value) -> void { this->settings.audio.audioprocessing = false; });
  825. audioGroup.add_argument ("--audio-screen")
  826. .help (
  827. "Only the background on this screen (matches --screen-root names) produces audio; every other screen "
  828. "is muted regardless of its own sound. Default: no restriction, every screen can produce sound."
  829. )
  830. .action ([this] (const std::string& value) -> void {
  831. if (!value.empty ()) {
  832. this->settings.audio.audioScreen = value;
  833. }
  834. });
  835. audioGroup.add_argument ("--ambient-volume")
  836. .help (
  837. "Separate volume (0-128) for non-video backgrounds (scene sound objects and web wallpapers), instead "
  838. "of --volume; video wallpapers always keep using --volume. Web wallpapers only support mute (0) vs "
  839. "unmuted (any other value), since CEF exposes no analog volume control. Default: same as --volume."
  840. )
  841. .action ([this] (const std::string& value) -> void {
  842. try {
  843. this->settings.audio.ambientVolume = std::stoi (value);
  844. } catch (const std::exception&) {
  845. sLog.exception ("Invalid --ambient-volume value: ", value);
  846. }
  847. });
  848. auto& screenshotGroup = program.add_group ("Screenshot options");
  849. screenshotGroup.add_argument ("--screenshot")
  850. .help ("Takes a screenshot of the background for it's use with tools like PyWAL")
  851. .default_value ("")
  852. .action ([this] (const std::string& value) -> void {
  853. this->settings.screenshot.take = true;
  854. this->settings.screenshot.path = value;
  855. });
  856. screenshotGroup.add_argument ("--screenshot-delay")
  857. .help ("Frames to wait before taking the screenshot")
  858. .default_value<uint32_t> (5)
  859. .store_into (this->settings.screenshot.delay);
  860. auto& contentGroup = program.add_group ("Content options");
  861. contentGroup.add_argument ("--assets-dir")
  862. .help ("Folder where the assets are stored")
  863. .default_value ("")
  864. .action ([this] (const std::string& value) -> void { this->settings.general.assets = value; });
  865. auto& configurationGroup = program.add_group ("Wallpaper configuration options");
  866. const auto parseVideoTime = [] (const char* name, const std::string& value) -> double {
  867. const auto seconds = WallpaperEngine::Render::Wallpapers::CVideo::parseTime (value);
  868. if (!seconds.has_value ()) {
  869. sLog.exception ("Invalid ", name, " value (seconds, m:ss or h:mm:ss): ", value);
  870. }
  871. return *seconds;
  872. };
  873. configurationGroup.add_argument ("--video-start")
  874. .help (
  875. "Video wallpapers only: where the part of the video that loops starts, in seconds, m:ss or h:mm:ss (e.g. "
  876. "\"3:00\"). Without --video-end it loops from here to the end of the video"
  877. )
  878. .action ([this, parseVideoTime] (const std::string& value) -> void {
  879. this->settings.render.videoStart = parseVideoTime ("--video-start", value);
  880. });
  881. configurationGroup.add_argument ("--video-end")
  882. .help (
  883. "Video wallpapers only: where the part of the video that loops ends, in seconds, m:ss or h:mm:ss (e.g. "
  884. "\"4:00\"). Without --video-start it loops from the beginning up to here"
  885. )
  886. .action ([this, parseVideoTime] (const std::string& value) -> void {
  887. this->settings.render.videoEnd = parseVideoTime ("--video-end", value);
  888. });
  889. configurationGroup.add_argument ("--control-file")
  890. .help (
  891. "File the SIGUSR1 hotswap request is read from. Give every engine its own when several run at once, "
  892. "otherwise they all read the same one. Default: $XDG_RUNTIME_DIR/lwe-control"
  893. )
  894. .action ([this] (const std::string& value) -> void {
  895. if (!value.empty ()) {
  896. this->settings.general.controlFile = value;
  897. }
  898. });
  899. configurationGroup.add_argument ("--disable-particles")
  900. .help ("Disables particles for the backgrounds")
  901. .flag ()
  902. .action ([this] (const std::string& value) -> void { this->settings.general.disableParticles = true; });
  903. configurationGroup.add_argument ("--expand-canvas")
  904. .help (
  905. "Grows a scene's render canvas so image layers that extend past the camera's projection (a tall or wide "
  906. "picture the author only meant to be revealed by parallax) are shown in full instead of cropped. Layout "
  907. "stays centered on the original canvas, so it only ever adds room around it. Combine with "
  908. "--disable-parallax and --scaling fit to see the whole picture"
  909. )
  910. .flag ()
  911. .action ([this] (const std::string& value) -> void { this->settings.general.expandCanvas = true; });
  912. configurationGroup.add_argument ("--post-processing")
  913. .help (
  914. "Wallpaper Engine's post processing quality: \"enabled\" (default), \"ultra\" or \"displayhdr\". With "
  915. "ultra, scenes that turn on both bloom and hdr render in HDR with Wallpaper Engine's HDR bloom; displayhdr "
  916. "also lets their highlights go up to an HDR output's peak brightness (with --hdr)"
  917. )
  918. .choices ("enabled", "ultra", "displayhdr")
  919. .action ([this] (const std::string& value) -> void {
  920. this->settings.general.ultraPostProcessing = value == "ultra" || value == "displayhdr";
  921. this->settings.general.displayHDR = value == "displayhdr";
  922. });
  923. // same names and numbers as Wallpaper Engine's quality settings (sub_14010DAD0)
  924. const auto qualityLevel = [] (const std::string& value) {
  925. return value == "disabled" ? 0 : value == "low" ? 1 : value == "high" ? 3 : value == "ultra" ? 4 : 2;
  926. };
  927. configurationGroup.add_argument ("--volumetrics")
  928. .help ("Wallpaper Engine's volumetric lighting quality: disabled, low, medium (default), high or ultra")
  929. .choices ("disabled", "low", "medium", "high", "ultra")
  930. .action ([this, qualityLevel] (const std::string& value) -> void {
  931. this->settings.general.volumetricsQuality = qualityLevel (value);
  932. });
  933. configurationGroup.add_argument ("--shadows")
  934. .help ("Wallpaper Engine's shadow quality: disabled, low, medium (default), high or ultra")
  935. .choices ("disabled", "low", "medium", "high", "ultra")
  936. .action ([this, qualityLevel] (const std::string& value) -> void {
  937. this->settings.general.shadowQuality = qualityLevel (value);
  938. });
  939. configurationGroup.add_argument ("--msaa")
  940. .help (
  941. "Wallpaper Engine's anti-aliasing setting: none (default), x2, x4 or x8. Like Wallpaper Engine it only "
  942. "applies "
  943. "to scenes with a 3D model object, which then draw their objects multisampled"
  944. )
  945. .choices ("none", "x2", "x4", "x8")
  946. .action ([this] (const std::string& value) -> void {
  947. this->settings.general.msaaSamples = value == "x2" ? 2 : value == "x4" ? 4 : value == "x8" ? 8 : 0;
  948. });
  949. configurationGroup.add_argument ("--ssaa")
  950. .help (
  951. "Supersampling for scenes: none (default), x2, x3 or x4. The scene renders at that many times the output "
  952. "size per axis and is averaged down, so it costs that factor squared in GPU time and memory. Effects "
  953. "measured in pixels (blur, bloom) cover the same pixels as on a screen that much bigger"
  954. )
  955. .choices ("none", "x2", "x3", "x4")
  956. .action ([this] (const std::string& value) -> void {
  957. this->settings.general.supersampling = value == "x2" ? 2 : value == "x3" ? 3 : value == "x4" ? 4 : 1;
  958. });
  959. configurationGroup.add_argument ("--disable-animations")
  960. .help ("Freezes all scene animation (scripts, particles, effects and puppet meshes) at its current frame")
  961. .flag ()
  962. .action ([this] (const std::string& value) -> void { this->settings.render.freezeAnimations = true; });
  963. configurationGroup.add_argument ("--disable-mouse")
  964. .help ("Disables mouse interaction with the backgrounds")
  965. .flag ()
  966. .action ([this] (const std::string& value) -> void { this->settings.mouse.enabled = false; });
  967. configurationGroup.add_argument ("--disable-parallax")
  968. .help ("Disables parallax effect for the backgrounds")
  969. .flag ()
  970. .action ([this] (const std::string& value) -> void { this->settings.mouse.disableparallax = true; });
  971. configurationGroup.add_argument ("--allow-parallax-overflow")
  972. .help (
  973. "Lets parallax push an image past its own edges, exposing black corners on layers too small for the "
  974. "movement. Disabled by default, which clamps parallax displacement to each image's own size; images "
  975. "whose texture tiles/repeats are always exempt from the clamp, since going past their edges is seamless"
  976. )
  977. .flag ()
  978. .action ([this] (const std::string& value) -> void { this->settings.mouse.clampParallaxToImageSize = false; });
  979. configurationGroup.add_argument ("-l", "--list-properties")
  980. .help ("List all the available properties and their configuration")
  981. .flag ()
  982. .store_into (this->settings.general.onlyListProperties);
  983. configurationGroup.add_argument ("--set-property", "--property")
  984. .help ("Overrides the default value of the given property")
  985. .action ([this] (const std::string& value) -> void {
  986. const std::string::size_type equals = value.find ('=');
  987. // properties without a value are treated as booleans for now
  988. if (equals == std::string::npos) {
  989. this->settings.general.properties[value] = "1";
  990. } else {
  991. this->settings.general.properties[value.substr (0, equals)] = value.substr (equals + 1);
  992. }
  993. })
  994. .append ();
  995. configurationGroup.add_argument ("--list-objects")
  996. .help ("List all the objects/layers a background has, with their id, name and type")
  997. .flag ()
  998. .store_into (this->settings.general.onlyListObjects);
  999. configurationGroup.add_argument ("--disable-object")
  1000. .help ("Hides an object/layer (parallax layer, clock, particles, etc), matched by id or name. Can be repeated")
  1001. .action ([this] (const std::string& value) -> void {
  1002. this->settings.general.disabledObjects.push_back (value);
  1003. })
  1004. .append ();
  1005. configurationGroup.add_argument ("--enable-object")
  1006. .help (
  1007. "Forces an object/layer to show even if the background hides it by default, matched by id or name. "
  1008. "Can be repeated"
  1009. )
  1010. .action ([this] (const std::string& value) -> void { this->settings.general.enabledObjects.push_back (value); })
  1011. .append ();
  1012. configurationGroup.add_argument ("--list-effects")
  1013. .help (
  1014. "List all effects (bloom, blur, glow, etc) attached to a background's objects, with their id, editor "
  1015. "name and category"
  1016. )
  1017. .flag ()
  1018. .store_into (this->settings.general.onlyListEffects);
  1019. configurationGroup.add_argument ("--disable-effect")
  1020. .help (
  1021. "Disables an object's visual effect (bloom, blur, glow, etc), matched by effect id or editor name. "
  1022. "Can be repeated"
  1023. )
  1024. .action ([this] (const std::string& value) -> void {
  1025. this->settings.general.disabledEffects.push_back (value);
  1026. })
  1027. .append ();
  1028. configurationGroup.add_argument ("--enable-effect")
  1029. .help (
  1030. "Forces an effect to show even if the scene hides it by default, matched by effect id or editor name. "
  1031. "Can be repeated"
  1032. )
  1033. .action ([this] (const std::string& value) -> void { this->settings.general.enabledEffects.push_back (value); })
  1034. .append ();
  1035. configurationGroup.add_argument ("--list-audio-objects")
  1036. .help (
  1037. "List objects/properties whose script reacts to music (via engine.registerAudioBuffers), with their "
  1038. "current minvalue/maxvalue/frequency/smoothing"
  1039. )
  1040. .flag ()
  1041. .store_into (this->settings.general.onlyListAudioObjects);
  1042. configurationGroup.add_argument ("--audio-sensitivity")
  1043. .help (
  1044. "Scales how much an audio-reactive object's music-driven properties swing around their authored "
  1045. "midpoint, matched by id or name: 0 locks it (no pulse), 1 is the wallpaper's original behavior, "
  1046. ">1 exaggerates it. Use \"*\" as the id to set a default for every audio-reactive object with no "
  1047. "more specific match. Format: <id-or-name-or-*>=<multiplier>. Can be repeated"
  1048. )
  1049. .action ([this] (const std::string& value) -> void {
  1050. const std::string::size_type equals = value.find ('=');
  1051. if (equals == std::string::npos) {
  1052. sLog.exception ("--audio-sensitivity expects <id-or-name>=<multiplier>, got '" + value + "'");
  1053. }
  1054. const std::string target = value.substr (0, equals);
  1055. const std::string multiplierStr = value.substr (equals + 1);
  1056. try {
  1057. this->settings.general.audioSensitivity[target] = std::stof (multiplierStr);
  1058. } catch (const std::exception&) {
  1059. sLog.exception ("--audio-sensitivity: '" + multiplierStr + "' is not a valid number");
  1060. }
  1061. })
  1062. .append ();
  1063. configurationGroup.add_argument ("--sound-volume")
  1064. .help (
  1065. "Sets a Sound object's own volume (0-1), independent of the global volume - lets a wallpaper with "
  1066. "several alternate music tracks play only one, matched by id or name. Use \"*\" as the id to set a "
  1067. "default for every Sound object with no more specific match. Format: <id-or-name-or-*>=<volume>. Can "
  1068. "be repeated"
  1069. )
  1070. .action ([this] (const std::string& value) -> void {
  1071. const std::string::size_type equals = value.find ('=');
  1072. if (equals == std::string::npos) {
  1073. sLog.exception ("--sound-volume expects <id-or-name>=<volume>, got '" + value + "'");
  1074. }
  1075. const std::string target = value.substr (0, equals);
  1076. const std::string volumeStr = value.substr (equals + 1);
  1077. try {
  1078. this->settings.general.soundVolume[target] = std::stof (volumeStr);
  1079. } catch (const std::exception&) {
  1080. sLog.exception ("--sound-volume: '" + volumeStr + "' is not a valid number");
  1081. }
  1082. })
  1083. .append ();
  1084. auto& debuggingGroup = program.add_group ("Debugging options");
  1085. debuggingGroup.add_argument ("-z", "--dump-structure")
  1086. .help ("Dumps the structure of the backgrounds")
  1087. .flag ()
  1088. .store_into (this->settings.general.dumpStructure);
  1089. debuggingGroup.add_argument ("--render-debug")
  1090. .help (
  1091. "Scene render debug mode: base-only, no-solid-final, pass-log, brightness-log, no-puppet-animation, "
  1092. "object=<id>, "
  1093. "skip-object=<id>, or skip-effect=<id>. Can be repeated."
  1094. )
  1095. .action ([this] (const std::string& value) -> void {
  1096. const auto parseDebugId = [&value] (const std::string& prefix) -> std::optional<int> {
  1097. try {
  1098. return std::stoi (value.substr (prefix.length ()));
  1099. } catch (const std::invalid_argument&) {
  1100. sLog.exception ("Invalid numeric value for --render-debug ", value);
  1101. } catch (const std::out_of_range&) {
  1102. sLog.exception ("Out-of-range numeric value for --render-debug ", value);
  1103. }
  1104. return std::nullopt;
  1105. };
  1106. if (value == "base-only") {
  1107. this->settings.render.debug.baseOnly = true;
  1108. } else if (value == "no-solid-final") {
  1109. this->settings.render.debug.noSolidFinal = true;
  1110. } else if (value == "pass-log") {
  1111. this->settings.render.debug.passLog = true;
  1112. } else if (value == "brightness-log") {
  1113. this->settings.render.debug.brightnessLog = true;
  1114. } else if (value == "no-puppet-animation") {
  1115. this->settings.render.debug.noPuppetAnimation = true;
  1116. } else if (value.rfind ("object=", 0) == 0) {
  1117. this->settings.render.debug.objectFilter = parseDebugId ("object=");
  1118. } else if (value.rfind ("skip-object=", 0) == 0) {
  1119. if (const auto id = parseDebugId ("skip-object="); id.has_value ()) {
  1120. this->settings.render.debug.skipObjects.emplace_back (*id);
  1121. }
  1122. } else if (value.rfind ("skip-effect=", 0) == 0) {
  1123. if (const auto id = parseDebugId ("skip-effect="); id.has_value ()) {
  1124. this->settings.render.debug.skipEffects.emplace_back (*id);
  1125. }
  1126. } else {
  1127. sLog.exception ("Invalid render debug mode: ", value);
  1128. }
  1129. })
  1130. .append ();
  1131. program.add_epilog (
  1132. "Usage examples:\n"
  1133. " linux-wallpaperengine --screen-root HDMI-1 --bg 2317494988 --scaling fill --clamp border\n"
  1134. " Runs the background 2317494988 on screen HDMI-1, scaling it to fill the screen and clamping the UVs to "
  1135. "the border\n\n"
  1136. " linux-wallpaperengine 2317494988\n"
  1137. " Previews the background 2317494988 on a window\n\n"
  1138. " linux-wallpaperengine --screen-root HDMI-1 --bg 2317494988 --screen-root HDMI-2 --bg 1108150151\n"
  1139. " Runs two backgrounds on two screens, one on HDMI-1 and the other on HDMI-2\n\n"
  1140. " linux-wallpaperengine --screen-root HDMI-1 --screen-root HDMI-2 2317494988\n"
  1141. " Runs the background 2317494988 on two screens, one on HDMI-1 and the other on HDMI-2\n\n"
  1142. " linux-wallpaperengine --screen-span HDMI-1,HDMI-2 --bg 2317494988 --scaling fill\n"
  1143. " Spans the background 2317494988 across HDMI-1 and HDMI-2 as a single stretched wallpaper\n\n"
  1144. );
  1145. try {
  1146. program.parse_known_args (this->m_argc, this->m_argv);
  1147. if (this->settings.general.defaultBackground.empty ()) {
  1148. throw std::runtime_error ("At least one background ID must be specified");
  1149. }
  1150. this->settings.audio.volume = std::max (0, std::min (this->settings.audio.volume, 128));
  1151. if (this->settings.audio.ambientVolume.has_value ()) {
  1152. this->settings.audio.ambientVolume = std::max (0, std::min (*this->settings.audio.ambientVolume, 128));
  1153. }
  1154. this->settings.screenshot.delay
  1155. = std::max<uint32_t> (0, std::min<uint32_t> (this->settings.screenshot.delay, 5000));
  1156. // std::cout directly, in case logging is disabled, so this is still visible
  1157. std::stringbuf buffer;
  1158. std::ostream bufferStream (&buffer);
  1159. bufferStream << "Running with: ";
  1160. for (int i = 0; i < this->m_argc; i++) {
  1161. bufferStream << this->m_argv[i];
  1162. bufferStream << " ";
  1163. }
  1164. if (!isHelperProcess (this->m_argc, this->m_argv, this->settings.general.webHost)) {
  1165. std::cout << buffer.str () << std::endl;
  1166. }
  1167. this->validateAssets ();
  1168. this->validateScreenshot ();
  1169. this->state.general.keepRunning = true;
  1170. this->state.audio.enabled = this->settings.audio.enabled;
  1171. this->state.audio.volume = this->settings.audio.volume;
  1172. this->state.mouse.enabled = this->settings.mouse.enabled;
  1173. #if DEMOMODE
  1174. sLog.error ("WARNING: RUNNING IN DEMO MODE WILL STOP WALLPAPERS AFTER 5 SECONDS SO VIDEO CAN BE RECORDED");
  1175. this->settings.render.maximumFPS = 30;
  1176. this->settings.screenshot.take = false;
  1177. this->settings.render.pauseOnFullscreen = false;
  1178. #endif /* DEMOMODE */
  1179. } catch (const std::runtime_error& e) {
  1180. throw std::runtime_error (
  1181. std::string (e.what ()) + ". Use " + std::string (this->m_argv[0]) + " --help for more information"
  1182. );
  1183. }
  1184. }
  1185. int ApplicationContext::getArgc () const { return this->m_argc; }
  1186. char** ApplicationContext::getArgv () const { return this->m_argv; }
  1187. std::filesystem::path ApplicationContext::translateBackground (const std::string& bgIdOrPath) {
  1188. if (bgIdOrPath.find ('/') == std::string::npos) {
  1189. return Steam::FileSystem::workshopDirectory (WORKSHOP_APP_ID, bgIdOrPath);
  1190. }
  1191. return bgIdOrPath;
  1192. }
  1193. void ApplicationContext::validateAssets () {
  1194. if (!this->settings.general.assets.empty ()) {
  1195. if (!isHelperProcess (this->m_argc, this->m_argv, this->settings.general.webHost)) {
  1196. sLog.out (
  1197. "Using wallpaper engine's assets at ", this->settings.general.assets, " based on --assets-dir parameter"
  1198. );
  1199. }
  1200. return;
  1201. }
  1202. try {
  1203. this->settings.general.assets = Steam::FileSystem::appDirectory (APP_DIRECTORY, "assets");
  1204. } catch (std::runtime_error&) {
  1205. this->settings.general.assets = std::filesystem::canonical ("/proc/self/exe").parent_path () / "assets";
  1206. }
  1207. }
  1208. void ApplicationContext::validateScreenshot () const {
  1209. if (!this->settings.screenshot.take) {
  1210. return;
  1211. }
  1212. if (!this->settings.screenshot.path.has_extension ()) {
  1213. sLog.exception ("Cannot determine screenshot format");
  1214. }
  1215. const std::string extension = this->settings.screenshot.path.extension ();
  1216. if (extension != ".bmp" && extension != ".png" && extension != ".jpeg" && extension != ".jpg") {
  1217. sLog.exception ("Cannot determine screenshot format, unknown extension ", extension);
  1218. }
  1219. }