Compare commits
3 commits
d4996988d9
...
a2f1f83ee3
| Author | SHA1 | Date | |
|---|---|---|---|
| a2f1f83ee3 | |||
| c3fc5e7dd1 | |||
| e7636afe3d |
21 changed files with 1375 additions and 102 deletions
24
README.md
24
README.md
|
|
@ -1,6 +1,6 @@
|
|||
# PLWL — Portable Linux Wine Launcher
|
||||
|
||||
A portable launcher for Windows games and applications on Linux.
|
||||
A portable launcher for Windows games and applications on Linux — and for native Linux apps, run with their own isolated home (bubblewrap when available).
|
||||
|
||||
## Portable layout
|
||||
|
||||
|
|
@ -9,7 +9,7 @@ Everything the launcher needs lives next to the executable:
|
|||
```
|
||||
./files/
|
||||
wines/ imported Wine / Proton builds
|
||||
wineprefixes/ wine prefixes
|
||||
wineprefixes/ wine prefixes (a native Linux app's data lives in <prefix>/linux_pfx)
|
||||
apps/ imported app folders (optional)
|
||||
data/ launcher config (apps.json, settings.json)
|
||||
translations/ translation files
|
||||
|
|
@ -36,6 +36,26 @@ npm start
|
|||
|
||||
Besides copy/move/leave, an app can be imported **from a prefix**: nothing is copied — paths are stored relative to the prefix, so wine sees the app as installed on `C:\` (registry entries keep working). Plain prefixes (`drive_c` on top) and Proton ones (`pfx/`) both work. The app stays tied to that prefix; removing the entry never deletes prefix files. A prefix can be renamed later — the folder moves and everything stored relative follows. Edits wait for running apps: renaming/deleting a prefix in use (or moving the default away from an app without its own) is refused with the app to close first; deleting a prefix that still has apps is refused too. Imports recreate symlinks (relative when the target belongs to the launcher) and keep permissions, so an imported game runs straight away.
|
||||
|
||||
## Native Linux apps
|
||||
|
||||
The import dialog starts with a choice: **Windows app (Wine / Proton)** or **Linux app (native)** — after that both go through the same copy/move/leave steps.
|
||||
|
||||
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/<prefix>/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.
|
||||
|
||||
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.
|
||||
|
||||
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 `~`.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## "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.
|
||||
|
|
|
|||
|
|
@ -13,7 +13,11 @@ src/ main process (Node/Electron backend)
|
|||
index.js handler registration, icon protocol, dialogs
|
||||
games.js games service: run/stop state, wine resolution, open-with handoff
|
||||
lansync.js LAN sync handlers (identity, devices, re-roll, sync + progress)
|
||||
runner.js spawns wine/proton (env, prefix, playtime, logs)
|
||||
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
|
||||
linuxapp.js native app detection (ELF/AppImage/.desktop) + icon lookup
|
||||
sandbox.js bubblewrap probe (functional, cached) + buildBwrapArgs
|
||||
library.js apps registry (apps.json) + settings + playtime files, plus
|
||||
the "which prefix does this app use" / in-use guards
|
||||
wines.js wine/proton build scan, registry, portable symlink healing
|
||||
|
|
@ -63,10 +67,26 @@ Renderer never touches Node/Electron directly — everything goes through the `w
|
|||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
### 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.
|
||||
- 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/<app>/`, 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`.
|
||||
- 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).
|
||||
|
|
@ -78,6 +98,7 @@ Renderer never touches Node/Electron directly — everything goes through the `w
|
|||
- 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.
|
||||
- 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 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.
|
||||
- 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).
|
||||
|
||||
|
|
@ -108,6 +129,11 @@ 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-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)
|
||||
npm start # click through the flow you touched
|
||||
|
||||
# Repairing / testing a real instance (test/ scripts are gitignored helpers):
|
||||
|
|
|
|||
|
|
@ -34,8 +34,14 @@
|
|||
"library.removeConfirm": "Remove {0} from the launcher?{1}",
|
||||
"library.removeFilesNote": "\nIts imported files in files/apps will also be deleted.",
|
||||
"library.removePrefixNote": "\nFiles stay in the prefix, only the launcher entry is removed.",
|
||||
"library.removeLinuxDataNote": "\nIts files in files/apps are deleted; its data in the prefix is kept.",
|
||||
"library.tools": "Wine tools",
|
||||
"library.reorderHint": "Drag to change the order",
|
||||
"import.kind.title": "What are you importing?",
|
||||
"import.kind.windows": "Windows app (Wine / Proton)",
|
||||
"import.kind.windowsHint": "Runs through wine or proton.",
|
||||
"import.kind.linux": "Linux app (native)",
|
||||
"import.kind.linuxHint": "Runs directly on this system, with its own isolated home folder. Needs an ELF binary, an .AppImage or a .desktop file.",
|
||||
"import.question": "Should the app files be brought into the launcher so it stays portable, or left where they are?",
|
||||
"import.mode.copy": "Copy into launcher (portable)",
|
||||
"import.mode.move": "Move into launcher (portable)",
|
||||
|
|
@ -58,9 +64,11 @@
|
|||
"import.done": "Import finished",
|
||||
"import.failed": "Import failed: {0}",
|
||||
"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",
|
||||
"config.title": "App configuration",
|
||||
"config.icon.auto": "Extract from exe",
|
||||
"config.icon.autoLinux": "Extract icon",
|
||||
"config.icon.browse": "Choose image",
|
||||
"config.icon.remove": "Remove icon",
|
||||
"config.icon.pick": "Choose an icon image",
|
||||
|
|
@ -80,6 +88,18 @@
|
|||
"config.prefixDefault": "Default prefix ({0})",
|
||||
"config.prefixLocked": "This app was imported from a prefix, its prefix cannot be changed",
|
||||
"config.prefixLockedHint": "Pinned to the prefix it was imported from (its paths are stored relative to it)",
|
||||
"config.linuxDataRoot": "Data folder (prefix)",
|
||||
"config.linuxDataRootHint": "A native app keeps its home, config and cache in linux_pfx inside this prefix.",
|
||||
"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.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.",
|
||||
"config.disableUmu": "Disable UMU (launch with wine directly)",
|
||||
"config.disableUmuHint": "Runs the game with the build's own wine binary instead of its umu.exe/steam.exe launcher. This is the closest to a plain wine run.",
|
||||
"config.dllOverrides": "DLL overrides",
|
||||
|
|
@ -88,6 +108,23 @@
|
|||
"config.overrides.setting": "Setting",
|
||||
"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.status": "Status",
|
||||
"sandbox.check": "Check again",
|
||||
"sandbox.rechecked": "Isolation checked again",
|
||||
"sandbox.reason.missing": "not installed",
|
||||
"sandbox.reason.not-permitted": "blocked by the kernel (user namespaces are not permitted here)",
|
||||
"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.dismiss": "Got it",
|
||||
"sandbox.badgeStrong": "bwrap",
|
||||
"sandbox.badgeWeak": "no sandbox",
|
||||
"sandbox.badgeOff": "isolation off",
|
||||
"sandbox.badgeRequired": "bwrap required",
|
||||
"sandbox.required": "This app needs a working bubblewrap sandbox: {0}",
|
||||
"config.save": "Save changes",
|
||||
"config.shortcut": "Create shortcut",
|
||||
"config.shortcutCreated": "Shortcut for {0} created (menu + desktop)",
|
||||
|
|
@ -136,6 +173,13 @@
|
|||
"prefixes.inUse": "Cannot change prefix {0} while an app from it is running: {1}. Close it first.",
|
||||
"prefixes.inUseHint": "An app is running from this prefix right now - close it before renaming.",
|
||||
"prefixes.hasApps": "Cannot delete prefix {0} - these apps still use it: {1}. Point them at another prefix or remove them first.",
|
||||
"prefixes.resetConfig": "Reset Linux config",
|
||||
"prefixes.resetConfigHint": "Deletes the desktop preferences (theme, GTK/Qt, PulseAudio and X11 cookies) PLWL copied from your system into this prefix. They are copied again on the next app start; app data stays.",
|
||||
"prefixes.resetConfigConfirm": "Delete the desktop preferences copied into prefix {0}? The next app start copies them again from your system. App data is left untouched.",
|
||||
"prefixes.resetConfigDone": "Linux config of prefix {0} reset - it is copied again from your system on the next app start.",
|
||||
"prefixes.resetConfigNone": "Nothing to reset in prefix {0} - the desktop preferences are not copied in.",
|
||||
"prefixes.resetConfigBusy": "Cannot reset the Linux config of prefix {0} while an app from it is running: {1}. Close it first.",
|
||||
"prefixes.resetConfigFailed": "Could not reset the Linux config of prefix {0}.",
|
||||
"wines.title": "Wine versions",
|
||||
"wines.subtitle": "You can import your wine/proton builds here. Proton runs fully without Steam.",
|
||||
"wines.system": "System Wine",
|
||||
|
|
|
|||
|
|
@ -34,8 +34,14 @@
|
|||
"library.removeConfirm": "Usunąć {0} z launchera?{1}",
|
||||
"library.removeFilesNote": "\nJej zaimportowane pliki w files/apps również zostaną usunięte.",
|
||||
"library.removePrefixNote": "\nPliki zostają w prefiksie, usuwany jest tylko wpis w launcherze.",
|
||||
"library.removeLinuxDataNote": "\nJej pliki w files/apps zostaną usunięte; dane w prefiksie zostają.",
|
||||
"library.tools": "Narzędzia Wine",
|
||||
"library.reorderHint": "Przeciągnij, aby zmienić kolejność",
|
||||
"import.kind.title": "Co importujesz?",
|
||||
"import.kind.windows": "Aplikacja Windows (Wine / Proton)",
|
||||
"import.kind.windowsHint": "Uruchamiana przez wine albo proton.",
|
||||
"import.kind.linux": "Aplikacja Linux (natywna)",
|
||||
"import.kind.linuxHint": "Uruchamiana bezpośrednio w systemie, z własnym odizolowanym folderem domowym. Wymaga binarki ELF, pliku .AppImage lub .desktop.",
|
||||
"import.question": "Czy pliki aplikacji mają trafić do launchera, aby był przenośny, czy mają zostać tam, gdzie są?",
|
||||
"import.mode.copy": "Skopiuj do launchera (przenośne)",
|
||||
"import.mode.move": "Przenieś do launchera (przenośne)",
|
||||
|
|
@ -58,9 +64,11 @@
|
|||
"import.done": "Import zakończony",
|
||||
"import.failed": "Import nie powiódł się: {0}",
|
||||
"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",
|
||||
"config.title": "Konfiguracja aplikacji",
|
||||
"config.icon.auto": "Wyciągnij z exe",
|
||||
"config.icon.autoLinux": "Wyciągnij ikonę",
|
||||
"config.icon.browse": "Wybierz obrazek",
|
||||
"config.icon.remove": "Usuń ikonę",
|
||||
"config.icon.pick": "Wybierz obrazek ikony",
|
||||
|
|
@ -80,6 +88,18 @@
|
|||
"config.prefixDefault": "Prefiks domyślny ({0})",
|
||||
"config.prefixLocked": "Ta aplikacja została zaimportowana z prefiksu, nie można zmienić jej prefiksu",
|
||||
"config.prefixLockedHint": "Przypięta do prefiksu, z którego została zaimportowana (ścieżki trzymane są względem niego)",
|
||||
"config.linuxDataRoot": "Folder danych (prefiks)",
|
||||
"config.linuxDataRootHint": "Natywna aplikacja trzyma swój home, config i cache w linux_pfx w tym prefiksie.",
|
||||
"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.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.",
|
||||
"config.disableUmu": "Wyłącz UMU (uruchamiaj bezpośrednio wine)",
|
||||
"config.disableUmuHint": "Uruchamia grę bezpośrednio binarką wine z builda, z pominięciem launchera umu.exe/steam.exe. To najbliżej zwykłego uruchomienia wine.",
|
||||
"config.dllOverrides": "Nadpisania DLL",
|
||||
|
|
@ -88,6 +108,23 @@
|
|||
"config.overrides.setting": "Ustawienie",
|
||||
"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.status": "Status",
|
||||
"sandbox.check": "Sprawdź ponownie",
|
||||
"sandbox.rechecked": "Sprawdzono izolację ponownie",
|
||||
"sandbox.reason.missing": "nie jest zainstalowany",
|
||||
"sandbox.reason.not-permitted": "blokowany przez jądro (brak zgody na user namespaces)",
|
||||
"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.dismiss": "Rozumiem",
|
||||
"sandbox.badgeStrong": "bwrap",
|
||||
"sandbox.badgeWeak": "bez sandboxa",
|
||||
"sandbox.badgeOff": "izolacja wyłączona",
|
||||
"sandbox.badgeRequired": "wymaga bwrap",
|
||||
"sandbox.required": "Ta aplikacja wymaga działającego sandboxa bubblewrap: {0}",
|
||||
"config.save": "Zapisz zmiany",
|
||||
"config.shortcut": "Utwórz skrót",
|
||||
"config.shortcutCreated": "Skrót dla {0} utworzony (menu + pulpit)",
|
||||
|
|
@ -136,6 +173,13 @@
|
|||
"prefixes.inUse": "Nie można zmienić prefiksu {0}, gdy działa z niego aplikacja: {1}. Najpierw ją zamknij.",
|
||||
"prefixes.inUseHint": "Właśnie działa aplikacja z tego prefiksu - zamknij ją przed zmianą nazwy.",
|
||||
"prefixes.hasApps": "Nie można usunąć prefiksu {0} - używają go jeszcze aplikacje: {1}. Wskaż im inny prefiks albo usuń je najpierw.",
|
||||
"prefixes.resetConfig": "Resetuj config Linuksa",
|
||||
"prefixes.resetConfigHint": "Usuwa preferencje pulpitu (motyw, GTK/Qt, ciasteczka PulseAudio i X11) skopiowane z systemu do tego prefiksu. Przy następnym starcie apki zostaną skopiowane od nowa; dane aplikacji zostają.",
|
||||
"prefixes.resetConfigConfirm": "Usunąć preferencje pulpitu skopiowane do prefiksu {0}? Przy następnym starcie apki zostaną skopiowane od nowa z systemu. Dane aplikacji pozostaną nietknięte.",
|
||||
"prefixes.resetConfigDone": "Zresetowano config Linuksa prefiksu {0} - przy następnym starcie apki zostanie skopiowany od nowa z systemu.",
|
||||
"prefixes.resetConfigNone": "W prefiksie {0} nie ma nic do zresetowania - preferencje pulpitu nie są tam skopiowane.",
|
||||
"prefixes.resetConfigBusy": "Nie można zresetować configu Linuksa prefiksu {0}, gdy działa z niego aplikacja: {1}. Najpierw ją zamknij.",
|
||||
"prefixes.resetConfigFailed": "Nie udało się zresetować configu Linuksa prefiksu {0}.",
|
||||
"wines.title": "Wersje Wine",
|
||||
"wines.subtitle": "Tutaj możesz zaimportować swoje buildy wine/proton. Proton działa w pełni bez Steama.",
|
||||
"wines.system": "Wine systemowe",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "PLWL",
|
||||
"productName": "PLWL",
|
||||
"version": "0.4.3",
|
||||
"version": "0.5.0",
|
||||
"description": "Portable Linux Wine Launcher",
|
||||
"main": "src/main.js",
|
||||
"scripts": {
|
||||
|
|
|
|||
150
renderer/app.js
150
renderer/app.js
|
|
@ -26,6 +26,7 @@ const state = {
|
|||
prefixes: { default: '', prefixes: [] },
|
||||
games: [],
|
||||
currentGame: null,
|
||||
sandbox: null,
|
||||
lansync: null,
|
||||
// true while this device pushes a sync: it owns the single popup
|
||||
lanPushing: false,
|
||||
|
|
@ -383,18 +384,20 @@ function showView(name) {
|
|||
}
|
||||
|
||||
async function loadAll() {
|
||||
const [langs, settings, wines, prefixes, games] = await Promise.all([
|
||||
const [langs, settings, wines, prefixes, games, sandbox] = await Promise.all([
|
||||
window.plwl.i18nList(),
|
||||
window.plwl.settingsGet(),
|
||||
window.plwl.winesList(),
|
||||
window.plwl.prefixesList(),
|
||||
window.plwl.gamesList()
|
||||
window.plwl.gamesList(),
|
||||
window.plwl.sandboxStatus()
|
||||
])
|
||||
state.langs = langs
|
||||
state.settings = settings
|
||||
state.wines = wines
|
||||
state.prefixes = prefixes
|
||||
state.games = games
|
||||
state.sandbox = sandbox
|
||||
state.lang = settings.language || 'en-us'
|
||||
await loadLangTexts(state.lang)
|
||||
}
|
||||
|
|
@ -416,6 +419,29 @@ function iconUrl(id) {
|
|||
return `plwl-icon://${encodeURIComponent(id)}/icon`
|
||||
}
|
||||
|
||||
// --- native Linux apps ------------------------------------------------------
|
||||
|
||||
const isLinuxGame = game => !!game && game.kind === 'linux'
|
||||
|
||||
function sandboxStrong() {
|
||||
return !!(state.sandbox && state.sandbox.backend === 'bwrap')
|
||||
}
|
||||
|
||||
// "bwrap 0.12.0 (strong)" / "no sandbox: not installed"
|
||||
function isolationStatusText(status) {
|
||||
if (!status) return ''
|
||||
if (status.backend === 'bwrap') return t('config.isolation.bwrap', status.version || '')
|
||||
return t('config.isolation.env', t('sandbox.reason.' + (status.reason || 'failed')))
|
||||
}
|
||||
|
||||
function isolationBadge(game) {
|
||||
const policy = (game && game.isolation) || 'auto'
|
||||
if (policy === 'off') return `<span class="badge">${t('sandbox.badgeOff')}</span>`
|
||||
if (sandboxStrong()) return `<span class="badge primary">${t('sandbox.badgeStrong')}</span>`
|
||||
if (policy === 'require') return `<span class="badge">${t('sandbox.badgeRequired')}</span>`
|
||||
return `<span class="badge">${t('sandbox.badgeWeak')}</span>`
|
||||
}
|
||||
|
||||
// Portable apps show files/-relative paths; external apps keep absolute ones.
|
||||
function displayPath(p) {
|
||||
if (!p) return ''
|
||||
|
|
@ -565,6 +591,7 @@ function renderLibrary() {
|
|||
card.style.animationDelay = `${idx * 0.04}s`
|
||||
const portable = game.mode === 'copy' || game.mode === 'move'
|
||||
const inPrefix = game.importSource === 'prefix'
|
||||
const isLinux = isLinuxGame(game)
|
||||
const sourceBadge = inPrefix
|
||||
? `<span class="badge primary">${t('library.inPrefix')}${game.prefix ? ' · ' + game.prefix : ''}</span>`
|
||||
: `<span class="badge ${portable ? 'primary' : ''}">${portable ? t('library.portable') : t('library.external')}</span>`
|
||||
|
|
@ -573,7 +600,8 @@ function renderLibrary() {
|
|||
<h3 title=""></h3>
|
||||
<div class="meta">
|
||||
${sourceBadge}
|
||||
<span class="badge">${wineLabel(game.wine)}</span>
|
||||
${isLinux ? `<span class="badge">${t('config.linuxKindValue')}</span>` : `<span class="badge">${wineLabel(game.wine)}</span>`}
|
||||
${isLinux ? isolationBadge(game) : ''}
|
||||
</div>
|
||||
<div class="meta">${t('library.lastPlayed', last)}</div>
|
||||
<div class="meta">${t('library.playtime', fmtPlaytime(game.playSeconds || 0))}</div>
|
||||
|
|
@ -605,7 +633,7 @@ function renderLibrary() {
|
|||
card.querySelector('[data-act=remove]').onclick = async () => {
|
||||
const note = game.mode === 'copy' || game.mode === 'move'
|
||||
? t('library.removeFilesNote')
|
||||
: (inPrefix ? t('library.removePrefixNote') : '')
|
||||
: (inPrefix ? t('library.removePrefixNote') : (isLinux ? t('library.removeLinuxDataNote') : ''))
|
||||
const ok = await confirmModal(t('library.removeConfirm', game.name, note), t('library.remove'))
|
||||
if (!ok) return
|
||||
// portable apps delete their folder too - show how far that got
|
||||
|
|
@ -633,6 +661,9 @@ async function playGame(game) {
|
|||
const entry = runningCards.get(game.id)
|
||||
if (entry) entry.applyRunning(true)
|
||||
toast(t('library.running'), 'error')
|
||||
} else if (res.error === 'sandbox-required') {
|
||||
const reason = t('sandbox.reason.' + ((state.sandbox && state.sandbox.reason) || 'failed'))
|
||||
toast(t('sandbox.required', reason), 'error')
|
||||
} else {
|
||||
toast(t('toast.startFailed', game.name, res.error || ''), 'error')
|
||||
}
|
||||
|
|
@ -666,7 +697,34 @@ function wireRealtime() {
|
|||
}, 15000)
|
||||
}
|
||||
|
||||
// Step 0: Windows or native Linux? Everything after this is the same flow.
|
||||
async function startImportFlow() {
|
||||
const modal = showModal(`
|
||||
<h2>${t('library.import')}</h2>
|
||||
<p>${t('import.kind.title')}</p>
|
||||
<div class="mode-buttons">
|
||||
<button class="button" data-kind="windows">${t('import.kind.windows')}</button>
|
||||
<p class="subtitle">${t('import.kind.windowsHint')}</p>
|
||||
<button class="button" data-kind="linux">${t('import.kind.linux')}</button>
|
||||
<p class="subtitle">${t('import.kind.linuxHint')}</p>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="button" id="modal-cancel">${t('dialog.cancel')}</button>
|
||||
</div>
|
||||
`)
|
||||
modal.querySelector('#modal-cancel').onclick = closeModal
|
||||
modal.querySelectorAll('[data-kind]').forEach(btn => {
|
||||
btn.onclick = () => {
|
||||
const kind = btn.dataset.kind
|
||||
closeModal()
|
||||
startModeFlow(kind)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Step 1: same question as before; only Windows apps can come from a prefix.
|
||||
async function startModeFlow(kind) {
|
||||
const fromPrefix = kind !== 'linux'
|
||||
const modal = showModal(`
|
||||
<h2>${t('library.import')}</h2>
|
||||
<p>${t('import.question')}</p>
|
||||
|
|
@ -674,7 +732,7 @@ async function startImportFlow() {
|
|||
<button class="button" data-mode="copy">${t('import.mode.copy')}</button>
|
||||
<button class="button" data-mode="move">${t('import.mode.move')}</button>
|
||||
<button class="button" data-mode="leave">${t('import.mode.leave')}</button>
|
||||
<button class="button" data-mode="prefix">${t('import.mode.prefix')}</button>
|
||||
${fromPrefix ? `<button class="button" data-mode="prefix">${t('import.mode.prefix')}</button>` : ''}
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="button" id="modal-cancel">${t('dialog.cancel')}</button>
|
||||
|
|
@ -688,7 +746,7 @@ async function startImportFlow() {
|
|||
if (mode === 'prefix') return startPrefixImportFlow()
|
||||
const srcDir = await window.plwl.gamesPickFolder()
|
||||
if (!srcDir) return
|
||||
await doImport(srcDir, mode)
|
||||
await doImport(srcDir, mode, kind)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -733,7 +791,7 @@ async function startPrefixImportFlow() {
|
|||
}
|
||||
}
|
||||
|
||||
async function doImport(srcDir, mode) {
|
||||
async function doImport(srcDir, mode, kind) {
|
||||
const name = srcDir.split('/').filter(Boolean).pop()
|
||||
const modal = showModal(`
|
||||
<h2>${t('import.progress', name)}</h2>
|
||||
|
|
@ -754,12 +812,13 @@ async function doImport(srcDir, mode) {
|
|||
if (status) status.textContent = t('import.fileDone', (data && data.files) || count)
|
||||
})
|
||||
try {
|
||||
const game = await window.plwl.gamesImport(srcDir, mode)
|
||||
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')
|
||||
|
|
@ -939,6 +998,7 @@ function renderPrefixes() {
|
|||
<div class="actions">
|
||||
${locked ? '' : '<button class="button small" data-act="rename"></button>'}
|
||||
<button class="button small" data-act="default" ${p.name === defs.default ? 'style="display:none"' : ''}></button>
|
||||
<button class="button small" data-act="reset"></button>
|
||||
<button class="button small danger" data-act="delete" ${locked ? 'style="display:none"' : ''}></button>
|
||||
</div>
|
||||
`
|
||||
|
|
@ -984,6 +1044,21 @@ function renderPrefixes() {
|
|||
state.prefixes = await window.plwl.prefixesList()
|
||||
renderPrefixes()
|
||||
}
|
||||
const resetBtn = row.querySelector('[data-act=reset]')
|
||||
resetBtn.textContent = t('prefixes.resetConfig')
|
||||
resetBtn.title = t('prefixes.resetConfigHint')
|
||||
resetBtn.onclick = async () => {
|
||||
const ok = await confirmModal(t('prefixes.resetConfigConfirm', p.name), t('prefixes.resetConfig'))
|
||||
if (!ok) return
|
||||
const res = await window.plwl.prefixesResetLinuxConfig(p.name)
|
||||
if (!res || !res.ok) {
|
||||
if (res && res.error === 'inUse') toast(t('prefixes.resetConfigBusy', p.name, (res.apps || []).join(', ')), 'error')
|
||||
else toast(t('prefixes.resetConfigFailed', p.name), 'error')
|
||||
return
|
||||
}
|
||||
if (res.removed && res.removed.length) toast(t('prefixes.resetConfigDone', p.name), 'success')
|
||||
else toast(t('prefixes.resetConfigNone', p.name), 'success')
|
||||
}
|
||||
const delBtn = row.querySelector('[data-act=delete]')
|
||||
delBtn.innerHTML = `${ICONS.trash()}<span>${t('prefixes.delete')}</span>`
|
||||
delBtn.onclick = async () => {
|
||||
|
|
@ -1109,6 +1184,32 @@ function renderSettings() {
|
|||
selects['set-wine'].update(state.wines.map(w => ({ value: w.id, label: w.label })), state.settings.defaultWine || 'system')
|
||||
selects['set-prefix'].update(state.prefixes.prefixes.map(p => ({ value: p.name, label: p.name })), state.prefixes.default)
|
||||
qs('#set-closetotray').checked = state.settings.closeToTray !== false
|
||||
qs('#set-sandbox-status').textContent = isolationStatusText(state.sandbox) || '…'
|
||||
}
|
||||
|
||||
async function recheckSandbox() {
|
||||
state.sandbox = await window.plwl.sandboxProbe()
|
||||
if (state.currentView === 'settings') renderSettings()
|
||||
if (state.currentView === 'library') renderLibrary()
|
||||
toast(t('sandbox.rechecked'), 'success')
|
||||
}
|
||||
|
||||
// A silent downgrade is the worst outcome, so say it once per install.
|
||||
function warnSandboxOnce() {
|
||||
const status = state.sandbox
|
||||
if (!status || status.backend === 'bwrap') return
|
||||
if (state.settings && state.settings.sandboxNotifySeen) return
|
||||
const modal = showModal(`
|
||||
<h2>${t('sandbox.warnTitle')}</h2>
|
||||
<p>${t('sandbox.warnBody', t('sandbox.reason.' + (status.reason || 'failed')))}</p>
|
||||
<div class="modal-actions">
|
||||
<button class="button primary" id="sandbox-warn-ok">${t('sandbox.dismiss')}</button>
|
||||
</div>
|
||||
`)
|
||||
modal.querySelector('#sandbox-warn-ok').onclick = async () => {
|
||||
closeModal()
|
||||
state.settings = await window.plwl.settingsSet({ sandboxNotifySeen: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSettings() {
|
||||
|
|
@ -1199,6 +1300,28 @@ async function openGameConfig(id) {
|
|||
renderOverrides(game.dllOverrides || [])
|
||||
qs('#gc-disable-umu').checked = !!game.disableUmu
|
||||
renderTools()
|
||||
// a native app has no wine, no proton launcher and no Wine tools
|
||||
const isLinux = isLinuxGame(game)
|
||||
qsa('.win-only').forEach(el => { el.style.display = isLinux ? 'none' : '' })
|
||||
qsa('.linux-only').forEach(el => { el.style.display = isLinux ? '' : 'none' })
|
||||
qs('#gc-icon-auto').textContent = t(isLinux ? 'config.icon.autoLinux' : 'config.icon.auto')
|
||||
if (isLinux) {
|
||||
renderIsolationOptions(game.isolation || 'auto')
|
||||
qs('#gc-isolation-status').textContent = isolationStatusText(state.sandbox)
|
||||
qs('#gc-force-x11').checked = !!game.forceX11
|
||||
}
|
||||
}
|
||||
|
||||
const isolationOptions = () => [
|
||||
{ value: 'auto', label: t('config.isolation.auto') },
|
||||
{ value: 'off', label: t('config.isolation.off') },
|
||||
{ value: 'require', label: t('config.isolation.require') }
|
||||
]
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
async function createAppShortcut() {
|
||||
|
|
@ -1316,6 +1439,10 @@ async function saveGameConfig() {
|
|||
dllOverrides: readOverrides(),
|
||||
disableUmu: qs('#gc-disable-umu').checked
|
||||
}
|
||||
if (isLinuxGame(game)) {
|
||||
patch.isolation = selects['gc-isolation'].value
|
||||
patch.forceX11 = qs('#gc-force-x11').checked
|
||||
}
|
||||
await window.plwl.gamesUpdate(game.id, patch)
|
||||
state.games = await window.plwl.gamesList()
|
||||
// show what was actually stored (split/stripped)
|
||||
|
|
@ -1891,6 +2018,7 @@ function wireEvents() {
|
|||
})
|
||||
qs('#btn-settings-save').addEventListener('click', saveSettings)
|
||||
qs('#btn-open-files').addEventListener('click', () => window.plwl.shellOpenPath(window.plwl.FILES_DIR))
|
||||
|
||||
qs('#btn-clear-hash-cache').addEventListener('click', async () => {
|
||||
const ok = await confirmModal(t('settings.hashCacheClearConfirm'), t('settings.clearHashCache'))
|
||||
if (!ok) return
|
||||
|
|
@ -1899,6 +2027,11 @@ function wireEvents() {
|
|||
})
|
||||
qs('#btn-gc-back').addEventListener('click', () => showView('library'))
|
||||
qs('#btn-gc-save').addEventListener('click', saveGameConfig)
|
||||
qs('#btn-gc-data-folder').addEventListener('click', async () => {
|
||||
const res = await window.plwl.gamesOpenDataFolder(state.currentGame.id)
|
||||
if (!res || !res.ok) toast(String((res && res.error) || ''), 'error')
|
||||
})
|
||||
qs('#btn-sandbox-check').addEventListener('click', recheckSandbox)
|
||||
qs('#btn-gc-shortcut').addEventListener('click', createAppShortcut)
|
||||
qs('#btn-gc-logs').addEventListener('click', showAppLogs)
|
||||
qs('#gc-override-add').addEventListener('click', addOverrideRow)
|
||||
|
|
@ -1967,6 +2100,7 @@ async function boot() {
|
|||
qs('#loading').remove()
|
||||
qs('#main').style.display = 'flex'
|
||||
showView('library')
|
||||
warnSandboxOnce()
|
||||
}
|
||||
|
||||
boot()
|
||||
|
|
|
|||
|
|
@ -110,6 +110,15 @@
|
|||
<button class="button danger" id="btn-clear-hash-cache" data-t="settings.clearHashCache"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-card">
|
||||
<h2 data-t="sandbox.title"></h2>
|
||||
<p class="subtitle" data-t="sandbox.hint"></p>
|
||||
<label class="field-label" data-t="sandbox.status"></label>
|
||||
<p class="subtitle" id="set-sandbox-status"></p>
|
||||
<div class="form-actions">
|
||||
<button class="button" id="btn-sandbox-check" data-t="sandbox.check"></button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="view-lansync" class="view">
|
||||
|
|
@ -180,26 +189,47 @@
|
|||
<label class="field-label" data-t="config.args"></label>
|
||||
<input type="text" id="gc-args" data-ph="config.argsHint">
|
||||
|
||||
<label class="field-label" data-t="config.wine"></label>
|
||||
<span id="gc-wine"></span>
|
||||
<div class="win-only">
|
||||
<label class="field-label" data-t="config.wine"></label>
|
||||
<span id="gc-wine"></span>
|
||||
</div>
|
||||
|
||||
<label class="field-label" data-t="config.prefix"></label>
|
||||
<label class="field-label win-only" data-t="config.prefix"></label>
|
||||
<label class="field-label linux-only" data-t="config.linuxDataRoot" style="display:none"></label>
|
||||
<span id="gc-prefix"></span>
|
||||
<p class="subtitle" id="gc-prefix-lock-hint" data-t="config.prefixLockedHint" style="display:none"></p>
|
||||
<p class="subtitle win-only" id="gc-prefix-lock-hint" data-t="config.prefixLockedHint" style="display:none"></p>
|
||||
<p class="subtitle linux-only" data-t="config.linuxDataRootHint" style="display:none"></p>
|
||||
<div class="linux-only" style="display:none">
|
||||
<button class="button" id="btn-gc-data-folder" data-t="config.openData"></button>
|
||||
</div>
|
||||
|
||||
<label class="check-label">
|
||||
<input type="checkbox" id="gc-disable-umu">
|
||||
<span data-t="config.disableUmu"></span>
|
||||
</label>
|
||||
<p class="subtitle" data-t="config.disableUmuHint"></p>
|
||||
<div class="linux-only" style="display:none">
|
||||
<label class="field-label" data-t="config.isolation"></label>
|
||||
<span id="gc-isolation"></span>
|
||||
<p class="subtitle" id="gc-isolation-status"></p>
|
||||
|
||||
<label class="check-label">
|
||||
<input type="checkbox" id="gc-force-x11">
|
||||
<span data-t="config.forceX11"></span>
|
||||
</label>
|
||||
<p class="subtitle" data-t="config.forceX11Hint"></p>
|
||||
</div>
|
||||
|
||||
<label class="field-label" data-t="config.env"></label>
|
||||
<textarea id="gc-env" rows="3" data-ph="config.envHint"></textarea>
|
||||
|
||||
<label class="field-label" data-t="config.dllOverrides"></label>
|
||||
<div id="gc-overrides" class="overrides"></div>
|
||||
<button class="button" id="gc-override-add" data-t="config.overrides.add"></button>
|
||||
<p class="subtitle" data-t="config.overrides.hint"></p>
|
||||
<div class="win-only">
|
||||
<label class="check-label">
|
||||
<input type="checkbox" id="gc-disable-umu">
|
||||
<span data-t="config.disableUmu"></span>
|
||||
</label>
|
||||
<p class="subtitle" data-t="config.disableUmuHint"></p>
|
||||
|
||||
<label class="field-label" data-t="config.dllOverrides"></label>
|
||||
<div id="gc-overrides" class="overrides"></div>
|
||||
<button class="button" id="gc-override-add" data-t="config.overrides.add"></button>
|
||||
<p class="subtitle" data-t="config.overrides.hint"></p>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button class="button danger" id="btn-gc-clear-playtime" data-t="config.clearPlaytime"></button>
|
||||
|
|
@ -208,7 +238,7 @@
|
|||
<button class="button primary" id="btn-gc-save" data-t="config.save"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-card">
|
||||
<div class="form-card win-only">
|
||||
<h2 data-t="tools.title"></h2>
|
||||
<p class="subtitle" data-t="tools.subtitle"></p>
|
||||
<div class="tools-grid" id="gc-tools"></div>
|
||||
|
|
|
|||
|
|
@ -161,6 +161,44 @@ async function copyTree(src, dst, onProgress) {
|
|||
return { done, bytes }
|
||||
}
|
||||
|
||||
// Imported trees come from media that lose permissions (archives, FAT, a
|
||||
// read-only backup drive), and copyFile keeps whatever the source had: every
|
||||
// node gets owner rwx and `x` mirrored from `r`, so the app can run its own
|
||||
// binaries and write its own files.
|
||||
async function chmodTree(root) {
|
||||
const desired = mode => mode | 0o700 | ((mode & 0o444) >> 2)
|
||||
let files = 0
|
||||
let dirs = 0
|
||||
const walk = async dir => {
|
||||
let entries
|
||||
try {
|
||||
entries = await fsp.readdir(dir, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isSymbolicLink()) continue
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full)
|
||||
} else if (!entry.isFile()) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const before = (await fsp.stat(full)).mode & 0o7777
|
||||
const after = desired(before)
|
||||
if (after !== before) {
|
||||
await fsp.chmod(full, after)
|
||||
if (entry.isDirectory()) dirs++
|
||||
else files++
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
await walk(root)
|
||||
return { files, dirs }
|
||||
}
|
||||
|
||||
// Delete deepest-first with progress through onProgress; symlinks are
|
||||
// unlinked, never followed.
|
||||
async function removeTree(root, onProgress) {
|
||||
|
|
@ -228,5 +266,5 @@ async function removeTree(root, onProgress) {
|
|||
return { files, dirs, bytes }
|
||||
}
|
||||
|
||||
module.exports = { pathExists, dedupeDir, copyTree, treeSize, removeTree, progressGate, mapLimit }
|
||||
module.exports = { pathExists, dedupeDir, copyTree, treeSize, removeTree, chmodTree, progressGate, mapLimit }
|
||||
|
||||
|
|
|
|||
34
src/icons.js
34
src/icons.js
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { desktopFileFor, readDesktopEntry, findIconFile, pngOrSvg } = require('./linuxapp')
|
||||
|
||||
function rvaToOffset(sections, rva) {
|
||||
for (const s of sections) {
|
||||
|
|
@ -208,4 +209,35 @@ function extractIconFromExe(exePath, outPath) {
|
|||
}
|
||||
}
|
||||
|
||||
module.exports = { extractIconFromExe, parseIcons, buildIco }
|
||||
// Native Linux apps carry no icon inside the binary: it comes from the
|
||||
// .desktop entry (Icon=), an image next to the program, or the theme.
|
||||
// `outBase` is a path without extension; the sniffed one is appended.
|
||||
function iconFromLinuxApp(exePath, outBase) {
|
||||
try {
|
||||
const desktop = desktopFileFor(exePath)
|
||||
const entry = desktop ? readDesktopEntry(desktop) : null
|
||||
const baseDir = desktop ? path.dirname(desktop) : path.dirname(exePath)
|
||||
let source = findIconFile(entry && entry.Icon, baseDir)
|
||||
if (!source) {
|
||||
// no .desktop: a same-named image (or the AppImage .DirIcon) next to it
|
||||
const dir = path.dirname(exePath)
|
||||
const stem = path.basename(exePath).replace(/\.(appimage|sh|bin)$/i, '')
|
||||
for (const name of [stem + '.png', stem + '.svg', '.DirIcon', 'icon.png', 'icon.svg']) {
|
||||
const candidate = path.join(dir, name)
|
||||
if (pngOrSvg(candidate)) {
|
||||
source = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!source) return { ok: false, error: 'no-icon' }
|
||||
const outPath = `${outBase}.${pngOrSvg(source)}`
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true })
|
||||
fs.copyFileSync(source, outPath)
|
||||
return { ok: true, path: outPath }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String((err && err.message) || err) }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { extractIconFromExe, iconFromLinuxApp, parseIcons, buildIco }
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ const fsp = fs.promises
|
|||
const path = require('path')
|
||||
const { DIRS, resolvePortablePath } = require('./paths')
|
||||
const { newGame, newGameId, addGame } = require('./library')
|
||||
const { extractIconFromExe } = require('./icons')
|
||||
const { extractIconFromExe, iconFromLinuxApp } = require('./icons')
|
||||
const { findLinuxExe } = require('./linuxapp')
|
||||
const { listPrefixes, prefixDriveRoots, isPrefixRoot } = require('./prefixes')
|
||||
const { rewireSymlinks } = require('./symlinks')
|
||||
const { copyTree, treeSize } = require('./fsutil')
|
||||
const { copyTree, treeSize, chmodTree } = require('./fsutil')
|
||||
|
||||
// Directories that typically hold installers/redistributables, not the game.
|
||||
const SKIPPED_DIRS = new Set(['redist', 'directx', '_commonredist', 'support', 'dotnet', 'vc'])
|
||||
|
|
@ -21,13 +22,16 @@ function moveFolder(src, dst, onProgress) {
|
|||
return fsp.rename(src, dst).catch(fallback)
|
||||
}
|
||||
|
||||
async function importGame(srcDir, mode, onProgress) {
|
||||
async function importGame(srcDir, mode, onProgress, kind = 'windows') {
|
||||
const isLinux = kind === 'linux'
|
||||
// a prefix (or its drive_c/pfx) is not an app folder
|
||||
if (isPrefixRoot(srcDir)) return { ok: false, error: 'prefix-root' }
|
||||
const name = path.basename(srcDir)
|
||||
// validate before touching anything: no .exe -> refuse
|
||||
const preExe = await findDefaultExe(srcDir)
|
||||
if (!preExe) return { ok: false, error: 'no-exe-found' }
|
||||
const finder = isLinux ? findLinuxExe : findDefaultExe
|
||||
const missing = isLinux ? 'no-linux-exe' : 'no-exe-found'
|
||||
// validate before touching anything: no entry point -> refuse
|
||||
const preExe = await finder(srcDir)
|
||||
if (!preExe) return { ok: false, error: missing }
|
||||
// the id doubles as the imported folder name
|
||||
const id = newGameId()
|
||||
let workdir = srcDir
|
||||
|
|
@ -43,21 +47,27 @@ async function importGame(srcDir, mode, onProgress) {
|
|||
await copyTree(srcDir, dst, p => emit('copy', { files: p.done, bytes: p.bytes, totalFiles: total.files, totalBytes: total.bytes }))
|
||||
} else await moveFolder(srcDir, dst, onProgress)
|
||||
workdir = dst
|
||||
// the source's permissions are not the source's truth: an app out of a
|
||||
// read-only or mode-less medium has to become runnable and writable
|
||||
await chmodTree(dst)
|
||||
// in-data link targets become relative, so the import survives a move
|
||||
try {
|
||||
await rewireSymlinks(dst, [DIRS.FILES])
|
||||
} catch {}
|
||||
}
|
||||
const exePath = (await findDefaultExe(workdir)) || preExe
|
||||
const exePath = (await finder(workdir)) || preExe
|
||||
if (!exePath) {
|
||||
return { ok: false, error: 'no-exe-found' }
|
||||
return { ok: false, error: missing }
|
||||
}
|
||||
const game = newGame({ id, name, exePath, workdir, mode })
|
||||
const game = newGame({ id, name, exePath, workdir, mode, kind })
|
||||
game.imported = mode === 'copy' || mode === 'move'
|
||||
// auto-picked exe -> grab its icon; a missing icon is not a failure
|
||||
const icon = path.join(DIRS.DATA, 'icons', id, 'icon.ico')
|
||||
if (extractIconFromExe(resolvePortablePath(exePath), icon).ok) {
|
||||
game.iconSource = icon
|
||||
const iconDir = path.join(DIRS.DATA, 'icons', id)
|
||||
const icon = isLinux
|
||||
? iconFromLinuxApp(resolvePortablePath(exePath), path.join(iconDir, 'icon'))
|
||||
: extractIconFromExe(resolvePortablePath(exePath), path.join(iconDir, 'icon.ico'))
|
||||
if (icon.ok) {
|
||||
game.iconSource = icon.path
|
||||
}
|
||||
return addGame(game)
|
||||
}
|
||||
|
|
@ -140,4 +150,4 @@ async function findDefaultExe(dir) {
|
|||
return best
|
||||
}
|
||||
|
||||
module.exports = { importGame, importGameFromPrefix, findDefaultExe, moveFolder }
|
||||
module.exports = { importGame, importGameFromPrefix, findDefaultExe, findLinuxExe, moveFolder }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
'use strict'
|
||||
|
||||
const { runGame, runTool } = require('../runner')
|
||||
const { runLinuxGame } = require('../linuxrunner')
|
||||
const { importGame, importGameFromPrefix } = require('../importer')
|
||||
const library = require('../library')
|
||||
|
||||
|
|
@ -22,7 +23,7 @@ function sendToWindow(win, channel, data) {
|
|||
// onGamesChanged fires in the main process when the running set changes.
|
||||
const STARTUP_GRACE_MS = 60000
|
||||
|
||||
function createGamesService({ getWindow, onGamesChanged }) {
|
||||
function createGamesService({ getWindow, onGamesChanged, sandbox }) {
|
||||
const running = new Map()
|
||||
const startedAt = new Map()
|
||||
const killRequests = new Set()
|
||||
|
|
@ -91,30 +92,40 @@ function createGamesService({ getWindow, onGamesChanged }) {
|
|||
if (onGameExit) onGameExit(id)
|
||||
}
|
||||
|
||||
// Native Linux apps skip wine entirely; everything else stays the same.
|
||||
function runnerFor(game) {
|
||||
if (!library.isLinuxGame(game)) return null
|
||||
return payload => runLinuxGame({ game, sandbox, ...payload })
|
||||
}
|
||||
|
||||
async function start(win, id, openFile) {
|
||||
const game = library.getGame(id)
|
||||
if (!game) return { ok: false, error: 'game-not-found' }
|
||||
prune()
|
||||
let wine
|
||||
try {
|
||||
wine = resolveWine(game)
|
||||
} catch {
|
||||
return { ok: false, error: 'wine-not-found' }
|
||||
const isLinux = library.isLinuxGame(game)
|
||||
let wine = null
|
||||
if (!isLinux) {
|
||||
try {
|
||||
wine = resolveWine(game)
|
||||
} catch {
|
||||
return { ok: false, error: 'wine-not-found' }
|
||||
}
|
||||
}
|
||||
const run = isLinux ? runnerFor(game) : payload => runGame({ game, wine, systemWine: wine.type === 'system', ...payload })
|
||||
if (running.has(id)) {
|
||||
// a document into a running app is a handoff, not a tracked run
|
||||
if (!openFile) return { ok: false, error: 'already-running' }
|
||||
try {
|
||||
await runGame({ game, wine, systemWine: wine.type === 'system', openFile, handoff: true })
|
||||
await run({ openFile, handoff: true })
|
||||
return { ok: true, pid: null, logFile: null }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String((err && err.message) || err) }
|
||||
}
|
||||
}
|
||||
running.set(id, { pid: null, prefix: library.prefixNameForGame(game), wine: wine.id })
|
||||
running.set(id, { pid: null, prefix: library.prefixNameForGame(game), wine: wine ? wine.id : '' })
|
||||
startedAt.set(id, Date.now())
|
||||
try {
|
||||
const res = await runGame({ game, wine, systemWine: wine.type === 'system', onExit: () => handleExit(id), openFile })
|
||||
const res = await run({ onExit: () => handleExit(id), openFile })
|
||||
// stop requested while still starting: kill and clear
|
||||
if (killRequests.has(id)) {
|
||||
killRequests.delete(id)
|
||||
|
|
@ -158,6 +169,8 @@ function createGamesService({ getWindow, onGamesChanged }) {
|
|||
async function runToolFor(id, tool, args) {
|
||||
const game = library.getGame(id)
|
||||
if (!game) return { ok: false, error: 'game-not-found' }
|
||||
// Wine tools make no sense for a native Linux app
|
||||
if (library.isLinuxGame(game)) return { ok: false, error: 'not-windows' }
|
||||
let wine
|
||||
try {
|
||||
wine = resolveWine(game)
|
||||
|
|
@ -177,8 +190,8 @@ function createGamesService({ getWindow, onGamesChanged }) {
|
|||
onGameExit = typeof fn === 'function' ? fn : null
|
||||
}
|
||||
|
||||
async function importTo(win, srcDir, mode) {
|
||||
return importGame(srcDir, mode, data => sendToWindow(win, 'import:progress', data))
|
||||
async function importTo(win, srcDir, mode, kind) {
|
||||
return importGame(srcDir, mode, data => sendToWindow(win, 'import:progress', data), kind)
|
||||
}
|
||||
|
||||
// prefix import: register in place, nothing copied
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@ const library = require('../library')
|
|||
const wines = require('../wines')
|
||||
const prefixes = require('../prefixes')
|
||||
const runner = require('../runner')
|
||||
const { extractIconFromExe } = require('../icons')
|
||||
const linuxrunner = require('../linuxrunner')
|
||||
const { createSandboxProbe } = require('../sandbox')
|
||||
const { extractIconFromExe, iconFromLinuxApp } = require('../icons')
|
||||
const { createGamesService, sendToWindow } = require('./games')
|
||||
const shortcuts = require('../shortcuts')
|
||||
const openwith = require('../openwith')
|
||||
|
|
@ -34,13 +36,15 @@ function clearIconDir(id, keep) {
|
|||
} catch {}
|
||||
}
|
||||
|
||||
function extractGameIcon(id, exePath) {
|
||||
const out = path.join(iconDir(id), 'icon.ico')
|
||||
const res = extractIconFromExe(exePath, out)
|
||||
function extractGameIcon(id, exePath, kind) {
|
||||
const isLinux = kind === 'linux'
|
||||
// the Linux helper picks the extension itself (png/svg), the PE one is ico
|
||||
const out = path.join(iconDir(id), isLinux ? 'icon' : 'icon.ico')
|
||||
const res = isLinux ? iconFromLinuxApp(exePath, out) : extractIconFromExe(exePath, out)
|
||||
// on failure nothing is cleared, so the previous icon survives a wrong exe
|
||||
if (res.ok) {
|
||||
clearIconDir(id, 'icon.ico')
|
||||
library.updateGame(id, { iconSource: out })
|
||||
clearIconDir(id, path.basename(res.path))
|
||||
library.updateGame(id, { iconSource: res.path })
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
|
@ -48,7 +52,16 @@ function extractGameIcon(id, exePath) {
|
|||
// --- registration -----------------------------------------------------------
|
||||
|
||||
function registerIpc({ getWindow, onGamesChanged }) {
|
||||
const games = createGamesService({ getWindow, onGamesChanged })
|
||||
// one probe per launcher, cached: it decides bwrap vs plain run
|
||||
const sandbox = createSandboxProbe()
|
||||
const games = createGamesService({ getWindow, onGamesChanged, sandbox })
|
||||
|
||||
// sandbox --------------------------------------------------------------------
|
||||
ipcMain.handle('sandbox:status', async () => sandbox.status() || (await sandbox.probe()))
|
||||
ipcMain.handle('sandbox:probe', async () => {
|
||||
sandbox.invalidate()
|
||||
return sandbox.probe()
|
||||
})
|
||||
|
||||
// i18n ---------------------------------------------------------------------
|
||||
ipcMain.handle('i18n:list', async () => {
|
||||
|
|
@ -107,6 +120,12 @@ function registerIpc({ getWindow, onGamesChanged }) {
|
|||
return prefixes.deletePrefix(name, data => sendToWindow(getWindow(), 'import:progress', data))
|
||||
})
|
||||
ipcMain.handle('prefixes:rename', (e, oldName, newName) => prefixInUse(oldName) || prefixes.renamePrefix(oldName, newName))
|
||||
// The seeded desktop config is ours to drop (app data is not a seed), but a
|
||||
// running app would lose the files under its feet.
|
||||
ipcMain.handle('prefixes:resetLinuxConfig', (e, name) => {
|
||||
if (!prefixes.listPrefixes().prefixes.some(p => p.name === name)) return { ok: false, error: 'notFound' }
|
||||
return prefixInUse(name) || linuxrunner.resetSeededConfig(name)
|
||||
})
|
||||
ipcMain.handle('prefixes:setDefault', (e, name) => {
|
||||
// switching the default would silently move apps that follow it
|
||||
const defs = prefixes.listPrefixes()
|
||||
|
|
@ -175,7 +194,7 @@ function registerIpc({ getWindow, onGamesChanged }) {
|
|||
ipcMain.handle('games:extractIcon', (e, id) => {
|
||||
const game = library.getGame(id)
|
||||
if (!game || !game.exePath) return { ok: false, error: 'bad-request' }
|
||||
return extractGameIcon(id, game.exePath)
|
||||
return extractGameIcon(id, game.exePath, game.kind)
|
||||
})
|
||||
// use the exe the field holds (maybe picked but not saved yet)
|
||||
ipcMain.handle('games:autoIcon', (e, id, exePath) => {
|
||||
|
|
@ -183,7 +202,19 @@ function registerIpc({ getWindow, onGamesChanged }) {
|
|||
if (!game) return { ok: false, error: 'bad-request' }
|
||||
const exe = exePath || game.exePath
|
||||
if (!exe) return { ok: false, error: 'bad-request' }
|
||||
return extractGameIcon(id, exe)
|
||||
return extractGameIcon(id, exe, game.kind)
|
||||
})
|
||||
// Linux apps keep their data next to the prefix's Windows side
|
||||
ipcMain.handle('games:openDataFolder', async (e, id) => {
|
||||
const game = library.getGame(id)
|
||||
if (!library.isLinuxGame(game)) return { ok: false, error: 'not-linux' }
|
||||
try {
|
||||
const root = linuxrunner.ensureLinuxPfx(library.prefixNameForGame(game))
|
||||
const err = await shell.openPath(root)
|
||||
return err ? { ok: false, error: err } : { ok: true, path: root }
|
||||
} catch (err) {
|
||||
return errorResult(err)
|
||||
}
|
||||
})
|
||||
|
||||
// "Open with PLWL" ------------------------------------------------------------------
|
||||
|
|
@ -226,9 +257,9 @@ function registerIpc({ getWindow, onGamesChanged }) {
|
|||
})
|
||||
return res.canceled || !res.filePaths[0] ? null : res.filePaths[0]
|
||||
})
|
||||
ipcMain.handle('games:import', async (e, srcDir, mode) => {
|
||||
ipcMain.handle('games:import', async (e, srcDir, mode, kind) => {
|
||||
try {
|
||||
return await games.import(getWindow(), srcDir, mode)
|
||||
return await games.import(getWindow(), srcDir, mode, kind)
|
||||
} catch (err) {
|
||||
return errorResult(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
const path = require('path')
|
||||
const fs = require('fs')
|
||||
const fsp = fs.promises
|
||||
const { isLocalOnlyRel } = require('./prefixes')
|
||||
|
||||
function createManifestBuilder({ filesPath, filesRoot, hash, mapLimit, concurrency }) {
|
||||
// Targets inside the launcher data travel relative (the mirrored layout is
|
||||
|
|
@ -38,6 +39,8 @@ function createManifestBuilder({ filesPath, filesRoot, hash, mapLimit, concurren
|
|||
const leaves = []
|
||||
for (const entry of entries) {
|
||||
const relChild = `${dirRel}/${entry.name}`
|
||||
// native Linux app data never leaves this machine
|
||||
if (isLocalOnlyRel(relChild)) continue
|
||||
if (entry.isDirectory()) {
|
||||
const record = { path: relChild, type: 'dir' }
|
||||
out.push(record)
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ const { createDiscovery } = require('./lansync-discovery')
|
|||
const library = require('./library')
|
||||
const wines = require('./wines')
|
||||
const prefixes = require('./prefixes')
|
||||
const { isPrefixRel } = prefixes
|
||||
const { isPrefixRel, isLocalOnlyRel } = prefixes
|
||||
|
||||
const CONFIG = path.join(DIRS.DATA, 'lansync.json')
|
||||
|
||||
|
|
@ -432,6 +432,8 @@ async function pruneTree(abs, rel, keep) {
|
|||
for (const entry of entries) {
|
||||
const childAbs = path.join(abs, entry.name)
|
||||
const childRel = `${rel}/${entry.name}`
|
||||
// a mirror must not delete this machine's native Linux app data
|
||||
if (isLocalOnlyRel(childRel)) continue
|
||||
if (!keep.has(childRel)) {
|
||||
if (removeAbs(childAbs)) removed++
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -108,6 +108,27 @@ function gamesFollowingDefault(running) {
|
|||
})
|
||||
}
|
||||
|
||||
// Windows is the default: entries written before Linux apps existed have no
|
||||
// kind at all.
|
||||
function isLinuxGame(game) {
|
||||
return !!game && game.kind === 'linux'
|
||||
}
|
||||
|
||||
const ISOLATION_MODES = ['auto', 'off', 'require']
|
||||
|
||||
// Only known values reach the registry; anything else falls back to the safe
|
||||
// default (a typo must not silently disable the sandbox).
|
||||
function sanitizeLinuxPatch(patch) {
|
||||
if (!patch) return patch
|
||||
const out = { ...patch }
|
||||
if (out.kind !== undefined) out.kind = out.kind === 'linux' ? 'linux' : 'windows'
|
||||
if (out.isolation !== undefined) {
|
||||
out.isolation = ISOLATION_MODES.includes(out.isolation) ? out.isolation : 'auto'
|
||||
}
|
||||
if (out.forceX11 !== undefined) out.forceX11 = !!out.forceX11
|
||||
return out
|
||||
}
|
||||
|
||||
function addGame(game) {
|
||||
const games = loadGames()
|
||||
games.push(game)
|
||||
|
|
@ -127,7 +148,7 @@ function updateGame(id, patch) {
|
|||
}
|
||||
// playSeconds lives in its own file; the registry mirrors it
|
||||
if (patch.playSeconds !== undefined) writePlaySeconds(id, patch.playSeconds)
|
||||
Object.assign(g, patch)
|
||||
Object.assign(g, sanitizeLinuxPatch(patch))
|
||||
saveGames(games)
|
||||
return g
|
||||
}
|
||||
|
|
@ -175,11 +196,12 @@ function newGameId() {
|
|||
return id
|
||||
}
|
||||
|
||||
function newGame({ id, name, exePath, workdir, mode }) {
|
||||
function newGame({ id, name, exePath, workdir, mode, kind }) {
|
||||
return {
|
||||
id: id || newGameId(),
|
||||
name,
|
||||
mode,
|
||||
kind: kind === 'linux' ? 'linux' : 'windows',
|
||||
path: workdir,
|
||||
exePath,
|
||||
workdir,
|
||||
|
|
@ -189,6 +211,10 @@ function newGame({ id, name, exePath, workdir, mode }) {
|
|||
dllOverrides: [],
|
||||
// Proton-only: UMU by default, or the build's steam.exe launcher
|
||||
disableUmu: false,
|
||||
// Linux-only: how hard to try the bwrap sandbox before falling back
|
||||
isolation: 'auto',
|
||||
// Linux-only: force XWayland, where a window can still carry its icon
|
||||
forceX11: false,
|
||||
env: {},
|
||||
iconSource: '',
|
||||
playSeconds: 0,
|
||||
|
|
@ -232,4 +258,4 @@ function resolvePrefixDir(game) {
|
|||
return prefixPath(prefixNameForGame(game))
|
||||
}
|
||||
|
||||
module.exports = { loadGames, saveGames, portableGame, getGame, addGame, updateGame, removeGame, reorderGames, renamePrefixRefs, prefixNameForGame, gamesUsingPrefix, appsUsingPrefix, isPrefixInUse, isWineInUse, gamesFollowingDefault, loadSettings, saveSettings, newGame, newGameId, resolvePrefixDir, clearPlaytime, readPlaySeconds, writePlaySeconds, playtimeFile }
|
||||
module.exports = { loadGames, saveGames, portableGame, getGame, isLinuxGame, addGame, updateGame, removeGame, reorderGames, renamePrefixRefs, prefixNameForGame, gamesUsingPrefix, appsUsingPrefix, isPrefixInUse, isWineInUse, gamesFollowingDefault, loadSettings, saveSettings, newGame, newGameId, resolvePrefixDir, clearPlaytime, readPlaySeconds, writePlaySeconds, playtimeFile }
|
||||
|
|
|
|||
265
src/linuxapp.js
Normal file
265
src/linuxapp.js
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
'use strict'
|
||||
|
||||
// What makes a file a runnable native Linux app: an ELF binary or an AppImage
|
||||
// (both with the executable bit), or a .desktop entry pointing at one.
|
||||
|
||||
const fs = require('fs')
|
||||
const fsp = fs.promises
|
||||
const os = require('os')
|
||||
const path = require('path')
|
||||
|
||||
const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46])
|
||||
|
||||
// Folders that ship libraries/data, never the entry point. Skipping them is
|
||||
// what keeps `share/` and `lib/` .desktop files out of the candidates.
|
||||
const SKIPPED_DIRS = new Set([
|
||||
'lib', 'lib32', 'lib64', 'libexec', 'share', 'include', 'man', 'doc', 'docs',
|
||||
'locale', 'node_modules', 'redist', 'python', 'site-packages', '__pycache__',
|
||||
'translations', 'resources', 'licenses', 'locale'
|
||||
])
|
||||
|
||||
const LIBRARY_RE = /\.(so(\.\d+(\.\d+)*)?|a|o|py|pyc|jar|dll|dylib)$/i
|
||||
const SCRIPT_RE = /^(run|start|launch|play|app)\.sh$/i
|
||||
|
||||
function isElfBuffer(buf) {
|
||||
return !!buf && buf.length >= 4 && buf.subarray(0, 4).equals(ELF_MAGIC)
|
||||
}
|
||||
|
||||
function isElfSync(file) {
|
||||
try {
|
||||
const fd = fs.openSync(file, 'r')
|
||||
try {
|
||||
const buf = Buffer.alloc(4)
|
||||
fs.readSync(fd, buf, 0, 4, 0)
|
||||
return isElfBuffer(buf)
|
||||
} finally {
|
||||
fs.closeSync(fd)
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// [Desktop Entry] fields we care about; the first group wins, later groups
|
||||
// (Desktop Action ...) are ignored.
|
||||
function parseDesktopEntry(text) {
|
||||
const entry = {}
|
||||
let inEntry = false
|
||||
for (const raw of String(text || '').split('\n')) {
|
||||
const line = raw.trim()
|
||||
if (line.startsWith('[')) {
|
||||
inEntry = line === '[Desktop Entry]'
|
||||
continue
|
||||
}
|
||||
if (!inEntry || !line || line.startsWith('#')) continue
|
||||
const eq = line.indexOf('=')
|
||||
if (eq <= 0) continue
|
||||
const key = line.slice(0, eq).trim()
|
||||
const value = line.slice(eq + 1).trim()
|
||||
if (key === 'Exec' || key === 'Icon' || key === 'Path' || key === 'Name' || key === 'Type') {
|
||||
if (!(key in entry)) entry[key] = value
|
||||
}
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
function readDesktopEntry(file) {
|
||||
try {
|
||||
return parseDesktopEntry(fs.readFileSync(file, 'utf8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Exec is a command line with field codes: the first token is the program.
|
||||
function execToken(exec) {
|
||||
const m = String(exec || '').match(/"([^"]*)"|'([^']*)'|(\S+)/)
|
||||
const token = m ? (m[1] ?? m[2] ?? m[3]) : ''
|
||||
return token && !/^%[fFuUdDnNickvm]?$/.test(token) ? token : ''
|
||||
}
|
||||
|
||||
// A .desktop's program, resolved against the entry's own folder. Relative
|
||||
// Exec= paths are common in app dirs; the spec says that is not allowed, so
|
||||
// the fallback is to the folder itself.
|
||||
function desktopExecPath(entry, desktopFile) {
|
||||
const token = execToken(entry && entry.Exec)
|
||||
if (!token) return ''
|
||||
const dir = path.dirname(desktopFile)
|
||||
const resolved = path.isAbsolute(token) ? token : path.resolve(dir, token)
|
||||
try {
|
||||
fs.accessSync(resolved)
|
||||
return resolved
|
||||
} catch {
|
||||
const base = path.join(dir, path.basename(token))
|
||||
try {
|
||||
fs.accessSync(base)
|
||||
return base
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isExecutable(file) {
|
||||
try {
|
||||
return (fs.statSync(file).mode & 0o111) !== 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function sizeOf(file) {
|
||||
try {
|
||||
return (await fsp.stat(file)).size
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Best entry point in an app folder: the same question findDefaultExe answers
|
||||
// for Windows, with ELF/AppImage/.desktop instead of .exe.
|
||||
async function findLinuxExe(dir) {
|
||||
const candidates = []
|
||||
const desktops = []
|
||||
const walk = async (d, depth) => {
|
||||
let entries
|
||||
try {
|
||||
entries = await fsp.readdir(d, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const subdirs = []
|
||||
for (const entry of entries) {
|
||||
const full = path.join(d, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
if (!SKIPPED_DIRS.has(entry.name.toLowerCase())) subdirs.push([full, depth + 1])
|
||||
continue
|
||||
}
|
||||
const lower = entry.name.toLowerCase()
|
||||
if (lower.endsWith('.desktop')) {
|
||||
desktops.push([full, depth])
|
||||
continue
|
||||
}
|
||||
if (lower.endsWith('.appimage')) {
|
||||
candidates.push({ file: full, depth, score: 100 })
|
||||
continue
|
||||
}
|
||||
if (LIBRARY_RE.test(entry.name)) continue
|
||||
if (SCRIPT_RE.test(entry.name)) {
|
||||
candidates.push({ file: full, depth, score: 60 })
|
||||
continue
|
||||
}
|
||||
if (isElfSync(full)) candidates.push({ file: full, depth, score: isExecutable(full) ? 55 : 40 })
|
||||
}
|
||||
await Promise.all(subdirs.map(([full, next]) => walk(full, next)))
|
||||
}
|
||||
await walk(dir, 0)
|
||||
|
||||
// A .desktop is the intended way in when it names a program in the tree.
|
||||
for (const [full, depth] of desktops) {
|
||||
const exec = desktopExecPath(readDesktopEntry(full), full)
|
||||
if (exec) candidates.push({ file: exec, depth, score: 90 })
|
||||
}
|
||||
if (!candidates.length) return ''
|
||||
|
||||
let best = ''
|
||||
let bestScore = -Infinity
|
||||
for (const candidate of candidates) {
|
||||
const size = await sizeOf(candidate.file)
|
||||
// shallow wins, and between equals the bigger binary is the app
|
||||
const score = candidate.score - candidate.depth * 5 + Math.min(size / 1000000, 20)
|
||||
if (score > bestScore) {
|
||||
bestScore = score
|
||||
best = candidate.file
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// The .desktop that belongs to this program: one in the same folder, whose
|
||||
// Exec points at it (or the only one there).
|
||||
function desktopFileFor(exePath) {
|
||||
const dir = path.dirname(exePath)
|
||||
let names = []
|
||||
try {
|
||||
names = fs.readdirSync(dir).filter(n => n.toLowerCase().endsWith('.desktop'))
|
||||
} catch {}
|
||||
if (!names.length) {
|
||||
try {
|
||||
names = fs.readdirSync(path.join(dir, '..')).filter(n => n.toLowerCase().endsWith('.desktop'))
|
||||
} catch {}
|
||||
if (names.length) return path.join(dir, '..', names[0])
|
||||
return ''
|
||||
}
|
||||
for (const name of names) {
|
||||
const file = path.join(dir, name)
|
||||
if (desktopExecPath(readDesktopEntry(file), file) === exePath) return file
|
||||
}
|
||||
return path.join(dir, names[0])
|
||||
}
|
||||
|
||||
function pngOrSvg(file) {
|
||||
try {
|
||||
const fd = fs.openSync(file, 'r')
|
||||
try {
|
||||
const buf = Buffer.alloc(64)
|
||||
const read = fs.readSync(fd, buf, 0, 64, 0)
|
||||
const head = buf.subarray(0, read)
|
||||
if (head.length >= 8 && head.readUInt32BE(0) === 0x89504e47) return 'png'
|
||||
const text = head.toString('utf8').trim().toLowerCase()
|
||||
if (text.startsWith('<svg') || text.startsWith('<?xml')) return 'svg'
|
||||
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8) return 'jpg'
|
||||
} finally {
|
||||
fs.closeSync(fd)
|
||||
}
|
||||
} catch {}
|
||||
return ''
|
||||
}
|
||||
|
||||
const THEME_SIZES = ['512x512', '256x256', '128x128', 'scalable', '64x64', '48x48', '32x32']
|
||||
|
||||
// An `Icon=` value: an absolute path, a path relative to the .desktop's
|
||||
// folder (AppImage app dirs put .DirIcon next to it), or a theme icon name.
|
||||
function findIconFile(spec, baseDir) {
|
||||
const candidates = []
|
||||
const name = String(spec || '').trim() || '.DirIcon'
|
||||
if (path.isAbsolute(name)) {
|
||||
candidates.push(name)
|
||||
} else {
|
||||
if (baseDir) candidates.push(path.join(baseDir, name))
|
||||
if (!path.extname(name)) {
|
||||
const dataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
|
||||
for (const dir of [path.join(dataHome, 'icons'), '/usr/share/icons']) {
|
||||
for (const size of THEME_SIZES) {
|
||||
for (const ext of ['png', 'svg']) candidates.push(path.join(dir, 'hicolor', size, 'apps', `${name}.${ext}`))
|
||||
}
|
||||
}
|
||||
for (const dir of [dataHome, '/usr/share', '/usr/local/share']) {
|
||||
candidates.push(path.join(dir, 'pixmaps', name + '.png'), path.join(dir, 'pixmaps', name + '.svg'))
|
||||
}
|
||||
} else {
|
||||
for (const dir of ['/usr/share/pixmaps', process.env.XDG_DATA_HOME ? path.join(process.env.XDG_DATA_HOME, 'pixmaps') : '']) {
|
||||
if (dir) candidates.push(path.join(dir, name))
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue
|
||||
const kind = pngOrSvg(candidate)
|
||||
if (kind) return candidate
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ELF_MAGIC,
|
||||
isElfBuffer,
|
||||
isElfSync,
|
||||
findLinuxExe,
|
||||
parseDesktopEntry,
|
||||
readDesktopEntry,
|
||||
desktopExecPath,
|
||||
desktopFileFor,
|
||||
findIconFile,
|
||||
pngOrSvg
|
||||
}
|
||||
349
src/linuxrunner.js
Normal file
349
src/linuxrunner.js
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
'use strict'
|
||||
|
||||
// Native Linux apps: the twin of runner.js. Same tracked spawn tail, but the
|
||||
// program runs directly (no wine) with a redirected home and, when bubblewrap
|
||||
// works, inside a namespace.
|
||||
|
||||
const crypto = require('crypto')
|
||||
const fs = require('fs')
|
||||
const os = require('os')
|
||||
const path = require('path')
|
||||
const { DIRS, readJson, writeJson } = require('./paths')
|
||||
const { prefixPath, prefixLinuxRoot } = require('./prefixes')
|
||||
const { prefixNameForGame } = require('./library')
|
||||
const { spawnTracked, parseArgs } = require('./runner')
|
||||
const { buildBwrapArgs, SHARE_ROOT } = require('./sandbox')
|
||||
|
||||
const DATA_DIRS = ['home', 'config', 'data', 'cache', 'state']
|
||||
|
||||
// host folder <-> in-sandbox XDG variable, so both backends set the same env
|
||||
const XDG_LAYOUT = {
|
||||
XDG_CONFIG_HOME: ['config', '.config'],
|
||||
XDG_DATA_HOME: ['data', path.join('.local', 'share')],
|
||||
XDG_CACHE_HOME: ['cache', '.cache'],
|
||||
XDG_STATE_HOME: ['state', path.join('.local', 'state')]
|
||||
}
|
||||
|
||||
// Write access is handed out to the folder the app was imported from and to
|
||||
// nothing else outside its home: a portable app writes its logs and data next
|
||||
// to itself (Prism Launcher refuses to start otherwise), while system trees
|
||||
// must never come back writable.
|
||||
const SYSTEM_DIRS = ['/bin', '/sbin', '/lib', '/lib32', '/lib64', '/libx32', '/usr', '/etc', '/boot', '/proc', '/sys', '/dev', '/run']
|
||||
|
||||
function writableAppDir(game) {
|
||||
const dir = (game && (game.path || (game.exePath && path.dirname(game.exePath)))) || ''
|
||||
// realpathSync('') would answer with the cwd - never hand that out
|
||||
if (!dir) return ''
|
||||
let real
|
||||
try {
|
||||
real = fs.realpathSync(dir)
|
||||
if (!fs.statSync(real).isDirectory()) return ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
// launcher-owned folders: only an imported app may be written to
|
||||
if (real.startsWith(DIRS.FILES + path.sep)) {
|
||||
return real.startsWith(DIRS.APPS + path.sep) ? real : ''
|
||||
}
|
||||
if (real === '/') return ''
|
||||
for (const system of SYSTEM_DIRS) {
|
||||
if (real === system || real.startsWith(system + '/')) return ''
|
||||
}
|
||||
return real
|
||||
}
|
||||
|
||||
function linuxUser() {
|
||||
try {
|
||||
return os.userInfo().username
|
||||
} catch {
|
||||
return process.env.USER || 'user'
|
||||
}
|
||||
}
|
||||
|
||||
function copyFromHost(src, dst, { refresh = false } = {}) {
|
||||
try {
|
||||
if (!refresh && fs.existsSync(dst)) return false
|
||||
if (!fs.statSync(src).isFile()) return false
|
||||
fs.mkdirSync(path.dirname(dst), { recursive: true })
|
||||
fs.copyFileSync(src, dst)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// PulseAudio looks for its cookie under $HOME/.config/pulse; with HOME
|
||||
// redirected there is none, and sound dies for everything going through
|
||||
// Pulse. Copied once - the app owns it afterwards.
|
||||
function seedPulseCookie(root) {
|
||||
const dst = path.join(root, 'config', 'pulse', 'cookie')
|
||||
const seeded = copyFromHost(path.join(os.homedir(), '.config', 'pulse', 'cookie'), dst)
|
||||
if (seeded) {
|
||||
try {
|
||||
fs.chmodSync(dst, 0o600)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// The host's desktop preferences, not its data: a redirected home has no
|
||||
// theme at all, and Qt/GTK then fall back to their built-in light look (KDE's
|
||||
// dark palette lives in kdeglobals).
|
||||
const DESKTOP_SEEDS = [
|
||||
'kdeglobals',
|
||||
'kdedefaults/kdeglobals',
|
||||
'gtk-3.0/settings.ini',
|
||||
'gtk-4.0/settings.ini',
|
||||
'qt5ct/qt5ct.conf',
|
||||
'qt6ct/qt6ct.conf',
|
||||
'Trolltech.conf',
|
||||
'user-dirs.dirs'
|
||||
]
|
||||
|
||||
// The host's desktop *data* - fonts, icons, themes, colour schemes - is not
|
||||
// copied but handed over read-only (see buildBwrapArgs), so it follows the
|
||||
// host without an import.
|
||||
const DATA_SHARES = ['fonts', 'icons', 'themes', 'color-schemes']
|
||||
|
||||
function hostShareDir() {
|
||||
return path.join(os.homedir(), '.local', 'share')
|
||||
}
|
||||
|
||||
function dataShares() {
|
||||
return DATA_SHARES.map(name => path.join(hostShareDir(), name)).filter(dir => fs.existsSync(dir))
|
||||
}
|
||||
|
||||
function hashOf(file) {
|
||||
try {
|
||||
return crypto.createHash('sha1').update(fs.readFileSync(file)).digest('hex')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function mtimeOf(file) {
|
||||
try {
|
||||
return fs.statSync(file).mtimeMs
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Hashes of what we put in the prefix, so a host change can be followed while
|
||||
// the app has not touched our copy. Kept in the prefix root: the app only
|
||||
// ever sees home/config/data/cache/state.
|
||||
const SEED_MARKER = '.seeded.json'
|
||||
|
||||
// Copies a preference in, then keeps following it for as long as we can prove
|
||||
// the copy is still ours: an unusable theme is worse than a stale one, and an
|
||||
// app's own edit is never overwritten.
|
||||
function syncDesktopConfig(root) {
|
||||
const hostConfig = path.join(os.homedir(), '.config')
|
||||
const markerFile = path.join(root, SEED_MARKER)
|
||||
const marker = readJson(markerFile, {})
|
||||
let changed = false
|
||||
for (const rel of DESKTOP_SEEDS) {
|
||||
const src = path.join(hostConfig, rel)
|
||||
const dst = path.join(root, 'config', rel)
|
||||
const hostHash = hashOf(src)
|
||||
if (!hostHash) continue
|
||||
const known = marker[rel]
|
||||
if (fs.existsSync(dst)) {
|
||||
const current = hashOf(dst)
|
||||
if (known) {
|
||||
// the app owns it now, or there is nothing to do
|
||||
if (current !== known || current === hostHash) continue
|
||||
} else if (current !== hostHash && mtimeOf(dst) >= mtimeOf(src)) {
|
||||
// a prefix from an older launcher: an identical copy is ours, and so is
|
||||
// one the host's file has since outgrown. A copy that is not older than
|
||||
// the host's is the app's own - ties stay with the app
|
||||
continue
|
||||
}
|
||||
}
|
||||
// refresh: this is provably still our own copy
|
||||
if (copyFromHost(src, dst, { refresh: true })) {
|
||||
marker[rel] = hostHash
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
try {
|
||||
writeJson(markerFile, marker)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// X11 access: XAUTHORITY usually lives in /run/user (bound), but a launcher
|
||||
// started without it would leave X11 dead inside. Refreshed: a cookie is
|
||||
// session state, not data.
|
||||
function seedXauthority(root) {
|
||||
copyFromHost(path.join(os.homedir(), '.Xauthority'), path.join(root, 'home', '.Xauthority'), { refresh: true })
|
||||
}
|
||||
|
||||
// Everything this module copies in from the host, prefix-relative: the one
|
||||
// list a reset has to clear.
|
||||
function seededRelPaths() {
|
||||
return [
|
||||
...DESKTOP_SEEDS.map(rel => path.join('config', rel)),
|
||||
path.join('config', 'pulse', 'cookie'),
|
||||
path.join('home', '.Xauthority'),
|
||||
SEED_MARKER
|
||||
]
|
||||
}
|
||||
|
||||
// syncDesktopConfig only follows the host while the copy is provably ours, so
|
||||
// an app that edited its own theme keeps it forever. The reset drops our
|
||||
// copies (and the hashes that track them) and lets the next start seed clean
|
||||
// ones - the app's own files in the same folders are never touched.
|
||||
function resetSeededConfig(name) {
|
||||
const root = prefixLinuxRoot(name)
|
||||
const removed = []
|
||||
for (const rel of seededRelPaths()) {
|
||||
const file = path.join(root, rel)
|
||||
try {
|
||||
// lstat: a link pointing out of the prefix is none of our business
|
||||
if (!fs.lstatSync(file).isFile()) continue
|
||||
fs.rmSync(file, { force: true })
|
||||
removed.push(rel)
|
||||
} catch {}
|
||||
}
|
||||
// folders that exist only for a seed, and only while nothing else lives there
|
||||
const dirs = ['kdedefaults', 'gtk-3.0', 'gtk-4.0', 'qt5ct', 'qt6ct', 'pulse']
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
fs.rmdirSync(path.join(root, 'config', dir))
|
||||
} catch {}
|
||||
}
|
||||
return { ok: true, removed }
|
||||
}
|
||||
|
||||
function ensureLinuxPfx(name) {
|
||||
const root = prefixLinuxRoot(name)
|
||||
fs.mkdirSync(path.join(root, 'home', '.local', 'share'), { recursive: true })
|
||||
for (const dir of DATA_DIRS) fs.mkdirSync(path.join(root, dir), { recursive: true })
|
||||
seedPulseCookie(root)
|
||||
seedXauthority(root)
|
||||
return root
|
||||
}
|
||||
|
||||
// Wayland cannot carry a window icon and the compositor only guesses one from
|
||||
// the app id; XWayland can, and GLFW/Qt/GTK all read these, so one flag moves
|
||||
// the whole process tree (Prism and the Minecraft it launches) back to X11.
|
||||
const X11_ENV = { XDG_SESSION_TYPE: 'x11', QT_QPA_PLATFORM: 'xcb', GDK_BACKEND: 'x11' }
|
||||
|
||||
// The theme data sits in front of the inherited list: on the host the user's
|
||||
// own icons and fonts also win over the system ones.
|
||||
function withHostShare(env, entries) {
|
||||
const own = entries.filter(Boolean)
|
||||
if (!own.length) return
|
||||
env.XDG_DATA_DIRS = [...own, env.XDG_DATA_DIRS].filter(Boolean).join(':')
|
||||
}
|
||||
|
||||
// HOME and the XDG folders point at the prefix (plain run) or at the bind
|
||||
// targets inside the sandbox - the two must agree or the app writes outside.
|
||||
function buildLinuxEnv({ game, backend = 'env' }) {
|
||||
const prefixName = prefixNameForGame(game)
|
||||
const root = ensureLinuxPfx(prefixName)
|
||||
syncDesktopConfig(root)
|
||||
const sandboxed = backend === 'bwrap'
|
||||
const home = sandboxed ? `/home/${linuxUser()}` : path.join(root, 'home')
|
||||
const env = { ...process.env }
|
||||
env.HOME = home
|
||||
for (const [key, [hostDir, sandboxSub]] of Object.entries(XDG_LAYOUT)) {
|
||||
env[key] = sandboxed ? path.join(home, sandboxSub) : path.join(root, hostDir)
|
||||
}
|
||||
// XDG_RUNTIME_DIR stays the host's: Wayland, PipeWire and the session bus
|
||||
// live there. It weakens the isolation, and the UI says so.
|
||||
// The X session manager sits in the private /tmp, so its pointer would only
|
||||
// lead to a dead socket; clients skip it when it is absent.
|
||||
if (sandboxed) delete env.SESSION_MANAGER
|
||||
// the host's fonts/icons/themes: mounted read-only by buildBwrapArgs, or - in
|
||||
// a plain run, where nothing is hidden - just put on the search path
|
||||
if (dataShares().length) withHostShare(env, [sandboxed ? SHARE_ROOT : hostShareDir()])
|
||||
if (game.forceX11) Object.assign(env, X11_ENV)
|
||||
// the app's own environment comes last: it overrides everything above
|
||||
for (const [k, v] of Object.entries(game.env || {})) env[k] = v
|
||||
return { env, root, home, prefixName, prefixDir: prefixPath(prefixName) }
|
||||
}
|
||||
|
||||
// bwrap when it works, plain run otherwise - unless the app demands a sandbox.
|
||||
function pickBackend({ game, sandbox }) {
|
||||
const policy = (game && game.isolation) || 'auto'
|
||||
const status = sandbox && typeof sandbox.status === 'function' ? sandbox.status() : null
|
||||
const available = !!status && status.backend === 'bwrap'
|
||||
if (policy === 'off') return { ok: true, backend: 'env', policy, status }
|
||||
if (available) return { ok: true, backend: 'bwrap', policy, status }
|
||||
if (policy === 'require') return { ok: false, error: 'sandbox-required', policy, status }
|
||||
return { ok: true, backend: 'env', policy, status }
|
||||
}
|
||||
|
||||
function isolationLine({ backend, status }) {
|
||||
if (backend === 'bwrap') return `[plwl] isolation: bwrap ${(status && status.version) || ''}`.trim()
|
||||
const reason = (status && status.reason) || 'missing'
|
||||
return `[plwl] isolation: env-only (reason: ${reason})`
|
||||
}
|
||||
|
||||
// "Open with": a native app takes the file where it is (the sandbox sees /).
|
||||
function linuxPathFor(file) {
|
||||
let abs = String(file || '')
|
||||
try {
|
||||
abs = fs.realpathSync(abs)
|
||||
} catch {}
|
||||
return abs
|
||||
}
|
||||
|
||||
function bwrapSource() {
|
||||
const devices = ['/dev/shm', '/dev/dri', '/dev/snd', '/dev/input'].filter(d => fs.existsSync(d))
|
||||
const x11 = fs.existsSync('/tmp/.X11-unix') ? '/tmp/.X11-unix' : ''
|
||||
const runUser = `/run/user/${typeof process.getuid === 'function' ? process.getuid() : 0}`
|
||||
return {
|
||||
devices,
|
||||
x11,
|
||||
runUser: fs.existsSync(runUser) ? runUser : '',
|
||||
shares: dataShares(),
|
||||
user: linuxUser()
|
||||
}
|
||||
}
|
||||
|
||||
async function runLinuxGame({ game, sandbox, onExit, openFile, handoff = false }) {
|
||||
const chosen = pickBackend({ game, sandbox })
|
||||
if (!chosen.ok) throw new Error(chosen.error)
|
||||
|
||||
const exe = game.exePath
|
||||
const workdir = game.workdir || path.dirname(exe)
|
||||
const argList = parseArgs(game.args)
|
||||
if (openFile) argList.push(linuxPathFor(openFile))
|
||||
|
||||
const { env, root } = buildLinuxEnv({ game, backend: chosen.backend })
|
||||
const header = [isolationLine(chosen)]
|
||||
if (game.forceX11) header.push('[plwl] x11 forced (XWayland)')
|
||||
|
||||
let cmd = exe
|
||||
let args = argList
|
||||
if (chosen.backend === 'bwrap') {
|
||||
const source = bwrapSource()
|
||||
cmd = 'bwrap'
|
||||
args = [...buildBwrapArgs({ dataRoot: root, user: source.user, devices: source.devices, x11: source.x11, runUser: source.runUser, shares: source.shares, appDir: writableAppDir(game) }), '--', exe, ...argList]
|
||||
header.push(`[plwl] HOME=${env.HOME}`)
|
||||
}
|
||||
|
||||
return spawnTracked({ game, cmd, args, cwd: workdir, env, handoff, header, onExit })
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DATA_DIRS,
|
||||
XDG_LAYOUT,
|
||||
SYSTEM_DIRS,
|
||||
DESKTOP_SEEDS,
|
||||
DATA_SHARES,
|
||||
X11_ENV,
|
||||
writableAppDir,
|
||||
ensureLinuxPfx,
|
||||
resetSeededConfig,
|
||||
dataShares,
|
||||
syncDesktopConfig,
|
||||
buildLinuxEnv,
|
||||
pickBackend,
|
||||
isolationLine,
|
||||
linuxPathFor,
|
||||
runLinuxGame
|
||||
}
|
||||
|
|
@ -38,6 +38,20 @@ function prefixPath(name) {
|
|||
return path.join(DIRS.PREFIXES, name)
|
||||
}
|
||||
|
||||
// Native Linux apps keep their redirected home/config/cache in here, next to
|
||||
// the Windows side of the same prefix.
|
||||
const LINUX_PFX = 'linux_pfx'
|
||||
|
||||
function prefixLinuxRoot(name) {
|
||||
return path.join(prefixPath(name), LINUX_PFX)
|
||||
}
|
||||
|
||||
// Native Linux app data is machine-local (sockets, caches, machine-id, the
|
||||
// sandbox's home): a sync neither sends it nor deletes it as an extra.
|
||||
function isLocalOnlyRel(rel) {
|
||||
return String(rel || '').split('/').includes(LINUX_PFX)
|
||||
}
|
||||
|
||||
function prefixExists(name) {
|
||||
try {
|
||||
fs.accessSync(prefixPath(name))
|
||||
|
|
@ -100,6 +114,7 @@ function isPrefixRoot(p) {
|
|||
const root = prefixPath(entry.name)
|
||||
if (abs === root || abs === path.join(root, 'pfx')) return true
|
||||
if (abs === path.join(root, 'drive_c') || abs === path.join(root, 'pfx', 'drive_c')) return true
|
||||
if (abs === path.join(root, LINUX_PFX) || abs === path.join(root, LINUX_PFX, 'home')) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
@ -173,4 +188,4 @@ function setDefaultPrefix(name) {
|
|||
return { ok: true }
|
||||
}
|
||||
|
||||
module.exports = { isPrefixRel, PREFIX_REL_RE, listPrefixes, savePrefixes, createPrefix, deletePrefix, renamePrefix, setDefaultPrefix, prefixPath, prefixExists, prefixDriveRoots, isPrefixRoot, healPrefix, ensureUnifiedPrefix, MAIN }
|
||||
module.exports = { isPrefixRel, PREFIX_REL_RE, LINUX_PFX, isLocalOnlyRel, listPrefixes, savePrefixes, createPrefix, deletePrefix, renamePrefix, setDefaultPrefix, prefixPath, prefixLinuxRoot, prefixExists, prefixDriveRoots, isPrefixRoot, healPrefix, ensureUnifiedPrefix, MAIN }
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ contextBridge.exposeInMainWorld('plwl', {
|
|||
prefixesDelete: name => ipcRenderer.invoke('prefixes:delete', name),
|
||||
prefixesRename: (oldName, newName) => ipcRenderer.invoke('prefixes:rename', oldName, newName),
|
||||
prefixesSetDefault: name => ipcRenderer.invoke('prefixes:setDefault', name),
|
||||
prefixesResetLinuxConfig: name => ipcRenderer.invoke('prefixes:resetLinuxConfig', name),
|
||||
openwithTake: () => ipcRenderer.invoke('openwith:take'),
|
||||
openwithRun: payload => ipcRenderer.invoke('openwith:run', payload),
|
||||
openwithTexts: lang => ipcRenderer.invoke('openwith:texts', lang),
|
||||
|
|
@ -68,7 +69,10 @@ contextBridge.exposeInMainWorld('plwl', {
|
|||
gamesShortcutPaths: id => ipcRenderer.invoke('games:shortcutPaths', id),
|
||||
gamesPickFolder: () => ipcRenderer.invoke('games:pickFolder'),
|
||||
gamesPickPrefixFolder: prefix => ipcRenderer.invoke('games:pickPrefixFolder', prefix),
|
||||
gamesImport: (src, mode) => ipcRenderer.invoke('games:import', src, mode),
|
||||
gamesImport: (src, mode, kind) => ipcRenderer.invoke('games:import', src, mode, kind),
|
||||
gamesOpenDataFolder: id => ipcRenderer.invoke('games:openDataFolder', id),
|
||||
sandboxStatus: () => ipcRenderer.invoke('sandbox:status'),
|
||||
sandboxProbe: () => ipcRenderer.invoke('sandbox:probe'),
|
||||
gamesImportFromPrefix: (prefix, src) => ipcRenderer.invoke('games:importFromPrefix', prefix, src),
|
||||
gamesRun: id => ipcRenderer.invoke('games:run', id),
|
||||
gamesRunTool: (id, tool, args) => ipcRenderer.invoke('games:runTool', id, tool, args),
|
||||
|
|
|
|||
|
|
@ -198,6 +198,10 @@ function windowsPathFor(file, prefixDir) {
|
|||
}
|
||||
|
||||
const GRACE_MS = 60000
|
||||
// A finished run may leave output in the pipes (or a grandchild holding them
|
||||
// open): the log closes when its writers are done, at the latest this long
|
||||
// after the exit.
|
||||
const LOG_DRAIN_MS = 5000
|
||||
|
||||
// Live playtime: tiny file updated every 30s, totals mirrored to the registry
|
||||
// on exit. `base` comes from the caller (live file, not the registry) so
|
||||
|
|
@ -222,32 +226,17 @@ function openLatestLog(gameId) {
|
|||
return fs.createWriteStream(logFile, { flags: 'w' })
|
||||
}
|
||||
|
||||
async function runGame({ game, wine, systemWine, onExit, openFile, handoff = false }) {
|
||||
await healPrefixOnce(game)
|
||||
const isProton = wine && wine.type === 'proton'
|
||||
const { env, prefixDir } = buildEnv({ game, wine })
|
||||
const exe = game.exePath
|
||||
const workdir = game.workdir || path.dirname(exe)
|
||||
const argList = parseArgs(game.args)
|
||||
// an opened file is an argument to the exe, exactly like Windows' "Open with"
|
||||
if (openFile) argList.push(windowsPathFor(openFile, prefixDir))
|
||||
|
||||
let cmd
|
||||
let base
|
||||
if (isProton) {
|
||||
cmd = wine.wineBin || path.join(wine.path, 'proton')
|
||||
base = [protonVerb(game), exe, ...argList]
|
||||
} else {
|
||||
cmd = systemWine ? 'wine' : wine.wineBin
|
||||
base = [exe, ...argList]
|
||||
}
|
||||
|
||||
// The tail every tracked run shares (wine and native Linux alike): spawn
|
||||
// detached, tee output into the app's latest log, tick playtime, stamp
|
||||
// lastPlayed, report the exit. `header` lines land right after the launch line.
|
||||
function spawnTracked({ game, cmd, args, cwd, env, handoff = false, header = [], onExit }) {
|
||||
const library = require('./library')
|
||||
fs.mkdirSync(DIRS.DATA, { recursive: true })
|
||||
return new Promise((resolve, reject) => {
|
||||
let child
|
||||
try {
|
||||
child = spawn(cmd, base, {
|
||||
cwd: workdir,
|
||||
child = spawn(cmd, args, {
|
||||
cwd,
|
||||
env,
|
||||
// a handoff is untracked: its pipes drain so the app never blocks
|
||||
stdio: handoff ? 'ignore' : ['ignore', 'pipe', 'pipe'],
|
||||
|
|
@ -272,24 +261,36 @@ async function runGame({ game, wine, systemWine, onExit, openFile, handoff = fal
|
|||
const logFile = latestLogPath(game.id)
|
||||
const ws = openLatestLog(game.id)
|
||||
// a launch line first, so the log answers "which prefix/overrides/run"
|
||||
ws.write(`[plwl] ${cmd} ${base.join(' ')}\n`)
|
||||
ws.write(`[plwl] WINEPREFIX=${env.WINEPREFIX}\n`)
|
||||
if (env.WINEDLLOVERRIDES) ws.write(`[plwl] WINEDLLOVERRIDES=${env.WINEDLLOVERRIDES}\n`)
|
||||
if (isProton) ws.write(`[plwl] proton launcher: ${game.disableUmu ? 'direct wine (no UMU, no Steam)' : `umu.exe (UMU_ID=${env.UMU_ID})`}\n`)
|
||||
child.stdout.pipe(ws)
|
||||
child.stderr.pipe(ws)
|
||||
ws.write(`[plwl] ${cmd} ${args.join(' ')}\n`)
|
||||
for (const line of header) ws.write(line + '\n')
|
||||
// two pipes feed one log, so neither may end it: pipe() would close the
|
||||
// stream on the first EOF, and the second writer then kills the process
|
||||
// with ERR_STREAM_WRITE_AFTER_END (an unhandled WriteStream 'error')
|
||||
child.stdout.pipe(ws, { end: false })
|
||||
child.stderr.pipe(ws, { end: false })
|
||||
let openPipes = 2
|
||||
const endLog = () => {
|
||||
if (--openPipes <= 0) ws.end()
|
||||
}
|
||||
child.stdout.once('end', endLog)
|
||||
child.stderr.once('end', endLog)
|
||||
// an unwritable log (full disk, file removed) must not take us down
|
||||
ws.on('error', () => {})
|
||||
child.unref()
|
||||
const startedAt = Date.now()
|
||||
// read the LIVE playtime file, not the registry (shared ids)
|
||||
const basePlaySeconds = require('./library').readPlaySeconds(game.id) ?? (game.playSeconds || 0)
|
||||
const basePlaySeconds = library.readPlaySeconds(game.id) ?? (game.playSeconds || 0)
|
||||
const stopTicker = startPlaytimeTicker({ game, startedAt, base: basePlaySeconds })
|
||||
// stamp "last played" once at start, even if we crash later
|
||||
require('./library').updateGame(game.id, { lastPlayed: startedAt })
|
||||
library.updateGame(game.id, { lastPlayed: startedAt })
|
||||
child.on('exit', (code, signal) => {
|
||||
stopTicker()
|
||||
ws.end()
|
||||
// nothing may outlive the run: end the log once the buffered output had
|
||||
// its chance, even if something else still holds the pipes
|
||||
const drain = setTimeout(() => ws.end(), LOG_DRAIN_MS)
|
||||
if (drain.unref) drain.unref()
|
||||
const counted = Math.max(0, Math.round((Date.now() - startedAt - GRACE_MS) / 1000))
|
||||
require('./library').updateGame(game.id, {
|
||||
library.updateGame(game.id, {
|
||||
lastPlayed: startedAt,
|
||||
playSeconds: basePlaySeconds + counted
|
||||
})
|
||||
|
|
@ -300,6 +301,32 @@ async function runGame({ game, wine, systemWine, onExit, openFile, handoff = fal
|
|||
})
|
||||
}
|
||||
|
||||
async function runGame({ game, wine, systemWine, onExit, openFile, handoff = false }) {
|
||||
await healPrefixOnce(game)
|
||||
const isProton = wine && wine.type === 'proton'
|
||||
const { env, prefixDir } = buildEnv({ game, wine })
|
||||
const exe = game.exePath
|
||||
const workdir = game.workdir || path.dirname(exe)
|
||||
const argList = parseArgs(game.args)
|
||||
// an opened file is an argument to the exe, exactly like Windows' "Open with"
|
||||
if (openFile) argList.push(windowsPathFor(openFile, prefixDir))
|
||||
|
||||
let cmd
|
||||
let base
|
||||
if (isProton) {
|
||||
cmd = wine.wineBin || path.join(wine.path, 'proton')
|
||||
base = [protonVerb(game), exe, ...argList]
|
||||
} else {
|
||||
cmd = systemWine ? 'wine' : wine.wineBin
|
||||
base = [exe, ...argList]
|
||||
}
|
||||
|
||||
const header = [`[plwl] WINEPREFIX=${env.WINEPREFIX}`]
|
||||
if (env.WINEDLLOVERRIDES) header.push(`[plwl] WINEDLLOVERRIDES=${env.WINEDLLOVERRIDES}`)
|
||||
if (isProton) header.push(`[plwl] proton launcher: ${game.disableUmu ? 'direct wine (no UMU, no Steam)' : `umu.exe (UMU_ID=${env.UMU_ID})`}`)
|
||||
return spawnTracked({ game, cmd, args: base, cwd: workdir, env, handoff, header, onExit })
|
||||
}
|
||||
|
||||
async function runTool({ game, wine, tool, args, systemWine }) {
|
||||
await healPrefixOnce(game)
|
||||
const isProton = wine && wine.type === 'proton'
|
||||
|
|
@ -336,4 +363,4 @@ function runAdHoc({ openPath, wine, systemWine, prefix, onExit }) {
|
|||
return runGame({ game, wine, systemWine, onExit })
|
||||
}
|
||||
|
||||
module.exports = { buildEnv, runGame, runTool, runAdHoc, parseArgs, latestLogPath, windowsPathFor }
|
||||
module.exports = { buildEnv, runGame, runTool, runAdHoc, parseArgs, latestLogPath, windowsPathFor, spawnTracked }
|
||||
|
|
|
|||
160
src/sandbox.js
Normal file
160
src/sandbox.js
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
'use strict'
|
||||
|
||||
const { execFile } = require('child_process')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
// bubblewrap is only usable when unprivileged user namespaces actually work:
|
||||
// Ubuntu 24.04 ships bwrap but AppArmor kills it ("Failed to unshare user
|
||||
// namespace"), so a functional probe decides - not `which bwrap`.
|
||||
const PROBE_TIMEOUT_MS = 3000
|
||||
// /bin/true is a symlink on most distros but missing on a few; env is the
|
||||
// last resort that still exits 0.
|
||||
const TRUE_BINARIES = ['/bin/true', '/usr/bin/true', '/usr/bin/env']
|
||||
|
||||
function firstExisting(candidates) {
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
fs.accessSync(candidate)
|
||||
return candidate
|
||||
} catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function firstLine(text) {
|
||||
return String(text || '').trim().split('\n')[0].trim()
|
||||
}
|
||||
|
||||
// A failed probe maps to a reason the UI and the log can name.
|
||||
function reasonFor(err, stderr) {
|
||||
if (err && err.code === 'ENOENT') return 'missing'
|
||||
if (err && (err.killed || err.signal === 'SIGKILL')) return 'timeout'
|
||||
const text = String(stderr || '') + ' ' + String((err && err.message) || '')
|
||||
if (/Operation not permitted|Permission denied|Failed to unshare|uid map|setting up uid|No permissions to create/i.test(text)) return 'not-permitted'
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
function run(cmd, args, timeoutMs) {
|
||||
return new Promise(resolve => {
|
||||
execFile(cmd, args, { timeout: timeoutMs, killSignal: 'SIGKILL' }, (err, stdout, stderr) => {
|
||||
resolve({ err, stdout: String(stdout || ''), stderr: String(stderr || '') })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Status = { backend: 'bwrap' | 'env', version, reason, detail, checkedAt }
|
||||
// reason = null | 'missing' | 'not-permitted' | 'timeout' | 'failed'
|
||||
function createSandboxProbe({ timeoutMs = PROBE_TIMEOUT_MS } = {}) {
|
||||
let cached = null
|
||||
let inflight = null
|
||||
|
||||
const makeStatus = (backend, version, reason, detail) => ({
|
||||
backend,
|
||||
version: version || null,
|
||||
reason: reason || null,
|
||||
detail: detail || '',
|
||||
checkedAt: Date.now()
|
||||
})
|
||||
|
||||
async function measure() {
|
||||
const trueBin = firstExisting(TRUE_BINARIES)
|
||||
if (!trueBin) {
|
||||
cached = makeStatus('env', null, 'missing', 'no /bin/true to probe with')
|
||||
return cached
|
||||
}
|
||||
const versionRun = await run('bwrap', ['--version'], timeoutMs)
|
||||
if (versionRun.err && versionRun.err.code === 'ENOENT') {
|
||||
cached = makeStatus('env', null, 'missing', 'bubblewrap is not installed')
|
||||
return cached
|
||||
}
|
||||
const version = firstLine(versionRun.stdout).split(/\s+/).pop() || null
|
||||
const probeRun = await run('bwrap', ['--ro-bind', '/', '/', '--proc', '/proc', '--dev', '/dev', '--', trueBin], timeoutMs)
|
||||
if (probeRun.err) {
|
||||
cached = makeStatus('env', version, reasonFor(probeRun.err, probeRun.stderr), firstLine(probeRun.stderr) || firstLine(probeRun.err.message))
|
||||
return cached
|
||||
}
|
||||
cached = makeStatus('bwrap', version, null, '')
|
||||
return cached
|
||||
}
|
||||
|
||||
// Runs the probe once and answers from the cache afterwards (3s on every
|
||||
// launch click would be unacceptable).
|
||||
function probe() {
|
||||
if (cached) return Promise.resolve(cached)
|
||||
if (!inflight) inflight = measure().finally(() => { inflight = null })
|
||||
return inflight
|
||||
}
|
||||
|
||||
return {
|
||||
probe,
|
||||
status: () => cached,
|
||||
invalidate: () => { cached = null }
|
||||
}
|
||||
}
|
||||
|
||||
// Host theme data (fonts, icons, colour schemes) is mounted read-only under
|
||||
// this path - inside the private /tmp the app cannot mistake it for its own
|
||||
// data, and the caller lists it in XDG_DATA_DIRS. A bind, not a symlink: the
|
||||
// prefix is mounted over ~, so a link back into ~ would point at itself.
|
||||
const SHARE_ROOT = '/tmp/.plwl-host'
|
||||
|
||||
// The bwrap profile for a native Linux app. Pure: the caller decides which
|
||||
// devices and host folders exist on this machine, so the argv is testable
|
||||
// as-is.
|
||||
function buildBwrapArgs({
|
||||
dataRoot,
|
||||
user,
|
||||
home = `/home/${user}`,
|
||||
uid = typeof process.getuid === 'function' ? process.getuid() : 0,
|
||||
devices = [],
|
||||
x11 = '',
|
||||
runUser = '',
|
||||
shares = [],
|
||||
hideHome = false,
|
||||
etcRoot = '',
|
||||
unshareNet = false,
|
||||
appDir = ''
|
||||
}) {
|
||||
const xdgDir = sub => path.join(home, sub)
|
||||
return [
|
||||
'--die-with-parent',
|
||||
'--new-session',
|
||||
// network stays: multiplayer and DNS keep working
|
||||
'--unshare-all',
|
||||
unshareNet ? '--unshare-net' : '--share-net',
|
||||
'--hostname', 'plwl',
|
||||
// --- filesystem ---
|
||||
'--ro-bind', '/', '/',
|
||||
'--proc', '/proc',
|
||||
'--dev', '/dev',
|
||||
...devices.flatMap(device => ['--dev-bind', device, device]),
|
||||
'--tmpfs', '/tmp',
|
||||
// X11 sockets live in /tmp, which the tmpfs above just emptied
|
||||
...(x11 ? ['--ro-bind', x11, x11] : []),
|
||||
// the host's theme data, read-only: fonts, icons, colour schemes
|
||||
...shares.flatMap(dir => ['--ro-bind', dir, path.join(SHARE_ROOT, path.basename(dir))]),
|
||||
// hard profile: nothing of anybody's /home is even readable
|
||||
...(hideHome ? ['--tmpfs', '/home', '--tmpfs', '/root', '--tmpfs', '/mnt', '--tmpfs', '/media'] : []),
|
||||
// the app's own folder stays writable (portable apps keep logs/data next
|
||||
// to themselves); the rest of the read-only root does not
|
||||
...(appDir ? ['--bind', appDir, appDir] : []),
|
||||
// --- app data (host paths bound to a fresh HOME) ---
|
||||
'--bind', path.join(dataRoot, 'home'), home,
|
||||
'--bind', path.join(dataRoot, 'config'), xdgDir('.config'),
|
||||
'--bind', path.join(dataRoot, 'data'), xdgDir(path.join('.local', 'share')),
|
||||
'--bind', path.join(dataRoot, 'cache'), xdgDir('.cache'),
|
||||
'--bind', path.join(dataRoot, 'state'), xdgDir(path.join('.local', 'state')),
|
||||
// Wayland, PipeWire, PulseAudio and the session bus all live here
|
||||
...(runUser ? ['--bind', runUser, runUser] : []),
|
||||
...(etcRoot ? ['--bind', etcRoot, '/etc'] : []),
|
||||
// --- environment ---
|
||||
'--setenv', 'HOME', home,
|
||||
'--setenv', 'XDG_CONFIG_HOME', xdgDir('.config'),
|
||||
'--setenv', 'XDG_DATA_HOME', xdgDir(path.join('.local', 'share')),
|
||||
'--setenv', 'XDG_CACHE_HOME', xdgDir('.cache'),
|
||||
'--setenv', 'XDG_STATE_HOME', xdgDir(path.join('.local', 'state'))
|
||||
]
|
||||
}
|
||||
|
||||
module.exports = { createSandboxProbe, buildBwrapArgs, SHARE_ROOT, PROBE_TIMEOUT_MS }
|
||||
Loading…
Add table
Add a link
Reference in a new issue