diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..5f5cb78 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: andormanu diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9d1a8af..66e1bba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,6 @@ name: release -# Tag a commit `vX.Y.Z` and this builds DragonwildsSync.exe on a clean +# Tag a commit `vX.Y.Z` and this builds WorldSync.exe on a clean # Windows runner and attaches it to the GitHub release, so the download # is reproducible from source and never depends on anyone's laptop. @@ -25,14 +25,14 @@ jobs: env: QT_QPA_PLATFORM: offscreen - run: python tools/generate_icon.py - - run: python -m PyInstaller --noconfirm DragonwildsSync.spec + - run: python -m PyInstaller --noconfirm WorldSync.spec - name: Print SHA-256 (compare against your download) - run: (Get-FileHash dist/DragonwildsSync.exe -Algorithm SHA256).Hash + run: (Get-FileHash dist/WorldSync.exe -Algorithm SHA256).Hash - name: Create the release if the tag is new, then attach the exe shell: bash run: | tag="${{ github.ref_name }}" - gh release view "$tag" >/dev/null 2>&1 || gh release create "$tag" --title "Dragonwilds Sync ${tag#v}" --generate-notes - gh release upload "$tag" dist/DragonwildsSync.exe --clobber + gh release view "$tag" >/dev/null 2>&1 || gh release create "$tag" --title "WorldSync ${tag#v}" --generate-notes + gh release upload "$tag" dist/WorldSync.exe --clobber env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e357443..0fa7c82 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,6 +18,9 @@ jobs: with: python-version: "3.12" cache: pip + - name: Qt system libraries (the UI smoke tests build real widgets) + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libegl1 libgl1 libxkbcommon0 libfontconfig1 libdbus-1-3 - run: pip install -r requirements.txt -r requirements-dev.txt - run: python -m pytest tests -q env: diff --git a/CHANGELOG.md b/CHANGELOG.md index c0c4aab..7aedffe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## 2.0.0 - 2026-10-05 + +**Dragonwilds Sync is now WorldSync.** + +- Ten games: RuneScape: Dragonwilds, Valheim, Enshrouded, Palworld, Core + Keeper, Sons of the Forest, V Rising, Grounded, Raft and 7 Days to Die. + Dragonwilds is tested; the others are marked beta until real groups have + played them for a while. +- A game library is the new home screen. Adding a game opens a picker with + the games installed through Steam at the top. +- Every game has its own palette, typefaces and animated banner. +- A step-by-step setup guide for every game, in the app and in docs/GAMES.md. +- Setup finds each game's save folder and lists its worlds by when they were + last played, with the game's known quirks shown before the first share. +- Folder-based worlds sync as a whole, including nested files and autosaves + the game rotates out; their change detection covers every file. +- The shared folder now records which game it belongs to, and WorldSync + refuses to pull or push a world into a different game. +- Invite codes carry the game. Dragonwilds codes keep the old `DWS1.` format + so friends on 1.x can still join. +- Upgrading: settings, worlds and backups are copied from + `%APPDATA%\DragonwildsSync` on first start (the old folder is left alone), + and the config moves to schema 3 with a `config.v2.bak` kept. +- Fixed: a missing import in the controller. +- Sync protocol unchanged for Dragonwilds worlds; manifests gain an optional + `game` field that older versions ignore. + ## 1.3.2 - 2026-10-05 Housekeeping only. In-app changelog caught up, README and UI wording diff --git a/DESIGN.md b/DESIGN.md index eabefc1..2aa5918 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,7 +1,34 @@ # Design rationale -*(v1.2 redesign notes at the very bottom; v1.1 additions below that; the v1.0 -rationale still holds underneath.)* +*(2.0 WorldSync notes first; v1.2 redesign notes at the very bottom; v1.1 +additions below that; the v1.0 rationale still holds underneath.)* + +## 2.0: from one game to a library + +- **Games are data, not code paths.** `app/core/games.py` describes each game: + save-folder templates (with `*` for Steam-ID folders, newest wins), how to + list existing worlds, and the file patterns that make up one world. + `config.effective_cfg` flattens that into the same dict the sync core has + always taken, plus three optional keys (`patterns`, `mirror`, `game`). The + core never imports the game table. +- **Dragonwilds stays byte-for-byte 1.x.** Its profile has `patterns=None`, + which keeps the original "files starting with the world name" rule, the + first-file hash and flat backups. Existing groups and 1.x friends see no + difference; the manifest just gains a `game` field old apps ignore. +- **Folder worlds need two new ideas.** A fingerprint over every file (a new + autosave is a change, not just an edit to the first file), and mirroring: + files the other side no longer has are removed after the backup, otherwise + rotated autosaves pile up in everyone's cloud drive. +- **Wrong-game guard.** Pull and push refuse when the shared folder's + manifest names a different game. Pointing Raft at a Valheim folder copies + nothing. +- **Themes are tokens, swapped at runtime.** `theme.use()` rewrites the + module-level colour tokens and fonts, the stylesheet is rebuilt, and pages + with code-styled bits implement `retheme()`. Text greys, amber and red are + shared by every theme so legibility never depends on the game. +- **Scenes instead of art.** Each game's banner is procedural QPainter work + seeded by the world name. No game assets ship, so there's nothing to + license and the exe stays small. ## Stack: Python + PySide6 (Qt), PyInstaller diff --git a/README.md b/README.md index 82170f9..46537a5 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,124 @@ -# Dragonwilds Sync +# WorldSync -[![tests](https://github.com/AndorManu/dragonwilds-sync/actions/workflows/tests.yml/badge.svg)](https://github.com/AndorManu/dragonwilds-sync/actions/workflows/tests.yml) -[![release](https://img.shields.io/github/v/release/AndorManu/dragonwilds-sync?label=download&color=3ddc97)](https://github.com/AndorManu/dragonwilds-sync/releases/latest) -[![license](https://img.shields.io/badge/license-MIT-d9a441)](LICENSE) +[![tests](https://github.com/AndorManu/worldsync/actions/workflows/tests.yml/badge.svg)](https://github.com/AndorManu/worldsync/actions/workflows/tests.yml) +[![release](https://img.shields.io/github/v/release/AndorManu/worldsync?label=download&color=7a9bff)](https://github.com/AndorManu/worldsync/releases/latest) +[![license](https://img.shields.io/badge/license-MIT-f2b66b)](LICENSE) ![python](https://img.shields.io/badge/python-3.12-blue) ![platform](https://img.shields.io/badge/platform-Windows-lightgrey) -**Your world shouldn't need one PC.** +**Your co-op world shouldn't live on one PC.** -In *RuneScape: Dragonwilds* a world lives on the computer of whoever created -it. If that person isn't online, nobody else can play it. Dragonwilds Sync -moves the world into a shared cloud folder instead, so **anyone in the group -can host**: tonight you, tomorrow a friend, next week you alone for an hour. -Whoever presses Play always gets the newest save, and their progress goes -back to the group when they quit. No server, no subscription, nothing to -keep running. +In most survival games a world lives on the computer of whoever created it. +If that person isn't online, nobody else can play it. WorldSync moves the +world into a shared cloud folder instead, so **anyone in the group can +host**: tonight you, tomorrow a friend, next week you alone for an hour. +Whoever presses Play gets the newest save, and their progress goes back to +the group when they quit. No server, no subscription, nothing to keep +running. Free and open source ([tips welcome](https://ko-fi.com/andormanu)). -Around that core: invite codes, live "who's playing", turn-passing with tray -pings, conflict detection in both directions, automatic backups, one-click -self-updates through the same folder, and a Characters page - all in a -dark-fantasy launcher that fits the game. +

+ The game library + Adding a game, installed games first + A friend is playing right now +

+ +## Supported games + +| Game | Status | Good to know | +|---|---|---| +| RuneScape: Dragonwilds | Tested | Where WorldSync started. Also gets a Characters page. | +| Valheim | Beta | Worlds in Steam Cloud need *Manage Saves → Move to Local* first. Characters stay on each PC. | +| Enshrouded | Beta | If you use Steam Cloud saves, point WorldSync at `Steam\userdata` during setup. | +| Palworld | Beta | Palworld ties the host's character to the host's PC; the original host can look reset when someone else hosts. Everyone else keeps theirs. | +| Core Keeper | Beta | Worlds are stored by slot, so the group shares the same slot number. | +| Sons of the Forest | Beta | The host's inventory lives in the save, so whoever hosts carries it. | +| V Rising | Beta | Every vampire is stored per Steam account, so everyone keeps their own. | +| Grounded | Beta | Steam version only; Game Pass saves sit in a protected folder. | +| Raft | Beta | | +| 7 Days to Die | Beta | A random-gen map travels with the save the first time (a few hundred MB). | + +Step-by-step setup for each game, and where its saves live: **[docs/GAMES.md](docs/GAMES.md)** +(the same guide is in the app, under the world menu). + +**Beta** means the save layout comes from community guides and WorldSync's +own tests, but hasn't had a full season of real groups yet. Every overwrite +is backed up first, so a surprise costs you a restore, not a world. If a +game does something unexpected, [open an issue](https://github.com/AndorManu/worldsync/issues) +and it moves to Tested once it's proven. More games get added one by one - +[ask for yours](https://github.com/AndorManu/worldsync/issues/new?labels=game-request&title=Game+request:+). + +

+ Every game gets its own look +

+ +Every game has its own look: Valheim's aurora, V Rising's blood moon, a +pixel cave for Core Keeper, a wasteland skyline for 7 Days to Die. All of +it is drawn by the app itself; no game art is shipped. ### Isn't this what dedicated servers are for? Yes, if your group plays together often enough to justify one. A dedicated -server needs a machine running 24/7 (yours, or ~€5-15/month rented) and -someone to keep it updated in step with the game. Dragonwilds Sync is for the +server needs a machine running 24/7 (yours, or roughly €5-15 a month rented) +and someone to keep it updated in step with the game. WorldSync is for the other kind of group: three to five friends who play a couple of evenings a -week, rarely all at once, and don't want a bill or a box to maintain. Nothing -runs when nobody's playing; the world is just files in a folder you already -have. Steam Cloud doesn't cover this either - it syncs *your* saves between -*your* PCs, not between friends. - -Built against the early-access saves; the 1.0 release (Sept 2026) kept the -same save layout, so nothing needs migrating. If your version moved something, -[open an issue](https://github.com/AndorManu/dragonwilds-sync/issues) with the -log from *Settings → Open log folder*. Windows/Steam only - console saves -can't be reached from the file system. +week, rarely all at once, and don't want a bill or a box to maintain. +Nothing runs when nobody's playing; the world is just files in a folder you +already have. Steam Cloud doesn't cover this either - it syncs *your* saves +between *your* PCs, not between friends. -

- Main screen: up to date, Play button, recent sessions - A friend is playing right now - Conflict warning before an overwrite -

+There are paid tools that do something similar through their own cloud. +WorldSync is free, the code is public, and your saves never touch anyone's +server but the cloud drive you already use. ## Download -Grab `DragonwildsSync.exe` from the **[latest release](https://github.com/AndorManu/dragonwilds-sync/releases/latest)**. -One file, no install, no Python, no account. Windows only (the game is). +Grab `WorldSync.exe` from the **[latest release](https://github.com/AndorManu/worldsync/releases/latest)**. +One file, no install, no Python, no account. Windows only. SmartScreen will warn the first time because the exe isn't code-signed - **More info → Run anyway**. The exe on every release is built by [GitHub Actions](.github/workflows/release.yml) from the tagged source on a clean runner, not on anyone's laptop; and if you'd rather not trust it at -all, the whole thing is Python - build it yourself in two commands (see below). +all, build it yourself in two commands (see below). + +**Coming from Dragonwilds Sync?** Just run WorldSync. Your worlds, settings, +backups and invite codes carry over on first start, and friends still on +Dragonwilds Sync 1.x can keep joining your Dragonwilds worlds. ## How it works -Everyone in the group points the app at the **same shared folder** - any -folder inside a cloud drive that each of you syncs to your own PC (Google -Drive, Dropbox, OneDrive… the app doesn't care which, and nothing ever needs -a paid server). - -- **Play** pulls the newest save, launches the game through Steam, and - - once you close the game - shares your progress back automatically. -- A tiny `version.json` manifest tracks a version number, who played last, - and when. Every share bumps the version; every pull checks it. -- If your local save changed without being shared *and* someone else has - since shared a newer version, you get an unmissable warning before - anything is overwritten - in **both** directions. Whatever gets replaced - is backed up first (browse and restore under *world menu → Backups*). +1. **Add a game.** The picker lists every supported game with the ones + installed through Steam at the top. +2. **Pick the world.** WorldSync looks in the game's usual save folder and + lists the worlds it finds, most recently played first, so you don't have + to go digging through AppData. +3. **Pick a shared folder** inside a cloud drive every friend syncs to their + own PC (Google Drive, Dropbox, OneDrive... it doesn't care which). +4. **Invite friends** with a code. It carries the game, the world and the + folder, so joining is paste, click, done. + +From then on: + +- **Play** pulls the newest save, launches the game through Steam, and + shares your progress back automatically once you close it. +- A small `version.json` in the shared folder tracks a version number, who + played last and when. Every share bumps the version; every pull checks it. +- If your local save changed without being shared *and* a friend has since + shared a newer one, you get a clear warning before anything is + overwritten, in **both** directions. Whatever gets replaced is backed up + first (browse and restore under *world menu → Backups*). - The app shows **who's playing right now**, lets you call **"I've got next"**, pings you from the tray when it's your turn, and can post to a Discord/Slack/ntfy **webhook** when someone shares a save. +- Worlds that are whole folders (V Rising, Palworld, Raft...) sync as a + whole, including autosaves the game rotates out, and WorldSync refuses to + copy one game's world into another game's folder. -## Joining a friend's world (the 60-second version) - -1. Download `DragonwildsSync.exe` (see above, or take your friend's copy) - and double-click it. -2. Type your name, pick **“Join with an invite code”**, paste the code your - friend sent you. -3. The app opens their share link - sign in to Google and click - **“Add shortcut to Drive”**. That's the one click we can't do for you. -4. Done. The app spots the folder as soon as Google Drive syncs it and drops - you on the main screen. Hit **Play**. - -You do need [Google Drive for desktop](https://www.google.com/drive/download/) -(or Dropbox/OneDrive) installed and signed in - the app tells you if it's -missing. - -## Hosting a world & inviting friends - -1. Pick **“Create a new world”** during setup: choose your world and a shared - folder inside your cloud drive. -2. Hit **“Invite friends”** on the main screen. Share the folder once in the - Drive UI (right-click → Share → *Anyone with the link* → Copy link), - paste the link, and copy the generated invite code into your group chat. -3. Each friend follows the three steps above. New invites for the same world - are one click - the link is remembered. +

+ Finding the world + Inviting friends + Conflict warning before an overwrite +

**House rule:** one person plays at a time. The app warns loudly (before *and* after the fact) if two sessions collide, but the polite fix is a @@ -105,76 +126,88 @@ message in the group chat. ## Keeping everyone on the latest version -No store, no manual re-sending of the exe: - -1. Build the new `DragonwildsSync.exe` and run it yourself to test. -2. Settings → **Publish this version to friends**. The app copies itself into - the shared folder's `_app` subfolder with a version manifest. -3. Everyone else's app notices the newer build (it's already syncing to their - PC), shows an **Update** bar, and swaps itself in place on confirm - worlds - and settings kept. +No store, no re-sending the exe: run the new build yourself, then +*Settings → Publish this version to friends*. Everyone else's app sees the +newer build in the shared folder, shows an **Update** bar, and swaps itself +in place on confirm. Worlds and settings are kept. ## Extras -- **Test my setup** (Settings) - a checklist that verifies folders, cloud - sync, and game launch so setup problems are obvious, not mysterious. +- **Test my setup** (Settings) - a checklist for folders, cloud sync and + game launch, so setup problems are obvious, not mysterious. - **Checkpoints** (world menu → Backups) - name a snapshot before something - risky; restore it any time. Automatic backups are taken whenever a save - would be overwritten. + risky; restore it any time. +- **Group history** - the last few shared versions stay in the shared + folder, so the whole group can roll back, not just whoever made a backup. - **Pass the turn** - hand a specific friend the world; they get a tray ping. -- **Phone status page** - with the toggle on, a `status.html` is written into - the shared folder; open it from your phone's cloud-drive app to see who's - playing without launching anything. +- **Phone status page** - a `status.html` in the shared folder shows who's + playing, readable from your phone's cloud-drive app. ## Building from source ```powershell -git clone https://github.com/AndorManu/dragonwilds-sync.git -cd dragonwilds-sync -.\build.ps1 # creates .venv, runs tests, builds dist\DragonwildsSync.exe +git clone https://github.com/AndorManu/worldsync.git +cd worldsync +.\build.ps1 # creates .venv, runs tests, builds dist\WorldSync.exe ``` -That single `.exe` is the whole distribution - dropping it in the shared -folder works great. Optionally compile `installer.iss` with -[Inno Setup](https://jrsoftware.org/isinfo.php) for a setup wizard. - Development: ```powershell python -m venv .venv .\.venv\Scripts\pip install -r requirements.txt -r requirements-dev.txt .\.venv\Scripts\python -m app # run from source -.\.venv\Scripts\python -m pytest tests # protocol + services test suite +.\.venv\Scripts\python -m pytest tests # the test suite .\.venv\Scripts\python tools\screenshots.py # re-render docs/screenshots ``` +## Adding a game + +A game is a single entry in [`app/core/games.py`](app/core/games.py): where +it keeps its saves, how to tell worlds apart, which files make up a world, +and the exe to watch for. For example: + +```python +GameProfile( + id="raft", name="Raft", steam_app_id="648800", + process_names=("Raft.exe",), + save_roots=("{LOCALLOW}/Redbeet Interactive/Raft/User/User_*/World",), + discover=(Discover("*", r"^(?P[^/]+)$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, +) +``` + +Give it a theme in [`app/ui/gamethemes.py`](app/ui/gamethemes.py) and a +scene in [`app/ui/scenes.py`](app/ui/scenes.py), add a test, and open a PR. + ## Layout ``` app/ - core/ sync protocol, config schema, invites, presence, webhooks, - backups, game launch/watch, cloud/Steam detection - no Qt - ui/ theme, widgets, screens (PySide6) + core/ sync protocol, game profiles, config schema, invites, presence, + webhooks, backups, game launch/watch, Steam detection - no Qt + ui/ library, picker, per-game themes and scenes, screens (PySide6) controller.py worker threads in, Qt signals out main.py entry point (--tray starts quietly in the tray) -tests/ pytest suite (184 tests) +tests/ pytest suite, including offscreen UI smoke tests tools/ icon generator, screenshot harness ``` ## Why it's built this way The sync core is deliberately small and boring: a `version.json` manifest, -a monotonic version counter, and content hashes compared on **both** pull -and push. Every overwrite is preceded by a backup, and every manifest write -is atomic (temp file + rename), so a cloud client dying mid-sync can't leave -a half-written state. The core has no Qt in it and is tested in isolation; -everything user-facing lives in a controller layer around it. Cloud drives -were chosen over a server on purpose - a group of friends already has one, -it's free, and there's nothing to host, patch, or pay for. - -Per-user data lives in `%APPDATA%\DragonwildsSync\` (config, per-world state, -logs, safety backups). v1.0 configs migrate automatically; the originals are -kept as `config.v1.bak` / `state.v1.bak`. +a monotonic version counter, and content fingerprints compared on **both** +pull and push. Every overwrite is preceded by a backup, and every manifest +write is atomic (temp file + rename), so a cloud client dying mid-sync can't +leave a half-written state. Games are plain data: the core never knows which +game it's syncing, it just gets a folder and a set of file patterns. Cloud +drives were chosen over a server on purpose - a group of friends already has +one, it's free, and there's nothing to host, patch or pay for. + +Per-user data lives in `%APPDATA%\WorldSync\` (config, per-world state, +logs, safety backups). Older configs migrate automatically and the +originals are kept as `config.v1.bak` / `config.v2.bak`. ## Security notes, honestly @@ -189,40 +222,46 @@ kept as `config.v1.bak` / `state.v1.bak`. - **The exe isn't code-signed** (certificates cost money; this is a hobby project). Verify a release by building it yourself, or compare the exe's SHA-256 with the one printed in the GitHub Actions log of that release. -- **Save files are only ever replaced after a backup is written**, and the - game's own `.backup` twin of each character file is never touched. +- **Save files are only ever replaced after a backup is written.** ## Troubleshooting -- **“Shared folder not found”** - your cloud client isn't running or the +- **"Shared folder not found"** - your cloud client isn't running or the folder moved; fix the path in Settings. -- **The newest save “hasn't finished syncing”** - the manifest arrived before +- **The newest save "hasn't finished syncing"** - the manifest arrived before the save files; give the cloud client a few seconds and hit refresh. +- **No worlds found** - start the game once and create or load the world, + then browse to the save folder if WorldSync still can't see it. - **Joining: the folder never appears** - make sure you clicked *Add shortcut to Drive* (not just opened the link), and that Google Drive for desktop is - running. “Browse for it manually” always works as a fallback. + running. "Browse for it manually" always works as a fallback. - **Game never detected** - Steam sometimes takes ages; the app waits two minutes, then falls back to the manual save button. -- **App won't quit** - it lives in the tray by default so it can ping you; - right-click the tray icon → Quit, or turn it off in Settings. - Logs: **Settings → Open log folder**. ## Contributing -Issues and pull requests are welcome. Keep the sync core (`app/core/sync.py`) -boring: any change there needs a test in `tests/test_sync.py`, and the -protocol must stay readable by older versions (the manifest is plain JSON on -purpose). Run `python -m pytest tests` before opening a PR - CI runs the same -suite on Windows and Linux. +Issues and pull requests are welcome, game requests especially. Keep the +sync core (`app/core/sync.py`) boring: any change there needs a test in +`tests/test_sync.py` or `tests/test_games.py`, and the manifest must stay +readable by older versions (it's plain JSON on purpose). Run +`python -m pytest tests` before opening a PR - CI runs the same suite on +Windows and Linux. + +## Support + +WorldSync is free and stays free. If it saved your group a server bill, +you can [buy me a coffee on Ko-fi](https://ko-fi.com/andormanu). It goes +straight into adding the next game. ## Credits & license - Code: [MIT](LICENSE). Built by [AndorManu](https://github.com/AndorManu). - Fonts: Cinzel, Cinzel Decorative and EB Garamond, under the - [SIL Open Font License](app/assets/fonts/OFL-Cinzel.txt). -- Item and unlock ID tables (`app/assets/*.json`) are derived from the - community datamine in [PEAKEGames/DWCharacterEditor](https://github.com/PEAKEGames/DWCharacterEditor). - No game assets are shipped; all icons and artwork in the app are drawn - procedurally. -- *RuneScape: Dragonwilds* is a trademark of Jagex Ltd. This is an - independent fan-made tool, not affiliated with or endorsed by Jagex. + [SIL Open Font License](app/assets/fonts/OFL-Cinzel.txt). Other typefaces + are the ones that ship with Windows. +- Dragonwilds item and unlock tables (`app/assets/*.json`) are derived from + the community datamine in [PEAKEGames/DWCharacterEditor](https://github.com/PEAKEGames/DWCharacterEditor). +- No game assets are shipped; every scene and icon is drawn by the app. +- All game names are trademarks of their respective owners. WorldSync is an + independent fan-made tool, not affiliated with or endorsed by any of them. diff --git a/SUPPORT.md b/SUPPORT.md index 091fd77..4bf6741 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -1,15 +1,15 @@ # Support -**Something broke?** Open an [issue](https://github.com/AndorManu/dragonwilds-sync/issues/new) with: +**Something broke?** Open an [issue](https://github.com/AndorManu/worldsync/issues/new) with: 1. What you did (Play / Save now / Join / Update…) 2. What you expected and what happened instead 3. The log: in the app, *Settings → Open log folder*, attach the newest `.log` -4. Game version (Steam → Dragonwilds → Properties → Updates) and app version (About page) +4. Which game, and its version (Steam → the game → Properties → Updates) and app version (About page) Saves are never deleted by the app - every overwrite is backed up first under *world menu → Backups*, and the automatic copies live in -`%APPDATA%\DragonwildsSync\backups\`. If a save looks wrong, restore from +`%APPDATA%\WorldSync\backups\`. If a save looks wrong, restore from there before anything else. -**Questions, ideas, "does it work with…"** → [Discussions](https://github.com/AndorManu/dragonwilds-sync/discussions). +**Questions, ideas, "does it work with…"** → [Discussions](https://github.com/AndorManu/worldsync/discussions). diff --git a/DragonwildsSync.spec b/WorldSync.spec similarity index 90% rename from DragonwildsSync.spec rename to WorldSync.spec index 0c55271..9405f01 100644 --- a/DragonwildsSync.spec +++ b/WorldSync.spec @@ -1,5 +1,5 @@ -# PyInstaller build spec - produces a single dist/DragonwildsSync.exe -# Build with: .\.venv\Scripts\python.exe -m PyInstaller --noconfirm DragonwildsSync.spec +# PyInstaller build spec - produces a single dist/WorldSync.exe +# Build with: .\.venv\Scripts\python.exe -m PyInstaller --noconfirm WorldSync.spec a = Analysis( ["run.py"], @@ -37,7 +37,7 @@ exe = EXE( a.binaries, a.datas, [], - name="DragonwildsSync", + name="WorldSync", icon="app/assets/icon.ico", debug=False, strip=False, diff --git a/app/__init__.py b/app/__init__.py index e3538bd..e6ac9fc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,4 +1,4 @@ -"""Dragonwilds Sync - turn-based world-save relay for RuneScape: Dragonwilds.""" +"""WorldSync - take turns hosting one co-op world through a shared cloud folder.""" -__version__ = "1.3.2" -APP_NAME = "Dragonwilds Sync" +__version__ = "2.0.0" +APP_NAME = "WorldSync" diff --git a/app/assets/icon.ico b/app/assets/icon.ico index 85b537c..8fa59b5 100644 Binary files a/app/assets/icon.ico and b/app/assets/icon.ico differ diff --git a/app/assets/icon.png b/app/assets/icon.png index b03db03..138e7f7 100644 Binary files a/app/assets/icon.png and b/app/assets/icon.png differ diff --git a/app/assets/icon.svg b/app/assets/icon.svg index 545ae00..651e199 100644 --- a/app/assets/icon.svg +++ b/app/assets/icon.svg @@ -1,35 +1,43 @@ - - - - + + + + - - - + + + - - - + + + + + + - + + stroke="#232B48" stroke-width="3"/> - - - - - - - - + + + + + + + + + + + + diff --git a/app/controller.py b/app/controller.py index 4e9c993..e1512db 100644 --- a/app/controller.py +++ b/app/controller.py @@ -5,6 +5,7 @@ detail - happens here, *around* the frozen sync core, never inside it. """ +import json import logging import threading import time @@ -17,9 +18,9 @@ import re from . import __version__ -from .core import (backups, characters, chime, config, discordrp, game, health, - paths, presence, saga, statuspage, storage, sync, update, - webhook, worldhistory) +from .core import (backups, characters, chime, config, discordrp, game, games, + health, paths, presence, saga, statuspage, storage, sync, + update, webhook, worldhistory) from .core.sync import MANIFEST_SCHEMA, SyncResult, world_files @@ -60,6 +61,7 @@ class Controller(QObject): update_available = Signal(object, str) # UpdateInfo, world_name nudge_received = Signal(str, str) # from_player, world_name quit_for_update = Signal() + library_summary = Signal(object) # {game_id: {...}} for the library cards # Worker threads must never touch widgets. Emitting a callable through # this signal marshals it onto the GUI thread (queued connection). run_on_ui = Signal(object) @@ -110,9 +112,14 @@ def _save_all(self): def setup_first_config(self, player_name, local_save_dir, world): self.cfg = self.cfg or {} base, _ = config.migrate_config(self.cfg if config.worlds(self.cfg) else {}) - base.update({"player_name": player_name, "local_save_dir": local_save_dir}) + base["player_name"] = player_name + game_id = world.get("game", games.DEFAULT_GAME) + if local_save_dir: + config.set_game_save_dir(base, game_id, local_save_dir) + config.add_to_library(base, game_id) base["worlds"] = config.worlds(base) + [world] base["active_world"] = world["id"] + base["last_view"] = game_id self.cfg = base self._save_all() self._prime_seen_versions() @@ -120,10 +127,15 @@ def setup_first_config(self, player_name, local_save_dir, world): self.worlds_changed.emit() self.refresh_status() - def add_world(self, world, activate=True): + def add_world(self, world, activate=True, save_dir=None): + game_id = world.get("game", games.DEFAULT_GAME) + config.add_to_library(self.cfg, game_id) + if save_dir: + config.set_game_save_dir(self.cfg, game_id, save_dir) self.cfg["worlds"] = config.worlds(self.cfg) + [world] if activate: self.cfg["active_world"] = world["id"] + self.cfg["last_view"] = game_id self._save_all() self.worlds_changed.emit() self.refresh_status() @@ -139,6 +151,84 @@ def remove_world(self, world_id): self.worlds_changed.emit() self.refresh_status() + # -- library ------------------------------------------------------------------ + def active_game(self) -> games.GameProfile: + return config.world_game(self.active_world()) + + def is_dragonwilds(self, world=None) -> bool: + return config.world_game(world or self.active_world()).id == games.DRAGONWILDS.id + + def add_game(self, game_id, save_dir=None): + config.add_to_library(self.cfg, game_id) + if save_dir: + config.set_game_save_dir(self.cfg, game_id, save_dir) + self._save_all() + self.worlds_changed.emit() + + def remove_game(self, game_id) -> bool: + try: + config.remove_from_library(self.cfg, game_id) + except ValueError: + return False + self._save_all() + self.worlds_changed.emit() + return True + + def set_game_save_dir(self, game_id, folder): + config.set_game_save_dir(self.cfg, game_id, folder) + self._save_all() + + def set_last_view(self, view): + if self.cfg is not None and self.cfg.get("last_view") != view: + self.cfg["last_view"] = view + self._save_all() + + def open_game(self, game_id): + """Make the most recent world of `game_id` active (for its game page).""" + self.set_last_view(game_id) + current = self.active_world() + if current and current.get("game", games.DEFAULT_GAME) == game_id: + self.refresh_status() + return + candidates = config.worlds_for_game(self.cfg, game_id) + if candidates: + self.set_active_world(candidates[-1]["id"]) + + def update_game(self, game_id, save_dir=None, exe_path=None): + if save_dir: + config.set_game_save_dir(self.cfg, game_id, save_dir) + if game_id == games.DRAGONWILDS.id: + self.cfg["exe_path"] = exe_path + else: + config.game_settings(self.cfg, game_id)["exe_path"] = exe_path + self._save_all() + + def request_library_summary(self): + """Who's playing / who played last, per game - read off the thread.""" + cfg = self.cfg or {} + + def worker(): + out = {} + for prof in config.library(cfg): + info = {"worlds": 0, "playing": None, "last": None} + for w in config.worlds_for_game(cfg, prof.id): + info["worlds"] += 1 + try: + who = presence.who_is_playing(w["sync_dir"]) + if who and who.get("player") != self.player_name: + info["playing"] = who.get("player") + manifest = sync.get_shared_manifest(w["sync_dir"]) + if manifest and manifest.get("timestamp"): + last = (manifest.get("last_editor", "?"), manifest["timestamp"]) + if not info["last"] or last[1] > info["last"][1]: + info["last"] = last + except Exception: + continue + out[prof.id] = info + self.library_summary.emit(out) + + threading.Thread(target=worker, daemon=True, name="library").start() + def set_active_world(self, world_id): if self.cfg.get("active_world") == world_id: return @@ -190,7 +280,7 @@ def _world_status(self, world) -> WorldStatus: log.exception("Presence check failed") newer = bool(getattr(snapshot, "manifest_schema", None) and snapshot.manifest_schema > MANIFEST_SCHEMA) - return WorldStatus(world_id=world["id"], world_name=world["world_name"], + return WorldStatus(world_id=world["id"], world_name=config.world_label(world), snapshot=snapshot, playing=playing, next_claim=next_claim, newer_app_needed=newer) @@ -220,7 +310,7 @@ def _scan_all_worlds(self): nudge = presence.read_nudge_for(w["sync_dir"], self.player_name) if nudge: presence.clear_nudge(w["sync_dir"]) - self.nudge_received.emit(nudge.get("player", "A friend"), w["world_name"]) + self.nudge_received.emit(nudge.get("player", "A friend"), config.world_label(w)) except Exception: pass if not manifest: @@ -230,7 +320,7 @@ def _scan_all_worlds(self): self._seen_versions[w["id"]] = manifest["version"] editor = manifest.get("last_editor", "Someone") if last and editor != self.player_name: - self.friend_pushed.emit(w["world_name"], editor, manifest["version"]) + self.friend_pushed.emit(config.world_label(w), editor, manifest["version"]) self.check_updates() # -- auto update --------------------------------------------------------------- @@ -246,7 +336,7 @@ def worker(): continue if info: self._update_offered = True - self.update_available.emit(info, w["world_name"]) + self.update_available.emit(info, config.world_label(w)) return threading.Thread(target=worker, daemon=True, name="update-check").start() @@ -277,7 +367,7 @@ def worker(): return update.publish(world["sync_dir"], __version__, update.current_exe(), self.player_name, notes="") - self.toast.emit("success", f"Published v{__version__} to {world['world_name']}. " + self.toast.emit("success", f"Published v{__version__} to {config.world_label(world)}. " f"Friends will be offered the update automatically.") except Exception: log.exception("publish_update failed") @@ -305,17 +395,26 @@ def _conflict_details(self) -> str: """Sizes + times of the two saves, so a conflict choice is informed.""" try: world = self.active_world() - wn = world["world_name"] - local = world_files(Path(self.cfg["local_save_dir"]), wn) - shared = world_files(Path(world["sync_dir"]), wn) + flat = self._flat_cfg(world) + wn, pats = world["world_name"], flat["patterns"] + local = world_files(Path(flat["local_save_dir"]), wn, pats) + shared = world_files(Path(world["sync_dir"]), wn, pats) def describe(files): - prim = next((f for f in files if f.suffix.lower() == ".sav"), None) - if not prim: + if not files: return None - st = prim.stat() - when = datetime.fromtimestamp(st.st_mtime).strftime("%d %b %H:%M") - return f"{st.st_size // 1024} KB · saved {when}" + if pats is None: + prim = next((f for f in files if f.suffix.lower() == ".sav"), None) + if not prim: + return None + st = prim.stat() + size, mtime = st.st_size, st.st_mtime + else: + stats = [f.stat() for f in files] + size = sum(st.st_size for st in stats) + mtime = max(st.st_mtime for st in stats) + when = datetime.fromtimestamp(mtime).strftime("%d %b %H:%M") + return f"{size // 1024} KB · saved {when}" li, si = describe(local), describe(shared) lines = [] @@ -335,7 +434,7 @@ def _write_status(self, world): return try: manifest = sync.get_shared_manifest(world["sync_dir"]) - statuspage.write(world["sync_dir"], world["world_name"], manifest, + statuspage.write(world["sync_dir"], config.world_label(world), manifest, presence.who_is_playing(world["sync_dir"]), presence.who_has_next(world["sync_dir"])) except Exception: @@ -739,6 +838,9 @@ def _play_flow(self): wstate = self._wstate(world) sync_dir = world["sync_dir"] world_name = world["world_name"] + profile = config.world_game(world) + dragonwilds = profile.id == games.DRAGONWILDS.id + procs = flat["process_names"] started_at = None try: playing = presence.who_is_playing(sync_dir) @@ -757,7 +859,7 @@ def _play_flow(self): return self._set_phase("checking") - if health.shared_still_syncing(sync_dir, world_name): + if health.shared_still_syncing(sync_dir, world_name, flat["patterns"]): self.toast.emit("warning", "The shared folder is still downloading the " "latest save - launching your current copy for now.") else: @@ -773,22 +875,28 @@ def _play_flow(self): elif result == SyncResult.MISSING_FILES: self.toast.emit("warning", "The newest save hasn't finished syncing to " "this PC - you're playing your current local copy.") + elif result == SyncResult.WRONG_GAME: + self.toast.emit("error", "That shared folder belongs to a different " + "game. Nothing was copied - check the folder " + "in Settings.") + return - self._travel_pull(world) + if dragonwilds: + self._travel_pull(world) - recent = self._recent_character() + recent = self._recent_character() if dragonwilds else None presence.start_playing( sync_dir, self.player_name, self.cfg.get("player_emoji", ""), character=recent.name if recent else "", portrait=characters.portrait_descriptor(recent) if recent else "") presence.clear_next(sync_dir, self.player_name) self._write_status(world) - char_mtimes_before = self._char_mtimes() + char_mtimes_before = self._char_mtimes() if dragonwilds else {} started_at = time.monotonic() - if game.find_game_process(): - self.toast.emit("info", "Dragonwilds is already running - I'll share " - "your progress when you close it.") + if game.find_game_process(procs): + self.toast.emit("info", f"{profile.name} is already running - I'll share " + f"your progress when you close it.") else: self._set_phase("launching") if self.cfg.get("play_chime", True): @@ -802,7 +910,7 @@ def _play_flow(self): return self._set_phase("waiting") - proc = game.find_game_process() or game.wait_for_game_start() + proc = game.find_game_process(procs) or game.wait_for_game_start(procs) if proc is None: presence.stop_playing(sync_dir, self.player_name) self._write_status(world) @@ -813,8 +921,9 @@ def _play_flow(self): self._set_phase("ingame") try: - self._rp.set_playing(world["world_name"], - recent.name if recent else "") + self._rp.set_playing(config.world_label(world), + recent.name if recent else "", + "" if dragonwilds else profile.name) except Exception: log.debug("Rich presence failed", exc_info=True) game.wait_for_game_exit(proc) @@ -822,11 +931,13 @@ def _play_flow(self): self._set_phase("pushing") duration = int(time.monotonic() - started_at) if started_at else None - played = self._changed_characters(char_mtimes_before) - self._vault_characters(played) - self._travel_push(world) - self._do_push_guarded(world, flat, wstate, duration, - played[0] if played else self._recent_character()) + played_char = None + if dragonwilds: + played = self._changed_characters(char_mtimes_before) + self._vault_characters(played) + self._travel_push(world) + played_char = played[0] if played else self._recent_character() + self._do_push_guarded(world, flat, wstate, duration, played_char) except Exception: log.exception("Play flow failed") self.toast.emit("error", "Something went wrong during the session. Your save " @@ -865,8 +976,8 @@ def _do_push_guarded(self, world, flat, wstate, duration_s, played_char=None): """Health-gate the push so a corrupt save can't poison the group.""" save_dir = Path(flat["local_save_dir"]) world_name = flat["world_name"] - if world_files(save_dir, world_name): - hp = health.check_local_save(save_dir, world_name) + if world_files(save_dir, world_name, flat["patterns"]): + hp = health.check_local_save(save_dir, world_name, flat["patterns"]) if not hp.ok: self.toast.emit("warning", f"Your save looks {hp.reason}, so I didn't share " f"it - that protects everyone from a bad file. " @@ -881,7 +992,8 @@ def _after_push(self, world, result, duration_s, played_char=None): if result == SyncResult.PUSHED: version = self._wstate(world).get("last_applied_version") self._seen_versions[world["id"]] = version - played_char = played_char or self._recent_character() + if self.is_dragonwilds(world): + played_char = played_char or self._recent_character() try: sync.amend_history_entry( world["sync_dir"], version, duration_s=duration_s, @@ -894,9 +1006,10 @@ def _after_push(self, world, result, duration_s, played_char=None): log.exception("Could not annotate history entry") try: worldhistory.archive_version(world["sync_dir"], - world["world_name"], version) + world["world_name"], version, + patterns=self._flat_cfg(world)["patterns"]) saga.bump_stats(world["sync_dir"], self.player_name, duration_s) - saga.write_saga(world["sync_dir"], world["world_name"], + saga.write_saga(world["sync_dir"], config.world_label(world), sync.get_shared_manifest(world["sync_dir"])) except Exception: log.exception("Post-push extras failed") @@ -906,8 +1019,8 @@ def _after_push(self, world, result, duration_s, played_char=None): if world.get("webhook_url"): webhook.send_async( world["webhook_url"], - f"🐉 {self.player_name} shared v{version} of " - f"{world['world_name']} - the wilds await.", + f"{self._webhook_mark(world)} {self.player_name} shared v{version} of " + f"{config.world_label(world)} ({config.world_game(world).name}).", on_error=lambda e: self.toast.emit( "warning", "Save shared fine, but the webhook didn't go " "through - check the URL in Settings.")) @@ -917,6 +1030,13 @@ def _after_push(self, world, result, duration_s, played_char=None): "there was nothing to share.") elif result == SyncResult.STALE_CANCELLED: self.toast.emit("info", "Didn't share. Hit Play to pick up the newer save first.") + elif result == SyncResult.WRONG_GAME: + self.toast.emit("error", "That shared folder belongs to a different game, " + "so nothing was shared. Check the folder in Settings.") + + @staticmethod + def _webhook_mark(world) -> str: + return "🐉" if config.world_game(world).id == games.DRAGONWILDS.id else "🎮" # -- session notes --------------------------------------------------------------- def save_session_note(self, world_id, version, note): @@ -985,8 +1105,8 @@ def worker(): if world.get("webhook_url"): webhook.send_async( world["webhook_url"], - f"🐉 {self.player_name} passed the turn to {to_player} " - f"in {world['world_name']}.") + f"{self._webhook_mark(world)} {self.player_name} passed the turn to {to_player} " + f"in {config.world_label(world)}.") except Exception: log.exception("Nudge failed") @@ -999,9 +1119,10 @@ def create_checkpoint(self, name, done=None): def worker(): info = None try: + flat = self._flat_cfg(world) info = backups.create_checkpoint( - self.cfg["local_save_dir"], world["world_name"], name, - self._backup_root(world)) + flat["local_save_dir"], world["world_name"], name, + self._backup_root(world), patterns=flat["patterns"]) except Exception: log.exception("Checkpoint failed") if info: @@ -1036,7 +1157,7 @@ def export_saga(self): def worker(): try: manifest = sync.get_shared_manifest(world["sync_dir"]) - path = saga.write_saga(world["sync_dir"], world["world_name"], manifest) + path = saga.write_saga(world["sync_dir"], config.world_label(world), manifest) if path: import os as _os _os.startfile(str(path)) # noqa: S606 diff --git a/app/core/autostart.py b/app/core/autostart.py index 06405cb..599f918 100644 --- a/app/core/autostart.py +++ b/app/core/autostart.py @@ -10,7 +10,8 @@ log = logging.getLogger("dwsync.autostart") RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run" -VALUE_NAME = "DragonwildsSync" +VALUE_NAME = "WorldSync" +LEGACY_VALUE_NAMES = ("DragonwildsSync",) try: import winreg @@ -39,6 +40,11 @@ def set_enabled(enable: bool) -> bool: try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY, 0, winreg.KEY_SET_VALUE) as k: + for old in LEGACY_VALUE_NAMES: # the pre-2.0 entry points at the old exe + try: + winreg.DeleteValue(k, old) + except FileNotFoundError: + pass if enable: winreg.SetValueEx(k, VALUE_NAME, 0, winreg.REG_SZ, f'"{sys.executable}" --tray') diff --git a/app/core/backups.py b/app/core/backups.py index 10e8608..56c4912 100644 --- a/app/core/backups.py +++ b/app/core/backups.py @@ -11,7 +11,7 @@ from datetime import datetime from pathlib import Path -from .sync import _backup_files +from .sync import _backup_files, _copy_world, _rel, _remove_stale, world_files log = logging.getLogger("dwsync.backups") @@ -47,7 +47,7 @@ def list_backups(backup_root) -> list[BackupInfo]: label = name if folder.name == CHECKPOINTS_DIRNAME: continue - files = [f for f in folder.iterdir() if f.is_file()] + files = _files_in(folder) infos.append(BackupInfo(path=folder, stamp=stamp, label=label, file_count=len(files))) return infos @@ -74,19 +74,25 @@ def list_checkpoints(backup_root) -> list[BackupInfo]: for folder in sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.name, reverse=True): name, stamp = _read_checkpoint_meta(folder) - files = [f for f in folder.iterdir() if f.is_file() and f.name != "checkpoint.json"] + files = _files_in(folder) infos.append(BackupInfo(path=folder, stamp=stamp, label="checkpoint", file_count=len(files), name=name, is_checkpoint=True)) return infos -def create_checkpoint(save_dir, world_name: str, name: str, backup_root) -> BackupInfo | None: +def _files_in(folder: Path) -> list[Path]: + """Every file in a backup folder (nested for folder worlds), minus metadata.""" + return sorted(f for f in folder.rglob("*") + if f.is_file() and not (f.parent == folder and f.name == "checkpoint.json")) + + +def create_checkpoint(save_dir, world_name: str, name: str, backup_root, + patterns=None) -> BackupInfo | None: """Pin the current local save under a friendly name. Not auto-pruned.""" import json save_dir = Path(save_dir) - files = sorted(p for p in save_dir.glob(f"{world_name}*") if p.is_file()) \ - if save_dir.exists() else [] + files = world_files(save_dir, world_name, patterns) if not files: return None root = Path(backup_root) / CHECKPOINTS_DIRNAME @@ -98,8 +104,11 @@ def create_checkpoint(save_dir, world_name: str, name: str, backup_root) -> Back dest = root / f"{base}-{n}" n += 1 dest.mkdir(parents=True) - for f in files: - shutil.copy2(f, dest / f.name) + if patterns is None: + for f in files: + shutil.copy2(f, dest / f.name) + else: + _copy_world(files, save_dir, dest) (dest / "checkpoint.json").write_text( json.dumps({"name": name.strip() or "Checkpoint", "created": stamp.isoformat(timespec="seconds")}), @@ -118,27 +127,31 @@ def delete_backup(backup_path) -> bool: return False -def restore_backup(backup_path, save_dir, world_name: str, backup_root) -> int: +def restore_backup(backup_path, save_dir, world_name: str, backup_root, + patterns=None, mirror: bool = False) -> int: """Copy a backup's files into the local save folder. The save files being replaced are themselves backed up first - (label ``pre_restore``), so a restore is always reversible. + (label ``pre_restore``), so a restore is always reversible. With + `mirror`, world files the backup doesn't contain are removed, so a + folder world comes back exactly as it was. Returns the number of files restored. """ backup_path = Path(backup_path) save_dir = Path(save_dir) - files = [f for f in backup_path.iterdir() - if f.is_file() and f.name != "checkpoint.json"] + files = _files_in(backup_path) if not files: return 0 - current = sorted(p for p in save_dir.glob(f"{world_name}*") if p.is_file()) \ - if save_dir.exists() else [] + current = world_files(save_dir, world_name, patterns) if current: - _backup_files(current, "pre_restore", backup_root) + _backup_files(current, "pre_restore", backup_root, + root=save_dir if patterns is not None else None) save_dir.mkdir(parents=True, exist_ok=True) - for f in files: - shutil.copy2(f, save_dir / f.name) + _copy_world(files, backup_path, save_dir) + if mirror and patterns is not None: + _remove_stale(save_dir, world_name, patterns, + {_rel(f, backup_path).as_posix() for f in files}) log.info("Restored %d file(s) from %s", len(files), backup_path.name) return len(files) diff --git a/app/core/config.py b/app/core/config.py index 17db654..0330998 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -1,7 +1,9 @@ -"""Config/state schema v2: multiple worlds, global player + machine settings. +"""Config/state schema v3: a library of games, each with its worlds. -v1 (single world, flat) is migrated automatically and non-destructively: -the old files are kept as ``config.v1.bak`` / ``state.v1.bak``. +v1 (single world, flat) and v2 (multiple Dragonwilds worlds) migrate +automatically and non-destructively: the old files are kept as +``config.v1.bak`` / ``config.v2.bak``. In v3 every world names its game; +anything from before 2.0 is a Dragonwilds world. The sync core keeps its v1-shaped flat dict interface; ``effective_cfg`` builds that flat dict for one world. That boundary is what lets every new @@ -12,14 +14,14 @@ import shutil import uuid -from . import paths +from . import games, paths from .storage import load_config as _load_raw_config from .storage import load_state as _load_raw_state from .storage import save_config, save_state log = logging.getLogger("dwsync.config") -CONFIG_SCHEMA = 2 +CONFIG_SCHEMA = 3 GLOBAL_DEFAULTS = { "schema": CONFIG_SCHEMA, @@ -38,10 +40,15 @@ "discord_app_id": "", "active_world": None, "worlds": [], + "library": [], # game ids in the order the player added them + "games": {}, # per-game machine settings: {id: {save_dir, exe_path}} + "last_view": None, # "library" or a game id - where the app reopens } WORLD_DEFAULTS = { "id": None, + "game": games.DEFAULT_GAME, + "label": None, # friendly name when the id is a code (V Rising, Palworld) "world_name": "", "sync_dir": "", "share_link": None, @@ -73,12 +80,28 @@ def _backup_file(path, suffix=".v1.bak"): log.warning("Could not write migration backup for %s", path) +def _to_v3(cfg: dict) -> dict: + """Fill v3 fields: every world gets a game, the library lists them.""" + for w in cfg.get("worlds", []): + w.setdefault("game", games.DEFAULT_GAME) + library = list(cfg.get("library") or []) + for w in cfg.get("worlds", []): + if w["game"] not in library: + library.append(w["game"]) + cfg["library"] = library + cfg["games"] = dict(cfg.get("games") or {}) + if cfg.get("last_view") is None and library: + cfg["last_view"] = library[0] + cfg["schema"] = CONFIG_SCHEMA + return cfg + + def migrate_config(cfg: dict) -> tuple[dict, str | None]: - """v1 flat config -> v2. Returns (v2_config, migrated_world_id | None).""" + """Any older config -> v3. Returns (v3_config, migrated_world_id | None).""" if not _is_v1(cfg): merged = dict(GLOBAL_DEFAULTS) merged.update(cfg) - return merged, None + return _to_v3(merged), None world = make_world(cfg.get("world_name", ""), cfg.get("sync_dir", "")) v2 = dict(GLOBAL_DEFAULTS) v2.update({ @@ -89,7 +112,7 @@ def migrate_config(cfg: dict) -> tuple[dict, str | None]: "active_world": world["id"], "worlds": [world], }) - return v2, world["id"] + return _to_v3(v2), world["id"] def migrate_state(state: dict, migrated_world_id: str | None) -> dict: @@ -120,8 +143,14 @@ def load() -> tuple[dict | None, dict]: save_config(cfg) save_state(state) else: - cfg, _ = migrate_config(cfg) # fill any missing v2 defaults + older = cfg.get("schema", 2) < CONFIG_SCHEMA + if older: + log.info("Migrating config to v%d (game library)", CONFIG_SCHEMA) + _backup_file(paths.CONFIG_PATH, suffix=f".v{cfg.get('schema', 2)}.bak") + cfg, _ = migrate_config(cfg) # fill any missing defaults state = migrate_state(state, None) + if older: + save_config(cfg) return cfg, state @@ -145,15 +174,98 @@ def active_world(cfg: dict) -> dict | None: return w +def world_label(world: dict | None) -> str: + """What to call a world on screen: its in-game name if we know it.""" + if not world: + return "" + return world.get("label") or world.get("world_name", "") + + +def world_game(world: dict | None) -> games.GameProfile: + return games.get((world or {}).get("game")) + + +def worlds_for_game(cfg: dict, game_id: str) -> list[dict]: + return [w for w in worlds(cfg) if w.get("game", games.DEFAULT_GAME) == game_id] + + +def library(cfg: dict) -> list[games.GameProfile]: + return [games.get(g) for g in (cfg or {}).get("library", []) if g in games.BY_ID] + + +def add_to_library(cfg: dict, game_id: str): + lib = cfg.setdefault("library", []) + if game_id not in lib: + lib.append(game_id) + + +def remove_from_library(cfg: dict, game_id: str): + """Only allowed once the game has no worlds left.""" + if worlds_for_game(cfg, game_id): + raise ValueError("game still has worlds") + cfg["library"] = [g for g in cfg.get("library", []) if g != game_id] + cfg.get("games", {}).pop(game_id, None) + if cfg.get("last_view") == game_id: + cfg["last_view"] = "library" + + +def game_settings(cfg: dict, game_id: str) -> dict: + return cfg.setdefault("games", {}).setdefault(game_id, {}) + + +def game_save_dir(cfg: dict, game_id: str) -> str: + """The save folder for a game on this PC: the player's choice, else the + detected default, else where it normally lives (for display). + + Dragonwilds keeps using the v1 ``local_save_dir`` key so the + Dragonwilds-only extras (characters) keep finding it. + """ + if game_id == games.DRAGONWILDS.id: + return cfg.get("local_save_dir") or str(paths.DEFAULT_SAVE_DIR) + chosen = ((cfg.get("games") or {}).get(game_id) or {}).get("save_dir") + if chosen: + return chosen + profile = games.get(game_id) + found = games.default_save_dir(profile) + return str(found or games.fallback_save_dir(profile)) + + +def set_game_save_dir(cfg: dict, game_id: str, folder: str): + if game_id == games.DRAGONWILDS.id: + cfg["local_save_dir"] = folder + else: + game_settings(cfg, game_id)["save_dir"] = folder + + +def game_exe_path(cfg: dict, game_id: str) -> str | None: + if game_id == games.DRAGONWILDS.id: + return cfg.get("exe_path") + return ((cfg.get("games") or {}).get(game_id) or {}).get("exe_path") + + def effective_cfg(cfg: dict, world: dict) -> dict: - """The flat, v1-shaped dict the sync core was validated against.""" + """The flat, v1-shaped dict the sync core was validated against. + + WorldSync adds a few keys the core reads with .get(): the world's file + patterns, whether to mirror deletions, and the game id (stamped on the + manifest and checked on pull). Dragonwilds worlds carry patterns=None, + which is the exact v1 behaviour. + """ + profile = world_game(world) + app_id = profile.steam_app_id + if profile.id == games.DRAGONWILDS.id: + app_id = cfg.get("steam_app_id") or app_id return { "player_name": cfg.get("player_name", ""), - "local_save_dir": cfg.get("local_save_dir", ""), + "local_save_dir": game_save_dir(cfg, profile.id), "world_name": world.get("world_name", ""), "sync_dir": world.get("sync_dir", ""), - "exe_path": cfg.get("exe_path"), - "steam_app_id": cfg.get("steam_app_id", paths.STEAM_APP_ID), + "exe_path": game_exe_path(cfg, profile.id), + "steam_app_id": app_id, + "game": profile.id, + "patterns": list(profile.patterns) if profile.patterns is not None else None, + "mirror": profile.mirror, + "process_names": list(profile.process_names), } diff --git a/app/core/discordrp.py b/app/core/discordrp.py index 7c6bb4e..f7c824d 100644 --- a/app/core/discordrp.py +++ b/app/core/discordrp.py @@ -76,13 +76,13 @@ def _read_frame(self): _op, length = struct.unpack(" bool: return psutil is not None -def find_game_process(): +def find_game_process(names=None): + """The running game process, matched on any of `names` (exe file names).""" if not psutil: return None + wanted = {n.lower() for n in (names or (paths.GAME_PROCESS_NAME,))} for p in psutil.process_iter(["name"]): try: - if p.info["name"] and p.info["name"].lower() == paths.GAME_PROCESS_NAME.lower(): + if p.info["name"] and p.info["name"].lower() in wanted: return p except (psutil.NoSuchProcess, psutil.AccessDenied): continue @@ -58,11 +60,11 @@ def launch_game(cfg) -> str: return "steam" -def wait_for_game_start(timeout_s: float = START_TIMEOUT_S): +def wait_for_game_start(names=None, timeout_s: float = START_TIMEOUT_S): """Poll until the game process appears; returns it, or None on timeout.""" deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: - proc = find_game_process() + proc = find_game_process(names) if proc: return proc time.sleep(START_POLL_S) diff --git a/app/core/games.py b/app/core/games.py new file mode 100644 index 0000000..927822e --- /dev/null +++ b/app/core/games.py @@ -0,0 +1,547 @@ +"""Game profiles: everything WorldSync needs to know about one game. + +A profile is plain data. It says where the game keeps its saves, how to tell +one world apart from another inside that folder, which files make up a +world, and how to launch and watch the game. The sync core never sees a +profile directly - ``config.effective_cfg`` flattens the bits it needs +(save folder, file patterns, mirror flag) into the same dict it has always +taken, so adding a game never touches the protocol. + +Path templates use a few tokens (``{LOCALAPPDATA}``, ``{APPDATA}``, +``{LOCALLOW}``, ``{SAVEDGAMES}``, ``{USERPROFILE}``, ``{DOCUMENTS}``) and may +contain ``*`` segments for folders named after a Steam ID. When a ``*`` +matches several folders, the most recently written one wins - that is the +account that played last. + +File patterns are globs relative to the save folder. ``{world}`` is the +world id and ``{map}`` is the part before the first ``/`` (7 Days to Die +keeps a world as ``/``). ``patterns=None`` means the original +Dragonwilds rule: every file in the folder whose name starts with the world +name. That keeps existing Dragonwilds groups byte-for-byte compatible. +""" + +import os +import re +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path + +VERIFIED = "verified" # tested end to end with real saves +BETA = "beta" # layout from community guides; waiting on reports + + +@dataclass(frozen=True) +class Discover: + """How to list the worlds that already exist in a save folder.""" + glob: str # relative to the save folder + regex: str # applied to the match's path relative to the folder + dirs: bool = False # match folders instead of files + + +@dataclass(frozen=True) +class GameProfile: + id: str + name: str + steam_app_id: str + process_names: tuple[str, ...] + save_roots: tuple[str, ...] # templates, first that exists wins + discover: tuple[Discover, ...] + patterns: tuple[str, ...] | None # None = legacy prefix rule + mirror: bool = False # delete files the other side no longer has + status: str = BETA + tagline: str = "" # one line for the library card + world_word: str = "world" # what the game calls it: world, save, slot + world_hint: str = "" # how to recognise the right world + caveats: tuple[str, ...] = () # shown before the first share + label_fmt: str = "" # e.g. "Slot {slot}" for numbered worlds + label_json: tuple[str, str] | None = None # (file inside the world, key) for a nicer name + extras: tuple[str, ...] = field(default=()) # optional feature flags, e.g. "characters" + short_name: str = "" # for tight spots; defaults to name + + @property + def verified(self) -> bool: + return self.status == VERIFIED + + @property + def short(self) -> str: + return self.short_name or self.name + + +# -- the library ---------------------------------------------------------------- + +DRAGONWILDS = GameProfile( + id="dragonwilds", + name="RuneScape: Dragonwilds", + steam_app_id="1374490", + process_names=("RSDragonwilds.exe",), + save_roots=("{LOCALAPPDATA}/RSDragonwilds/Saved/SaveGames",), + discover=(Discover("*.sav", r"^(?P.+)\.sav$"),), + patterns=None, + status=VERIFIED, + tagline="Dark fantasy survival in Ashenfall", + world_hint="The world name as it appears in the game's world list.", + extras=("characters", "secret", "rich_presence"), + short_name="Dragonwilds", +) + +VALHEIM = GameProfile( + id="valheim", + name="Valheim", + steam_app_id="892970", + process_names=("valheim.exe",), + save_roots=("{LOCALLOW}/IronGate/Valheim/worlds_local",), + discover=(Discover("*.fwl", r"^(?P[^/]+)\.fwl$"), + Discover("*", r"^(?P[^/.]+)$", dirs=True)), + patterns=("{world}.fwl*", "{world}.db*", "{world}/**/*"), + mirror=True, + tagline="Viking afterlife, ten worlds deep", + world_hint="The world name from the Start Game screen.", + caveats=( + "Worlds stored in Steam Cloud aren't in this folder. In Valheim, " + "select the world, choose Manage Saves and Move to Local first.", + "Characters live on each player's own PC, so everyone keeps their own " + "Viking - only the world travels.", + ), +) + +ENSHROUDED = GameProfile( + id="enshrouded", + name="Enshrouded", + steam_app_id="1203620", + process_names=("enshrouded.exe",), + save_roots=("{SAVEDGAMES}/Enshrouded", + "{PROGRAMFILESX86}/Steam/userdata/*/1203620/remote"), + discover=(Discover("*", r"^(?P[0-9a-f]{8})$"),), + patterns=("{world}", "{world}-*", "{world}_*"), + mirror=True, + tagline="Fight back the Shroud together", + world_hint="Enshrouded names world files with an 8 character code. " + "Pick the one you played most recently.", + caveats=( + "With Steam Cloud saves on, Enshrouded keeps worlds under Steam\\userdata. " + "WorldSync looks there as well; browse to it if nothing shows up.", + ), +) + +PALWORLD = GameProfile( + id="palworld", + name="Palworld", + steam_app_id="1623730", + process_names=("Palworld-Win64-Shipping.exe", "Palworld.exe"), + save_roots=("{LOCALAPPDATA}/Pal/Saved/SaveGames/*",), + discover=(Discover("*", r"^(?P[0-9A-Fa-f]{32})$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, + tagline="Catch, build, and survive with Pals", + world_word="world", + world_hint="Palworld names world folders with a long code. " + "Pick the one you played most recently.", + caveats=( + "Palworld ties the host's character to the host's PC. When a " + "different friend hosts, the original host's character can look " + "reset. Everyone else keeps theirs. Community tools such as " + "PalworldSaveTools can move a host character if you need it.", + ), +) + +CORE_KEEPER = GameProfile( + id="core_keeper", + name="Core Keeper", + steam_app_id="1621690", + process_names=("CoreKeeper.exe",), + save_roots=("{LOCALLOW}/Pugstorm/Core Keeper/Steam/*",), + discover=(Discover("worlds/*.world.gzip", r"^worlds/(?P\d+)\.world\.gzip$"),), + patterns=("worlds/{world}.world.gzip*", "maps/*/{world}.mapparts.gzip*", + "worldinfos/{world}.*", "worldgenparams/{world}.*"), + mirror=True, + tagline="Mine deep, wake the Core", + world_word="slot", + world_hint="Core Keeper numbers worlds by their slot on the world menu.", + label_fmt="Slot {slot}", + caveats=( + "Core Keeper stores worlds by slot number, so everyone in the group " + "uses the same slot for this world. If a friend already has a " + "different world in that slot, WorldSync backs it up before replacing it.", + ), +) + +SONS_OF_THE_FOREST = GameProfile( + id="sons_of_the_forest", + name="Sons of the Forest", + steam_app_id="1326470", + process_names=("SonsOfTheForest.exe",), + save_roots=("{LOCALLOW}/Endnight/SonsOfTheForest/Saves/*/Multiplayer",), + discover=(Discover("*", r"^(?P\d+)$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, + tagline="Survive the island, together", + world_word="save", + world_hint="Multiplayer saves are numbered folders. Pick the one you " + "played most recently.", + caveats=( + "The host's inventory and stats are stored inside the save. Whoever " + "hosts the shared save carries that host inventory; guests keep their " + "own from the MultiplayerClient folder.", + ), +) + +V_RISING = GameProfile( + id="v_rising", + name="V Rising", + steam_app_id="1604030", + process_names=("VRising.exe",), + save_roots=("{LOCALLOW}/Stunlock Studios/VRising/Saves/v*",), + discover=(Discover("*", r"^(?P[^/]+)$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, + tagline="Rise from the grave, build a castle", + world_hint="Each private game is a folder with a long code name.", + label_json=("ServerHostSettings.json", "Name"), + caveats=( + "Vampires are stored per Steam account inside the world, so every " + "friend keeps their own character whoever hosts.", + ), +) + +GROUNDED = GameProfile( + id="grounded", + name="Grounded", + steam_app_id="962130", + process_names=("Maine-Win64-Shipping.exe", "Grounded.exe"), + save_roots=("{SAVEDGAMES}/Grounded/[0-9]*", "{SAVEDGAMES}/Grounded"), + discover=(Discover("*", r"^(?P[^/.]+)$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, + tagline="Shrunk to the size of an ant", + world_hint="Each world is a folder with a screenshot inside to recognise it.", + caveats=( + "Grounded on Game Pass keeps saves in a protected folder WorldSync " + "can't reach. The Steam version works.", + ), +) + +RAFT = GameProfile( + id="raft", + name="Raft", + steam_app_id="648800", + process_names=("Raft.exe",), + save_roots=("{LOCALLOW}/Redbeet Interactive/Raft/User/User_*/World",), + discover=(Discover("*", r"^(?P[^/]+)$", dirs=True),), + patterns=("{world}/**/*",), + mirror=True, + tagline="Adrift with a hook and a shark", + world_hint="The world name from Load World.", +) + +SEVEN_DAYS = GameProfile( + id="seven_days_to_die", + name="7 Days to Die", + steam_app_id="251570", + process_names=("7DaysToDie.exe",), + save_roots=("{APPDATA}/7DaysToDie",), + discover=(Discover("Saves/*/*", r"^Saves/(?P[^/]+/[^/]+)$", dirs=True),), + patterns=("Saves/{world}/**/*", "GeneratedWorlds/{map}/**/*"), + mirror=True, + tagline="Survive the blood moon horde", + world_word="save", + world_hint="Your save names from Continue Game; the map travels along with it.", + label_fmt="{save}", + caveats=( + "A random-gen map travels with the save the first time, so the " + "first share can be a few hundred MB. After that only changes move.", + ), +) + +ALL: tuple[GameProfile, ...] = ( + DRAGONWILDS, VALHEIM, ENSHROUDED, PALWORLD, CORE_KEEPER, + SONS_OF_THE_FOREST, V_RISING, GROUNDED, RAFT, SEVEN_DAYS, +) +BY_ID = {g.id: g for g in ALL} +DEFAULT_GAME = DRAGONWILDS.id + + +def get(game_id: str | None) -> GameProfile: + """Profile by id; unknown ids fall back to Dragonwilds (the v1 game).""" + return BY_ID.get(game_id or DEFAULT_GAME, DRAGONWILDS) + + +# -- path resolution -------------------------------------------------------------- + +def _tokens() -> dict[str, str]: + home = Path(os.environ.get("USERPROFILE") or Path.home()) + return { + "USERPROFILE": str(home), + "LOCALAPPDATA": os.environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local"), + "APPDATA": os.environ.get("APPDATA") or str(home / "AppData" / "Roaming"), + "LOCALLOW": str(home / "AppData" / "LocalLow"), + "SAVEDGAMES": str(home / "Saved Games"), + "DOCUMENTS": str(home / "Documents"), + "PROGRAMFILESX86": os.environ.get("ProgramFiles(x86)") or "C:/Program Files (x86)", + } + + +def _newest(paths: list[Path]) -> Path | None: + best, best_t = None, -1.0 + for p in paths: + try: + t = p.stat().st_mtime + except OSError: + continue + if t > best_t: + best, best_t = p, t + return best + + +def expand(template: str, tokens: dict[str, str] | None = None) -> Path | None: + """Turn a template into a real folder, or None if it doesn't exist here.""" + text = template.format(**(tokens or _tokens())) + parts = Path(text).parts + current = Path(parts[0]) + for part in parts[1:]: + if "*" in part or "?" in part: + try: + matches = [p for p in current.glob(part) if p.is_dir()] + except OSError: + return None + current = _newest(matches) + if current is None: + return None + else: + current = current / part + try: + return current if current.is_dir() else None + except OSError: + return None + + +def default_save_dir(profile: GameProfile, tokens: dict[str, str] | None = None) -> Path | None: + for template in profile.save_roots: + found = expand(template, tokens) + if found: + return found + return None + + +def fallback_save_dir(profile: GameProfile) -> Path: + """Where the save folder normally is, for display when it doesn't exist yet.""" + text = profile.save_roots[0].format(**_tokens()) + # stop at the first wildcard: that part is per-account + keep = [] + for part in Path(text).parts: + if "*" in part or "?" in part: + break + keep.append(part) + return Path(*keep) + + +# -- world discovery ---------------------------------------------------------------- + +@dataclass +class FoundWorld: + id: str + label: str + modified: datetime | None + size: int + + +def _tree_size_and_mtime(path: Path) -> tuple[int, float]: + if path.is_file(): + st = path.stat() + return st.st_size, st.st_mtime + size, newest = 0, path.stat().st_mtime + for f in path.rglob("*"): + try: + if f.is_file(): + st = f.stat() + size += st.st_size + newest = max(newest, st.st_mtime) + except OSError: + continue + return size, newest + + +def _label(profile: GameProfile, world_id: str, root: Path) -> str: + if profile.label_json: + rel, key = profile.label_json + try: + import json + data = json.loads((root / world_id / rel).read_text(encoding="utf-8-sig")) + name = str(data.get(key) or "").strip() + if name: + return name + except (OSError, ValueError, AttributeError): + pass + if profile.label_fmt: + slot = int(world_id) + 1 if world_id.isdigit() else world_id + first, _, last = world_id.partition("/") + return profile.label_fmt.format(world=world_id, slot=slot, map=first, + save=last or first) + return world_id.replace("/", " / ") + + +def discover_worlds(profile: GameProfile, save_dir) -> list[FoundWorld]: + """Worlds that exist in `save_dir`, most recently played first.""" + root = Path(save_dir) + if not root.is_dir(): + return [] + found: dict[str, FoundWorld] = {} + for spec in profile.discover: + rx = re.compile(spec.regex) + try: + candidates = list(root.glob(spec.glob)) + except OSError: + continue + for path in candidates: + try: + if spec.dirs != path.is_dir(): + continue + except OSError: + continue + rel = path.relative_to(root).as_posix() + m = rx.match(rel) + if not m: + continue + wid = m.group("w") + try: + size, mtime = _tree_size_and_mtime(path) + except OSError: + size, mtime = 0, 0.0 + prev = found.get(wid) + when = datetime.fromtimestamp(mtime) if mtime else None + if prev: + prev.size += size + if when and (not prev.modified or when > prev.modified): + prev.modified = when + else: + found[wid] = FoundWorld(wid, _label(profile, wid, root), when, size) + return sorted(found.values(), + key=lambda w: w.modified or datetime.min, reverse=True) + + +def is_valid_world_id(world_id: str) -> bool: + """Reject ids that could escape the save folder when used in a pattern.""" + if not world_id or world_id.strip() != world_id: + return False + parts = world_id.replace("\\", "/").split("/") + return all(p and p not in (".", "..") for p in parts) and ":" not in world_id + + +# -- setup guides ------------------------------------------------------------------ +# Shown in the app's per-game setup guide and in docs/GAMES.md. Written for the +# person setting it up the first time: what to do in the game before WorldSync +# can see the world, and what to tell the group. + +SETUP_STEPS: dict[str, tuple[str, ...]] = { + "dragonwilds": ( + "Start Dragonwilds, create or load the world you want to share, then quit to desktop.", + "In WorldSync, pick that world by its name from the in-game world list.", + "Characters are yours: everyone keeps their own character file, only the world travels. " + "Turn on Character travel (world menu → Characters) to take yours between your own PCs.", + ), + "valheim": ( + "Start Valheim, choose Start Game and select your world.", + "If the world is stored in Steam Cloud, use Manage Saves and Move to Local first, " + "otherwise WorldSync can't see it.", + "Quit to desktop, then pick the world by its name in WorldSync.", + "Characters stay on each player's PC, so everyone brings their own Viking.", + "Playing with mods? Everyone needs the same mods, the same as joining a normal server.", + ), + "enshrouded": ( + "Start Enshrouded, load the world you want to share once, then quit to desktop.", + "Enshrouded names worlds with an 8 character code. WorldSync lists them with the most " + "recently played first, so the top one is usually the right one.", + "With Steam Cloud saves on, the worlds live under Steam\\userdata. WorldSync looks " + "there too; if it still finds nothing, browse to Steam\\userdata\\\\1203620\\remote.", + "Characters are separate files, so every player keeps their own.", + ), + "palworld": ( + "The person who created the co-op world starts Palworld, loads it, then quits to desktop.", + "Worlds are folders with a long code name. WorldSync lists them with the most recently " + "played first.", + "Know the host quirk: Palworld ties the original host's character to their PC. When a " + "friend hosts the shared world, the original host's character can look reset. Everyone " + "else keeps theirs. PalworldSaveTools can move a host character if you need it.", + "This is for the in-game co-op world, not a dedicated server.", + ), + "core_keeper": ( + "Start Core Keeper, load the world, then quit to desktop.", + "Worlds are numbered by their slot on the world menu (slot 1 is file 0). Pick the slot " + "you play in.", + "Everyone in the group uses that same slot for this world. If a friend already has a " + "different world there, WorldSync backs it up before replacing it, but a free slot is " + "cleaner.", + "Characters are separate, so everyone keeps their own.", + ), + "sons_of_the_forest": ( + "The host starts a Multiplayer game, saves at a shelter or tent, then quits to desktop.", + "Multiplayer saves are numbered folders. WorldSync lists them with the most recently " + "played first.", + "The host's own inventory and stats live inside the save, so whoever hosts the shared " + "world plays with that host inventory. Guests keep theirs.", + ), + "v_rising": ( + "Start V Rising and host a Private Game, play a moment so it saves, then quit to desktop.", + "WorldSync shows the world by the server name you gave it.", + "Every vampire is stored per Steam account inside the world, so all friends keep their " + "own character whoever hosts. The game settings travel with the world too.", + ), + "grounded": ( + "Use the Steam version. Game Pass saves sit in a protected folder WorldSync can't reach.", + "Start Grounded, load the world, then quit to desktop.", + "Each world is its own folder. WorldSync lists them with the most recently played first.", + ), + "raft": ( + "Start Raft, load the world you want to share, then quit to desktop.", + "Not sure which folder it is? Load World in Raft has an Open Save Folder button.", + "Pick the world by its name in WorldSync.", + ), + "seven_days_to_die": ( + "Start 7 Days to Die, continue the save you want to share, then quit to desktop.", + "Pick the save by its name. For a random-gen map, the generated map folder travels " + "with it automatically.", + "The first share can be a few hundred MB. Let your cloud drive finish uploading before " + "a friend presses Play.", + "Everyone needs the same game version (the same Steam beta branch, if you use one).", + ), +} + +# Shown for every game, after the game's own steps. +COMMON_STEPS: tuple[str, ...] = ( + "Everyone in the group needs the game, a cloud drive app (Google Drive, Dropbox or " + "OneDrive) and WorldSync.", + "Always start the game with Play in WorldSync. It pulls the newest world first and shares " + "yours back when you close the game.", + "One person hosts at a time. Playing together still works the normal way: one person " + "hosts in-game and the others join; WorldSync makes sure that host has the latest world.", +) + +_HUMAN_TOKENS = { + "{LOCALAPPDATA}": "%LOCALAPPDATA%", + "{APPDATA}": "%APPDATA%", + "{LOCALLOW}": "%USERPROFILE%\\AppData\\LocalLow", + "{SAVEDGAMES}": "%USERPROFILE%\\Saved Games", + "{USERPROFILE}": "%USERPROFILE%", + "{DOCUMENTS}": "%USERPROFILE%\\Documents", + "{PROGRAMFILESX86}": "C:\\Program Files (x86)", +} + + +def setup_steps(profile: GameProfile) -> tuple[str, ...]: + return SETUP_STEPS.get(profile.id, ()) + + +def human_save_path(template: str) -> str: + """'{LOCALLOW}/Pal/*' -> '%USERPROFILE%\\AppData\\LocalLow\\Pal\\'.""" + text = template + for token, human in _HUMAN_TOKENS.items(): + text = text.replace(token, human) + parts = [] + for part in text.split("/"): + if part in ("*", "[0-9]*"): + part = "" + elif part == "v*": # V Rising's save-format folder + part = "v3" + elif "*" in part: + part = part.replace("*", "") + parts.append(part) + return "\\".join(parts) diff --git a/app/core/health.py b/app/core/health.py index 35325e5..bcc7fde 100644 --- a/app/core/health.py +++ b/app/core/health.py @@ -11,7 +11,6 @@ from dataclasses import dataclass from pathlib import Path -from . import paths from .sync import world_files # A real Dragonwilds .sav is comfortably larger than this; below it, assume @@ -30,12 +29,26 @@ class SaveHealth: primary_size: int = 0 -def check_local_save(save_dir, world_name: str) -> SaveHealth: +def _primary(files: list[Path], patterns) -> Path: + """The file that best represents the save: the .sav for Dragonwilds, + otherwise the biggest file (the world data, not an index or thumbnail).""" + if patterns is None: + return next((f for f in files if f.suffix.lower() == ".sav"), files[0]) + sized = [] + for f in files: + try: + sized.append((f.stat().st_size, f)) + except OSError: + continue + return max(sized, key=lambda t: t[0])[1] if sized else files[0] + + +def check_local_save(save_dir, world_name: str, patterns=None) -> SaveHealth: """Is there a plausibly-complete local save worth sharing?""" - files = world_files(Path(save_dir), world_name) + files = world_files(Path(save_dir), world_name, patterns) if not files: return SaveHealth(False, "no save files found") - primary = next((f for f in files if f.suffix.lower() == ".sav"), files[0]) + primary = _primary(files, patterns) try: size = primary.stat().st_size except OSError: @@ -45,7 +58,7 @@ def check_local_save(save_dir, world_name: str) -> SaveHealth: return SaveHealth(True, "", size) -def shared_still_syncing(sync_dir, world_name: str) -> bool: +def shared_still_syncing(sync_dir, world_name: str, patterns=None) -> bool: """True if the shared folder shows signs of an in-progress cloud download.""" folder = Path(sync_dir) if not folder.exists(): @@ -57,8 +70,19 @@ def shared_still_syncing(sync_dir, world_name: str) -> bool: return True except OSError: continue + files = world_files(folder, world_name, patterns) + if patterns is not None: + # folder worlds: a partial download can sit deep inside the world + if any(f.name.lower().endswith(PARTIAL_SUFFIXES) for f in files): + return True + if files: + try: + return _primary(files, patterns).stat().st_size == 0 + except OSError: + return False + return False # A world file that exists but is zero bytes is a classic half-synced state. - for f in world_files(folder, world_name): + for f in files: try: if f.suffix.lower() == ".sav" and f.stat().st_size == 0: return True diff --git a/app/core/invite.py b/app/core/invite.py index 77a035f..654e8dd 100644 --- a/app/core/invite.py +++ b/app/core/invite.py @@ -3,13 +3,20 @@ Fully local - the code is just compressed JSON (world name, shared folder name, optional cloud share link), base64url-encoded with a versioned prefix. No backend anywhere: the cloud drive itself is the transport. + +Two prefixes: ``DWS1.`` is the original Dragonwilds Sync format and is still +written for Dragonwilds worlds, so friends on 1.x can join. Every other game +uses ``WS1.`` with the game id inside; 1.x apps reject those cleanly instead +of copying the wrong game's files. """ import base64 import json import zlib -PREFIX = "DWS1." +PREFIX = "WS1." +LEGACY_PREFIX = "DWS1." +LEGACY_GAME = "dragonwilds" MAX_CODE_LEN = 2000 @@ -17,23 +24,33 @@ class InviteError(ValueError): """Raised when a code can't be decoded; message is user-friendly.""" -def encode(world_name: str, folder_name: str, share_link: str | None) -> str: +def encode(world_name: str, folder_name: str, share_link: str | None, + game: str = LEGACY_GAME, label: str | None = None) -> str: payload = {"v": 1, "w": world_name, "f": folder_name, "l": share_link or ""} + prefix = LEGACY_PREFIX + if game != LEGACY_GAME: + payload["g"] = game + prefix = PREFIX + if label and label != world_name: + payload["n"] = label raw = json.dumps(payload, separators=(",", ":")).encode("utf-8") packed = base64.urlsafe_b64encode(zlib.compress(raw, 9)).decode("ascii").rstrip("=") - return PREFIX + packed + return prefix + packed def decode(code: str) -> dict: - """Returns {world_name, folder_name, share_link}. Raises InviteError.""" + """Returns {world_name, folder_name, share_link, game}. Raises InviteError.""" code = "".join((code or "").split()) # tolerate whitespace/newlines from chat apps if not code: raise InviteError("That looks empty - paste the whole invite code.") if len(code) > MAX_CODE_LEN: raise InviteError("That's too long to be an invite code.") - if not code.startswith(PREFIX): - raise InviteError("That doesn't look like a Dragonwilds Sync invite code.") - packed = code[len(PREFIX):] + if code.startswith(LEGACY_PREFIX): + packed = code[len(LEGACY_PREFIX):] + elif code.startswith(PREFIX): + packed = code[len(PREFIX):] + else: + raise InviteError("That doesn't look like a WorldSync invite code.") try: padded = packed + "=" * (-len(packed) % 4) raw = zlib.decompress(base64.urlsafe_b64decode(padded)) @@ -47,4 +64,6 @@ def decode(code: str) -> dict: "world_name": str(payload["w"]), "folder_name": str(payload["f"]), "share_link": str(payload.get("l") or "") or None, + "game": str(payload.get("g") or LEGACY_GAME), + "label": str(payload.get("n") or "") or None, } diff --git a/app/core/logs.py b/app/core/logs.py index 1d03b51..1bbffb5 100644 --- a/app/core/logs.py +++ b/app/core/logs.py @@ -6,7 +6,7 @@ from . import paths -LOG_FILE = paths.LOG_DIR / "dragonwilds-sync.log" +LOG_FILE = paths.LOG_DIR / "worldsync.log" def setup_logging(): diff --git a/app/core/paths.py b/app/core/paths.py index 775f4bf..e0de044 100644 --- a/app/core/paths.py +++ b/app/core/paths.py @@ -1,9 +1,9 @@ -"""Well-known locations and game constants.""" +"""Well-known locations. Per-game paths live in games.py.""" import os from pathlib import Path -APP_ID = "DragonwildsSync" +APP_ID = "WorldSync" # Per-user app data (config, state, logs, safety backups). APP_DIR = Path(os.environ.get("APPDATA", str(Path.home()))) / APP_ID @@ -12,11 +12,15 @@ LOG_DIR = APP_DIR / "logs" BACKUP_DIR = APP_DIR / "backups" +# Before 2.0 the app was "Dragonwilds Sync" and lived here; copied over on first run. +LEGACY_APP_DIR = Path(os.environ.get("APPDATA", str(Path.home()))) / "DragonwildsSync" + # Config location used by the original CLI/Tkinter prototype; migrated on first run. LEGACY_DIR = Path.home() / ".dragonwilds_sync" LEGACY_CONFIG_PATH = LEGACY_DIR / "config.json" LEGACY_STATE_PATH = LEGACY_DIR / "state.json" +# Dragonwilds defaults, still used by the Dragonwilds-only extras. DEFAULT_SAVE_DIR = ( Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "RSDragonwilds" / "Saved" / "SaveGames" diff --git a/app/core/preflight.py b/app/core/preflight.py index 337f368..a8b6834 100644 --- a/app/core/preflight.py +++ b/app/core/preflight.py @@ -5,12 +5,10 @@ render as a checklist. """ -import os from dataclasses import dataclass from pathlib import Path -from . import clouds, game, health, paths -from .sync import get_shared_manifest, world_files +from . import clouds, config, game, health OK, WARN, FAIL = "ok", "warn", "fail" @@ -33,21 +31,24 @@ def _writable(folder: Path) -> bool: def run(cfg: dict, world: dict) -> list[Check]: - """cfg is the v2 global config; world is the active world dict.""" + """cfg is the global config; world is the active world dict.""" checks: list[Check] = [] - save_dir = Path(cfg.get("local_save_dir", "")) + flat = config.effective_cfg(cfg, world) + profile = config.world_game(world) + save_dir = Path(flat["local_save_dir"]) + patterns = flat["patterns"] world_name = world.get("world_name", "") sync_dir = Path(world.get("sync_dir", "")) # 1. Save folder if save_dir.exists(): - checks.append(Check("Game save folder", OK, str(save_dir))) + checks.append(Check(f"{profile.name} save folder", OK, str(save_dir))) else: - checks.append(Check("Game save folder", FAIL, - "Not found - set it in Settings.")) + checks.append(Check(f"{profile.name} save folder", FAIL, + "Not found - start the game once, or set it in Settings.")) # 2. The world save itself - hp = health.check_local_save(save_dir, world_name) + hp = health.check_local_save(save_dir, world_name, patterns) if hp.ok: checks.append(Check(f"World save “{world_name}”", OK, f"{hp.primary_size // 1024} KB")) @@ -88,20 +89,20 @@ def run(cfg: dict, world: dict) -> list[Check]: "None detected - saves won't reach friends without one.")) # 5. Still-syncing check - if sync_dir.exists() and health.shared_still_syncing(sync_dir, world_name): + if sync_dir.exists() and health.shared_still_syncing(sync_dir, world_name, patterns): checks.append(Check("Sync state", WARN, "The cloud folder looks like it's still downloading. " "Give it a minute.")) # 6. Game launch path - exe = cfg.get("exe_path") + exe = flat.get("exe_path") if exe and Path(exe).is_file(): checks.append(Check("Game launch", OK, "Direct exe configured.")) - elif game.find_game_process(): + elif game.find_game_process(flat["process_names"]): checks.append(Check("Game launch", OK, "Game is running right now.")) else: from . import steam - found = steam.find_game_exe() + found = steam.find_game_exe(profile) if found: checks.append(Check("Game launch", OK, "Found your Steam install.")) else: diff --git a/app/core/saga.py b/app/core/saga.py index fe25da9..c91bde7 100644 --- a/app/core/saga.py +++ b/app/core/saga.py @@ -107,7 +107,7 @@ def _humanize(ts: str) -> str:
{stats}

The chronicle

{entries} -
Written by Dragonwilds Sync · {updated}
+
Written by WorldSync · {updated}
""" diff --git a/app/core/statuspage.py b/app/core/statuspage.py index 48d8919..ba3638b 100644 --- a/app/core/statuspage.py +++ b/app/core/statuspage.py @@ -18,7 +18,7 @@ _TEMPLATE = """ -{world} · Dragonwilds Sync +{world} · WorldSync

{world}

-
Dragonwilds Sync · shared world status
+
WorldSync · shared world status
{headline}
{detail}
diff --git a/app/core/steam.py b/app/core/steam.py index 9014d28..426ec5f 100644 --- a/app/core/steam.py +++ b/app/core/steam.py @@ -4,7 +4,7 @@ import re from pathlib import Path -from . import paths +from . import games log = logging.getLogger("dwsync.steam") @@ -48,19 +48,52 @@ def _library_folders(steam_root: Path) -> list[Path]: return libraries -def find_game_exe() -> Path | None: - """Full path to RSDragonwilds.exe, or None if not found.""" +def _libraries() -> list[Path]: root = _steam_root() - if not root: - return None - for lib in _library_folders(root): - common = lib / "steamapps" / "common" + return _library_folders(root) if root else [] + + +def installed_app_ids(libraries: list[Path] | None = None) -> set[str]: + """Steam app ids with an install manifest in any library on this PC.""" + ids = set() + for lib in (libraries if libraries is not None else _libraries()): try: - candidates = list(common.glob("*Dragonwilds*/" + paths.GAME_PROCESS_NAME)) + for acf in (lib / "steamapps").glob("appmanifest_*.acf"): + m = re.fullmatch(r"appmanifest_(\d+)\.acf", acf.name) + if m: + ids.add(m.group(1)) except OSError: continue - for c in candidates: - if c.is_file(): - log.info("Found game install: %s", c) - return c + return ids + + +def _install_dir(lib: Path, app_id: str) -> Path | None: + acf = lib / "steamapps" / f"appmanifest_{app_id}.acf" + try: + text = acf.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + m = re.search(r'"installdir"\s+"([^"]+)"', text) + if not m: + return None + folder = lib / "steamapps" / "common" / m.group(1) + return folder if folder.is_dir() else None + + +def find_game_exe(profile=None, libraries: list[Path] | None = None) -> Path | None: + """Full path to the game's exe, or None if it isn't installed via Steam.""" + profile = profile or games.DRAGONWILDS + for lib in (libraries if libraries is not None else _libraries()): + folder = _install_dir(lib, profile.steam_app_id) + if not folder: + continue + for name in profile.process_names: + try: + hits = [p for p in folder.rglob(name) if p.is_file()] + except OSError: + continue + if hits: + hits.sort(key=lambda p: len(p.parts)) # the top-level exe, not a helper + log.info("Found %s install: %s", profile.name, hits[0]) + return hits[0] return None diff --git a/app/core/storage.py b/app/core/storage.py index 6fb56a9..0672618 100644 --- a/app/core/storage.py +++ b/app/core/storage.py @@ -3,6 +3,7 @@ import json import logging import os +import shutil from pathlib import Path from . import paths @@ -53,3 +54,29 @@ def load_state(): def save_state(state): write_json(paths.STATE_PATH, state) + + +def migrate_legacy_app_dir() -> bool: + """First run of 2.0: copy the Dragonwilds Sync data folder across. + + Only when the new folder has no config yet, and the old folder is left + untouched so going back to 1.x still works. Logs and UI caches aren't + worth carrying over. + """ + old, new = paths.LEGACY_APP_DIR, paths.APP_DIR + try: + if (new / "config.json").exists() or not (old / "config.json").exists(): + return False + new.mkdir(parents=True, exist_ok=True) + for item in old.iterdir(): + if item.name in ("logs", "ui", "app.lock", "update"): + continue + target = new / item.name + if item.is_dir(): + shutil.copytree(item, target, dirs_exist_ok=True) + else: + shutil.copy2(item, target) + return True + except OSError: + log.warning("Could not carry over the Dragonwilds Sync folder", exc_info=True) + return False diff --git a/app/core/sync.py b/app/core/sync.py index c3c8666..f2a37d7 100644 --- a/app/core/sync.py +++ b/app/core/sync.py @@ -30,6 +30,7 @@ the exact same code runs under pytest and behind the GUI. """ +import glob as _glob import hashlib import logging import shutil @@ -65,6 +66,7 @@ class SyncResult(Enum): PUSHED = auto() NOTHING_TO_PUSH = auto() # no local files matching the world name STALE_CANCELLED = auto() # user chose not to overwrite a newer shared save + WRONG_GAME = auto() # the shared folder holds a different game's world @dataclass @@ -87,12 +89,76 @@ def sha256_file(path: Path) -> str: return h.hexdigest() -def world_files(folder: Path, world_name: str) -> list[Path]: - """Every file in `folder` that belongs to this world (save + backup).""" +def world_files(folder: Path, world_name: str, patterns=None) -> list[Path]: + """Every file in `folder` that belongs to this world. + + ``patterns=None`` is the original rule (top-level files whose name starts + with the world name), kept exactly for Dragonwilds groups. Otherwise each + pattern is a glob relative to `folder` with ``{world}`` / ``{map}`` + placeholders, and matches may sit in subfolders. + """ folder = Path(folder) if not folder.exists(): return [] - return sorted(p for p in folder.glob(f"{world_name}*") if p.is_file()) + if patterns is None: + return sorted(p for p in folder.glob(f"{world_name}*") if p.is_file()) + if not world_name: + return [] # an empty id would turn "{world}/**/*" into the whole drive + safe = _glob.escape(world_name) + first = _glob.escape(world_name.split("/", 1)[0]) + found = {} + for pattern in patterns: + try: + matches = folder.glob(pattern.format(world=safe, map=first)) + for p in matches: + if p.is_file(): + found[p.relative_to(folder).as_posix()] = p + except (OSError, ValueError, NotImplementedError): + continue + return [found[k] for k in sorted(found)] + + +def _rel(path: Path, root: Path) -> Path: + try: + return Path(path).relative_to(root) + except ValueError: + return Path(Path(path).name) + + +def world_fingerprint(files: list[Path], root: Path, patterns=None) -> str | None: + """What "this save changed" is measured against. + + Legacy worlds hash the first file (the protocol v1 always used). Folder + worlds hash every file plus its relative path, so a new autosave or a + deleted one counts as a change too. + """ + if not files: + return None + if patterns is None: + return sha256_file(files[0]) + h = hashlib.sha256() + for f in files: + h.update(_rel(f, root).as_posix().encode("utf-8")) + h.update(b"\0") + h.update(sha256_file(f).encode("ascii")) + return h.hexdigest() + + +def _copy_world(files: list[Path], src_root: Path, dst_root: Path): + for f in files: + dest = Path(dst_root) / _rel(f, src_root) + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(f, dest) + + +def _remove_stale(dst_root: Path, world_name: str, patterns, keep: set[str]): + """Mirror mode: drop world files the source side no longer has.""" + for f in world_files(dst_root, world_name, patterns): + if _rel(f, dst_root).as_posix() not in keep: + try: + f.unlink() + except OSError: + logger.warning("Could not remove stale file %s", f) def get_shared_manifest(sync_dir: Path): @@ -119,8 +185,12 @@ def get_status(cfg, state) -> StatusSnapshot: ) -def _backup_files(files: list[Path], label: str, backup_root: Path): - """Copy `files` into a timestamped backup folder; prune old backups.""" +def _backup_files(files: list[Path], label: str, backup_root: Path, root: Path | None = None): + """Copy `files` into a timestamped backup folder; prune old backups. + + With `root`, files keep their path relative to it (folder worlds); + without, they're stored flat by name as before. + """ if not files: return None stamp = datetime.now().strftime("%Y%m%d-%H%M%S") @@ -130,10 +200,12 @@ def _backup_files(files: list[Path], label: str, backup_root: Path): n += 1 dest.mkdir(parents=True) for f in files: - shutil.copy2(f, dest / f.name) + target = dest / (_rel(f, root) if root is not None else Path(f).name) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(f, target) # Keep only the newest few backup folders. folders = sorted( - (p for p in Path(backup_root).iterdir() if p.is_dir()), + (p for p in Path(backup_root).iterdir() if p.is_dir() and p.name != "checkpoints"), key=lambda p: p.name, reverse=True, ) @@ -143,20 +215,43 @@ def _backup_files(files: list[Path], label: str, backup_root: Path): return dest +def _world_spec(cfg): + """(save_dir, world_name, patterns, mirror, game) from a flat cfg.""" + patterns = cfg.get("patterns") + return (Path(cfg["local_save_dir"]), cfg["world_name"], + list(patterns) if patterns is not None else None, + bool(cfg.get("mirror")), cfg.get("game")) + + +def _wrong_game(manifest, game) -> bool: + """True if the shared folder was made for a different game. + + Manifests from before WorldSync carry no game and are Dragonwilds; a + flat cfg without a game (tests, characters) skips the check. + """ + if not manifest or not game: + return False + return manifest.get("game", "dragonwilds") != game + + def do_pull(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): """Bring the local save up to the shared version. Returns (SyncResult, state). `state` is updated in place on success. """ sync_dir = Path(cfg["sync_dir"]) - save_dir = Path(cfg["local_save_dir"]) - world_name = cfg["world_name"] + save_dir, world_name, patterns, mirror, game = _world_spec(cfg) manifest = get_shared_manifest(sync_dir) if not manifest: log("No shared save yet - you'll be the first to share one after this session.") return SyncResult.NO_SHARED, state + if _wrong_game(manifest, game): + log(f"The shared folder holds a {manifest.get('game', 'dragonwilds')} world, " + f"not {game}. Nothing was copied.") + return SyncResult.WRONG_GAME, state + shared_version = manifest["version"] if shared_version <= state.get("last_applied_version", 0): log(f"Already up to date (v{shared_version}).") @@ -164,9 +259,9 @@ def do_pull(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): # Conflict check: the local save changed since our last known sync point # but was never pushed (e.g. played without the app / offline). - local_files = world_files(save_dir, world_name) + local_files = world_files(save_dir, world_name, patterns) if local_files and state.get("last_hash"): - current_hash = sha256_file(local_files[0]) + current_hash = world_fingerprint(local_files, save_dir, patterns) if current_hash != state["last_hash"]: proceed = confirm( "Overwrite your local progress?", @@ -179,7 +274,7 @@ def do_pull(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): log("Kept your local progress. Use “Save my progress now” first if you want to share it.") return SyncResult.CONFLICT_CANCELLED, state - shared_files = world_files(sync_dir, world_name) + shared_files = world_files(sync_dir, world_name, patterns) if not shared_files: log("A newer save is listed, but its files haven't appeared in the shared folder yet. " "Give your cloud folder a moment to finish syncing, then try again.") @@ -187,14 +282,18 @@ def do_pull(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): # Safety net: keep a local copy of whatever we're about to overwrite. if local_files: - _backup_files(local_files, f"local_v{state.get('last_applied_version', 0)}", backup_root) + _backup_files(local_files, f"local_v{state.get('last_applied_version', 0)}", backup_root, + root=save_dir if patterns is not None else None) save_dir.mkdir(parents=True, exist_ok=True) - for f in shared_files: - shutil.copy2(f, save_dir / f.name) + _copy_world(shared_files, sync_dir, save_dir) + if mirror: + _remove_stale(save_dir, world_name, patterns, + {_rel(f, sync_dir).as_posix() for f in shared_files}) state["last_applied_version"] = shared_version - state["last_hash"] = sha256_file(save_dir / shared_files[0].name) + state["last_hash"] = world_fingerprint( + world_files(save_dir, world_name, patterns), save_dir, patterns) log(f"Got the latest world - v{shared_version}, last played by {manifest.get('last_editor', 'a friend')}.") return SyncResult.PULLED, state @@ -205,15 +304,18 @@ def do_push(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): Returns (SyncResult, state). `state` is updated in place on success. """ sync_dir = Path(cfg["sync_dir"]) - save_dir = Path(cfg["local_save_dir"]) - world_name = cfg["world_name"] + save_dir, world_name, patterns, mirror, game = _world_spec(cfg) - local_files = world_files(save_dir, world_name) + local_files = world_files(save_dir, world_name, patterns) if not local_files: log(f"No save files found for “{world_name}” - nothing to share yet.") return SyncResult.NOTHING_TO_PUSH, state manifest = get_shared_manifest(sync_dir) + if _wrong_game(manifest, game): + log(f"The shared folder holds a {manifest.get('game', 'dragonwilds')} world, " + f"not {game}. Nothing was shared.") + return SyncResult.WRONG_GAME, state # Mirror of the pull-side conflict check: someone pushed while we played. last_applied = state.get("last_applied_version", 0) @@ -228,8 +330,9 @@ def do_push(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): log("Didn't share. Your progress is still on this machine - hit Play to sync up first.") return SyncResult.STALE_CANCELLED, state _backup_files( - world_files(sync_dir, world_name), + world_files(sync_dir, world_name, patterns), f"shared_v{manifest['version']}", backup_root, + root=sync_dir if patterns is not None else None, ) # Version base survives a corrupted/deleted manifest: never go backwards. @@ -237,8 +340,10 @@ def do_push(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): new_version = max(base, last_applied) + 1 sync_dir.mkdir(parents=True, exist_ok=True) - for f in local_files: - shutil.copy2(f, sync_dir / f.name) + _copy_world(local_files, save_dir, sync_dir) + if mirror: + _remove_stale(sync_dir, world_name, patterns, + {_rel(f, save_dir).as_posix() for f in local_files}) entry = { "version": new_version, @@ -248,17 +353,20 @@ def do_push(cfg, state, log, confirm, backup_root: Path = paths.BACKUP_DIR): history = (manifest.get("history", []) if manifest else []) history = (history + [entry])[-HISTORY_LIMIT:] - write_json(Path(sync_dir) / paths.MANIFEST_NAME, { + new_manifest = { "version": new_version, "last_editor": cfg["player_name"], "timestamp": entry["timestamp"], "world_name": world_name, "history": history, "app_schema": MANIFEST_SCHEMA, - }) + } + if game: + new_manifest["game"] = game + write_json(Path(sync_dir) / paths.MANIFEST_NAME, new_manifest) state["last_applied_version"] = new_version - state["last_hash"] = sha256_file(local_files[0]) + state["last_hash"] = world_fingerprint(local_files, save_dir, patterns) log(f"Shared your progress as v{new_version}. Friends will get it next time they hit Play.") return SyncResult.PUSHED, state diff --git a/app/core/update.py b/app/core/update.py index 28c49bb..bb3d414 100644 --- a/app/core/update.py +++ b/app/core/update.py @@ -55,7 +55,7 @@ def publish(sync_dir, version: str, exe_source, published_by: str, notes: str = update_dir = Path(sync_dir) / UPDATE_DIR_NAME update_dir.mkdir(parents=True, exist_ok=True) - filename = f"DragonwildsSync-{version}.exe" + filename = f"WorldSync-{version}.exe" shutil.copy2(exe_source, update_dir / filename) write_json(update_dir / UPDATE_MANIFEST, { "version": version, @@ -98,7 +98,7 @@ def build_swap_script(staged_exe: Path, target_exe: Path, script_path: Path) -> """Write the batch script that swaps the exe after this process exits.""" script = f"""@echo off setlocal -echo Updating Dragonwilds Sync... +echo Updating WorldSync... :waitloop timeout /t 1 /nobreak >nul copy /y "{staged_exe}" "{target_exe}" >nul 2>&1 diff --git a/app/core/webhook.py b/app/core/webhook.py index 9109699..c890c75 100644 --- a/app/core/webhook.py +++ b/app/core/webhook.py @@ -28,7 +28,7 @@ def build_request(url: str, text: str) -> urllib.request.Request: content_type = "text/plain; charset=utf-8" return urllib.request.Request( url, data=data, method="POST", - headers={"Content-Type": content_type, "User-Agent": "DragonwildsSync"}, + headers={"Content-Type": content_type, "User-Agent": "WorldSync"}, ) diff --git a/app/core/worldhistory.py b/app/core/worldhistory.py index bdf2e1c..7bba48d 100644 --- a/app/core/worldhistory.py +++ b/app/core/worldhistory.py @@ -14,7 +14,7 @@ from datetime import datetime from pathlib import Path -from .sync import world_files +from .sync import _copy_world, world_files log = logging.getLogger("dwsync.worldhistory") @@ -36,16 +36,19 @@ def _history_root(sync_dir) -> Path: def archive_version(sync_dir, world_name: str, version: int, - keep: int = VERSIONS_TO_KEEP) -> bool: + keep: int = VERSIONS_TO_KEEP, patterns=None) -> bool: """Copy the just-pushed world files into _history/v{version}; prune.""" try: - files = world_files(Path(sync_dir), world_name) + files = world_files(Path(sync_dir), world_name, patterns) if not files: return False dest = _history_root(sync_dir) / f"v{version}" dest.mkdir(parents=True, exist_ok=True) - for f in files: - shutil.copy2(f, dest / f.name) + if patterns is None: + for f in files: + shutil.copy2(f, dest / f.name) + else: + _copy_world(files, Path(sync_dir), dest) _prune(sync_dir, keep) log.info("Archived v%d to group history", version) return True @@ -78,7 +81,7 @@ def list_versions(sync_dir) -> list[ArchivedVersion]: m = re.fullmatch(r"v(\d+)", p.name) if not (p.is_dir() and m): continue - files = [f for f in p.iterdir() if f.is_file()] + files = [f for f in p.rglob("*") if f.is_file()] try: modified = datetime.fromtimestamp(max(f.stat().st_mtime for f in files)) \ if files else None diff --git a/app/main.py b/app/main.py index 7182d82..15900d9 100644 --- a/app/main.py +++ b/app/main.py @@ -10,7 +10,7 @@ from . import APP_NAME from .controller import Controller -from .core import paths +from .core import paths, storage from .core.logs import setup_logging from .ui import theme from .ui.window import MainWindow @@ -23,12 +23,15 @@ def resource_path(relative: str) -> Path: def main(): + migrated = storage.migrate_legacy_app_dir() log = setup_logging() log.info("---- %s starting ----", APP_NAME) + if migrated: + log.info("Carried settings over from Dragonwilds Sync") if sys.platform == "win32": # Give the process its own taskbar identity (icon grouping, pinning). - ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("DragonwildsSync.App") + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("WorldSync.App") app = QApplication(sys.argv) app.setApplicationName(APP_NAME) @@ -42,7 +45,7 @@ def main(): lock.setStaleLockTime(0) if not lock.tryLock(1): QMessageBox.information(None, APP_NAME, - "Dragonwilds Sync is already running - check your taskbar.") + f"{APP_NAME} is already running - check your taskbar.") return 0 theme.apply(app) diff --git a/app/ui/about_page.py b/app/ui/about_page.py index 4bc1f2c..a126bc6 100644 --- a/app/ui/about_page.py +++ b/app/ui/about_page.py @@ -1,12 +1,29 @@ """About: version, a short changelog, and one quiet credit.""" +import webbrowser + from PySide6.QtCore import Qt, Signal from PySide6.QtWidgets import QHBoxLayout, QLabel, QScrollArea, QVBoxLayout, QWidget from .. import __version__ +from ..core import games from . import icons, theme, widgets +from .library_page import TIP_URL CHANGELOG = [ + ("2.0.0", [ + "Dragonwilds Sync is now WorldSync: one app for every co-op world", + "Ten games to start: Dragonwilds, Valheim, Enshrouded, Palworld, Core Keeper, " + "Sons of the Forest, V Rising, Grounded, Raft and 7 Days to Die", + "A game library as the new home screen, with a picker that puts your " + "installed Steam games first", + "Every game has its own look, from Valheim's aurora to V Rising's blood moon", + "A step-by-step setup guide for every game (world menu → How to set up)", + "Finds each game's save folder and lists its worlds by when you last played", + "Folder-based worlds sync whole, including rotated autosaves", + "Refuses to copy one game's world into another", + "Your Dragonwilds worlds, settings and invite codes carry straight over", + ]), ("1.3.2", [ "Small cleanup: wording, version info and screenshots brought up to date", ]), @@ -71,22 +88,28 @@ def __init__(self, parent=None): root.addSpacing(18) mark = QLabel() - mark.setPixmap(icons.mark_pixmap(44)) + mark.setPixmap(icons.worldsync_mark(48)) mark.setAlignment(Qt.AlignHCenter) root.addWidget(mark) root.addSpacing(10) - name = QLabel("Dragonwilds Sync") + name = QLabel("WorldSync") name.setAlignment(Qt.AlignHCenter) name.setStyleSheet( f"font-family: '{theme.deco_family()}'; font-size: 24px; font-weight: 700;" f"color: {theme.GOLD_TEXT}; letter-spacing: 1px;") root.addWidget(name) - ver = QLabel(f"Version {__version__}") + ver = QLabel(f"Version {__version__} · {len(games.ALL)} games · free and open source") ver.setAlignment(Qt.AlignHCenter) ver.setStyleSheet(f"color: {theme.TEXT_DIM}; font-size: 12px;") root.addWidget(ver) + if TIP_URL: + root.addSpacing(10) + tip = widgets.make_button("Buy me a coffee", "ghost", "heart", height=32) + tip.setToolTip("WorldSync stays free. Tips keep new games coming.") + tip.clicked.connect(lambda: webbrowser.open(TIP_URL)) + root.addWidget(tip, 0, Qt.AlignHCenter) root.addSpacing(16) scroll = QScrollArea() diff --git a/app/ui/addgame_page.py b/app/ui/addgame_page.py new file mode 100644 index 0000000..2f8d149 --- /dev/null +++ b/app/ui/addgame_page.py @@ -0,0 +1,211 @@ +"""Add a game: every supported game, the ones installed on this PC first. + +Each row is a small poster of the game's scene with its name in the game's +own typeface. Steam installs are detected from the library manifests, so +the games you actually own float to the top. +""" + +import threading +import webbrowser + +from PySide6.QtCore import QRectF, Qt, Signal +from PySide6.QtGui import QColor, QFont, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import (QHBoxLayout, QLabel, QLineEdit, QScrollArea, + QVBoxLayout, QWidget) + +from ..core import games, steam +from . import gamethemes, icons, theme, widgets +from .library_page import game_font, game_thumb + +ROW_H = 74 +THUMB_W = 104 +REQUEST_URL = "https://github.com/AndorManu/worldsync/issues/new?labels=game-request&title=Game+request:+" + + +class GameRow(QWidget): + clicked = Signal(str) + + def __init__(self, profile, installed: bool, in_library: bool, parent=None): + super().__init__(parent) + self.profile = profile + self.installed = installed + self.in_library = in_library + self._hover = False + self.setFixedHeight(ROW_H) + self.setCursor(Qt.PointingHandCursor) + self.setAttribute(Qt.WA_Hover, True) + + def mousePressEvent(self, e): + if e.button() == Qt.LeftButton: + self.clicked.emit(self.profile.id) + + def event(self, e): + if e.type() in (e.Type.HoverEnter, e.Type.HoverLeave): + self._hover = e.type() == e.Type.HoverEnter + self.update() + return super().event(e) + + def _badge(self, p, x, y, text, color): + f = QFont(self.font().family()) + f.setPixelSize(9) + f.setWeight(QFont.Bold) + f.setLetterSpacing(QFont.AbsoluteSpacing, 0.6) + p.setFont(f) + w = p.fontMetrics().horizontalAdvance(text) + 14 + c = QColor(color) + fill = QColor(c) + fill.setAlphaF(0.16) + p.setPen(QPen(c, 1)) + p.setBrush(fill) + p.drawRoundedRect(QRectF(x, y, w, 17), 8.5, 8.5) + p.drawText(QRectF(x, y, w, 17), Qt.AlignCenter, text) + return x + w + 6 + + def paintEvent(self, e): + tok = gamethemes.get(self.profile.id).tokens() + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing) + r = QRectF(self.rect()).adjusted(1, 1, -1, -1) + p.setPen(QPen(QColor(tok["ACCENT"] if self._hover else theme.BORDER_SOFT), 1.2)) + p.setBrush(QColor(theme.SURFACE_2 if self._hover else theme.SURFACE)) + p.drawRoundedRect(r, 12, 12) + + thumb = QRectF(8, 8, THUMB_W, ROW_H - 16) + clip = QPainterPath() + clip.addRoundedRect(thumb, 8, 8) + p.save() + p.setClipPath(clip) + p.drawPixmap(thumb.toRect(), game_thumb(self.profile.id, THUMB_W * 2, (ROW_H - 16) * 2)) + p.restore() + + x = THUMB_W + 22 + p.setPen(QColor("#FFFFFF")) + p.setFont(game_font(self.profile.id, 15)) + p.drawText(QRectF(x, 10, r.width() - x - 10, 22), Qt.AlignLeft | Qt.AlignVCenter, + self.profile.name) + f = QFont(self.font()) + f.setPixelSize(12) + p.setFont(f) + p.setPen(QColor(theme.TEXT_DIM)) + p.drawText(QRectF(x, 31, r.width() - x - 10, 18), Qt.AlignLeft | Qt.AlignVCenter, + self.profile.tagline) + bx = x + if self.in_library: + bx = self._badge(p, bx, 50, "IN LIBRARY", theme.TEXT_DIM) + if self.installed: + bx = self._badge(p, bx, 50, "INSTALLED", tok["ACCENT"]) + if not self.profile.verified: + self._badge(p, bx, 50, "BETA", tok["EMBER"]) + p.end() + + +class AddGamePage(QWidget): + game_chosen = Signal(str) + back_requested = Signal() + installed_ready = Signal(object) + + def __init__(self, parent=None): + super().__init__(parent) + self._installed: set[str] = set() + self._library: set[str] = set() + self._rows: list[GameRow] = [] + + root = QVBoxLayout(self) + root.setContentsMargins(24, 6, 24, 18) + root.setSpacing(12) + + header = QHBoxLayout() + back = widgets.icon_button("chevron-left", theme.TEXT_DIM, tooltip="Back") + back.clicked.connect(self.back_requested.emit) + header.addWidget(back) + self.title = QLabel("Add a game") + self.title.setStyleSheet("font-size: 20px; font-weight: 650;") + header.addWidget(self.title) + header.addStretch(1) + root.addLayout(header) + + self.sub = QLabel("Pick the game your group shares a world in. " + "Games installed through Steam are at the top.") + self.sub.setWordWrap(True) + self.sub.setStyleSheet(f"color: {theme.TEXT_DIM}; font-size: 12.5px;") + root.addWidget(self.sub) + + self.search = QLineEdit() + self.search.setPlaceholderText("Search games") + self.search.setClearButtonEnabled(True) + self.search.setFixedHeight(38) + self.search.addAction(icons.icon("search", theme.TEXT_FAINT, 16), + QLineEdit.LeadingPosition) + self.search.textChanged.connect(self._filter) + root.addWidget(self.search) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + holder = QWidget() + holder.setStyleSheet("background: transparent;") + self.list_box = QVBoxLayout(holder) + self.list_box.setContentsMargins(0, 0, 4, 0) + self.list_box.setSpacing(8) + self.list_box.addStretch(1) + scroll.setWidget(holder) + root.addWidget(scroll, 1) + + self.empty = QLabel("No game matches that search.") + self.empty.setAlignment(Qt.AlignCenter) + self.empty.setStyleSheet(f"color: {theme.TEXT_FAINT}; font-size: 12.5px;") + self.empty.setVisible(False) + root.addWidget(self.empty) + + foot = QHBoxLayout() + foot.addStretch(1) + req = widgets.make_button("Missing a game? Ask for it", "subtle", "external", height=28) + req.clicked.connect(lambda: webbrowser.open(REQUEST_URL)) + foot.addWidget(req) + root.addLayout(foot) + + self.installed_ready.connect(self._on_installed) + + # -- public ----------------------------------------------------------------- + def open(self, library_ids, first_run=False): + self._library = set(library_ids) + self.title.setText("Pick your first game" if first_run else "Add a game") + self.search.clear() + self._rebuild() + threading.Thread(target=self._detect, daemon=True, name="steam-scan").start() + + # -- internals -------------------------------------------------------------- + def _detect(self): + try: + ids = steam.installed_app_ids() + except Exception: + ids = set() + self.installed_ready.emit(ids) + + def _on_installed(self, app_ids): + self._installed = {g.id for g in games.ALL if g.steam_app_id in app_ids} + self._rebuild() + + def _rebuild(self): + for row in self._rows: + row.deleteLater() + self._rows = [] + + def order(g): + return (g.id in self._library, g.id not in self._installed, not g.verified, g.name) + + for i, prof in enumerate(sorted(games.ALL, key=order)): + row = GameRow(prof, prof.id in self._installed, prof.id in self._library) + row.clicked.connect(self.game_chosen.emit) + self.list_box.insertWidget(i, row) + self._rows.append(row) + self._filter(self.search.text()) + + def _filter(self, text): + q = (text or "").strip().lower() + shown = 0 + for row in self._rows: + hit = not q or q in row.profile.name.lower() or q in row.profile.tagline.lower() + row.setVisible(hit) + shown += hit + self.empty.setVisible(shown == 0) diff --git a/app/ui/backups_page.py b/app/ui/backups_page.py index 04d4c47..a1dab69 100644 --- a/app/ui/backups_page.py +++ b/app/ui/backups_page.py @@ -78,7 +78,7 @@ def __init__(self, parent=None): def _new_checkpoint(self): name, ok = QInputDialog.getText( self, "New checkpoint", "Name this snapshot of your current save:", - QLineEdit.Normal, "Before the dragon") + QLineEdit.Normal, "Before the boss") if ok and name.strip(): self.checkpoint_requested.emit(name.strip()) diff --git a/app/ui/banner.py b/app/ui/banner.py index b556d9f..2817be9 100644 --- a/app/ui/banner.py +++ b/app/ui/banner.py @@ -1,25 +1,18 @@ """Procedural world-art hero banner. -No bundled image files - every world's landscape is painted from a seed -derived from its name, so each world looks distinct and consistent across -runs and machines. Layered ridge silhouettes, a moon with a soft halo, mist -bands, and a few drifting embers, all tinted by the world's accent colour. -A bottom scrim keeps the overlaid title legible and blends into the app. +No bundled image files: the active game's scene (scenes.py) is painted from +a seed derived from the world name, so each world looks distinct and +consistent across runs and machines. A bottom scrim keeps the overlaid +title legible and blends the art into the app background. """ import hashlib -import math -import random -from PySide6.QtCore import QPointF, QRectF, Qt, QTimer -from PySide6.QtGui import (QBrush, QColor, QLinearGradient, QPainter, - QPainterPath, QRadialGradient) +from PySide6.QtCore import QRectF, Qt, QTimer +from PySide6.QtGui import QBrush, QColor, QLinearGradient, QPainter from PySide6.QtWidgets import QWidget -from . import theme - -RIDGE_LAYERS = 4 -EMBER_COUNT = 16 +from . import scenes, theme def _seed(world_name: str) -> int: @@ -33,12 +26,10 @@ def __init__(self, height=168, parent=None): self.setFixedHeight(height) self.setAttribute(Qt.WA_StyledBackground, False) self._world = "" - self._accent = QColor(theme.ACCENT) - self._ridges: list[list[QPointF]] = [] - self._moon = (0.72, 0.4, 26.0) # x-frac, y-frac, radius - self._cache_key = None - self._embers = [] + self._scene_id = None + self._scene = None self._t = 0.0 + self.set_scene(theme.scene()) self._timer = QTimer(self) self._timer.setInterval(40) # ~25 fps, gentle @@ -47,11 +38,15 @@ def __init__(self, height=168, parent=None): # -- public ------------------------------------------------------------ def set_world(self, world_name: str, accent: str | None = None): self._world = world_name or "" - if accent: - c = QColor(accent) - if c.isValid(): - self._accent = c - self._cache_key = None + self.update() + + def set_scene(self, scene_id: str): + """Follow the active theme: its scene, accent and ember colours.""" + key = (scene_id, theme.ACCENT, theme.EMBER) + if key == self._scene_id: + return + self._scene_id = key + self._scene = scenes.make(scene_id, theme.ACCENT, theme.EMBER) self.update() # -- lifecycle --------------------------------------------------------- @@ -65,112 +60,27 @@ def hideEvent(self, e): def _tick(self): self._t += 0.04 - for em in self._embers: - em["y"] -= em["speed"] - em["x"] += math.sin(self._t * em["drift"] + em["phase"]) * 0.15 - if em["y"] < -0.05: - em["y"] = 1.05 - em["x"] = random.random() self.update() - # -- scene build (cached per size+seed) -------------------------------- - def _rebuild(self, w, h): - rng = random.Random(_seed(self._world)) - self._ridges = [] - for layer in range(RIDGE_LAYERS): - pts = [] - # nearer layers sit lower and are jaggier - base = 0.30 + layer * 0.17 - rough = 0.05 + layer * 0.05 - steps = 7 + layer * 3 - for i in range(steps + 1): - x = i / steps - y = base + (rng.random() - 0.5) * rough * 2 \ - + math.sin(x * math.pi * (1 + layer)) * 0.03 * (rng.random() + 0.4) - pts.append(QPointF(x * w, y * h)) - self._ridges.append(pts) - self._moon = (0.18 + rng.random() * 0.64, 0.26 + rng.random() * 0.18, - 20.0 + rng.random() * 12.0) - self._embers = [{ - "x": rng.random(), "y": rng.random(), - "speed": 0.0016 + rng.random() * 0.0034, - "size": 1.0 + rng.random() * 2.2, - "phase": rng.random() * 6.28, "drift": 0.6 + rng.random() * 1.2, - } for _ in range(EMBER_COUNT)] - self._cache_key = (w, h, self._world) - # -- painting ---------------------------------------------------------- def paintEvent(self, e): w, h = self.width(), self.height() - if self._cache_key != (w, h, self._world): - self._rebuild(w, h) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) + p.setClipRect(self.rect()) + self._scene.ensure(w, h, _seed(self._world)) + self._scene.paint(p, self._t) - hue = self._accent.hueF() - if hue < 0: - hue = 0.42 - - # rounded-top clip so the banner tucks under the titlebar cleanly - clip = QPainterPath() - clip.addRect(QRectF(0, 0, w, h)) - p.setClipPath(clip) - - # sky - sky = QLinearGradient(0, 0, 0, h) - sky.setColorAt(0.0, QColor.fromHsvF(hue, 0.55, 0.20)) - sky.setColorAt(0.55, QColor.fromHsvF((hue + 0.03) % 1.0, 0.5, 0.09)) - sky.setColorAt(1.0, QColor("#070A0E")) - p.fillRect(self.rect(), QBrush(sky)) - - # moon + halo - mx, my, mr = self._moon - cx, cy = mx * w, my * h - halo = QRadialGradient(cx, cy, mr * 3.2) - glow = QColor.fromHsvF(hue, 0.30, 1.0) - glow.setAlphaF(0.28) - halo.setColorAt(0.0, glow) - halo.setColorAt(1.0, QColor(0, 0, 0, 0)) - p.setBrush(QBrush(halo)) - p.setPen(Qt.NoPen) - p.drawEllipse(QPointF(cx, cy), mr * 3.2, mr * 3.2) - disc = QColor.fromHsvF(hue, 0.12, 0.98) - p.setBrush(QBrush(disc)) - p.drawEllipse(QPointF(cx, cy), mr, mr) - - # ridges, back (lighter, tinted) to front (near black) - for i, pts in enumerate(self._ridges): - t = i / (RIDGE_LAYERS - 1) - val = 0.16 * (1 - t) + 0.03 - sat = 0.42 * (1 - t) - color = QColor.fromHsvF(hue, sat, val) - path = QPainterPath() - path.moveTo(pts[0].x(), h) - for pt in pts: - path.lineTo(pt) - path.lineTo(pts[-1].x(), h) - path.closeSubpath() - p.setBrush(QBrush(color)) - p.setPen(Qt.NoPen) - p.drawPath(path) - - # embers rising in front of the ridges - ember = QColor(theme.EMBER_HI) - for em in self._embers: - ex, ey = em["x"] * w, em["y"] * h - if ey < h * 0.35: - continue - a = max(0.0, min(0.8, (em["y"] - 0.35) * 1.1)) - a *= 0.6 + 0.4 * math.sin(self._t * 2 + em["phase"]) - ember.setAlphaF(max(0.0, a)) - p.setBrush(QBrush(ember)) - p.drawEllipse(QPointF(ex, ey), em["size"], em["size"]) - - # bottom scrim for text legibility + blend into app bg + # bottom scrim for text legibility + blend into the app background + bg = QColor(theme.BG) scrim = QLinearGradient(0, h * 0.35, 0, h) - scrim.setColorAt(0.0, QColor(6, 9, 13, 0)) - scrim.setColorAt(0.72, QColor(6, 9, 13, 150)) - scrim.setColorAt(1.0, QColor(10, 13, 18, 235)) + c0, c1, c2 = QColor(bg), QColor(bg), QColor(bg) + c0.setAlpha(0) + c1.setAlpha(150) + c2.setAlpha(235) + scrim.setColorAt(0.0, c0) + scrim.setColorAt(0.72, c1) + scrim.setColorAt(1.0, c2) p.fillRect(QRectF(0, h * 0.35, w, h * 0.65), QBrush(scrim)) # faint vignette on the sides diff --git a/app/ui/format.py b/app/ui/format.py index c593f24..b153d60 100644 --- a/app/ui/format.py +++ b/app/ui/format.py @@ -36,6 +36,15 @@ def humanize(ts: str) -> str: return f"{local.day} {local.strftime('%b')}" +def relative_time(dt: datetime) -> str: + """The same wording as humanize(), for a local (naive) datetime.""" + if dt is None: + return "" + if dt.tzinfo is None: + dt = dt.astimezone() + return humanize(dt.astimezone(timezone.utc).isoformat()) + + def initials(name: str) -> str: parts = [p for p in (name or "?").split() if p] if not parts: diff --git a/app/ui/gamethemes.py b/app/ui/gamethemes.py new file mode 100644 index 0000000..7931d4e --- /dev/null +++ b/app/ui/gamethemes.py @@ -0,0 +1,151 @@ +"""Every game gets its own look: palette, typefaces and banner scene. + +A theme is a handful of base colours; the hover / pressed / surface shades +are derived so each one stays internally consistent. Text greys are shared +by every theme on purpose - legibility shouldn't change with the game. + +Typefaces are the bundled Cinzel family plus fonts that ship with every +Windows 10/11 install, so nothing extra has to be downloaded. +""" + +import colorsys +from dataclasses import dataclass, field + + +def _rgb(hex_color: str) -> tuple[float, float, float]: + h = hex_color.lstrip("#") + return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) + + +def _hex(r: float, g: float, b: float) -> str: + return "#{:02X}{:02X}{:02X}".format(*(max(0, min(255, round(c * 255))) for c in (r, g, b))) + + +def shade(hex_color: str, light: float = 0.0, sat: float = 0.0) -> str: + """Shift lightness/saturation in HLS space (-1..1 steps, clamped).""" + h, l, s = colorsys.rgb_to_hls(*_rgb(hex_color)) + return _hex(*colorsys.hls_to_rgb(h, max(0, min(1, l + light)), max(0, min(1, s + sat)))) + + +def rgba(hex_color: str, alpha: float) -> str: + r, g, b = (round(c * 255) for c in _rgb(hex_color)) + return f"rgba({r}, {g}, {b}, {alpha})" + + +@dataclass(frozen=True) +class GameTheme: + id: str + bg: str # window base + surface: str # cards + accent: str # the "go / play" colour + accent2: str # gradient partner for the primary button + on_accent: str # text on the accent + ember: str # identity colour: section labels, flourishes + gold_text: str # legible warm text over art + display: str # titles and section labels + deco: str # hero world name + voice: str # flavour lines + scene: str # banner painter in scenes.py + title_spacing: int = 3 + caps: bool = True # display text in capitals + overrides: dict = field(default_factory=dict, hash=False, compare=False) + + # derived --------------------------------------------------------------- + def tokens(self) -> dict[str, str]: + return { + "BG": self.bg, + "BG_HI": shade(self.bg, 0.035, 0.05), + "BG_LO": shade(self.bg, -0.03), + "SURFACE": self.surface, + "SURFACE_2": shade(self.surface, 0.035), + "SURFACE_GLASS": rgba(shade(self.surface, 0.04), 0.74), + "FIELD_BG": shade(self.surface, -0.025), + "BORDER": shade(self.surface, 0.07), + "BORDER_SOFT": shade(self.surface, 0.035), + "BORDER_GOLD": shade(self.ember, -0.32, -0.3), + "ACCENT": self.accent, + "ACCENT_HOVER": shade(self.accent, 0.07), + "ACCENT_PRESSED": shade(self.accent, -0.09), + "ACCENT_TEAL": self.accent2, + "ACCENT_TEAL_HI": shade(self.accent2, 0.07), + "ACCENT_TEAL_LO": shade(self.accent2, -0.09), + "ON_ACCENT": self.on_accent, + "EMBER": self.ember, + "EMBER_HI": shade(self.ember, 0.1), + "EMBER_DEEP": shade(self.ember, -0.12), + "EMBER_PRESSED": shade(self.ember, -0.2), + "GOLD_TEXT": self.gold_text, + } | self.overrides + + +THEMES: dict[str, GameTheme] = {t.id: t for t in ( + # WorldSync's own home: deep ink with a cool signal blue and a warm spark. + GameTheme("library", bg="#0A0C14", surface="#121624", accent="#7A9BFF", + accent2="#5CD6C9", on_accent="#070B1A", ember="#F2B66B", + gold_text="#E9D7B8", display="Bahnschrift SemiBold", + deco="Bahnschrift SemiBold", voice="Georgia", scene="library", + title_spacing=4), + # The original look, unchanged. + GameTheme("dragonwilds", bg="#0A0D12", surface="#12191F", accent="#3ECF8E", + accent2="#1FA89B", on_accent="#07130D", ember="#E8A23D", + gold_text="#E6C892", display="Cinzel", deco="Cinzel Decorative", + voice="EB Garamond", scene="dragonwilds", + overrides={"BG_HI": "#10161E", "BG_LO": "#070A0E", "SURFACE_2": "#1A232C", + "SURFACE_GLASS": "rgba(22, 30, 39, 0.72)", "FIELD_BG": "#0D131A", + "BORDER": "#222E39", "BORDER_SOFT": "#19222C", + "BORDER_GOLD": "#3A3223", "ACCENT_HOVER": "#55DCA0", + "ACCENT_PRESSED": "#29A872", "ACCENT_TEAL_HI": "#23BCAD", + "ACCENT_TEAL_LO": "#17897E", "EMBER_HI": "#F6C56A", + "EMBER_DEEP": "#B9761F", "EMBER_PRESSED": "#8F5A16"}), + # Aurora over the tenth world; bronze for the runes. + GameTheme("valheim", bg="#080D12", surface="#101920", accent="#55D6B4", + accent2="#3A9FC4", on_accent="#04140F", ember="#C99A55", + gold_text="#E2CFA8", display="Cinzel", deco="Cinzel", + voice="Constantia", scene="valheim", title_spacing=5), + # The Shroud: violet fog against a flame. + GameTheme("enshrouded", bg="#0C0A12", surface="#16121F", accent="#B88CFF", + accent2="#7C5BE0", on_accent="#120A21", ember="#FF8F4A", + gold_text="#F0D2B6", display="Georgia", deco="Georgia", + voice="Georgia", scene="enshrouded", caps=False, title_spacing=1), + # Bright, round and friendly: sky blue and sunshine. + GameTheme("palworld", bg="#0A1018", surface="#111B27", accent="#4DBBFF", + accent2="#2F8CFF", on_accent="#04121F", ember="#FFD447", + gold_text="#FFE8A3", display="Segoe UI Black", deco="Segoe UI Black", + voice="Segoe UI", scene="palworld", caps=False, title_spacing=0), + # Glowing core crystals in a dark cave; pixel scene, monospace type. + GameTheme("core_keeper", bg="#090B10", surface="#12151D", accent="#5FE3F2", + accent2="#3C9BE6", on_accent="#031418", ember="#FFB54D", + gold_text="#F3D9A8", display="Consolas", deco="Consolas", + voice="Consolas", scene="core_keeper", title_spacing=2), + # Survival horror: blood and bone among the pines. + GameTheme("sons_of_the_forest", bg="#0A0B0A", surface="#141614", accent="#D9493C", + accent2="#9E2B24", on_accent="#FFF1EC", ember="#D8CBB0", + gold_text="#E4DAC4", display="Bahnschrift SemiCondensed", + deco="Bahnschrift SemiBold Condensed", voice="Georgia", + scene="sons_of_the_forest", title_spacing=4), + # Gothic: blood moon crimson and a royal violet. + GameTheme("v_rising", bg="#0C080C", surface="#181019", accent="#E33A55", + accent2="#9A2A5E", on_accent="#FFF0F3", ember="#A98BE8", + gold_text="#E6D0E8", display="Cinzel", deco="Cinzel Decorative", + voice="EB Garamond", scene="v_rising", title_spacing=4), + # Backyard sunshine: leaf green and orange juice. + GameTheme("grounded", bg="#0A0F09", surface="#121A10", accent="#93D640", + accent2="#4FAE3A", on_accent="#0B1504", ember="#FFA53D", + gold_text="#F6E1A6", display="Trebuchet MS", deco="Trebuchet MS", + voice="Trebuchet MS", scene="grounded", caps=False, title_spacing=0), + # Open water at sunset. + GameTheme("raft", bg="#071017", surface="#0E1B24", accent="#33CFE0", + accent2="#1E8FB8", on_accent="#03161B", ember="#FF8466", + gold_text="#FFD9C4", display="Franklin Gothic Medium", + deco="Franklin Gothic Medium", voice="Georgia", scene="raft", + title_spacing=2), + # Wasteland: rust, hazard yellow and a red sky. + GameTheme("seven_days_to_die", bg="#0D0A08", surface="#1A1410", accent="#EE7A2F", + accent2="#B8461E", on_accent="#1A0B03", ember="#E8C532", + gold_text="#EAD9B0", display="Impact", deco="Impact", + voice="Bahnschrift", scene="seven_days_to_die", title_spacing=3), +)} + + +def get(theme_id: str | None) -> GameTheme: + return THEMES.get(theme_id or "library", THEMES["library"]) diff --git a/app/ui/guide_page.py b/app/ui/guide_page.py new file mode 100644 index 0000000..71a8e71 --- /dev/null +++ b/app/ui/guide_page.py @@ -0,0 +1,152 @@ +"""Setup guide: how to get one game ready for WorldSync, step by step. + +Opened from the game's setup flow and from the world menu. It shows what to +do in the game first, where the saves live (and whether they were found on +this PC), and the few rules that hold for every game. +""" + +import os + +from PySide6.QtCore import Qt, Signal +from PySide6.QtWidgets import (QHBoxLayout, QLabel, QScrollArea, QVBoxLayout, + QWidget) + +from ..core import games +from . import theme, widgets +from .banner import WorldBanner + + +def _step_row(number: int, text: str) -> QWidget: + row = QWidget() + box = QHBoxLayout(row) + box.setContentsMargins(0, 0, 0, 0) + box.setSpacing(12) + badge = QLabel(str(number)) + badge.setFixedSize(24, 24) + badge.setAlignment(Qt.AlignCenter) + badge.setStyleSheet( + f"background: {theme.ACCENT}; color: {theme.ON_ACCENT}; border-radius: 12px;" + "font-size: 12px; font-weight: 700;") + box.addWidget(badge, 0, Qt.AlignTop) + label = QLabel(text) + label.setWordWrap(True) + label.setStyleSheet(f"color: {theme.TEXT}; font-size: 12.5px;") + box.addWidget(label, 1) + return row + + +def _bullet_row(text: str) -> QLabel: + label = QLabel(f"· {text}") + label.setWordWrap(True) + label.setStyleSheet(f"color: {theme.TEXT_DIM}; font-size: 12.5px;") + return label + + +class GuidePage(QWidget): + back_requested = Signal() + + def __init__(self, parent=None): + super().__init__(parent) + self._found = None + root = QVBoxLayout(self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + + hero = QWidget() + hero.setFixedHeight(112) + self.banner = WorldBanner(112, hero) + overlay = QWidget(hero) + overlay.setStyleSheet("background: transparent;") + ov = QVBoxLayout(overlay) + ov.setContentsMargins(14, 8, 18, 12) + top = QHBoxLayout() + back = widgets.icon_button("chevron-left", "#FFFFFF", tooltip="Back") + back.clicked.connect(self.back_requested.emit) + top.addWidget(back) + top.addStretch(1) + ov.addLayout(top) + ov.addStretch(1) + self.title = QLabel("") + ov.addWidget(self.title) + hero.resizeEvent = lambda e: (self.banner.setGeometry(0, 0, hero.width(), 112), + overlay.setGeometry(0, 0, hero.width(), 112)) + root.addWidget(hero) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.body = QWidget() + self.body.setStyleSheet("background: transparent;") + self.box = QVBoxLayout(self.body) + self.box.setContentsMargins(24, 14, 22, 20) + self.box.setSpacing(10) + scroll.setWidget(self.body) + root.addWidget(scroll, 1) + + # -- public ----------------------------------------------------------------- + def load(self, profile, save_dir: str = ""): + self.banner.set_scene(theme.scene()) + self.banner.set_world(profile.name) + self.title.setText(f"Setting up {profile.short}") + self.title.setStyleSheet( + "background: transparent; color: #FFFFFF;" + f"font-family: '{theme.deco_family()}'; font-size: 24px; font-weight: 700;") + + while self.box.count(): + item = self.box.takeAt(0) + if item.widget(): + item.widget().deleteLater() + + if not profile.verified: + beta = QLabel(f"{profile.name} support is in beta: it follows the save layout the " + f"community documents. Every overwrite is backed up first, and " + f"reports on GitHub move it to tested.") + beta.setWordWrap(True) + beta.setStyleSheet( + "background: rgba(242,180,65,0.08); border: 1px solid rgba(242,180,65,0.28);" + f"border-radius: 10px; padding: 10px 12px; color: {theme.TEXT_DIM};" + "font-size: 11.5px;") + self.box.addWidget(beta) + + self._section("In the game") + for i, step in enumerate(games.setup_steps(profile), 1): + self.box.addWidget(_step_row(i, step)) + + self._section("Where the saves live") + for template in profile.save_roots: + path = QLabel(games.human_save_path(template)) + path.setWordWrap(True) + path.setTextInteractionFlags(Qt.TextSelectableByMouse) + path.setStyleSheet( + f"background: {theme.FIELD_BG}; border: 1px solid {theme.BORDER};" + "border-radius: 8px; padding: 8px 10px; font-family: Consolas, monospace;" + f"font-size: 11.5px; color: {theme.TEXT_DIM};") + self.box.addWidget(path) + found = save_dir if save_dir and os.path.isdir(save_dir) else None + self._found = found + status_row = QHBoxLayout() + status = QLabel("Found on this PC." if found else + "Not on this PC yet. Start the game once and load a world, " + "then WorldSync finds it.") + status.setWordWrap(True) + status.setStyleSheet( + f"color: {theme.ACCENT if found else theme.TEXT_FAINT}; font-size: 12px;") + status_row.addWidget(status, 1) + if found: + open_btn = widgets.make_button("Open folder", "ghost", "folder", height=30) + open_btn.clicked.connect(lambda: os.startfile(found)) # noqa: S606 + status_row.addWidget(open_btn, 0, Qt.AlignTop) + holder = QWidget() + holder.setLayout(status_row) + self.box.addWidget(holder) + + self._section("For the whole group") + for line in games.COMMON_STEPS: + self.box.addWidget(_bullet_row(line)) + self.box.addStretch(1) + + def _section(self, text): + label = QLabel(theme.caps(text)) + label.setObjectName("SectionLabel") + self.box.addSpacing(6) + self.box.addWidget(label) diff --git a/app/ui/icons.py b/app/ui/icons.py index 14f753d..2b0beba 100644 --- a/app/ui/icons.py +++ b/app/ui/icons.py @@ -1,6 +1,7 @@ """Inline SVG icon set, rendered to pixmaps at the right DPI and color. -Outline icons are from Feather (MIT); the dragon-eye mark is our own. +Outline icons are from Feather (MIT); the dragon-eye and the WorldSync +orbit mark are our own. """ from PySide6.QtCore import QByteArray, QRectF, Qt @@ -273,6 +274,27 @@ '' '' ), + "grid": ( + '' + '' + ), + "search": '', + "heart": ( + '' + ), + "orbit": ( + '' + '' + '' + '' + ), + "gamepad": ( + '' + '' + '' + ), } @@ -299,6 +321,46 @@ """ +# WorldSync's own mark: a planet with two friends in orbit. +WS_MARK_SVG = """ + + + + + + + + + + + + + + + + + +""" + + +def _render_svg(svg: str, size: int, dpr: float) -> QPixmap: + renderer = QSvgRenderer(QByteArray(svg.encode())) + pm = QPixmap(int(size * dpr), int(size * dpr)) + pm.fill(Qt.transparent) + painter = QPainter(pm) + painter.setRenderHint(QPainter.Antialiasing) + renderer.render(painter, QRectF(0, 0, size * dpr, size * dpr)) + painter.end() + pm.setDevicePixelRatio(dpr) + return pm + + +def worldsync_mark(size: int, dpr: float = 2.0) -> QPixmap: + return _render_svg(WS_MARK_SVG, size, dpr) + + def mark_pixmap(size: int, dpr: float = 2.0) -> QPixmap: renderer = QSvgRenderer(QByteArray(MARK_SVG.encode())) pm = QPixmap(int(size * dpr), int(size * dpr)) diff --git a/app/ui/invite_page.py b/app/ui/invite_page.py index 7ab2209..e2d6325 100644 --- a/app/ui/invite_page.py +++ b/app/ui/invite_page.py @@ -119,7 +119,7 @@ def __init__(self, parent=None): def load(self, world: dict): self._world = world - self.title.setText(f"Invite friends - {world['world_name']}") + self.title.setText(f"Invite friends - {world.get('label') or world['world_name']}") self.link_field.edit.setText(world.get("share_link") or "") self.link_field.clear_error() self.code_box.setVisible(False) @@ -140,7 +140,9 @@ def _generate(self): self.share_link_saved.emit(self._world["id"], link) self._world["share_link"] = link folder_name = Path(self._world["sync_dir"]).name - code = invite.encode(self._world["world_name"], folder_name, link or None) + code = invite.encode(self._world["world_name"], folder_name, link or None, + game=self._world.get("game", "dragonwilds"), + label=self._world.get("label")) self.code_box.setPlainText(code) self.code_box.setVisible(True) self.copy_btn.setVisible(True) diff --git a/app/ui/library_page.py b/app/ui/library_page.py new file mode 100644 index 0000000..31f1a66 --- /dev/null +++ b/app/ui/library_page.py @@ -0,0 +1,321 @@ +"""The library: WorldSync's main menu. + +Every game the player has added gets a card painted in that game's own +scene and colours, with a live line underneath (who's playing, who played +last). The last card adds a game. Invite codes can be pasted from here too, +since a code already says which game it's for. +""" + +import webbrowser +import zlib + +from PySide6.QtCore import QRectF, QSize, Qt, Signal +from PySide6.QtGui import QColor, QFont, QLinearGradient, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import (QGridLayout, QHBoxLayout, QLabel, + QScrollArea, QVBoxLayout, QWidget) + +from .. import __version__ +from . import format as fmt +from . import gamethemes, icons, scenes, theme, widgets +from .banner import WorldBanner + +# The tip jar. Set to "" to hide the button. +TIP_URL = "https://ko-fi.com/andormanu" + +CARD_W, CARD_H = 204, 124 # two columns plus a scrollbar fit the 512px window +_THUMBS: dict[tuple, object] = {} + + +def game_thumb(game_id: str, w: int, h: int): + """A cached still of the game's scene, in that game's own colours.""" + key = (game_id, w, h) + if key not in _THUMBS: + tok = gamethemes.get(game_id).tokens() + _THUMBS[key] = scenes.render(gamethemes.get(game_id).scene, w, h, + tok["ACCENT"], tok["EMBER"], seed=zlib.crc32(game_id.encode())) + return _THUMBS[key] + + +def game_font(game_id: str, px: int, bold=True) -> QFont: + t = gamethemes.get(game_id) + f = QFont(theme._family(t.deco)) + f.setPixelSize(px) + f.setWeight(QFont.Bold if bold else QFont.Normal) + if t.title_spacing: + f.setLetterSpacing(QFont.AbsoluteSpacing, min(t.title_spacing, 2) * 0.6) + return f + + +class GameCard(QWidget): + """A game in the library, drawn as a little poster.""" + + clicked = Signal(str) + + def __init__(self, profile, parent=None): + super().__init__(parent) + self.profile = profile + self._line = "" + self._live = False + self._hover = False + self.setFixedSize(CARD_W, CARD_H) + self.setCursor(Qt.PointingHandCursor) + self.setAttribute(Qt.WA_Hover, True) + self.setToolTip(profile.name) + + def set_line(self, text: str, live: bool = False): + self._line, self._live = text, live + self.update() + + def mousePressEvent(self, e): + if e.button() == Qt.LeftButton: + self.clicked.emit(self.profile.id) + + def event(self, e): + if e.type() in (e.Type.HoverEnter, e.Type.HoverLeave): + self._hover = e.type() == e.Type.HoverEnter + self.update() + return super().event(e) + + def paintEvent(self, e): + tok = gamethemes.get(self.profile.id).tokens() + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing) + r = QRectF(self.rect()).adjusted(1, 1, -1, -1) + clip = QPainterPath() + clip.addRoundedRect(r, 14, 14) + p.setClipPath(clip) + p.drawPixmap(0, 0, game_thumb(self.profile.id, CARD_W, CARD_H)) + + shade = QLinearGradient(0, CARD_H * 0.3, 0, CARD_H) + shade.setColorAt(0, QColor(0, 0, 0, 0)) + shade.setColorAt(0.6, QColor(0, 0, 0, 150)) + shade.setColorAt(1, QColor(0, 0, 0, 225)) + p.fillRect(r, shade) + if self._hover: + p.fillRect(r, QColor(255, 255, 255, 14)) + + # title in the game's own typeface + p.setPen(QColor("#FFFFFF")) + p.setFont(game_font(self.profile.id, 17)) + title_rect = QRectF(14, CARD_H - 54, CARD_W - 28, 24) + name = self.profile.name.replace("RuneScape: ", "") + p.drawText(title_rect, Qt.AlignLeft | Qt.AlignVCenter, + p.fontMetrics().elidedText(name, Qt.ElideRight, int(title_rect.width()))) + + # live line + f = QFont(self.font()) + f.setPixelSize(11) + p.setFont(f) + x = 14 + if self._live: + p.setPen(Qt.NoPen) + p.setBrush(QColor(tok["ACCENT"])) + p.drawEllipse(QRectF(x, CARD_H - 25, 7, 7)) + x += 12 + p.setPen(QColor(tok["GOLD_TEXT"]) if self._live else QColor(theme.TEXT_DIM)) + p.drawText(QRectF(x, CARD_H - 32, CARD_W - x - 12, 20), Qt.AlignLeft | Qt.AlignVCenter, + p.fontMetrics().elidedText(self._line, Qt.ElideRight, CARD_W - x - 12)) + + if not self.profile.verified: + p.setFont(QFont(self.font().family(), 7, QFont.Bold)) + badge = QRectF(CARD_W - 50, 10, 40, 16) + p.setPen(Qt.NoPen) + p.setBrush(QColor(0, 0, 0, 140)) + p.drawRoundedRect(badge, 8, 8) + p.setPen(QColor(tok["EMBER"])) + p.drawText(badge, Qt.AlignCenter, "BETA") + + p.setClipping(False) + border = QColor(tok["ACCENT"]) if self._hover else QColor(255, 255, 255, 26) + p.setPen(QPen(border, 1.6 if self._hover else 1.0)) + p.setBrush(Qt.NoBrush) + p.drawRoundedRect(r, 14, 14) + p.end() + + +class AddGameCard(QWidget): + clicked = Signal() + + def __init__(self, parent=None): + super().__init__(parent) + self._hover = False + self.setFixedSize(CARD_W, CARD_H) + self.setCursor(Qt.PointingHandCursor) + self.setAttribute(Qt.WA_Hover, True) + + def mousePressEvent(self, e): + if e.button() == Qt.LeftButton: + self.clicked.emit() + + def event(self, e): + if e.type() in (e.Type.HoverEnter, e.Type.HoverLeave): + self._hover = e.type() == e.Type.HoverEnter + self.update() + return super().event(e) + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing) + r = QRectF(self.rect()).adjusted(1.5, 1.5, -1.5, -1.5) + p.setBrush(QColor(theme.SURFACE_2 if self._hover else theme.SURFACE)) + pen = QPen(QColor(theme.ACCENT if self._hover else theme.BORDER), 1.4, Qt.DashLine) + p.setPen(pen) + p.drawRoundedRect(r, 14, 14) + color = theme.ACCENT if self._hover else theme.TEXT_DIM + pm = icons.pixmap("plus", color, 26) + p.drawPixmap(int(CARD_W / 2 - 13), int(CARD_H / 2 - 26), pm) + f = QFont(theme.display_family()) + f.setPixelSize(13) + f.setWeight(QFont.DemiBold) + p.setFont(f) + p.setPen(QColor(color)) + p.drawText(QRectF(0, CARD_H / 2 + 6, CARD_W, 22), Qt.AlignCenter, "Add a game") + p.end() + + +class LibraryPage(QWidget): + game_opened = Signal(str) + add_game_clicked = Signal() + join_clicked = Signal() + + def __init__(self, parent=None): + super().__init__(parent) + self._cards: dict[str, GameCard] = {} + + root = QVBoxLayout(self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + + # -- hero --------------------------------------------------------------- + hero = QWidget() + hero.setFixedHeight(150) + self.banner = WorldBanner(150, hero) + overlay = QWidget(hero) + overlay.setStyleSheet("background: transparent;") + ov = QVBoxLayout(overlay) + ov.setContentsMargins(22, 14, 22, 14) + ov.addStretch(1) + brand = QHBoxLayout() + brand.setSpacing(12) + mark = QLabel() + mark.setPixmap(icons.worldsync_mark(40)) + mark.setStyleSheet("background: transparent;") + brand.addWidget(mark, 0, Qt.AlignVCenter) + words = QVBoxLayout() + words.setSpacing(0) + self.wordmark = QLabel("WorldSync") + self.wordmark.setStyleSheet("background: transparent; color: #FFFFFF;") + self.greeting = QLabel("") + self.greeting.setStyleSheet(f"background: transparent; color: {theme.TEXT_DIM};" + "font-size: 12.5px;") + words.addWidget(self.wordmark) + words.addWidget(self.greeting) + brand.addLayout(words, 1) + ov.addLayout(brand) + hero.resizeEvent = lambda e: (self.banner.setGeometry(0, 0, hero.width(), 150), + overlay.setGeometry(0, 0, hero.width(), 150)) + root.addWidget(hero) + + # -- cards -------------------------------------------------------------- + body = QWidget() + bb = QVBoxLayout(body) + bb.setContentsMargins(24, 10, 24, 14) + bb.setSpacing(10) + self.section = QLabel("") + self.section.setObjectName("SectionLabel") + bb.addWidget(self.section) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + holder = QWidget() + holder.setStyleSheet("background: transparent;") + self.grid = QGridLayout(holder) + self.grid.setContentsMargins(0, 2, 0, 2) + self.grid.setHorizontalSpacing(14) + self.grid.setVerticalSpacing(14) + self.grid.setAlignment(Qt.AlignTop | Qt.AlignLeft) + scroll.setWidget(holder) + bb.addWidget(scroll, 1) + + self.add_card = AddGameCard() + self.add_card.clicked.connect(self.add_game_clicked.emit) + + actions = QHBoxLayout() + actions.setSpacing(8) + join = widgets.make_button("Join with an invite code", "ghost", "link", height=38) + join.clicked.connect(self.join_clicked.emit) + actions.addWidget(join, 1) + bb.addLayout(actions) + + footer = QHBoxLayout() + self.tip_btn = widgets.make_button("Support WorldSync", "subtle", "heart", height=26) + self.tip_btn.setToolTip("WorldSync is free. If it saved your group a server bill, " + "a tip keeps it going.") + self.tip_btn.clicked.connect(lambda: webbrowser.open(TIP_URL)) + self.tip_btn.setVisible(bool(TIP_URL)) + footer.addWidget(self.tip_btn) + footer.addStretch(1) + version = QLabel(f"v{__version__} · free and open source") + version.setObjectName("FooterText") + footer.addWidget(version) + bb.addLayout(footer) + root.addWidget(body, 1) + self.retheme() + + # -- public ----------------------------------------------------------------- + def retheme(self): + self.banner.set_scene(theme.scene()) + # set through the stylesheet: the global QSS font-size would win over setFont + self.wordmark.setStyleSheet( + "background: transparent; color: #FFFFFF;" + f"font-family: '{theme.display_family()}'; font-size: 30px; font-weight: 700;" + "letter-spacing: 0.5px;") + self.section.setText(theme.caps("Your library")) + self.tip_btn.setIcon(icons.icon("heart", theme.EMBER, 14)) + + def set_player(self, name: str, game_count: int): + self._me = name + hello = f"Hi {name}" if name else "Welcome" + if game_count: + self.greeting.setText(f"{hello} · {game_count} game" + f"{'s' if game_count != 1 else ''} in your library") + else: + self.greeting.setText(f"{hello} · add your first game to get going") + + def set_games(self, profiles, world_counts: dict): + while self.grid.count(): + item = self.grid.takeAt(0) + w = item.widget() + if w is not None and w is not self.add_card: + w.deleteLater() + self._cards = {} + for i, prof in enumerate(profiles): + card = GameCard(prof) + n = world_counts.get(prof.id, 0) + card.set_line(f"{n} world{'s' if n != 1 else ''}" if n else "No worlds yet") + card.clicked.connect(self.game_opened.emit) + self._cards[prof.id] = card + self.grid.addWidget(card, i // 2, i % 2) + i = len(profiles) + self.grid.addWidget(self.add_card, i // 2, i % 2) + + def set_summary(self, summary: dict): + """{game_id: {"playing": name|None, "last": (editor, iso_ts)|None, "worlds": n}}""" + for gid, info in summary.items(): + card = self._cards.get(gid) + if not card: + continue + n = info.get("worlds", 0) + worlds = f"{n} world{'s' if n != 1 else ''}" + if info.get("playing"): + card.set_line(f"{info['playing']} is playing", live=True) + elif info.get("last"): + editor, ts = info["last"] + editor = "you" if editor == getattr(self, "_me", None) else editor + card.set_line(f"{worlds} · {editor}, {fmt.humanize(ts)}") + else: + card.set_line(worlds if n else "No worlds yet") + + def sizeHint(self): + return QSize(480, 720) diff --git a/app/ui/main_screen.py b/app/ui/main_screen.py index 3231193..7416d72 100644 --- a/app/ui/main_screen.py +++ b/app/ui/main_screen.py @@ -74,6 +74,7 @@ class BannerHeader(QWidget): world_menu_requested = Signal() refresh_requested = Signal() invite_requested = Signal() + library_requested = Signal() def __init__(self, height=158, parent=None): super().__init__(parent) @@ -88,6 +89,12 @@ def __init__(self, height=158, parent=None): top = QHBoxLayout() top.setSpacing(6) + self.library_btn = QPushButton("") + self.library_btn.setObjectName("LibraryCrumb") + self.library_btn.setCursor(Qt.PointingHandCursor) + self.library_btn.setToolTip("Back to your game library") + self.library_btn.clicked.connect(self.library_requested.emit) + top.addWidget(self.library_btn) top.addStretch(1) self.refresh_btn = widgets.icon_button("refresh", theme.GOLD_TEXT, tooltip="Check again") @@ -107,10 +114,7 @@ def __init__(self, height=158, parent=None): self.title_btn.setStyleSheet( "QPushButton#WorldTitle { background: transparent; border: none;" "color: #FFFFFF; text-align: left; padding: 0; }") - f = QFont(theme.deco_family()) - f.setPixelSize(29) - f.setWeight(QFont.Bold) - self.title_btn.setFont(f) + self._apply_title_font() self.title_btn.clicked.connect(self.world_menu_requested.emit) ov.addWidget(self.title_btn) @@ -124,6 +128,30 @@ def __init__(self, height=158, parent=None): ov.addSpacing(5) ov.addLayout(pill_row) + def _apply_title_font(self): + f = QFont(theme.deco_family()) + f.setPixelSize(29) + f.setWeight(QFont.Bold) + self.title_btn.setFont(f) + + def set_game(self, game_name: str): + """The crumb back to the library, labelled with the current game.""" + self.library_btn.setText(f"‹ {theme.caps(game_name)}") + self.library_btn.setStyleSheet( + "QPushButton#LibraryCrumb { background: rgba(0,0,0,0.28);" + f"color: {theme.GOLD_TEXT}; border: 1px solid rgba(255,255,255,0.10);" + "border-radius: 13px; padding: 4px 12px 4px 10px;" + f"font-family: '{theme.display_family()}'; font-size: 11px; font-weight: 600;" + f"letter-spacing: {min(theme.TITLE_SPACING, 2)}px; }}" + "QPushButton#LibraryCrumb:hover { background: rgba(0,0,0,0.45);" + f"border-color: {theme.ACCENT}; }}") + + def retheme(self): + self.banner.set_scene(theme.scene()) + self._apply_title_font() + self.refresh_btn.setIcon(icons.icon("refresh", theme.GOLD_TEXT, 16)) + self.invite_btn.setIcon(icons.icon("user-plus", theme.GOLD_TEXT, 16)) + def resizeEvent(self, e): self.banner.setGeometry(0, 0, self.width(), self.height()) self.overlay.setGeometry(0, 0, self.width(), self.height()) @@ -161,6 +189,8 @@ class MainPage(QWidget): update_clicked = Signal() characters_clicked = Signal() saga_clicked = Signal() + guide_clicked = Signal() + library_clicked = Signal() def __init__(self, parent=None): super().__init__(parent) @@ -169,6 +199,8 @@ def __init__(self, parent=None): self._me = "" self._worlds = [] self._active_id = None + self._game_name = "the game" + self._has_characters = True root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) @@ -179,6 +211,7 @@ def __init__(self, parent=None): self.header.world_menu_requested.connect(self._open_world_menu) self.header.refresh_requested.connect(self.refresh_clicked.emit) self.header.invite_requested.connect(self.invite_clicked.emit) + self.header.library_requested.connect(self.library_clicked.emit) root.addWidget(self.header) body = QWidget() @@ -190,20 +223,14 @@ def __init__(self, parent=None): # -- update bar (hidden until an update is published) --------------- self.update_bar = QFrame() self.update_bar.setObjectName("UpdateBar") - self.update_bar.setStyleSheet( - f"#UpdateBar {{ background: rgba(232,162,61,0.12);" - f"border: 1px solid rgba(232,162,61,0.40); border-radius: 10px; }}") ub = QHBoxLayout(self.update_bar) ub.setContentsMargins(12, 8, 8, 8) ub.setSpacing(9) - ub_icon = QLabel() - ub_icon.setPixmap(icons.pixmap("rocket", theme.EMBER, 17)) - ub_icon.setStyleSheet("background: transparent; border: none;") - ub.addWidget(ub_icon, 0, Qt.AlignVCenter) + self._ub_icon = QLabel() + self._ub_icon.setStyleSheet("background: transparent; border: none;") + ub.addWidget(self._ub_icon, 0, Qt.AlignVCenter) self.update_label = QLabel("") self.update_label.setWordWrap(True) - self.update_label.setStyleSheet( - f"background: transparent; border: none; color: {theme.GOLD_TEXT}; font-size: 12px;") ub.addWidget(self.update_label, 1) update_btn = widgets.make_button("Update", "primary", height=30) update_btn.clicked.connect(self.update_clicked.emit) @@ -258,9 +285,9 @@ def __init__(self, parent=None): body_box.addLayout(claim_row) # -- feed ----------------------------------------------------------- - section = QLabel(FEED_TITLE) - section.setObjectName("SectionLabel") - body_box.addWidget(section) + self.feed_title = QLabel(FEED_TITLE) + self.feed_title.setObjectName("SectionLabel") + body_box.addWidget(self.feed_title) feed_card = QFrame() feed_card.setObjectName("Card") @@ -293,24 +320,47 @@ def __init__(self, parent=None): footer.addWidget(version) body_box.addLayout(footer) + self.retheme() + self._clock = QTimer(self) self._clock.setInterval(60_000) self._clock.timeout.connect(self._rerender) self._clock.start() + # -- theme & game --------------------------------------------------------- + def retheme(self): + """Pick up the active game's theme for the parts styled in code.""" + self.header.retheme() + e = theme.EMBER.lstrip("#") + r, g, b = int(e[0:2], 16), int(e[2:4], 16), int(e[4:6], 16) + self.update_bar.setStyleSheet( + f"#UpdateBar {{ background: rgba({r},{g},{b},0.12);" + f"border: 1px solid rgba({r},{g},{b},0.40); border-radius: 10px; }}") + self._ub_icon.setPixmap(icons.pixmap("rocket", theme.EMBER, 17)) + self.update_label.setStyleSheet( + f"background: transparent; border: none; color: {theme.GOLD_TEXT}; font-size: 12px;") + self.play_btn.setIcon(icons.icon("play", theme.ON_ACCENT, 20)) + self.play_btn.retheme() + self.feed_title.setText(theme.caps("Recent sessions")) + + def set_game(self, name: str, has_characters: bool): + self._game_name = name + self._has_characters = has_characters + self.header.set_game(name) + # -- world switcher ------------------------------------------------------ def set_worlds(self, worlds, active_id): self._worlds = worlds self._active_id = active_id active = next((w for w in worlds if w["id"] == active_id), None) - name = active["world_name"] if active else "No world" + name = (active.get("label") or active["world_name"]) if active else "No world" accent = (active or {}).get("accent") or fmt.name_color(name) self.header.set_world(name, accent) def _open_world_menu(self): menu = QMenu(self) for w in self._worlds: - action = menu.addAction(w["world_name"]) + action = menu.addAction(w.get("label") or w["world_name"]) if w["id"] == self._active_id: action.setIcon(icons.icon("check", theme.ACCENT, 14)) action.triggered.connect( @@ -318,10 +368,14 @@ def _open_world_menu(self): menu.addSeparator() add = menu.addAction(icons.icon("plus", theme.TEXT_DIM, 14), "Add a world…") add.triggered.connect(self.add_world_clicked.emit) - chars = menu.addAction(icons.icon("dragon", theme.TEXT_DIM, 14), "Characters…") - chars.triggered.connect(self.characters_clicked.emit) + if self._has_characters: + chars = menu.addAction(icons.icon("dragon", theme.TEXT_DIM, 14), "Characters…") + chars.triggered.connect(self.characters_clicked.emit) saga = menu.addAction(icons.icon("map", theme.TEXT_DIM, 14), "The Saga…") saga.triggered.connect(self.saga_clicked.emit) + guide = menu.addAction(icons.icon("book-open", theme.TEXT_DIM, 14), + f"How to set up {self._game_name}…") + guide.triggered.connect(self.guide_clicked.emit) backups = menu.addAction(icons.icon("archive", theme.TEXT_DIM, 14), "Backups…") backups.triggered.connect(self.backups_clicked.emit) menu.exec(self.header.title_btn.mapToGlobal( @@ -376,7 +430,7 @@ def set_phase(self, phase): self.header.set_pill("Syncing", theme.EMBER) elif phase == "launching": self.hero_icon.show_spinner() - self._say("Launching Dragonwilds…", "Handing you over to Steam.") + self._say(f"Launching {self._game_name}…", "Handing you over to Steam.") self.header.set_pill("Launching", theme.EMBER) elif phase == "waiting": self.hero_icon.show_spinner() @@ -385,7 +439,7 @@ def set_phase(self, phase): self.header.set_pill("Launching", theme.EMBER) elif phase == "ingame": self.hero_icon.show_pulse() - self._say("You're in the wilds", + self._say(f"You're in {self._game_name}", "Your progress is shared automatically when you close the game.") self.header.set_pill("Playing", theme.ACCENT) elif phase == "pushing": @@ -409,8 +463,8 @@ def _rerender(self): if status.newer_app_needed: self.hero_icon.show_icon("alert", theme.AMBER) self._say("This world needs a newer app", - "A friend shared a save with a newer version of Dragonwilds " - "Sync. Update your app before playing so nothing gets scrambled.") + "A friend shared a save with a newer version of WorldSync. " + "Update your app before playing so nothing gets scrambled.") self.play_btn.setEnabled(False) self.save_btn.setEnabled(False) self.header.set_pill("Update needed", theme.AMBER) @@ -429,7 +483,7 @@ def _rerender(self): since = f"{minutes // 60} h ago" self.hero_icon.show_pulse(amber=True) as_char = f" as {who['character']}" if who.get("character") else "" - self._say(f"{who['player']} is in the wilds right now", + self._say(f"{who['player']} is playing right now", f"Playing{as_char} - started {since}. Best wait for their " f"save; you'll see it land here.") self.header.set_pill(f"{who['player']} playing", theme.AMBER) diff --git a/app/ui/onboarding.py b/app/ui/onboarding.py index c177919..e987e41 100644 --- a/app/ui/onboarding.py +++ b/app/ui/onboarding.py @@ -1,15 +1,17 @@ -"""Onboarding: welcome → name → create-or-join fork → done in under a minute. +"""Onboarding: welcome → name, then per game: create-or-join → done. -Also reused as the "Add a world" flow for already-configured users (the name -step is skipped and Back from the fork returns to the main screen). +The first run asks for a name and hands over to the game picker +(`name_chosen`). Every game then goes through the same fork, worded for that +game: create a world (find the save folder and the world in it, pick a +shared folder) or join with an invite code. Joining straight from the +library works too - the code says which game it's for. `finished` emits a payload: - {"kind": "create"|"join", "player_name", "local_save_dir", + {"kind": "create"|"join", "game", "player_name", "local_save_dir", "world_name", "sync_dir", "share_link"} """ import getpass -import os import webbrowser from pathlib import Path @@ -17,7 +19,9 @@ from PySide6.QtWidgets import (QHBoxLayout, QLabel, QPushButton, QStackedWidget, QVBoxLayout, QWidget) -from ..core import clouds, invite, paths +import re + +from ..core import clouds, games, invite from . import icons, theme, widgets STEP_WELCOME, STEP_NAME, STEP_CHOICE = 0, 1, 2 @@ -49,15 +53,24 @@ def set_active(self, index): d.setStyleSheet(f"background: {color}; border-radius: 3px;") +def _folder_safe(text: str) -> str: + return re.sub(r'[<>:"/\\|?*]', "-", text).strip(" .") or "World" + + class OnboardingPage(QWidget): finished = Signal(dict) - cancelled = Signal() # only from "Add a world" mode + cancelled = Signal() # Back out of a game's flow + name_chosen = Signal(str) # first run: the name step is done, pick a game + guide_requested = Signal(str) # game id: open that game's setup guide def __init__(self, parent=None): super().__init__(parent) self.add_mode = False self._existing_name = "" self._join_info = None + self.profile = games.DRAGONWILDS + self._default_save_dir = "" + self._join_only = False self._watch_timer = QTimer(self) self._watch_timer.setInterval(WATCH_INTERVAL_MS) self._watch_timer.timeout.connect(self._watch_tick) @@ -81,13 +94,61 @@ def start_fresh(self): self._watch_timer.stop() self._go(STEP_WELCOME) - def start_add_world(self, player_name: str): - """Skip straight to the fork; Back there cancels to the main screen.""" + def start_game(self, profile, player_name: str, save_dir: str): + """The create-or-join fork for one game; Back there cancels.""" self.add_mode = True + self._join_only = False self._existing_name = player_name self._watch_timer.stop() + self._set_profile(profile, save_dir) self._go(STEP_CHOICE) + def start_add_world(self, player_name: str, profile=None, save_dir: str = ""): + self.start_game(profile or self.profile, player_name, save_dir) + + def start_join(self, player_name: str): + """Paste a code from the library; the code picks the game.""" + self.add_mode = True + self._join_only = True + self._existing_name = player_name + self._watch_timer.stop() + self.code_field.edit.clear() + self.code_field.clear_error() + self._go(STEP_JOIN_CODE) + + def _set_profile(self, profile, save_dir: str): + self.profile = profile + self._default_save_dir = save_dir + name = profile.name + word = profile.world_word + self.choice_title.setText(f"Your {name} {word}") + self.choice_sub.setText(f"Create a shared {word} for your group, or join one " + f"a friend already shares.") + self.create_card.set_text(f"Share a {word}", + f"You have the {word} on this PC (or will start it) - " + f"set up the shared folder and invite the others.") + self.world_title.setText(f"Where does your {word} live?") + self.choice_guide_btn.setText(f"How to set up {profile.short}") + self.save_dir_field.label.setText(f"{name} save folder") + self.save_dir_field.edit.setText(save_dir) + found = games.default_save_dir(profile) + self.save_dir_field.note.setText( + "Found it automatically." if found and str(found) == save_dir else + "Not found yet - start the game once and make a world, or browse to it.") + self.save_dir_field.note.setVisible(True) + self.world_field.label.setText(f"{word.capitalize()} to sync") + self.world_field._hint = profile.world_hint + caveats = list(profile.caveats) + if not profile.verified: + caveats.insert(0, f"{name} support is new. It follows the save layout the " + f"community documents - if something looks off, the " + f"backups have you covered and an issue on GitHub helps " + f"everyone.") + self.caveat_box.setText("\n\n".join(caveats)) + self.caveat_box.setVisible(bool(caveats)) + self.world_field.combo.setCurrentText("") + self._rescan_worlds() + # -- shared scaffolding --------------------------------------------------------- def _step_scaffold(self, dot_index, title, subtitle, back_to=None): page = QWidget() @@ -119,6 +180,7 @@ def _step_scaffold(self, dot_index, title, subtitle, back_to=None): box.addSpacing(6) box.addWidget(s) box.addSpacing(20) + page.title_label, page.sub_label = t, s content = QVBoxLayout() content.setSpacing(14) @@ -153,19 +215,19 @@ def _welcome_step(self): box.addStretch(5) mark = QLabel() - mark.setPixmap(icons.mark_pixmap(60)) + mark.setPixmap(icons.worldsync_mark(64)) mark.setAlignment(Qt.AlignHCenter) box.addWidget(mark) box.addSpacing(18) - title = QLabel("Dragonwilds Sync") + title = QLabel("WorldSync") title.setAlignment(Qt.AlignHCenter) title.setStyleSheet( f"font-family: '{theme.deco_family()}'; font-size: 32px; font-weight: 700;" f"color: {theme.GOLD_TEXT}; letter-spacing: 1px;") box.addWidget(title) - tag = QLabel("One world, shared between friends.") + tag = QLabel("One world, every friend can host.") tag.setAlignment(Qt.AlignHCenter) tag.setStyleSheet( f"font-family: '{theme.display_family()}'; color: {theme.ACCENT};" @@ -173,8 +235,9 @@ def _welcome_step(self): box.addSpacing(6) box.addWidget(tag) - body = QLabel("Take turns in the same Dragonwilds world without renting a server. " - "Whoever plays next always picks up the newest save - automatically.") + body = QLabel("Take turns in the same co-op world without renting a server. " + "Whoever plays next always picks up the newest save - " + "Valheim, Palworld, V Rising, Dragonwilds and more.") body.setAlignment(Qt.AlignHCenter) body.setWordWrap(True) body.setStyleSheet(f"color: {theme.TEXT_DIM}; font-size: 12.5px;") @@ -187,7 +250,7 @@ def _welcome_step(self): btn.clicked.connect(lambda: self._go(STEP_NAME)) box.addWidget(btn, 0, Qt.AlignHCenter) - cap = QLabel("Takes under a minute · No account needed") + cap = QLabel("Free · No account · Your own cloud drive") cap.setAlignment(Qt.AlignHCenter) cap.setStyleSheet(f"color: {theme.TEXT_FAINT}; font-size: 11px;") box.addSpacing(12) @@ -214,7 +277,7 @@ def _submit_name(self): self.name_field.set_error("Everyone needs a name - even a dragon.") return self.name_field.clear_error() - self._go(STEP_CHOICE) + self.name_chosen.emit(self.name_field.value()) # -- step 2: create or join -------------------------------------------------------- def _choice_step(self): @@ -222,12 +285,14 @@ def _choice_step(self): 1, "How are you starting out?", "Create a world for your group, or join one a friend already shares.", back_to=self._back_from_choice) + self.choice_title, self.choice_sub = page.title_label, page.sub_label create = widgets.OptionCard( "sparkle", "Create a new world", "You have (or will make) the world save - set up the shared folder " "and invite the others.") create.set_on_click(lambda: self._go(STEP_CREATE_WORLD)) + self.create_card = create content.addWidget(create) join = widgets.OptionCard( @@ -235,43 +300,62 @@ def _choice_step(self): "A friend sent you a code from their app - paste it and you're in.") join.set_on_click(lambda: self._go(STEP_JOIN_CODE)) content.addWidget(join) + + self.choice_guide_btn = widgets.make_button("How to set up this game", "subtle", + "book-open", height=30) + self.choice_guide_btn.clicked.connect( + lambda: self.guide_requested.emit(self.profile.id)) + content.addWidget(self.choice_guide_btn, 0, Qt.AlignLeft) return page def _back_from_choice(self): - if self.add_mode: - self.cancelled.emit() - else: - self._go(STEP_NAME) + self.cancelled.emit() # -- step 3: create - world -------------------------------------------------------- def _world_step(self): page, box, content = self._step_scaffold( 2, "Where does your world live?", - "This is the game's save folder on this PC. We've already found " - "the usual spot - just pick the world you all share.", + "This is the game's save folder on this PC. We look in the usual " + "spot first - just pick the one you all share.", back_to=lambda: self._go(STEP_CHOICE)) + self.world_title = page.title_label self.save_dir_field = widgets.FormField( - "Dragonwilds save folder", str(paths.DEFAULT_SAVE_DIR), browse="dir") + "Save folder", "", browse="dir") self.save_dir_field.edit.editingFinished.connect(self._rescan_worlds) content.addWidget(self.save_dir_field) self.world_field = widgets.WorldField("World to sync", hint="") content.addWidget(self.world_field) - self._rescan_worlds() + + self.caveat_box = QLabel("") + self.caveat_box.setWordWrap(True) + self.caveat_box.setStyleSheet( + "background: rgba(242,180,65,0.08); border: 1px solid rgba(242,180,65,0.28);" + f"border-radius: 10px; padding: 10px 12px; color: {theme.TEXT_DIM};" + "font-size: 11.5px;") + self.caveat_box.setVisible(False) + content.addWidget(self.caveat_box) + + guide_btn = widgets.make_button("Step-by-step setup guide", "subtle", "book-open", + height=30) + guide_btn.clicked.connect(lambda: self.guide_requested.emit(self.profile.id)) + content.addWidget(guide_btn, 0, Qt.AlignLeft) self._continue_row(box, "Continue", self._submit_world) return page def _rescan_worlds(self): - names = self.world_field.refresh(self.save_dir_field.value()) + word = self.profile.world_word + names = self.world_field.refresh(self.save_dir_field.value(), profile=self.profile) if names: self.world_field.note.setText( - f"Found {len(names)} world{'s' if len(names) != 1 else ''} in this folder.") + f"Found {len(names)} {word}{'s' if len(names) != 1 else ''}, most recently " + f"played first. {self.profile.world_hint}") self.world_field.note.setProperty("role", "hint") self.world_field.note.setVisible(True) else: self.world_field.note.setText( - "No saves found here yet - fine if the world lives on a friend's PC. " - "Type its name exactly as they see it.") + f"No {word}s found here yet - fine if it lives on a friend's PC. " + f"{self.profile.world_hint}") self.world_field.note.setVisible(True) def _submit_world(self): @@ -280,10 +364,14 @@ def _submit_world(self): self.save_dir_field.set_error("Point me at the game's save folder.") ok = False if not self.world_field.value(): - self.world_field.set_error("Which world are you sharing?") + self.world_field.set_error(f"Which {self.profile.world_word} are you sharing?") + ok = False + elif not games.is_valid_world_id(self.world_field.value()): + self.world_field.set_error("That name has characters a folder can't hold.") ok = False if ok: self.world_field.clear_error() + self._suggest_shared_names() self._go(STEP_CREATE_SHARED) # -- step 4: create - shared folder --------------------------------------------------- @@ -296,6 +384,7 @@ def _shared_step(self): back_to=lambda: self._go(STEP_CREATE_WORLD)) cloud_roots = clouds.detect_cloud_roots() + self._cloud_chips = [] if cloud_roots: chip_row = QHBoxLayout() chip_row.setSpacing(8) @@ -310,10 +399,9 @@ def _shared_step(self): chip = QPushButton(label) chip.setProperty("variant", "chip") chip.setCursor(Qt.PointingHandCursor) - suggested = root / "Dragonwilds Sync" - chip.setToolTip(str(suggested)) chip.clicked.connect( - lambda _=False, s=suggested: self.shared_field.edit.setText(str(s))) + lambda _=False, c=chip: self.shared_field.edit.setText(c.toolTip())) + self._cloud_chips.append((chip, root)) chip_row.addWidget(chip) chip_row.addStretch(1) content.addLayout(chip_row) @@ -331,11 +419,18 @@ def _shared_step(self): self.shared_field = widgets.FormField( "Shared folder", "", browse="dir", hint="We'll create it if it doesn't exist yet.", - placeholder=r"e.g. C:\Users\you\OneDrive\Dragonwilds Sync") + placeholder=r"e.g. C:\Users\you\OneDrive\WorldSync\Valheim - Midgard") content.addWidget(self.shared_field) - self._continue_row(box, "Enter the wilds", self._submit_create) + self._continue_row(box, "Start syncing", self._submit_create) return page + def _suggest_shared_names(self): + """Each world gets its own folder: WorldSync/ - .""" + label = self.world_field.combo.currentText().split(" · ")[0] + name = _folder_safe(f"{self.profile.name.replace('RuneScape: ', '')} - {label}") + for chip, root in self._cloud_chips: + chip.setToolTip(str(root / "WorldSync" / name)) + def _submit_create(self): shared = self.shared_field.value() if not shared: @@ -347,8 +442,11 @@ def _submit_create(self): self.shared_field.set_error("Couldn't create that folder - check the path.") return self.shared_field.clear_error() + label = self.world_field.combo.currentText().split(" · ")[0].strip() self.finished.emit({ "kind": "create", + "game": self.profile.id, + "world_label": label if label and label != self.world_field.value() else None, "player_name": self._player_name(), "local_save_dir": self.save_dir_field.value(), "world_name": self.world_field.value(), @@ -362,20 +460,30 @@ def _join_code_step(self): 2, "Paste your invite code", "Your friend generates it in their app under “Invite friends” and " "sends it any way they like.", - back_to=lambda: self._go(STEP_CHOICE)) + back_to=self._back_from_code) self.code_field = widgets.FormField( - "Invite code", "", placeholder="DWS1.…") + "Invite code", "", placeholder="WS1.…") content.addWidget(self.code_field) self._continue_row(box, "Continue", self._submit_code) self.code_field.edit.returnPressed.connect(self._submit_code) return page + def _back_from_code(self): + if self._join_only: + self.cancelled.emit() + else: + self._go(STEP_CHOICE) + def _submit_code(self): try: self._join_info = invite.decode(self.code_field.value()) except invite.InviteError as e: self.code_field.set_error(str(e)) return + if self._join_info["game"] not in games.BY_ID: + self.code_field.set_error("That invite is for a game this version of WorldSync " + "doesn't know yet - update the app and try again.") + return self.code_field.clear_error() self._start_watching() self._go(STEP_JOIN_WATCH) @@ -452,8 +560,10 @@ def _start_watching(self): link_note = "" if info.get("share_link") else ( "\nThis code has no link in it - ask your friend to share the " "folder with you in their cloud drive.") + game = games.get(info["game"]).name self.join_summary.setText( - f"World: {info['world_name']}\nFolder: {info['folder_name']}{link_note}") + f"Game: {game}\nWorld: {info.get('label') or info['world_name']}\n" + f"Folder: {info['folder_name']}{link_note}") self.open_link_btn.setVisible(bool(info.get("share_link"))) self.no_cloud_panel.setVisible(not clouds.any_cloud_present()) self.watch_label.setText("Watching for the folder to appear…") @@ -491,8 +601,10 @@ def _finish_join(self, folder: Path): info = self._join_info self.finished.emit({ "kind": "join", + "game": info["game"], + "world_label": info.get("label"), "player_name": self._player_name(), - "local_save_dir": str(paths.DEFAULT_SAVE_DIR), + "local_save_dir": None, # the game's detected folder on this PC "world_name": info["world_name"], "sync_dir": str(folder), "share_link": info.get("share_link"), diff --git a/app/ui/saga_page.py b/app/ui/saga_page.py index 2e00d84..ea1e51f 100644 --- a/app/ui/saga_page.py +++ b/app/ui/saga_page.py @@ -74,7 +74,7 @@ def __init__(self, parent=None): root.addWidget(card, 1) def load(self, world, manifest, stats, all_time, me=""): - name = world["world_name"] if world else "-" + name = (world.get("label") or world["world_name"]) if world else "-" self.title.setText(f"The Saga of {name}") history = (manifest or {}).get("history", []) scope = "all time" if all_time else f"the last {len(history)} sessions" diff --git a/app/ui/scenes.py b/app/ui/scenes.py new file mode 100644 index 0000000..6c53f0c --- /dev/null +++ b/app/ui/scenes.py @@ -0,0 +1,811 @@ +"""Procedural banner scenes, one per game. + +No image files and no game assets: every scene is painted with QPainter from +a seed (the world name), so each world looks a little different but always +the same on every PC. A scene builds its static layout once per size and +seed, then ``paint`` draws a frame at time ``t`` (seconds, ~25 fps) for the +gentle motion: aurora, fog, waves, bats, ash. + +The banner widget adds the bottom scrim and vignette on top, so scenes only +paint the world itself. +""" + +import math +import random + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import (QBrush, QColor, QImage, QLinearGradient, QPainter, + QPainterPath, QPen, QPixmap, QRadialGradient) + + +def col(hex_color: str, alpha: float = 1.0) -> QColor: + c = QColor(hex_color) + c.setAlphaF(max(0.0, min(1.0, alpha))) + return c + + +def vgrad(p: QPainter, rect: QRectF, stops): + g = QLinearGradient(rect.left(), rect.top(), rect.left(), rect.bottom()) + for at, c in stops: + g.setColorAt(at, c if isinstance(c, QColor) else QColor(c)) + p.fillRect(rect, QBrush(g)) + + +def glow(p: QPainter, x, y, r, color: QColor, core: float = 0.0): + g = QRadialGradient(x, y, r) + g.setColorAt(0.0, color) + mid = QColor(color) + mid.setAlphaF(color.alphaF() * 0.35) + g.setColorAt(0.45, mid) + g.setColorAt(1.0, QColor(0, 0, 0, 0)) + p.setPen(Qt.NoPen) + p.setBrush(QBrush(g)) + p.drawEllipse(QPointF(x, y), r, r) + if core: + c = QColor(color) + c.setAlphaF(1.0) + p.setBrush(QBrush(c)) + p.drawEllipse(QPointF(x, y), core, core) + + +def ridge(rng, w, h, base, rough, steps, wave=0.03): + pts = [] + for i in range(steps + 1): + x = i / steps + y = base + (rng.random() - 0.5) * rough * 2 + math.sin(x * math.pi * 2.3) * wave + pts.append(QPointF(x * w, y * h)) + return pts + + +def fill_ridge(p: QPainter, pts, h, color: QColor): + path = QPainterPath() + path.moveTo(pts[0].x(), h) + for pt in pts: + path.lineTo(pt) + path.lineTo(pts[-1].x(), h) + path.closeSubpath() + p.setPen(Qt.NoPen) + p.setBrush(QBrush(color)) + p.drawPath(path) + + +def smooth_ridge(rng, w, h, base, amp, bumps): + """A soft hill line built from cubic curves.""" + path = QPainterPath() + path.moveTo(0, h) + xs = [i * w / bumps for i in range(bumps + 1)] + ys = [h * (base + (rng.random() - 0.5) * amp) for _ in xs] + path.lineTo(xs[0], ys[0]) + for i in range(bumps): + mx = (xs[i] + xs[i + 1]) / 2 + path.cubicTo(mx, ys[i], mx, ys[i + 1], xs[i + 1], ys[i + 1]) + path.lineTo(w, h) + path.closeSubpath() + return path + + +class Scene: + """Base: subclasses fill build() and paint().""" + particles = 0 + + def __init__(self, accent: str, ember: str): + self.accent = accent + self.ember = ember + self._key = None + self.w = self.h = 0 + + def ensure(self, w, h, seed): + if self._key != (w, h, seed): + self.w, self.h = w, h + self.rng = random.Random(seed) + self.build(w, h, self.rng) + self._key = (w, h, seed) + + def build(self, w, h, rng): + pass + + def paint(self, p: QPainter, t: float): + raise NotImplementedError + + # shared particle field: x,y in 0..1, drifting with wrap-around + def make_particles(self, rng, n, speed=(0.002, 0.005), size=(1.0, 2.6)): + return [{"x": rng.random(), "y": rng.random(), + "v": speed[0] + rng.random() * (speed[1] - speed[0]), + "s": size[0] + rng.random() * (size[1] - size[0]), + "ph": rng.random() * 6.28, "dr": 0.5 + rng.random()} for _ in range(n)] + + @staticmethod + def particle_pos(pt, t, direction=-1, sway=0.012): + y = (pt["y"] + direction * pt["v"] * t * 25) % 1.2 - 0.1 + x = (pt["x"] + math.sin(t * pt["dr"] + pt["ph"]) * sway) % 1.0 + return x, y + + +# -- RuneScape: Dragonwilds - the original moonlit ridges and rising embers ---------- + +class DragonwildsScene(Scene): + def build(self, w, h, rng): + self.hue = QColor(self.accent).hueF() + self.ridges = [] + for layer in range(4): + pts = [] + base = 0.30 + layer * 0.17 + rough = 0.05 + layer * 0.05 + steps = 7 + layer * 3 + for i in range(steps + 1): + x = i / steps + y = base + (rng.random() - 0.5) * rough * 2 \ + + math.sin(x * math.pi * (1 + layer)) * 0.03 * (rng.random() + 0.4) + pts.append(QPointF(x * w, y * h)) + self.ridges.append(pts) + self.moon = (0.18 + rng.random() * 0.64, 0.26 + rng.random() * 0.18, + 20.0 + rng.random() * 12.0) + self.embers = self.make_particles(rng, 16, (0.0016, 0.005), (1.0, 3.2)) + + def paint(self, p, t): + w, h, hue = self.w, self.h, self.hue + vgrad(p, QRectF(0, 0, w, h), [(0, QColor.fromHsvF(hue, 0.55, 0.20)), + (0.55, QColor.fromHsvF((hue + 0.03) % 1, 0.5, 0.09)), + (1, QColor("#070A0E"))]) + mx, my, mr = self.moon + halo = QColor.fromHsvF(hue, 0.30, 1.0) + halo.setAlphaF(0.28) + glow(p, mx * w, my * h, mr * 3.2, halo) + p.setBrush(QColor.fromHsvF(hue, 0.12, 0.98)) + p.drawEllipse(QPointF(mx * w, my * h), mr, mr) + for i, pts in enumerate(self.ridges): + k = i / 3 + fill_ridge(p, pts, h, QColor.fromHsvF(hue, 0.42 * (1 - k), 0.16 * (1 - k) + 0.03)) + ember = QColor(self.ember).lighter(125) + for em in self.embers: + x, y = self.particle_pos(em, t) + if y < 0.35: + continue + a = max(0.0, min(0.8, (y - 0.35) * 1.1)) * (0.6 + 0.4 * math.sin(t * 2 + em["ph"])) + p.setBrush(col(ember.name(), a)) + p.drawEllipse(QPointF(x * w, y * h), em["s"] * 0.7, em["s"] * 0.7) + + +# -- Valheim - aurora, snowy peaks, a pine-black shoreline ------------------------------ + +class ValheimScene(Scene): + def build(self, w, h, rng): + self.stars = [(rng.random() * w, rng.random() * h * 0.55, rng.random()) for _ in range(70)] + self.peaks = [ridge(rng, w, h, 0.42 + i * 0.12, 0.10 - i * 0.02, 6 + i * 3, 0.02) + for i in range(3)] + self.pines = [] + x = -10 + while x < w + 10: + ph = h * (0.18 + rng.random() * 0.16) + self.pines.append((x, ph, 8 + rng.random() * 8)) + x += 7 + rng.random() * 9 + self.snow = self.make_particles(rng, 40, (0.001, 0.003), (0.8, 2.0)) + self.phase = rng.random() * 6.28 + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#050A16"), (0.6, "#0B1A26"), (1, "#0A1218")]) + for sx, sy, tw in self.stars: + a = 0.25 + 0.55 * (0.5 + 0.5 * math.sin(t * (1 + tw * 2) + tw * 9)) + p.setPen(Qt.NoPen) + p.setBrush(col("#DDEBFF", a * 0.8)) + p.drawEllipse(QPointF(sx, sy), 0.9, 0.9) + # aurora: soft ribbons made of vertical gradient strips along a sine path + for band, (c1, amp, off, yb) in enumerate(((self.accent, 0.10, 0.0, 0.22), + ("#7CE3FF", 0.07, 1.7, 0.30), + ("#B48CFF", 0.05, 3.1, 0.18))): + strips = 70 + for i in range(strips): + x = i / strips + y = yb + math.sin(x * 5.0 + t * 0.35 + off + self.phase) * amp \ + + math.sin(x * 11 + t * 0.6 + off) * 0.015 + top, height = y * h, h * (0.16 + 0.05 * math.sin(x * 7 + t + off)) + g = QLinearGradient(0, top, 0, top + height) + a = 0.16 + 0.12 * math.sin(x * 9 + t * 0.8 + off) + g.setColorAt(0.0, col(c1, 0)) + g.setColorAt(0.55, col(c1, a * (0.7 if band else 1.0))) + g.setColorAt(1.0, col(c1, 0)) + p.fillRect(QRectF(x * w, top, w / strips + 1, height), QBrush(g)) + # mountains with snow caps + for i, pts in enumerate(self.peaks): + base = QColor("#1B2E3C").darker(100 + i * 45) + fill_ridge(p, pts, h, base) + if i < 2: + p.save() + path = QPainterPath() + path.moveTo(pts[0].x(), h) + for pt in pts: + path.lineTo(pt) + path.lineTo(pts[-1].x(), h) + p.setClipPath(path) + top = min(pt.y() for pt in pts) + vgrad(p, QRectF(0, top, w, h * 0.12), [(0, col("#E8F4FF", 0.55 - i * 0.2)), + (1, col("#E8F4FF", 0))]) + p.restore() + # pine shoreline + p.setBrush(QColor("#050B0E")) + p.setPen(Qt.NoPen) + for x, ph, pw in self.pines: + base = h + 2 + path = QPainterPath() + tiers = 4 + for k in range(tiers): + ty = base - ph * (k / tiers) + hw = pw * (1 - k / (tiers + 0.6)) + path.moveTo(x - hw, ty) + path.lineTo(x, ty - ph / tiers * 1.6) + path.lineTo(x + hw, ty) + path.closeSubpath() + p.drawPath(path) + for s in self.snow: + x, y = self.particle_pos(s, t, direction=1, sway=0.02) + p.setBrush(col("#F2F8FF", 0.55)) + p.drawEllipse(QPointF(x * w, y * h), s["s"] * 0.6, s["s"] * 0.6) + + +# -- Enshrouded - violet shroud rolling around a flame ----------------------------------- + +class EnshroudedScene(Scene): + def build(self, w, h, rng): + self.hills = [smooth_ridge(rng, w, h, 0.55 + i * 0.13, 0.12, 4 + i) for i in range(3)] + self.tower_x = w * (0.62 + rng.random() * 0.2) + self.fog = [(rng.random(), 0.45 + rng.random() * 0.45, 60 + rng.random() * 90, + rng.random() * 6.28, 0.02 + rng.random() * 0.03) for _ in range(9)] + self.spores = self.make_particles(rng, 26, (0.001, 0.003), (1.0, 2.4)) + self.flame_x = w * (0.22 + rng.random() * 0.2) + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#120B22"), (0.5, "#2A1238"), (0.8, "#3A1630"), + (1, "#120A14")]) + glow(p, w * 0.75, h * 0.32, w * 0.45, col("#FF7A59", 0.18)) + # ruined tower + tx, ty = self.tower_x, h * 0.30 + path = QPainterPath() + path.moveTo(tx - 9, h * 0.62) + path.lineTo(tx - 7, ty + 10) + path.lineTo(tx - 3, ty) + path.lineTo(tx + 1, ty + 6) + path.lineTo(tx + 5, ty + 2) + path.lineTo(tx + 8, h * 0.62) + path.closeSubpath() + p.setPen(Qt.NoPen) + p.setBrush(QColor("#1A0F24")) + p.drawPath(path) + for i, hill in enumerate(self.hills): + p.setBrush(QColor("#1E1030").darker(100 + i * 60)) + p.drawPath(hill) + # shroud fog + for fx, fy, fr, ph, sp in self.fog: + x = ((fx + t * sp * 0.3) % 1.3 - 0.15) * w + y = fy * h + math.sin(t * 0.4 + ph) * 6 + glow(p, x, y, fr, col("#B06BFF" if ph > 3 else "#E0457A", 0.22)) + # flame + fx, fy = self.flame_x, h * 0.66 + flick = 0.8 + 0.2 * math.sin(t * 9) * math.sin(t * 5.3) + glow(p, fx, fy, 46 * flick, col(self.ember, 0.55)) + glow(p, fx, fy - 4, 12 * flick, col("#FFE2A8", 0.95), core=2.5) + for s in self.spores: + x, y = self.particle_pos(s, t) + a = 0.35 + 0.35 * math.sin(t * 2 + s["ph"]) + p.setBrush(col(self.accent, a)) + p.drawEllipse(QPointF(x * w, y * h), s["s"] * 0.7, s["s"] * 0.7) + + +# -- Palworld - a bright day with fat clouds and round friends on the hills ---------------- + +class PalworldScene(Scene): + def build(self, w, h, rng): + self.clouds = [] + for _ in range(5): + cx, cy, scale = rng.random(), 0.12 + rng.random() * 0.25, 0.7 + rng.random() * 0.8 + puffs = [((rng.random() - 0.5) * 50 * scale, (rng.random() - 0.5) * 10 * scale, + (10 + rng.random() * 12) * scale) for _ in range(6)] + self.clouds.append((cx, cy, puffs, 0.004 + rng.random() * 0.006)) + self.hills = [smooth_ridge(rng, w, h, 0.56 + i * 0.13, 0.14, 3 + i) for i in range(3)] + self.pals = [(0.15 + rng.random() * 0.7, 0.7 + rng.random() * 0.12, + 7 + rng.random() * 5, rng.random() * 6.28, + rng.choice(["#FFE3A3", "#9FE3FF", "#FFB3C8", "#C9F29B"])) + for _ in range(3)] + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#2F8DE0"), (0.5, "#6FC3F5"), (1, "#BEE8FF")]) + sx, sy = w * 0.82, h * 0.2 + glow(p, sx, sy, 80, col("#FFF4B8", 0.55)) + p.setBrush(col("#FFF6CC")) + p.drawEllipse(QPointF(sx, sy), 16, 16) + p.setPen(Qt.NoPen) + for cx, cy, puffs, sp in self.clouds: + x0 = ((cx + t * sp) % 1.3 - 0.15) * w + for dx, dy, r in puffs: + p.setBrush(col("#FFFFFF", 0.92)) + p.drawEllipse(QPointF(x0 + dx, cy * h + dy), r, r) + greens = ["#7DD36B", "#4EB45A", "#2E8E4C"] + for i, hill in enumerate(self.hills): + p.setBrush(QColor(greens[i])) + p.drawPath(hill) + for px, py, r, ph, c in self.pals: + hop = abs(math.sin(t * 2.2 + ph)) * 5 + x, y = px * w, py * h - hop + p.setBrush(col("#000000", 0.18)) + p.drawEllipse(QPointF(x, py * h + r * 0.9), r * 0.9, r * 0.25) + p.setBrush(QColor(c)) + p.drawEllipse(QPointF(x, y), r, r * 0.92) + ear = QPainterPath() + ear.moveTo(x - r * 0.7, y - r * 0.4) + ear.lineTo(x - r * 0.45, y - r * 1.35) + ear.lineTo(x - r * 0.1, y - r * 0.7) + ear.moveTo(x + r * 0.7, y - r * 0.4) + ear.lineTo(x + r * 0.45, y - r * 1.35) + ear.lineTo(x + r * 0.1, y - r * 0.7) + p.drawPath(ear) + p.setBrush(QColor("#2A2A2A")) + p.drawEllipse(QPointF(x - r * 0.33, y - r * 0.05), r * 0.12, r * 0.15) + p.drawEllipse(QPointF(x + r * 0.33, y - r * 0.05), r * 0.12, r * 0.15) + + +# -- Core Keeper - a pixel-art cave around the glowing Core -------------------------------- + +class CoreKeeperScene(Scene): + CELL = 5 + + def build(self, w, h, rng): + cw, ch = max(1, w // self.CELL), max(1, h // self.CELL) + img = QImage(cw, ch, QImage.Format_RGB32) + rock = [QColor("#151820"), QColor("#1C2029"), QColor("#232836"), QColor("#2B3142")] + cx, cy = cw * 0.5, ch * 0.48 + for y in range(ch): + for x in range(cw): + # a cavern: open (dark) near the middle, rock towards the edges + dx, dy = (x - cx) / (cw * 0.55), (y - cy) / (ch * 0.62) + d = dx * dx + dy * dy + (rng.random() - 0.5) * 0.18 + if d < 0.55: + c = QColor("#0B0D12") if (x + y) % 2 else QColor("#0D1016") + else: + c = rock[min(3, int((d - 0.55) * 5 + rng.random() * 1.5))] + img.setPixelColor(x, y, c) + # ore veins + self.ores = [] + for _ in range(14): + x, y = rng.randrange(cw), rng.randrange(ch) + dx, dy = (x - cx) / (cw * 0.55), (y - cy) / (ch * 0.62) + if dx * dx + dy * dy > 0.6: + c = rng.choice(["#E3A54D", "#5FE3F2", "#B87CF0"]) + img.setPixelColor(x, y, QColor(c)) + self.ores.append((x, y, c, rng.random() * 6.28)) + self.base = QPixmap.fromImage(img.scaled(cw * self.CELL, ch * self.CELL, + Qt.IgnoreAspectRatio, Qt.FastTransformation)) + self.core = (cx * self.CELL, cy * self.CELL) + self.torches = [(w * 0.18, h * 0.55), (w * 0.82, h * 0.5)] + + def paint(self, p, t): + p.drawPixmap(0, 0, self.base) + cx, cy = self.core + pulse = 0.75 + 0.25 * math.sin(t * 1.6) + glow(p, cx, cy, 120 * pulse, col(self.accent, 0.35)) + # the Core: a blocky crystal, drawn on the pixel grid + c = self.CELL + p.setPen(Qt.NoPen) + shape = [(0, -4), (-1, -3), (0, -3), (1, -3), (-2, -2), (-1, -2), (0, -2), (1, -2), + (2, -2), (-2, -1), (-1, -1), (0, -1), (1, -1), (2, -1), (-1, 0), (0, 0), + (1, 0), (0, 1)] + for dx, dy in shape: + shade_ = "#D8FBFF" if dx <= 0 and dy < -1 else self.accent + p.setBrush(QColor(shade_)) + p.drawRect(QRectF(cx + dx * c - c / 2, cy + dy * c, c, c)) + # pedestal + p.setBrush(QColor("#3A4152")) + p.drawRect(QRectF(cx - 3 * c - c / 2, cy + 2 * c, 7 * c, c * 2)) + for tx, ty in self.torches: + fl = 0.7 + 0.3 * math.sin(t * 11 + tx) + glow(p, tx, ty, 40 * fl, col(self.ember, 0.45)) + p.setBrush(QColor("#6B4A2A")) + p.drawRect(QRectF(tx - c / 2, ty, c, c * 3)) + p.setBrush(QColor("#FFD27A")) + p.drawRect(QRectF(tx - c / 2, ty - c, c, c)) + for x, y, oc, ph in self.ores: + if math.sin(t * 2 + ph) > 0.85: + p.setBrush(col("#FFFFFF", 0.9)) + p.drawRect(QRectF(x * c + 1, y * c + 1, c - 2, c - 2)) + + +# -- Sons of the Forest - pine trunks in the fog, a far fire ------------------------------ + +class SonsScene(Scene): + def build(self, w, h, rng): + self.layers = [] + for depth in range(4): + trunks = [] + x = -20 + while x < w + 20: + tw = (3 + depth * 3.5) * (0.7 + rng.random() * 0.6) + trunks.append((x, tw, rng.random() * 0.1)) + x += tw + 6 + rng.random() * (40 - depth * 7) + self.layers.append(trunks) + self.leaves = self.make_particles(rng, 18, (0.001, 0.0025), (1.2, 2.8)) + self.fire_x = w * (0.3 + rng.random() * 0.4) + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#1B201C"), (0.6, "#262B24"), (1, "#0C0E0C")]) + flick = 0.85 + 0.15 * math.sin(t * 7) * math.sin(t * 3.1) + glow(p, self.fire_x, h * 0.78, 90 * flick, col(self.accent, 0.35)) + p.setPen(Qt.NoPen) + for depth, trunks in enumerate(self.layers): + shade_ = 0.32 - depth * 0.085 + c = QColor.fromHsvF(0.28, 0.18, max(0.02, shade_ * 0.55)) + for x, tw, lean in trunks: + path = QPainterPath() + path.moveTo(x, h) + path.lineTo(x + lean * 30, 0) + path.lineTo(x + lean * 30 + tw * 0.8, 0) + path.lineTo(x + tw, h) + path.closeSubpath() + p.setBrush(c) + p.drawPath(path) + # fog band between depths + y = h * (0.55 + depth * 0.1) + math.sin(t * 0.3 + depth) * 4 + vgrad(p, QRectF(0, y - 18, w, 36), [(0, col("#9AA59A", 0)), + (0.5, col("#9AA59A", 0.10)), + (1, col("#9AA59A", 0))]) + for lf in self.leaves: + x, y = self.particle_pos(lf, t, direction=1, sway=0.04) + p.save() + p.translate(x * w, y * h) + p.rotate((t * 60 + lf["ph"] * 57) % 360) + p.setBrush(col("#6B5A3A", 0.7)) + p.drawEllipse(QPointF(0, 0), lf["s"] * 1.4, lf["s"] * 0.6) + p.restore() + + +# -- V Rising - blood moon, castle spires, bats ----------------------------------------------- + +class VRisingScene(Scene): + def build(self, w, h, rng): + self.moon = (w * (0.62 + rng.random() * 0.18), h * 0.34, 34 + rng.random() * 10) + self.craters = [((rng.random() - 0.5) * 1.2, (rng.random() - 0.5) * 1.2, + 0.08 + rng.random() * 0.14) for _ in range(6)] + self.cliff = ridge(rng, w, h, 0.66, 0.08, 9, 0.04) + self.castle_x = w * (0.18 + rng.random() * 0.15) + self.towers = [(dx, 22 + rng.random() * 30, 6 + rng.random() * 5) + for dx in (-34, -18, -4, 12, 28)] + self.bats = [(rng.random(), 0.15 + rng.random() * 0.35, 0.02 + rng.random() * 0.03, + rng.random() * 6.28, 3 + rng.random() * 3) for _ in range(7)] + self.mist = ridge(rng, w, h, 0.8, 0.04, 6, 0.02) + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#14061A"), (0.55, "#2E0B24"), (1, "#0E060C")]) + mx, my, mr = self.moon + glow(p, mx, my, mr * 3.4, col(self.accent, 0.35)) + p.setPen(Qt.NoPen) + p.setBrush(QColor("#C8283F")) + p.drawEllipse(QPointF(mx, my), mr, mr) + for cx, cy, cr in self.craters: + p.setBrush(col("#7E1428", 0.45)) + p.drawEllipse(QPointF(mx + cx * mr * 0.7, my + cy * mr * 0.7), cr * mr, cr * mr) + fill_ridge(p, self.cliff, h, QColor("#0A0409")) + # castle + bx = self.castle_x + base_y = min(pt.y() for pt in self.cliff) + 6 + p.setBrush(QColor("#0A0409")) + p.drawRect(QRectF(bx - 40, base_y - 18, 80, 30)) + for dx, th, tw in self.towers: + x = bx + dx + p.drawRect(QRectF(x - tw / 2, base_y - 18 - th, tw, th + 2)) + spire = QPainterPath() + spire.moveTo(x - tw / 2 - 1, base_y - 18 - th) + spire.lineTo(x, base_y - 18 - th - tw * 2.2) + spire.lineTo(x + tw / 2 + 1, base_y - 18 - th) + spire.closeSubpath() + p.drawPath(spire) + if math.sin(t * 0.7 + dx) > -0.2: + p.setBrush(col("#FF4D5E", 0.85)) + p.drawRect(QRectF(x - 1, base_y - 18 - th * 0.6, 2, 3)) + p.setBrush(QColor("#0A0409")) + for bx0, by, sp, ph, size in self.bats: + x = ((bx0 + t * sp) % 1.2 - 0.1) * w + y = by * h + math.sin(t * 1.3 + ph) * 8 + flap = math.sin(t * 14 + ph) * size * 0.8 + path = QPainterPath() + path.moveTo(x - size * 1.8, y - flap) + path.quadTo(x - size * 0.7, y - size * 0.2, x, y) + path.quadTo(x + size * 0.7, y - size * 0.2, x + size * 1.8, y - flap) + path.quadTo(x + size * 0.6, y + size * 0.4, x, y + size * 0.3) + path.quadTo(x - size * 0.6, y + size * 0.4, x - size * 1.8, y - flap) + p.setBrush(QColor("#050205")) + p.drawPath(path) + fill_ridge(p, self.mist, h, col("#3A0F2A", 0.5)) + + +# -- Grounded - the backyard from ant height ------------------------------------------------ + +class GroundedScene(Scene): + def build(self, w, h, rng): + self.blades = [] + for _ in range(42): + depth = rng.random() + self.blades.append((rng.random() * w, h * (0.25 + (1 - depth) * 0.45), + 3 + depth * 9, depth, (rng.random() - 0.5) * 0.5, + rng.random() * 6.28)) + self.blades.sort(key=lambda b: b[3]) + self.bokeh = [(rng.random() * w, rng.random() * h * 0.6, 8 + rng.random() * 26, + rng.random() * 6.28) for _ in range(12)] + self.dew = [(rng.randrange(len(self.blades)), 0.3 + rng.random() * 0.4) + for _ in range(5)] + self.seed = self.make_particles(rng, 3, (0.0006, 0.0012), (2.0, 3.0)) + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#BFE6A2"), (0.45, "#7CC46A"), (1, "#1E3F1A")]) + sx, sy = w * 0.25, h * 0.15 + glow(p, sx, sy, 160, col("#FFF3B0", 0.65)) + for bx, by, br, ph in self.bokeh: + a = 0.10 + 0.08 * math.sin(t * 0.8 + ph) + p.setPen(Qt.NoPen) + p.setBrush(col("#FFFBE0", a)) + p.drawEllipse(QPointF(bx, by), br, br) + tips = [] + for x, height, width, depth, lean, ph in self.blades: + sway = math.sin(t * 1.1 + ph) * (4 + depth * 6) + top_x = x + lean * height + sway + top_y = h - height * (0.9 + depth * 0.9) + path = QPainterPath() + path.moveTo(x - width / 2, h + 2) + path.quadTo(x - width / 3 + sway * 0.3, h - height * 0.6, top_x, top_y) + path.quadTo(x + width / 3 + sway * 0.3, h - height * 0.6, x + width / 2, h + 2) + path.closeSubpath() + g = QLinearGradient(0, top_y, 0, h) + base = QColor.fromHsvF(0.27 + depth * 0.03, 0.55 + depth * 0.2, 0.75 - depth * 0.5) + g.setColorAt(0, base.lighter(135)) + g.setColorAt(1, base.darker(160)) + p.setBrush(QBrush(g)) + p.drawPath(path) + tips.append((top_x, top_y, x, h)) + for idx, k in self.dew: + tx, ty, bx, by = tips[idx] + x, y = tx + (bx - tx) * k, ty + (by - ty) * k + glint = 0.6 + 0.4 * math.sin(t * 3 + idx) + p.setBrush(col("#E8FFF6", 0.55)) + p.drawEllipse(QPointF(x, y), 3.2, 3.2) + p.setBrush(col("#FFFFFF", glint)) + p.drawEllipse(QPointF(x - 1, y - 1), 1.1, 1.1) + p.setPen(QPen(col("#FFFFFF", 0.7), 0.8)) + for s in self.seed: + x, y = self.particle_pos(s, t, sway=0.05) + cx, cy = x * w, y * h + for k in range(8): + ang = k * math.pi / 4 + t * 0.4 + p.drawLine(QPointF(cx, cy), + QPointF(cx + math.cos(ang) * 6, cy + math.sin(ang) * 6)) + p.setPen(Qt.NoPen) + + +# -- Raft - sunset over open water, a raft and a fin ------------------------------------------ + +class RaftScene(Scene): + def build(self, w, h, rng): + self.horizon = h * 0.58 + self.sun_x = w * (0.55 + rng.random() * 0.3) + self.waves = [(0.0 + i * 0.1, 0.8 + i * 0.6, rng.random() * 6.28) for i in range(5)] + self.raft_x = w * (0.18 + rng.random() * 0.2) + self.gulls = [(rng.random(), 0.12 + rng.random() * 0.2, rng.random() * 6.28) + for _ in range(3)] + + def paint(self, p, t): + w, h, hz = self.w, self.h, self.horizon + vgrad(p, QRectF(0, 0, w, hz), [(0, "#1B2550"), (0.45, "#8A3F6E"), (0.8, "#F07A5A"), + (1, "#FFC07A")]) + glow(p, self.sun_x, hz, 110, col("#FFD58A", 0.6)) + p.setPen(Qt.NoPen) + p.setBrush(QColor("#FFE2A6")) + p.drawPie(QRectF(self.sun_x - 24, hz - 24, 48, 48), 0, 180 * 16) + vgrad(p, QRectF(0, hz, w, h - hz), [(0, "#2A6F8F"), (1, "#062030")]) + for i in range(10): # sun reflection streaks + y = hz + 4 + i * 6 + half = (26 - i * 2) * (0.8 + 0.2 * math.sin(t * 2 + i)) + p.setBrush(col("#FFD08A", 0.55 - i * 0.05)) + p.drawRect(QRectF(self.sun_x - half, y, half * 2, 1.6)) + for i, (depth, speed, ph) in enumerate(self.waves): + y0 = hz + (h - hz) * (0.15 + depth * 1.6) + path = QPainterPath() + path.moveTo(0, h) + for k in range(41): + x = k / 40 * w + y = y0 + math.sin(k * 0.6 + t * speed + ph) * (2 + i) + path.lineTo(x, y) + path.lineTo(w, h) + path.closeSubpath() + p.setBrush(col("#0B3A52", 0.35 + i * 0.1)) + p.drawPath(path) + # raft + bob = math.sin(t * 1.4) * 2 + rx, ry = self.raft_x, hz + (h - hz) * 0.42 + bob + p.setBrush(QColor("#5A3A22")) + p.drawRect(QRectF(rx - 18, ry, 36, 5)) + p.setBrush(QColor("#3A2616")) + p.drawRect(QRectF(rx - 1, ry - 26, 2, 26)) + sail = QPainterPath() + sail.moveTo(rx + 1, ry - 25) + sail.lineTo(rx + 16, ry - 8) + sail.lineTo(rx + 1, ry - 6) + sail.closeSubpath() + p.setBrush(QColor("#E8D8B8")) + p.drawPath(sail) + # shark fin circling + ang = t * 0.5 + fx = rx + math.cos(ang) * 70 + fy = ry + 14 + math.sin(ang) * 10 + fin = QPainterPath() + fin.moveTo(fx - 7, fy) + fin.quadTo(fx - 1, fy - 6, fx + 2, fy - 13) + fin.quadTo(fx + 3, fy - 5, fx + 7, fy) + fin.closeSubpath() + p.setBrush(QColor("#1C2C36")) + p.drawPath(fin) + p.setPen(QPen(col("#2A1A2A", 0.8), 1.2)) + for gx, gy, ph in self.gulls: + x = ((gx + t * 0.01) % 1.1) * w + y = gy * h + math.sin(t + ph) * 4 + flap = math.sin(t * 6 + ph) * 2.5 + p.drawLine(QPointF(x - 6, y - flap), QPointF(x, y)) + p.drawLine(QPointF(x, y), QPointF(x + 6, y - flap)) + p.setPen(Qt.NoPen) + + +# -- 7 Days to Die - a ruined skyline under a red sky ---------------------------------------- + +class SevenDaysScene(Scene): + def build(self, w, h, rng): + self.buildings = [] + x = -5 + while x < w + 5: + bw = 18 + rng.random() * 34 + bh = h * (0.18 + rng.random() * 0.36) + broken = [(rng.random(), rng.random() * 0.25) for _ in range(3)] + windows = [(rng.random(), rng.random(), rng.random() * 6.28) for _ in range(5)] + self.buildings.append((x, bw, bh, broken, windows)) + x += bw + rng.random() * 6 + self.moon = (w * (0.15 + rng.random() * 0.7), h * 0.26, 20 + rng.random() * 8) + self.ash = self.make_particles(rng, 36, (0.001, 0.003), (0.8, 1.8)) + self.walkers = [(rng.random(), 0.004 + rng.random() * 0.004, rng.random() * 6.28) + for _ in range(4)] + self.poles = [w * (0.1 + i * 0.27 + rng.random() * 0.05) for i in range(4)] + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#2A0A08"), (0.5, "#7A2414"), (0.8, "#B8481E"), + (1, "#2A120A")]) + mx, my, mr = self.moon + glow(p, mx, my, mr * 4, col("#FF5A3A", 0.4)) + p.setPen(Qt.NoPen) + p.setBrush(QColor("#E0432A")) + p.drawEllipse(QPointF(mx, my), mr, mr) + ground = h * 0.86 + for x, bw, bh, broken, windows in self.buildings: + top = ground - bh + path = QPainterPath() + path.moveTo(x, ground) + path.lineTo(x, top + broken[0][1] * bh) + path.lineTo(x + bw * broken[1][0] * 0.5, top + broken[1][1] * bh) + path.lineTo(x + bw * (0.5 + broken[2][0] * 0.5), top + broken[2][1] * bh * 0.4) + path.lineTo(x + bw, top + broken[0][1] * bh * 0.6) + path.lineTo(x + bw, ground) + path.closeSubpath() + p.setBrush(QColor("#1A0B07")) + p.drawPath(path) + for wx, wy, ph in windows: + if math.sin(t * 0.9 + ph) > 0.3: + p.setBrush(col("#FFB347", 0.75)) + p.drawRect(QRectF(x + 3 + wx * (bw - 8), top + bh * 0.3 + wy * bh * 0.6, 3, 4)) + p.setPen(QPen(QColor("#120604"), 1.2)) + for i, px in enumerate(self.poles): + p.drawLine(QPointF(px, ground), QPointF(px, ground - h * 0.32)) + p.drawLine(QPointF(px - 8, ground - h * 0.3), QPointF(px + 8, ground - h * 0.3)) + if i + 1 < len(self.poles): + nx = self.poles[i + 1] + wire = QPainterPath() + wire.moveTo(px, ground - h * 0.3) + wire.quadTo((px + nx) / 2, ground - h * 0.22, nx, ground - h * 0.3) + p.setBrush(Qt.NoBrush) + p.drawPath(wire) + p.setPen(Qt.NoPen) + p.setBrush(QColor("#0E0503")) + p.drawRect(QRectF(0, ground, w, h - ground)) + for wx0, sp, ph in self.walkers: + x = ((wx0 + t * sp) % 1.1 - 0.05) * w + y = ground + lurch = math.sin(t * 3 + ph) * 1.5 + p.setBrush(QColor("#080302")) + p.drawEllipse(QPointF(x + lurch, y - 15), 2.6, 2.8) + p.drawRect(QRectF(x - 2 + lurch * 0.5, y - 12, 4, 8)) + p.drawRect(QRectF(x - 2, y - 4, 1.5, 4)) + p.drawRect(QRectF(x + 0.5, y - 4, 1.5, 4)) + p.drawRect(QRectF(x + 1 + lurch * 0.5, y - 11, 6, 1.5)) + for a in self.ash: + x, y = self.particle_pos(a, t, direction=1, sway=0.03) + p.setBrush(col("#CFC2B8", 0.45)) + p.drawEllipse(QPointF(x * w, y * h), a["s"] * 0.6, a["s"] * 0.6) + + +# -- WorldSync library - a slowly turning globe, friends in orbit --------------------------- + +class LibraryScene(Scene): + def build(self, w, h, rng): + self.stars = [(rng.random() * w, rng.random() * h, rng.random()) for _ in range(90)] + self.nodes = [(rng.random() * 6.28, 0.55 + rng.random() * 0.5, 0.15 + rng.random() * 0.25, + rng.choice([self.accent, "#5CD6C9", self.ember, "#F27BA8"])) + for _ in range(6)] + + def paint(self, p, t): + w, h = self.w, self.h + vgrad(p, QRectF(0, 0, w, h), [(0, "#0B1030"), (0.6, "#0A0E22"), (1, "#080A14")]) + for sx, sy, tw in self.stars: + a = 0.2 + 0.5 * (0.5 + 0.5 * math.sin(t * (0.7 + tw) + tw * 11)) + p.setPen(Qt.NoPen) + p.setBrush(col("#DCE4FF", a)) + p.drawEllipse(QPointF(sx, sy), 0.8, 0.8) + cx, cy, r = w * 0.5, h * 0.62, min(w, h) * 0.42 + glow(p, cx, cy, r * 1.9, col(self.accent, 0.20)) + p.setBrush(col("#10183A", 0.95)) + p.drawEllipse(QPointF(cx, cy), r, r) + pen = QPen(col(self.accent, 0.35), 1.0) + p.setPen(pen) + p.setBrush(Qt.NoBrush) + for k in range(1, 6): # latitudes + yy = cy + r * math.cos(k * math.pi / 6) + rx = r * math.sin(k * math.pi / 6) + p.drawEllipse(QPointF(cx, yy), rx, rx * 0.18) + for k in range(6): # longitudes, turning + ang = (k / 6) * math.pi + t * 0.15 + rx = abs(math.cos(ang)) * r + p.setPen(QPen(col(self.accent, 0.12 + 0.3 * abs(math.cos(ang))), 1.0)) + p.drawEllipse(QPointF(cx, cy), rx, r) + # orbiting friends, linked to each other by faint arcs + pts = [] + for ph, rad, speed, c in self.nodes: + ang = ph + t * speed + x = cx + math.cos(ang) * r * rad * 1.6 + y = cy - r * 0.2 + math.sin(ang) * r * rad * 0.45 + pts.append((x, y, c, math.sin(ang))) + p.setPen(QPen(col(self.accent, 0.25), 1.0)) + for i in range(len(pts)): + a, b = pts[i], pts[(i + 1) % len(pts)] + path = QPainterPath() + path.moveTo(a[0], a[1]) + path.quadTo((a[0] + b[0]) / 2, min(a[1], b[1]) - 30, b[0], b[1]) + p.drawPath(path) + p.setPen(Qt.NoPen) + for x, y, c, depth in pts: + size = 2.6 + depth * 1.2 + glow(p, x, y, 12 + depth * 4, col(c, 0.5)) + p.setBrush(QColor(c)) + p.drawEllipse(QPointF(x, y), size, size) + + +SCENES = { + "dragonwilds": DragonwildsScene, "valheim": ValheimScene, + "enshrouded": EnshroudedScene, "palworld": PalworldScene, + "core_keeper": CoreKeeperScene, "sons_of_the_forest": SonsScene, + "v_rising": VRisingScene, "grounded": GroundedScene, "raft": RaftScene, + "seven_days_to_die": SevenDaysScene, "library": LibraryScene, +} + + +def make(scene_id: str, accent: str, ember: str) -> Scene: + return SCENES.get(scene_id, LibraryScene)(accent, ember) + + +def render(scene_id: str, w: int, h: int, accent: str, ember: str, + seed: int = 7, t: float = 2.5) -> QPixmap: + """A still frame, for library cards and thumbnails.""" + pm = QPixmap(w, h) + pm.fill(QColor("#000000")) + scene = make(scene_id, accent, ember) + scene.ensure(w, h, seed) + p = QPainter(pm) + p.setRenderHint(QPainter.Antialiasing) + scene.paint(p, t) + p.end() + return pm diff --git a/app/ui/settings.py b/app/ui/settings.py index a84bf14..e517e21 100644 --- a/app/ui/settings.py +++ b/app/ui/settings.py @@ -6,7 +6,7 @@ from PySide6.QtWidgets import (QCheckBox, QComboBox, QFrame, QHBoxLayout, QLabel, QScrollArea, QVBoxLayout, QWidget) -from ..core import autostart, paths, steam +from ..core import autostart, config, games, paths, steam from . import icons, theme, widgets EMOJI_CHOICES = ["", "🐉", "⚔️", "🛡️", "🏹", "🔥", "🌿", "🍺", "👑", "🧙", "🪓", "🦴"] @@ -84,8 +84,9 @@ def __init__(self, parent=None): form.addWidget(flair_hint) # -- game ---------------------------------------------------------------- - form.addWidget(self._section("GAME")) - self.save_dir_field = widgets.FormField("Dragonwilds save folder", browse="dir") + self.game_section = self._section("GAME") + form.addWidget(self.game_section) + self.save_dir_field = widgets.FormField("Save folder", browse="dir") self.save_dir_field.edit.editingFinished.connect(self._rescan) form.addWidget(self.save_dir_field) @@ -108,7 +109,7 @@ def __init__(self, parent=None): form.addWidget(self.world_section) self.world_field = widgets.WorldField( "World to sync", - hint="The save filename, without extension - must match on every PC.") + hint="Must be the same world on every PC.") form.addWidget(self.world_field) self.shared_field = widgets.FormField( "Shared folder", browse="dir", @@ -237,6 +238,8 @@ def _swatch(self, color_hex): pm.fill(QColor(color_hex)) return QIcon(pm) + _profile = games.DRAGONWILDS + def load(self, cfg: dict, world: dict | None): cfg = cfg or {} self.name_field.edit.setText(cfg.get("player_name", "")) @@ -246,8 +249,13 @@ def load(self, cfg: dict, world: dict | None): color = cfg.get("player_color", "") self.color_combo.setCurrentIndex( theme.AVATAR_COLORS.index(color) + 1 if color in theme.AVATAR_COLORS else 0) - self.save_dir_field.edit.setText(cfg.get("local_save_dir", str(paths.DEFAULT_SAVE_DIR))) - self.exe_field.edit.setText(cfg.get("exe_path") or "") + self._profile = config.world_game(world) + game = self._profile.name + self.game_section.setText(theme.caps(game)) + self.save_dir_field.label.setText(f"{game} save folder") + self.save_dir_field.edit.setText(config.game_save_dir(cfg, self._profile.id)) + self.exe_field.edit.setText(config.game_exe_path(cfg, self._profile.id) or "") + self.world_field.label.setText(f"{self._profile.world_word.capitalize()} to sync") self.detect_result.setText("") self.tray_check.setChecked(bool(cfg.get("close_to_tray", True))) self.startup_check.setChecked(autostart.is_enabled()) @@ -258,11 +266,13 @@ def load(self, cfg: dict, world: dict | None): self._world_id = world["id"] if world else None has_world = world is not None for w in (self.world_section, self.world_field, self.shared_field, - self.webhook_field, self.forget_btn, self.accent_row): + self.webhook_field, self.forget_btn): w.setVisible(has_world) + self.accent_row.setVisible(False) # banners follow the game's theme since 2.0 if world: - self.world_field.refresh(self.save_dir_field.value(), keep_current=False) - self.world_field.combo.setCurrentText(world.get("world_name", "")) + self.world_field.refresh(self.save_dir_field.value(), keep_current=False, + profile=self._profile) + self.world_field.set_value(world.get("world_name", "")) self.shared_field.edit.setText(world.get("sync_dir", "")) self.webhook_field.edit.setText(world.get("webhook_url") or "") accent = world.get("accent") or "" @@ -276,10 +286,10 @@ def load(self, cfg: dict, world: dict | None): self.world_field.clear_error() def _rescan(self): - self.world_field.refresh(self.save_dir_field.value()) + self.world_field.refresh(self.save_dir_field.value(), profile=self._profile) def _detect_exe(self): - found = steam.find_game_exe() + found = steam.find_game_exe(self._profile) if found: self.exe_field.edit.setText(str(found)) self.detect_result.setText("Found it.") @@ -327,8 +337,8 @@ def _submit(self): "player_name": self.name_field.value(), "player_emoji": emoji, "player_color": color, - "local_save_dir": self.save_dir_field.value(), - "exe_path": exe or None, + "_game": {"id": self._profile.id, "save_dir": self.save_dir_field.value(), + "exe_path": exe or None}, "close_to_tray": self.tray_check.isChecked(), "launch_on_startup": self.startup_check.isChecked(), "publish_status_page": self.statuspage_check.isChecked(), diff --git a/app/ui/theme.py b/app/ui/theme.py index 525bcae..5cf87cf 100644 --- a/app/ui/theme.py +++ b/app/ui/theme.py @@ -1,20 +1,23 @@ """Design system: palette, typography, and the global stylesheet. -A dark-fantasy game-launcher look: deep warm-obsidian base, cinematic depth, -an emerald "go" accent for action and an ember-gold accent for identity and -attention. Cinzel display type carries the fantasy; a clean sans keeps the -body legible. Red strictly for destruction. +The palette below is the Dragonwilds look the app started with. Since 2.0 +every game has its own theme (gamethemes.py): ``use(theme_id)`` swaps these +module-level tokens and ``apply_game`` re-applies the stylesheet, so code +that reads ``theme.ACCENT`` at paint time follows the active game. Text +greys, amber and red stay the same in every theme. Red strictly for +destruction. """ from PySide6.QtGui import QFont from PySide6.QtWidgets import QApplication from ..core import paths -from . import fonts +from . import fonts, gamethemes # -- palette ---------------------------------------------------------------- BG = "#0A0D12" # window base (deep warm obsidian) BG_HI = "#10161E" # top of the ambient gradient +BG_LO = "#070A0E" # bottom of the ambient gradient SURFACE = "#12191F" # cards SURFACE_2 = "#1A232C" # raised elements, hover fills SURFACE_GLASS = "rgba(22, 30, 39, 0.72)" # frosted panels over the banner @@ -27,11 +30,15 @@ TEXT_FAINT = "#5E6B7A" ACCENT = "#3ECF8E" # dragonfire emerald - the "go / play" colour ACCENT_HOVER = "#55DCA0" +ACCENT_PRESSED = "#29A872" ACCENT_TEAL = "#1FA89B" # gradient partner +ACCENT_TEAL_HI = "#23BCAD" +ACCENT_TEAL_LO = "#17897E" ON_ACCENT = "#07130D" # text on emerald EMBER = "#E8A23D" # ember gold - identity, titles, flourishes EMBER_HI = "#F6C56A" EMBER_DEEP = "#B9761F" +EMBER_PRESSED = "#8F5A16" GOLD_TEXT = "#E6C892" # legible gold for text over dark art AMBER = "#F2B441" RED = "#E5484D" @@ -43,40 +50,80 @@ FONT_STACK = '"Segoe UI Variable Display", "Segoe UI", sans-serif' +# Active theme (set by use()); Dragonwilds until something else is chosen. +THEME_ID = "dragonwilds" +CAPS = True +TITLE_SPACING = 3 +_DISPLAY = _DECO = _VOICE = None # None -> the bundled Cinzel family + + +def _family(name): + """Map a theme's font name to the family Qt actually registered.""" + bundled = {"Cinzel": fonts.DISPLAY, "Cinzel Decorative": fonts.DISPLAY_DECO, + "EB Garamond": fonts.VOICE} + return bundled.get(name, name) + + def display_family() -> str: - return fonts.DISPLAY + return _family(_DISPLAY) if _DISPLAY else fonts.DISPLAY def deco_family() -> str: - return fonts.DISPLAY_DECO + return _family(_DECO) if _DECO else fonts.DISPLAY_DECO def voice_family() -> str: - return fonts.VOICE + return _family(_VOICE) if _VOICE else fonts.VOICE -UI_CACHE = paths.APP_DIR / "ui" +def scene() -> str: + return gamethemes.get(THEME_ID).scene + -_CHEVRON_SVG = ( - '' - '' -) +def use(theme_id: str): + """Switch the module tokens to `theme_id` (no restyling - see apply_game).""" + global THEME_ID, CAPS, TITLE_SPACING, _DISPLAY, _DECO, _VOICE + t = gamethemes.get(theme_id) + globals().update(t.tokens()) + THEME_ID, CAPS, TITLE_SPACING = t.id, t.caps, t.title_spacing + _DISPLAY, _DECO, _VOICE = t.display, t.deco, t.voice -_CHECK_SVG = ( - '' - '' -) +def caps(text: str) -> str: + """Section labels in the active theme's casing.""" + return text.upper() if CAPS else text + + +def apply_game(theme_id: str): + """Switch theme and restyle the running app. Cheap enough per page change.""" + if theme_id == THEME_ID and QApplication.instance().styleSheet(): + return + use(theme_id) + QApplication.instance().setStyleSheet(build_qss()) + + +UI_CACHE = paths.APP_DIR / "ui" def _write_qss_assets() -> tuple[str, str]: - """QSS image: url() needs real files; render the few we use to disk.""" + """QSS image: url() needs real files; render the few we use to disk. + + Built per call so the check mark follows the active theme's colours. + """ + chevron_svg = ( + '' + '' + ) + check_svg = ( + '' + '' + ) UI_CACHE.mkdir(parents=True, exist_ok=True) chevron = UI_CACHE / "chevron-down.svg" - chevron.write_text(_CHEVRON_SVG, encoding="utf-8") - check = UI_CACHE / "check.svg" - check.write_text(_CHECK_SVG, encoding="utf-8") + chevron.write_text(chevron_svg, encoding="utf-8") + check = UI_CACHE / f"check-{THEME_ID}.svg" + check.write_text(check_svg, encoding="utf-8") return chevron.as_posix(), check.as_posix() @@ -91,7 +138,7 @@ def build_qss() -> str: #Chrome {{ background: qlineargradient(x1:0, y1:0, x2:0.35, y2:1, - stop:0 {BG_HI}, stop:0.55 {BG}, stop:1 #070A0E); + stop:0 {BG_HI}, stop:0.55 {BG}, stop:1 {BG_LO}); border: 1px solid {BORDER}; border-radius: 16px; }} @@ -100,10 +147,10 @@ def build_qss() -> str: #TitleBar {{ background: transparent; }} #TitleText {{ color: {GOLD_TEXT}; - font-family: "{fonts.DISPLAY}"; + font-family: "{display_family()}"; font-size: 14px; font-weight: 600; - letter-spacing: 3px; + letter-spacing: {TITLE_SPACING}px; }} QPushButton[variant="titlebar"], QPushButton[variant="titlebarClose"] {{ background: transparent; @@ -129,18 +176,18 @@ def build_qss() -> str: border-radius: 14px; }} #HeroHeadline {{ - font-family: "{fonts.DISPLAY}"; + font-family: "{display_family()}"; font-size: 22px; font-weight: 600; letter-spacing: 0.5px; }} #HeroSubline {{ font-size: 12.5px; color: {TEXT_DIM}; }} #SectionLabel {{ - font-family: "{fonts.DISPLAY}"; + font-family: "{display_family()}"; font-size: 11px; font-weight: 600; letter-spacing: 2.5px; color: {EMBER}; }} #FooterText {{ font-size: 11px; color: {TEXT_FAINT}; }} #WorldTitle {{ - font-family: "{fonts.DISPLAY_DECO}"; + font-family: "{deco_family()}"; font-size: 30px; font-weight: 700; color: #FFFFFF; letter-spacing: 1px; }} @@ -151,7 +198,7 @@ def build_qss() -> str: /* -- buttons ------------------------------------------------------------ */ QPushButton[variant="primary"] {{ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, - stop:0 #33C286, stop:1 {ACCENT_TEAL}); + stop:0 {ACCENT}, stop:1 {ACCENT_TEAL}); color: {ON_ACCENT}; border: none; border-radius: 12px; @@ -162,11 +209,11 @@ def build_qss() -> str: }} QPushButton[variant="primary"]:hover {{ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, - stop:0 #3FD494, stop:1 #23BCAD); + stop:0 {ACCENT_HOVER}, stop:1 {ACCENT_TEAL_HI}); }} QPushButton[variant="primary"]:pressed {{ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, - stop:0 #29A872, stop:1 #17897E); + stop:0 {ACCENT_PRESSED}, stop:1 {ACCENT_TEAL_LO}); }} QPushButton[variant="primary"]:disabled {{ background: {SURFACE_2}; @@ -176,7 +223,7 @@ def build_qss() -> str: QPushButton[variant="ember"] {{ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {EMBER}, stop:1 {EMBER_DEEP}); - color: #1A1206; + color: {BG_LO}; border: none; border-radius: 12px; font-size: 14px; @@ -190,7 +237,7 @@ def build_qss() -> str: }} QPushButton[variant="ember"]:pressed {{ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, - stop:0 {EMBER_DEEP}, stop:1 #8F5A16); + stop:0 {EMBER_DEEP}, stop:1 {EMBER_PRESSED}); }} QPushButton[variant="ember"]:disabled {{ background: {SURFACE_2}; @@ -366,16 +413,17 @@ def build_qss() -> str: }} #SettingsSection {{ - font-family: "{fonts.DISPLAY}"; + font-family: "{display_family()}"; font-size: 11px; font-weight: 600; letter-spacing: 2px; color: {EMBER}; }} """ -def apply(app: QApplication): +def apply(app: QApplication, theme_id: str = "dragonwilds"): app.setStyle("Fusion") fonts.load() + use(theme_id) font = QFont() font.setFamilies(["Segoe UI Variable Display", "Segoe UI"]) font.setPointSizeF(9.5) diff --git a/app/ui/titlebar.py b/app/ui/titlebar.py index 0d7377a..e864ee3 100644 --- a/app/ui/titlebar.py +++ b/app/ui/titlebar.py @@ -1,6 +1,7 @@ """Custom titlebar for the frameless window: mark, wordmark, window controls. -The dragon-eye mark keeps a secret: five quick clicks wake it. +The mark follows the game: WorldSync's orbit, or the dragon eye in a +Dragonwilds world - and the eye keeps a secret: five quick clicks wake it. """ from PySide6.QtCore import QElapsedTimer, Qt, Signal @@ -19,10 +20,14 @@ class SecretMark(QLabel): def __init__(self, parent=None): super().__init__(parent) - self.setPixmap(icons.pixmap("dragon", theme.ACCENT, 18)) + self.retheme() self._clicks = 0 self._timer = QElapsedTimer() + def retheme(self): + name = "dragon" if theme.THEME_ID == "dragonwilds" else "orbit" + self.setPixmap(icons.pixmap(name, theme.ACCENT, 18)) + def mousePressEvent(self, e): if e.button() == Qt.LeftButton: if not self._timer.isValid() or self._timer.elapsed() > SECRET_WINDOW_MS: @@ -49,11 +54,11 @@ def __init__(self, parent=None): row.setContentsMargins(16, 0, 10, 0) row.setSpacing(8) - mark = SecretMark() - mark.awakened.connect(self.secret_awakened.emit) - row.addWidget(mark) + self.mark = SecretMark() + self.mark.awakened.connect(self.secret_awakened.emit) + row.addWidget(self.mark) - title = QLabel("DRAGONWILDS SYNC") + title = QLabel("WORLDSYNC") title.setObjectName("TitleText") row.addWidget(title) row.addStretch(1) @@ -71,6 +76,9 @@ def __init__(self, parent=None): close.clicked.connect(lambda: self.window().close()) row.addWidget(close) + def retheme(self): + self.mark.retheme() + def mousePressEvent(self, e): if e.button() == Qt.LeftButton: handle = self.window().windowHandle() diff --git a/app/ui/tray.py b/app/ui/tray.py index 2190a43..95640f0 100644 --- a/app/ui/tray.py +++ b/app/ui/tray.py @@ -22,10 +22,10 @@ def __init__(self, icon: QIcon, parent=None): return self.tray = QSystemTrayIcon(icon, self) - self.tray.setToolTip("Dragonwilds Sync") + self.tray.setToolTip("WorldSync") menu = QMenu() - open_action = menu.addAction("Open Dragonwilds Sync") + open_action = menu.addAction("Open WorldSync") open_action.triggered.connect(self.open_requested.emit) menu.addSeparator() quit_action = menu.addAction("Quit") @@ -58,7 +58,7 @@ def notify_update(self, version: str): if self.available: self.tray.showMessage( "Update available", - f"Version {version} is ready. Open Dragonwilds Sync to update.", + f"Version {version} is ready. Open WorldSync to update.", QSystemTrayIcon.Information, 7000) def show_minimized_tip(self): @@ -66,6 +66,6 @@ def show_minimized_tip(self): self._tip_shown = True self.tray.showMessage( "Still keeping watch", - "Dragonwilds Sync lives in the tray now - you'll get a ping " + "WorldSync lives in the tray now - you'll get a ping " "when a friend shares a save. Right-click the icon to quit.", QSystemTrayIcon.Information, 6000) diff --git a/app/ui/widgets.py b/app/ui/widgets.py index f8e8701..8cb1650 100644 --- a/app/ui/widgets.py +++ b/app/ui/widgets.py @@ -260,13 +260,22 @@ def __init__(self, icon_name, title, description, parent=None): col.setSpacing(3) t = QLabel(title) t.setStyleSheet("background: transparent; font-size: 14px; font-weight: 650;") + self._title, self._icon, self._icon_name = t, ic, icon_name d = QLabel(description) + self._desc = d d.setWordWrap(True) d.setStyleSheet(f"background: transparent; color: {theme.TEXT_DIM}; font-size: 12px;") col.addWidget(t) col.addWidget(d) row.addLayout(col, 1) + def set_text(self, title, description): + self._title.setText(title) + self._desc.setText(description) + + def retheme(self): + self._icon.setPixmap(icons.pixmap(self._icon_name, theme.ACCENT, 22)) + # clicked is wired via mousePressEvent -> callback for simplicity def set_on_click(self, callback): self._on_click = callback @@ -330,6 +339,7 @@ def __init__(self, text="PLAY", parent=None, variant="primary", f.setWeight(QFont.Black) f.setLetterSpacing(QFont.AbsoluteSpacing, 2.0) self.setFont(f) + self._fixed_glow = glow_color self._glow = QGraphicsDropShadowEffect(self) self._glow.setColor(QColor(glow_color or theme.ACCENT)) self._glow.setOffset(0, 3) @@ -349,6 +359,10 @@ def __init__(self, text="PLAY", parent=None, variant="primary", self._breathe.setLoopCount(-1) self._breathe.start() + def retheme(self): + if not self._fixed_glow: + self._glow.setColor(QColor(theme.ACCENT)) + def _flare(self, target): self._breathe.stop() self._hover_anim.stop() @@ -378,21 +392,28 @@ def setEnabled(self, on): self._breathe.stop() -def scan_worlds(save_dir: str) -> list[str]: - """World names (= .sav stems) found in a save folder.""" - folder = Path(save_dir) if save_dir else None - names: list[str] = [] - if folder and folder.exists(): - seen = set() - for p in sorted(folder.glob("*.sav")): - if p.stem not in seen: - seen.add(p.stem) - names.append(p.stem) - return names +def scan_worlds(save_dir: str, profile=None) -> list: + """Worlds found in a save folder for `profile` (Dragonwilds by default), + most recently played first.""" + from ..core import games + return games.discover_worlds(profile or games.DRAGONWILDS, save_dir) if save_dir else [] + + +def _world_display(found) -> str: + """'Castle Night · 2 h ago'. Long code-like ids are left out of the label.""" + when = fmt.relative_time(found.modified) if found.modified else "" + label = found.label + if len(label) > 22 and " " not in label: # Palworld-style 32-char codes + label = f"{label[:8]}…{label[-4:]}" + return f"{label} · {when}" if when else label class WorldField(QWidget): - """Label + editable combo listing the worlds found in the save folder.""" + """Label + editable combo listing the worlds found in the save folder. + + Items show a friendly label and when the world was last played; value() + returns the world id the profile uses (folder name, file stem, slot). + """ def __init__(self, label="World", value="", hint="", parent=None): super().__init__(parent) @@ -400,9 +421,9 @@ def __init__(self, label="World", value="", hint="", parent=None): box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) box.setSpacing(6) - lab = QLabel(label) - lab.setProperty("role", "fieldLabel") - box.addWidget(lab) + self.label = QLabel(label) + self.label.setProperty("role", "fieldLabel") + box.addWidget(self.label) self.combo = QComboBox() self.combo.setEditable(True) self.combo.setFixedHeight(38) @@ -415,23 +436,36 @@ def __init__(self, label="World", value="", hint="", parent=None): self._hint = hint box.addWidget(self.note) - def refresh(self, save_dir: str, keep_current=True): - current = self.combo.currentText().strip() - names = scan_worlds(save_dir) + def refresh(self, save_dir: str, keep_current=True, profile=None): + current = self.value() + found = scan_worlds(save_dir, profile) self.combo.blockSignals(True) self.combo.clear() - self.combo.addItems(names) + for f in found: + self.combo.addItem(_world_display(f), f.id) + ids = [f.id for f in found] if keep_current and current: - self.combo.setCurrentText(current) - elif names: - self.combo.setCurrentText(names[0]) + self.set_value(current) + elif found: + self.combo.setCurrentIndex(0) else: self.combo.setCurrentText("") self.combo.blockSignals(False) - return names + return ids + + def set_value(self, world_id: str): + idx = self.combo.findData(world_id) + if idx >= 0: + self.combo.setCurrentIndex(idx) + else: + self.combo.setCurrentText(world_id) def value(self) -> str: - return self.combo.currentText().strip() + text = self.combo.currentText().strip() + idx = self.combo.findText(text) + if idx >= 0 and self.combo.itemData(idx): + return self.combo.itemData(idx) + return text def set_error(self, message): self.note.setText(message) @@ -458,9 +492,9 @@ def __init__(self, label, value="", hint="", browse=None, placeholder="", parent box.setContentsMargins(0, 0, 0, 0) box.setSpacing(6) - lab = QLabel(label) - lab.setProperty("role", "fieldLabel") - box.addWidget(lab) + self.label = QLabel(label) + self.label.setProperty("role", "fieldLabel") + box.addWidget(self.label) row = QHBoxLayout() row.setSpacing(8) diff --git a/app/ui/window.py b/app/ui/window.py index 734cb6a..47fa2c0 100644 --- a/app/ui/window.py +++ b/app/ui/window.py @@ -11,12 +11,15 @@ from ..controller import Controller from ..core import backups as backups_core -from ..core import config, preflight +from ..core import config, games, preflight from .about_page import AboutPage +from .addgame_page import AddGamePage from .backups_page import BackupsPage from .characters_page import CharactersPage from .grimoire_page import GrimoirePage +from .guide_page import GuidePage from .invite_page import InvitePage +from .library_page import LibraryPage from .main_screen import MainPage from .note_overlay import NoteOverlay from .onboarding import OnboardingPage @@ -46,7 +49,11 @@ def __init__(self, controller: Controller, app_icon: QIcon, parent=None): | Qt.WindowMinimizeButtonHint) self.setAttribute(Qt.WA_TranslucentBackground) self.setFixedSize(WINDOW_W, WINDOW_H) - self.setWindowTitle("Dragonwilds Sync") + self.setWindowTitle("WorldSync") + self._onboarding_return = None + self._pending_name = "" + self._first_run = not controller.has_config + theme.apply_game(self._start_theme()) outer = QVBoxLayout(self) outer.setContentsMargins(*([SHADOW_MARGIN] * 4)) @@ -80,10 +87,15 @@ def __init__(self, controller: Controller, app_icon: QIcon, parent=None): self.characters_page = CharactersPage() self.grimoire_page = GrimoirePage() self.saga_page = SagaPage() + self.library_page = LibraryPage() + self.addgame_page = AddGamePage() + self.guide_page = GuidePage() + self._guide_return = None for p in (self.main_page, self.settings_page, self.onboarding_page, self.invite_page, self.backups_page, self.about_page, self.preflight_page, self.characters_page, self.grimoire_page, - self.saga_page): + self.saga_page, self.library_page, self.addgame_page, + self.guide_page): self.pages.addWidget(p) self._backup_ctx = None @@ -96,9 +108,11 @@ def __init__(self, controller: Controller, app_icon: QIcon, parent=None): self._wire() if controller.has_config: - self._sync_world_header() - self._show_page(self.main_page) - controller.refresh_status() + view = (controller.cfg or {}).get("last_view") + if view in games.BY_ID and config.worlds_for_game(controller.cfg, view): + self._open_game(view) + else: + self._go_library() else: self.titlebar.settings_btn.hide() self.onboarding_page.start_fresh() @@ -122,6 +136,20 @@ def _wire(self): self.main_page.update_clicked.connect(self._apply_update) self.main_page.characters_clicked.connect(self._open_characters) self.main_page.saga_clicked.connect(self._open_saga) + self.main_page.library_clicked.connect(self._go_library) + self.main_page.guide_clicked.connect( + lambda: self._open_guide(self.controller.active_game().id)) + self.onboarding_page.guide_requested.connect(self._open_guide) + self.guide_page.back_requested.connect( + lambda: self._show_page(self._guide_return or self.main_page)) + + # library & game picker + self.library_page.game_opened.connect(self._open_game) + self.library_page.add_game_clicked.connect(lambda: self._open_add_game()) + self.library_page.join_clicked.connect(self._join_from_library) + self.addgame_page.game_chosen.connect(self._on_game_chosen) + self.addgame_page.back_requested.connect(self._addgame_back) + c.library_summary.connect(self.library_page.set_summary) self.saga_page.back_requested.connect(lambda: self._show_page(self.main_page)) self.saga_page.export_requested.connect(c.export_saga) # (the grimoire deliberately has no menu entry - see _awaken_secret) @@ -166,9 +194,10 @@ def _wire(self): # onboarding / settings / sub-pages self.onboarding_page.finished.connect(self._finish_onboarding) - self.onboarding_page.cancelled.connect(lambda: self._show_page(self.main_page)) + self.onboarding_page.cancelled.connect(self._onboarding_back) + self.onboarding_page.name_chosen.connect(self._on_name_chosen) self.settings_page.saved.connect(self._save_settings) - self.settings_page.cancelled.connect(lambda: self._show_page(self.main_page)) + self.settings_page.cancelled.connect(self._settings_back) self.settings_page.remove_world_requested.connect(self._remove_world) self.settings_page.about_requested.connect( lambda: self._show_page(self.about_page)) @@ -192,8 +221,106 @@ def _wire(self): # -- controller-driven bits ---------------------------------------------------- def _sync_world_header(self): cfg = self.controller.cfg or {} + world = self.controller.active_world() + profile = config.world_game(world) self.main_page.set_player_name(cfg.get("player_name", "")) - self.main_page.set_worlds(config.worlds(cfg), cfg.get("active_world")) + self.main_page.set_game(profile.short, "characters" in profile.extras) + self.main_page.set_worlds(config.worlds_for_game(cfg, profile.id), + cfg.get("active_world")) + + # -- library, games and themes ------------------------------------------------- + def _start_theme(self) -> str: + cfg = self.controller.cfg or {} + view = cfg.get("last_view") + if self.controller.has_config and view in games.BY_ID \ + and config.worlds_for_game(cfg, view): + return view + return "library" + + def _apply_theme(self, theme_id: str): + if theme_id == theme.THEME_ID: + return + theme.apply_game(theme_id) + self.main_page.retheme() + self.library_page.retheme() + self.titlebar.retheme() + + def _go_library(self): + c = self.controller + cfg = c.cfg or {} + self._apply_theme("library") + lib = config.library(cfg) + counts = {g.id: len(config.worlds_for_game(cfg, g.id)) for g in lib} + self.library_page.set_player(c.player_name, len(lib)) + self.library_page.set_games(lib, counts) + c.set_last_view("library") + c.request_library_summary() + self._show_page(self.library_page) + + def _open_game(self, game_id: str): + c = self.controller + if not config.worlds_for_game(c.cfg, game_id): + # in the library but no worlds (all forgotten): straight to its setup + self._start_game_flow(game_id, back_to=self.library_page) + return + c.open_game(game_id) + self._apply_theme(game_id) + self._sync_world_header() + self._show_page(self.main_page) + c.refresh_status() + + def _open_guide(self, game_id: str): + self._guide_return = self.pages.currentWidget() + save_dir = config.game_save_dir(self.controller.cfg or {}, game_id) + self.guide_page.load(games.get(game_id), save_dir) + self._show_page(self.guide_page) + + def _open_add_game(self, first_run=False): + self._apply_theme("library") + self.addgame_page.open((self.controller.cfg or {}).get("library", []), + first_run=first_run) + self._show_page(self.addgame_page) + + def _addgame_back(self): + if self._first_run and not self.controller.has_config: + self.onboarding_page.start_fresh() + self.onboarding_page._go(1) # back to the name step + self._show_page(self.onboarding_page) + else: + self._go_library() + + def _on_name_chosen(self, name): + self._pending_name = name + self._open_add_game(first_run=True) + + def _player_for_flow(self) -> str: + return self.controller.player_name or self._pending_name + + def _start_game_flow(self, game_id, back_to=None): + profile = games.get(game_id) + self._onboarding_return = back_to or self.addgame_page + self._apply_theme(game_id) + save_dir = config.game_save_dir(self.controller.cfg or {}, game_id) + self.onboarding_page.start_game(profile, self._player_for_flow(), save_dir) + self._show_page(self.onboarding_page) + + def _on_game_chosen(self, game_id): + self._start_game_flow(game_id, back_to=self.addgame_page) + + def _join_from_library(self): + self._onboarding_return = self.library_page + self.onboarding_page.start_join(self._player_for_flow()) + self._show_page(self.onboarding_page) + + def _onboarding_back(self): + target = self._onboarding_return or self.main_page + if target is self.library_page: + self._go_library() + elif target is self.addgame_page: + self._open_add_game(first_run=self._first_run and not self.controller.has_config) + else: + self._apply_theme(self.controller.active_game().id) + self._show_page(target) def _on_confirm_request(self, request): answer = self.confirm.ask(request["title"], request["body"], @@ -330,61 +457,82 @@ def _reload_backups(self): # -- onboarding & worlds ----------------------------------------------------------- def _finish_onboarding(self, payload): c = self.controller + game_id = payload.get("game") or games.DEFAULT_GAME world = config.make_world(payload["world_name"], payload["sync_dir"], - share_link=payload.get("share_link")) + share_link=payload.get("share_link"), game=game_id, + label=payload.get("world_label")) + shown = config.world_label(world) if c.has_config: - c.add_world(world) + c.add_world(world, save_dir=payload.get("local_save_dir")) else: - c.setup_first_config(payload["player_name"], payload["local_save_dir"], world) + c.setup_first_config(payload["player_name"] or self._pending_name, + payload.get("local_save_dir"), world) + self._first_run = False self.titlebar.settings_btn.show() - self._sync_world_header() - self._show_page(self.main_page) + self._open_game(game_id) if payload["kind"] == "join": self.toasts.show_toast("success", - f"Welcome to {payload['world_name']}. Hit Play - " + f"Welcome to {shown}. Hit Play - " f"the latest save comes to you.") else: self.toasts.show_toast("success", - f"{payload['world_name']} is ready. Invite your " + f"{shown} is ready. Invite your " f"friends from the button up top.") def _open_add_world(self): - self.onboarding_page.start_add_world(self.controller.player_name) - self._show_page(self.onboarding_page) + game_id = self.controller.active_game().id + self._start_game_flow(game_id, back_to=self.main_page) def _remove_world(self, world_id): world = config.world_by_id(self.controller.cfg, world_id) - name = world["world_name"] if world else "this world" + name = config.world_label(world) if world else "this world" if self.confirm.ask( f"Forget {name}?", "This only removes it from the app on this PC. The shared folder, " "the saves, and your friends' setups are untouched - you can " "rejoin with an invite code any time.", danger_label="Forget world", safe_label="Keep it"): + game_id = config.world_game(world).id self.controller.remove_world(world_id) - self._sync_world_header() - self._show_page(self.main_page) if not self.controller.has_config: - self.titlebar.settings_btn.hide() - self.onboarding_page.start_fresh() - self._show_page(self.onboarding_page) + self.controller.remove_game(game_id) + self._go_library() + elif config.worlds_for_game(self.controller.cfg, game_id): + self._open_game(game_id) + else: + self.controller.remove_game(game_id) + self._go_library() # -- settings ------------------------------------------------------------------------ def _open_settings(self): if self.pages.currentWidget() is self.onboarding_page \ and not self.controller.has_config: return + here = self.pages.currentWidget() + if here in (self.library_page, self.addgame_page): + self._settings_return = self.library_page + elif here is not self.settings_page: + self._settings_return = self.main_page self.settings_page.load(self.controller.cfg, self.controller.active_world()) self._show_page(self.settings_page) + def _settings_back(self): + if getattr(self, "_settings_return", None) is self.library_page: + self._go_library() + else: + self._show_page(self.main_page) + def _save_settings(self, global_fields, world_fields): c = self.controller + game_fields = global_fields.pop("_game", None) + if game_fields: + c.update_game(game_fields["id"], game_fields["save_dir"], game_fields["exe_path"]) c.update_globals(global_fields) if world_fields: wid = world_fields.pop("id") c.update_world(wid, world_fields) self._sync_world_header() - self._show_page(self.main_page) + self._settings_back() self.toasts.show_toast("success", "Settings saved.") c.refresh_status() @@ -411,7 +559,9 @@ def _open_saga(self): def _awaken_secret(self): """The eye is the only door. No menu entry, no trace - five quick clicks on the titlebar mark, every time.""" - if not self.controller.has_config: + if not self.controller.has_config or not self.controller.is_dragonwilds(): + return + if self.pages.currentWidget() is not self.main_page: return self._open_grimoire() @@ -576,10 +726,13 @@ def _open_backups(self): world = self.controller.active_world() if not world: return + flat = config.effective_cfg(self.controller.cfg, world) self._backup_ctx = { "kind": "world", - "title": world["world_name"], - "save_dir": self.controller.cfg["local_save_dir"], + "title": config.world_label(world), + "save_dir": flat["local_save_dir"], + "patterns": flat["patterns"], + "mirror": flat["mirror"], "match": world["world_name"], "root": config.backup_root_for(world["id"]), "back_page": self.main_page, @@ -622,7 +775,8 @@ def _restore_backup(self, info): def worker(): try: count = backups_core.restore_backup( - info.path, ctx["save_dir"], ctx["match"], ctx["root"]) + info.path, ctx["save_dir"], ctx["match"], ctx["root"], + patterns=ctx.get("patterns"), mirror=ctx.get("mirror", False)) if count: self.controller.toast.emit( "success", "Backup restored to this PC." @@ -714,7 +868,7 @@ def closeEvent(self, event): if self.controller.phase in ("waiting", "ingame", "pushing"): stay = not self.confirm.ask( "The game is still running", - "If you quit Dragonwilds Sync now, your progress won't be shared " + "If you quit WorldSync now, your progress won't be shared " "automatically when you finish playing.\n\n" "You can always share it later with “Save my progress now”.", danger_label="Quit anyway", safe_label="Stay open") diff --git a/build.ps1 b/build.ps1 index ccbc850..78ccb44 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,4 +1,4 @@ -# One-command build: produces dist\DragonwildsSync.exe +# One-command build: produces dist\WorldSync.exe # Usage: .\build.ps1 $ErrorActionPreference = "Stop" @@ -17,13 +17,13 @@ if ($LASTEXITCODE -ne 0) { throw "Tests failed - not building." } Write-Host "Regenerating icon..." .\.venv\Scripts\python.exe tools\generate_icon.py -Write-Host "Building DragonwildsSync.exe..." +Write-Host "Building WorldSync.exe..." # PyInstaller writes its progress log to stderr; don't let PowerShell treat that as a failure. $ErrorActionPreference = "Continue" -.\.venv\Scripts\python.exe -m PyInstaller --noconfirm DragonwildsSync.spec 2>&1 | Out-Host +.\.venv\Scripts\python.exe -m PyInstaller --noconfirm WorldSync.spec 2>&1 | Out-Host if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed." } $ErrorActionPreference = "Stop" Write-Host "" -Write-Host "Done -> dist\DragonwildsSync.exe" +Write-Host "Done -> dist\WorldSync.exe" Write-Host "(Optional: compile installer.iss with Inno Setup for a setup wizard.)" diff --git a/docs/GAMES.md b/docs/GAMES.md new file mode 100644 index 0000000..500e597 --- /dev/null +++ b/docs/GAMES.md @@ -0,0 +1,171 @@ +# Setting up each game + + + +The same guide is in the app: open a game's world menu and choose +*How to set up*, or use the link during setup. + +## Every game + +- Everyone in the group needs the game, a cloud drive app (Google Drive, Dropbox or OneDrive) and WorldSync. +- Always start the game with Play in WorldSync. It pulls the newest world first and shares yours back when you close the game. +- One person hosts at a time. Playing together still works the normal way: one person hosts in-game and the others join; WorldSync makes sure that host has the latest world. + +| Game | Status | +|---|---| +| [RuneScape: Dragonwilds](#runescape-dragonwilds) | Tested | +| [Valheim](#valheim) | Beta | +| [Enshrouded](#enshrouded) | Beta | +| [Palworld](#palworld) | Beta | +| [Core Keeper](#core-keeper) | Beta | +| [Sons of the Forest](#sons-of-the-forest) | Beta | +| [V Rising](#v-rising) | Beta | +| [Grounded](#grounded) | Beta | +| [Raft](#raft) | Beta | +| [7 Days to Die](#7-days-to-die) | Beta | + +## RuneScape: Dragonwilds + +1. Start Dragonwilds, create or load the world you want to share, then quit to desktop. +2. In WorldSync, pick that world by its name from the in-game world list. +3. Characters are yours: everyone keeps their own character file, only the world travels. Turn on Character travel (world menu → Characters) to take yours between your own PCs. + +**Where the saves live** + +- `%LOCALAPPDATA%\RSDragonwilds\Saved\SaveGames` + +WorldSync calls one of these a *world*. The world name as it appears in the game's world list. + +## Valheim + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start Valheim, choose Start Game and select your world. +2. If the world is stored in Steam Cloud, use Manage Saves and Move to Local first, otherwise WorldSync can't see it. +3. Quit to desktop, then pick the world by its name in WorldSync. +4. Characters stay on each player's PC, so everyone brings their own Viking. +5. Playing with mods? Everyone needs the same mods, the same as joining a normal server. + +**Where the saves live** + +- `%USERPROFILE%\AppData\LocalLow\IronGate\Valheim\worlds_local` + +WorldSync calls one of these a *world*. The world name from the Start Game screen. + +## Enshrouded + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start Enshrouded, load the world you want to share once, then quit to desktop. +2. Enshrouded names worlds with an 8 character code. WorldSync lists them with the most recently played first, so the top one is usually the right one. +3. With Steam Cloud saves on, the worlds live under Steam\userdata. WorldSync looks there too; if it still finds nothing, browse to Steam\userdata\\1203620\remote. +4. Characters are separate files, so every player keeps their own. + +**Where the saves live** + +- `%USERPROFILE%\Saved Games\Enshrouded` +- `C:\Program Files (x86)\Steam\userdata\\1203620\remote` + +WorldSync calls one of these a *world*. Enshrouded names world files with an 8 character code. Pick the one you played most recently. + +## Palworld + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. The person who created the co-op world starts Palworld, loads it, then quits to desktop. +2. Worlds are folders with a long code name. WorldSync lists them with the most recently played first. +3. Know the host quirk: Palworld ties the original host's character to their PC. When a friend hosts the shared world, the original host's character can look reset. Everyone else keeps theirs. PalworldSaveTools can move a host character if you need it. +4. This is for the in-game co-op world, not a dedicated server. + +**Where the saves live** + +- `%LOCALAPPDATA%\Pal\Saved\SaveGames\` + +WorldSync calls one of these a *world*. Palworld names world folders with a long code. Pick the one you played most recently. + +## Core Keeper + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start Core Keeper, load the world, then quit to desktop. +2. Worlds are numbered by their slot on the world menu (slot 1 is file 0). Pick the slot you play in. +3. Everyone in the group uses that same slot for this world. If a friend already has a different world there, WorldSync backs it up before replacing it, but a free slot is cleaner. +4. Characters are separate, so everyone keeps their own. + +**Where the saves live** + +- `%USERPROFILE%\AppData\LocalLow\Pugstorm\Core Keeper\Steam\` + +WorldSync calls one of these a *slot*. Core Keeper numbers worlds by their slot on the world menu. + +## Sons of the Forest + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. The host starts a Multiplayer game, saves at a shelter or tent, then quits to desktop. +2. Multiplayer saves are numbered folders. WorldSync lists them with the most recently played first. +3. The host's own inventory and stats live inside the save, so whoever hosts the shared world plays with that host inventory. Guests keep theirs. + +**Where the saves live** + +- `%USERPROFILE%\AppData\LocalLow\Endnight\SonsOfTheForest\Saves\\Multiplayer` + +WorldSync calls one of these a *save*. Multiplayer saves are numbered folders. Pick the one you played most recently. + +## V Rising + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start V Rising and host a Private Game, play a moment so it saves, then quit to desktop. +2. WorldSync shows the world by the server name you gave it. +3. Every vampire is stored per Steam account inside the world, so all friends keep their own character whoever hosts. The game settings travel with the world too. + +**Where the saves live** + +- `%USERPROFILE%\AppData\LocalLow\Stunlock Studios\VRising\Saves\v3` + +WorldSync calls one of these a *world*. Each private game is a folder with a long code name. + +## Grounded + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Use the Steam version. Game Pass saves sit in a protected folder WorldSync can't reach. +2. Start Grounded, load the world, then quit to desktop. +3. Each world is its own folder. WorldSync lists them with the most recently played first. + +**Where the saves live** + +- `%USERPROFILE%\Saved Games\Grounded\` +- `%USERPROFILE%\Saved Games\Grounded` + +WorldSync calls one of these a *world*. Each world is a folder with a screenshot inside to recognise it. + +## Raft + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start Raft, load the world you want to share, then quit to desktop. +2. Not sure which folder it is? Load World in Raft has an Open Save Folder button. +3. Pick the world by its name in WorldSync. + +**Where the saves live** + +- `%USERPROFILE%\AppData\LocalLow\Redbeet Interactive\Raft\User\User_\World` + +WorldSync calls one of these a *world*. The world name from Load World. + +## 7 Days to Die + +*Beta: the save layout follows community guides and WorldSync's own tests. Every overwrite is backed up first; reports on GitHub move it to tested.* + +1. Start 7 Days to Die, continue the save you want to share, then quit to desktop. +2. Pick the save by its name. For a random-gen map, the generated map folder travels with it automatically. +3. The first share can be a few hundred MB. Let your cloud drive finish uploading before a friend presses Play. +4. Everyone needs the same game version (the same Steam beta branch, if you use one). + +**Where the saves live** + +- `%APPDATA%\7DaysToDie` + +WorldSync calls one of these a *save*. Your save names from Continue Game; the map travels along with it. diff --git a/docs/screenshots/01_onboarding_welcome.png b/docs/screenshots/01_onboarding_welcome.png deleted file mode 100644 index dbed6cf..0000000 Binary files a/docs/screenshots/01_onboarding_welcome.png and /dev/null differ diff --git a/docs/screenshots/01_welcome.png b/docs/screenshots/01_welcome.png new file mode 100644 index 0000000..20bd73c Binary files /dev/null and b/docs/screenshots/01_welcome.png differ diff --git a/docs/screenshots/02_onboarding_name.png b/docs/screenshots/02_onboarding_name.png deleted file mode 100644 index bf216fb..0000000 Binary files a/docs/screenshots/02_onboarding_name.png and /dev/null differ diff --git a/docs/screenshots/02_pick_a_game.png b/docs/screenshots/02_pick_a_game.png new file mode 100644 index 0000000..48e1384 Binary files /dev/null and b/docs/screenshots/02_pick_a_game.png differ diff --git a/docs/screenshots/03_find_the_world.png b/docs/screenshots/03_find_the_world.png new file mode 100644 index 0000000..17f44fe Binary files /dev/null and b/docs/screenshots/03_find_the_world.png differ diff --git a/docs/screenshots/03_onboarding_choice.png b/docs/screenshots/03_onboarding_choice.png deleted file mode 100644 index 17a9dfc..0000000 Binary files a/docs/screenshots/03_onboarding_choice.png and /dev/null differ diff --git a/docs/screenshots/04_library.png b/docs/screenshots/04_library.png new file mode 100644 index 0000000..8930190 Binary files /dev/null and b/docs/screenshots/04_library.png differ diff --git a/docs/screenshots/04_onboarding_shared.png b/docs/screenshots/04_onboarding_shared.png deleted file mode 100644 index 0715b12..0000000 Binary files a/docs/screenshots/04_onboarding_shared.png and /dev/null differ diff --git a/docs/screenshots/05_every_game_its_own_look.png b/docs/screenshots/05_every_game_its_own_look.png new file mode 100644 index 0000000..5955a0c Binary files /dev/null and b/docs/screenshots/05_every_game_its_own_look.png differ diff --git a/docs/screenshots/05_onboarding_join_watch.png b/docs/screenshots/05_onboarding_join_watch.png deleted file mode 100644 index da6cbb5..0000000 Binary files a/docs/screenshots/05_onboarding_join_watch.png and /dev/null differ diff --git a/docs/screenshots/06_friend_playing.png b/docs/screenshots/06_friend_playing.png new file mode 100644 index 0000000..dc80884 Binary files /dev/null and b/docs/screenshots/06_friend_playing.png differ diff --git a/docs/screenshots/06_main_up_to_date.png b/docs/screenshots/06_main_up_to_date.png deleted file mode 100644 index 3d29c45..0000000 Binary files a/docs/screenshots/06_main_up_to_date.png and /dev/null differ diff --git a/docs/screenshots/07_in_game.png b/docs/screenshots/07_in_game.png new file mode 100644 index 0000000..1456c1b Binary files /dev/null and b/docs/screenshots/07_in_game.png differ diff --git a/docs/screenshots/07_main_new_save.png b/docs/screenshots/07_main_new_save.png deleted file mode 100644 index 3a7044e..0000000 Binary files a/docs/screenshots/07_main_new_save.png and /dev/null differ diff --git a/docs/screenshots/08_invite.png b/docs/screenshots/08_invite.png new file mode 100644 index 0000000..ced6890 Binary files /dev/null and b/docs/screenshots/08_invite.png differ diff --git a/docs/screenshots/08_main_friend_playing.png b/docs/screenshots/08_main_friend_playing.png deleted file mode 100644 index f3f6fd0..0000000 Binary files a/docs/screenshots/08_main_friend_playing.png and /dev/null differ diff --git a/docs/screenshots/09_conflict.png b/docs/screenshots/09_conflict.png new file mode 100644 index 0000000..3a9ebc1 Binary files /dev/null and b/docs/screenshots/09_conflict.png differ diff --git a/docs/screenshots/09_main_turn_claimed.png b/docs/screenshots/09_main_turn_claimed.png deleted file mode 100644 index c5f5634..0000000 Binary files a/docs/screenshots/09_main_turn_claimed.png and /dev/null differ diff --git a/docs/screenshots/10_backups.png b/docs/screenshots/10_backups.png new file mode 100644 index 0000000..a1a4b04 Binary files /dev/null and b/docs/screenshots/10_backups.png differ diff --git a/docs/screenshots/10_main_in_game.png b/docs/screenshots/10_main_in_game.png deleted file mode 100644 index ab1a0f2..0000000 Binary files a/docs/screenshots/10_main_in_game.png and /dev/null differ diff --git a/docs/screenshots/11_about.png b/docs/screenshots/11_about.png new file mode 100644 index 0000000..e08efc9 Binary files /dev/null and b/docs/screenshots/11_about.png differ diff --git a/docs/screenshots/11_main_toast.png b/docs/screenshots/11_main_toast.png deleted file mode 100644 index 369469d..0000000 Binary files a/docs/screenshots/11_main_toast.png and /dev/null differ diff --git a/docs/screenshots/12_invite.png b/docs/screenshots/12_invite.png deleted file mode 100644 index 4e06881..0000000 Binary files a/docs/screenshots/12_invite.png and /dev/null differ diff --git a/docs/screenshots/13_backups.png b/docs/screenshots/13_backups.png deleted file mode 100644 index e731340..0000000 Binary files a/docs/screenshots/13_backups.png and /dev/null differ diff --git a/docs/screenshots/14_settings.png b/docs/screenshots/14_settings.png deleted file mode 100644 index a244f5e..0000000 Binary files a/docs/screenshots/14_settings.png and /dev/null differ diff --git a/docs/screenshots/15_about.png b/docs/screenshots/15_about.png deleted file mode 100644 index eb6a948..0000000 Binary files a/docs/screenshots/15_about.png and /dev/null differ diff --git a/docs/screenshots/16_note_prompt.png b/docs/screenshots/16_note_prompt.png deleted file mode 100644 index 990dea5..0000000 Binary files a/docs/screenshots/16_note_prompt.png and /dev/null differ diff --git a/docs/screenshots/17_conflict.png b/docs/screenshots/17_conflict.png deleted file mode 100644 index a37bdf6..0000000 Binary files a/docs/screenshots/17_conflict.png and /dev/null differ diff --git a/docs/screenshots/18_preflight.png b/docs/screenshots/18_preflight.png deleted file mode 100644 index 93aa6c2..0000000 Binary files a/docs/screenshots/18_preflight.png and /dev/null differ diff --git a/docs/screenshots/19_backups_checkpoints.png b/docs/screenshots/19_backups_checkpoints.png deleted file mode 100644 index 5e7de44..0000000 Binary files a/docs/screenshots/19_backups_checkpoints.png and /dev/null differ diff --git a/docs/screenshots/20_update_bar.png b/docs/screenshots/20_update_bar.png deleted file mode 100644 index fd285d4..0000000 Binary files a/docs/screenshots/20_update_bar.png and /dev/null differ diff --git a/docs/screenshots/21_characters.png b/docs/screenshots/21_characters.png deleted file mode 100644 index 1c56721..0000000 Binary files a/docs/screenshots/21_characters.png and /dev/null differ diff --git a/docs/screenshots/23_saga.png b/docs/screenshots/23_saga.png deleted file mode 100644 index b22ede9..0000000 Binary files a/docs/screenshots/23_saga.png and /dev/null differ diff --git a/installer.iss b/installer.iss index 08e6cb4..d3a5a2e 100644 --- a/installer.iss +++ b/installer.iss @@ -1,19 +1,19 @@ -; Optional Inno Setup script - turns dist\DragonwildsSync.exe into a proper +; Optional Inno Setup script - turns dist\WorldSync.exe into a proper ; installer with Start Menu + Desktop shortcuts. ; ; 1. Install Inno Setup: winget install JRSoftware.InnoSetup ; 2. Build the exe first: .\build.ps1 -; 3. Compile: iscc installer.iss -> dist\DragonwildsSync-Setup.exe +; 3. Compile: iscc installer.iss -> dist\WorldSync-Setup.exe [Setup] -AppName=Dragonwilds Sync -AppVersion=1.3.2 -AppPublisher=Andor & friends -DefaultDirName={autopf}\Dragonwilds Sync -DefaultGroupName=Dragonwilds Sync +AppName=WorldSync +AppVersion=2.0.0 +AppPublisher=AndorManu +DefaultDirName={autopf}\WorldSync +DefaultGroupName=WorldSync DisableProgramGroupPage=yes OutputDir=dist -OutputBaseFilename=DragonwildsSync-Setup +OutputBaseFilename=WorldSync-Setup SetupIconFile=app\assets\icon.ico Compression=lzma2 SolidCompression=yes @@ -21,14 +21,14 @@ WizardStyle=modern PrivilegesRequired=lowest [Files] -Source: "dist\DragonwildsSync.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "dist\WorldSync.exe"; DestDir: "{app}"; Flags: ignoreversion [Icons] -Name: "{group}\Dragonwilds Sync"; Filename: "{app}\DragonwildsSync.exe" -Name: "{autodesktop}\Dragonwilds Sync"; Filename: "{app}\DragonwildsSync.exe"; Tasks: desktopicon +Name: "{group}\WorldSync"; Filename: "{app}\WorldSync.exe" +Name: "{autodesktop}\WorldSync"; Filename: "{app}\WorldSync.exe"; Tasks: desktopicon [Tasks] Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription: "Additional shortcuts:" [Run] -Filename: "{app}\DragonwildsSync.exe"; Description: "Launch Dragonwilds Sync"; Flags: nowait postinstall skipifsilent +Filename: "{app}\WorldSync.exe"; Description: "Launch WorldSync"; Flags: nowait postinstall skipifsilent diff --git a/tests/test_config.py b/tests/test_config.py index 9258d14..e233819 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,4 +1,4 @@ -"""Config schema v2 migration and accessors.""" +"""Config schema migration (v1 -> v3) and accessors.""" from app.core import config @@ -15,7 +15,9 @@ def test_v1_config_migrates_to_one_world(): v2, wid = config.migrate_config(dict(V1_CFG)) - assert v2["schema"] == 2 + assert v2["schema"] == 3 + assert v2["library"] == ["dragonwilds"] + assert v2["worlds"][0]["game"] == "dragonwilds" assert v2["player_name"] == "Andor" assert v2["local_save_dir"] == r"C:\saves" assert len(v2["worlds"]) == 1 @@ -46,7 +48,12 @@ def test_v1_state_migrates_under_world_id(): def test_effective_cfg_matches_v1_shape(): v2, wid = config.migrate_config(dict(V1_CFG)) flat = config.effective_cfg(v2, config.active_world(v2)) - assert flat == V1_CFG + # every v1 key comes through unchanged... + assert {k: flat[k] for k in V1_CFG} == V1_CFG + # ...and the WorldSync additions keep the core on its v1 behaviour + assert flat["patterns"] is None + assert flat["mirror"] is False + assert flat["game"] == "dragonwilds" def test_world_state_slice_is_mutable_and_persistent(): diff --git a/tests/test_every_game.py b/tests/test_every_game.py new file mode 100644 index 0000000..5f47f70 --- /dev/null +++ b/tests/test_every_game.py @@ -0,0 +1,198 @@ +"""End to end, for every supported game, on two simulated PCs. + +Each game gets its real save-folder layout (Steam-ID folders and all) under +a fake home folder. The test then runs what a group actually does: find the +save folder, discover the world, share it from PC A, pull it on PC B, play +on B, share back, pull on A, and hit a real conflict. Other worlds sitting +in the same save folder must never travel or be touched. +""" + +import json +from pathlib import Path + +import pytest + +from app.core import config, games, health +from app.core.sync import SyncResult, do_pull, do_push +from tools.games_doc import render as render_games_doc + +STEAM = "76561198000000001" + +# game id -> (save folder under home, world id, the world's files, other files there) +LAYOUTS = { + "dragonwilds": ( + "AppData/Local/RSDragonwilds/Saved/SaveGames", "Ashenreach", + ["Ashenreach.sav", "Ashenreach.sav.backup"], + ["Frostspire.sav"]), + "valheim": ( + "AppData/LocalLow/IronGate/Valheim/worlds_local", "Midgard", + ["Midgard.fwl", "Midgard.db", "Midgard.db.old"], + ["Midgard2.fwl", "Midgard2.db"]), + "enshrouded": ( + "Saved Games/Enshrouded", "3ad85aea", + ["3ad85aea", "3ad85aea-1", "3ad85aea_info"], + ["9b1c2d3e", "characters"]), + "palworld": ( + f"AppData/Local/Pal/Saved/SaveGames/{STEAM}", "0123456789ABCDEF0123456789ABCDEF", + ["0123456789ABCDEF0123456789ABCDEF/Level.sav", + "0123456789ABCDEF0123456789ABCDEF/LevelMeta.sav", + "0123456789ABCDEF0123456789ABCDEF/Players/00000000000000000000000000000001.sav"], + ["FEDCBA9876543210FEDCBA9876543210/Level.sav"]), + "core_keeper": ( + f"AppData/LocalLow/Pugstorm/Core Keeper/Steam/{STEAM}", "1", + ["worlds/1.world.gzip", "maps/0/1.mapparts.gzip", "worldinfos/1.json", + "worldgenparams/1.json"], + ["worlds/0.world.gzip", "maps/0/0.mapparts.gzip", "worldinfos/0.json", + "worlds/10.world.gzip"]), + "sons_of_the_forest": ( + f"AppData/LocalLow/Endnight/SonsOfTheForest/Saves/{STEAM}/Multiplayer", "0412345678", + ["0412345678/GameStateSaveData.json", "0412345678/SaveData.json", + "0412345678/PlayerInventorySaveData.json"], + ["0499999999/SaveData.json"]), + "v_rising": ( + "AppData/LocalLow/Stunlock Studios/VRising/Saves/v3", "a1b2c3d4-0000", + ["a1b2c3d4-0000/AutoSave_31.save.gz", "a1b2c3d4-0000/ServerHostSettings.json", + "a1b2c3d4-0000/ServerGameSettings.json"], + ["ffff0000-1111/AutoSave_2.save.gz"]), + "grounded": ( + "Saved Games/Grounded/2535412345678901", "Backyard", + ["Backyard/SaveData.sav", "Backyard/Screenshot.png"], + ["Hedge/SaveData.sav"]), + "raft": ( + f"AppData/LocalLow/Redbeet Interactive/Raft/User/User_{STEAM}/World", "Seagull", + ["Seagull/Seagull.rgd", "Seagull/Seagull-Latest.rgd"], + ["Island/Island.rgd"]), + "seven_days_to_die": ( + "AppData/Roaming/7DaysToDie", "Pregen06k1/Horde Night", + ["Saves/Pregen06k1/Horde Night/main.ttw", + "Saves/Pregen06k1/Horde Night/Player/76561198000000001.ttp", + "GeneratedWorlds/Pregen06k1/dtm.raw"], + ["Saves/Navezgane/Other/main.ttw", "GeneratedWorlds/OtherMap/dtm.raw"]), +} + + +def test_every_game_has_a_layout_here(): + assert set(LAYOUTS) == {g.id for g in games.ALL} + + +def write(path: Path, text: str): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((text * 300).encode()) # comfortably over the health minimum + + +def use_home(monkeypatch, home: Path): + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.setenv("LOCALAPPDATA", str(home / "AppData" / "Local")) + monkeypatch.setenv("APPDATA", str(home / "AppData" / "Roaming")) + + +def snapshot(root: Path, rels) -> dict: + return {r: (root / r).read_bytes() for r in rels} + + +def make_pc(monkeypatch, home: Path, game_id: str, shared: Path, player: str): + use_home(monkeypatch, home) + profile = games.get(game_id) + save_dir = games.default_save_dir(profile) + assert save_dir is not None, f"{game_id}: save folder not found from its templates" + cfg, _ = config.migrate_config({"player_name": player, "worlds": []}) + config.set_game_save_dir(cfg, game_id, str(save_dir)) + world = config.make_world(LAYOUTS[game_id][1], str(shared), game=game_id) + return config.effective_cfg(cfg, world), save_dir + + +def logs(): + return lambda message: None + + +def yes(title, body): + return True + + +def no(title, body): + return False + + +@pytest.mark.parametrize("game_id", sorted(LAYOUTS)) +def test_full_round_trip(game_id, tmp_path, monkeypatch): + rel_root, world_id, world_files, others = LAYOUTS[game_id] + shared = tmp_path / "cloud" / "shared" + home_a, home_b = tmp_path / "pc_a", tmp_path / "pc_b" + for rel in world_files: + write(home_a / rel_root / rel, f"A-{rel}") + for rel in others: + write(home_a / rel_root / rel, f"A-other-{rel}") + write(home_b / rel_root / rel, f"B-other-{rel}") # B has its own other worlds + + # PC A finds the folder and the world, then shares it + flat_a, root_a = make_pc(monkeypatch, home_a, game_id, shared, "Andor") + assert root_a == home_a / rel_root + found = [w.id for w in games.discover_worlds(games.get(game_id), root_a)] + assert world_id in found + assert health.check_local_save(root_a, world_id, flat_a["patterns"]).ok + state_a = {"last_applied_version": 0, "last_hash": None} + res, _ = do_push(flat_a, state_a, logs(), yes, tmp_path / "bk_a") + assert res == SyncResult.PUSHED + manifest = json.loads((shared / "version.json").read_text()) + assert manifest["game"] == game_id + for rel in world_files: + assert (shared / rel).is_file(), f"{game_id}: {rel} didn't travel" + for rel in others: + assert not (shared / rel).exists(), f"{game_id}: {rel} leaked into the shared folder" + + # PC B pulls it next to its own worlds + flat_b, root_b = make_pc(monkeypatch, home_b, game_id, shared, "Kim") + others_b = snapshot(root_b, others) + state_b = {"last_applied_version": 0, "last_hash": None} + res, _ = do_pull(flat_b, state_b, logs(), yes, tmp_path / "bk_b") + assert res == SyncResult.PULLED + assert snapshot(root_b, world_files) == snapshot(root_a, world_files) + assert snapshot(root_b, others) == others_b + + # Kim plays: the main file changes (and folder worlds grow a new autosave) + write(root_b / world_files[0], "B-played") + extra = None + if flat_b["patterns"] is not None and "/" in world_files[0]: + extra = str(Path(world_files[0]).parent / "AutoSave_new.dat").replace("\\", "/") + write(root_b / extra, "B-new-autosave") + from app.core.sync import world_files as files_of + belongs = {f.relative_to(root_b).as_posix() + for f in files_of(root_b, world_id, flat_b["patterns"])} + if extra not in belongs: # slot-file games: a stray file isn't the world's + extra = None + res, _ = do_push(flat_b, state_b, logs(), yes, tmp_path / "bk_b") + assert res == SyncResult.PUSHED + + # Andor picks it up + use_home(monkeypatch, home_a) + res, _ = do_pull(flat_a, state_a, logs(), yes, tmp_path / "bk_a") + assert res == SyncResult.PULLED + assert (root_a / world_files[0]).read_bytes() == (root_b / world_files[0]).read_bytes() + if extra: + assert (root_a / extra).read_bytes() == (root_b / extra).read_bytes() + for rel in others: + assert (root_a / rel).read_bytes().startswith(b"A-other-") + + # a real conflict: Andor played offline while Kim shared again + write(root_a / world_files[0], "A-offline") + write(root_b / world_files[0], "B-second-session") + use_home(monkeypatch, home_b) + assert do_push(flat_b, state_b, logs(), yes, tmp_path / "bk_b")[0] == SyncResult.PUSHED + use_home(monkeypatch, home_a) + res, _ = do_pull(flat_a, state_a, logs(), no, tmp_path / "bk_a") + assert res == SyncResult.CONFLICT_CANCELLED + assert (root_a / world_files[0]).read_bytes().startswith(b"A-offline") + + +def test_every_game_has_a_setup_guide(): + for g in games.ALL: + steps = games.setup_steps(g) + assert len(steps) >= 3, f"{g.id} needs a real setup guide" + assert all("—" not in s for s in steps) + assert len(games.COMMON_STEPS) >= 3 + + +def test_games_doc_is_up_to_date(): + doc = Path(__file__).resolve().parent.parent / "docs" / "GAMES.md" + assert doc.read_text(encoding="utf-8") == render_games_doc(), \ + "docs/GAMES.md is stale - run tools/games_doc.py" diff --git a/tests/test_features.py b/tests/test_features.py index 9668e22..1d60672 100644 --- a/tests/test_features.py +++ b/tests/test_features.py @@ -139,7 +139,7 @@ def test_preflight_all_ok(tmp_path, monkeypatch): world = {"world_name": WORLD, "sync_dir": str(shared)} checks = preflight.run(cfg, world) labels = {c.label: c for c in checks} - assert labels["Game save folder"].status == preflight.OK + assert labels["RuneScape: Dragonwilds save folder"].status == preflight.OK assert labels["Shared folder"].status == preflight.OK assert labels["Cloud drive"].status == preflight.OK assert preflight.worst(checks) in (preflight.OK, preflight.WARN) diff --git a/tests/test_games.py b/tests/test_games.py new file mode 100644 index 0000000..9fd9580 --- /dev/null +++ b/tests/test_games.py @@ -0,0 +1,423 @@ +"""WorldSync multi-game engine: profiles, discovery, folder worlds, safety.""" + +import json +import os +import time +from pathlib import Path + +import pytest + +from app.core import backups, config, games, health, invite, steam, worldhistory +from app.core.sync import (SyncResult, do_pull, do_push, world_files, + world_fingerprint) + + +def touch(path: Path, data: bytes = b"x" * 2048, mtime: float | None = None): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + if mtime: + os.utime(path, (mtime, mtime)) + return path + + +def logs(): + out = [] + return out, out.append + + +def yes(title, body): + return True + + +def no(title, body): + return False + + +# --------------------------------------------------------------------------- +# profiles +# --------------------------------------------------------------------------- + +def test_every_profile_is_complete(): + ids = set() + for g in games.ALL: + assert g.id not in ids + ids.add(g.id) + assert g.name and g.steam_app_id.isdigit() + assert g.process_names and all(n.lower().endswith(".exe") for n in g.process_names) + assert g.save_roots and g.discover + assert g.tagline + for t in g.save_roots: + assert t.startswith("{"), "save roots must be anchored to a known folder" + assert len(games.ALL) == 10 + + +def test_only_dragonwilds_uses_the_legacy_rule(): + legacy = [g.id for g in games.ALL if g.patterns is None] + assert legacy == ["dragonwilds"] + + +def test_unknown_game_falls_back_to_dragonwilds(): + assert games.get("nope") is games.DRAGONWILDS + assert games.get(None) is games.DRAGONWILDS + + +def test_expand_picks_newest_wildcard_folder(tmp_path): + old = tmp_path / "Pal" / "Saved" / "SaveGames" / "111" + new = tmp_path / "Pal" / "Saved" / "SaveGames" / "222" + old.mkdir(parents=True) + new.mkdir(parents=True) + os.utime(old, (time.time() - 1000, time.time() - 1000)) + tokens = {"LOCALAPPDATA": str(tmp_path)} + assert games.expand("{LOCALAPPDATA}/Pal/Saved/SaveGames/*", tokens) == new + + +def test_expand_missing_returns_none(tmp_path): + assert games.expand("{LOCALLOW}/Nope/*/x", {"LOCALLOW": str(tmp_path)}) is None + + +def test_world_id_validation(): + assert games.is_valid_world_id("Navezgane/My Save") + assert games.is_valid_world_id("3ad85aea") + for bad in ("", " x", "../evil", "a/../b", "C:/x", "a//b"): + assert not games.is_valid_world_id(bad) + + +# --------------------------------------------------------------------------- +# discovery +# --------------------------------------------------------------------------- + +def test_discover_valheim_both_layouts(tmp_path): + now = time.time() + touch(tmp_path / "Old.fwl", mtime=now - 500) + touch(tmp_path / "Old.db", mtime=now - 500) + touch(tmp_path / "Midgard" / "Midgard.db", mtime=now) + found = games.discover_worlds(games.VALHEIM, tmp_path) + assert [w.id for w in found] == ["Midgard", "Old"] + + +def test_discover_seven_days_map_and_save(tmp_path): + touch(tmp_path / "Saves" / "Navezgane" / "Alpha" / "main.ttw") + touch(tmp_path / "Saves" / "Pregen06k1" / "Beta" / "main.ttw") + found = {w.id: w for w in games.discover_worlds(games.SEVEN_DAYS, tmp_path)} + assert set(found) == {"Navezgane/Alpha", "Pregen06k1/Beta"} + assert found["Navezgane/Alpha"].label == "Alpha" + + +def test_discover_core_keeper_slots(tmp_path): + touch(tmp_path / "worlds" / "0.world.gzip") + touch(tmp_path / "worlds" / "2.world.gzip") + labels = {w.id: w.label for w in games.discover_worlds(games.CORE_KEEPER, tmp_path)} + assert labels == {"0": "Slot 1", "2": "Slot 3"} + + +def test_discover_v_rising_reads_world_name(tmp_path): + guid = "4b5e8f9c-aaaa" + touch(tmp_path / guid / "AutoSave_12.save.gz") + (tmp_path / guid / "ServerHostSettings.json").write_text( + json.dumps({"Name": "Castle Night"}), encoding="utf-8") + [w] = games.discover_worlds(games.V_RISING, tmp_path) + assert (w.id, w.label) == (guid, "Castle Night") + + +def test_discover_missing_folder_is_empty(tmp_path): + assert games.discover_worlds(games.RAFT, tmp_path / "nope") == [] + + +# --------------------------------------------------------------------------- +# folder worlds through the sync core +# --------------------------------------------------------------------------- + +def flat_for(profile, save_dir, sync_dir, world, player="Andor"): + return { + "player_name": player, "local_save_dir": str(save_dir), + "world_name": world, "sync_dir": str(sync_dir), "exe_path": None, + "game": profile.id, "mirror": profile.mirror, + "patterns": list(profile.patterns) if profile.patterns is not None else None, + } + + +@pytest.fixture +def vr(tmp_path): + a, b, shared = tmp_path / "a", tmp_path / "b", tmp_path / "shared" + for p in (a, b, shared): + p.mkdir() + world = "guid-1" + return a, b, shared, world + + +def test_folder_world_roundtrip_with_nested_files(vr, tmp_path): + a, b, shared, world = vr + touch(a / world / "AutoSave_1.save.gz", b"one" * 500) + touch(a / world / "ServerGameSettings.json", b"{}" * 600) + touch(a / "other-world" / "AutoSave_9.save.gz") # must not travel + sa, sb = {"last_applied_version": 0, "last_hash": None}, \ + {"last_applied_version": 0, "last_hash": None} + _, log = logs() + res, _ = do_push(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + assert res == SyncResult.PUSHED + assert (shared / world / "AutoSave_1.save.gz").exists() + assert not (shared / "other-world").exists() + assert json.loads((shared / "version.json").read_text())["game"] == "v_rising" + + res, _ = do_pull(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, yes, tmp_path / "bk") + assert res == SyncResult.PULLED + assert (b / world / "AutoSave_1.save.gz").read_bytes() == b"one" * 500 + + +def test_mirror_removes_rotated_autosaves(vr, tmp_path): + a, b, shared, world = vr + touch(a / world / "AutoSave_1.save.gz") + sa = {"last_applied_version": 0, "last_hash": None} + sb = {"last_applied_version": 0, "last_hash": None} + _, log = logs() + do_push(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + do_pull(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, yes, tmp_path / "bk") + + # Kim plays: the game rotates autosave 1 out and writes autosave 2 + (b / world / "AutoSave_1.save.gz").unlink() + touch(b / world / "AutoSave_2.save.gz") + do_push(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, yes, tmp_path / "bk") + assert not (shared / world / "AutoSave_1.save.gz").exists() + + do_pull(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + assert sorted(p.name for p in (a / world).iterdir()) == ["AutoSave_2.save.gz"] + + +def test_new_autosave_counts_as_local_change(vr, tmp_path): + """A folder world's fingerprint covers every file, not just the first.""" + a, b, shared, world = vr + touch(a / world / "AutoSave_1.save.gz") + sa = {"last_applied_version": 0, "last_hash": None} + sb = {"last_applied_version": 0, "last_hash": None} + _, log = logs() + do_push(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + do_pull(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, yes, tmp_path / "bk") + + touch(b / world / "AutoSave_2.save.gz") # Kim played offline + touch(a / world / "AutoSave_3.save.gz") # Andor shared meanwhile + do_push(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + + res, _ = do_pull(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, no, tmp_path / "bk") + assert res == SyncResult.CONFLICT_CANCELLED + + +def test_conflict_backup_keeps_folder_structure(vr, tmp_path): + a, b, shared, world = vr + touch(a / world / "AutoSave_1.save.gz", b"A" * 3000) + sa = {"last_applied_version": 0, "last_hash": None} + sb = {"last_applied_version": 0, "last_hash": None} + _, log = logs() + touch(b / world / "AutoSave_7.save.gz", b"B" * 3000) # Kim's own copy + do_push(flat_for(games.V_RISING, a, shared, world), sa, log, yes, tmp_path / "bk") + do_pull(flat_for(games.V_RISING, b, shared, world, "Kim"), sb, log, yes, tmp_path / "bk") + backed = list((tmp_path / "bk").rglob("AutoSave_7.save.gz")) + assert backed and backed[0].parent.name == world + + +def test_seven_days_carries_map_and_save(tmp_path): + a, shared = tmp_path / "a", tmp_path / "shared" + touch(a / "Saves" / "Pregen06k1" / "Alpha" / "main.ttw") + touch(a / "Saves" / "Pregen06k1" / "Alpha" / "Player" / "76561.ttp") + touch(a / "GeneratedWorlds" / "Pregen06k1" / "dtm.raw") + touch(a / "GeneratedWorlds" / "OtherMap" / "dtm.raw") + files = world_files(a, "Pregen06k1/Alpha", list(games.SEVEN_DAYS.patterns)) + rels = sorted(f.relative_to(a).as_posix() for f in files) + assert rels == ["GeneratedWorlds/Pregen06k1/dtm.raw", + "Saves/Pregen06k1/Alpha/Player/76561.ttp", + "Saves/Pregen06k1/Alpha/main.ttw"] + state = {"last_applied_version": 0, "last_hash": None} + _, log = logs() + res, _ = do_push(flat_for(games.SEVEN_DAYS, a, shared, "Pregen06k1/Alpha"), + state, log, yes, tmp_path / "bk") + assert res == SyncResult.PUSHED + assert (shared / "GeneratedWorlds" / "Pregen06k1" / "dtm.raw").exists() + + +def test_prefix_patterns_dont_catch_similar_names(tmp_path): + touch(tmp_path / "Test.fwl") + touch(tmp_path / "Test.db") + touch(tmp_path / "Test2.fwl") + touch(tmp_path / "Test2.db") + names = [f.name for f in world_files(tmp_path, "Test", list(games.VALHEIM.patterns))] + assert names == ["Test.db", "Test.fwl"] + + +def test_world_names_with_glob_characters_are_literal(tmp_path): + touch(tmp_path / "[A]" / "x.sav") + touch(tmp_path / "A" / "y.sav") + files = world_files(tmp_path, "[A]", ["{world}/**/*"]) + assert [f.name for f in files] == ["x.sav"] + + +def test_legacy_fingerprint_is_first_file_hash(tmp_path): + from app.core.sync import sha256_file + f1 = touch(tmp_path / "W.sav", b"abc") + touch(tmp_path / "W.sav.backup", b"def") + files = world_files(tmp_path, "W") + assert world_fingerprint(files, tmp_path, None) == sha256_file(f1) + + +# --------------------------------------------------------------------------- +# the wrong-game guard +# --------------------------------------------------------------------------- + +def test_pull_refuses_other_games_world(tmp_path): + a, shared = tmp_path / "a", tmp_path / "shared" + touch(a / "Midgard.fwl") + touch(a / "Midgard.db") + _, log = logs() + s1 = {"last_applied_version": 0, "last_hash": None} + do_push(flat_for(games.VALHEIM, a, shared, "Midgard"), s1, log, yes, tmp_path / "bk") + b = tmp_path / "b" + b.mkdir() + s2 = {"last_applied_version": 0, "last_hash": None} + res, _ = do_pull(flat_for(games.RAFT, b, shared, "Midgard"), s2, log, yes, tmp_path / "bk") + assert res == SyncResult.WRONG_GAME + assert not any(b.iterdir()) + + +def test_old_manifest_counts_as_dragonwilds(tmp_path): + shared = tmp_path / "shared" + shared.mkdir() + (shared / "version.json").write_text(json.dumps({"version": 3, "world_name": "W"})) + a = tmp_path / "a" + touch(a / "W" / "x.dat") + _, log = logs() + state = {"last_applied_version": 0, "last_hash": None} + res, _ = do_push(flat_for(games.RAFT, a, shared, "W"), state, log, yes, tmp_path / "bk") + assert res == SyncResult.WRONG_GAME + dw = flat_for(games.DRAGONWILDS, tmp_path / "dw", shared, "W") + res, _ = do_pull(dw, {"last_applied_version": 0, "last_hash": None}, log, yes, tmp_path / "bk") + assert res != SyncResult.WRONG_GAME + + +def test_dragonwilds_push_still_stamps_game(tmp_path): + a, shared = tmp_path / "a", tmp_path / "shared" + touch(a / "W.sav") + _, log = logs() + do_push(flat_for(games.DRAGONWILDS, a, shared, "W"), + {"last_applied_version": 0, "last_hash": None}, log, yes, tmp_path / "bk") + assert json.loads((shared / "version.json").read_text())["game"] == "dragonwilds" + + +# --------------------------------------------------------------------------- +# health, backups, group history for folder worlds +# --------------------------------------------------------------------------- + +def test_health_uses_biggest_file_for_folder_worlds(tmp_path): + pats = list(games.VALHEIM.patterns) + touch(tmp_path / "M.fwl", b"x" * 80) # tiny metadata file + touch(tmp_path / "M.db", b"x" * 50_000) + assert health.check_local_save(tmp_path, "M", pats).ok + (tmp_path / "M.db").write_bytes(b"") + assert not health.check_local_save(tmp_path, "M", pats).ok + + +def test_still_syncing_sees_nested_partial_files(tmp_path): + pats = ["{world}/**/*"] + touch(tmp_path / "W" / "AutoSave_1.save.gz") + assert not health.shared_still_syncing(tmp_path, "W", pats) + touch(tmp_path / "W" / "AutoSave_2.save.gz.tmp") + assert health.shared_still_syncing(tmp_path, "W", pats) + + +def test_checkpoint_and_mirror_restore_folder_world(tmp_path): + pats = ["{world}/**/*"] + save, root = tmp_path / "save", tmp_path / "bk" + touch(save / "W" / "AutoSave_1.save.gz", b"before" * 400) + cp = backups.create_checkpoint(save, "W", "Before boss", root, patterns=pats) + assert cp.file_count == 1 + assert (cp.path / "W" / "AutoSave_1.save.gz").exists() + + touch(save / "W" / "AutoSave_2.save.gz", b"after" * 400) + (save / "W" / "AutoSave_1.save.gz").write_bytes(b"changed" * 400) + n = backups.restore_backup(cp.path, save, "W", root, patterns=pats, mirror=True) + assert n == 1 + assert sorted(p.name for p in (save / "W").iterdir()) == ["AutoSave_1.save.gz"] + assert (save / "W" / "AutoSave_1.save.gz").read_bytes() == b"before" * 400 + pre = [b for b in backups.list_backups(root) if b.label == "pre_restore"] + assert pre and pre[0].file_count == 2 + + +def test_group_history_archives_nested_world(tmp_path): + pats = ["{world}/**/*"] + touch(tmp_path / "W" / "a" / "b.dat") + assert worldhistory.archive_version(tmp_path, "W", 4, patterns=pats) + [v] = worldhistory.list_versions(tmp_path) + assert v.file_count == 1 and (v.path / "W" / "a" / "b.dat").exists() + + +# --------------------------------------------------------------------------- +# config v3 +# --------------------------------------------------------------------------- + +def test_v2_config_migrates_to_library(): + v2 = {"schema": 2, "player_name": "Andor", "local_save_dir": "C:/dw", + "worlds": [{"id": "w_1", "world_name": "Ash", "sync_dir": "S"}], + "active_world": "w_1"} + v3, _ = config.migrate_config(v2) + assert v3["schema"] == 3 + assert v3["library"] == ["dragonwilds"] + assert v3["worlds"][0]["game"] == "dragonwilds" + assert v3["last_view"] == "dragonwilds" + assert config.game_save_dir(v3, "dragonwilds") == "C:/dw" + + +def test_effective_cfg_for_folder_game(): + cfg, _ = config.migrate_config({"player_name": "Andor", "worlds": []}) + config.set_game_save_dir(cfg, "valheim", "D:/vh") + world = config.make_world("Midgard", "S", game="valheim") + flat = config.effective_cfg(cfg, world) + assert flat["local_save_dir"] == "D:/vh" + assert flat["patterns"] == list(games.VALHEIM.patterns) + assert flat["mirror"] is True + assert flat["steam_app_id"] == "892970" + assert flat["process_names"] == ["valheim.exe"] + # Dragonwilds' save folder is untouched by other games' settings + assert config.game_save_dir(cfg, "dragonwilds") != "D:/vh" + + +def test_remove_game_only_when_empty(): + cfg, _ = config.migrate_config({"player_name": "A", "worlds": []}) + config.add_to_library(cfg, "raft") + cfg["worlds"].append(config.make_world("Sea", "S", game="raft")) + with pytest.raises(ValueError): + config.remove_from_library(cfg, "raft") + cfg["worlds"] = [] + config.remove_from_library(cfg, "raft") + assert "raft" not in cfg["library"] + + +# --------------------------------------------------------------------------- +# invites and Steam detection +# --------------------------------------------------------------------------- + +def test_invite_carries_game(): + code = invite.encode("Midgard", "Valheim crew", None, game="valheim") + assert code.startswith("WS1.") + assert invite.decode(code)["game"] == "valheim" + + +def test_dragonwilds_invites_stay_readable_by_1x(): + code = invite.encode("Ash", "DW crew", None) + assert code.startswith("DWS1.") + assert invite.decode(code)["game"] == "dragonwilds" + + +def test_steam_install_detection(tmp_path): + lib = tmp_path / "SteamLibrary" + apps = lib / "steamapps" + apps.mkdir(parents=True) + (apps / "appmanifest_892970.acf").write_text( + '"AppState"\n{\n\t"appid"\t"892970"\n\t"installdir"\t"Valheim"\n}\n') + touch(apps / "common" / "Valheim" / "valheim.exe") + touch(apps / "common" / "Valheim" / "tools" / "valheim.exe") + assert steam.installed_app_ids([lib]) == {"892970"} + exe = steam.find_game_exe(games.VALHEIM, libraries=[lib]) + assert exe == apps / "common" / "Valheim" / "valheim.exe" + assert steam.find_game_exe(games.RAFT, libraries=[lib]) is None + + +def test_empty_world_name_matches_nothing(tmp_path): + touch(tmp_path / "W" / "x.dat") + assert world_files(tmp_path, "", ["{world}/**/*"]) == [] diff --git a/tests/test_ui_smoke.py b/tests/test_ui_smoke.py new file mode 100644 index 0000000..5cae476 --- /dev/null +++ b/tests/test_ui_smoke.py @@ -0,0 +1,139 @@ +"""Smoke tests for the real window: first run, the upgrade from 1.x, themes. + +They build the actual MainWindow offscreen against a throwaway data folder +and walk the navigation, so a broken signal or a missing attribute fails CI +instead of the first person who clicks it. +""" + +import json +import os + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtGui import QIcon # noqa: E402 +from PySide6.QtWidgets import QApplication # noqa: E402 + +from app.core import paths # noqa: E402 + + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() or QApplication([]) + from app.ui import theme + theme.apply(app) + return app + + +@pytest.fixture +def sandbox(tmp_path, monkeypatch): + home = tmp_path / "home" + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.setenv("LOCALAPPDATA", str(home / "AppData" / "Local")) + monkeypatch.setenv("APPDATA", str(home / "AppData" / "Roaming")) + data = tmp_path / "appdata" + monkeypatch.setattr(paths, "APP_DIR", data) + monkeypatch.setattr(paths, "CONFIG_PATH", data / "config.json") + monkeypatch.setattr(paths, "STATE_PATH", data / "state.json") + monkeypatch.setattr(paths, "LOG_DIR", data / "logs") + monkeypatch.setattr(paths, "BACKUP_DIR", data / "backups") + monkeypatch.setattr(paths, "LEGACY_CONFIG_PATH", tmp_path / "none" / "config.json") + monkeypatch.setattr(paths, "LEGACY_STATE_PATH", tmp_path / "none" / "state.json") + monkeypatch.setattr(paths, "LEGACY_APP_DIR", tmp_path / "DragonwildsSync") + from app.ui import theme + monkeypatch.setattr(theme, "UI_CACHE", data / "ui") + return home, data + + +def make_window(): + from app.controller import Controller + from app.ui.window import MainWindow + controller = Controller() + win = MainWindow(controller, QIcon()) + controller._poll.stop() + return controller, win + + +def test_first_run_through_picker_to_a_game(qapp, sandbox): + home, _ = sandbox + vh = home / "AppData" / "LocalLow" / "IronGate" / "Valheim" / "worlds_local" + vh.mkdir(parents=True) + (vh / "Midgard.fwl").write_bytes(b"x" * 100) + (vh / "Midgard.db").write_bytes(b"x" * 5000) + + c, win = make_window() + from app.ui import theme + assert win.pages.currentWidget() is win.onboarding_page + assert theme.THEME_ID == "library" + + win.onboarding_page.name_field.edit.setText("Andor") + win.onboarding_page._submit_name() + assert win.pages.currentWidget() is win.addgame_page + + win.addgame_page.game_chosen.emit("valheim") + assert theme.THEME_ID == "valheim" + ob = win.onboarding_page + assert ob.save_dir_field.value() == str(vh) + assert ob.world_field.value() == "Midgard" + + shared = home / "Drive" / "Valheim - Midgard" + ob._submit_world() + ob.shared_field.edit.setText(str(shared)) + ob._submit_create() + + assert win.pages.currentWidget() is win.main_page + assert c.cfg["library"] == ["valheim"] + assert c.active_world()["game"] == "valheim" + assert c.cfg["player_name"] == "Andor" + + win._go_library() + assert win.pages.currentWidget() is win.library_page + assert theme.THEME_ID == "library" + assert list(win.library_page._cards) == ["valheim"] + win.close() + + +def test_upgrade_from_dragonwilds_sync_opens_straight_into_dragonwilds(qapp, sandbox): + _, data = sandbox + data.mkdir(parents=True) + (data / "config.json").write_text(json.dumps({ + "schema": 2, "player_name": "Andor", "local_save_dir": "C:/dw", + "worlds": [{"id": "w_1", "world_name": "Ashenreach", "sync_dir": "C:/none"}], + "active_world": "w_1", + })) + c, win = make_window() + from app.ui import theme + assert win.pages.currentWidget() is win.main_page + assert theme.THEME_ID == "dragonwilds" + assert c.cfg["schema"] == 3 and c.cfg["library"] == ["dragonwilds"] + assert (data / "config.v2.bak").exists() + # the Dragonwilds-only extras are offered here... + assert win.main_page._has_characters + win.close() + + +def test_secret_stays_shut_outside_dragonwilds(qapp, sandbox): + _, data = sandbox + data.mkdir(parents=True) + (data / "config.json").write_text(json.dumps({ + "schema": 3, "player_name": "Andor", "library": ["raft"], "last_view": "raft", + "worlds": [{"id": "w_1", "game": "raft", "world_name": "Sea", "sync_dir": "C:/none"}], + "active_world": "w_1", + })) + c, win = make_window() + assert win.pages.currentWidget() is win.main_page + assert not win.main_page._has_characters + win._awaken_secret() + assert win.pages.currentWidget() is win.main_page + win.close() + + +def test_every_theme_applies_and_every_scene_paints(qapp): + from app.ui import gamethemes, scenes, theme + for tid in gamethemes.THEMES: + theme.apply_game(tid) + assert theme.THEME_ID == tid + pm = scenes.render(gamethemes.get(tid).scene, 160, 60, theme.ACCENT, theme.EMBER) + assert not pm.isNull() + theme.apply_game("dragonwilds") diff --git a/tools/games_doc.py b/tools/games_doc.py new file mode 100644 index 0000000..09594c6 --- /dev/null +++ b/tools/games_doc.py @@ -0,0 +1,60 @@ +"""Write docs/GAMES.md from the game profiles, so the docs never drift. + +Run: .venv\\Scripts\\python.exe tools\\games_doc.py +A test fails if docs/GAMES.md is out of date with app/core/games.py. +""" + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +from app.core import games # noqa: E402 + +OUT = ROOT / "docs" / "GAMES.md" + + +def render() -> str: + lines = [ + "# Setting up each game", + "", + "", + "", + "The same guide is in the app: open a game's world menu and choose", + "*How to set up*, or use the link during setup.", + "", + "## Every game", + "", + ] + lines += [f"- {line}" for line in games.COMMON_STEPS] + lines.append("") + lines.append("| Game | Status |") + lines.append("|---|---|") + for g in games.ALL: + anchor = g.name.lower().replace(":", "").replace(" ", "-") + lines.append(f"| [{g.name}](#{anchor}) | {'Tested' if g.verified else 'Beta'} |") + for g in games.ALL: + lines += ["", f"## {g.name}", ""] + if not g.verified: + lines += ["*Beta: the save layout follows community guides and WorldSync's own " + "tests. Every overwrite is backed up first; reports on GitHub move it " + "to tested.*", ""] + for i, step in enumerate(games.setup_steps(g), 1): + lines.append(f"{i}. {step}") + lines += ["", "**Where the saves live**", ""] + for template in g.save_roots: + lines.append(f"- `{games.human_save_path(template)}`") + lines += ["", f"WorldSync calls one of these a *{g.world_word}*. {g.world_hint}"] + lines.append("") + return "\n".join(lines) + + +def main(): + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(render(), encoding="utf-8", newline="\n") + print("wrote", OUT) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_icon.py b/tools/generate_icon.py index d5a498a..58145ea 100644 --- a/tools/generate_icon.py +++ b/tools/generate_icon.py @@ -1,4 +1,4 @@ -"""Render the app icon (dragon-eye badge) to app/assets/icon.ico + icon.png. +"""Render the app icon (WorldSync orbit badge) to app/assets/icon.ico + icon.png. Run once: .venv\\Scripts\\python.exe tools\\generate_icon.py """ @@ -21,37 +21,45 @@ ICON_SVG = """ - - - - + + + + - - - + + + - - - + + + + + + - + - - - - - - - - - + stroke="#232B48" stroke-width="3"/> + + + + + + + + + + + + + """ diff --git a/tools/screenshots.py b/tools/screenshots.py index b344b19..5c669a4 100644 --- a/tools/screenshots.py +++ b/tools/screenshots.py @@ -1,11 +1,13 @@ -"""Render every app state to PNG for design review - no window flashing. +"""Render the app's key screens to PNG for the README - no window flashing. Run: .venv\\Scripts\\python.exe tools\\screenshots.py -Writes docs/screenshots/*.png using a throwaway config in a temp folder -(the real per-user config is never touched). +Writes docs/screenshots/*.png from a throwaway home folder and config in a +temp directory (the real per-user data is never touched). Every name and +world here is made up. """ import json +import os import sys import tempfile from datetime import datetime, timedelta, timezone @@ -14,8 +16,13 @@ ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) -# Redirect all app storage into a scratch folder BEFORE anything reads it. -scratch = Path(tempfile.mkdtemp(prefix="dwsync_shots_")) +# Redirect storage and the "home" folder BEFORE anything reads them. +scratch = Path(tempfile.mkdtemp(prefix="worldsync_shots_")) +home = scratch / "home" +os.environ["USERPROFILE"] = str(home) +os.environ["LOCALAPPDATA"] = str(home / "AppData" / "Local") +os.environ["APPDATA"] = str(home / "AppData" / "Roaming") + from app.core import paths # noqa: E402 paths.APP_DIR = scratch / "appdata" @@ -25,13 +32,14 @@ paths.BACKUP_DIR = paths.APP_DIR / "backups" paths.LEGACY_CONFIG_PATH = scratch / "nolegacy" / "config.json" paths.LEGACY_STATE_PATH = scratch / "nolegacy" / "state.json" +paths.LEGACY_APP_DIR = scratch / "nolegacy" from PySide6.QtCore import Qt # noqa: E402 -from PySide6.QtGui import QIcon # noqa: E402 +from PySide6.QtGui import QColor, QIcon, QPainter, QPixmap # noqa: E402 from PySide6.QtTest import QTest # noqa: E402 from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 -from app.core import config, presence, storage, sync # noqa: E402 +from app.core import config, games, presence, steam, storage # noqa: E402 from app.core.logs import setup_logging # noqa: E402 from app.core.sync import _backup_files # noqa: E402 from app.controller import Controller # noqa: E402 @@ -39,61 +47,25 @@ from app.ui.window import MainWindow # noqa: E402 theme.UI_CACHE = paths.APP_DIR / "ui" - OUT = ROOT / "docs" / "screenshots" OUT.mkdir(parents=True, exist_ok=True) - -WORLD = "Minhalla" +SHOTS: dict[str, QPixmap] = {} def ts(hours_ago: float) -> str: return (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat(timespec="seconds") -def seed_world(): - save_dir = scratch / "saves" - shared = scratch / "shared" - save_dir.mkdir(exist_ok=True) - shared.mkdir(exist_ok=True) - (save_dir / f"{WORLD}.sav").write_bytes(b"save-data") - (save_dir / f"{WORLD}.sav.backup").write_bytes(b"save-data-backup") - (shared / f"{WORLD}.sav").write_bytes(b"shared-save") - (shared / f"{WORLD}.sav.backup").write_bytes(b"shared-save-backup") - history = [ - {"version": 11, "editor": "Reinier", "timestamp": ts(76), - "duration_s": 5400, "emoji": "🪓"}, - {"version": 12, "editor": "Bram", "timestamp": ts(29), - "note": "Tamed the salamander. It has opinions.", "duration_s": 8100, - "character": "Grimjaw", - "portrait": "male_A_01|SkinTone3|Preset2|Color2|M_B_Preset2|Color1"}, - {"version": 13, "editor": "Andor", "timestamp": ts(7), - "note": "Built the gatehouse, found the swamp cave", "duration_s": 4520, - "character": "Ashvale", - "portrait": "male_A_01|SkinTone1|Preset7|Color8|M_D_Preset4|Color2"}, - {"version": 14, "editor": "Elise", "timestamp": ts(1.8), "duration_s": 6300, - "character": "Sylwen", "color": "#5EA2EF", - "portrait": "female_A_01|SkinTone6|Preset11|Color5|F_PresetNone|Color3"}, - ] - storage.write_json(shared / paths.MANIFEST_NAME, { - "version": 14, "last_editor": "Elise", "timestamp": ts(1.8), - "world_name": WORLD, "history": history, "app_schema": 1, - }) - world = config.make_world(WORLD, str(shared), - share_link="https://drive.google.com/drive/folders/x") - world2 = config.make_world("Frostspire", str(scratch / "shared2")) - cfg, _ = config.migrate_config({}) - cfg.update({ - "player_name": "Andor", "player_emoji": "🐉", - "local_save_dir": str(save_dir), - "active_world": world["id"], - "worlds": [world, world2], - }) - return cfg, world, shared, save_dir +def write(path: Path, data: bytes = b"x" * 4096): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) def shoot(window, name): - QTest.qWait(300) - window.grab().save(str(OUT / f"{name}.png")) + QTest.qWait(350) + pm = window.grab() + pm.save(str(OUT / f"{name}.png")) + SHOTS[name] = pm print(" wrote", name + ".png") @@ -107,218 +79,214 @@ def clear_toasts(window): QTest.qWait(50) +# -- a believable group across four games ------------------------------------------ + +PEOPLE = [("Reinier", "🪓", None), ("Bram", "🛡️", None), ("Elise", "🏹", "#5EA2EF"), + ("Kim", "🌙", "#B78AF7"), ("Andor", "🐉", None)] + +NOTES = { + "valheim": ["Found a crypt full of surtling cores", "Moved the portal hub to the plains", + "Elder down. Swamp next week?", "Built the longhouse roof, finally"], + "v_rising": ["Castle walls up, servants are hunting", "Took down Grayson the Armourer", + "Night run to the Silverlight hills", "Coffins for everyone"], + "dragonwilds": ["Built the gatehouse, found the swamp cave", "Tamed the salamander. It has opinions.", + "Runecrafting at 30!", "Cleared the old mine"], + "palworld": ["Base moved next to the ore field", "Caught a shiny Lamball", "Automated the berry farm", + "Breeding farm is running"], + "seven_days_to_die": ["Survived horde night 14", "Spike trench around the base", + "Looted the shotgun messiah factory", "Forge and workbench upgraded"], + "core_keeper": ["Opened the Azeos wilderness", "Automated the copper drills", + "Ghorm the Devourer is down", "Fishing pond and a kitchen"], +} + + +def history_for(game_id: str): + out = [] + for i, (name, emoji, color) in enumerate(PEOPLE[1:]): + entry = {"version": 10 + i, "editor": name, "timestamp": ts(70 - i * 22 + 2), + "duration_s": 3600 + i * 1700, "emoji": emoji, + "note": NOTES[game_id][i % len(NOTES[game_id])]} + if color: + entry["color"] = color + out.append(entry) + return out + + +def seed(): + drive = home / "Google Drive" / "WorldSync" + worlds = [] + cfg, _ = config.migrate_config({}) + cfg.update({"player_name": "Andor", "player_emoji": "🐉"}) + + def add(game_id, world_id, label, save_root, files): + profile = games.get(game_id) + for rel in files: + write(save_root / rel) + shared = drive / f"{profile.short} - {label or world_id}" + shared.mkdir(parents=True, exist_ok=True) + for rel in files: + write(shared / rel) + hist = history_for(game_id) + storage.write_json(shared / paths.MANIFEST_NAME, { + "version": hist[-1]["version"], "last_editor": hist[-1]["editor"], + "timestamp": hist[-1]["timestamp"], "world_name": world_id, + "history": hist, "app_schema": 1, "game": game_id}) + world = config.make_world(world_id, str(shared), game=game_id, label=label, + share_link="https://drive.google.com/drive/folders/x") + worlds.append(world) + config.add_to_library(cfg, game_id) + if game_id != "dragonwilds": + config.set_game_save_dir(cfg, game_id, str(save_root)) + return world, shared + + lowlow = home / "AppData" / "LocalLow" + v, v_shared = add("valheim", "Midgard", None, lowlow / "IronGate" / "Valheim" / "worlds_local", + ["Midgard.fwl", "Midgard.db"]) + r, r_shared = add("v_rising", "4b5e8f9c-1d2e", "Dunley Nights", + lowlow / "Stunlock Studios" / "VRising" / "Saves" / "v3", + ["4b5e8f9c-1d2e/AutoSave_31.save.gz"]) + dw_root = home / "AppData" / "Local" / "RSDragonwilds" / "Saved" / "SaveGames" + d, d_shared = add("dragonwilds", "Ashenreach", None, dw_root, + ["Ashenreach.sav", "Ashenreach.sav.backup"]) + cfg["local_save_dir"] = str(dw_root) + p, p_shared = add("palworld", "9F3A6C0D2B7E4A1C8D5F0E6B3A9C7D21", "Palpagos Crew", + home / "AppData" / "Local" / "Pal" / "Saved" / "SaveGames" / "765611", + ["9F3A6C0D2B7E4A1C8D5F0E6B3A9C7D21/Level.sav"]) + s, s_shared = add("seven_days_to_die", "Pregen06k1/Horde Night", "Horde Night", + home / "AppData" / "Roaming" / "7DaysToDie", + ["Saves/Pregen06k1/Horde Night/main.ttw"]) + k, k_shared = add("core_keeper", "1", "Slot 2", + lowlow / "Pugstorm" / "Core Keeper" / "Steam" / "765611", + ["worlds/1.world.gzip"]) + cfg["worlds"] = worlds + cfg["active_world"] = v["id"] + cfg["last_view"] = "library" + state = {"schema": 3, "worlds": {}} + for w in worlds: + manifest = storage.read_json(Path(w["sync_dir"]) / paths.MANIFEST_NAME) + state["worlds"][w["id"]] = {"last_applied_version": manifest["version"], "last_hash": "x"} + storage.save_config(cfg) + storage.save_state(state) + return {"valheim": (v, v_shared), "v_rising": (r, r_shared), "dragonwilds": (d, d_shared), + "palworld": (p, p_shared), "seven_days_to_die": (s, s_shared), + "core_keeper": (k, k_shared)} + + +def collage(names, out_name, cols=3, scale=0.62): + pms = [SHOTS[n] for n in names] + w, h = int(pms[0].width() * scale), int(pms[0].height() * scale) + rows = (len(pms) + cols - 1) // cols + gap = 18 + sheet = QPixmap(cols * w + (cols + 1) * gap, rows * h + (rows + 1) * gap) + sheet.fill(QColor("#07090E")) + p = QPainter(sheet) + p.setRenderHint(QPainter.SmoothPixmapTransform) + for i, pm in enumerate(pms): + x = gap + (i % cols) * (w + gap) + y = gap + (i // cols) * (h + gap) + p.drawPixmap(x, y, pm.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)) + p.end() + sheet.save(str(OUT / f"{out_name}.png")) + print(" wrote", out_name + ".png") + + def main(): setup_logging() app = QApplication(sys.argv) theme.apply(app) - - # ---- onboarding states (no config yet) -------------------------------------- - controller = Controller() - window = MainWindow(controller, QIcon()) - window.setAttribute(Qt.WA_DontShowOnScreen, True) # render fully, never flash - window.show() - shoot(window, "01_onboarding_welcome") - window.onboarding_page._go(1) - shoot(window, "02_onboarding_name") - window.onboarding_page._go(2) - shoot(window, "03_onboarding_choice") - window.onboarding_page._go(4) - shoot(window, "04_onboarding_shared") - window.onboarding_page.code_field.edit.setText("DWS1.demo") - window.onboarding_page._join_info = { - # deliberately non-existent folder so the watcher keeps spinning - "world_name": "Emberfall", "folder_name": "Emberfall Sync", - "share_link": "https://drive.google.com/drive/folders/x"} - window.onboarding_page._start_watching() - window.onboarding_page._go(6) - shoot(window, "05_onboarding_join_watch") - window.onboarding_page._watch_timer.stop() - window.close() - - # ---- configured states ----------------------------------------------------------- - cfg, world, shared, save_dir = seed_world() - storage.save_config(cfg) - storage.save_state({"schema": 2, "worlds": { - world["id"]: {"last_applied_version": 14, "last_hash": "x"}}}) - - controller2 = Controller() - window2 = MainWindow(controller2, QIcon()) - window2.setAttribute(Qt.WA_DontShowOnScreen, True) - window2.show() - - window2.main_page.set_status(controller2._world_status(world)) - shoot(window2, "06_main_up_to_date") - - config.world_state(controller2.state, world["id"])["last_applied_version"] = 13 - window2.main_page.set_status(controller2._world_status(world)) - shoot(window2, "07_main_new_save") - - presence.start_playing(shared, "Bram", "🪓") - window2.main_page.set_status(controller2._world_status(world)) - shoot(window2, "08_main_friend_playing") - presence.stop_playing(shared, "Bram") - - presence.claim_next(shared, "Elise", "🏹") - config.world_state(controller2.state, world["id"])["last_applied_version"] = 14 - window2.main_page.set_status(controller2._world_status(world)) - shoot(window2, "09_main_turn_claimed") - presence.clear_next(shared) - - window2.main_page.set_status(controller2._world_status(world)) - window2.main_page.set_phase("ingame") - shoot(window2, "10_main_in_game") - window2.main_page.set_phase("idle") - - window2.toasts.show_toast("success", - "Shared your progress as v15 - your friends are up to date.") + steam.installed_app_ids = lambda libraries=None: {"892970", "1604030", "1623730", "1374490"} + + # ---- first run ------------------------------------------------------------------- + write(home / "AppData" / "LocalLow" / "IronGate" / "Valheim" / "worlds_local" / "Midgard.fwl") + write(home / "AppData" / "LocalLow" / "IronGate" / "Valheim" / "worlds_local" / "Midgard.db", + b"x" * 60000) + c0 = Controller() + w0 = MainWindow(c0, QIcon()) + w0.setAttribute(Qt.WA_DontShowOnScreen, True) + w0.show() + shoot(w0, "01_welcome") + w0.onboarding_page.name_field.edit.setText("Andor") + w0.onboarding_page._submit_name() QTest.qWait(400) - shoot(window2, "11_main_toast") - clear_toasts(window2) - - # invite page - window2.invite_page.load(world) - window2._show_page(window2.invite_page) - window2.invite_page._generate() - shoot(window2, "12_invite") - - # backups page - files = sorted(save_dir.glob(f"{WORLD}*")) - root = config.backup_root_for(world["id"]) - _backup_files(files, "local_v13", root) - _backup_files(files, "shared_v14", root) - window2._open_backups() - shoot(window2, "13_backups") - - # settings + about - window2.settings_page.load(cfg, world) - window2._show_page(window2.settings_page) - shoot(window2, "14_settings") - window2._show_page(window2.about_page) - shoot(window2, "15_about") - window2._show_page(window2.main_page) - - # note overlay - window2.note_overlay.open(world["id"], 15) - shoot(window2, "16_note_prompt") - window2.note_overlay._skip() - - # preflight page - from app.core import preflight - window2._show_page(window2.preflight_page) - window2.preflight_page.show_results(preflight.run(cfg, world)) - shoot(window2, "18_preflight") - - # backups with a checkpoint - from app.core.sync import _backup_files as _bk - root = config.backup_root_for(world["id"]) - from app.core import backups as bkmod - bkmod.create_checkpoint(save_dir, WORLD, "Before the dragon", root) - window2._reload_backups() - window2._show_page(window2.backups_page) - shoot(window2, "19_backups_checkpoints") - - # update bar on the main screen - window2._show_page(window2.main_page) - window2.main_page.set_status(controller2._world_status(world)) - window2.main_page.show_update_bar("1.3.0", "Bram") - QTest.qWait(150) - shoot(window2, "20_update_bar") - window2.main_page.hide_update_bar() - - # characters page (synthetic characters in the scratch dir) - import sys as _sys - _sys.path.insert(0, str(ROOT / "tests")) - from test_characters import make_character - chars_dir = scratch / "SaveCharacters" - make_character(chars_dir, "Ashvale") - make_character(chars_dir, "Wrenholt") - controller2.cfg["characters_dir"] = str(chars_dir) - - # give Ashvale a believable real-item bag so the demo reads naturally - from app.core import items as _items - _sample = _items.search(min_rank=0) - _picks = {} - for _r in _sample: # a spread across rarities - _picks.setdefault(_r["rank"], _r) - _ash = chars_dir / "Ashvale.json" - _data = json.loads(_ash.read_text(encoding="utf-8")) - _inv = {"MaxSlotIndex": 30} - for _i, _row in enumerate(list(_picks.values()) * 3): - _slot = {"GUID": f"g{_i}", "ItemData": _row["id"]} - if _row["max"] > 1: - _slot["Count"] = min(_row["max"], (_i + 1) * 7) - else: - _slot["Durability"] = 300 + _i * 90 - _inv[str(_i)] = _slot - _data["GameProgress"]["Inventory"] = _inv - _ash.write_text(json.dumps(_data, indent="\t"), encoding="utf-8") - window2._open_characters() - shoot(window2, "21_characters") - - # the grimoire (opened the way anyone opens it: through the eye) - window2._open_grimoire() - shoot(window2, "22_grimoire") - window2.grimoire_page.char_combo.setCurrentText("Ashvale") - QTest.qWait(60) - window2.grimoire_page._switch_tab(1) - shoot(window2, "22b_grimoire_bag") - window2.grimoire_page._switch_tab(2) # mirror - shoot(window2, "22e_grimoire_mirror") - window2.grimoire_page._switch_tab(3) # scrolls - shoot(window2, "22c_grimoire_scrolls") - window2.grimoire_page._switch_tab(0) - - # the conjuring catalogue - from app.ui.item_picker import ItemPicker - picker = ItemPicker(window2) - picker.setAttribute(Qt.WA_DontShowOnScreen, True) - picker.show() - picker.search.setText("dragon") - QTest.qWait(120) - if picker.list.count(): - picker.list.setCurrentRow(0) - QTest.qWait(120) - picker.grab().save(str(OUT / "22d_conjure.png")) - print(" wrote 22d_conjure.png") - picker.close() - - # the Learn picker (recipes, with output-item icons) - from app.ui.learn_picker import LearnPicker - lp = LearnPicker({"recipes": set(), "spells": set(), "buildings": set()}, window2) - lp.setAttribute(Qt.WA_DontShowOnScreen, True) - lp.show() - lp.search.setText("bronze") - QTest.qWait(120) - lp.grab().save(str(OUT / "22f_learn.png")) - print(" wrote 22f_learn.png") - lp.close() - - # the saga - from app.core import saga as saga_mod - saga_mod.bump_stats(shared, "Andor", 4520) - saga_mod.bump_stats(shared, "Elise", 6300) - saga_mod.bump_stats(shared, "Bram", 8100) - saga_mod.bump_stats(shared, "Bram", 5400) - window2._open_saga() - shoot(window2, "23_saga") - - # conflict overlay - ov = window2.confirm + shoot(w0, "02_pick_a_game") + w0.addgame_page.game_chosen.emit("valheim") + w0.onboarding_page._go(3) + shoot(w0, "03_find_the_world") + w0._really_quit = True + w0.close() + + # ---- a full library ------------------------------------------------------------------- + seeded = seed() + presence.start_playing(seeded["v_rising"][1], "Kim", "🌙") + c = Controller() + c._poll.stop() + win = MainWindow(c, QIcon()) + win.setAttribute(Qt.WA_DontShowOnScreen, True) + win.show() + QTest.qWait(900) # library summary thread + shoot(win, "04_library") + + order = ["valheim", "v_rising", "dragonwilds", "palworld", "seven_days_to_die", "core_keeper"] + for gid in order: + world, shared = seeded[gid] + win._open_game(gid) + QTest.qWait(200) + win.main_page.set_status(c._world_status(world)) + clear_toasts(win) + shoot(win, f"game_{gid}") + collage([f"game_{g}" for g in order], "05_every_game_its_own_look") + + # live states + win._open_game("v_rising") + win.main_page.set_status(c._world_status(seeded["v_rising"][0])) + shoot(win, "06_friend_playing") + presence.stop_playing(seeded["v_rising"][1], "Kim") + + win._open_game("valheim") + world, shared = seeded["valheim"] + win.main_page.set_status(c._world_status(world)) + win.main_page.set_phase("ingame") + shoot(win, "07_in_game") + win.main_page.set_phase("idle") + + win._open_invite() + win.invite_page._generate() + shoot(win, "08_invite") + win._show_page(win.main_page) + + ov = win.confirm ov.title_label.setText("Overwrite your local progress?") ov.body_label.setText( "Your local save has changed since your last sync, but a newer save " - "(v14, from Elise) is waiting in the shared folder.\n\n" + "(v13, from Kim) is waiting in the shared folder.\n\n" "Continuing will replace your local, un-shared progress.") ov.danger_btn.setText("Overwrite") ov.safe_btn.setText("Keep my progress") - ov.setGeometry(window2.chrome.rect()) + ov.setGeometry(win.chrome.rect()) ov.show() ov.raise_() - shoot(window2, "17_conflict") + shoot(win, "09_conflict") ov.hide() - window2._really_quit = True - window2.close() + flat = config.effective_cfg(c.cfg, world) + root = config.backup_root_for(world["id"]) + files = sorted(Path(flat["local_save_dir"]).glob("Midgard*")) + _backup_files(files, "local_v12", root) + _backup_files(files, "shared_v13", root) + from app.core import backups as bk + bk.create_checkpoint(flat["local_save_dir"], "Midgard", "Before Moder", root, + patterns=flat["patterns"]) + win._open_backups() + shoot(win, "10_backups") + + win._show_page(win.about_page) + shoot(win, "11_about") + + # drop the per-game singles; the collage carries them + for gid in order: + (OUT / f"game_{gid}.png").unlink(missing_ok=True) + win._really_quit = True + win.close() print("done ->", OUT)