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
-[](https://github.com/AndorManu/dragonwilds-sync/actions/workflows/tests.yml)
-[](https://github.com/AndorManu/dragonwilds-sync/releases/latest)
-[](LICENSE)
+[](https://github.com/AndorManu/worldsync/actions/workflows/tests.yml)
+[](https://github.com/AndorManu/worldsync/releases/latest)
+[](LICENSE)


-**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.
+
+
+
+
+
+
+## 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 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.
-
-
-
-
-
+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.
+
+
+
+
+
**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 @@
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 ``