Explorar el Código

added localstorage and hwdec flag

UwU hace 1 mes
padre
commit
2e2f262483

+ 6 - 1
CMakeLists.txt

@@ -637,6 +637,10 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Scripting/JS.cpp
     src/WallpaperEngine/Scripting/ConsoleObject.h
     src/WallpaperEngine/Scripting/ConsoleObject.cpp
+    src/WallpaperEngine/Scripting/LocalStorage.h
+    src/WallpaperEngine/Scripting/LocalStorage.cpp
+    src/WallpaperEngine/Scripting/LocalStorageObject.h
+    src/WallpaperEngine/Scripting/LocalStorageObject.cpp
     src/WallpaperEngine/Scripting/EngineObject.h
     src/WallpaperEngine/Scripting/EngineObject.cpp
     src/WallpaperEngine/Scripting/InputObject.h
@@ -684,7 +688,8 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/TextInputProperty.cpp
         src/WallpaperEngine/Testing/Cases/TextLayoutRules.cpp
         src/WallpaperEngine/Testing/Cases/MediaCover.cpp
-        src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp)
+        src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp
+        src/WallpaperEngine/Testing/Cases/LocalStorage.cpp)
 endif()
 
 add_library(

+ 3 - 1
README.md

@@ -33,6 +33,7 @@ Scenes:
 Scripts and audio:
 
 - Scene scripts run on V8 like in Wallpaper Engine, with Wallpaper Engine's own helper classes from its assets and most of the SceneScript API (layer creation and sorting, cursor events, video textures, animations, bones, camera, model data, timers, user shortcuts).
+- Script `localStorage` survives restarts like in Wallpaper Engine (same file format, in `~/.local/state/linux-wallpaperengine/scenestorage`), so a dragged clock or character stays where it was put.
 - The audio spectrum is computed like Wallpaper Engine computes it, so visualizers move the same.
 - Web wallpapers run CEF in a separate, disposable process and get properties, audio data and Wallpaper Engine's JavaScript API.
 
@@ -108,7 +109,7 @@ The folder can live anywhere. Web wallpapers run in Chromium's sandbox when the
 
 Other ways to get it:
 
-- **AUR**: `linux-wallpaperengine-kde-bin` (the portable build in `/opt`) or `linux-wallpaperengine-kde-git` (built from this repository, needs the AUR's `libnode`).
+- **AUR** (coming soon, AUR registration is paused right now): `linux-wallpaperengine-kde-bin` (the portable build in `/opt`) and `linux-wallpaperengine-kde-git` (built from this repository, needs the AUR's `libnode`). Until then use the portable build.
 - **Flatpak**: [WE Manager](https://github.com/WallpaperEngineLover/we_manager)'s Flatpak comes with the engine.
 - **Nix**: `nix run github:WallpaperEngineLover/linux-wallpaperengine-kde -- --help` builds it from source against nixpkgs (the first build also compiles Node.js as a shared library for V8) (`packages.x86_64-linux.generic` without the KDE integration, `overlays.default` adds `linux-wallpaperengine-kde`).
 
@@ -191,6 +192,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--hdr` | Wayland only: HDR (PQ, BT.2020) output to monitors running in HDR mode, HDR videos in HDR |
 | `--layer <layer>` | Wayland only: `wlr-layer-shell` layer (`background`, `bottom`, `top`, `overlay`). Default `bottom`, on KDE `background` can end up under plasmashell's desktop window |
 | `--speed <factor>` | Global playback speed multiplier |
+| `--hwdec <backend>` | mpv hardware decoding for videos: `auto` (default), `no`, `vaapi-copy`, `nvdec-copy`, ... Try `no` if videos crash on NVIDIA |
 | `--video-start <time>`, `--video-end <time>` | Video wallpapers only: loop just this part of the video, in seconds, `m:ss` or `h:mm:ss` (either one alone leaves that side at the video's start/end) |
 | `--video-segments <start-end,...>` | Video wallpapers only: play these parts one after the other and skip everything between them, e.g. `"2:00-3:00,4:00-5:00"`; an empty side is the video's start/end (`"4:00-"`) |
 | `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control` |

+ 1 - 1
packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD

@@ -1,4 +1,4 @@
-# Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
+# Maintainer: WallpaperEngineLover <260361707+WallpaperEngineLover@users.noreply.github.com>
 # pkgver and the checksum are set by the aur job of .github/workflows/cmake.yml on every release
 pkgname=linux-wallpaperengine-kde-bin
 _pkgname=linux-wallpaperengine-kde

+ 1 - 1
packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD

@@ -1,4 +1,4 @@
-# Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
+# Maintainer: WallpaperEngineLover <260361707+WallpaperEngineLover@users.noreply.github.com>
 pkgname=linux-wallpaperengine-kde-git
 _pkgname=linux-wallpaperengine-kde
 pkgver=r0

+ 14 - 0
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -911,6 +911,20 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.playbackSpeed = speed;
 	});
 
+    performanceGroup.add_argument ("--hwdec")
+	.help (
+	    "Hardware video decoding backend handed to mpv for video wallpapers and video textures: auto (default), "
+	    "no, vaapi, vaapi-copy, nvdec, nvdec-copy, cuda, vulkan or any other mpv --hwdec value. Try no or a -copy "
+	    "variant if videos crash, stay black or fall back to software decoding. Control file: hwdec=<backend>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    if (!WallpaperEngine::VideoPlayback::MPV::GLPlayer::isValidHwdec (value)) {
+		sLog.exception ("Invalid --hwdec value: ", value);
+	    }
+
+	    this->settings.render.hwdec = value;
+	});
+
     performanceGroup.add_argument ("--no-fullscreen-pause")
 	.help ("Prevents the background pausing when an app is fullscreen")
 	.flag ()

+ 3 - 0
src/WallpaperEngine/Application/ApplicationContext.h

@@ -186,6 +186,8 @@ public:
 	    /** Global playback speed multiplier for animations, particles and effects, see --speed */
 	    float playbackSpeed;
 	    WallpaperEngine::VideoPlayback::VideoSegments videoSegments;
+	    /** mpv hwdec value for every video player, see --hwdec */
+	    std::string hwdec;
 	    /** Freezes scene time entirely (scripts, particles, effects and puppet meshes all stop advancing), see
 	     * --disable-animations */
 	    bool freezeAnimations;
@@ -302,6 +304,7 @@ public:
             .maximumFPS = 60,
             .playbackSpeed = 1.0f,
             .videoSegments = {},
+            .hwdec = "auto",
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,

+ 57 - 4
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -15,6 +15,7 @@
 #include "WallpaperEngine/Render/Wallpapers/CSplat.h"
 #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
 #include "WallpaperEngine/Render/Wallpapers/CWeb.h"
+#include "WallpaperEngine/Scripting/LocalStorage.h"
 
 #include "WallpaperEngine/Data/Dumpers/StringPrinter.h"
 #include "WallpaperEngine/Data/Parsers/ProjectParser.h"
@@ -214,7 +215,7 @@ WallpaperApplication::ProjectSource WallpaperApplication::openProjectSource (con
     auto json = WallpaperEngine::Data::JSON::JSON::parseAsset (container->readString ("project.json"));
 
     if (json.contains ("file") || !json.contains ("dependency")) {
-	return { std::move (container), std::move (json), std::nullopt };
+	return { std::move (container), std::move (json), std::nullopt, path };
     }
 
     const auto dependency = json.at ("dependency");
@@ -235,7 +236,7 @@ WallpaperApplication::ProjectSource WallpaperApplication::openProjectSource (con
     auto baseContainer = this->setupAssetLocator (baseDir.string (), presetDir);
     auto baseJson = WallpaperEngine::Data::JSON::JSON::parseAsset (baseContainer->readString ("project.json"));
 
-    return { std::move (baseContainer), std::move (baseJson), json.optional ("preset") };
+    return { std::move (baseContainer), std::move (baseJson), json.optional ("preset"), baseDir };
 }
 
 namespace {
@@ -355,7 +356,7 @@ void WallpaperApplication::applyPreset (
 }
 
 ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
-    auto [container, json, preset] = this->openProjectSource (bg);
+    auto [container, json, preset, directory] = this->openProjectSource (bg);
 
     // reset screenshot state so a background change (e.g. playlist advance) can screenshot again
     if (this->m_context.settings.screenshot.take) {
@@ -368,7 +369,23 @@ ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) {
 	this->m_screenShotTaken = false;
     }
 
+    const std::string sceneFileName = json.contains ("file") && json.at ("file").is_string ()
+	? json.at ("file").get<std::string> ()
+	: std::string ();
     auto project = WallpaperEngine::Data::Parsers::ProjectParser::parse (json, std::move (container));
+    std::error_code error;
+    auto folder = std::filesystem::weakly_canonical (std::filesystem::absolute (directory), error);
+
+    if (error || folder.empty ()) {
+	folder = std::filesystem::absolute (directory).lexically_normal ();
+    }
+
+    if (!folder.has_filename ()) {
+	folder = folder.parent_path ();
+    }
+
+    // WE opens scene.pkg when there is one
+    project->sceneFile = std::filesystem::exists (folder / "scene.pkg") ? folder / "scene.pkg" : folder / sceneFileName;
 
     if (preset.has_value ()) {
 	std::filesystem::path presetDir = bg;
@@ -584,6 +601,7 @@ void WallpaperApplication::advancePlaylist (
 		    *this->m_backgrounds[screen]->wallpaper, *this->m_renderContext, *this->m_audioContext, nextPath,
 		    scaling, clamp, this->resolveScreenRenderSize (screen)
 		);
+		wallpaper->setStorageScreen (this->storageScreen (screen));
 		wallpaper->setZoom (this->resolveScreenZoom (screen));
 		const auto offset = this->resolveScreenOffset (screen);
 		wallpaper->setOffset (offset.x, offset.y);
@@ -694,6 +712,8 @@ struct HotswapRequest {
     std::optional<std::string> videoEnd;
     /** "" or "none" clears it */
     std::optional<std::string> videoSegments;
+    /** mpv hwdec value, see --hwdec */
+    std::optional<std::string> hwdec;
     /** position to jump video wallpapers to, same format */
     std::optional<std::string> videoSeek;
     /** screen name to restrict audio to, or "" to clear the restriction, see --audio-screen */
@@ -850,6 +870,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.videoSegments = value;
 	} else if (key == "video-seek") {
 	    request.videoSeek = value;
+	} else if (key == "hwdec") {
+	    request.hwdec = value;
 	} else if (key == "audio-screen") {
 	    request.audioScreen = value;
 	} else if (key == "ambient-volume") {
@@ -917,7 +939,7 @@ void WallpaperApplication::checkHotswapRequest () {
 	&& !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
 	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
 	&& !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
-	&& !request.disableAnimations.has_value ()) {
+	&& !request.disableAnimations.has_value () && !request.hwdec.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -998,6 +1020,10 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applyVideoSeekHotswap (*request.videoSeek);
     }
 
+    if (request.hwdec.has_value ()) {
+	this->applyHwdecHotswap (*request.hwdec);
+    }
+
     if (request.audioScreen.has_value ()) {
 	this->applyAudioScreenHotswap (*request.audioScreen);
     }
@@ -1143,6 +1169,7 @@ void WallpaperApplication::checkHotswapRequest () {
 			*background->wallpaper, *this->m_renderContext, *this->m_audioContext, targetPath, scaling,
 			clamp, this->resolveScreenRenderSize (screen)
 		    );
+		    wallpaper->setStorageScreen (this->storageScreen (screen));
 		    wallpaper->setZoom (this->resolveScreenZoom (screen));
 		    const auto offset = this->resolveScreenOffset (screen);
 		    wallpaper->setOffset (offset.x, offset.y);
@@ -1185,6 +1212,12 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 }
 
+std::string WallpaperApplication::storageScreen (const std::string& screen) const {
+    // WE: nothing in a window, "Monitor<index>" on the desktop (sub_14012E710); output names survive reordering
+    const auto mode = this->m_context.settings.render.mode;
+    return mode == ApplicationContext::NORMAL_WINDOW || mode == ApplicationContext::EXPLICIT_WINDOW ? "" : screen;
+}
+
 std::string WallpaperApplication::resolveScreenBackgroundPath (const std::string& screen) const {
     if (screen.starts_with ("span:")) {
 	for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
@@ -1647,6 +1680,22 @@ void WallpaperApplication::applyVideoSeekHotswap (const std::string& value) {
     }
 }
 
+void WallpaperApplication::applyHwdecHotswap (const std::string& value) {
+    if (!WallpaperEngine::VideoPlayback::MPV::GLPlayer::isValidHwdec (value)) {
+	sLog.error ("Hotswap: ignoring invalid hwdec value: ", value);
+	return;
+    }
+
+    if (this->m_context.settings.render.hwdec == value) {
+	return;
+    }
+
+    this->m_context.settings.render.hwdec = value;
+    WallpaperEngine::VideoPlayback::MPV::GLPlayer::setHwdecForAll (value);
+
+    sLog.out ("Hotswap: applied hwdec ", value, " live");
+}
+
 void WallpaperApplication::applyAudioScreenHotswap (const std::string& value) {
     this->m_context.settings.audio.audioScreen = value.empty () ? std::nullopt : std::optional<std::string> (value);
 
@@ -2460,6 +2509,7 @@ void WallpaperApplication::prepareOutputs () {
 	    *info->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (background),
 	    scaling, clamp, this->resolveScreenRenderSize (background)
 	);
+	wallpaper->setStorageScreen (this->storageScreen (background));
 	wallpaper->setZoom (this->resolveScreenZoom (background));
 	const auto offset = this->resolveScreenOffset (background);
 	wallpaper->setOffset (offset.x, offset.y);
@@ -2524,6 +2574,7 @@ void WallpaperApplication::prepareOutputs () {
 	    *bgIt->second->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (groupKey),
 	    spanGroup.scaling, spanGroup.clamp, glm::ivec2 { maxX - minX, maxY - minY }
 	);
+	sharedWallpaper->setStorageScreen (this->storageScreen (groupKey));
 	sharedWallpaper->setZoom (spanGroup.zoom);
 	sharedWallpaper->setOffset (spanGroup.offset.x, spanGroup.offset.y);
 	sharedWallpaper->setAlignment (spanGroup.alignment);
@@ -2764,6 +2815,8 @@ void WallpaperApplication::show () {
     while (this->m_context.state.general.keepRunning) {
 	render ();
     }
+    // before teardown, a manager may SIGKILL a slow stop
+    WallpaperEngine::Scripting::LocalStorage::flushAll ();
     cleanup ();
 }
 

+ 5 - 0
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -62,6 +62,8 @@ private:
 	AssetLocatorUniquePtr container;
 	WallpaperEngine::Data::JSON::JSON json;
 	std::optional<WallpaperEngine::Data::JSON::JSON> preset;
+	/** Wallpaper folder, the base wallpaper's for a preset */
+	std::filesystem::path directory;
     };
 
     /** overlay is an extra folder mounted after bg, used for preset-owned files (e.g. splat data) */
@@ -181,6 +183,7 @@ private:
 
     /** Jumps video wallpapers to a position (seconds, m:ss or h:mm:ss), e.g. a few seconds before the loop end */
     void applyVideoSeekHotswap (const std::string& value);
+    void applyHwdecHotswap (const std::string& value);
 
     /**
      * Pushes a new --audio-screen restriction live (empty value clears it back to "no
@@ -215,6 +218,8 @@ private:
      * hotswap can reload it without the caller having to resend the path
      */
     [[nodiscard]] std::string resolveScreenBackgroundPath (const std::string& screen) const;
+    /** Screen suffix for script localStorage's screen store */
+    [[nodiscard]] std::string storageScreen (const std::string& screen) const;
     [[nodiscard]] float resolveScreenZoom (const std::string& screen) const;
     [[nodiscard]] glm::vec2 resolveScreenOffset (const std::string& screen) const;
     [[nodiscard]] WallpaperEngine::Render::WallpaperState::Alignment

+ 3 - 0
src/WallpaperEngine/Data/Model/Project.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <filesystem>
 #include <memory>
 #include <string>
 
@@ -22,6 +23,8 @@ struct Project {
     AssetLocatorUniquePtr assetLocator;
     /** Image filter, color options and flip a preset carries (wcc_*, wec_*, alignmentfliph) */
     ImageAdjustments imageAdjustments;
+    /** Scene file WE opens (the base wallpaper's for a preset), keys script localStorage */
+    std::filesystem::path sceneFile;
     /** scene.json "version", 0 when missing */
     int sceneVersion = 0;
 };

+ 2 - 0
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -804,6 +804,8 @@ std::shared_ptr<const CFBO> CWallpaper::findFBO (const std::string& name) const
 
 std::shared_ptr<const CFBO> CWallpaper::getFBO () const { return this->m_sceneFBO; }
 
+const std::filesystem::path& CWallpaper::getSceneFile () const { return this->m_wallpaperData.project.sceneFile; }
+
 std::unique_ptr<CWallpaper> CWallpaper::fromWallpaper (
     const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext,
     const std::filesystem::path& resolvedBackgroundPath, const WallpaperState::TextureUVsScaling& scalingMode,

+ 5 - 0
src/WallpaperEngine/Render/CWallpaper.h

@@ -141,6 +141,10 @@ public:
     [[nodiscard]] int getFramebufferHeight () const;
     /** Size of the output the wallpaper was last rendered to, zero until the first frame */
     [[nodiscard]] const glm::ivec2& getScreenSize () const { return this->m_screenSize; }
+    /** Screen key for script localStorage's screen store, empty in a window */
+    void setStorageScreen (std::string screen) { this->m_storageScreen = std::move (screen); }
+    [[nodiscard]] const std::string& getStorageScreen () const { return this->m_storageScreen; }
+    [[nodiscard]] const std::filesystem::path& getSceneFile () const;
     /** This frame's --ssaa factor per axis */
     [[nodiscard]] int getSupersampling () const { return this->m_supersampling; }
 
@@ -252,5 +256,6 @@ private:
     // Avoids redundant renderFrame calls when the same wallpaper is shared across viewports (span mode)
     uint32_t m_lastRenderedFrame = UINT32_MAX;
     glm::ivec2 m_screenSize = { 0, 0 };
+    std::string m_storageScreen;
 };
 } // namespace WallpaperEngine::Render

+ 407 - 0
src/WallpaperEngine/Scripting/LocalStorage.cpp

@@ -0,0 +1,407 @@
+#include "LocalStorage.h"
+
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <fstream>
+#include <mutex>
+#include <sys/file.h>
+#include <unistd.h>
+
+using namespace WallpaperEngine::Scripting;
+
+namespace {
+constexpr char FILE_MAGIC[] = "LSBK0001";
+constexpr size_t KEY_LENGTH = 40;
+
+std::mutex g_registryMutex;
+std::map<std::string, std::weak_ptr<LocalStorage::Store>> g_registry;
+std::optional<std::filesystem::path> g_directoryOverride;
+
+uint32_t rotl (const uint32_t value, const int bits) { return (value << bits) | (value >> (32 - bits)); }
+
+void sha1Block (std::array<uint32_t, 5>& state, const uint8_t* block) {
+    uint32_t w[80];
+
+    for (int i = 0; i < 16; i++) {
+	w[i] = (uint32_t (block[i * 4]) << 24) | (uint32_t (block[i * 4 + 1]) << 16)
+	    | (uint32_t (block[i * 4 + 2]) << 8) | uint32_t (block[i * 4 + 3]);
+    }
+
+    for (int i = 16; i < 80; i++) {
+	w[i] = rotl (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
+    }
+
+    uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
+
+    for (int i = 0; i < 80; i++) {
+	uint32_t f, k;
+
+	if (i < 20) {
+	    f = (b & c) | (~b & d);
+	    k = 0x5A827999;
+	} else if (i < 40) {
+	    f = b ^ c ^ d;
+	    k = 0x6ED9EBA1;
+	} else if (i < 60) {
+	    f = (b & c) | (b & d) | (c & d);
+	    k = 0x8F1BBCDC;
+	} else {
+	    f = b ^ c ^ d;
+	    k = 0xCA62C1D6;
+	}
+
+	const uint32_t temp = rotl (a, 5) + f + e + k + w[i];
+	e = d;
+	d = c;
+	c = rotl (b, 30);
+	b = a;
+	a = temp;
+    }
+
+    state[0] += a;
+    state[1] += b;
+    state[2] += c;
+    state[3] += d;
+    state[4] += e;
+}
+
+void appendU32 (std::string& out, const uint32_t value) {
+    for (int i = 0; i < 4; i++) {
+	out.push_back (static_cast<char> ((value >> (8 * i)) & 0xFF));
+    }
+}
+
+bool readU32 (std::istream& in, uint32_t& value) {
+    uint8_t bytes[4];
+
+    if (!in.read (reinterpret_cast<char*> (bytes), 4)) {
+	return false;
+    }
+
+    value = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (uint32_t (bytes[3]) << 24);
+    return true;
+}
+
+size_t storedBytes (const std::vector<std::pair<std::string, std::string>>& entries, const std::string& except) {
+    size_t total = 0;
+
+    for (const auto& [key, value] : entries) {
+	if (key != except) {
+	    total += value.size ();
+	}
+    }
+
+    return total;
+}
+
+/** Locks the directory since store files are replaced by rename */
+class DirectoryLock {
+public:
+    explicit DirectoryLock (const std::filesystem::path& directory) {
+	this->m_fd = ::open ((directory / ".lock").c_str (), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
+
+	if (this->m_fd >= 0) {
+	    flock (this->m_fd, LOCK_EX);
+	}
+    }
+
+    ~DirectoryLock () {
+	if (this->m_fd >= 0) {
+	    flock (this->m_fd, LOCK_UN);
+	    close (this->m_fd);
+	}
+    }
+
+    DirectoryLock (const DirectoryLock&) = delete;
+    DirectoryLock& operator= (const DirectoryLock&) = delete;
+
+private:
+    int m_fd = -1;
+};
+} // namespace
+
+std::string LocalStorage::sha1Hex (const std::string_view data) {
+    std::array<uint32_t, 5> state = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
+    const auto* bytes = reinterpret_cast<const uint8_t*> (data.data ());
+    size_t offset = 0;
+
+    for (; offset + 64 <= data.size (); offset += 64) {
+	sha1Block (state, bytes + offset);
+    }
+
+    uint8_t tail[128] = {};
+    const size_t remaining = data.size () - offset;
+    memcpy (tail, bytes + offset, remaining);
+    tail[remaining] = 0x80;
+
+    const size_t tailLength = remaining + 9 > 64 ? 128 : 64;
+    const uint64_t bits = static_cast<uint64_t> (data.size ()) * 8;
+
+    for (int i = 0; i < 8; i++) {
+	tail[tailLength - 1 - i] = static_cast<uint8_t> (bits >> (8 * i));
+    }
+
+    sha1Block (state, tail);
+
+    if (tailLength == 128) {
+	sha1Block (state, tail + 64);
+    }
+
+    static constexpr char digits[] = "0123456789abcdef";
+    std::string hex;
+    hex.reserve (KEY_LENGTH);
+
+    for (const uint32_t word : state) {
+	for (int shift = 28; shift >= 0; shift -= 4) {
+	    hex.push_back (digits[(word >> shift) & 0xF]);
+	}
+    }
+
+    return hex;
+}
+
+std::filesystem::path LocalStorage::directory () {
+    if (g_directoryOverride.has_value ()) {
+	return *g_directoryOverride;
+    }
+
+    if (const char* state = std::getenv ("XDG_STATE_HOME"); state != nullptr && state[0] == '/') {
+	return std::filesystem::path (state) / "linux-wallpaperengine" / "scenestorage";
+    }
+
+    if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] != '\0') {
+	return std::filesystem::path (home) / ".local" / "state" / "linux-wallpaperengine" / "scenestorage";
+    }
+
+    return {};
+}
+
+void LocalStorage::setDirectory (std::filesystem::path directory) { g_directoryOverride = std::move (directory); }
+
+std::vector<std::pair<std::string, std::string>> LocalStorage::readFile (const std::filesystem::path& file) {
+    std::vector<std::pair<std::string, std::string>> entries;
+    std::ifstream in (file, std::ios::binary);
+    std::error_code error;
+
+    // sub_140185960: header and count only = empty
+    if (!in || std::filesystem::file_size (file, error) <= 12 || error) {
+	return entries;
+    }
+
+    char magic[8];
+    uint32_t count = 0;
+
+    if (!in.read (magic, 8) || memcmp (magic, FILE_MAGIC, 8) != 0 || !readU32 (in, count)) {
+	return entries;
+    }
+
+    for (uint32_t i = 0; i < count; i++) {
+	char key[KEY_LENGTH + 1] = {};
+	uint32_t size = 0;
+
+	if (!in.read (key, KEY_LENGTH) || !readU32 (in, size) || size > MAX_STORE_BYTES) {
+	    break;
+	}
+
+	std::string value (size, '\0');
+
+	if (!in.read (value.data (), size)) {
+	    break;
+	}
+
+	std::string name (key);
+	const auto existing
+	    = std::ranges::find_if (entries, [&name] (const auto& entry) { return entry.first == name; });
+
+	if (existing != entries.end ()) {
+	    existing->second = std::move (value);
+	} else {
+	    entries.emplace_back (std::move (name), std::move (value));
+	}
+    }
+
+    return entries;
+}
+
+bool LocalStorage::writeFile (
+    const std::filesystem::path& file, const std::vector<std::pair<std::string, std::string>>& entries
+) {
+    std::string data (FILE_MAGIC, 8);
+    appendU32 (data, static_cast<uint32_t> (entries.size ()));
+
+    // sub_1401E2BC0
+    for (const auto& [key, value] : entries) {
+	std::string paddedKey = key.substr (0, KEY_LENGTH);
+	paddedKey.resize (KEY_LENGTH, '\0');
+	data += paddedKey;
+	appendU32 (data, static_cast<uint32_t> (value.size ()));
+	data += value;
+    }
+
+    const auto temporary = file.string () + ".tmp" + std::to_string (getpid ());
+
+    {
+	std::ofstream out (temporary, std::ios::binary | std::ios::trunc);
+
+	if (!out.write (data.data (), static_cast<std::streamsize> (data.size ())) || !out.flush ()) {
+	    std::error_code ignored;
+	    std::filesystem::remove (temporary, ignored);
+	    return false;
+	}
+    }
+
+    std::error_code error;
+    std::filesystem::rename (temporary, file, error);
+
+    if (error) {
+	std::filesystem::remove (temporary, error);
+	return false;
+    }
+
+    return true;
+}
+
+LocalStorage::Store::Store (std::string name) : m_name (std::move (name)) {
+    if (const auto dir = directory (); !dir.empty ()) {
+	this->m_entries = readFile (dir / (this->m_name + ".bin"));
+    }
+}
+
+LocalStorage::Store::~Store () { this->flush (); }
+
+std::vector<std::pair<std::string, std::string>>::iterator LocalStorage::Store::find (const std::string& key) {
+    return std::ranges::find_if (this->m_entries, [&key] (const auto& entry) { return entry.first == key; });
+}
+
+std::optional<std::string> LocalStorage::Store::get (const std::string& key) const {
+    const auto entry = std::ranges::find_if (this->m_entries, [&key] (const auto& e) { return e.first == key; });
+
+    if (entry == this->m_entries.end ()) {
+	return std::nullopt;
+    }
+
+    return entry->second;
+}
+
+bool LocalStorage::Store::set (const std::string& key, std::string value) {
+    // sub_14018E3A0
+    if (storedBytes (this->m_entries, key) + value.size () > MAX_STORE_BYTES) {
+	return false;
+    }
+
+    this->m_changes[key] = value;
+
+    if (const auto entry = this->find (key); entry != this->m_entries.end ()) {
+	entry->second = std::move (value);
+    } else {
+	this->m_entries.emplace_back (key, std::move (value));
+    }
+
+    return true;
+}
+
+bool LocalStorage::Store::remove (const std::string& key) {
+    const auto entry = this->find (key);
+
+    if (entry == this->m_entries.end ()) {
+	return false;
+    }
+
+    this->m_entries.erase (entry);
+    this->m_changes[key] = std::nullopt;
+    return true;
+}
+
+void LocalStorage::Store::clear () {
+    this->m_entries.clear ();
+    this->m_changes.clear ();
+    this->m_cleared = true;
+}
+
+void LocalStorage::Store::flush () {
+    if (!this->m_cleared && this->m_changes.empty ()) {
+	return;
+    }
+
+    const auto dir = directory ();
+
+    if (dir.empty ()) {
+	return;
+    }
+
+    std::error_code error;
+    std::filesystem::create_directories (dir, error);
+
+    if (error) {
+	sLog.error ("localStorage: cannot create ", dir.string (), ": ", error.message ());
+	return;
+    }
+
+    const DirectoryLock lock (dir);
+    const auto file = dir / (this->m_name + ".bin");
+    auto entries = this->m_cleared ? std::vector<std::pair<std::string, std::string>> {} : readFile (file);
+
+    for (const auto& [key, value] : this->m_changes) {
+	const auto entry = std::ranges::find_if (entries, [&key] (const auto& e) { return e.first == key; });
+
+	if (!value.has_value ()) {
+	    if (entry != entries.end ()) {
+		entries.erase (entry);
+	    }
+	} else if (entry != entries.end ()) {
+	    entry->second = *value;
+	} else {
+	    entries.emplace_back (key, *value);
+	}
+    }
+
+    if (!writeFile (file, entries)) {
+	sLog.error ("localStorage: cannot write ", file.string ());
+	return;
+    }
+
+    this->m_entries = std::move (entries);
+    this->m_changes.clear ();
+    this->m_cleared = false;
+}
+
+std::shared_ptr<LocalStorage::Store> LocalStorage::open (const std::string& name) {
+    const std::lock_guard lock (g_registryMutex);
+
+    if (const auto existing = g_registry.find (name); existing != g_registry.end ()) {
+	if (auto store = existing->second.lock ()) {
+	    return store;
+	}
+    }
+
+    auto store = std::make_shared<Store> (name);
+    g_registry[name] = store;
+    return store;
+}
+
+void LocalStorage::flushAll () {
+    std::vector<std::shared_ptr<Store>> stores;
+
+    {
+	const std::lock_guard lock (g_registryMutex);
+
+	for (auto it = g_registry.begin (); it != g_registry.end ();) {
+	    if (auto store = it->second.lock ()) {
+		stores.push_back (std::move (store));
+		++it;
+	    } else {
+		it = g_registry.erase (it);
+	    }
+	}
+    }
+
+    for (const auto& store : stores) {
+	store->flush ();
+    }
+}

+ 70 - 0
src/WallpaperEngine/Scripting/LocalStorage.h

@@ -0,0 +1,70 @@
+#pragma once
+
+#include <filesystem>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+namespace WallpaperEngine::Scripting {
+/**
+ * Script localStorage files in wallpaper64.exe 2.8.42's format: "LSBK0001", u32 count, then per entry sha1 hex key
+ * (40 bytes), u32 size, value ("LSKV0001" + JSON). Global store = sha1hex(path), screen store = sha1hex(path + screen).
+ * Written when the last user lets go (sub_140186340) or at exit.
+ */
+class LocalStorage {
+public:
+    /** WE's limit on the sum of a store's values, checked on set */
+    static constexpr size_t MAX_STORE_BYTES = 100000;
+
+    class Store {
+    public:
+	explicit Store (std::string name);
+	~Store ();
+
+	Store (const Store&) = delete;
+	Store& operator= (const Store&) = delete;
+
+	[[nodiscard]] std::optional<std::string> get (const std::string& key) const;
+	/** False past MAX_STORE_BYTES */
+	bool set (const std::string& key, std::string value);
+	bool remove (const std::string& key);
+	void clear ();
+	/** Merges this process's changes into the file under a lock, other engine processes may share it */
+	void flush ();
+
+	[[nodiscard]] const std::string& getName () const { return this->m_name; }
+	[[nodiscard]] const std::vector<std::pair<std::string, std::string>>& getEntries () const {
+	    return this->m_entries;
+	}
+
+    private:
+	std::vector<std::pair<std::string, std::string>>::iterator find (const std::string& key);
+
+	std::string m_name;
+	std::vector<std::pair<std::string, std::string>> m_entries;
+	/** key -> new value, nullopt for removed */
+	std::map<std::string, std::optional<std::string>> m_changes;
+	bool m_cleared = false;
+    };
+
+    /** Process wide store with this name, loaded on first open */
+    static std::shared_ptr<Store> open (const std::string& name);
+    /** For exit paths that may not destroy the scenes */
+    static void flushAll ();
+
+    /** Lower case hex, like WE's sub_1400811D0 */
+    static std::string sha1Hex (std::string_view data);
+
+    /** $XDG_STATE_HOME/linux-wallpaperengine/scenestorage, empty without a home */
+    static std::filesystem::path directory ();
+    static void setDirectory (std::filesystem::path directory);
+
+    static std::vector<std::pair<std::string, std::string>> readFile (const std::filesystem::path& file);
+    static bool
+    writeFile (const std::filesystem::path& file, const std::vector<std::pair<std::string, std::string>>& entries);
+};
+} // namespace WallpaperEngine::Scripting

+ 160 - 0
src/WallpaperEngine/Scripting/LocalStorageObject.cpp

@@ -0,0 +1,160 @@
+#include "LocalStorageObject.h"
+
+#include "JS.h"
+#include "ScriptEngine.h"
+#include "WallpaperEngine/Render/Wallpapers/CScene.h"
+
+#include <strings.h>
+
+using namespace WallpaperEngine::Scripting;
+
+namespace {
+constexpr char VALUE_MAGIC[] = "LSKV0001";
+
+LocalStorageObject& storageOf (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    return ScriptEngine::from (info.GetIsolate ()).getLocalStorageObject ();
+}
+
+// WE throws at module top level, messages copied as is
+bool rejectGlobalScope (const v8::FunctionCallbackInfo<v8::Value>& info, const char* message) {
+    if (!ScriptEngine::from (info.GetIsolate ()).isEvaluatingModuleBody ()) {
+	return false;
+    }
+
+    JS::throwSyntaxError (info.GetIsolate (), message);
+    return true;
+}
+
+bool rejectKey (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    if (info.Length () > 0 && info[0]->IsString ()) {
+	return false;
+    }
+
+    JS::throwSyntaxError (info.GetIsolate (), "LocalStorageSet key not a string.");
+    return true;
+}
+
+// only a string matching "global" (_stricmp), anything else is the screen store
+bool isGlobal (const v8::FunctionCallbackInfo<v8::Value>& info, int index) {
+    if (info.Length () <= index || !info[index]->IsString ()) {
+	return false;
+    }
+
+    return strcasecmp (JS::toString (info.GetIsolate (), info[index]).c_str (), "global") == 0;
+}
+
+std::string storageKey (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    return LocalStorage::sha1Hex (JS::toString (info.GetIsolate (), info[0]));
+}
+
+void localstorage_delete (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    if (rejectGlobalScope (info, "LocalStorageDelete cannot be cleared from global scope.") || rejectKey (info)) {
+	return;
+    }
+
+    const bool removed = storageOf (info).getStore (isGlobal (info, 1)).remove (storageKey (info));
+    info.GetReturnValue ().Set (removed);
+}
+
+void localstorage_set (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    if (rejectGlobalScope (info, "LocalStorageSet cannot be cleared from global scope.") || rejectKey (info)) {
+	return;
+    }
+
+    const auto isolate = info.GetIsolate ();
+    const v8::Local<v8::Value> value = info.Length () > 1 ? info[1] : v8::Undefined (isolate).As<v8::Value> ();
+
+    // WE passes the same args to delete, whose location is then the undefined value: always the screen store
+    if (value->IsUndefined ()) {
+	localstorage_delete (info);
+	return;
+    }
+
+    const bool global = isGlobal (info, 2);
+    std::string json;
+
+    {
+	const v8::TryCatch tryCatch (isolate);
+	v8::Local<v8::String> text;
+
+	if (v8::JSON::Stringify (isolate->GetCurrentContext (), value).ToLocal (&text)) {
+	    json = JS::toString (isolate, text);
+	}
+    }
+
+    if (!storageOf (info).getStore (global).set (storageKey (info), VALUE_MAGIC + json)) {
+	JS::throwSyntaxError (isolate, "LocalStorageSet failed, possibly out of memory.");
+    }
+}
+
+void localstorage_get (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    if (rejectGlobalScope (info, "LocalStorageGet cannot be cleared from global scope.") || rejectKey (info)) {
+	return;
+    }
+
+    const auto isolate = info.GetIsolate ();
+    const auto data = storageOf (info).getStore (isGlobal (info, 1)).get (storageKey (info));
+
+    if (!data.has_value () || data->size () < 8 || data->compare (0, 8, VALUE_MAGIC) != 0) {
+	return;
+    }
+
+    // stops at the first NUL like WE, unparsable values give null
+    const v8::TryCatch tryCatch (isolate);
+    v8::Local<v8::Value> parsed;
+
+    if (v8::JSON::Parse (isolate->GetCurrentContext (), JS::string (isolate, data->c_str () + 8)).ToLocal (&parsed)) {
+	info.GetReturnValue ().Set (parsed);
+    } else {
+	info.GetReturnValue ().SetNull ();
+    }
+}
+
+void localstorage_clear (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    if (rejectGlobalScope (info, "LocalStorageClear cannot be cleared from global scope.")) {
+	return;
+    }
+
+    storageOf (info).getStore (isGlobal (info, 0)).clear ();
+    info.GetReturnValue ().Set (true);
+}
+} // namespace
+
+LocalStorageObject::LocalStorageObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene) :
+    m_scene (scene), m_engine (engine) {
+    const auto isolate = engine.getIsolate ();
+    const auto context = engine.getContext ();
+    const v8::Local<v8::Object> instance = v8::Object::New (isolate);
+    const auto constant = static_cast<v8::PropertyAttribute> (v8::ReadOnly | v8::DontEnum | v8::DontDelete);
+
+    JS::set (context, instance, "set", JS::function (context, localstorage_set));
+    JS::set (context, instance, "get", JS::function (context, localstorage_get));
+    JS::set (context, instance, "delete", JS::function (context, localstorage_delete));
+    JS::set (context, instance, "clear", JS::function (context, localstorage_clear));
+    instance
+	->DefineOwnProperty (context, JS::name (isolate, "LOCATION_GLOBAL"), JS::string (isolate, "global"), constant)
+	.Check ();
+    instance
+	->DefineOwnProperty (context, JS::name (isolate, "LOCATION_SCREEN"), JS::string (isolate, "screen"), constant)
+	.Check ();
+
+    this->m_instance.Reset (isolate, instance);
+}
+
+v8::Local<v8::Object> LocalStorageObject::getInstance () const {
+    return this->m_instance.Get (this->m_engine.getIsolate ());
+}
+
+LocalStorage::Store& LocalStorageObject::getStore (const bool global) {
+    auto& store = global ? this->m_globalStore : this->m_screenStore;
+
+    if (!store) {
+	// sub_140113C80: sha1 of the scene path, plus the screen string for the screen store
+	const std::string identity = this->m_scene.getSceneFile ().generic_string ();
+	store = LocalStorage::open (
+	    LocalStorage::sha1Hex (global ? identity : identity + this->m_scene.getStorageScreen ())
+	);
+    }
+
+    return *store;
+}

+ 36 - 0
src/WallpaperEngine/Scripting/LocalStorageObject.h

@@ -0,0 +1,36 @@
+#pragma once
+
+#include "LocalStorage.h"
+
+#include <v8-local-handle.h>
+#include <v8-persistent-handle.h>
+
+#include <memory>
+
+namespace v8 {
+class Object;
+}
+
+namespace WallpaperEngine::Render::Wallpapers {
+class CScene;
+}
+namespace WallpaperEngine::Scripting {
+class ScriptEngine;
+/** scenescript64 2.8.42 localStorage (sub_181647AA0, sub_181658680..sub_181659150) */
+class LocalStorageObject {
+public:
+    LocalStorageObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene);
+
+    v8::Local<v8::Object> getInstance () const;
+    /** Lazy, the scene learns its screen after the engine exists */
+    LocalStorage::Store& getStore (bool global);
+
+protected:
+    Render::Wallpapers::CScene& m_scene;
+    ScriptEngine& m_engine;
+    std::shared_ptr<LocalStorage::Store> m_screenStore;
+    std::shared_ptr<LocalStorage::Store> m_globalStore;
+
+    v8::Global<v8::Object> m_instance;
+};
+} // namespace WallpaperEngine::Scripting

+ 3 - 0
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -404,6 +404,7 @@ ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& media
     this->m_inputObject = std::make_unique<InputObject> (*this, scene);
     this->m_sceneObject = std::make_unique<SceneObject> (*this, scene);
     this->m_consoleObject = std::make_unique<ConsoleObject> (*this, scene);
+    this->m_localStorageObject = std::make_unique<LocalStorageObject> (*this, scene);
     this->m_scriptPropertiesObject = std::make_unique<ScriptPropertiesObject> (*this, scene);
 
     this->installBuiltins ();
@@ -414,6 +415,7 @@ ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& media
     JS::define (context, global, "input", this->m_inputObject->getInstance ());
     JS::define (context, global, "thisScene", this->m_sceneObject->getInstance ());
     JS::define (context, global, "console", this->m_consoleObject->getInstance ());
+    JS::define (context, global, "localStorage", this->m_localStorageObject->getInstance ());
     JS::define (context, global, "shared", v8::Object::New (this->m_isolate));
 }
 
@@ -428,6 +430,7 @@ ScriptEngine::~ScriptEngine () {
     this->m_imports.clear ();
 
     this->m_consoleObject.reset ();
+    this->m_localStorageObject.reset ();
     this->m_engineObject.reset ();
     this->m_inputObject.reset ();
     this->m_sceneObject.reset ();

+ 3 - 0
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -5,6 +5,7 @@
 #include "ConsoleObject.h"
 #include "EngineObject.h"
 #include "InputObject.h"
+#include "LocalStorageObject.h"
 #include "SceneObject.h"
 
 #include <chrono>
@@ -244,6 +245,7 @@ public:
     EngineObject& getEngineObject () const { return *m_engineObject; }
     ScriptPropertiesObject& getScriptPropertiesObject () const { return *m_scriptPropertiesObject; }
     SceneObject& getSceneObject () const { return *m_sceneObject; }
+    LocalStorageObject& getLocalStorageObject () const { return *m_localStorageObject; }
     /** Whether a script module is currently running for this property value */
     [[nodiscard]] bool hasScript (const DynamicValue& value) const;
     const JSObjectAdapters& getAdapters () const { return m_adapters; }
@@ -305,6 +307,7 @@ private:
     std::unique_ptr<InputObject> m_inputObject;
     std::unique_ptr<SceneObject> m_sceneObject;
     std::unique_ptr<ConsoleObject> m_consoleObject;
+    std::unique_ptr<LocalStorageObject> m_localStorageObject;
     std::unique_ptr<ScriptPropertiesObject> m_scriptPropertiesObject;
 
     std::map<std::string, LoadedModule> m_scriptModules = {};

+ 0 - 31
src/WallpaperEngine/Scripting/resources/builtins.js

@@ -1,32 +1 @@
 globalThis.__intervals = Object.create(null);
-// same shape as scenescript64.dll's: values go through JSON like WE's on-disk store, a location
-// other than "global" (or none) means the per-screen store, and setting undefined deletes the key
-globalThis.localStorage = globalThis.localStorage || {
-  LOCATION_GLOBAL: 'global',
-  LOCATION_SCREEN: 'screen',
-  __stores: { global: Object.create(null), screen: Object.create(null) },
-  __store(location) {
-    return String(location).toLowerCase() === 'global' ? this.__stores.global : this.__stores.screen;
-  },
-  get(key, location) {
-    const store = this.__store(location);
-    key = String(key);
-    return Object.prototype.hasOwnProperty.call(store, key) ? JSON.parse(store[key]) : undefined;
-  },
-  set(key, value, location) {
-    const serialized = value === undefined ? undefined : JSON.stringify(value);
-    if (serialized === undefined) {
-      this.delete(key, location);
-      return;
-    }
-    this.__store(location)[String(key)] = serialized;
-  },
-  delete(key, location) { delete this.__store(location)[String(key)]; },
-  clear(location) {
-    if (String(location).toLowerCase() === 'global') {
-      this.__stores.global = Object.create(null);
-    } else {
-      this.__stores.screen = Object.create(null);
-    }
-  }
-};

+ 113 - 0
src/WallpaperEngine/Testing/Cases/LocalStorage.cpp

@@ -0,0 +1,113 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <unistd.h>
+
+#include "WallpaperEngine/Scripting/LocalStorage.h"
+
+using WallpaperEngine::Scripting::LocalStorage;
+
+namespace {
+std::filesystem::path storageDir (const std::string& name) {
+    auto dir = std::filesystem::temp_directory_path () / ("lwe-storage-test-" + std::to_string (getpid ())) / name;
+    std::filesystem::remove_all (dir);
+    std::filesystem::create_directories (dir);
+    LocalStorage::setDirectory (dir);
+    return dir;
+}
+
+std::string readBytes (const std::filesystem::path& file) {
+    std::ifstream in (file, std::ios::binary);
+    return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char> () };
+}
+} // namespace
+
+TEST_CASE ("localStorage keys are lower case sha1 hex") {
+    CHECK (LocalStorage::sha1Hex ("") == "da39a3ee5e6b4b0d3255bfef95601890afd80709");
+    CHECK (LocalStorage::sha1Hex ("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d");
+    // 56 bytes, the padding spills into a second block
+    CHECK (
+	LocalStorage::sha1Hex ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
+	== "84983e441c3bd26ebaae4aa1f95129e5e54670f1"
+    );
+    CHECK (LocalStorage::sha1Hex (std::string (1000, 'a')) == "291e9a6c66994949b57ba5e650361e98fc36b1ba");
+}
+
+TEST_CASE ("localStorage files use WE's LSBK0001 layout") {
+    const auto dir = storageDir ("layout");
+    const std::string key = LocalStorage::sha1Hex ("origin");
+
+    {
+	LocalStorage::Store store ("layout");
+	REQUIRE (store.set (key, "LSKV0001{\"x\":1}"));
+    }
+
+    const std::string bytes = readBytes (dir / "layout.bin");
+    REQUIRE (bytes.size () == 8 + 4 + 40 + 4 + 15);
+    CHECK (bytes.substr (0, 8) == "LSBK0001");
+    CHECK (bytes.substr (8, 4) == std::string ("\x01\0\0\0", 4));
+    CHECK (bytes.substr (12, 40) == key);
+    CHECK (bytes.substr (52, 4) == std::string ("\x0f\0\0\0", 4));
+    CHECK (bytes.substr (56) == "LSKV0001{\"x\":1}");
+
+    const LocalStorage::Store reopened ("layout");
+    CHECK (reopened.get (key) == "LSKV0001{\"x\":1}");
+}
+
+TEST_CASE ("localStorage stores hold at most 100000 bytes") {
+    storageDir ("cap");
+    LocalStorage::Store store ("cap");
+
+    CHECK (store.set ("a", std::string (60000, 'x')));
+    CHECK_FALSE (store.set ("b", std::string (50000, 'x')));
+    // replacing a key doesn't count its old value
+    CHECK (store.set ("a", std::string (100000, 'x')));
+    CHECK_FALSE (store.set ("a", std::string (100001, 'x')));
+    CHECK (store.get ("a")->size () == 100000);
+}
+
+TEST_CASE ("localStorage flushes merge what other engines wrote") {
+    const auto dir = storageDir ("merge");
+    LocalStorage::Store first ("shared");
+    LocalStorage::Store second ("shared");
+
+    first.set ("one", "1");
+    second.set ("two", "2");
+    first.flush ();
+    second.flush ();
+
+    auto entries = LocalStorage::readFile (dir / "shared.bin");
+    REQUIRE (entries.size () == 2);
+
+    first.remove ("one");
+    first.flush ();
+    entries = LocalStorage::readFile (dir / "shared.bin");
+    REQUIRE (entries.size () == 1);
+    CHECK (entries[0].first == "two");
+
+    // nothing changed, nothing written
+    std::filesystem::remove (dir / "shared.bin");
+    first.flush ();
+    CHECK_FALSE (std::filesystem::exists (dir / "shared.bin"));
+}
+
+TEST_CASE ("localStorage clear empties the file") {
+    const auto dir = storageDir ("clear");
+
+    {
+	LocalStorage::Store store ("clear");
+	store.set ("one", "1");
+    }
+
+    {
+	LocalStorage::Store store ("clear");
+	REQUIRE (store.get ("one").has_value ());
+	store.clear ();
+	CHECK_FALSE (store.remove ("one"));
+    }
+
+    CHECK (LocalStorage::readFile (dir / "clear.bin").empty ());
+    CHECK (LocalStorage::open ("clear") == LocalStorage::open ("clear"));
+}

+ 29 - 1
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -2,6 +2,8 @@
 
 #include "WallpaperEngine/Logging/Log.h"
 
+#include <algorithm>
+#include <cctype>
 #include <chrono>
 #include <cstdlib>
 #include <mpv/render_gl.h>
@@ -14,6 +16,7 @@ using namespace WallpaperEngine::VideoPlayback;
 using namespace WallpaperEngine::VideoPlayback::MPV;
 
 std::unordered_map<std::filesystem::path, GLPlayer*> GLPlayer::s_activePlayers;
+std::unordered_set<GLPlayer*> GLPlayer::s_players;
 double GLPlayer::s_statsMillis = 0.0;
 
 // the synchronous mpv_set_property/mpv_command wait for mpv's core thread, which can take a few hundred ms
@@ -35,6 +38,7 @@ GLPlayer::GLPlayer (
 
     this->prepareGL ();
     this->setSource (file);
+    s_players.insert (this);
 }
 
 GLPlayer::GLPlayer (
@@ -46,9 +50,11 @@ GLPlayer::GLPlayer (
 
     this->prepareGL ();
     this->setSource (std::move (stream));
+    s_players.insert (this);
 }
 
 GLPlayer::~GLPlayer () {
+    s_players.erase (this);
     this->stop ();
 
     if (this->m_doWeOwnFramebuffer) {
@@ -134,6 +140,24 @@ void GLPlayer::setSpeed (double speed) {
     }
 }
 
+bool GLPlayer::isValidHwdec (const std::string& value) {
+    if (value.empty () || value.front () == ',' || value.back () == ',') {
+	return false;
+    }
+
+    return std::all_of (value.begin (), value.end (), [] (const char c) {
+	return std::isalnum (static_cast<unsigned char> (c)) || c == '-' || c == '_' || c == ',';
+    });
+}
+
+void GLPlayer::setHwdecForAll (const std::string& value) {
+    for (GLPlayer* player : s_players) {
+	if (player->m_handle) {
+	    setPropertyAsync (player->m_handle, "hwdec", value.c_str ());
+	}
+    }
+}
+
 void GLPlayer::setPaused () {
     this->m_paused = true;
 
@@ -505,7 +529,11 @@ void GLPlayer::init () {
     // it every frame stalled the render thread ~160-200ms every few seconds on a paused video
     mpv_observe_property (this->m_handle, 0, "eof-reached", MPV_FORMAT_FLAG);
 
-    mpv_set_property_string (this->m_handle, "hwdec", "auto");
+    const auto& hwdec = this->getContext ().getApp ().getContext ().settings.render.hwdec;
+
+    if (mpv_set_property_string (this->m_handle, "hwdec", hwdec.c_str ()) < 0) {
+	sLog.error ("mpv rejected hwdec value ", hwdec, ", decoding in software");
+    }
     mpv_set_property_string (this->m_handle, "loop", this->m_loop ? "inf" : "no");
     mpv_set_property_string (this->m_handle, "keep-open", "yes");
     const auto [loopA, loopB] = abLoopPoints (this->m_segments);

+ 6 - 0
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h

@@ -10,6 +10,7 @@
 #include <optional>
 #include <string>
 #include <unordered_map>
+#include <unordered_set>
 
 namespace WallpaperEngine::VideoPlayback::MPV {
 class GLPlayer : public Helpers::ContextAware {
@@ -71,6 +72,10 @@ public:
     /** Current playback position in seconds, or 0 if playback hasn't started yet */
     double getPlaybackPosition () const;
 
+    /** Comma separated backend names only, so no other mpv option gets injected */
+    static bool isValidHwdec (const std::string& value);
+    static void setHwdecForAll (const std::string& value);
+
     /** Time spent in render () since the last reset, only collected while LWE_FRAME_STATS is set */
     static double s_statsMillis;
 
@@ -122,6 +127,7 @@ protected:
     // the same video another monitor is already showing can pick up around the same spot
     // instead of always restarting from zero
     static std::unordered_map<std::filesystem::path, GLPlayer*> s_activePlayers;
+    static std::unordered_set<GLPlayer*> s_players;
 };
 
 using GLPlayerUniquePtr = std::unique_ptr<GLPlayer>;

+ 6 - 0
tools/wecompare/README.md

@@ -35,6 +35,12 @@ Data locations (all overridable):
 
 - `we_display.sh` - starts the isolated display :98 (headless weston + Xwayland in a private runtime dir).
 - `we_full.sh <scene> <outdir> [count] [interval]` - single cold run with full-screen grabs.
+  `WE_DESKTOP=1` runs WE in desktop mode (wallpaper of monitor 0, fullscreen, no window frame) instead of
+  `-playInWindow`: Wine has no Progman/WorkerW shell windows, `wedesktop.c` (built on first use with
+  `x86_64-w64-mingw32-gcc`, or `python3 -m ziglang cc` when that is missing) provides the Windows 10 layout WE looks
+  for. `WE_UNLOAD=1` opens another wallpaper (`WE_UNLOAD_SCENE`) before stopping, so WE unloads the scene and writes
+  its script localStorage to `bin/scenestorage`; give it a `WE_LIVE_DIR` whose `we28/bin` is a real folder of links,
+  not a link into the Steam install.
 - `we_cursor.sh <scene> <outdir> "x,y x,y" [settle]` - warps the pointer before each grab (parallax, cursor).
 - `we_capture.sh <scene> [secs]` - RenderDoc capture of one WE frame (inspect with `tools/rdc_dump.py` on :98,
   `rdscripts/` has the replay scripts).

+ 24 - 1
tools/wecompare/wine/we_full.sh

@@ -2,7 +2,10 @@
 # usage: we_full.sh <scene dir or scene.json/scene.pkg> <out dir> [count] [interval seconds]
 # runs on the GPU display :98 (DXVK); WE_DISPLAY=:97 WE_WINED3D=1 is the old Xvfb + wined3d (llvmpipe) path
 # full window captures (1920x1058 at +4+30 on :97) of real WE 2.8.42 under Wine, see README.md
+# WE_DESKTOP=1: desktop mode on monitor 0 via the wedesktop.c shell windows instead of -playInWindow
+# WE_UNLOAD=1: open another wallpaper before stopping so WE writes bin/scenestorage (needs a real we28/bin, not a link)
 ulimit -c 0
+HERE=$(cd "$(dirname "$0")" && pwd)
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=${WE_DISPLAY:-:98}
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }
@@ -31,7 +34,21 @@ if [ -n "$WE_AUDIO_REC" ]; then
     for i in $(seq 50); do pactl list short source-outputs 2>/dev/null | grep -q . && break; sleep 0.1; done
     sleep 0.5
 fi
-nohup $WINE wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
+MODE=-playInWindow
+if [ -n "$WE_DESKTOP" ]; then
+    MODE=
+    EXE=$S/wedesktop.exe
+    if [ ! -f "$EXE" ] || [ "$HERE/wedesktop.c" -nt "$EXE" ]; then
+        if command -v x86_64-w64-mingw32-gcc >/dev/null; then
+            x86_64-w64-mingw32-gcc -O2 -municode -mwindows -o "$EXE" "$HERE/wedesktop.c" -luser32 -lgdi32 || exit 1
+        else
+            python3 -m ziglang cc -target x86_64-windows-gnu -O2 -municode -o "$EXE" "$HERE/wedesktop.c" -luser32 -lgdi32 || exit 1
+        fi
+    fi
+    nohup $WINE "$EXE" > $S/wedesktop.log 2>&1 &
+    timeout 4 tail -f /dev/null
+fi
+nohup $WINE wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 $MODE -silent > $S/we_run_last.log 2>&1 &
 timeout 25 tail -f /dev/null
 mkdir -p "$2"
 python3 - "$2" "${3:-10}" "${4:-1}" "$D" <<'PY'
@@ -58,6 +75,12 @@ with mss.MSS(display=sys.argv[4]) as m:
         Image.frombytes('RGB',s.size,s.rgb).save('%s/f%03d_%.1f.png'%(sys.argv[1],i,time.time()-t0))
         time.sleep(float(sys.argv[3]))
 PY
+if [ -n "$WE_UNLOAD" ]; then
+    # any other scene, keyorder's probe loads fast
+    OTHER=$(echo "Z:${WE_UNLOAD_SCENE:-$HOME/.local/share/we_live/tests/keyorder/probe/scene.json}" | tr '/' '\\')
+    $WINE wallpaper64.exe -control openWallpaper -file "$OTHER" -monitor 0 $MODE >> $S/we_run_last.log 2>&1
+    timeout 10 tail -f /dev/null
+fi
 $WINESERVER -k 2>/dev/null
 if [ -n "$REC" ]; then
     pkill -INT -P $REC timeout

+ 78 - 0
tools/wecompare/wine/wedesktop.c

@@ -0,0 +1,78 @@
+/*
+ * Stand-in desktop shell windows so live WE under Wine runs in desktop mode. WE 2.8.42 (sub_14003C840/sub_14003C760)
+ * sends Progman 0x52C, then parents its window to the WorkerW below the one holding SHELLDLL_DefView.
+ * Run before wallpaper64.exe with the same wine prefix; we_full.sh builds it.
+ */
+#include <windows.h>
+
+static HWND g_progman, g_defView, g_iconHost, g_wallpaperHost;
+
+static LRESULT CALLBACK windowProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
+    if (msg == WM_ERASEBKGND) {
+	RECT rect;
+	GetClientRect (hwnd, &rect);
+	FillRect ((HDC) wParam, &rect, (HBRUSH) GetStockObject (BLACK_BRUSH));
+	return 1;
+    }
+
+    if (hwnd == g_progman && msg == 0x52C && g_wallpaperHost == NULL) {
+	const int x = GetSystemMetrics (SM_XVIRTUALSCREEN), y = GetSystemMetrics (SM_YVIRTUALSCREEN);
+	const int w = GetSystemMetrics (SM_CXVIRTUALSCREEN), h = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+	HINSTANCE instance = GetModuleHandleW (NULL);
+
+	g_iconHost = CreateWindowExW (
+	    WS_EX_TOOLWINDOW, L"WorkerW", L"", WS_POPUP | WS_CLIPCHILDREN, x, y, 1, 1, NULL, NULL, instance, NULL
+	);
+	SetParent (g_defView, g_iconHost);
+	g_wallpaperHost = CreateWindowExW (
+	    WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, L"WorkerW", L"", WS_POPUP | WS_CLIPCHILDREN | WS_VISIBLE, x, y, w, h,
+	    NULL, NULL, instance, NULL
+	);
+	SetWindowPos (g_wallpaperHost, g_iconHost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+	return 0;
+    }
+
+    if (msg == WM_DESTROY && hwnd == g_progman) {
+	PostQuitMessage (0);
+    }
+
+    return DefWindowProcW (hwnd, msg, wParam, lParam);
+}
+
+static void registerClass (const wchar_t* name) {
+    WNDCLASSW cls = { 0 };
+    cls.lpfnWndProc = windowProc;
+    cls.hInstance = GetModuleHandleW (NULL);
+    cls.lpszClassName = name;
+    cls.hCursor = LoadCursorW (NULL, (LPCWSTR) IDC_ARROW);
+    RegisterClassW (&cls);
+}
+
+int WINAPI wWinMain (HINSTANCE instance, HINSTANCE previous, PWSTR commandLine, int show) {
+    registerClass (L"Progman");
+    registerClass (L"WorkerW");
+    registerClass (L"SHELLDLL_DefView");
+    registerClass (L"SysListView32");
+
+    const int w = GetSystemMetrics (SM_CXVIRTUALSCREEN), h = GetSystemMetrics (SM_CYVIRTUALSCREEN);
+
+    g_progman = CreateWindowExW (
+	WS_EX_TOOLWINDOW, L"Progman", L"Program Manager", WS_POPUP | WS_CLIPCHILDREN, 0, 0, w, h, NULL, NULL, instance,
+	NULL
+    );
+    g_defView = CreateWindowExW (
+	0, L"SHELLDLL_DefView", L"", WS_CHILD | WS_VISIBLE, 0, 0, w, h, g_progman, NULL, instance, NULL
+    );
+    CreateWindowExW (
+	0, L"SysListView32", L"FolderView", WS_CHILD | WS_VISIBLE, 0, 0, w, h, g_defView, NULL, instance, NULL
+    );
+
+    MSG msg;
+
+    while (GetMessageW (&msg, NULL, 0, 0) > 0) {
+	TranslateMessage (&msg);
+	DispatchMessageW (&msg);
+    }
+
+    return 0;
+}