diff --git a/README.md b/README.md index 21084ec..9f4401f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # PLWL — Portable Linux Wine Launcher -A portable launcher for Windows games and applications on Linux — and for native Linux apps, run with their own isolated home (bubblewrap when available). +A portable launcher for Windows games and applications on Linux — and for native Linux apps, run with their own home and a chosen isolation level (bubblewrap when available). ## Portable layout @@ -42,23 +42,34 @@ The import dialog starts with a choice: **Windows app (Wine / Proton)** or **Lin The entry point is found automatically in the picked folder: an ELF binary or `.AppImage` (with the executable bit), or a `.desktop` entry whose `Exec=` points at one. Libraries (`lib/`, `share/`, …) are skipped, and the icon comes from the `.desktop` `Icon=`, an image next to the program, or the system theme. -A native app runs with its **own home folder**: `HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME` and `XDG_STATE_HOME` point into `files/wineprefixes//linux_pfx/`, so config, cache and state land there instead of in your `~`. The prefix select in the app's config picks which one; **Open data folder** takes you to it. `linux_pfx` is machine-local — a LAN sync never pushes it and never deletes it. +A native app runs with its **own home folder**: `HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME` and `XDG_STATE_HOME` point into `files/wineprefixes//linux_pfx/`, so config, cache and state land there instead of in your `~`. The prefix select in the app's config picks which one; **Open data folder** takes you to it. `linux_pfx` is part of its prefix like everything else: a sync carries it with the prefix — Linux apps and their data travel in the same categories as the Windows ones. -When **bubblewrap** is installed *and* usable (PLWL probes it with a real run, not `which bwrap` — Ubuntu's AppArmor profile kills it even when it is installed), the app also gets its own namespaces: `/` is mounted read-only, so only **its home folder and its own app folder stay writable** — anything else fails with `EROFS`. The app folder is included on purpose: portable apps keep their logs and data next to themselves (Prism Launcher refuses to start otherwise). System trees are never handed out writable, not even when the app itself lives in one. Screens, audio (X11/Wayland, PulseAudio/PipeWire), gamepads and networking keep working. `XDG_RUNTIME_DIR` stays the host's, so the session bus is shared — the sandbox is not airtight, and the UI says so rather than pretending. +When **bubblewrap** is installed *and* usable (PLWL probes it with a real run, not `which bwrap` — Ubuntu's AppArmor profile kills it even when it is installed), the two sandboxed levels also give the app its own namespaces: `/` is mounted read-only, so only **its home folder and its own app folder stay writable** — anything else fails with `EROFS`. Relaxed adds exactly one mount on top of that profile (the writable host filesystem described below); everything else on this page is the same at both levels. The app folder is included on purpose: portable apps keep their logs and data next to themselves (Prism Launcher refuses to start otherwise). System trees are never handed out writable, not even when the app itself lives in one. Screens, audio (X11/Wayland, PulseAudio/PipeWire), gamepads and networking keep working. `XDG_RUNTIME_DIR` stays the host's, so the session bus is shared — the sandbox is not airtight, and the UI says so rather than pretending. + +A file your desktop hands the app — a drag-and-drop from your file manager, a file picked in a file dialog — is named by its **real path** (`/home/you/Downloads/mod.jar`), and inside the sandbox that name is the app's own redirected home. At **Relaxed** your home folders are linked back into the app at those very paths, through the writable mount, so the drop opens where it lies and a save lands on your real file; the one name left alone is the folder the app itself lives in, which keeps its plain path (a link there turned a launcher app's own instances into a `/tmp` path, which Prism Launcher refuses to see as permanent). At **Isolated** there is no view to link into, and what reaches the app there is only what the launcher hands it, as a copy (see the levels below). The redirected home starts with a **copy of your desktop preferences** — `kdeglobals`, the GTK 3/4 settings and `user-dirs.dirs` — so the app keeps your theme instead of falling back to its built-in light look. The copy keeps following your host as long as the app has not changed it: a theme change arrives on the next launch, and the moment the app writes its own version, PLWL never touches it again. Your own **fonts, icons, themes and colour schemes are not copied but mounted read-only** inside the sandbox and added to `XDG_DATA_DIRS`, so they follow the host live and nothing can be written back to your `~`. +**Anything the app wants to open is opened by your own desktop.** A **link** goes to the host's xdg-desktop-portal, so it lands in the browser you actually chose instead of one resolved in here, where the default association and its `.desktop` file are behind the redirected home — that used to mean a system browser you never picked, or nothing at all. Both routes reach the portal: `xdg-open` itself (what Qt, Prism and Electron call) and GIO's in-process resolution (`gtk_show_uri`). A **folder or a document** (Prism's *Open Pack Folder*, a text file, a drop) takes the other route: the app leaves the target in its own home, PLWL picks it up, translates the path back out of the sandbox and opens it with your `xdg-open` — so it arrives in your file manager, and a scheme nothing handles gets your desktop's own *Choose an application* dialog rather than a guess. On a machine without a portal nothing is changed — a link then behaves exactly as it did before. A KDE-native app that resolves the link in-process through KIO (Dolphin, Kate) is the one path still left out: it asks KDE's own handler database, which has no answer in here (measured: `kde-open` opens nothing and reports success). + Every prefix in the **Wine prefixes** tab has a **Reset Linux config** button: it deletes the desktop preferences PLWL copied in (and the hashes that track them), so the next app start seeds a clean copy from your system — the way back when an app has hijacked a seeded file with its own theme. App data in `linux_pfx` is never touched, and an app running from that prefix blocks the reset. -Imported trees get **normalised permissions**: every file gets the owner's `rwx` and an `x` mirrored from its `r`, because sources come from archives, FAT sticks or read-only backups where those bits are simply not there. +Imported trees get **normalised permissions**: every file gets the owner's `rwx` and an `x` mirrored from its `r`, because sources come from archives, FAT sticks or read-only backups where those bits are simply not there. An import whose copy could not reproduce every file is **refused** and the partial copy is removed, so a half-copied app is never registered. Some apps draw their window icon themselves, which Wayland does not allow — Minecraft (LWJGL 3.4+) is the known case: its taskbar icon turns into the generic Wayland one. The per-app **Force X11 (XWayland)** switch moves the app *and the programs it launches* back to X11, where the icon works again. -Per app you choose the **Isolation** policy: *Automatic* (bwrap when it works, plain run when it does not), *Off*, or *Required* (refuse to start instead of running unsandboxed). The backend actually used is always visible: a badge on the library card, a `[plwl] isolation: …` line in the app log, and a status card in Settings with **Check again**. When bwrap is missing, PLWL says so once instead of quietly launching without it. +Per app you choose the **Isolation** level — what the app gets besides its own home folder: + +- **None** — a plain run. The app sees your real filesystem exactly as any other program of yours does: what a shortcut hands it works, including into an app that is already running. +- **Relaxed** — the sandbox *plus* your whole filesystem mounted writable at `/tmp/plwl-fs-root`. A document handed over behaves natively — it opens where the app was told it is, it can be saved, and it also reaches an app that is already running, because the mount is there from the first second of every run. Your home folders are linked back into the app through that mount, so a file you drag onto the app, or pick in its own dialog, opens at its real path too. The price is real and the UI says it: at this level the app can change anything your user can. +- **Isolated** — the sandbox without that mount. The system stays read-only, and a document handed over is **copied** first, into `plwl-handoff` inside the app's own home folder; the app works on that copy (so the original cannot be touched), and a copy big enough to be noticed shows a progress popup in the launcher. There is no view of your home here, so a drop from your desktop or a file picked in a dialog cannot reach the app — only what the launcher hands over does, as that copy. +- **Automatic** (default) — Relaxed where bubblewrap works, None where it does not. + +An explicit Relaxed or Isolated on a machine without a working bubblewrap **refuses to start** instead of quietly dropping the promise; Automatic is the one level allowed to weaken itself. What the app really ran as is always visible: a badge on the library card, a `[plwl] isolation: …` line in the app log, and a status card in Settings with **Check again**. When bwrap is missing, PLWL says so once instead of quietly launching without it. ## "Open with PLWL" -The desktop entry registers `.exe/.msi/.bat/.cmd/.lnk` in file managers. Opening one shows a popup to pick the **Wine/Proton build** and **prefix** for that run (defaults preselected, nothing imported). A second instance hands the path to the running one. App shortcuts work as **Open With** targets too: the app receives the file as the Windows path it would get on Windows — `C:\...` inside its prefix, `Z:\...` otherwise. A file handed to an already running app goes to that instance instead of a second tracked run. +The desktop entry registers `.exe/.msi/.bat/.cmd/.lnk` in file managers. Opening one shows a popup to pick the **Wine/Proton build** and **prefix** for that run (defaults preselected, nothing imported). A second instance hands the path to the running one. App shortcuts work as **Open With** targets too: the app receives the file as the Windows path it would get on Windows — `C:\...` inside its prefix, `Z:\...` otherwise. A file handed to an already running app goes to that instance instead of a second tracked run. A **Linux app shortcut** is an Open With target the same way, and what the app is handed depends on its isolation level: at **None** the plain absolute path, at **Relaxed** the same file through the writable host mount (`/tmp/plwl-fs-root/…`) — which is also the only shape an app that is *already running* can resolve, since a mount cannot be added to a live sandbox — and at **Isolated** a copy in `plwl-handoff` inside the app's own home folder, so the original stays untouched. ## LAN syncing @@ -66,13 +77,19 @@ Two PLWL installs on one LAN can mirror each other (sidebar → **LAN syncing**) - **Device ID** (24 chars) and **Sync code** (8 chars, letters+digits, case-insensitive), both re-rollable. A caller must prove it knows its own code; each verification costs 2 s and one may run at a time, so guessing is pointless. A correct code still opens an **Accept/Decline popup** on the receiver (60 s timeout); declining or ignoring never touches this machine and keeps the pairing. - **Devices on your network** are found over UDP and visible only while PLWL runs there (a few seconds after it closes they are gone). -- Pick what to push: **portable apps**, **prefix-imported apps**, **Wine/Proton builds**, **prefixes**, **Sync settings**. Only what is ticked travels — without **Sync settings** the other machine's defaults and app configs are untouched. An accepted code is stored with the device ID, so later syncs need no typing; a re-rolled code is forgotten and asked for again. +- Pick what to push: **portable apps**, **prefix-imported apps**, **Wine/Proton builds**, **prefixes**, **Sync settings**. Each category also has a **Select** list: everything starts ticked, and unchecking an app, a build or a prefix keeps that item on both machines untouched. Only what is ticked travels — without **Sync settings** the other machine's defaults and app configs are untouched. An accepted code is stored with the device ID, so later syncs need no typing; a re-rolled code is forgotten and asked for again. + + A prefix-imported app's own folder lives inside its prefix, not in `files/apps/`. Unchecking such an app leaves that folder alone even when the prefix itself is synced: the sender takes it out of the prefix unit and marks it as off-limits for deletion. The picker says so when the app is ticked but its prefix is not — the folder then stays behind with the prefix. **Both machines show a progress popup** (phase, unit, files, per-category counters like `Apps: 2/5`, transferred vs. planned bytes; the bar follows the current phase). The popups cannot be dismissed, and a sender hashing a big unit shows *Waiting for the other device…* instead of a dead popup — the sender pings while it works. They close on completion, or after 15 minutes of silence (and reopen if the sync turns out to be alive). -The **sender is the source of truth**: differing files are overwritten, missing ones written, extras inside the synced trees (`files/apps/`, `files/wines/`, `files/wineprefixes/`, `files/data/icons/`) deleted. Files are compared with BLAKE2b-512 (SHA-512/SHA-256 fallback); **Force sync all files** skips the comparison. Hashes are cached per file (size + mtime), so an unchanged library costs nothing to re-sync. Permissions travel with the files, and symlinks are sent as **relative** paths whenever the target belongs to the launcher (a Proton prefix's links into its build keep working on the other machine); `dosdevices` and targets outside `files/` stay absolute, and links wine itself rewrote to absolute are relativized again on the wire, on import and before every run. +The **sender is the source of truth for what it sends**: differing files are overwritten, missing ones written, and extras inside the synced trees (`files/apps/`, `files/wines/`, `files/wineprefixes/`, `files/data/icons/`) are removed — but only after the receiver says so. Nothing is deleted while the bytes move: each unit only *plans* its leftovers, and the receiver gets one popup at the end with the top-most folders that would go (a fully redundant folder is a single collapsed row, a partly redundant one can be expanded). Every row is ticked to delete; unchecking a folder or a file keeps it. **Keep everything** is always one click away, an unanswered or expired list removes nothing, and a tree the sender could not fully read is never pruned at all, because a missing entry may only mean it was unreadable. -A sync also carries **how apps are set up**: wine build and prefix, args, env, DLL overrides, playtime and last played. **Sync settings** carries the registry-level part even when no files move: default wine/prefix, custom build names, prefix registry, every app's configuration and the library order. It only patches what already exists (unknown ids are ignored, unknown apps/prefixes stay), deletes nothing, and playtime only grows — the higher counter wins. Language, window settings, logs and external (leave) apps stay local. +That review is the only deletion path, so no backup copy is ever made — the files simply stay on disk until the answer. Two things it cannot undo: files that exist on both sides with different content are **overwritten** with the sender's version (the popup says so; if a game is installed on both computers, leave its prefix out of the sync), and a file kept in one sync is proposed again the next time, since the mirror is recomputed from scratch every run. + +Only one sync runs at a time (a second attempt on the same machine answers *busy*), and a transfer cut off mid-file leaves no half-written file behind. Files are compared with BLAKE2b-512 (SHA-512/SHA-256 fallback); **Force sync all files** skips the comparison. Hashes are cached per file (size + mtime), so an unchanged library costs nothing to re-sync. Permissions travel with the files, and symlinks are sent as **relative** paths whenever the target belongs to the launcher (a Proton prefix's links into its build keep working on the other machine); `dosdevices` and targets outside `files/` stay absolute, and links wine itself rewrote to absolute are relativized again on the wire, on import and before every run. A peer that predates the review cannot sync units at all (it would prune without asking); update both machines. + +A sync also carries **how apps are set up**: wine build and prefix, args, env, DLL overrides, a native Linux app's isolation level and Force X11, playtime and last played. **Sync settings** carries the registry-level part even when no files move: default wine/prefix, custom build names, prefix registry, every app's configuration and the library order. It only patches what already exists (unknown ids are ignored, unknown apps/prefixes stay), deletes nothing, and playtime only grows — the higher counter wins. Language, window settings, logs and external (leave) apps stay local. ## Wine & Proton support diff --git a/development.md b/development.md index f464a91..8f02827 100644 --- a/development.md +++ b/development.md @@ -15,11 +15,17 @@ src/ main process (Node/Electron backend) lansync.js LAN sync handlers (identity, devices, re-roll, sync + progress) runner.js spawns wine/proton (env, prefix, playtime, logs) and owns spawnTracked() - the log/playtime/exit tail every run shares - linuxrunner.js native Linux apps: redirected HOME/XDG, bwrap or plain run + linuxrunner.js native Linux apps: redirected HOME/XDG, the isolation level + (none/relaxed/isolated/auto), the handed-document path and + the relaxed home redirects + openrelay.js the launcher side of the hand-off: the request folder an app + leaves what it wants opened in, watched while it runs linuxapp.js native app detection (ELF/AppImage/.desktop) + icon lookup sandbox.js bubblewrap probe (functional, cached) + buildBwrapArgs + (+ FS_ROOT, the one mount the relaxed level adds) library.js apps registry (apps.json) + settings + playtime files, plus - the "which prefix does this app use" / in-use guards + the "which prefix does this app use" / in-use guards and + the isolation-mode gate on the way in wines.js wine/proton build scan, registry, portable symlink healing prefixes.js prefix registry (files/wineprefixes) symlinks.js relative symlink rewiring + executable-bit restoration @@ -38,6 +44,8 @@ src/ main process (Node/Electron backend) (with its receive-progress hook); uses hashcache.js, lansync-identity.js, lansync-manifest.js, lansync-discovery.js lansyncpush.js the pushing side (createPusher factory, keeps helper state out) + lansync-plan.js planned (never immediate) deletions: the receiver's leftovers, + top-most folders, and execution of only what was approved hashcache.js file hash cache (path -> size/mtime/hash) for LAN sync lansync-identity.js identity + sync code (createIdentity factory) lansync-manifest.js sender-side manifest building (createManifestBuilder) @@ -64,43 +72,61 @@ Renderer never touches Node/Electron directly — everything goes through the `w - No duplicate logic: the second time you copy something, move it into a helper and call it from both places. - Everything user-visible goes through the translation files (en-us.json, pl.json) with `{0}`, `{1}` placeholders. No hardcoded strings in app.js. - Paths stored on disk are FILES-relative (portable layout): write with toPortablePath(), read with resolvePortablePath() — never store absolute paths for anything inside files/. -- Registries (apps.json, wines.json, prefixes.json) are rewritten whole via writeJson(); playtime lives in its own tiny file so the registry is not rewritten while a game runs. +- Registries (apps.json, wines.json, prefixes.json) are rewritten whole via writeJson(); playtime lives in its own tiny file so the registry is not rewritten while a game runs. A settings sync batches its patches instead of one write per app/build (`library.updateGames`, `wines.applySettings`). +- Tree walks (`copyTree`/`treeSize`/`removeTree`/`chmodTree`) keep TREE_CONCURRENCY operations in flight instead of one syscall per await. `copyTree` returns a `failed` count; an import that could not reproduce every entry is refused and its partial destination removed, never registered with holes. +- The app's own folder is `library.appFolder(game)` — the folder it was imported as, never `workdir` and never `dirname(exePath)`. The properties may point the working directory elsewhere, and the sandbox, the delete path and LAN sync all have to agree on the same tree. - Deleting user data needs a confirm modal; best-effort cleanup is try/catch-and-ignore with a comment saying why it is safe to ignore. - Windows apps run through runGame()/buildEnv() — never spawn wine directly elsewhere (prefix handling, Proton env and playtime live there). -- Native Linux apps run through linuxrunner.runLinuxGame()/buildLinuxEnv() the same way: HOME and the XDG folders are redirected into `{prefix}/linux_pfx/`, and bwrap (when the probe says it works) forces the same layout with mounts. Never spawn a native app elsewhere. `game.kind` is absent on old entries — that means Windows; `game.isolation` is `auto` (bwrap when usable, plain run otherwise), `off` or `require` (refuse to start instead of quietly weakening). The chosen backend always lands in the log and the UI (a silent downgrade is the failure mode to avoid). -- Under bwrap ONLY two things stay writable: the redirected home and the app's own folder (`writableAppDir`: inside files/apps, or the folder the app was imported from — never `/usr`, `/etc`, `/bin`… and never files/wines). Portable apps write logs and data next to themselves and a read-only app folder makes them refuse to start (Prism Launcher: "couldn't create a log file - Read-only file system"). Everything else is `EROFS` by design. +- Native Linux apps run through linuxrunner.runLinuxGame()/buildLinuxEnv() the same way: HOME and the XDG folders are redirected into `{prefix}/linux_pfx/`, and bwrap (when the probe says it works) forces the same layout with mounts. Never spawn a native app elsewhere. `game.kind` is absent on old entries — that means Windows; `game.isolation` is one of four levels, resolved by linuxrunner.resolveLevel: `none` (plain run), `relaxed` (bwrap + the whole host filesystem mounted writable at sandbox.FS_ROOT) and `isolated` (bwrap with the stock read-only profile), with `auto` (default) meaning relaxed where bwrap works and none where it does not. Only `auto` may weaken itself — an explicit relaxed/isolated answers `sandbox-required` instead ("no silent downgrade"). library.js keeps exactly these four values, both when reading the registry and when a patch is saved (anything else falls back to `auto`), and the level always lands in the log and the UI. resolveLevel awaits the probe when nothing has measured yet: a shortcut boots HEADLESS, so no renderer ran `sandbox:status` — without that wait `auto` would read an empty cache and quietly pick `none` (and an explicit level would refuse a machine that can sandbox perfectly well). +- Under bwrap ONLY two things stay writable: the redirected home and the app's own folder (`writableAppDir`: inside files/apps, or the folder the app was imported from — never `/usr`, `/etc`, `/bin`… and never files/wines). Portable apps write logs and data next to themselves and a read-only app folder makes them refuse to start (Prism Launcher: "couldn't create a log file - Read-only file system"). That bind is written LAST in buildBwrapArgs on purpose: an app lives under the host's home and the redirected home is mounted over that very directory, so the bind used to be swallowed by it and bwrap answered `execvp : No such file or directory` — a click on Play and the window closed again (measured on 0.12.0, and again as a real exec in test/sandbox-appdir.test.js). Everything else is `EROFS` by design — at the isolated level. Relaxed is the deliberate exception and says so in the UI: `FS_ROOT` is the same filesystem, mounted writable, so "everything else" is only unreachable through the real paths. - Two pipes feed one log in spawnTracked: neither may end the stream (pipe(ws, { end: false }), closed when both sources drained, at the latest LOG_DRAIN_MS after the exit) and the write stream carries an error listener. Ending it at `exit` while a pipe still had data killed the whole launcher with ERR_STREAM_WRITE_AFTER_END. - A prefix or wine build a running app uses cannot be renamed/deleted (wine holds files open there): the guards sit next to the handlers in src/ipc/, use the games service's running list plus library.js helpers (prefixNameForGame/gamesUsingPrefix/is*InUse) and answer `{ ok:false, error:'inUse'|'hasApps', apps:[names] }` for the toast. -- Long operations stream progress through the single import:progress slot as `{ phase: 'count'|'copy'|'remove', files, bytes, totalFiles, totalBytes }` (runWithProgress for deletes/imports). Emit 'count' (a treeSize walk) first, copy/remove through the fsutil helpers. +- Long operations stream progress through the single import:progress slot as `{ phase: 'count'|'copy'|'remove', files, bytes, totalFiles, totalBytes }` (runWithProgress for deletes/imports). Emit 'count' (a treeSize walk) first, copy/remove through the fsutil helpers. An isolated hand-off has its own slot, handoff:progress (`{ phase: 'copy'|'done'|'error', name, bytes, totalBytes, notice }`), because it can start before the window exists: main.js gets the event first and, when `notice` is set (a copy above linuxrunner.STAGE_NOTICE_BYTES), puts the launcher window up so the renderer's popup can be seen; below that the copy is over before a window could paint. Copies of one file go through fsutil.copyFileProgress (streamed, throttled by progressGate, `.part` + rename). - CSS: reuse the existing variables/classes (.button, .field-label, .custom-select, form-card); spacing comes from --button-margin and flex gaps, not per-element magic numbers. +- The blanket `transform: translateZ(0)` (crisper small glyphs) makes every element its own stacking context, so a select's own z-index cannot escape the wrapper it sits in: a list opened inside `.linux-only`, `.win-only` or an override row was painted UNDER the field label and textarea that follow it (measuring with `elementsFromPoint` over the open list returned the label). CustomSelect lifts the chain instead of the host — `lift()` adds `.select-lift` to every STATIC ancestor while the list is open, and `close()`/`closeAll()` take it off again; positioned ancestors are skipped, so the fixed modal overlay keeps stacking over every view on its own. ### Native Linux apps - Entry point detection (linuxapp.js): ELF, `.AppImage`, or a `.desktop` whose `Exec=` points at one; `lib/`, `share/` … are skipped. The icon comes from the `.desktop` `Icon=`, an image next to the program, or the system theme — `extractIconFromExe` is PE-only. -- The redirected home starts as a COPY of the desktop preferences (kdeglobals, kdedefaults/kdeglobals, gtk-3.0|gtk-4.0/settings.ini, qt5ct/qt6ct, Trolltech.conf, user-dirs.dirs). Without the seed Qt falls back to its built-in light palette (measured: `#eff0f1` against the host's `#202326`). The copy keeps following the host while the app has not touched it: the hashes of what PLWL wrote live in `{prefix}/linux_pfx/.seeded.json`, OUTSIDE the app's home, and a prefix from an older launcher is adopted on evidence (byte-identical with the host, or the copy is older than the host's file). The PulseAudio cookie is seeded once, because with a redirected home Pulse looks in `$HOME/.config/pulse/cookie` and the app otherwise comes up silent; `~/.Xauthority` is refreshed instead, since nothing exports XAUTHORITY to a sandboxed app. +- The redirected home starts as a COPY of the desktop preferences (kdeglobals, kdedefaults/kdeglobals, gtk-3.0|gtk-4.0/settings.ini, qt5ct/qt6ct, Trolltech.conf, user-dirs.dirs). Without the seed Qt falls back to its built-in light palette (measured: `#eff0f1` against the host's `#202326`). The copy keeps following the host while the app has not touched it: the hashes of what PLWL wrote live in `{prefix}/linux_pfx/.seeded.json`, OUTSIDE the app's home, and a copy with no marker entry (or one the app has since changed) is the app's own and is never overwritten. The PulseAudio cookie is seeded once, because with a redirected home Pulse looks in `$HOME/.config/pulse/cookie` and the app otherwise comes up silent; `~/.Xauthority` is refreshed instead, since nothing exports XAUTHORITY to a sandboxed app. - Host fonts/icons/themes/colour schemes are not copied but `--ro-bind` under `/tmp/.plwl-host/…` and prepended to XDG_DATA_DIRS: live, and unable to write back into the user's `~`. Symlinks were measured and rejected — the prefix is mounted ON `~`, so a link to `~/.config/kdeglobals` points at itself (`Too many levels of symbolic links`); without bwrap the same link writes through into the real home. - `forceX11` (per app) sets XDG_SESSION_TYPE=x11 + QT_QPA_PLATFORM=xcb + GDK_BACKEND=x11 so the app and everything it launches falls back to XWayland, where window icons still exist at all (Wayland forbids them; a compiled GLFW probe showed XDG_SESSION_TYPE picks X11 vs Wayland, `GLFW_PLATFORM` does not exist). `game.env` still wins. - SESSION_MANAGER is dropped in the sandbox: the session socket sits in the private `/tmp`, so the pointer led nowhere (Qt: "Could not open network socket"). - Imports normalise permissions (fsutil.chmodTree): owner `rwx`, `x` mirrored from `r` (0644 → 0755). Sources are archives, FAT sticks and read-only backups. - **Reset Linux config** on every prefix row removes exactly what PLWL seeded (DESKTOP_SEEDS, the pulse cookie, `home/.Xauthority`, `.seeded.json`) plus the folders that existed only for the seed, so the next start seeds clean. syncDesktopConfig can only follow a copy it can still prove is its own; the reset does not argue. App data (`data/`, `cache/`, `state/`, `config//`, the rest of `home/`) is never touched, and a running app from that prefix blocks it (the usual `inUse` guard). -- The user's real `~` is deliberately invisible in the sandbox (HOME is bound straight to `{prefix}/linux_pfx/home`), so absolute paths an app wrote into its config before the import (Prism's instance `JavaPath`) do not resolve — that is what `isolation: 'off'` is for. -- Not built: a private or overlay `/etc` (`buildBwrapArgs` accepts `etcRoot`, nothing sets it; `--ro-bind / /` leaves `/etc` read-only, which is all we promise today), `--tmpfs /home` against OTHER users' homes (`hideHome` is plumbed, no UI) and `dataMode` — app data always lands in `{prefix}/linux_pfx`. +- A path the desktop hands the app (a drag-and-drop's `text/uri-list`, a file picked in a dialog - `QT_QPA_PLATFORMTHEME=xdgdesktopportal` on this desktop, so the chooser is the host portal's and answers with a real path) is a real `/home//…` path, and under bwrap that name is the app's own redirected home. A mount cannot fix it (a mount cannot be added to a namespace that is already running) and binding the host home in would hand the app the user's real folders at every level: `syncHomeRedirects` links the host home's own entries (never a name the profile mounts itself - `.plwl` and the XDG folders, which a link would turn into bwrap's `Can't mount on symlink destination` on the first relaxed run of a fresh prefix, measured; never a name the app already has, never a link resolving nowhere) into the one view the level has - at relaxed to `FS_ROOT/`, which is the real folder, live and writable (measured: the real file reads through the link, and a write through it lands on it), and at the other levels there is no view to point at, so the links are taken off again before the app starts. The name the app's own folder sits under is never linked either: a portable bundle resolves itself with `readlink -f "$0"`, so the link answered for the app's whole tree - instances included - with `FS_ROOT`, and Prism Launcher read that as "Your instance folder is in a temporary folder: '/tmp'!" on every start (measured on 11.0.2 on the device whose launcher lives in the home; the same app on a launcher outside `~` kept its real path and stayed quiet - the folder is bound at its real path anyway). Only the launcher's own links are removed (matched by their `FS_ROOT` target), and an isolated app gets no home folders at all: what reaches it there is the hand-off copy. The links outlive a run (a hand-off into an app that is already running is still using them); the next start at a level that cannot serve them clears them. +- With HOME bound straight to `{prefix}/linux_pfx/home`, the user's real `~` is invisible to the app — one reason absolute paths an app wrote into its config before the import (Prism's instance `JavaPath`) do not resolve. `relaxed` does not change that shadowing, but it does make the real filesystem reachable through `FS_ROOT`/home/… — and `none` gives the app the real paths outright, which is what those two levels are for. +- A clicked link belongs to the host desktop, so it leaves through `org.freedesktop.portal.OpenURI`: the `xdg-open` BINARY is replaced inside the sandbox (a written shim `--ro-bind` over `/usr/bin/xdg-open`, and over the app bundle's own `bin/xdg-open` too — that one sits first in the app's PATH, and its sharun wrapper dies on a closed stderr (`SIGPIPE`) before it ever delegates, which is exactly what Minecraft does after `Runtime.exec`; the name the bundle links to that same file, `gio-launch-desktop`, is answered by the shim, since bwrap refuses to mount over a symlink; a `-`-prefixed argument exits 2, because Java probes for `xdg-open` by running it with one) and Qt execs it (measured — `QGenericUnixServices` picks `xdg-open` first, and reaches the portal itself only under `/.flatpak-info`/`SNAP`, which a bwrap profile does not have); Electron does the same. GIO resolves an URI IN-PROCESS, which no shim can reach: for that the prefix seeds `home/.plwl/open-url` (launcher-written, like the shim) plus a desktop entry and a `mimeapps.list` naming it the default for `x-scheme-handler/http|https`, `text/html`, `x-scheme-handler/file` and `inode/directory`. Without the seed GIO falls back to the host's `/usr/share` list — measured: it offered `brave-origin.desktop`, and `gio open` answered "The specified location is not supported". Measured end to end (both backends): the portal launches the host's `helium.desktop` with the exact URI. `GIO_USE_PORTALS=1` was measured and REJECTED: it opened NOTHING and still reported success (GIO's portal path wants a sandbox marker this launcher does not fake). A KDE-native app resolving the link in-process through KIO (`kde-open`) stays uncovered — KDE ignores the seeded list (measured). +- The games service owns a run through the entry object it created: a start that failed, and the exit of a PREVIOUS run of the same app (stopped, then relaunched — SIGKILL is asynchronous), may not clear the new run's entry or close its request watcher (`forget`/`handleExit` compare that object). A start still in flight is never pruned, however long its isolated hand-off copy takes, because pruning it would drop the watcher mid-start; Stop during that window only records a kill request (`killRequests`), which the start fulfils the moment it has a pid — clearing the state there instead would let a second launch race past the first. Measured in test/games-service.test.js. +- The portal is not told about a FOLDER or a document, which is what "Open Pack Folder" or a drop asks for: it cannot see a path from in here and answers `Response` 2 for `file://` (measured, while https answered 0). The shim leaves those in `home/.plwl/open-request` (written as `.part` and renamed, so nothing ever reads half a request) — a live bind of the app's home, so it reaches an app that is ALREADY running — and the launcher opens it out here with the host's own `xdg-open` (openrelay.js: `createOpenRelay` watches that folder for exactly as long as the app runs, consumes each request once, and quits watching on exit). The target is rewritten on the way out — the private `$HOME` back to `{prefix}/linux_pfx/home`, `FS_ROOT` back to `/` at relaxed — so the host opens the REAL folder and never a path that only exists inside. Nothing in the sandbox can start a host program itself: measured, the host's own `xdg-open` run in there ends in `kde-open`, which exits 0 and opens no window at all. A scheme nothing on the host claims ends in the desktop's own "choose an application" dialog, which is the point of handing it out instead of guessing. +- The portal's `Response` is NOT read back: it is a signal addressed to the caller's own bus connection, so a separate `gdbus monitor` never receives it (measured: 15 calls, 15 timeouts, while the portal did open what it was given) and the readback only cost the app 3 s per click before giving up. Only whether the call went out is trusted, so a machine without a portal needs no special case any more: the call fails, and the request file is what still lands. (0.5.x had the host's own script parked inside the sandbox as the shim's fallback; measured, that route opens nothing.) +- A file handed over (a shortcut's `--file %f`, a drop on it) is the one path the sandbox cannot see by itself: a file out of the user's home is buried under the prefix home, one out of `/tmp` sits behind the private tmpfs, and the rest of the machine is read-only. Per-file `--bind` (what 0.5.0 did) is the wrong tool: a mount cannot be added to a namespace that is ALREADY running, so a hand-off into a running app could never be served that way. `handedPathFor` instead names the document in the one shape the chosen level can reach, and the app is told nothing else: `none` → the real path; `relaxed` → `FS_ROOT` + the real path; `isolated` → a copy in `{prefix}/linux_pfx/home/plwl-handoff/`, which is a live bind of the app's home, so it reaches a running app too (measured end to end in test/linux-e2e.js: both levels hand a document to a sandbox that is already up). Copies are one per name and refreshed on every open (the folder cannot grow), written through a `.part` name and renamed so nothing ever reads a half-written document, and the app's edits stay in the copy — that IS the level's promise. A handed path that is gone fails the hand-off instead of launching an app with no document. +- `FS_ROOT` (`/tmp/plwl-fs-root`) is where relaxed mounts the host filesystem, and it has to live under the private `/tmp`: bubblewrap creates the mount point itself, and the root of a read-only root cannot be written to (measured on 0.12.0: `Can't create file /PLWL_FS_ROOT: Read-only file system`, for a `--dir` before the `--ro-bind / /` too). Measured also: through it the real `~` reads, a write lands on the real file, and a file created AFTER a sandboxed run started is visible inside it — that last one is what makes a hand-off into a running app possible at all. +- Not built: a private or overlay `/etc` (`buildBwrapArgs` accepts `etcRoot`, nothing sets it; `--ro-bind / /` leaves `/etc` read-only, which is all we promise today), `--tmpfs /home` against OTHER users' homes (`hideHome` is plumbed, no UI); app data always lands in `{prefix}/linux_pfx`. - Measured, not assumed (Debian 13, kernel 6.12, `bwrap` 0.12.0): the functional probe passes here, no firejail/proot/fuse-overlayfs on the box, `/etc` is 16 MB and its `machine-id` is read-only even on the host. ### LAN sync - Two sides: the receiver lives in lansync.js, the sender in lansyncpush.js, built by createPusher(helpers) — several launcher states share the module, so nothing may sit in its module scope. Both sides report their own progress (receiver through the onReceive hook). +- **Deletions are planned, never inline.** `handleCommit` only walks the unit (`planUnitDeletions` -> `lansync-plan.js`) and stores the list on the session; `/plwl/apply` turns units plus registry leftovers into one review (`startReview`), and `executeReview` is the only place that removes anything. A path in the keep set survives (including a file inside a fully planned folder), an unreadable subtree is planned as kept, and a selection's excluded folders are protected the same way. Registry removals wait with the files, so unchecking an app row cannot leave its entry behind without its folder or the other way round. A review that times out, is skipped (no popup, headless) or never arrives cancels to **zero deletions**. A peer without the `review` flag in its verify answer cannot sync units (`old-peer`): it would prune inside its commit with no list to approve; a settings-only sync stays allowed because it deletes nothing. - An incoming sync needs CONSENT: a correct code opens the gate, but the receiver's onIncoming hook (registered in main.js) shows Accept/Decline, answered through lansync:respondIncoming. Unanswered requests expire (INCOMING_TIMEOUT_MS); a decline returns 'rejected' and KEEPS the pairing (the code was proven). Without an onIncoming hook (tests, headless) the gate stays open. - Progress is bytes plus per-category counters (items = announced units, itemsDone = finished, totals = everything picked) — "Apps: 2/5". The bar follows the CURRENT PHASE's bytes (barBytes/barTotalBytes) so a phase starts from an empty bar. Hashing and copying walk tens of thousands of files: every per-file update goes through progressGate (~10/s, phase changes forced) — never one IPC message per file. The gate holds a snapshot FUNCTION on the sender side: the snapshot is built when it flushes, so a throttled update never shows a byte count one gate window old. +- A finished sync ends with a result POPUP, not a toast: the sender swaps its locked progress modal for the summary, the receiver swaps the finished bar after ~1 s. It lists units per category, files moved/unchanged/removed, bytes transferred and the total size of the synced trees (`summary.sizeBytes`; the receiver adds each unit's announced `unitBytes`, replacing a retried unit's entry instead of double-counting). The device name is set with textContent, never interpolated into the modal HTML. +- App selection is a seam, not a UI yet: `buildUnits(cats, selection)` and `buildRegistryPayload(cats, selection)` take `selection = { apps: [ids] }` (a missing selection means every app). The payload then carries `appScope: 'selected'`; `applyApps` keeps the apps of that category that were not sent, and skips the `apps/` orphan sweep, instead of mirroring the category. Without the marker the sender's list is complete and extras are deleted as before. - The sender's transferred counter counts bytes AS THEY ARE READ (putFile's onBytes callback), not on upload completion: a multi-GB file has to move it while it flies or the sender shows hundreds of MB behind the receiver. A unit's byte total travels as the `{ unitBytes }` control record BEFORE its files; the receiver has to handle it before the entry filter (it has no path/type, so a filter-first order dropped it and the comparing bar measured against a placeholder total of 1 — read as 100% for the whole phase). The comparing phase ends on a full bar, then the copy bar restarts empty (its first PUT byte emits it). - While the receiver answers the consent popup (and whenever its side waits on the other one), both popups show "Waiting for the other device…" (lansync.waiting): the sender emits a 'wait' phase before verify, the receiver's ping handler emits stage 'wait'. A unit counts toward "Apps: 1/5" as soon as its comparison starts (not when it commits), and phases without a file count (hash/compare/commit) clear the counter so a stale "3 / 10 files" never lingers. On the wire the receiver's comparing phase is called 'compare' (sender-side 'plan' is unchanged). -- Registry-level settings are opt-in (the "settings" category, old name "defaults" still accepted as an alias on both sides). The payload carries defaults, wineSettings (displayName + disabled per build), prefixSettings, appSettings (name, wine, prefix, args, env, dllOverrides, disableUmu per app) and appOrder. The receiver only patches what already exists (unknown ids skipped, nothing created or deleted, unknown local entries kept at the end of the order) through the normal helpers (setWineDisplayName, library.updateGame, reorderGames). +- Registry-level settings are opt-in (the "settings" category). The payload carries defaults, wineSettings (displayName + disabled per build), prefixSettings, appSettings (name, wine, prefix, args, env, dllOverrides, disableUmu, isolation and forceX11 per app) and appOrder. The receiver only patches what already exists (unknown ids skipped, nothing created or deleted, unknown local entries kept at the end of the order) through the normal helpers — batched, so a large library is one registry write: `library.updateGames(patches)`, `wines.applySettings(entries)`, `reorderGames`. - File hashes are remembered in files/data/lansync-hashes.json (path -> size + mtime + hash; machine-local, never synced): equal size and mtime means equal bytes, so a repeat sync only stats the tree. Hashing and the receiver's comparison both run HASH_CONCURRENCY files at a time. +- A file's unit and path travel in the PUT's query, not in headers: Node rejects any header value holding a code above U+00FF (`ERR_INVALID_CHAR`), and a real library has those names (Minecraft pack names, Polish file names) — one such file killed the whole sync, leaving the receiver with half an app and no registry entry. Categories are matched by exact name; anything this build does not know is ignored. - File permissions travel with the manifest (`mode`) and are applied after the bytes; a file with the right hash but wrong mode is repaired without re-upload. +- A manifest the sender could not finish is not a licence to delete: a read that fails (a directory or file the user cannot open) sends a `{ unitIncomplete: true }` control record, and an aborted plan body is detected with `req.complete`. Either way the receiver still writes what it got but skips `pruneTree` for that unit — a missing entry may only mean "could not read it". For the same reason `applyApps`/`applyWines`/`applyPrefixes` mirror nothing when the payload has no list at all (malformed/truncated apply), while an explicit empty list still means "the sender has none" (a partial app selection excepted: it keeps the apps it did not send). +- A PUT settles on every failure path (`aborted`/`close` without the body having ended, stream or writer error): the `.plwl-sync-tmp` is removed and the request cannot stay half-open forever. The 60 s `PUT_IDLE_MS` only covers a body that stops sending. +- Verification is GLOBAL one-at-a-time (`state.verifying` is a boolean, set before the first await — parallel requests would pay the 2 s cost in parallel, which is exactly what makes a scheme pointless). One outgoing sync per process (`syncTo` answers 'busy'), so two syncs can never write the same receiver files at once. A failed bind resolves `{ ok: false, error }` instead of leaving `listening` pending forever, and the beacon only starts when the server is up. +- Names arriving on the wire that become paths (app ids in `data/icons/`, prefix folder names) are validated (`safeName`/`safePrefixName`): a corrupted or older peer must not be able to store `../../x` and turn a later Rename/Delete click into a write outside files/. - A sender hashing a big unit is minutes of silence: it pings `/plwl/ping` every HEARTBEAT_MS, the receiver re-arms its popup watchdog (stage 'wait' shows "Waiting for the other device…" but never while a file is being written). A receiving popup its watchdog closed reopens on the next real event — only 'done' ends a sync, and reopening never asks for consent again (consent is the onIncoming popup at verify time; the progress popup is driven by the same token's events). -- Native Linux app data (`{prefix}/linux_pfx/`: the redirected home, caches, PulseAudio cookie, machine-local state) is MACHINE-LOCAL: the sender's manifest skips it and the receiver's pruneTree refuses to delete it (prefixes.isLocalOnlyRel, shared by lansync-manifest.js and lansync.js). Otherwise a mirrored prefix sync would either push a huge cache or delete the other machine's app data. +- Native Linux app data (`{prefix}/linux_pfx/`: the redirected home, configs, caches, PulseAudio cookie, state) travels INSIDE its prefix unit like the Windows side of the same prefix: the manifest walks it and the mirror prunes it, so no file of the launcher's own trees is special-cased on the wire. Native apps sit in the same categories as Windows ones (`apps-portable`/`apps-prefix`), and only the per-app fields that are Linux-only (isolation, forceX11) are named as such in the settings payload. - A sync must never walk through a symlinked ROOT: pruneTree/healUnitRoots (sync), removeTree/treeSize (fsutil) and healBuild (wines) lstat the root first. `listDirs()` counts symlinked folders as units, so a build on another disk still travels — as the link it is (`wineUnits` maps nested builds to their TOP folder under wines/). -- Wine/Proton rewrite prefix links to absolute targets whenever they update a prefix, so on-disk links are not always relative after a run: the sync relativizes them on the wire (portableLinkTarget) and refreshWines()/healPrefix() repair what arrived from an older PLWL. A build whose binaries lost the executable bit is detected in refreshWines() and healed once (spawn() on a non-executable `proton` fails with EACCES while the game looks started). +- Wine/Proton rewrite prefix links to absolute targets whenever they update a prefix, so on-disk links are not always relative after a run: the sync relativizes them on the wire (portableLinkTarget) and refreshWines()/healPrefix() repair absolute links that reached disk anyway. A build whose binaries lost the executable bit is detected in refreshWines() and healed once (spawn() on a non-executable `proton` fails with EACCES while the game looks started). ### Paths and prefixes @@ -129,11 +155,15 @@ node test/lansync-pending-links.test.js # links to files created later, startup node test/lansync-consent.test.js # accept / decline / timeout gate node test/lansync-token.test.js # long-sync token expiry (sliding TTL) node test/bench-sync.js # timing: cold vs cached sync -node test/linux-sandbox.test.js # bwrap argv profile + auto/off/require choice +node test/linux-sandbox.test.js # bwrap argv profile + the four levels, handed paths, mode gate +node test/sandbox-appdir.test.js # the app folder stays reachable inside its own redirected home node test/linux-env.test.js # redirected HOME/XDG_* for both backends node test/linux-import.test.js # ELF/AppImage/.desktop detection + icons -node test/linux-sync.test.js # linux_pfx stays out of a sync -node test/linux-e2e.js # REAL run: plain + bwrap (/etc read-only, home in prefix) +node test/linux-links.test.js # link opening: shim binds + mime seed +node test/linux-open.test.js # what an app opens: the script + the launcher relay +node test/games-service.test.js # run bookkeeping: the request watcher, Stop while starting +node test/lansync-linux-apps.test.js # Linux apps + linux_pfx travel with their categories +node test/linux-e2e.js # REAL runs: plain, relaxed (+ its mount), isolated, hand-off into a running app npm start # click through the flow you touched # Repairing / testing a real instance (test/ scripts are gitignored helpers): diff --git a/files/translations/en-us.json b/files/translations/en-us.json index bac6a51..f412d6e 100644 --- a/files/translations/en-us.json +++ b/files/translations/en-us.json @@ -66,6 +66,7 @@ "import.noExe": "no .exe file found in the selected folder", "import.noLinuxExe": "no runnable Linux program found in the selected folder (ELF binary, .AppImage or .desktop)", "import.prefixRoot": "this folder is a wine prefix (or its C: drive) - import an app from inside its drive_c instead", + "import.copyIncomplete": "some files could not be copied - nothing was imported, the source folder is unchanged", "config.title": "App configuration", "config.icon.auto": "Extract from exe", "config.icon.autoLinux": "Extract icon", @@ -93,10 +94,15 @@ "config.openData": "Open data folder", "config.linuxKindValue": "Linux", "config.isolation": "Isolation", - "config.isolation.auto": "Automatic (strongest available)", - "config.isolation.off": "Off (plain run)", - "config.isolation.require": "Required (refuse to run without bwrap)", - "config.isolation.bwrap": "bwrap {0} (strong)", + "config.isolation.auto": "Automatic", + "config.isolation.none": "None", + "config.isolation.relaxed": "Relaxed", + "config.isolation.isolated": "Isolated", + "config.isolationHint.auto": "Relaxed where bubblewrap works; on a machine without it the app runs without isolation.", + "config.isolationHint.none": "No sandbox: the app sees, and may change, everything your user can.", + "config.isolationHint.relaxed": "The whole disk is mounted writable as /tmp/plwl-fs-root.", + "config.isolationHint.isolated": "The system is read-only.", + "config.isolation.bwrap": "bwrap {0} (available)", "config.isolation.env": "no sandbox: {0}", "config.forceX11": "Force X11 (XWayland)", "config.forceX11Hint": "Runs the app through XWayland instead of Wayland. Useful when a window cannot carry its own icon or misbehaves on Wayland.", @@ -109,7 +115,7 @@ "config.overrides.remove": "Remove", "config.overrides.hint": "Wine module names, e.g. dinput8. native,builtin (the default) loads a DLL shipped with the game and falls back to Wine's builtin; disabled blocks the module.", "sandbox.title": "Linux app isolation", - "sandbox.hint": "Native apps always run with a redirected home folder. With bubblewrap they get their own namespaces too: only their home folder and their own app folder stay writable, the rest of the system is read-only.", + "sandbox.hint": "Native apps always run with a redirected home folder, so their config and cache stay in the prefix. The isolation level says what else they get: None is no sandbox at all, Relaxed mounts the whole disk writable, Isolated writes nothing outside the app's own folders and copies an opened file into its home folder.", "sandbox.status": "Status", "sandbox.check": "Check again", "sandbox.rechecked": "Isolation checked again", @@ -118,13 +124,17 @@ "sandbox.reason.timeout": "not responding", "sandbox.reason.failed": "not working", "sandbox.warnTitle": "No sandbox for Linux apps", - "sandbox.warnBody": "bubblewrap is {0}. Linux apps will run with only a redirected home folder - they can still read the rest of your system, and write to anything your user can.", + "sandbox.warnBody": "bubblewrap is {0}. Apps left on Automatic run as plain programs (None), while apps set to Relaxed or Isolated refuse to start instead of pretending the sandbox is there.", "sandbox.dismiss": "Got it", - "sandbox.badgeStrong": "bwrap", - "sandbox.badgeWeak": "no sandbox", - "sandbox.badgeOff": "isolation off", - "sandbox.badgeRequired": "bwrap required", + "sandbox.badgeNone": "No isolation", + "sandbox.badgeRelaxed": "Relaxed", + "sandbox.badgeIsolated": "Isolated", + "sandbox.badgeRequired": "Bwrap required", + "handoff.copying": "Copying into the app: {0}", + "handoff.copyNote": "{0} / {1} - the app works on a copy inside its own home folder (plwl-handoff); edits in the copy never come back.", + "handoff.failed": "Could not copy {0} into the app: {1}", "sandbox.required": "This app needs a working bubblewrap sandbox: {0}", + "sandbox.linkOpener": "PLWL link opener", "config.save": "Save changes", "config.shortcut": "Create shortcut", "config.shortcutCreated": "Shortcut for {0} created (menu + desktop)", @@ -245,8 +255,8 @@ "lansync.prefixes": "Wine prefixes", "lansync.settings": "Sync settings (names, app configs and order)", "lansync.force": "Force sync all files (skip the hash check and overwrite everything)", - "lansync.mirrorWarning": "This device is the source of truth: on the other device, files and items that do not exist here will be deleted.", - "lansync.incomingMirror": "The other device is the source of truth: files and items on this device that do not exist there will be deleted.", + "lansync.mirrorWarning": "The selected items will match this device exactly. Nothing outside the selection is deleted, and the deletion list is approved on the other device.", + "lansync.incomingMirror": "The other device is the source of truth for the selected items. You will review the list of files to delete before the sync finishes.", "lansync.start": "Start sync", "lansync.progress": "Syncing to {0}…", "lansync.waiting": "Waiting for the other device…", @@ -257,7 +267,8 @@ "lansync.phase.copy": "Sending {0}", "lansync.recvPhase.copy": "Receiving {0}", "lansync.phase.registry": "Updating the library", - "lansync.phase.commit": "Removing extra files", + "lansync.phase.commit": "Checking for extra files", + "lansync.phase.review": "Waiting for the deletion approval", "lansync.phase.done": "Finishing up", "lansync.progressFiles": "{0} / {1} files", "lansync.progressBytes": "{0} / {1} transferred", @@ -278,6 +289,33 @@ "lansync.unknownDevice": "Unknown device", "lansync.recvIdle": "The other device stopped responding, the sync was interrupted.", "lansync.done": "Synced to {0}: {1} sent ({4}), {2} already up to date, {3} removed", + "lansync.summaryTitle": "Sync finished", + "lansync.summarySentTo": "Sent to {0}", + "lansync.summaryReceivedFrom": "Received from {0}", + "lansync.summaryApps": "Apps", + "lansync.summarySettings": "Settings", + "lansync.summarySent": "Files sent", + "lansync.summaryReceived": "Files received", + "lansync.summarySkipped": "Already up to date", + "lansync.summaryDeleted": "Removed", + "lansync.summaryTransferred": "Transferred", + "lansync.summarySize": "Synced data size", + "lansync.summaryKept": "Kept by the other device", + "lansync.pick": "Select", + "lansync.pickCount": "Select ({0}/{1})", + "lansync.pickSearch": "Search", + "lansync.pickAll": "Select all", + "lansync.pickNone": "Select none", + "lansync.prefixLeftBehind": "Prefix {0} is not selected — this app's folder will not travel.", + "lansync.reviewTitle": "Review deletions", + "lansync.reviewFrom": "Received from {0}. Review the list before anything is removed.", + "lansync.reviewText": "To delete: {0} files ({1}). Uncheck what should stay.", + "lansync.reviewOverwrite": "Files that exist on both sides are overwritten with the other device's version. If you play on both computers, leave this prefix out of the sync.", + "lansync.reviewKeepAll": "Keep everything", + "lansync.reviewDelete": "Delete {0} files ({1})", + "lansync.reviewDeleting": "Deleting…", + "lansync.reviewFiles": "{0} files · {1}", + "lansync.summaryYes": "yes", "lansync.failed": "Sync failed: {0}", "lansync.badCode": "Wrong sync code. Enter the code shown on the other device.", "lansync.busy": "The other device is busy (another sync or a running app).", @@ -287,6 +325,8 @@ "lansync.idRerolled": "New device ID generated", "lansync.codeRerolled": "New sync code generated", "lansync.unknownError": "unknown error", + "lansync.oldPeer": "The other device runs an older PLWL. Update it — without the deletion review this sync is not safe.", + "lansync.reviewExpired": "The deletion review expired and nothing was removed.", "openwith.title": "Open with Wine", "openwith.file": "File", "openwith.fileMissing": "This file no longer exists (or is not a Windows executable).", diff --git a/files/translations/pl.json b/files/translations/pl.json index 470e7c4..c900448 100644 --- a/files/translations/pl.json +++ b/files/translations/pl.json @@ -66,6 +66,7 @@ "import.noExe": "nie znaleziono pliku .exe w wybranym folderze", "import.noLinuxExe": "nie znaleziono uruchamialnego programu linuksowego w wybranym folderze (binarka ELF, .AppImage lub .desktop)", "import.prefixRoot": "ten folder to prefiks wine (lub jego dysk C:) - zaimportuj aplikację z wnętrza jego drive_c", + "import.copyIncomplete": "nie udało się skopiować niektórych plików - nic nie zaimportowano, folder źródłowy pozostał bez zmian", "config.title": "Konfiguracja aplikacji", "config.icon.auto": "Wyciągnij z exe", "config.icon.autoLinux": "Wyciągnij ikonę", @@ -93,10 +94,15 @@ "config.openData": "Otwórz folder danych", "config.linuxKindValue": "Linux", "config.isolation": "Izolacja", - "config.isolation.auto": "Automatyczna (najmocniejsza dostępna)", - "config.isolation.off": "Wyłączona (zwykłe uruchomienie)", - "config.isolation.require": "Wymagana (odmów bez bwrap)", - "config.isolation.bwrap": "bwrap {0} (mocna)", + "config.isolation.auto": "Automatyczna", + "config.isolation.none": "None", + "config.isolation.relaxed": "Relaxed", + "config.isolation.isolated": "Isolated", + "config.isolationHint.auto": "Relaxed, gdy bubblewrap działa; na maszynie bez bwrap aplikacja uruchamia bez izolacji.", + "config.isolationHint.none": "Bez sandboxa: aplikacja widzi i może zmienić wszystko, do czego ma prawo Twój użytkownik.", + "config.isolationHint.relaxed": "Cały dysk podmontowany zapisywalnie jako /tmp/plwl-fs-root.", + "config.isolationHint.isolated": "System tylko do odczytu.", + "config.isolation.bwrap": "bwrap {0} (dostępny)", "config.isolation.env": "brak sandboxa: {0}", "config.forceX11": "Wymuś X11 (XWayland)", "config.forceX11Hint": "Uruchamia aplikację przez XWayland zamiast Waylanda. Przydatne, gdy okno nie potrafi mieć własnej ikony albo źle działa na Waylandzie.", @@ -109,7 +115,7 @@ "config.overrides.remove": "Usuń", "config.overrides.hint": "Nazwy modułów Wine, np. dinput8. native,builtin (domyślne) wczytuje DLL dołączony do gry, a gdy go nie ma — wbudowany Wine; disabled blokuje moduł.", "sandbox.title": "Izolacja aplikacji Linux", - "sandbox.hint": "Natywne aplikacje zawsze działają z przekierowanym folderem domowym. Z bubblewrap dostają dodatkowo własne przestrzenie nazw: zapisywać można tylko w swoim folderze domowym i w swoim folderze aplikacji, reszta systemu jest tylko do odczytu.", + "sandbox.hint": "Natywne aplikacje zawsze działają z przekierowanym folderem domowym - ich config i cache zostają w prefiksie. Poziom izolacji mówi, co jeszcze dostają: None to brak sandboxa, Relaxed daje cały dysk zapisywalny, a Isolated nie pozwala zapisać niczego poza folderem aplikacji i kopiuje otwierane pliki do jej folderu domowego.", "sandbox.status": "Status", "sandbox.check": "Sprawdź ponownie", "sandbox.rechecked": "Sprawdzono izolację ponownie", @@ -118,13 +124,17 @@ "sandbox.reason.timeout": "nie odpowiada", "sandbox.reason.failed": "nie działa", "sandbox.warnTitle": "Brak sandboxa dla aplikacji Linux", - "sandbox.warnBody": "bubblewrap {0}. Aplikacje linuksowe będą działać tylko z przekierowanym folderem domowym - nadal mogą czytać resztę systemu i pisać wszędzie, gdzie pozwala Twój użytkownik.", + "sandbox.warnBody": "bubblewrap {0}. Aplikacje ustawione na Automatyczną uruchomią się jak zwykłe programy (None), a te ustawione jawnie na Relaxed albo Isolated odmówią startu, zamiast udawać, że sandbox działa.", "sandbox.dismiss": "Rozumiem", - "sandbox.badgeStrong": "bwrap", - "sandbox.badgeWeak": "bez sandboxa", - "sandbox.badgeOff": "izolacja wyłączona", - "sandbox.badgeRequired": "wymaga bwrap", + "sandbox.badgeNone": "Bez izolacji", + "sandbox.badgeRelaxed": "Relaxed", + "sandbox.badgeIsolated": "Isolated", + "sandbox.badgeRequired": "Wymaga bwrap", + "handoff.copying": "Kopiowanie do aplikacji: {0}", + "handoff.copyNote": "{0} / {1} - aplikacja pracuje na kopii w swoim folderze domowym (plwl-handoff); zmiany w kopii nie wracają do oryginału.", + "handoff.failed": "Nie udało się skopiować {0} do aplikacji: {1}", "sandbox.required": "Ta aplikacja wymaga działającego sandboxa bubblewrap: {0}", + "sandbox.linkOpener": "PLWL - otwieranie linków", "config.save": "Zapisz zmiany", "config.shortcut": "Utwórz skrót", "config.shortcutCreated": "Skrót dla {0} utworzony (menu + pulpit)", @@ -245,8 +255,8 @@ "lansync.prefixes": "Prefiksy Wine", "lansync.settings": "Ustawienia (nazwy, konfiguracje i kolejność aplikacji)", "lansync.force": "Wymuś synchronizację wszystkich plików (pomiń sprawdzanie hashy i nadpisz wszystko)", - "lansync.mirrorWarning": "To urządzenie jest źródłem prawdy: na drugim urządzeniu pliki i elementy, których tu nie ma, zostaną usunięte.", - "lansync.incomingMirror": "Drugie urządzenie jest źródłem prawdy: pliki i elementy na tym urządzeniu, których tam nie ma, zostaną usunięte.", + "lansync.mirrorWarning": "Zaznaczone elementy będą na drugim urządzeniu dokładnie takie jak tutaj. Niczego poza wyborem nie usuwamy, a listę usunięć zatwierdzisz na drugim urządzeniu.", + "lansync.incomingMirror": "Drugie urządzenie jest źródłem prawdy dla zaznaczonych elementów. Listę plików do usunięcia zatwierdzisz przed końcem synchronizacji.", "lansync.start": "Rozpocznij synchronizację", "lansync.progress": "Synchronizowanie na {0}…", "lansync.waiting": "Oczekiwanie na drugie urządzenie…", @@ -257,7 +267,8 @@ "lansync.phase.copy": "Wysyłanie {0}", "lansync.recvPhase.copy": "Odbieranie {0}", "lansync.phase.registry": "Aktualizowanie biblioteki", - "lansync.phase.commit": "Usuwanie zbędnych plików", + "lansync.phase.commit": "Sprawdzanie zbędnych plików", + "lansync.phase.review": "Czekanie na potwierdzenie usunięć", "lansync.phase.done": "Kończenie", "lansync.progressFiles": "{0} / {1} plików", "lansync.progressBytes": "{0} / {1} przesłane", @@ -278,6 +289,33 @@ "lansync.unknownDevice": "Nieznane urządzenie", "lansync.recvIdle": "Drugie urządzenie przestało odpowiadać, synchronizacja została przerwana.", "lansync.done": "Zsynchronizowano na {0}: wysłano {1} ({4}), aktualnych {2}, usunięto {3}", + "lansync.summaryTitle": "Synchronizacja zakończona", + "lansync.summarySentTo": "Wysłano do {0}", + "lansync.summaryReceivedFrom": "Odebrano od {0}", + "lansync.summaryApps": "Aplikacje", + "lansync.summarySettings": "Ustawienia", + "lansync.summarySent": "Wysłane pliki", + "lansync.summaryReceived": "Odebrane pliki", + "lansync.summarySkipped": "Niezmienione pliki", + "lansync.summaryDeleted": "Usunięte", + "lansync.summaryTransferred": "Przesłano", + "lansync.summarySize": "Rozmiar zsynchronizowanych danych", + "lansync.summaryKept": "Zachowane przez drugie urządzenie", + "lansync.pick": "Wybierz", + "lansync.pickCount": "Wybierz ({0}/{1})", + "lansync.pickSearch": "Szukaj", + "lansync.pickAll": "Zaznacz wszystko", + "lansync.pickNone": "Odznacz wszystko", + "lansync.prefixLeftBehind": "Prefiks {0} nie jest zaznaczony — folder tej aplikacji nie zostanie przesłany.", + "lansync.reviewTitle": "Przegląd usunięć", + "lansync.reviewFrom": "Odebrano od {0}. Przed usunięciem przejrzyj listę.", + "lansync.reviewText": "Do usunięcia: {0} plików ({1}). Odznacz to, co ma zostać.", + "lansync.reviewOverwrite": "Pliki istniejące po obu stronach zostaną nadpisane wersją z drugiego urządzenia. Jeśli grasz na obu komputerach, wyłącz ten prefiks z synchronizacji.", + "lansync.reviewKeepAll": "Zachowaj wszystko", + "lansync.reviewDelete": "Usuń {0} plików ({1})", + "lansync.reviewDeleting": "Usuwanie…", + "lansync.reviewFiles": "{0} plików · {1}", + "lansync.summaryYes": "tak", "lansync.failed": "Synchronizacja nie powiodła się: {0}", "lansync.badCode": "Błędny kod synchronizacji. Wpisz kod pokazany na drugim urządzeniu.", "lansync.busy": "Drugie urządzenie jest zajęte (inna synchronizacja lub uruchomiona aplikacja).", @@ -287,6 +325,8 @@ "lansync.idRerolled": "Wygenerowano nowe ID urządzenia", "lansync.codeRerolled": "Wygenerowano nowy kod synchronizacji", "lansync.unknownError": "nieznany błąd", + "lansync.oldPeer": "Drugie urządzenie ma starszą wersję PLWL. Zaktualizuj je — bez przeglądu usunięć ta synchronizacja nie jest bezpieczna.", + "lansync.reviewExpired": "Przegląd usunięć wygasł i nic nie zostało usunięte.", "openwith.title": "Otwórz przez Wine", "openwith.file": "Plik", "openwith.fileMissing": "Ten plik już nie istnieje (albo nie jest plikiem wykonywalnym Windows).", diff --git a/package.json b/package.json index 6cfb479..89f4169 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "PLWL", "productName": "PLWL", - "version": "0.5.0", + "version": "0.5.4", "description": "Portable Linux Wine Launcher", "main": "src/main.js", "scripts": { diff --git a/renderer/app.js b/renderer/app.js index 108108c..0711357 100644 --- a/renderer/app.js +++ b/renderer/app.js @@ -138,6 +138,8 @@ function settleModal(value) { function showModal(html, opts) { modalLocked = !!(opts && opts.locked) + // a review list needs the room a narrow form does not + qs('#modal').classList.toggle('wide', !!(opts && opts.wide)) settleModal(null) if (modalTeardownTimer) { clearTimeout(modalTeardownTimer) @@ -206,7 +208,7 @@ function closeModal() { modalSwapTimer = null } overlay.style.display = 'none' - modal.classList.remove('closing', 'swapping', 'resizing') + modal.classList.remove('closing', 'swapping', 'resizing', 'wide') modal.style.height = '' modal.innerHTML = '' modalLocked = false @@ -335,11 +337,24 @@ class CustomSelect { if (this.disabled) return const wasOpen = this.host.classList.contains('open') CustomSelect.closeAll() - if (!wasOpen) this.host.classList.add('open') + if (!wasOpen) { + this.host.classList.add('open') + this.lift() + } + } + + // the transform on every element (see style.css) makes each one its own + // stacking context, so an ancestor wrapper would still paint the open list + // under the rows that follow it; positioned ancestors already stack right + lift() { + for (let el = this.host.parentElement; el && el !== document.body; el = el.parentElement) { + if (getComputedStyle(el).position === 'static') el.classList.add('select-lift') + } } close() { this.host.classList.remove('open') + CustomSelect.unlift() } setValue(v) { @@ -358,6 +373,11 @@ class CustomSelect { static closeAll() { qsa('.custom-select.open').forEach(el => el.classList.remove('open')) + CustomSelect.unlift() + } + + static unlift() { + qsa('.select-lift').forEach(el => el.classList.remove('select-lift')) } } @@ -434,12 +454,21 @@ function isolationStatusText(status) { return t('config.isolation.env', t('sandbox.reason.' + (status.reason || 'failed'))) } -function isolationBadge(game) { +// The badge names the level the app would really run at, not the policy: +// automatic is a choice, and what it resolves to depends on this machine. +function isolationLevel(game) { const policy = (game && game.isolation) || 'auto' - if (policy === 'off') return `${t('sandbox.badgeOff')}` - if (sandboxStrong()) return `${t('sandbox.badgeStrong')}` - if (policy === 'require') return `${t('sandbox.badgeRequired')}` - return `${t('sandbox.badgeWeak')}` + if (policy === 'none') return 'none' + if (policy === 'auto') return sandboxStrong() ? 'relaxed' : 'none' + return sandboxStrong() ? policy : 'unavailable' +} + +function isolationBadge(game) { + const level = isolationLevel(game) + if (level === 'none') return `${t('sandbox.badgeNone')}` + if (level === 'unavailable') return `${t('sandbox.badgeRequired')}` + if (level === 'isolated') return `${t('sandbox.badgeIsolated')}` + return `${t('sandbox.badgeRelaxed')}` } // Portable apps show files/-relative paths; external apps keep absolute ones. @@ -629,7 +658,8 @@ function renderLibrary() { applyRunning(false) } card.querySelector('[data-act=config]').onclick = () => openGameConfig(game.id) - card.querySelector('[data-act=folder]').onclick = () => window.plwl.shellOpenPath(game.workdir) + // the app's own folder, not its working directory + card.querySelector('[data-act=folder]').onclick = () => window.plwl.shellOpenPath(game.path || game.workdir) card.querySelector('[data-act=remove]').onclick = async () => { const note = game.mode === 'copy' || game.mode === 'move' ? t('library.removeFilesNote') @@ -791,6 +821,17 @@ async function startPrefixImportFlow() { } } +// One place for the technical error tokens the import handlers answer with. +function importErrorText(raw) { + if (raw === 'no-exe-found') return t('import.noExe') + if (raw === 'no-linux-exe') return t('import.noLinuxExe') + if (raw === 'prefix-root') return t('import.prefixRoot') + if (raw === 'no-drive-c') return t('import.prefix.noDriveC') + if (raw === 'outside-drive-c') return t('import.prefix.outside') + if (raw === 'copy-incomplete') return t('import.copyIncomplete') + return raw || '' +} + async function doImport(srcDir, mode, kind) { const name = srcDir.split('/').filter(Boolean).pop() const modal = showModal(` @@ -815,13 +856,7 @@ async function doImport(srcDir, mode, kind) { const game = await window.plwl.gamesImport(srcDir, mode, kind) closeModal() if (!game || game.ok === false) { - const raw = (game && game.error) || '' - const errText = - raw === 'no-exe-found' ? t('import.noExe') - : raw === 'no-linux-exe' ? t('import.noLinuxExe') - : raw === 'prefix-root' ? t('import.prefixRoot') - : (raw || 'unknown error') - toast(t('import.failed', errText), 'error') + toast(t('import.failed', importErrorText((game && game.error) || '')), 'error') return } state.games = await window.plwl.gamesList() @@ -936,6 +971,36 @@ function wireOpenWith() { window.plwl.openwithTake().then(handleOpenWith) } +// --- isolated hand-off ------------------------------------------------------- + +// A document handed to an isolated app is copied in first. Only copies big +// enough to be noticed arrive here (main decides, and puts a window up so this +// popup can be seen at all). +function wireHandoffProgress() { + window.plwl.onHandoffProgress(data => { + if (!data || !data.notice) return + if (data.phase === 'copy') return showHandoffCopy(data) + if (data.phase !== 'done' && data.phase !== 'error') return + // only ever close our own modal: another one may have opened over it + if (qs('#modal').querySelector('#ho-progress')) closeModal() + if (data.phase === 'error') toast(t('handoff.failed', data.name, data.error || ''), 'error') + }) +} + +function showHandoffCopy(data) { + const modal = qs('#modal').querySelector('#ho-progress') + ? qs('#modal') + : showModal(` +

${t('handoff.copying', data.name)}

+
+

+ `) + renderProgressBar(modal.querySelector('#ho-progress'), data.bytes, data.totalBytes) + const pct = modal.querySelector('.progress-pct') + pct.textContent = data.totalBytes ? Math.round(((data.bytes || 0) / data.totalBytes) * 100) + '%' : '' + modal.querySelector('#ho-status').textContent = t('handoff.copyNote', formatBytes(data.bytes), formatBytes(data.totalBytes)) +} + // Import step 2: register the app in place, nothing is copied. async function doPrefixImport(prefix, srcDir) { const name = srcDir.split('/').filter(Boolean).pop() @@ -948,13 +1013,7 @@ async function doPrefixImport(prefix, srcDir) { const game = await window.plwl.gamesImportFromPrefix(prefix, srcDir) closeModal() if (!game || game.ok === false) { - const raw = (game && game.error) || '' - const errText = - raw === 'no-exe-found' ? t('import.noExe') - : raw === 'no-drive-c' ? t('import.prefix.noDriveC') - : raw === 'outside-drive-c' ? t('import.prefix.outside') - : (raw || 'unknown error') - toast(t('import.failed', errText), 'error') + toast(t('import.failed', importErrorText((game && game.error) || '')), 'error') return } state.games = await window.plwl.gamesList() @@ -1314,14 +1373,24 @@ async function openGameConfig(id) { const isolationOptions = () => [ { value: 'auto', label: t('config.isolation.auto') }, - { value: 'off', label: t('config.isolation.off') }, - { value: 'require', label: t('config.isolation.require') } + { value: 'none', label: t('config.isolation.none') }, + { value: 'relaxed', label: t('config.isolation.relaxed') }, + { value: 'isolated', label: t('config.isolation.isolated') } ] +// The level names are one word each - what they mean has to be spelled out +// right under the select, because the price of relaxed is not visible anywhere +// else in the UI. +function renderIsolationHint(value) { + qs('#gc-isolation-hint').textContent = t(`config.isolationHint.${value || 'auto'}`) +} + function renderIsolationOptions(selected) { const opts = isolationOptions() - if (!selects['gc-isolation']) selects['gc-isolation'] = new CustomSelect(qs('#gc-isolation'), opts, selected) - else selects['gc-isolation'].update(opts, selected) + if (!selects['gc-isolation']) { + selects['gc-isolation'] = new CustomSelect(qs('#gc-isolation'), opts, selected, renderIsolationHint) + } else selects['gc-isolation'].update(opts, selected) + renderIsolationHint(selected) } async function createAppShortcut() { @@ -1530,10 +1599,10 @@ function renderProgressBar(bar, bytes, totalBytes) { bar.value = Math.min(sent, bar.max) } -// Older peers only send the overall byte totals - then those drive the bar. +// The bar follows the current phase's bytes (a phase starts empty). function barValues(info) { - let bytes = Math.max(0, Number(info.barBytes == null ? info.bytes : info.barBytes) || 0) - let total = Math.max(0, Number(info.barTotalBytes == null ? info.totalBytes : info.barTotalBytes) || 0) + let bytes = Math.max(0, Number(info.barBytes) || 0) + let total = Math.max(0, Number(info.barTotalBytes) || 0) // a provisional total can be smaller than what already moved (it grows as // entries arrive): the bar reads full, never over 100% if (total > 0 && bytes > total) bytes = total @@ -1566,6 +1635,54 @@ async function runWithProgress({ title, action }) { } } +// End-of-sync popup: what moved, what was already there, and how much space +// the synced trees take. A toast is too easy to miss for a transfer that can +// run for minutes. +function showSyncSummary({ from, received, categories, summary }) { + const items = (summary && summary.items) || {} + const cats = new Set(categories || []) + const apps = Math.max(0, Number(items.apps) || 0) + const wines = Math.max(0, Number(items.wines) || 0) + const prefixes = Math.max(0, Number(items.prefixes) || 0) + const files = Math.max(0, Number(summary && summary.uploaded) || 0) + const skipped = Math.max(0, Number(summary && summary.skipped) || 0) + const deleted = Math.max(0, Number(summary && summary.deleted) || 0) + const kept = Math.max(0, Number(summary && summary.kept) || 0) + const bytes = Math.max(0, Number(summary && summary.bytes) || 0) + const sizeBytes = Math.max(0, Number(summary && summary.sizeBytes) || 0) + const rows = [] + const row = (label, value) => rows.push( + `
${label}${value}
` + ) + // a count alone also shows for a peer that did not send its categories + if (apps || cats.has('apps-portable') || cats.has('apps-prefix')) row(t('lansync.summaryApps'), apps) + if (wines || cats.has('wines')) row(t('lansync.wines'), wines) + if (prefixes || cats.has('prefixes')) row(t('lansync.prefixes'), prefixes) + if (cats.has('settings')) row(t('lansync.summarySettings'), t('lansync.summaryYes')) + if (files || skipped || deleted || kept) { + row(t(received ? 'lansync.summaryReceived' : 'lansync.summarySent'), files) + if (skipped) row(t('lansync.summarySkipped'), skipped) + if (deleted) row(t('lansync.summaryDeleted'), deleted) + if (kept) row(t('lansync.summaryKept'), kept) + } + if (bytes) row(t('lansync.summaryTransferred'), formatBytes(bytes)) + if (sizeBytes) row(t('lansync.summarySize'), formatBytes(sizeBytes)) + const modal = showModal(` +

${t('lansync.summaryTitle')}

+

+
${rows.join('')}
+ + `) + // the device name comes off the network: never interpolate it into HTML + modal.querySelector('#ls-summary-from').textContent = t( + received ? 'lansync.summaryReceivedFrom' : 'lansync.summarySentTo', + from || '' + ) + modal.querySelector('#ls-summary-ok').onclick = closeModal +} + // "340 MB / 1.2 GB" once the total is known, otherwise just the moved bytes. function lanBytesLine(bytes, totalBytes) { const sent = formatBytes(bytes) @@ -1645,15 +1762,7 @@ async function openLanSyncModal(device, errorKey) { code.focus() } modal.querySelector('#ls-what-label').textContent = t('lansync.what') - const box = modal.querySelector('#ls-categories') - for (const category of LAN_CATEGORIES) { - const label = document.createElement('label') - label.className = 'check-label' - label.innerHTML = '' - label.querySelector('input').id = 'ls-cat-' + category.id - label.querySelector('span').textContent = t(category.label) - box.appendChild(label) - } + const pickers = await wireLanPickers(modal) modal.querySelector('#ls-force-label').textContent = t('lansync.force') modal.querySelector('#ls-warning').textContent = t('lansync.mirrorWarning') modal.querySelector('#ls-cancel').textContent = t('dialog.cancel') @@ -1668,16 +1777,172 @@ async function openLanSyncModal(device, errorKey) { code.focus() return } - const categories = LAN_CATEGORIES.map(c => c.id).filter(id => modal.querySelector('#ls-cat-' + id).checked) - if (!categories.length) { + const picked = pickers.collect() + if (!picked.categories.length) { toast(t('lansync.noneSelected'), 'error') return } - await runLanSync(device, value, categories, modal.querySelector('#ls-force').checked) + await runLanSync(device, value, picked.categories, modal.querySelector('#ls-force').checked, picked.selection) } } -async function runLanSync(device, code, categories, force) { +// A category's checkbox says "this category travels"; the picker says which of +// its items. Everything starts selected, and a selection only ever narrows what +// is sent - nothing outside it may be deleted on the other side. +async function wireLanPickers(modal) { + const box = modal.querySelector('#ls-categories') + box.innerHTML = '' + let info = { apps: [], wines: [], prefixes: [] } + try { + info = await window.plwl.lansyncItems() + } catch {} + const groups = new Map([ + ['apps-portable', info.apps.filter(app => app.category === 'apps-portable')], + ['apps-prefix', info.apps.filter(app => app.category === 'apps-prefix')], + ['wines', info.wines || []], + ['prefixes', info.prefixes || []], + ['settings', []] + ]) + const chosen = new Map() + for (const [id, list] of groups) chosen.set(id, new Set(list.map(item => item.key))) + const rows = new Map() + + const refreshButton = id => { + const row = rows.get(id) + if (!row || !row.pick) return + const list = groups.get(id) || [] + row.pick.textContent = chosen.get(id).size === list.length + ? t('lansync.pick') + : t('lansync.pickCount', chosen.get(id).size, list.length) + } + + for (const category of LAN_CATEGORIES) { + const list = groups.get(category.id) || [] + const wrapper = document.createElement('div') + wrapper.className = 'lan-cat' + const head = document.createElement('div') + head.className = 'lan-cat-head' + const label = document.createElement('label') + label.className = 'check-label' + label.innerHTML = '' + const input = label.querySelector('input') + input.id = 'ls-cat-' + category.id + label.querySelector('span').textContent = t(category.label) + head.appendChild(label) + const row = { input, list: null, search: null, pick: null } + rows.set(category.id, row) + if (list.length) { + const pick = document.createElement('button') + pick.type = 'button' + pick.className = 'button small' + head.appendChild(pick) + row.pick = pick + const panel = document.createElement('div') + panel.className = 'lan-pick' + panel.hidden = true + const tools = document.createElement('div') + tools.className = 'lan-pick-tools' + if (list.length > 6) { + const search = document.createElement('input') + search.type = 'search' + search.className = 'lan-search' + search.placeholder = t('lansync.pickSearch') + tools.appendChild(search) + row.search = search + search.oninput = () => renderList(category.id) + } + const all = document.createElement('button') + all.type = 'button' + all.className = 'button small' + all.textContent = t('lansync.pickAll') + const none = document.createElement('button') + none.type = 'button' + none.className = 'button small' + none.textContent = t('lansync.pickNone') + tools.appendChild(all) + tools.appendChild(none) + const listEl = document.createElement('div') + listEl.className = 'lan-pick-list' + row.list = listEl + panel.appendChild(tools) + panel.appendChild(listEl) + pick.onclick = () => { + panel.hidden = !panel.hidden + if (!panel.hidden) renderList(category.id) + } + all.onclick = () => { + for (const item of list) chosen.get(category.id).add(item.key) + renderList(category.id) + } + none.onclick = () => { + chosen.get(category.id).clear() + renderList(category.id) + } + wrapper.appendChild(panel) + refreshButton(category.id) + } + wrapper.insertBefore(head, wrapper.firstChild) + box.appendChild(wrapper) + } + + function renderList(id) { + const row = rows.get(id) + if (!row || !row.list) return + const list = groups.get(id) || [] + const set = chosen.get(id) + const query = row.search ? row.search.value.trim().toLowerCase() : '' + row.list.innerHTML = '' + for (const item of list) { + if (query && !String(item.name || '').toLowerCase().includes(query)) continue + const label = document.createElement('label') + label.className = 'check-label lan-item' + label.innerHTML = '' + const input = label.querySelector('input') + input.checked = set.has(item.key) + label.querySelector('span').textContent = item.name + input.onchange = () => { + if (input.checked) set.add(item.key) + else set.delete(item.key) + refreshButton(id) + // a prefix app's own folder travels with its prefix, not with the app + if (id === 'apps-prefix') renderList('apps-prefix') + } + row.list.appendChild(label) + if (id === 'apps-prefix' && input.checked && item.prefix) { + const prefixKey = `prefix:${item.prefix}` + const prefixesOn = rows.get('prefixes').input.checked + if (prefixesOn && !chosen.get('prefixes').has(prefixKey)) { + const hint = document.createElement('p') + hint.className = 'subtitle lan-hint' + hint.textContent = t('lansync.prefixLeftBehind', item.prefix) + row.list.appendChild(hint) + } + } + } + } + + return { + collect() { + const categories = [] + const units = [] + let partial = false + for (const category of LAN_CATEGORIES) { + const input = rows.get(category.id).input + if (!input.checked) continue + const list = groups.get(category.id) || [] + const set = chosen.get(category.id) + // a checked category with nothing ticked inside it sends nothing + if (list.length && !set.size) continue + categories.push(category.id) + for (const item of list) if (set.has(item.key)) units.push(item.key) + if (set.size !== list.length) partial = true + } + return { categories, selection: partial ? { units } : undefined } + } + } +} + +async function runLanSync(device, code, categories, force, selection) { // locked: a running sync is not cancellable by a stray click on the backdrop const modal = showModal(`

@@ -1711,22 +1976,23 @@ async function runLanSync(device, code, categories, force) { }) let res = null try { - res = await window.plwl.lansyncSync({ deviceId: device.id, code, categories, force }) + res = await window.plwl.lansyncSync({ deviceId: device.id, code, categories, force, selection }) } catch (err) { res = { ok: false, error: (err && err.message) || '' } } finally { active = false state.lanPushing = false } - closeModal() if (res && res.ok) { - const summary = res.summary || {} - toast(t('lansync.done', device.name, summary.uploaded || 0, summary.skipped || 0, summary.deleted || 0, formatBytes(summary.bytes || 0)), 'success') + // swap the locked progress popup into the result, not a toast + showSyncSummary({ from: device.name, received: false, categories, summary: res.summary || {} }) await renderLanSync() return } + closeModal() const err = (res && res.error) || '' - if (err === 'bad-code') { + // the server answers a wrong code as 'auth-failed'; both mean "ask again" + if (err === 'bad-code' || err === 'auth-failed') { await window.plwl.lansyncForget(device.id) toast(t('lansync.badCode'), 'error') openLanSyncModal({ ...device, code: '' }, 'lansync.badCode') @@ -1734,9 +2000,10 @@ async function runLanSync(device, code, categories, force) { } const message = err === 'busy' ? t('lansync.busy') - : err === 'offline' ? t('lansync.offline') + : err === 'offline' || err === 'receiver-lost' ? t('lansync.offline') : err === 'rejected' ? t('lansync.rejected') : err === 'incoming-timeout' ? t('lansync.incomingTimedOut') + : err === 'old-peer' ? t('lansync.oldPeer') : (err || t('lansync.unknownError')) toast(t('lansync.failed', message), 'error') } @@ -1810,6 +2077,9 @@ function onLanIncoming(info) { } let receiving = false +// The last apply payload, for the end-of-sync summary (it carries files, +// bytes, skipped files and the total size of the synced trees). +let lastApplied = null // Only the sender's 'done' ends this; a watchdog-closed popup may reopen. let receiveEnded = false let receiveWatchdog = null @@ -1868,12 +2138,32 @@ function armReceiveWatchdog() { function onLanReceiving(info) { if (!info || !info.stage) return if (state.lanPushing) return // our own push owns the (single) popup - if (info.stage === 'start') receiveEnded = false - if (info.stage === 'done') receiveEnded = true + if (info.stage === 'start') { + receiveEnded = false + lastApplied = null + } + if (info.stage === 'done') { + receiveEnded = true + // the review's decision was the last thing on screen: this is its result + if (reviewFlow) { + reviewFlow = false + closeModal() + showReceiveSummary(info) + return + } + // the popup may have been closed by the watchdog: still show the result + // if nothing else owns the modal slot + if (!receiving) { + if (lastApplied && qs('#modal-overlay').style.display === 'none') showReceiveSummary(info) + return + } + } if (!receiving) { // reopen a watchdog-closed popup unless the sync already ended if (receiveEnded) return - if (qs('#modal-overlay').style.display !== 'none') return + // a completion summary underneath gives way to the next sync's progress + const summaryOpen = !!qs('#modal').querySelector('#ls-summary-ok') + if (!summaryOpen && qs('#modal-overlay').style.display !== 'none') return receiving = true const modal = showModal(`

@@ -1912,15 +2202,269 @@ function renderReceiving(info) { parts.stats.textContent = lanStatsLine(info.items, info.itemsDone, info.totals) parts.bytes.textContent = lanBytesLine(info.bytes, info.totalBytes) if (info.stage === 'done') { - // let the totals be read, then close (the library reloads itself) + // hold the finished bar for a moment, then swap it for the summary if (receiveCloseTimer) clearTimeout(receiveCloseTimer) receiveCloseTimer = setTimeout(() => { receiveCloseTimer = null - endReceiving('') - }, 4000) + showReceiveSummary(info) + }, 1200) } } +// Swap the finished progress popup for the result; the library has already +// been reloaded by the apply event. +function showReceiveSummary(info) { + if (receiveWatchdog) { + clearTimeout(receiveWatchdog) + receiveWatchdog = null + } + if (receiveStall) { + clearTimeout(receiveStall) + receiveStall = null + } + if (receiveCloseTimer) { + clearTimeout(receiveCloseTimer) + receiveCloseTimer = null + } + receiving = false + const applied = lastApplied || {} + showSyncSummary({ + from: applied.from || info.from || '', + received: true, + categories: applied.categories || [], + summary: { + uploaded: applied.files ?? info.done, + skipped: applied.skipped || 0, + deleted: applied.deleted ?? info.deleted, + kept: applied.kept ?? 0, + bytes: applied.bytes ?? info.bytes, + sizeBytes: applied.sizeBytes ?? info.sizeBytes, + items: applied.items || info.items || {} + } + }) +} + +// --- the receiver's deletion review ---------------------------------------- + +// Nothing the sender left out is removed before this: the list is planned, the +// user decides, and only then does anything get deleted. +let reviewFlow = false +// matches the receiver's own review timeout: an unanswered list deletes nothing +const REVIEW_WATCHDOG_MS = 10 * 60 * 1000 +let reviewTimer = null + +function clearReviewTimer() { + if (!reviewTimer) return + clearTimeout(reviewTimer) + reviewTimer = null +} + +function onLanReview(info) { + if (!info || !info.id) return + clearReviewTimer() + // the review replaces the receive progress popup and owns the modal slot + if (receiveWatchdog) { + clearTimeout(receiveWatchdog) + receiveWatchdog = null + } + if (receiveStall) { + clearTimeout(receiveStall) + receiveStall = null + } + if (receiveCloseTimer) { + clearTimeout(receiveCloseTimer) + receiveCloseTimer = null + } + receiving = false + // no progress popup may reopen between the decision and the sender's 'done' + receiveEnded = true + reviewFlow = true + reviewTimer = setTimeout(() => { + reviewTimer = null + reviewFlow = false + closeModal() + toast(t('lansync.reviewExpired'), 'error') + }, REVIEW_WATCHDOG_MS) + renderReview(info) +} + +function renderReview(info) { + const units = Array.isArray(info.units) ? info.units : [] + const files = Math.max(0, Number(info.files) || 0) + const bytes = Math.max(0, Number(info.bytes) || 0) + const kept = new Set() + const keptUnits = new Set() + const nodeInfo = new Map() + const modal = showModal(` +

${t('lansync.reviewTitle')}

+

+

+
+

+
+ + +
+ `, { locked: true, wide: true }) + // the device name comes off the network: never interpolate it into HTML + modal.querySelector('#ls-review-from').textContent = t('lansync.reviewFrom', info.name || info.deviceId || '') + modal.querySelector('#ls-review-text').textContent = t('lansync.reviewText', files, formatBytes(bytes)) + modal.querySelector('#ls-review-warning').textContent = t('lansync.reviewOverwrite') + const list = modal.querySelector('#ls-review-list') + const go = modal.querySelector('#ls-review-go') + const keepAll = modal.querySelector('#ls-review-keep') + keepAll.textContent = t('lansync.reviewKeepAll') + + const keptBy = path => [...kept].some(entry => path === entry || path.startsWith(entry + '/')) + const keptChild = path => [...kept].some(entry => entry !== path && entry.startsWith(path + '/')) + + const keptTotals = () => { + let keptFiles = 0 + let keptBytes = 0 + for (const unit of units) { + if (!keptUnits.has(unit.key)) continue + keptFiles += Math.max(0, Number(unit.files) || 0) + keptBytes += Math.max(0, Number(unit.bytes) || 0) + } + for (const path of kept) { + if ([...kept].some(entry => entry !== path && path.startsWith(entry + '/'))) continue + const unit = units.find(entry => (nodeInfo.get(path) || {}).unit === entry.key) + if (unit && keptUnits.has(unit.key)) continue + const node = nodeInfo.get(path) + if (!node) continue + keptFiles += node.files + keptBytes += node.bytes + } + return { files: keptFiles, bytes: keptBytes } + } + + const refresh = () => { + for (const row of modal.querySelectorAll('.lan-node')) { + const input = row.querySelector('input') + const path = row.dataset.path + const unitKept = keptUnits.has(row.dataset.unit) + input.checked = !unitKept && !keptBy(path) + input.indeterminate = input.checked && keptChild(path) + // kept through an ancestor: re-enable that ancestor instead + input.disabled = unitKept || (keptBy(path) && !kept.has(path)) + } + for (const row of modal.querySelectorAll('.lan-review-unit')) { + const input = row.querySelector('input') + const key = row.dataset.key + const unit = units.find(entry => entry.key === key) + input.checked = !keptUnits.has(key) + input.indeterminate = input.checked && [...kept].some(entry => (nodeInfo.get(entry) || {}).unit === key) + row.querySelector('.lan-review-meta').textContent = t('lansync.reviewFiles', unit ? unit.files : 0, formatBytes(unit ? unit.bytes : 0)) + } + const left = keptTotals() + go.textContent = t('lansync.reviewDelete', Math.max(0, files - left.files), formatBytes(Math.max(0, bytes - left.bytes))) + } + + const nodeRow = (node, unitKey, depth) => { + nodeInfo.set(node.path, { files: node.files || 0, bytes: node.bytes || 0, unit: unitKey }) + const row = document.createElement('div') + row.className = 'lan-node' + row.dataset.path = node.path + row.dataset.unit = unitKey + row.style.paddingLeft = `${depth * 18 + 6}px` + row.innerHTML = ` + + + + ` + row.querySelector('.lan-node-name').textContent = node.name + row.querySelector('.lan-node-meta').textContent = t('lansync.reviewFiles', node.files || 0, formatBytes(node.bytes || 0)) + const input = row.querySelector('input') + input.onchange = () => { + if (input.checked) { + kept.delete(node.path) + // keep the descendants' own entries from overriding an ancestor + for (const entry of [...kept]) if (entry.startsWith(node.path + '/')) kept.delete(entry) + } else { + for (const entry of [...kept]) if (entry.startsWith(node.path + '/')) kept.delete(entry) + kept.add(node.path) + } + refresh() + } + const childBox = document.createElement('div') + childBox.className = 'lan-nodes' + childBox.hidden = true + const open = row.querySelector('.lan-node-open') + if (node.hasChildren) { + open.hidden = false + open.textContent = '+' + open.onclick = async () => { + if (!childBox.dataset.loaded) { + childBox.dataset.loaded = '1' + const res = await window.plwl.lansyncReviewTree(info.id, node.path) + for (const child of (res && res.nodes) || []) childBox.appendChild(nodeRow(child, unitKey, depth + 1)) + } + childBox.hidden = !childBox.hidden + open.textContent = childBox.hidden ? '+' : '−' + refresh() + } + } + const wrap = document.createElement('div') + wrap.className = 'lan-node-wrap' + wrap.appendChild(row) + wrap.appendChild(childBox) + return wrap + } + + for (const unit of units) { + const row = document.createElement('div') + row.className = 'lan-review-unit' + row.dataset.key = unit.key + row.innerHTML = ` + + + ` + row.querySelector('.lan-review-name').textContent = unit.label || unit.key + row.querySelector('input').onchange = async event => { + if (event.target.checked) { + keptUnits.delete(unit.key) + for (const entry of [...kept]) if ((nodeInfo.get(entry) || {}).unit === unit.key) kept.delete(entry) + } else { + keptUnits.add(unit.key) + for (const entry of [...kept]) if ((nodeInfo.get(entry) || {}).unit === unit.key) kept.delete(entry) + } + refresh() + } + list.appendChild(row) + const children = document.createElement('div') + children.className = 'lan-nodes' + list.appendChild(children) + // top folders load on first paint; a unit's list is small (collapsed rows) + window.plwl.lansyncReviewTree(info.id, unit.key).then(res => { + for (const node of (res && res.nodes) || []) children.appendChild(nodeRow(node, unit.key, 1)) + refresh() + }) + } + + keepAll.onclick = () => { + for (const unit of units) keptUnits.add(unit.key) + kept.clear() + refresh() + decide() + } + + let deciding = false + const decide = async () => { + if (deciding) return + deciding = true + clearReviewTimer() + go.disabled = true + keepAll.disabled = true + go.textContent = t('lansync.reviewDeleting') + try { + await window.plwl.lansyncReviewDecide(info.id, { keep: [...kept], keepUnits: [...keptUnits] }) + } catch {} + closeModal() + } + go.onclick = decide + refresh() +} + // A received sync changed local files: reload every list (settings included). async function reloadLocalData() { const [wines, prefixes, games, settings] = await Promise.all([ @@ -1946,8 +2490,10 @@ function wireLanSync() { }) window.plwl.onLanSyncReceiving(info => onLanReceiving(info)) window.plwl.onLanSyncIncoming(info => onLanIncoming(info)) + window.plwl.onLanSyncReview(info => onLanReview(info)) window.plwl.onLanSyncApplied(async info => { - toast(t('lansync.applied', info.from || '', info.files || 0, formatBytes(info.bytes || 0)), 'success') + // the summary popup replaces the toast; reload behind it + lastApplied = info await reloadLocalData() }) qs('#ls-reroll-id').addEventListener('click', async () => { @@ -2012,7 +2558,7 @@ function wireEvents() { toast(t('wines.imported', res.path), 'success') state.wines = await window.plwl.winesList() } else { - toast(t('toast.importFailed') + ': ' + (res.error || ''), 'error') + toast(t('import.failed', importErrorText((res && res.error) || '')), 'error') } renderWines() }) @@ -2058,7 +2604,7 @@ function wireEvents() { }) qs('#gc-icon-browse').addEventListener('click', async () => { // start in the app's own folder, where the icon exe most likely lives - const start = absGamePathInput(qs('#gc-workdir').value.trim(), state.currentGame) + const start = state.currentGame.path || absGamePathInput(qs('#gc-workdir').value.trim(), state.currentGame) const p = await window.plwl.dialogPickFile({ properties: ['openFile'], defaultPath: start || window.plwl.FILES_DIR, @@ -2096,6 +2642,7 @@ async function boot() { wireEvents() wireRealtime() wireOpenWith() + wireHandoffProgress() wireLanSync() qs('#loading').remove() qs('#main').style.display = 'flex' diff --git a/renderer/index.html b/renderer/index.html index cb4bea1..4f521cc 100644 --- a/renderer/index.html +++ b/renderer/index.html @@ -206,6 +206,7 @@