Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13736d2524 | ||
|
|
a069c79c73 | ||
|
|
9ee9355348 | ||
|
|
0a2dbc3140 | ||
|
|
f7108c0ca4 | ||
|
|
21d72e51ef | ||
|
|
222633e462 | ||
|
|
f64c93b338 | ||
|
|
429899d6fc | ||
|
|
f1486609ab | ||
|
|
e35170d4f9 | ||
|
|
80a5c0b6d6 | ||
|
|
63f0125954 | ||
|
|
5e7c07c98e | ||
|
|
00d2b3bf6b | ||
|
|
02c697c2f0 | ||
|
|
511051952c | ||
|
|
dce2362cbb | ||
|
|
6782ace43d | ||
|
|
71447c932f | ||
|
|
45bcc76436 | ||
|
|
1a6c3321a1 | ||
|
|
b21ef9ece6 | ||
|
|
9b3c3b330a | ||
|
|
46d8c5c379 | ||
|
|
76542b53e5 | ||
|
|
088dac8fb6 | ||
|
|
4a511ca6e3 | ||
|
|
35da9c569a | ||
|
|
dec7b2a9ec | ||
|
|
ba1ed72a55 | ||
|
|
ba2ddef525 | ||
|
|
b20591540b | ||
|
|
f3dee5425e | ||
|
|
676b025c5b | ||
|
|
fac72d17c8 | ||
|
|
a2fa6021f5 | ||
|
|
c492e662cb | ||
|
|
ce803340b0 | ||
|
|
4be34d20ca | ||
|
|
a4e8e20fcd | ||
|
|
fc1bee2673 | ||
|
|
ad8847509b | ||
|
|
627c05bf98 | ||
|
|
b82b714165 | ||
|
|
0bfdfbd0e8 | ||
|
|
19addc1570 | ||
|
|
1f35c77a69 | ||
|
|
5973b6c85c | ||
|
|
d74dc1aa61 | ||
|
|
7b14207f81 |
No files matched your search
@@ -159,6 +159,12 @@ jobs:
|
||||
merge-multiple: true
|
||||
- name: Wheel (CLI install via uv tool / pipx / pip, and its self-update)
|
||||
run: uv build --wheel -o out && ls out
|
||||
- name: Videos (docs/media, rendered by the showcase workflow; frameport-<name>.mp4 → FramePort-<name>.mp4)
|
||||
run: |
|
||||
for f in docs/media/frameport-*.mp4; do
|
||||
[ -f "$f" ] || continue
|
||||
n=$(basename "$f" .mp4); cp "$f" "out/FramePort-${n#frameport-}.mp4"
|
||||
done
|
||||
- name: Checksums
|
||||
run: cd out && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
|
||||
- name: Publish release
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
name: showcase
|
||||
# Docs screenshots and the videos (the demo tour, the install tutorial, …), rendered from the demo library
|
||||
# (docs/showcase/, scripts/showcase/; see docs/SHOWCASE.md). Opens or updates one pull request (branch
|
||||
# showcase/update) when a picture really changed; the renders are also kept as a workflow artifact either way.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
videos:
|
||||
description: "Videos to record too: names from docs/showcase/videos (e.g. tour install), all, or empty"
|
||||
type: string
|
||||
default: ""
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "src/frameport/ui/**"
|
||||
- "src/frameport/locales/**"
|
||||
- "docs/showcase/**"
|
||||
- "scripts/showcase/**"
|
||||
|
||||
concurrency:
|
||||
group: showcase-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
render:
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
PYTHONUTF8: "1"
|
||||
PYTHONIOENCODING: utf-8
|
||||
TZ: UTC
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0 # the push's changed files decide whether the video is recorded again
|
||||
- uses: astral-sh/setup-uv@v10.2.0
|
||||
- name: ffmpeg and fonts
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg fonts-roboto fonts-noto-color-emoji
|
||||
- run: uv sync --extra dev --python 3.12 # the Python the renders are made with locally
|
||||
- name: Chromium for Playwright
|
||||
run: uv run playwright install --with-deps chromium
|
||||
- name: Store art cache (fetched once from the stores the app uses)
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: ~/.cache/frameport-showcase
|
||||
key: showcase-art-${{ hashFiles('docs/showcase/demo-library.yaml') }}
|
||||
restore-keys: showcase-art-
|
||||
|
||||
- name: Docs screenshots
|
||||
run: uv run python scripts/showcase/render_docs.py --keep showcase-out/screenshots
|
||||
|
||||
- name: Videos
|
||||
# a push records the videos whose storyboard (docs/showcase/videos/<name>.yaml) changed, or all of them when
|
||||
# the recorder changed (UI tweaks alone don't re-record ~10 MB files); Run workflow records what it's asked
|
||||
env:
|
||||
INPUT_VIDEOS: ${{ inputs.videos }}
|
||||
BEFORE: ${{ github.event.before }}
|
||||
run: |
|
||||
if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then
|
||||
read -ra names <<< "$INPUT_VIDEOS"
|
||||
if [ ${#names[@]} -eq 0 ]; then echo "no videos asked for"; exit 0; fi
|
||||
[ "${names[0]}" = all ] && names=()
|
||||
uv run python scripts/showcase/record_video.py "${names[@]}" --work showcase-out/videos
|
||||
else
|
||||
uv run python scripts/showcase/record_video.py --changed-since "$BEFORE" --work showcase-out/videos
|
||||
fi
|
||||
|
||||
- name: Keep the renders
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: showcase
|
||||
path: |
|
||||
showcase-out/screenshots
|
||||
showcase-out/videos/*/video.json
|
||||
docs/media
|
||||
docs/images/tour-teaser.webp
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
- name: What changed
|
||||
id: diff
|
||||
run: |
|
||||
git status --short -- docs/images docs/media
|
||||
if [ -n "$(git status --porcelain -- docs/images docs/media)" ]; then
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"; fi
|
||||
- name: Pull request
|
||||
if: steps.diff.outputs.changed == 'true' && github.ref == 'refs/heads/main'
|
||||
uses: peter-evans/create-pull-request@v8.1.1
|
||||
with:
|
||||
branch: showcase/update
|
||||
delete-branch: true
|
||||
add-paths: |
|
||||
docs/images/*
|
||||
docs/media/*
|
||||
commit-message: "Docs: update screenshots and videos"
|
||||
title: "Update docs screenshots and videos"
|
||||
body: |
|
||||
Rendered by the `showcase` workflow from the demo library (docs/showcase/demo-library.yaml) with a
|
||||
pretend Frame: only pictures that visibly changed are included. Look them over before merging (the
|
||||
run's `showcase` artifact has every render).
|
||||
|
||||
Run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -10,8 +10,20 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
|
||||
## Layout
|
||||
- `src/frameport/` — Python package. `pipeline.py` is the API the CLI (`cli.py`) and GUI (`ui/`, Flet 1.0) share.
|
||||
- `ui/` — `app.py` shell (sidebar with Frame connection + activity cards, routing, actions, 30 s connection poll),
|
||||
`theme.py` (dark design tokens; change colours/spacing only there), `components.py` (pill, card, callout,
|
||||
status_row, art_fill, confirm, `update()` = safe update: in Flet 1.0 reading `.page` of an unmounted control
|
||||
`theme.py` (design tokens; change colours/spacing only there. Dark-only colour themes (owner: no light mode):
|
||||
built-ins `portal` (default), `portal_oled` (true black) and `original` (the old violet; alias `classic`). Portal =
|
||||
the logo's dichotomy: orange ACCENT = main action + selection, blue SECONDARY = secondary (outlined) buttons,
|
||||
progress, switch tracks, PC; `dual` themes add the blue→orange sidebar edge, two-colour wordmark (`C.wordmark`) and
|
||||
selected-tab fade (`C.portal_gradient`). Installable theme files `<data>/themes/*.json` (docs/THEMES.md: name,
|
||||
base, dual, any subset of `T.TOKENS`; refused if light/unreadable, `T.ThemeError`), Settings → Appearance: cards
|
||||
switch live via `app.restyle()` (rebuilds the shell, drops cached views; setting `ui.theme`), "Install theme
|
||||
file…", "Copy this theme as a file", bin icon removes. Read tokens as `T.NAME` when building — never as a default argument or module-level constant (they
|
||||
keep the import-time theme; module maps refill through `T.on_change`, `tests/test_theme.py` checks defaults)),
|
||||
`glyphs.py` + `icons/` (the logo `logo.svg`/`logo-solid.svg` = a monitor that comes out of a tilted portal as the
|
||||
Frame, and 24 px line glyphs `fp:frame|port|patch|container|test|pc|sync|live|shot|keys|recipe|link`, copied into
|
||||
the assets dir and shown as tinted `ft.Image`s: pass `G.FRAME` … wherever an icon goes, `C.as_icon` / the button
|
||||
helpers handle both kinds; `src/assets/icon.png` = the bundles' app icon), `components.py` (pill, card, callout,
|
||||
checklist, art_fill, confirm, `update()` = safe update: in Flet 1.0 reading `.page` of an unmounted control
|
||||
raises), `jobs.py` (background FIFO job queue, one at a time, cancel via Reporter; no Flet), `views/`
|
||||
(library: search/filters/tags/sort as pure tested helpers; game: hero + one-click install, patches under
|
||||
"Customize"; frame: device + readiness + installed, or connect wizard; files: the Frame's file manager (persistent
|
||||
@@ -53,6 +65,14 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
|
||||
await a FilePicker) must be coroutine functions or go through `page.run_task`: Flet doesn't await a lambda's
|
||||
coroutine (the Files row Download button silently did nothing). `ui_smoke.py --fake-frame --gestures` drives real
|
||||
mouse drags/right-clicks.
|
||||
Live Frame data comes from one app-owned `app.monitor_hub` (`frame/monitor_hub.py`): subscribers name modules +
|
||||
interval, the hub runs one agent `_monitor` stream (union of modules, fastest interval; per-module collection
|
||||
needs agent v65), reconnects after a lost stream and stops it when nobody subscribes; `_poll` retries an "error".
|
||||
Subscribers: "monitor" (the Monitor tab, everything, only while shown) and "card" = the sidebar's live Frame card
|
||||
(`ui/frame_card.py` helpers: battery ring, "now playing" row with fps + 2-min sparkline → click opens Monitor;
|
||||
games + battery every 5 s, paused while a job's stage is "Upload…", only while connected and setting
|
||||
`ui.live_frame_card` (Settings → Appearance, default on) is on; else the battery comes from the 30 s poll).
|
||||
ui_smoke injects `FakeMonitorSession` as the hub's `session_factory`.
|
||||
User tags live in library entries (`tags`), filters in library setting `ui.library`.
|
||||
**Performance rules** (the app froze before): never put image bytes in controls — artwork is served by URL from the
|
||||
GUI assets dir (= user data dir; `ft.run(assets_dir=…)`), as thumbnails (`artwork/thumbs.py`, Pillow); the
|
||||
@@ -61,10 +81,31 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
|
||||
**Never recreate clickable controls on progress ticks** (sidebar, activity tiles): update their properties —
|
||||
replacing them 5×/s swallowed clicks (couldn't leave the Library during an upload).
|
||||
Labelled switches: `C.switch(label, …)` (Material's default label colour is dark on our dark theme).
|
||||
Cover cards (Library grid + shelf): `library.card_hover`/`hover_motion` (lift, art zoom inside the clipped frame,
|
||||
radial `scrim`, accent-tinted shadow) and `C.CoverButton` (frosted round button, accent under the pointer; Play =
|
||||
blue then orange ring ripple + "Starting on Frame…" pill for STARTING_S; its `.status` layer must sit *below*
|
||||
the button in the Stack, else it takes the clicks); the game page's Play turns into "Starting on …" with a spinner
|
||||
(`GameView._starting`). Reduce motion: no lift/zoom/rings. Filled buttons use a glyph's `-solid` variant
|
||||
(`glyphs.solid`, e.g. `frame-solid.svg`: the outline glyph faded into the orange).
|
||||
Empty states (`C.empty_state(..., features=[(icon, heading, sentence)])`): with features the portal is bigger, a
|
||||
soft portal light (`C.portal_glow`) fills the screen and `C.feature_row` says what the screen will show (the
|
||||
not-connected Files/Screenshots/Live/Type/Monitor tabs and the empty Library); the idle Live view is a framed
|
||||
"screen" with its own Start button + `live_features()`, Type on Frame shows `keyboard_tips()` under the box.
|
||||
Setup checklists (Frame → Ready to play, Settings → Tools / This PC) = `C.checklist([C.Check(ok, title, detail,
|
||||
help, fix=(label, icon, handler), extra=control)])`: ok True/False/"warn"/None (= spinner); the fix button shows
|
||||
inline only while an item isn't ready — wire existing actions only. Motion: `app.body` holds an
|
||||
`ft.AnimatedSwitcher` (`app._show_view`): a new route gets a new wrapper (150 ms fade), a same-route redraw swaps
|
||||
the wrapper's content (no animation; persistent views just remount); the wordmark's portal (`wordmark().data`)
|
||||
pulses once when frame_state turns "connected"; both off with setting `ui.reduce_motion` (Settings → Appearance
|
||||
"Reduce motion", `app.reduce_motion`). Settings has a fixed index column (`settings.SECTIONS` order, Appearance
|
||||
first, Remove FramePort last): entries scroll the section column via `scroll_to(scroll_key=…)` (sections wrapped
|
||||
in Containers with `ft.ScrollKey`), the header stays; `app.settings_view.show_section(key)` (ui_smoke
|
||||
`settings-index`).
|
||||
Help hints: wording for non-obvious terms lives in `ui/help.py` (`HELP`); show it with `C.help_icon(key)` or the
|
||||
`help=` argument of `section`/`status_row`/`kv`, tooltips via `C.tip()` (wraps). Game actions for the Library
|
||||
right-click menu (one `ft.ContextMenu` around the grid, filled on right-click) and the game page's "…" menu come
|
||||
from `app.game_actions()`. Picking art (`sources.apply_choice`) downloads into a staging dir and keeps the old
|
||||
`help=` argument of `section`/`kv` (`C.Check` help key), tooltips via `C.tip()` (wraps). Game actions for the Library
|
||||
right-click menu (one `ft.ContextMenu` around the grid, filled on right-click; short: `menus.quick_menu`, key actions
|
||||
+ "More actions…" = the game page with its full "…" menu opened from code, `app.open_game_menu`) and the game
|
||||
page's "…" menu (`menus.menu_sections` quick=False, sectioned) come from `app.game_actions()`. Picking art (`sources.apply_choice`) downloads into a staging dir and keeps the old
|
||||
art if nothing came back; "Update Steam art on Frame" re-sends the art set to the game's anchor (agent ≥ 12).
|
||||
Patch descriptions/reasons describe the general case, naming games only as "e.g. …".
|
||||
- Installs: queued/cancelled/failed ones are remembered (library setting `ui.installs`) → Library "Resume" bar;
|
||||
@@ -197,9 +238,15 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
|
||||
signed, `ready.json`); `apply()` writes + starts detached `apply.ps1`/`apply.sh` (wait for pid → Windows: copy over,
|
||||
replaced files kept in `updates/<ver>/previous` because the zip has no top folder; macOS/Linux: mv to `.old` + swap,
|
||||
rollback, `xattr -dr` quarantine → relaunch; `<data>/logs/update.log`). `ui/updater.py`: background check (10 s,
|
||||
then 6 h), sidebar card (hidden control, toggled), Library bar (`library_bar`), notes dialog (`ft.Markdown`), job
|
||||
then 6 h), sidebar card (hidden control, toggled), Library bar (`library_bar`), changelog dialog, job
|
||||
`app-update` that restarts only when no other job is active, `apply_pending_at_start()` in `main()` for
|
||||
"Install updates automatically"; Settings → Updates. CLI: `--version`, `frameport update [--check (exit 10)]
|
||||
"Install updates automatically"; Settings → Updates. Changelog: `updates.fetch_changelog` (releases list,
|
||||
`app-releases.json`, same 6 h cache, offline → cached / []) → `ChangelogEntry` (`whats_new()` keeps only the tag
|
||||
message's "What's new" part: CI's intro, update hint and release-footer.md stripped); `between`/`changelog_for`
|
||||
(installed < v ≤ offered, dev entry only when on/choosing dev, skipped versions included), `recent_history`;
|
||||
the update/dev dialogs show one collapsible section per version (`_changes_column`, newest open); after an update
|
||||
`pending_news` (setting `update.last_seen_version`; first start only records it; offline → retried next start)
|
||||
→ Library "was updated" bar → "See what's new…"; Settings → Updates "What's new…" = recent history. CLI: `--version`, `frameport update [--check (exit 10)]
|
||||
[--yes]`, once-a-day stderr hint read from the cache only (`refresh_cache()` in a daemon thread writes no
|
||||
settings, to avoid read-modify-write races). `scripts/update_smoke.py <archive>` runs the real extract + swap script
|
||||
(no relaunch) — CI runs it on all three OS with the archive it just built.
|
||||
@@ -233,11 +280,19 @@ Repo is on an NTFS drive (`core.fileMode=false`); line endings are LF (`.gitattr
|
||||
artwork, frames.json, the app's SSH key which the dev Frame authorizes).
|
||||
- Device checks: `frameport test <pkg>` / `frameport parity-device --results <parity.json> --baseline <launch.txt>
|
||||
[--test-only]`; the pre-FramePort baseline is `PATCHED/_known-good-2026-09-28/_frame-state/baseline-launch.txt`.
|
||||
- Docs screenshots (`docs/images/`): `python scripts/scrub_library.py ~/.local/share/frameport <dir> --status works,issues` (copies
|
||||
library + artwork only; titles replace folder names, local paths → `D:/Games/...`, sort by size) then
|
||||
`FRAMEPORT_HOME=<dir> python scripts/ui_smoke.py --out <shots> --docs --fake-frame --game <pkg>` (set
|
||||
FRAMEPORT_JAVA/_OVERPORT_JAR/_APKSIGNER_JAR so no tool download toast appears; `--viewport 1280x2600` + crop for the
|
||||
patch list). Check every PNG for paths, IPs, user names and repack/scene names before committing.
|
||||
- Docs screenshots + videos (docs/SHOWCASE.md): never by hand. `uv run python scripts/showcase/render_docs.py`
|
||||
renders `docs/showcase/shots.yaml` into `docs/images/` (every shot twice, kept when both agree; only visibly changed
|
||||
files are rewritten; `--check` for CI) and `scripts/showcase/record_video.py [names] [--draft]` records the
|
||||
storyboards `docs/showcase/videos/<name>.yaml` (tour = FramePort in use + README teaser; install = the install
|
||||
tutorial: instruction cards for the download / the command on the Frame, the rest filmed from a first start) into
|
||||
`docs/media/frameport-<name>.mp4`. Both build the demo library first (`demo_home.py`, profile `demo` or `fresh`:
|
||||
catalog games from `demo-library.yaml` + `demo-analyses.json`, art/details cached in ~/.cache/frameport-showcase, a
|
||||
pretend Frame from `showcase-frame.json`) in a temp FRAMEPORT_HOME: no personal data, refuses the real data dir
|
||||
and placeholder art; discovery is off and the setup command shows placeholders for the address and code. Steps find elements
|
||||
by name through Flutter's semantics tree (`scripts/showcase/web.py`: text, tooltip; the innermost match wins) —
|
||||
give new icon-only controls a tooltip. The `showcase` workflow renders on UI pushes to main (+ the videos whose
|
||||
storyboard changed, or the ones named on dispatch) and opens PR `showcase/update`; releases attach every video as
|
||||
`FramePort-<name>.mp4`. `scripts/scrub_library.py` (the owner's own library) is only for private screenshots now.
|
||||
README rules (owner): states the project is a proof of concept, provides no piracy tools, credits the wrapped
|
||||
projects (most functionality is theirs); neutral technical wording; no Quest2Frame mentions anywhere.
|
||||
- GUI smoke test: `uv pip install flet-web playwright && playwright install chromium`, then
|
||||
@@ -303,7 +358,10 @@ The Frame runs firewalld (22 and 32000 open). PC side: the setup server needs in
|
||||
firewall blocks it silently (`DefaultInboundAction Block`): `pairing.ensure_reachable` adds a temporary rule via one
|
||||
UAC prompt, removed when the server stops (flag file in %TEMP%, max 35 min); hints per OS after 45 s without a request
|
||||
(`pairing.firewall_hint`). Flet 1.0 patches aren't thread-safe → `app.serialize_flet_updates()` (a dialog shown while a
|
||||
scan redraw ran never closed: "dropped a patch for unknown control").
|
||||
scan redraw ran never closed: "dropped a patch for unknown control"); it also makes property writes (Flet's
|
||||
`Prop.__set__`) take the same `app.FLET_LOCK`: a property set on a background thread while the loop packed a patch
|
||||
changed the control's `_values` mid-iteration ("dictionary changed size during iteration", a sidebar click's page
|
||||
change died while the live Frame card took a sample). Anything that serves the app (ui_smoke, showcase) calls it too.
|
||||
**Lepton:** needs an activity with category **LAUNCHER** (Quest apps often only have INFO → "APP_ACTIVITY is empty").
|
||||
**2D apps:** Lepton runs every app headless (`lepton.headless=true`, only OpenXR output reaches the headset) unless the app folder (`<base>/lepton-app/`) has a `lepton-show-flatscreen` file (liblepton/app_metadata.sh) → Waydroid window on gamescope; agent v28 `set_flatscreen` at finalize for `vr_kind == "none"`. Android 11's navbar covered the
|
||||
app's controls → patch `device.hide_navbar` (default on for vr_kind none, migration `flat_hide_navbar`) exports
|
||||
|
||||
@@ -9,7 +9,10 @@
|
||||
|
||||
Install games that target the Meta Quest, Android, or general PCVR onto your **Valve Steam Frame**. FramePort handles everything from uploading game files, setting up your Frame, injecting compatibility patches, and adding shortcuts to your Steam library. FramePort aims to be as simple as possible by taking advantage of the fact that the Steam Frame runs on Linux.
|
||||
|
||||

|
||||
[](docs/media/frameport-tour.mp4)
|
||||
|
||||
▶ [Watch the full tour](docs/media/frameport-tour.mp4) · New to FramePort? [Watch the install tutorial](docs/media/frameport-install.mp4)
|
||||
(about 90 seconds each, MP4; also attached to every release)
|
||||
|
||||
> **Notice:** FramePort explicitly does NOT download, share, or unlock games. You must provide legally obtained game
|
||||
> executables. Core features of FramePort simply download and wrap other published tools (see [Built on](#built-on))
|
||||
@@ -18,6 +21,8 @@ Install games that target the Meta Quest, Android, or general PCVR onto your **V
|
||||
|
||||
## Features
|
||||
|
||||

|
||||
|
||||
- **Painless setup:** one short command on the Frame. No root, no `sudo`, no password.
|
||||
[What it changes](docs/FRAME_SETUP.md).
|
||||
- **Type on Frame:** use your computer's keyboard on the Frame: in VR apps, Android apps, Steam and the desktop.
|
||||
@@ -109,7 +114,7 @@ will attempt to guess key patches. If you find a new config that works for an ap
|
||||
|
||||
**[List of tested games](docs/GAMES.md)**
|
||||
|
||||
**Tested something? Share it.** In FramePort open the game → **…** → **Share working config…** (it fills in the
|
||||
**Tested something? Share it.** In FramePort open the game → **…** → **Share working recipe…** (it fills in the
|
||||
recipe for you) or **Report a problem…** (attaches a diagnostics zip with personal data removed). Without the app:
|
||||
[share a working config](https://github.com/spoopyghosty0/frameport/issues/new?template=working-config.yml) · [report a problem](https://github.com/spoopyghosty0/frameport/issues/new?template=bug-report.yml). Shared configs become built-in recipes for everyone.
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import time
|
||||
import zlib
|
||||
from types import SimpleNamespace
|
||||
|
||||
AGENT_VERSION = 64
|
||||
AGENT_VERSION = 66
|
||||
HOME = os.path.expanduser("~")
|
||||
STEAM = os.path.join(HOME, ".local/share/Steam")
|
||||
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
|
||||
@@ -2082,6 +2082,11 @@ def cmd_delete_screenshots(args):
|
||||
for p in paths:
|
||||
os.unlink(p)
|
||||
deleted.append(p)
|
||||
stem, ext = os.path.splitext(p)
|
||||
try: # a VR screenshot's stereo copy (<name>_vr.jpg) next to it goes too
|
||||
os.unlink(stem + "_vr" + ext)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
thumbs = os.path.join(os.path.dirname(p), "thumbnails")
|
||||
if inside_userdata(thumbs):
|
||||
try:
|
||||
@@ -2091,6 +2096,112 @@ def cmd_delete_screenshots(args):
|
||||
return {"deleted": deleted}
|
||||
|
||||
|
||||
# Headset screenshots through OpenVR's IVRScreenshots (SteamVR's own libopenvr_api.so via ctypes, no build step):
|
||||
# connect as a background app (never starts SteamVR), RequestScreenshot(stereo) = SteamVR captures what the wearer
|
||||
# sees into two files (a flat preview + the stereo image), SubmitScreenshot = the Steam client adds them to its
|
||||
# library like a shot taken in the headset (under SteamVR, 250820). Verified on the device 2026-10-08. (SteamVR's
|
||||
# dashboard debug command `screenshot_request` over its web mailbox did nothing here.) While the headset sleeps the
|
||||
# compositor captures nothing.
|
||||
OPENVR_LIBS = ("/opt/steamvr/bin/linuxarm64/libopenvr_api.so", "/opt/steamvr/bin/linux64/libopenvr_api.so")
|
||||
VR_APP_BACKGROUND = 3
|
||||
VR_SHOT_STEREO = 2
|
||||
HMD_STATE = re.compile(r"\[CCVTrackedHmdDriver\] in State(\w+)")
|
||||
|
||||
|
||||
def hmd_state():
|
||||
"""The headset's state from SteamVR's driver log ("Normal", "Standby", ... ; None = unknown)."""
|
||||
try:
|
||||
with open(os.path.join(STEAM, "logs", "vrserver.txt"), "rb") as f:
|
||||
f.seek(max(0, os.path.getsize(f.name) - 400_000))
|
||||
text = f.read().decode(errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
found = HMD_STATE.findall(text)
|
||||
return found[-1] if found else None
|
||||
|
||||
|
||||
def steamvr_shot_files():
|
||||
return set(glob.glob(os.path.join(STEAM, "userdata", "*", "760", "remote", STEAMVR_APPID, "screenshots", "*")))
|
||||
|
||||
|
||||
def vr_screenshot(capture_wait=6.0):
|
||||
"""Ask SteamVR for a stereo screenshot and hand it to Steam. Returns None when submitted, else why not:
|
||||
"steamvr" (not running / no OpenVR), "capture" (nothing captured: the headset sleeps), or an error text."""
|
||||
import ctypes
|
||||
import tempfile
|
||||
|
||||
lib = next((p for p in OPENVR_LIBS if os.path.isfile(p)), None)
|
||||
if lib is None:
|
||||
return "steamvr"
|
||||
vr = ctypes.CDLL(lib)
|
||||
vr.VR_InitInternal2.restype = ctypes.c_uint32
|
||||
vr.VR_InitInternal2.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_char_p]
|
||||
vr.VR_GetGenericInterface.restype = ctypes.c_void_p
|
||||
vr.VR_GetGenericInterface.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)]
|
||||
vr.VR_ShutdownInternal.restype = None
|
||||
err = ctypes.c_int(0)
|
||||
vr.VR_InitInternal2(ctypes.byref(err), VR_APP_BACKGROUND, None)
|
||||
if err.value:
|
||||
return "steamvr"
|
||||
tmp = tempfile.mkdtemp(prefix="frameport-shot-")
|
||||
try:
|
||||
request = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_uint32), ctypes.c_int, ctypes.c_char_p,
|
||||
ctypes.c_char_p)
|
||||
submit = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_uint32, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p)
|
||||
|
||||
class Table(ctypes.Structure): # openvr_capi.h VR_IVRScreenshots_FnTable (IVRScreenshots_001)
|
||||
_fields_ = [("RequestScreenshot", request), ("HookScreenshot", ctypes.c_void_p),
|
||||
("GetScreenshotPropertyType", ctypes.c_void_p),
|
||||
("GetScreenshotPropertyFilename", ctypes.c_void_p),
|
||||
("UpdateScreenshotProgress", ctypes.c_void_p), ("TakeStereoScreenshot", ctypes.c_void_p),
|
||||
("SubmitScreenshot", submit)]
|
||||
|
||||
ierr = ctypes.c_int(0)
|
||||
ptr = vr.VR_GetGenericInterface(b"FnTable:IVRScreenshots_001", ctypes.byref(ierr))
|
||||
if not ptr:
|
||||
return f"no screenshot interface ({ierr.value})"
|
||||
table = Table.from_address(ptr)
|
||||
base = os.path.join(tmp, "shot")
|
||||
handle = ctypes.c_uint32(0)
|
||||
r = table.RequestScreenshot(ctypes.byref(handle), VR_SHOT_STEREO, (base + "_preview").encode(),
|
||||
(base + "_vr").encode())
|
||||
if r:
|
||||
return f"SteamVR refused the screenshot ({r})"
|
||||
preview, full = base + "_preview.png", base + "_vr.png"
|
||||
deadline = time.time() + capture_wait
|
||||
while time.time() < deadline and not (os.path.isfile(preview) and os.path.isfile(full)):
|
||||
time.sleep(0.2)
|
||||
if not (os.path.isfile(preview) and os.path.isfile(full)):
|
||||
return "capture"
|
||||
time.sleep(0.4) # the second file can still be being written
|
||||
r = table.SubmitScreenshot(handle.value, VR_SHOT_STEREO, preview.encode(), full.encode())
|
||||
if r:
|
||||
return f"Steam didn't take the screenshot ({r})"
|
||||
time.sleep(1.5) # Steam copies the files: keep them until it has
|
||||
return None
|
||||
finally:
|
||||
vr.VR_ShutdownInternal()
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def cmd_take_screenshot(args):
|
||||
"""A headset screenshot now (vr_screenshot), saved by Steam under SteamVR; waits up to `wait` s for its file:
|
||||
{taken, path, reason, hmd}. reason: "steamvr" (SteamVR not running), "capture" (the headset sleeps), other text =
|
||||
an error."""
|
||||
wait = float(args.get("wait") or 8)
|
||||
before = steamvr_shot_files()
|
||||
reason = vr_screenshot()
|
||||
if reason is None:
|
||||
deadline = time.time() + wait
|
||||
while time.time() < deadline:
|
||||
new = [p for p in steamvr_shot_files() - before if SHOT_NAME.match(os.path.basename(p))]
|
||||
if new:
|
||||
return {"taken": True, "path": max(new, key=os.path.getmtime), "reason": None, "hmd": hmd_state()}
|
||||
time.sleep(0.4)
|
||||
reason = "not saved"
|
||||
return {"taken": False, "path": None, "reason": reason, "hmd": hmd_state()}
|
||||
|
||||
|
||||
def cmd_prepare(args):
|
||||
"""Where to upload, and what the Frame already has (so unchanged data is not re-sent)."""
|
||||
pkg = check_pkg(args["package"])
|
||||
@@ -4721,6 +4832,8 @@ MON_INTERVALS = (0.1, 0.25, 0.5, 1, 2, 5) # seconds between samples; processes
|
||||
MON_DEFAULT_INTERVAL = 0.5
|
||||
SCAN_SECONDS = 2.0
|
||||
MON_FILTERS = ("game", "steam", "all")
|
||||
# what a client can ask for ({"modules": [...]}, agent v65); without that message every module is collected
|
||||
MON_MODULES = ("games", "procs", "cpu", "gpu", "mem", "temps", "power", "battery", "net", "disk")
|
||||
MON_PROC_LIMIT = 150
|
||||
MON_CONTEXT = 3 # "game" filter: the busiest other processes, shown for context
|
||||
# processes never signalled: the session, SSH and system plumbing (killing them logs the user out or drops FramePort)
|
||||
@@ -4765,6 +4878,20 @@ def _num(text, default=None):
|
||||
return default
|
||||
|
||||
|
||||
def monitor_plan(modules=None):
|
||||
"""The collectors one tick runs for the requested modules (None, "all" or anything unusable = all of them).
|
||||
mem includes PSI, temps the zone detail and the fan. The process scan ("scan") runs for games and procs and also
|
||||
for gpu: GPU busy is summed from the render fds the scan finds; "gpu_ns" (per-process GPU time) for the same."""
|
||||
if modules is None or modules == "all" or not isinstance(modules, (list, tuple, set, frozenset)):
|
||||
wanted = set(MON_MODULES)
|
||||
else:
|
||||
wanted = {m for m in modules if m in MON_MODULES}
|
||||
plan = set(wanted)
|
||||
if wanted & {"games", "procs", "gpu"}:
|
||||
plan |= {"scan", "gpu_ns"}
|
||||
return frozenset(plan)
|
||||
|
||||
|
||||
def read_cpu_times():
|
||||
"""[total, core0, core1, …] as (busy, all) jiffies from /proc/stat."""
|
||||
out = []
|
||||
@@ -5036,6 +5163,7 @@ class Monitor:
|
||||
self.page = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096
|
||||
self.btime = next((int(x.split()[1]) for x in _rd(f"{PROC}/stat").splitlines() if x.startswith("btime ")), 0)
|
||||
self.filter = "game"
|
||||
self.plan = monitor_plan() # collectors per tick (set_modules)
|
||||
self.kthreads = set()
|
||||
self.drm = {} # pid -> (fds, time of the fd scan)
|
||||
self.gpu_ns = {} # pid -> last drm-engine ns
|
||||
@@ -5067,7 +5195,15 @@ class Monitor:
|
||||
"clusters": [{"cpus": c["cpus"], "max_mhz": c["max_mhz"]} for c in self.clusters],
|
||||
"mem_total": read_meminfo()["total"], "rails": [r[0] for r in self.rails],
|
||||
"temp_groups": sorted({z[0] for z in self.zones}, key=[g for g, _ in TEMP_GROUPS].index),
|
||||
"fan": bool(self.fan), "intervals": list(MON_INTERVALS), "filters": list(MON_FILTERS)}
|
||||
"fan": bool(self.fan), "intervals": list(MON_INTERVALS), "filters": list(MON_FILTERS),
|
||||
"modules": list(MON_MODULES)}
|
||||
|
||||
def set_modules(self, modules):
|
||||
"""Collect only these modules from the next tick on (None/"all" = everything)."""
|
||||
plan = monitor_plan(modules)
|
||||
if ("scan" in plan and "scan" not in self.plan) or ("procs" in plan and "procs" not in self.plan):
|
||||
self.scan_at = -1e9 # processes wanted (again): scan at once
|
||||
self.plan = plan
|
||||
|
||||
# -------------------------------------------------------------------- games
|
||||
def deployments(self, now):
|
||||
@@ -5274,53 +5410,73 @@ class Monitor:
|
||||
dt = now - self.last if self.last is not None else 0.0
|
||||
self.last = now
|
||||
out = {"t": round(wall, 3), "dt": round(dt, 3)}
|
||||
cur = read_cpu_times()
|
||||
if self.cpu_prev:
|
||||
pct = cpu_percent(self.cpu_prev, cur)
|
||||
out["cpu"] = {"total": pct[0] if pct else 0.0, "cores": pct[1:]}
|
||||
plan = self.plan
|
||||
if "cpu" in plan:
|
||||
cur = read_cpu_times()
|
||||
if self.cpu_prev:
|
||||
pct = cpu_percent(self.cpu_prev, cur)
|
||||
out["cpu"] = {"total": pct[0] if pct else 0.0, "cores": pct[1:]}
|
||||
else:
|
||||
out["cpu"] = {"total": 0.0, "cores": [0.0] * self.ncpu}
|
||||
self.cpu_prev = cur
|
||||
out["cpu"]["mhz"] = [_num(_rd(f"{c['policy']}/scaling_cur_freq"), 0) // 1000 for c in self.clusters]
|
||||
else:
|
||||
out["cpu"] = {"total": 0.0, "cores": [0.0] * self.ncpu}
|
||||
self.cpu_prev = cur
|
||||
out["cpu"]["mhz"] = [_num(_rd(f"{c['policy']}/scaling_cur_freq"), 0) // 1000 for c in self.clusters]
|
||||
out["mem"] = read_meminfo()
|
||||
out["psi"] = read_psi()
|
||||
if now - self.temps_at >= 2 or self.temps is None: # 48 sensor files (~3 ms at idle clocks); heat is slow
|
||||
self.temps, self.zone_detail = read_temps(self.zones)
|
||||
self.temps_at = now
|
||||
temps, detail = self.temps, self.zone_detail
|
||||
out["temps"] = temps
|
||||
if now - self.zone_detail_at >= 5:
|
||||
out["zones"] = detail
|
||||
self.zone_detail_at = now
|
||||
if self.fan:
|
||||
out["fan"] = _num(_rd(self.fan))
|
||||
out["power"] = self.power.read(now)
|
||||
out["battery"] = self.battery.read(now)
|
||||
net = read_net()
|
||||
if self.net_prev and dt > 0:
|
||||
prev = self.net_prev
|
||||
out["net"] = {k: [max(0, int((v[0] - prev[k][0]) / dt)), max(0, int((v[1] - prev[k][1]) / dt))]
|
||||
for k, v in net.items() if k in prev}
|
||||
self.net_prev = net
|
||||
if now - self.disk_at >= 30:
|
||||
self.cpu_prev = None # no average over the time it was off
|
||||
if "mem" in plan:
|
||||
out["mem"] = read_meminfo()
|
||||
out["psi"] = read_psi()
|
||||
if "temps" in plan:
|
||||
if now - self.temps_at >= 2 or self.temps is None: # 48 sensor files (~3 ms at idle clocks); heat is slow
|
||||
self.temps, self.zone_detail = read_temps(self.zones)
|
||||
self.temps_at = now
|
||||
temps, detail = self.temps, self.zone_detail
|
||||
out["temps"] = temps
|
||||
if now - self.zone_detail_at >= 5:
|
||||
out["zones"] = detail
|
||||
self.zone_detail_at = now
|
||||
if self.fan:
|
||||
out["fan"] = _num(_rd(self.fan))
|
||||
if "power" in plan:
|
||||
out["power"] = self.power.read(now)
|
||||
if "battery" in plan:
|
||||
out["battery"] = self.battery.read(now)
|
||||
if "net" in plan:
|
||||
net = read_net()
|
||||
if self.net_prev and dt > 0:
|
||||
prev = self.net_prev
|
||||
out["net"] = {k: [max(0, int((v[0] - prev[k][0]) / dt)), max(0, int((v[1] - prev[k][1]) / dt))]
|
||||
for k, v in net.items() if k in prev}
|
||||
self.net_prev = net
|
||||
else:
|
||||
self.net_prev = None # a delta over one tick's dt needs the previous tick's counters
|
||||
if "disk" in plan and now - self.disk_at >= 30:
|
||||
try:
|
||||
st = os.statvfs(HOME)
|
||||
out["disk"] = {"free": st.f_bavail * st.f_frsize, "total": st.f_blocks * st.f_frsize}
|
||||
except OSError:
|
||||
pass
|
||||
self.disk_at = now
|
||||
scan = now - self.scan_at >= SCAN_SECONDS or not self.procs
|
||||
scan = "scan" in plan and (now - self.scan_at >= SCAN_SECONDS or not self.procs)
|
||||
if scan:
|
||||
self.scan(now, wall)
|
||||
self.scan_at = now
|
||||
busy = self.gpu_sample(now, dt)
|
||||
out["gpu"] = {"busy": round(busy, 1) if dt > 0 else None,
|
||||
"mhz": _num(_rd(f"{self.gpu}/cur_freq"), 0) // 1000000 if self.gpu else None}
|
||||
out["games"] = self.games_sample(now)
|
||||
if scan:
|
||||
if "gpu_ns" in plan:
|
||||
busy = self.gpu_sample(now, dt)
|
||||
else:
|
||||
busy = None
|
||||
self.gpu_ns, self.gpu_pct, self.gpu_acc = {}, {}, {} # stale counters would spike on the next delta
|
||||
if "gpu" in plan:
|
||||
out["gpu"] = {"busy": round(busy, 1) if dt > 0 and busy is not None else None,
|
||||
"mhz": _num(_rd(f"{self.gpu}/cur_freq"), 0) // 1000000 if self.gpu else None}
|
||||
if "games" in plan:
|
||||
out["games"] = self.games_sample(now)
|
||||
if scan and "procs" in plan:
|
||||
out["procs"] = self.filtered(now)
|
||||
out["filter"] = self.filter
|
||||
self.scan_prev = now
|
||||
elif scan:
|
||||
self.gpu_acc = {}
|
||||
self.scan_prev = now
|
||||
self.tick += 1
|
||||
out["self_ms"] = round((time.process_time() - t0) * 1000, 2)
|
||||
return out
|
||||
@@ -5407,9 +5563,10 @@ def monitor_end_game(pkg, wait=6.0):
|
||||
|
||||
def monitor_session(stdin, stdout, monitor=None, sleep=time.sleep, max_ticks=None):
|
||||
"""Long-lived: prints {"ready": 1, "static": {...}}, then one sample per tick. Control lines on stdin:
|
||||
{"interval": 1|2|5}, {"procs": "game"|"steam"|"all"}, {"pause": bool}, {"id": n, "kill": pid, "sig": "TERM"|
|
||||
"KILL", "force": bool}, {"id": n, "end_game": package} (each with an id gets {"reply": n, "ok": …}). Ends at EOF
|
||||
or when the SSH session (parent) is gone."""
|
||||
{"interval": 1|2|5}, {"procs": "game"|"steam"|"all"}, {"pause": bool}, {"modules": [...]|"all"} (v63: only those
|
||||
collectors run, see monitor_plan), {"id": n, "kill": pid, "sig": "TERM"|"KILL", "force": bool}, {"id": n,
|
||||
"end_game": package} (each with an id gets {"reply": n, "ok": …}). Ends at EOF or when the SSH session (parent)
|
||||
is gone."""
|
||||
import threading
|
||||
|
||||
mon = monitor or Monitor()
|
||||
@@ -5451,6 +5608,8 @@ def monitor_session(stdin, stdout, monitor=None, sleep=time.sleep, max_ticks=Non
|
||||
mon.scan_at = -1e9 # rescan now
|
||||
if "pause" in msg:
|
||||
state["pause"] = bool(msg["pause"])
|
||||
if "modules" in msg and hasattr(mon, "set_modules"):
|
||||
mon.set_modules(msg["modules"])
|
||||
if "kill" in msg or "end_game" in msg:
|
||||
threading.Thread(target=act, args=(msg,), daemon=True).start()
|
||||
continue
|
||||
|
||||
@@ -6,7 +6,7 @@ Other games get suggested patches from detection rules; each suggestion states i
|
||||
switched on or off under **Customize**: described in plain words, with **Show technical details** for the exact
|
||||
effect of each patch.
|
||||
|
||||
Tried an untested game? Its page asks how it runs; **Share working config…** opens a prefilled GitHub issue so your
|
||||
Tried an untested game? Its page asks how it runs; **Share working recipe…** opens a prefilled GitHub issue so your
|
||||
recipe can join the built-in catalog for everyone.
|
||||
|
||||

|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Two ways users feed results back, both without a GitHub token:
|
||||
|
||||
- **Share working config** (game menu, `frameport share-recipe <pkg>`): saves the recipe as a user catalog entry and
|
||||
- **Share working recipe** (game menu, `frameport share-recipe <pkg>`): saves the recipe as a user catalog entry and
|
||||
opens a prefilled issue from `.github/ISSUE_TEMPLATE/working-config.yml`. A maintainer checks it and adds the label
|
||||
`catalog-accepted`. Then `.github/workflows/catalog-from-issue.yml` runs `scripts/catalog_from_issue.py`, which reads
|
||||
only the YAML block, validates it, and writes `catalog/games/<pkg>.yaml`, and the workflow opens a PR.
|
||||
|
||||
@@ -24,7 +24,7 @@ Games/ ← scan this folder (Add games → Scan
|
||||
as alternates.
|
||||
- **Scanning:** pick the folder that contains the game folders (`Games/` above) to add them all, or one game's folder
|
||||
to add just that game. FramePort looks up to 5 levels deep.
|
||||
- **A single game:** Add games → Add an APK file… works with a lone APK too. Its data is found when the data folder sits next
|
||||
- **A single game:** Add games → Add an APK… works with a lone APK too. Its data is found when the data folder sits next
|
||||
to the APK, named as above.
|
||||
|
||||
Not sure of the package name? Look at the OBB file names: `main.<version>.<package name>.obb`. Or add the APK
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Tested games
|
||||
|
||||
Games tested on the Steam Frame with FramePort's recipes. Games not listed here may work too: FramePort suggests patches for them, and a working config can be shared from the app (**Share working config…**).
|
||||
Games tested on the Steam Frame with FramePort's recipes. Games not listed here may work too: FramePort suggests patches for them, and a working recipe can be shared from the app (**Share working recipe…**).
|
||||
Tested a game? [Share a working config](https://github.com/spoopyghosty0/frameport/issues/new?template=working-config.yml) or [report a problem](https://github.com/spoopyghosty0/frameport/issues/new?template=bug-report.yml) (in the app: the game's **…** menu does both and fills in the details).
|
||||
Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Installing FramePort
|
||||
|
||||
▶ **[Watch the install tutorial](media/frameport-install.mp4)** (about 90 seconds, MP4; also attached to every
|
||||
release as `FramePort-install.mp4`): from the download to the first game on the Frame.
|
||||
|
||||
[](media/frameport-install.mp4)
|
||||
|
||||
Download the archive for your computer from the [latest release](https://github.com/spoopyghosty0/frameport/releases/latest)
|
||||
and extract it anywhere. No installer or admin rights are needed. On first start FramePort downloads its Java
|
||||
runtime, the OVRPort CLI and apksigner into its data folder (Settings → Tools shows them).
|
||||
@@ -99,7 +104,7 @@ which would end Desktop Mode). This is new: please report anything odd with **Re
|
||||
back/home/recents buttons are hidden by default (patch **Hide Android's navigation bar**). If FramePort guesses
|
||||
wrong (a phone app shows nothing in the headset, or a VR app opens as a flat window), choose **VR** or **Flat
|
||||
window** under **Show as VR or as a flat window** in the game's **Customize** section, then **Update on Frame**.
|
||||
- **Add games → Add a Windows program (.exe)…** adds a single Windows program; the Frame runs it through Proton (as a
|
||||
- **Add games → Add a Windows program…** adds a single Windows program; the Frame runs it through Proton (as a
|
||||
window unless it is a VR game). A program sitting in Downloads, the home folder or a drive root is copied on its
|
||||
own first, so the install doesn't upload everything next to it.
|
||||
- In the packaged app you can also **drag files onto the Library**: APKs, Linux apps (AppImage, `.zip`/`.tar.gz`),
|
||||
@@ -114,7 +119,7 @@ sideloader, documented at framedropvr.com/docs). FramePort understands the same
|
||||
the title, the files, their size and whether a checksum is given, and asks before it downloads anything. Then it
|
||||
downloads the build, adds it to your library and starts the usual install on the Frame. If no Frame is connected,
|
||||
the game is added now and installs once the Frame is back.
|
||||
- **Add games → Install from a link…** takes the button's address (right-click → Copy link), a `framedrop://` or
|
||||
- **Add games → Add from a link…** takes the button's address (right-click → Copy link), a `framedrop://` or
|
||||
`frameport://` link, a manifest (`.json`) or a direct link to an APK, a Linux build or a Windows program. Use it on
|
||||
macOS, where web pages can't hand links to FramePort yet.
|
||||
- **Settings → Install links** has one switch for `framedrop://` links (the buttons) and one for FramePort's own
|
||||
@@ -125,7 +130,8 @@ sideloader, documented at framedropvr.com/docs). FramePort understands the same
|
||||
(`{"schema": "framedrop.install/v1", "name": "…", "files": [{"url": "https://…", "sha256": "…"}]}`). FramePort
|
||||
also reads an optional `"frameport": {"description": "…", "icon": "https://….png"}` object (FrameDrop ignores
|
||||
it): the install question then shows the icon and description, and they become the game's icon and "About this
|
||||
game" text when no store has them. Without a manifest (a bare file link) FramePort guesses the title from the
|
||||
game" text when no store has them. For your page there's an "Install with FramePort" button:
|
||||
[INSTALL_BUTTON.md](INSTALL_BUTTON.md). Without a manifest (a bare file link) FramePort guesses the title from the
|
||||
file name and replaces it with the app's own name once it's downloaded.
|
||||
- Only `https://` links to public servers are used (plain `http://` only on this PC, for testing); links with a
|
||||
user name or password, or pointing into your local network, are refused. Only install from sites you trust.
|
||||
@@ -139,7 +145,7 @@ reality), showing only what matters for that game. Changes are kept with the gam
|
||||
|
||||
## Typing on the Frame
|
||||
|
||||
- **Type on Frame** (its own tab in the sidebar; also on the Steam Frame page and in a game's menu): while the tab is
|
||||
- **Type on Frame** (its own tab in the sidebar; also on the Steam Frame page): while the tab is
|
||||
open, this computer's keyboard works as a keyboard plugged into the Frame. Select a text field in the headset (in
|
||||
an app, Steam or the desktop) and type; Esc and shortcuts go to the Frame too. Paste longer text into the box to
|
||||
type it in one go (US keyboard layout). Opening another tab disconnects the keyboard.
|
||||
@@ -190,7 +196,7 @@ Command line: `frameport update` (`--check` only checks, exit code 10 = update a
|
||||
## PC VR games
|
||||
|
||||
PC VR games are Windows VR games (OpenXR, SteamVR or Oculus). Scan a folder of them (one folder per game) or use
|
||||
**Add games → Add one game folder…**. FramePort finds the game's program and asks when there is more than one
|
||||
**Add games → Add a PC game folder…**. FramePort finds the game's program and asks when there is more than one
|
||||
candidate. **Already patched** on a game page installs a copy unchanged. Oculus-only games need Revive: FramePort uses
|
||||
an installed Revive, or downloads a portable copy.
|
||||
|
||||
@@ -201,7 +207,7 @@ an installed Revive, or downloads a portable copy.
|
||||
on the game page.
|
||||
- Games that use the Oculus Platform SDK check the licence through the Oculus app, so they run on the PC only.
|
||||
|
||||
**Windows games without VR:** **Add games → Add one game folder…** with the game's folder (pick the program that
|
||||
**Windows games without VR:** **Add games → Add a PC game folder…** with the game's folder (pick the program that
|
||||
starts it if asked). FramePort installs it on the Frame and Proton runs it as a window, like Steam's own Windows games;
|
||||
it shows up in the Frame's Steam library tagged "Windows game on Frame". Whether a game runs depends on Proton on ARM
|
||||
(x86 games run through emulation).
|
||||
@@ -249,7 +255,7 @@ Command line: `frameport frame send <files> --dest videos` (`frameport frame sto
|
||||
|
||||
## Sharing a working game, reporting a problem
|
||||
|
||||
- **Share working config…** (game menu): opens a prefilled GitHub issue with the game's patches and settings. Accepted
|
||||
- **Share working recipe…** (game menu): opens a prefilled GitHub issue with the game's patches and settings. Accepted
|
||||
configs become built-in recipes. Untested games ask on their page once they've been installed or tested: **It
|
||||
works**, **It has issues** or **It doesn't run**.
|
||||
- **Report a problem…** (game menu, or Settings → Problems and feedback): saves a diagnostics zip to Documents (logs,
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# "Install with FramePort" button
|
||||
|
||||
A button for web pages and READMEs that opens a game straight in FramePort. Clicking it hands FramePort an install
|
||||
link; FramePort shows what it would download and asks before it does anything (see
|
||||
[Install links](INSTALL.md#install-links-install-with-framedrop-buttons)).
|
||||
|
||||
<p>
|
||||
<img src="badges/install-with-frameport-animated.svg" alt="Install with FramePort" width="216" height="60">
|
||||
</p>
|
||||
|
||||
## Files
|
||||
|
||||
All files are in [`docs/badges/`](badges/). Each SVG is self-contained (no external fonts or images), 216 × 60.
|
||||
|
||||
| File | Use it for |
|
||||
|---|---|
|
||||
| [`install-with-frameport.svg`](badges/install-with-frameport.svg) | Everywhere. No motion. |
|
||||
| [`install-with-frameport-animated.svg`](badges/install-with-frameport-animated.svg) | GitHub READMEs and other pages that only allow images. The glow plays by itself every 6 seconds: blue swells from the left, the portal between "Frame" and "Port" flares, then orange swells on the right. |
|
||||
| [`install-with-frameport-hover.svg`](badges/install-with-frameport-hover.svg) | Websites where you can paste HTML. The glow brightens and the middle portal lights up while the pointer is on the button. It only reacts to the mouse when the SVG code is placed in the page itself (see below). |
|
||||
| [`install-with-frameport@2x.png`](badges/install-with-frameport@2x.png) | Places without SVG support (some forums, email). 432 × 120; show it at 216 × 60. |
|
||||
|
||||
Both animated versions stop moving for visitors who turn on reduced motion in their system settings.
|
||||
|
||||
## The link
|
||||
|
||||
The button links to an install link, which names either a manifest or one file:
|
||||
|
||||
```
|
||||
frameport://install?manifest=<URL-encoded https address of a manifest .json>
|
||||
frameport://install?url=<URL-encoded https address of an .apk, a Linux build (.zip, .tar.*, .AppImage) or a Windows .exe>
|
||||
```
|
||||
|
||||
The manifest is the FrameDrop format, which FramePort reads as it is:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "framedrop.install/v1",
|
||||
"name": "My Game",
|
||||
"files": [{ "url": "https://example.com/my-game.apk", "sha256": "<64 hex digits>" }],
|
||||
"frameport": { "description": "One sentence about the game.", "icon": "https://example.com/icon.png" }
|
||||
}
|
||||
```
|
||||
|
||||
`name` becomes the game's title in Steam. `sha256` is optional but recommended: FramePort checks the download
|
||||
against it. The `frameport` object is optional and ignored by FrameDrop; its icon and description are shown in the
|
||||
install question. Only public `https://` addresses are accepted.
|
||||
|
||||
To build a link from Python: `frameport.deeplink.make_link(manifest_url="https://…/my-game.json")`.
|
||||
|
||||
## On a website
|
||||
|
||||
Image version (any page):
|
||||
|
||||
```html
|
||||
<a href="frameport://install?manifest=https%3A%2F%2Fexample.com%2Fmy-game.json">
|
||||
<img src="install-with-frameport.svg" alt="Install with FramePort" width="216" height="60">
|
||||
</a>
|
||||
```
|
||||
|
||||
Hover version: paste the contents of `install-with-frameport-hover.svg` inside the link instead of the `<img>`, and
|
||||
give the link an accessible name:
|
||||
|
||||
```html
|
||||
<a href="frameport://install?manifest=https%3A%2F%2Fexample.com%2Fmy-game.json" aria-label="Install with FramePort">
|
||||
<svg …>…</svg> <!-- the whole file -->
|
||||
</a>
|
||||
```
|
||||
|
||||
Host the files yourself, or load them from jsDelivr, which serves them with the right content type:
|
||||
`https://cdn.jsdelivr.net/gh/spoopyghosty0/frameport@main/docs/badges/install-with-frameport.svg` (replace `main`
|
||||
with a release tag such as `v0.12.0` to pin a version; jsDelivr caches `@main` for up to 12 hours).
|
||||
|
||||
## In a GitHub README
|
||||
|
||||
GitHub removes links that don't start with `https://` or `http://` from READMEs, so a `frameport://` link there is
|
||||
not clickable. Link the button to an `https://` page instead, for example your release page with instructions, or
|
||||
FrameDrop's install page, which opens `framedrop://` links (FramePort opens those too while Settings → Install links
|
||||
→ `framedrop://` is on):
|
||||
|
||||
```markdown
|
||||
[](https://framedropvr.com/install?manifest=https%3A%2F%2Fexample.com%2Fmy-game.json)
|
||||
```
|
||||
|
||||
Use the animated or still SVG; the hover version doesn't react inside a README, because GitHub shows SVGs as
|
||||
images.
|
||||
|
||||
## If a visitor doesn't have FramePort
|
||||
|
||||
A `frameport://` link does nothing visible (or shows the browser's "no app for this link" message) when FramePort
|
||||
isn't installed. Put a line next to the button such as "Needs [FramePort](https://github.com/spoopyghosty0/frameport)
|
||||
on Windows or Linux." On macOS, web pages can't hand links to FramePort yet: users paste the link into Add games →
|
||||
Add from a link….
|
||||
|
||||
## Usage rules
|
||||
|
||||
- Keep the alt text "Install with FramePort".
|
||||
- Don't recolor, stretch, crop or redraw the button, and don't show it smaller than 40 px tall.
|
||||
- Leave some space around it (at least 8 px) so it doesn't touch other buttons.
|
||||
- It works on light and dark pages as it is; there is no light version.
|
||||
@@ -103,7 +103,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
|---|---|---|
|
||||
| 2D Android app: Steam says it's running but nothing shows | Lepton runs apps headless unless the app folder has `lepton-show-flatscreen` | FramePort adds it for apps without VR (agent v28+); reinstall apps installed before |
|
||||
| A phone/tablet app shows nothing in the headset, or a VR app opens as a flat window | FramePort's VR/2D guess (`vr_kind`) is wrong for this app | patch `device.display_mode` → **Flat window** or **VR** (Customize → "Show as VR or as a flat window"), then Update on Frame |
|
||||
| "Install with FrameDrop" button opens FrameDrop (or nothing) instead of FramePort | another program owns `framedrop://`, or the switch is off, or macOS (Flet can't receive links there) | Settings → Install links → **Use FramePort for these links**; else Add games → Install from a link… (paste the button's address) |
|
||||
| "Install with FrameDrop" button opens FrameDrop (or nothing) instead of FramePort | another program owns `framedrop://`, or the switch is off, or macOS (Flet can't receive links there) | Settings → Install links → **Use FramePort for these links**; else Add games → Add from a link… (paste the button's address) |
|
||||
| 2D Android app: back/home/recents buttons cover the app's own buttons | Android's navigation bar | patch `device.hide_navbar` (on by default for apps without VR) sets `qemu.hw.mainkeys=1`; reinstall to apply |
|
||||
| Black screen, audio works, GLES engine with direct VrApi | Mesa rejects Quest-style GLSL | `frame.gl_shim` (logs `GLShim: SHADER COMPILE FAILED` + source lines) |
|
||||
| Black screen, audio works, log `Unsupported VrApi layer type N` | bridge drops frames containing that layer | extend the bridge (cylinder=3 is converted to a quad already) |
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# Screenshots and videos
|
||||
|
||||
The pictures in the docs and the videos are rendered by scripts, never taken by hand. The scripts show the real
|
||||
FramePort GUI with a demo library and a pretend Steam Frame, drive it the way a person would, and film or photograph
|
||||
it:
|
||||
|
||||
| What | Source | Output |
|
||||
|---|---|---|
|
||||
| Docs screenshots | `docs/showcase/shots.yaml` | `docs/images/*.png` |
|
||||
| Demo tour (about 95 s) | `docs/showcase/videos/tour.yaml` | `docs/media/frameport-tour.mp4` (+ `.jpg` poster), `docs/images/tour-teaser.webp` (README) |
|
||||
| Install tutorial (about 90 s) | `docs/showcase/videos/install.yaml` | `docs/media/frameport-install.mp4` (+ `.jpg` poster) |
|
||||
|
||||
Nothing comes from anyone's own library. The demo library (`docs/showcase/demo-library.yaml`) lists real catalog
|
||||
games, so recipes and patches are the ones FramePort really uses. Their technical analysis (`demo-analyses.json`:
|
||||
engine, VR API, libraries, sizes) was exported from real APK analyses without any paths. Art, in-game screenshots
|
||||
and store details come from the same public sources the app uses and are cached in `~/.cache/frameport-showcase`.
|
||||
The renderer refuses to run in FramePort's own data folder, scans the demo data for home paths and IP addresses
|
||||
first, and stops when a store didn't send art (placeholders never reach the docs; `--allow-missing-art` overrides
|
||||
that). Frame discovery is switched off during a render (no real device on your network can appear), and the setup
|
||||
command shows placeholders for the address and code (each PC has its own), never this computer's.
|
||||
|
||||
## Running it
|
||||
|
||||
You need the dev extras, Chromium for Playwright and ffmpeg:
|
||||
|
||||
```
|
||||
UV_LINK_MODE=copy uv sync --extra dev
|
||||
uv run playwright install chromium # once
|
||||
uv run python scripts/showcase/render_docs.py # all screenshots → docs/images (changed ones only)
|
||||
uv run python scripts/showcase/render_docs.py --only game,monitor --out /tmp/shots
|
||||
uv run python scripts/showcase/record_video.py install --draft # quick 720p check of a storyboard edit
|
||||
uv run python scripts/showcase/record_video.py # every video → docs/media (+ the README teaser)
|
||||
uv run python scripts/showcase/record_video.py tour install # some
|
||||
```
|
||||
|
||||
Every screenshot is rendered twice, each in a fresh window, and kept only when both agree (the headless GPU now and
|
||||
then draws a glyph wrong); a third render settles a disagreement, and `--fast` renders once for trying out an edit.
|
||||
A shot whose steps fail is tried again and never written. A screenshot is rewritten only when it visibly changed
|
||||
(`render_docs.changed`: anti-aliasing noise doesn't count), so running it twice changes nothing. `--check` writes
|
||||
nothing and exits 1 when a docs image is out of date.
|
||||
|
||||
For videos, `--names` prints what can be clicked after each scene and `SHOWCASE_DEBUG=1` prints every step with its
|
||||
start time (which step waited); `--draft --scenes a,b` records only some scenes. A video is encoded at the best
|
||||
quality that fits its `budget_mb` (12 by default), a teaser at 4 MB.
|
||||
|
||||
## Videos
|
||||
|
||||
One storyboard per video in `docs/showcase/videos/<name>.yaml`; adding a file adds a video (CI and releases pick it
|
||||
up by itself). The output must be `docs/media/frameport-<name>.mp4`: releases attach it as `FramePort-<name>.mp4`.
|
||||
|
||||
```yaml
|
||||
output: docs/media/frameport-install.mp4
|
||||
teaser: docs/images/tour-teaser.webp # optional: a looping WebP from the scenes' `teaser` parts
|
||||
budget_mb: 12
|
||||
poster_at: 9 # the poster frame, seconds after the title card
|
||||
start:
|
||||
profile: fresh # demo = FramePort in use (games installed, BONELAB running); fresh = its first start
|
||||
frame: disconnected # connected (default) or disconnected
|
||||
route: welcome # the page filming starts on (default library)
|
||||
stream: live # the monitor stream: live (default) or frozen
|
||||
setup: # steps before filming starts (a failure stops the recording)
|
||||
- hook: {name: first_run, args: ["D:/Games", 1.4]}
|
||||
vars: {game: com.playful.LuckysTale} # ${game} in any step
|
||||
title: {heading: Installing FramePort, line: …, seconds: 3.4}
|
||||
end: {heading: You're set, line: …, footer: github.com/spoopyghosty0/frameport, seconds: 4}
|
||||
scenes:
|
||||
- name: connect # a filmed scene
|
||||
caption: ["Connect your Steam Frame", "Once: FramePort shows a command to run on the Frame"]
|
||||
teaser: [0.6, 4.0] # optional: this part goes into the teaser
|
||||
hold: 1.5 # seconds of filming after the last step (default 0.6)
|
||||
steps: [...]
|
||||
- name: on-the-frame # an instruction card: for what happens outside FramePort
|
||||
seconds: 10
|
||||
card:
|
||||
eyebrow: "Step 3 · On the Frame, first time only"
|
||||
heading: Run the setup command
|
||||
steps: ["In the SteamVR dashboard: **Launch a program** → **Desktop**", …] # **bold** = a button or menu
|
||||
code: "curl -fsS <your-PC-address>:8765/<one-time-code> | bash"
|
||||
note: "Your address and code differ."
|
||||
```
|
||||
|
||||
Filmed scenes are one continuous session: each starts where the last one left off. Cards are rendered at the end
|
||||
and slotted in, with crossfades between everything. The `fresh` profile starts FramePort as on a new computer: an
|
||||
empty library, the welcome screen and a Frame that isn't set up. Its games wait for the pretend folder scan.
|
||||
|
||||
## Writing steps
|
||||
|
||||
Shots and scenes use one step language (`scripts/showcase/steps.py`). A step is a one-key mapping:
|
||||
|
||||
```yaml
|
||||
- go: monitor # a sidebar route
|
||||
- nav: "Monitor" # click that tab (checked: the page really changed)
|
||||
- open_game: ${game} # or {package: …, advanced: true}
|
||||
- call: {fn: settings_dialog, args: ["${game}"]} # any app method
|
||||
- hover: "Batman: Arkham Shadow" # the pointer: by name…
|
||||
- click: {name: "Lucky's Tale", dy: 0.35} # …offset inside the element (fraction of its size, or px)
|
||||
- click: "Install on Frame" # right_click, double_click, drag: [from, …, to]
|
||||
- type: "ri" # press: Escape
|
||||
- wait_for: "BONELAB · 2026-10-04 21:50"
|
||||
- wait: 1.2
|
||||
- hook: {name: held_install, args: ["${new_game}"]} # the pretend Frame's scripted events
|
||||
```
|
||||
|
||||
Elements are found by name through Flutter's accessibility tree: their visible text, a tooltip or a semantics
|
||||
label. Exact names win over prefixes, and buttons and cards win over plain text. When several match, the innermost
|
||||
one wins (a list carries the text of its rows; the row is meant). Icon-only buttons need a tooltip to be found,
|
||||
which also helps screen readers. The pointer moves on eased, slightly curved paths and is drawn into the picture,
|
||||
with a ring on every click. To open a game from a cover card, click its title (`dy: 0.35`): the card's middle is its
|
||||
Play/Install button.
|
||||
|
||||
Hooks (`steps.HOOKS`) cover what a real Frame would do:
|
||||
- `fake_install`: an install through the real job queue with every real stage name and a launch test that passes.
|
||||
- `held_install`: an install that stops mid-upload, for screenshots of the progress.
|
||||
- `connect` and `disconnect`
|
||||
- `first_run`: a first start. The welcome screen's tool download is a pretend one, and "Scan a folder…" scans a
|
||||
folder at once (the native folder picker can't be scripted).
|
||||
- `pairing_done`: the Frame ran the setup command, so FramePort connects.
|
||||
- `live_stream`: a test picture through the real relay.
|
||||
- `monitor_details`, `type_tab`, `select_files` and `settings_section`.
|
||||
|
||||
In a video, clicking Install runs the scripted install, and the game is then installed on the pretend Frame.
|
||||
|
||||
Pictures must not change from one run to the next:
|
||||
- Screenshot and file dates are fixed.
|
||||
- The Monitor's stream stops after its two-minute history.
|
||||
- The pointer leaves the page before a still picture is taken.
|
||||
- Each shot gets a fresh window and browser.
|
||||
- A picture is taken once the page has stopped changing.
|
||||
|
||||
Live data, such as the live view's relay port and data rate, doesn't belong in a docs screenshot.
|
||||
|
||||
## How it runs on GitHub
|
||||
|
||||
The `showcase` workflow (`.github/workflows/showcase.yml`):
|
||||
1. **When it runs:** on pushes to `main` that touch the UI, its translations or the showcase files, and on
|
||||
**Run workflow**.
|
||||
2. **What it renders:** the screenshots every time. Videos when their storyboard changed (all of them when the
|
||||
scripts changed), or the ones named on a manual run (`all`, or e.g. `tour install`). UI tweaks alone don't
|
||||
re-commit 10 MB videos.
|
||||
3. **What happens next:** every render is uploaded as the run's `showcase` artifact. When a picture changed, the
|
||||
workflow opens or updates the pull request on branch `showcase/update`, which you review and merge.
|
||||
|
||||
Releases attach every committed video as `FramePort-<name>.mp4`.
|
||||
|
||||
## Gallery
|
||||
|
||||
These are renders the README doesn't show (yet):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
@@ -0,0 +1,61 @@
|
||||
# Themes
|
||||
|
||||
FramePort comes with three colour themes, all dark:
|
||||
|
||||
| Theme | Look |
|
||||
|---|---|
|
||||
| **Portal** (default) | The logo's two portals: orange for actions and the current selection, blue for secondary actions, progress and the PC side. |
|
||||
| **Portal (OLED)** | Portal on true black, for OLED screens. |
|
||||
| **Original** | FramePort's first look, with a violet accent. |
|
||||
|
||||
Switch in **Settings → Appearance**. The change applies at once.
|
||||
|
||||
## Your own theme
|
||||
|
||||
A theme is a small JSON file. To make one:
|
||||
|
||||
1. In **Settings → Appearance**, pick the theme closest to what you want and click **Copy this theme as a file**.
|
||||
2. Paste it into a text editor and save it as `something.json`.
|
||||
3. Change the name and the colours you want different. You can delete every colour you keep: missing colours come
|
||||
from the `base` theme.
|
||||
4. Back in **Settings → Appearance**, click **Install theme file…** and choose the file. FramePort checks it,
|
||||
switches to it and keeps a copy in its data folder (`themes/`), so you can delete the original.
|
||||
|
||||
To remove an installed theme, click the bin icon on its card.
|
||||
|
||||
### Format
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Ember & Ice",
|
||||
"base": "portal",
|
||||
"dual": true,
|
||||
"colors": {
|
||||
"ACCENT": "#FF5A36",
|
||||
"SECONDARY": "#5CE1E6"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `name` | Shown on the theme's card (up to 40 characters). |
|
||||
| `base` | The built-in theme that fills in every colour the file leaves out: `portal` (default), `portal_oled` or `original`. |
|
||||
| `dual` | `true`: two-colour touches like Portal's (blue-to-orange sidebar edge, two-colour "FramePort", the selected tab's fade, blue secondary buttons). `false`: one accent, like Original. Default: the base's. |
|
||||
| `colors` | Any of the colours below, as `#RRGGBB` or `#RGB`. Names may be upper or lower case. |
|
||||
|
||||
| Colour | Used for |
|
||||
|---|---|
|
||||
| `BG` | Window background |
|
||||
| `SIDEBAR` | Sidebar and activity panel |
|
||||
| `SURFACE`, `SURFACE_2`, `SURFACE_3` | Cards; raised and hovered parts; inputs and chips |
|
||||
| `BORDER`, `BORDER_STRONG` | Outlines |
|
||||
| `TEXT`, `TEXT_2`, `TEXT_3` | Main text; secondary text; captions and disabled text |
|
||||
| `ACCENT`, `ACCENT_SOFT`, `ON_ACCENT` | Main buttons and the current selection; its tint; text on it |
|
||||
| `SECONDARY`, `SECONDARY_SOFT` | Secondary buttons, progress, switch tracks; its tint |
|
||||
| `OK`, `WARN`, `ERROR`, `INFO` | Status: works, needs attention, failed, information |
|
||||
| `PC` | PC VR games and "on this PC" |
|
||||
|
||||
FramePort refuses a theme file it can't show well, and says why: a light window background (FramePort is dark only),
|
||||
text that's hard to read on cards, an unknown colour name or a value that isn't a colour. An example is in
|
||||
[`themes/example-theme.json`](themes/example-theme.json).
|
||||
@@ -0,0 +1,28 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="216" height="60" viewBox="0 0 216 60" role="img" aria-label="Install with FramePort"><title>Install with FramePort</title><style>.fp-wb,.fp-wo{transform-box:view-box}
|
||||
.fp-wb{transform-origin:0 0;animation:fp-wb 6s ease-in-out infinite}
|
||||
.fp-wo{transform-origin:216px 0;animation:fp-wo 6s ease-in-out infinite}
|
||||
.fp-core{animation:fp-core 6s ease-in-out infinite}
|
||||
@keyframes fp-wb{0%,10%,100%{opacity:.45;transform:scaleX(1)}32%{opacity:1;transform:scaleX(1.5)}54%{opacity:.3;transform:scaleX(1)}}
|
||||
@keyframes fp-core{0%,28%,100%{opacity:0}42%{opacity:1}60%{opacity:0}}
|
||||
@keyframes fp-wo{0%,38%,100%{opacity:.6;transform:scaleX(1)}60%{opacity:1;transform:scaleX(1.4)}84%{opacity:.6;transform:scaleX(1)}}
|
||||
@media (prefers-reduced-motion:reduce){.fp-wb,.fp-wo,.fp-core{animation:none!important}}</style><defs>
|
||||
<linearGradient id="fab" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".46"/><stop offset=".55" stop-color="#3AA8FF" stop-opacity="0"/></linearGradient>
|
||||
<linearGradient id="fao" x1="0" y1="0" x2="1" y2="0"><stop offset=".45" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".34"/></linearGradient>
|
||||
<radialGradient id="far" gradientUnits="userSpaceOnUse" cx="122" cy="39" r="46" gradientTransform="translate(122 39) scale(1 .62) translate(-122 -39)"><stop offset="0" stop-color="#FFE2BD" stop-opacity=".42"/><stop offset=".25" stop-color="#FF8A1F" stop-opacity=".2"/><stop offset=".6" stop-color="#3AA8FF" stop-opacity=".08"/><stop offset="1" stop-color="#3AA8FF" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="fac"><rect x="1" y="1" width="214" height="58" rx="11.5"/></clipPath></defs>
|
||||
<rect x=".5" y=".5" width="215" height="59" rx="12" fill="#0D0E12" stroke="#2A2D37"/>
|
||||
<g clip-path="url(#fac)"><rect class="fp-wb" x="1" y="1" width="214" height="58" fill="url(#fab)" opacity=".45"/><rect class="fp-wo" x="1" y="1" width="214" height="58" fill="url(#fao)" opacity=".6"/><rect class="fp-core" x="1" y="1" width="214" height="58" fill="url(#far)" opacity="0"/></g>
|
||||
<g transform="translate(10 10) scale(0.625)">
|
||||
<defs><linearGradient id="fal0" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".18"/><stop offset=".5" stop-color="#3AA8FF" stop-opacity="0"/><stop offset=".5" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".18"/></linearGradient>
|
||||
<linearGradient id="fal1" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0"><stop offset=".3" stop-color="#3AA8FF"/><stop offset=".7" stop-color="#FF8A1F"/></linearGradient>
|
||||
<clipPath id="fal2"><polygon points="-30,-30 49.145,-30 8.855,94 -30,94"/></clipPath><clipPath id="fal3"><polygon points="55.145,-30 94,-30 94,94 14.855,94"/></clipPath></defs>
|
||||
<rect width="64" height="64" rx="15" fill="#101218"/><rect width="64" height="64" rx="15" fill="url(#fal0)"/>
|
||||
<g clip-path="url(#fal2)"><path d="M34 15H9a3 3 0 0 0-3 3v20a3 3 0 0 0 3 3h25z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><rect class="fp-scr" x="10.5" y="19.5" width="24" height="17" rx="1" fill="#3AA8FF" fill-opacity="0.35"/><path d="M18 41v6M11 47h14" stroke="#ECEDF3" stroke-width="3" stroke-linecap="round"/></g>
|
||||
<g clip-path="url(#fal3)"><path d="M56.5 31.5H58.5" stroke="#ECEDF3" stroke-width="3.4" stroke-linecap="round"/><path d="M22 21h27a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7a3 3 0 0 1-2.6 1.5H22z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><g class="fp-lens"><ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/><ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/></g></g>
|
||||
<g transform="rotate(18 32 32)"><g class="fp-ptl"><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="#08090C" stroke="#08090C" stroke-width="5.8"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="none" stroke="url(#fal1)" stroke-opacity=".25" stroke-width="6.46" class="fp-halo"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="url(#fal1)" fill-opacity="0.14" stroke="url(#fal1)" stroke-width="3.4"/></g></g></g>
|
||||
<text x="60" y="25" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="9.5" font-weight="600" letter-spacing="1.4" fill="#A7ABB7">INSTALL WITH</text>
|
||||
<text x="60" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#FF8A1F" textLength="53.1" lengthAdjust="spacingAndGlyphs">Frame</text>
|
||||
<g transform="translate(115.25999999999999 29.36) scale(0.8035714285714286)"><g class="fp-ptl"><defs><linearGradient id="fawr" gradientUnits="userSpaceOnUse" x1="2" y1="0" x2="14" y2="0"><stop offset=".3" stop-color="#FF8A1F"/><stop offset=".7" stop-color="#3AA8FF"/></linearGradient></defs>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="none" stroke="url(#fawr)" stroke-opacity=".35" stroke-width="5" class="fp-halo"/>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="#0D0E12" stroke="url(#fawr)" stroke-width="2.6"/></g></g>
|
||||
<text x="130.27714285714285" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#3AA8FF" textLength="36.9" lengthAdjust="spacingAndGlyphs">Port</text></svg>
|
||||
|
After Width: | Height: | Size: 5.2 KiB |
@@ -0,0 +1,26 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="216" height="60" viewBox="0 0 216 60" role="img" aria-label="Install with FramePort"><title>Install with FramePort</title><style>.fp-wb,.fp-wo{transform-box:view-box;transition:opacity .5s ease,transform .7s cubic-bezier(.2,.8,.2,1)}
|
||||
.fp-wb{transform-origin:0 0}.fp-wo{transform-origin:216px 0}
|
||||
.fp-core{transition:opacity .6s ease}
|
||||
svg:hover .fp-wb{opacity:1;transform:scaleX(1.4)}svg:hover .fp-wo{opacity:1;transform:scaleX(1.3)}
|
||||
svg:hover .fp-core{opacity:1}
|
||||
@media (prefers-reduced-motion:reduce){.fp-wb,.fp-wo,.fp-core{transition:none!important}}</style><defs>
|
||||
<linearGradient id="fhb" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".46"></stop><stop offset=".55" stop-color="#3AA8FF" stop-opacity="0"></stop></linearGradient>
|
||||
<linearGradient id="fho" x1="0" y1="0" x2="1" y2="0"><stop offset=".45" stop-color="#FF8A1F" stop-opacity="0"></stop><stop offset="1" stop-color="#FF8A1F" stop-opacity=".34"></stop></linearGradient>
|
||||
<radialGradient id="fhr" gradientUnits="userSpaceOnUse" cx="122" cy="39" r="46" gradientTransform="translate(122 39) scale(1 .62) translate(-122 -39)"><stop offset="0" stop-color="#FFE2BD" stop-opacity=".42"></stop><stop offset=".25" stop-color="#FF8A1F" stop-opacity=".2"></stop><stop offset=".6" stop-color="#3AA8FF" stop-opacity=".08"></stop><stop offset="1" stop-color="#3AA8FF" stop-opacity="0"></stop></radialGradient>
|
||||
<clipPath id="fhc"><rect x="1" y="1" width="214" height="58" rx="11.5"></rect></clipPath></defs>
|
||||
<rect x=".5" y=".5" width="215" height="59" rx="12" fill="#0D0E12" stroke="#2A2D37"></rect>
|
||||
<g clip-path="url(#fhc)"><rect class="fp-wb" x="1" y="1" width="214" height="58" fill="url(#fhb)" opacity=".45"></rect><rect class="fp-wo" x="1" y="1" width="214" height="58" fill="url(#fho)" opacity=".6"></rect><rect class="fp-core" x="1" y="1" width="214" height="58" fill="url(#fhr)" opacity="0"></rect></g>
|
||||
<g transform="translate(10 10) scale(0.625)">
|
||||
<defs><linearGradient id="fhl0" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".18"></stop><stop offset=".5" stop-color="#3AA8FF" stop-opacity="0"></stop><stop offset=".5" stop-color="#FF8A1F" stop-opacity="0"></stop><stop offset="1" stop-color="#FF8A1F" stop-opacity=".18"></stop></linearGradient>
|
||||
<linearGradient id="fhl1" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0"><stop offset=".3" stop-color="#3AA8FF"></stop><stop offset=".7" stop-color="#FF8A1F"></stop></linearGradient>
|
||||
<clipPath id="fhl2"><polygon points="-30,-30 49.145,-30 8.855,94 -30,94"></polygon></clipPath><clipPath id="fhl3"><polygon points="55.145,-30 94,-30 94,94 14.855,94"></polygon></clipPath></defs>
|
||||
<rect width="64" height="64" rx="15" fill="#101218"></rect><rect width="64" height="64" rx="15" fill="url(#fhl0)"></rect>
|
||||
<g clip-path="url(#fhl2)"><path d="M34 15H9a3 3 0 0 0-3 3v20a3 3 0 0 0 3 3h25z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"></path><rect class="fp-scr" x="10.5" y="19.5" width="24" height="17" rx="1" fill="#3AA8FF" fill-opacity="0.35"></rect><path d="M18 41v6M11 47h14" stroke="#ECEDF3" stroke-width="3" stroke-linecap="round"></path></g>
|
||||
<g clip-path="url(#fhl3)"><path d="M56.5 31.5H58.5" stroke="#ECEDF3" stroke-width="3.4" stroke-linecap="round"></path><path d="M22 21h27a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7a3 3 0 0 1-2.6 1.5H22z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"></path><g class="fp-lens"><ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"></ellipse><ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"></ellipse></g></g>
|
||||
<g transform="rotate(18 32 32)"><g class="fp-ptl"><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="#08090C" stroke="#08090C" stroke-width="5.8"></ellipse><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="none" stroke="url(#fhl1)" stroke-opacity=".25" stroke-width="6.46" class="fp-halo"></ellipse><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="url(#fhl1)" fill-opacity="0.14" stroke="url(#fhl1)" stroke-width="3.4"></ellipse></g></g></g>
|
||||
<text x="60" y="25" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="9.5" font-weight="600" letter-spacing="1.4" fill="#A7ABB7">INSTALL WITH</text>
|
||||
<text x="60" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#FF8A1F" textLength="53.1" lengthAdjust="spacingAndGlyphs">Frame</text>
|
||||
<g transform="translate(115.25999999999999 29.36) scale(0.8035714285714286)"><g class="fp-ptl"><defs><linearGradient id="fhwr" gradientUnits="userSpaceOnUse" x1="2" y1="0" x2="14" y2="0"><stop offset=".3" stop-color="#FF8A1F"></stop><stop offset=".7" stop-color="#3AA8FF"></stop></linearGradient></defs>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="none" stroke="url(#fhwr)" stroke-opacity=".35" stroke-width="5" class="fp-halo"></ellipse>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="#0D0E12" stroke="url(#fhwr)" stroke-width="2.6"></ellipse></g></g>
|
||||
<text x="130.27714285714285" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#3AA8FF" textLength="36.9" lengthAdjust="spacingAndGlyphs">Port</text></svg>
|
||||
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,21 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="216" height="60" viewBox="0 0 216 60" role="img" aria-label="Install with FramePort"><title>Install with FramePort</title><defs>
|
||||
<linearGradient id="fsb" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".46"/><stop offset=".55" stop-color="#3AA8FF" stop-opacity="0"/></linearGradient>
|
||||
<linearGradient id="fso" x1="0" y1="0" x2="1" y2="0"><stop offset=".45" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".34"/></linearGradient>
|
||||
<radialGradient id="fsr" gradientUnits="userSpaceOnUse" cx="122" cy="39" r="46" gradientTransform="translate(122 39) scale(1 .62) translate(-122 -39)"><stop offset="0" stop-color="#FFE2BD" stop-opacity=".42"/><stop offset=".25" stop-color="#FF8A1F" stop-opacity=".2"/><stop offset=".6" stop-color="#3AA8FF" stop-opacity=".08"/><stop offset="1" stop-color="#3AA8FF" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="fsc"><rect x="1" y="1" width="214" height="58" rx="11.5"/></clipPath></defs>
|
||||
<rect x=".5" y=".5" width="215" height="59" rx="12" fill="#0D0E12" stroke="#2A2D37"/>
|
||||
<g clip-path="url(#fsc)"><rect class="fp-wb" x="1" y="1" width="214" height="58" fill="url(#fsb)" opacity=".45"/><rect class="fp-wo" x="1" y="1" width="214" height="58" fill="url(#fso)" opacity=".6"/><rect class="fp-core" x="1" y="1" width="214" height="58" fill="url(#fsr)" opacity="0"/></g>
|
||||
<g transform="translate(10 10) scale(0.625)">
|
||||
<defs><linearGradient id="fsl0" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".18"/><stop offset=".5" stop-color="#3AA8FF" stop-opacity="0"/><stop offset=".5" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".18"/></linearGradient>
|
||||
<linearGradient id="fsl1" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0"><stop offset=".3" stop-color="#3AA8FF"/><stop offset=".7" stop-color="#FF8A1F"/></linearGradient>
|
||||
<clipPath id="fsl2"><polygon points="-30,-30 49.145,-30 8.855,94 -30,94"/></clipPath><clipPath id="fsl3"><polygon points="55.145,-30 94,-30 94,94 14.855,94"/></clipPath></defs>
|
||||
<rect width="64" height="64" rx="15" fill="#101218"/><rect width="64" height="64" rx="15" fill="url(#fsl0)"/>
|
||||
<g clip-path="url(#fsl2)"><path d="M34 15H9a3 3 0 0 0-3 3v20a3 3 0 0 0 3 3h25z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><rect class="fp-scr" x="10.5" y="19.5" width="24" height="17" rx="1" fill="#3AA8FF" fill-opacity="0.35"/><path d="M18 41v6M11 47h14" stroke="#ECEDF3" stroke-width="3" stroke-linecap="round"/></g>
|
||||
<g clip-path="url(#fsl3)"><path d="M56.5 31.5H58.5" stroke="#ECEDF3" stroke-width="3.4" stroke-linecap="round"/><path d="M22 21h27a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7a3 3 0 0 1-2.6 1.5H22z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><g class="fp-lens"><ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/><ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/></g></g>
|
||||
<g transform="rotate(18 32 32)"><g class="fp-ptl"><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="#08090C" stroke="#08090C" stroke-width="5.8"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="none" stroke="url(#fsl1)" stroke-opacity=".25" stroke-width="6.46" class="fp-halo"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="url(#fsl1)" fill-opacity="0.14" stroke="url(#fsl1)" stroke-width="3.4"/></g></g></g>
|
||||
<text x="60" y="25" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="9.5" font-weight="600" letter-spacing="1.4" fill="#A7ABB7">INSTALL WITH</text>
|
||||
<text x="60" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#FF8A1F" textLength="53.1" lengthAdjust="spacingAndGlyphs">Frame</text>
|
||||
<g transform="translate(115.25999999999999 29.36) scale(0.8035714285714286)"><g class="fp-ptl"><defs><linearGradient id="fswr" gradientUnits="userSpaceOnUse" x1="2" y1="0" x2="14" y2="0"><stop offset=".3" stop-color="#FF8A1F"/><stop offset=".7" stop-color="#3AA8FF"/></linearGradient></defs>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="none" stroke="url(#fswr)" stroke-opacity=".35" stroke-width="5" class="fp-halo"/>
|
||||
<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)" fill="#0D0E12" stroke="url(#fswr)" stroke-width="2.6"/></g></g>
|
||||
<text x="130.27714285714285" y="47" font-family="Segoe UI, Roboto, 'Helvetica Neue', Arial, sans-serif" font-size="18" font-weight="800" fill="#3AA8FF" textLength="36.9" lengthAdjust="spacingAndGlyphs">Port</text></svg>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 84 KiB After Width: | Height: | Size: 75 KiB |
|
Before Width: | Height: | Size: 365 KiB After Width: | Height: | Size: 417 KiB |
|
After Width: | Height: | Size: 505 KiB |
|
Before Width: | Height: | Size: 917 KiB After Width: | Height: | Size: 667 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 188 KiB After Width: | Height: | Size: 214 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 916 KiB After Width: | Height: | Size: 561 KiB |
|
Before Width: | Height: | Size: 643 KiB After Width: | Height: | Size: 596 KiB |
|
After Width: | Height: | Size: 846 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 283 KiB |
@@ -0,0 +1,64 @@
|
||||
# The demo library for the docs screenshots and the demo tour (built by scripts/showcase/demo_home.py into an
|
||||
# isolated FRAMEPORT_HOME; see docs/SHOWCASE.md). Real catalog games, so recipes, patches and store art are the
|
||||
# ones FramePort really uses; the technical analysis of each (engine, XR API, libraries, sizes) is in
|
||||
# demo-analyses.json, exported from real APK analyses without any paths. Nothing here is anyone's own data.
|
||||
#
|
||||
# Per game:
|
||||
# frame: on the pretend Frame: internal | sd | outdated (internal, but an older build: "Update on Frame");
|
||||
# left out = not installed
|
||||
# played: last played, days before the render (the Library sorts the "On your Frame" shelf by it)
|
||||
# added: added to the library, days before the render (default 30)
|
||||
# tested: the last launch test passed (default: when installed)
|
||||
# tags: user tags (store genres become tags by themselves)
|
||||
# title: overrides the catalog/store title
|
||||
# art: pick = the art a user gets from Find artwork's Meta result (when the store's own art is a placeholder)
|
||||
|
||||
frame:
|
||||
battery: 82 # %
|
||||
running: com.StressLevelZero.BONELAB # the game the Monitor tab and the sidebar's live card show (it needs
|
||||
# store screenshots: Take screenshot adds one of it)
|
||||
|
||||
games:
|
||||
- package: com.camouflaj.manta
|
||||
frame: internal
|
||||
played: 0.6
|
||||
tags: [Favorites]
|
||||
- package: com.Sanzaru.Wrath2
|
||||
art: pick # the store's image service has a placeholder cover for it: use the picker's Meta result
|
||||
frame: sd
|
||||
played: 1.2
|
||||
tags: [Favorites]
|
||||
- package: com.twistedpixelgames.PILO
|
||||
frame: internal
|
||||
played: 2.4
|
||||
- package: com.StressLevelZero.BONELAB
|
||||
frame: internal
|
||||
played: 0.05
|
||||
- package: com.vertigogames.ImpactDevelopment
|
||||
frame: outdated
|
||||
played: 4.5
|
||||
- package: com.CyanWorlds.Myst
|
||||
frame: sd
|
||||
played: 6
|
||||
- package: com.playful.LuckysTale
|
||||
frame: internal
|
||||
played: 9
|
||||
tags: [Favorites]
|
||||
- package: com.FuturLab.PowerWashSimulator
|
||||
frame: internal
|
||||
played: 12
|
||||
- package: com.CyanWorlds.Riven
|
||||
added: 2
|
||||
- package: com.FireproofStudios.TheRoomVR
|
||||
- package: com.NewFolderGames.IAmCat
|
||||
- package: com.BithellGames.Arcsmith
|
||||
- package: com.zenstudios.PFXVRQuest
|
||||
- package: com.Ubisoft.ACNexusVR
|
||||
- package: com.Solfar.InDeath
|
||||
- package: com.survios.Creed
|
||||
- package: com.crytek.climb2
|
||||
- package: com.thunderful.legobricktales
|
||||
- package: com.GhostlyBirdGames.BattleGlide
|
||||
- package: cn.vr4p.oculus4xvrplayerov
|
||||
- package: rift.rick_and_morty_virtual_rick_ality
|
||||
added: 5
|
||||
@@ -0,0 +1,109 @@
|
||||
# The docs screenshots: scripts/showcase/render_docs.py renders each into docs/images/<name>.png from the demo
|
||||
# library (demo-library.yaml) with a pretend Frame, and rewrites a file only when the picture really changed.
|
||||
# Steps: see scripts/showcase/steps.py. Each shot starts in a fresh window (its own app session).
|
||||
#
|
||||
# viewport: [w, h] browser size in px (default below); scale: UI scale (1.0)
|
||||
# crop: {dialog: true, pad}: the open dialog; {anchor: <name>, left, top, width, height}: a box placed
|
||||
# relative to the top-left corner of the element called <name> (left/top may be negative);
|
||||
# or {x, y, width, height} in page px
|
||||
# docs: where the image is used (checked by the tests: every image a doc shows has an entry here)
|
||||
|
||||
vars:
|
||||
game: com.camouflaj.manta # installed on the pretend Frame
|
||||
new_game: com.CyanWorlds.Riven # in the library, not installed yet
|
||||
|
||||
defaults:
|
||||
viewport: [1280, 820]
|
||||
|
||||
shots:
|
||||
- name: library
|
||||
docs: [README.md]
|
||||
steps:
|
||||
- go: library
|
||||
- wait_for: "On your Frame"
|
||||
- settle: true
|
||||
|
||||
- name: game
|
||||
docs: [docs/INSTALL.md, docs/SHOWCASE.md]
|
||||
viewport: [1280, 1100]
|
||||
steps:
|
||||
- open_game: ${game}
|
||||
- wait_for: "Where it's installed"
|
||||
|
||||
- name: game-settings
|
||||
docs: [docs/INSTALL.md]
|
||||
steps:
|
||||
- open_game: ${game}
|
||||
- call: {fn: settings_dialog, args: ["${game}"]}
|
||||
- wait_for: "Game settings"
|
||||
crop: {dialog: true}
|
||||
|
||||
- name: patches
|
||||
docs: [docs/COMPATIBILITY.md]
|
||||
viewport: [1280, 2600]
|
||||
steps:
|
||||
- open_game: {package: "${game}", advanced: true}
|
||||
- wait_for: "What FramePort will do"
|
||||
crop: {anchor: "What FramePort will do", left: -32, top: -12, width: 1044, height: 820}
|
||||
|
||||
- name: frame
|
||||
docs: [docs/COMPATIBILITY.md]
|
||||
steps:
|
||||
- go: frame
|
||||
- wait_for: "Ready to play"
|
||||
|
||||
- name: files
|
||||
docs: [docs/COMPATIBILITY.md]
|
||||
steps:
|
||||
- go: files
|
||||
- wait_for: "Upload files…"
|
||||
- wait: 1.0
|
||||
- hook: {name: select_files, args: [1, 2]}
|
||||
|
||||
- name: screenshots
|
||||
docs: [README.md]
|
||||
steps:
|
||||
- go: screenshots
|
||||
- wait_for: "Take screenshot"
|
||||
|
||||
- name: screenshot-viewer
|
||||
docs: [README.md]
|
||||
steps:
|
||||
- go: screenshots
|
||||
- wait_for: "Take screenshot"
|
||||
- wait: 1.5
|
||||
- call: {fn: screenshots_view.viewer, args: [0]}
|
||||
- wait_for: "Close"
|
||||
|
||||
- name: type-on-frame
|
||||
docs: [README.md]
|
||||
steps:
|
||||
- hook: type_tab
|
||||
- wait_for: "Keyboard connected"
|
||||
|
||||
- name: monitor
|
||||
docs: [README.md]
|
||||
viewport: [1280, 1150]
|
||||
steps:
|
||||
- go: monitor
|
||||
- wait_for: "Processes"
|
||||
|
||||
# newer screens (docs/SHOWCASE.md's gallery; the README picks what it needs)
|
||||
- name: live-view # idle: a running stream shows its relay's random port and the data rate (no stable picture)
|
||||
docs: [docs/SHOWCASE.md]
|
||||
steps:
|
||||
- go: live
|
||||
- wait_for: "What the player sees"
|
||||
|
||||
- name: install-progress
|
||||
docs: [docs/SHOWCASE.md]
|
||||
steps:
|
||||
- hook: {name: held_install, args: ["${new_game}"]}
|
||||
- open_game: ${new_game}
|
||||
- wait_for: "Cancel"
|
||||
|
||||
- name: appearance
|
||||
docs: [docs/SHOWCASE.md]
|
||||
steps:
|
||||
- go: settings
|
||||
- wait_for: "Portal (OLED)"
|
||||
@@ -0,0 +1,125 @@
|
||||
# The install tutorial: from the download to the first game on the Steam Frame (docs/INSTALL.md links it; every
|
||||
# release attaches it as FramePort-install.mp4). FramePort starts as on a new computer (the "fresh" demo profile:
|
||||
# empty library, welcome screen, no Frame set up); what happens outside FramePort (the download, a command typed
|
||||
# on the Frame) is told on instruction cards. Recorded by scripts/showcase/record_video.py; the format is in
|
||||
# docs/SHOWCASE.md ("Videos").
|
||||
|
||||
output: docs/media/frameport-install.mp4
|
||||
budget_mb: 12
|
||||
poster_at: 9
|
||||
start:
|
||||
profile: fresh # FramePort's first start
|
||||
frame: disconnected # the Frame isn't set up yet
|
||||
route: welcome
|
||||
setup:
|
||||
- hook: {name: first_run, args: ["D:/Games", 1.4]} # the tool download and the folder scan, at a watchable pace
|
||||
|
||||
vars:
|
||||
game: com.playful.LuckysTale
|
||||
|
||||
title:
|
||||
heading: Installing FramePort
|
||||
line: From the download to your first game on the Steam Frame
|
||||
seconds: 3.4
|
||||
end:
|
||||
heading: You're set
|
||||
line: Your game is in the Frame's Steam library. More help in docs/INSTALL.md
|
||||
footer: github.com/spoopyghosty0/frameport
|
||||
seconds: 4.0
|
||||
|
||||
scenes:
|
||||
- name: download
|
||||
seconds: 7.5
|
||||
card:
|
||||
eyebrow: "Step 1 · On your computer"
|
||||
heading: Download FramePort
|
||||
steps:
|
||||
- "Open **github.com/spoopyghosty0/frameport** → **Releases** → the latest one"
|
||||
- "Download the archive for your computer: **FramePort-windows-x64.zip**, **FramePort-macos-arm64.zip** or **FramePort-linux-x64.tar.gz**"
|
||||
- "Extract it anywhere. There's no installer and no admin rights are needed"
|
||||
|
||||
- name: first-start
|
||||
seconds: 7.5
|
||||
card:
|
||||
eyebrow: "Step 2 · First start"
|
||||
heading: Start FramePort
|
||||
steps:
|
||||
- "**Windows:** open **FramePort.exe**. At “Windows protected your PC” choose **More info** → **Run anyway**"
|
||||
- "**macOS:** right-click **FramePort.app** → **Open** → **Open**"
|
||||
- "**Linux:** run **FramePort/FramePort**"
|
||||
note: "FramePort is signed with a free certificate, so your system asks once."
|
||||
|
||||
- name: welcome
|
||||
caption: ["FramePort gets itself ready", "It downloads the tools it uses (Java, OVRPort, apksigner) by itself"]
|
||||
hold: 1.0
|
||||
steps:
|
||||
- wait: 1.0
|
||||
- hook: {name: wait_jobs, args: [40]}
|
||||
- wait_for: "Java, OVRPort and apksigner are ready."
|
||||
- wait: 1.0
|
||||
|
||||
- name: connect
|
||||
caption: ["Connect your Steam Frame", "Once: FramePort shows a command to run on the Frame"]
|
||||
hold: 1.5
|
||||
steps:
|
||||
- click: "Set up the Frame"
|
||||
- wait: 1.6
|
||||
- click: "Show setup command"
|
||||
- wait_for: "Waiting for your Frame"
|
||||
- wait: 1.0
|
||||
- hover: "Copy"
|
||||
- wait: 1.4
|
||||
|
||||
- name: on-the-frame
|
||||
seconds: 10
|
||||
card:
|
||||
eyebrow: "Step 3 · On the Frame, first time only"
|
||||
heading: Run the setup command
|
||||
steps:
|
||||
- "In the SteamVR dashboard: **Launch a program** → **Desktop**"
|
||||
- "Open the app menu (bottom left) → **System** → **Konsole**"
|
||||
- "Type the command FramePort shows and press **Enter**"
|
||||
code: "curl -fsS <your-PC-address>:8765/<one-time-code> | bash"
|
||||
note: "FramePort shows your PC's address and a one-time code in place of **<…>**. The desktop closes by itself after a few seconds (Steam restarts once); if Steam asks to install **Lepton**, confirm it. No password is needed."
|
||||
|
||||
- name: connected
|
||||
caption: ["Your Frame is connected", "From now on FramePort finds it by itself"]
|
||||
hold: 1.2
|
||||
steps:
|
||||
- hook: {name: pairing_done, args: [1.6]}
|
||||
- wait_for: "Ready to play"
|
||||
- wait: 1.2
|
||||
- hover: "Quest games (Lepton)"
|
||||
- wait: 1.6
|
||||
|
||||
- name: add-games
|
||||
caption: ["Add your games", "Point FramePort at the folder with your games"]
|
||||
hold: 1.0
|
||||
steps:
|
||||
- nav: "Library"
|
||||
- wait: 1.2
|
||||
- click: "Scan a folder…"
|
||||
- hook: {name: wait_jobs, args: [40]}
|
||||
- wait: 1.2
|
||||
- hover: {name: "Lucky's Tale", dy: 0.3}
|
||||
- wait: 1.0
|
||||
|
||||
- name: install
|
||||
caption: ["Install a game", "FramePort patches it, installs it and adds it to the Frame's Steam library"]
|
||||
hold: 1.2
|
||||
steps:
|
||||
- click: {name: "Lucky's Tale", dy: 0.35} # (the title: the card's middle is its Install button)
|
||||
- wait_for: "Where it's installed" # (the game page: a click that missed fails here)
|
||||
- wait: 1.2
|
||||
- click: "Install on Frame"
|
||||
- wait: 0.6
|
||||
- move: [860, 640]
|
||||
- hook: {name: wait_jobs, args: [45]}
|
||||
- wait: 1.0
|
||||
|
||||
- name: play
|
||||
caption: ["Play", "Start it from FramePort, or from Steam in the headset"]
|
||||
steps:
|
||||
- click: "Play on Frame"
|
||||
- wait: 2.6
|
||||
- park: true
|
||||
@@ -0,0 +1,134 @@
|
||||
# The demo tour: FramePort in use (README teaser, docs/media, every release as FramePort-tour.mp4).
|
||||
# Recorded by scripts/showcase/record_video.py; the storyboard format is in docs/SHOWCASE.md ("Videos").
|
||||
|
||||
output: docs/media/frameport-tour.mp4
|
||||
teaser: docs/images/tour-teaser.webp
|
||||
budget_mb: 12
|
||||
start:
|
||||
profile: demo # the library in use: games installed on the pretend Frame, BONELAB running
|
||||
frame: connected
|
||||
|
||||
vars:
|
||||
game: com.camouflaj.manta # installed on the pretend Frame
|
||||
new_game: com.CyanWorlds.Riven # installed during the tour
|
||||
|
||||
title:
|
||||
heading: FramePort
|
||||
line: Quest, Android and PC VR games on the Steam Frame
|
||||
seconds: 3.2
|
||||
end:
|
||||
heading: FramePort
|
||||
line: Open source · bring your own games
|
||||
footer: github.com/spoopyghosty0/frameport
|
||||
seconds: 3.6
|
||||
|
||||
scenes:
|
||||
- name: library
|
||||
caption: ["Your library, ready for the Frame", "Quest, Android and PC VR games from your own folders"]
|
||||
teaser: [0.8, 3.2]
|
||||
steps:
|
||||
- go: library
|
||||
- wait: 1.2
|
||||
- hover: {name: "Batman: Arkham Shadow", dy: 0.3}
|
||||
- wait: 1.0
|
||||
- hover: {name: "Marvel's Deadpool VR", dy: 0.3}
|
||||
- wait: 0.8
|
||||
- hover: "Assassin's Creed Nexus"
|
||||
- wait: 0.8
|
||||
- hover: "Lucky's Tale"
|
||||
- wait: 0.8
|
||||
- park: true
|
||||
- type: "ri"
|
||||
- wait: 1.6
|
||||
|
||||
- name: game
|
||||
caption: ["Every game gets its own recipe", "Known-good fixes from the catalog, or suggested from the game itself"]
|
||||
steps:
|
||||
- click: {name: "Riven", dy: 0.35} # (the title: the card's middle is its Install button)
|
||||
- wait: 1.8
|
||||
- hover: "Works"
|
||||
- wait: 0.7
|
||||
- scroll: {dy: 420, at: [860, 560]}
|
||||
- wait: 1.2
|
||||
- scroll: {dy: -420, at: [860, 560]}
|
||||
- wait: 0.5
|
||||
|
||||
- name: install
|
||||
caption: ["One click to install", "Patched, signed, uploaded, added to Steam and launch-tested"]
|
||||
teaser: [0.6, 4.0]
|
||||
hold: 1.2
|
||||
steps:
|
||||
- click: "Install on Frame"
|
||||
- wait: 0.6
|
||||
- move: [860, 640]
|
||||
- hook: {name: wait_jobs, args: [45]}
|
||||
- wait: 1.0
|
||||
|
||||
- name: play
|
||||
caption: ["Play from your PC", "Starts the game in the headset through Steam"]
|
||||
teaser: [4.3, 3.2]
|
||||
steps:
|
||||
- nav: "Library"
|
||||
- call: library_view.clear_search
|
||||
- wait: 1.4
|
||||
- hover: {name: "Asgard's Wrath 2", dy: 0.3}
|
||||
- wait: 0.6
|
||||
- hover: {name: "Batman: Arkham Shadow", dy: 0.3}
|
||||
- wait: 0.6
|
||||
- click: {name: "Play on Frame", nth: 0}
|
||||
- wait: 2.6
|
||||
- park: true
|
||||
- wait: 0.4
|
||||
|
||||
- name: monitor
|
||||
caption: ["See what the Frame is doing", "Frame rate, CPU, GPU, temperatures and every process, live"]
|
||||
teaser: [0.5, 2.6]
|
||||
steps:
|
||||
- nav: "Monitor"
|
||||
- wait: 2.4
|
||||
- hover: "Temperature" # (a tile only: "GPU" is also the process table's sortable column)
|
||||
- wait: 1.0
|
||||
- hover: "Battery"
|
||||
- wait: 1.0
|
||||
- click: "Show details"
|
||||
- wait: 1.8
|
||||
- park: true
|
||||
|
||||
- name: screenshots
|
||||
caption: ["Screenshots from the headset", "Take one from the PC, then view or download them"]
|
||||
steps:
|
||||
- nav: "Screenshots"
|
||||
- wait: 1.6
|
||||
- click: "Take screenshot"
|
||||
- wait_for: "BONELAB · 2026-10-04 21:50"
|
||||
- wait: 0.8
|
||||
- click: "BONELAB · 2026-10-04 21:50"
|
||||
- wait: 2.0
|
||||
- click: "Close"
|
||||
- wait: 0.4
|
||||
|
||||
- name: files
|
||||
caption: ["Files on the Frame", "Videos, mods and saves: upload, download, select with a drag"]
|
||||
steps:
|
||||
- nav: "Files"
|
||||
- wait: 1.6
|
||||
- drag: ["Concert 8K 3D.mp4", "Mars landing (VR180).mkv"]
|
||||
- wait: 1.0
|
||||
- right_click: "Earth from orbit (360).mp4"
|
||||
- wait: 1.4
|
||||
- press: Escape
|
||||
- wait: 0.6
|
||||
|
||||
- name: themes
|
||||
caption: ["Make it yours", "Dark themes, including true black for OLED screens"]
|
||||
steps:
|
||||
- nav: "Settings"
|
||||
- wait: 1.4
|
||||
- click: "Portal (OLED)"
|
||||
- wait: 1.4
|
||||
- click: "Original"
|
||||
- wait: 1.4
|
||||
- click: "Portal"
|
||||
- wait: 1.0
|
||||
- nav: "Library"
|
||||
- wait: 1.4
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Ember & Ice",
|
||||
"base": "portal",
|
||||
"dual": true,
|
||||
"colors": {
|
||||
"ACCENT": "#FF5A36",
|
||||
"ACCENT_SOFT": "#3A1710",
|
||||
"SECONDARY": "#5CE1E6",
|
||||
"SECONDARY_SOFT": "#0E3033",
|
||||
"PC": "#5CE1E6",
|
||||
"INFO": "#5CE1E6"
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,10 @@ dependencies = [
|
||||
"flet>=1.0",
|
||||
"flet-desktop>=1.0",
|
||||
"flet-dropzone>=0.4.0", # drag-and-drop uploads in the Files tab (packaged app only; Apache-2.0)
|
||||
# the live view inside the window (media_kit/libmpv; Apache-2.0). Not on Linux: there the plugin links libmpv.so.1
|
||||
# and a bundle with it wouldn't start without that library (Linux plays in an mpv window or the browser instead).
|
||||
# flet-video pins flet exactly: keep it at the installed flet's version.
|
||||
"flet-video==1.0.2; sys_platform != 'linux'",
|
||||
"paramiko>=3.4",
|
||||
"zeroconf>=0.132",
|
||||
"psutil>=5.9",
|
||||
|
||||
@@ -35,7 +35,7 @@ def render() -> str:
|
||||
rows.append(f"| {e.title} | {platform} | {STATUS[e.status]} | {note} |")
|
||||
return ("# Tested games\n\n"
|
||||
"Games tested on the Steam Frame with FramePort's recipes. Games not listed here may work too: FramePort "
|
||||
"suggests patches for them, and a working config can be shared from the app (**Share working config…**).\n"
|
||||
"suggests patches for them, and a working recipe can be shared from the app (**Share working recipe…**).\n"
|
||||
f"Tested a game? [Share a working config]({SHARE}) or [report a problem]({REPORT}) (in the app: the game's "
|
||||
"**…** menu does both and fills in the details).\n"
|
||||
"Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.\n\n"
|
||||
|
||||
@@ -69,6 +69,9 @@ def main() -> int:
|
||||
"--add-data", f"{DATA}{sep}frameport/_data",
|
||||
# translations (data files PyInstaller doesn't pick up from the imports)
|
||||
"--add-data", f"{ROOT / 'src/frameport/locales'}{sep}frameport/locales",
|
||||
# the logo and the GUI's own glyphs (SVG)
|
||||
"--add-data", f"{ROOT / 'src/frameport/ui/icons'}{sep}frameport/ui/icons",
|
||||
"--icon", str(ROOT / "src/assets/icon.png"),
|
||||
"--distpath", str(ROOT / "dist"), "--yes"]
|
||||
if TARGET == "linux":
|
||||
cmd.append("--onedir") # a folder: the bundle check sees the agent source, the archive the app
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the demo library (docs/showcase/demo-library.yaml + demo-analyses.json) into a fresh, isolated data dir for
|
||||
docs screenshots and the demo tour. No personal data: the games are catalog games, their analyses were exported
|
||||
without paths, local paths are made up (D:/Games/…), and the art + store details come from the same public sources
|
||||
the app uses (Meta/OculusDB, Steam), cached in ~/.cache/frameport-showcase so later builds (and CI) are offline and
|
||||
identical. A game whose art can't be fetched keeps FramePort's own placeholder art; the build never fails over art.
|
||||
|
||||
python scripts/showcase/demo_home.py build <dir> [--offline] [--refresh]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
FIXTURE = REPO / "docs" / "showcase" / "demo-library.yaml"
|
||||
ANALYSES = REPO / "docs" / "showcase" / "demo-analyses.json"
|
||||
CACHE = Path(os.environ.get("FRAMEPORT_SHOWCASE_CACHE") or Path.home() / ".cache" / "frameport-showcase")
|
||||
DAY = 86400.0
|
||||
FETCHED = 1790000000.0 # the "fetched" time stored with cached details (fixed: builds are identical)
|
||||
|
||||
|
||||
def real_data_dir() -> Path:
|
||||
"""The user's own FramePort data dir (never written by the showcase; not even created by asking)."""
|
||||
from frameport.core import paths
|
||||
|
||||
saved = os.environ.pop("FRAMEPORT_HOME", None)
|
||||
removed = paths._removed.is_set()
|
||||
paths._removed.set() # (user_data_dir creates the folder unless FramePort is being removed)
|
||||
try:
|
||||
return paths.user_data_dir().resolve()
|
||||
finally:
|
||||
if not removed:
|
||||
paths._removed.clear()
|
||||
if saved is not None:
|
||||
os.environ["FRAMEPORT_HOME"] = saved
|
||||
|
||||
|
||||
def load_fixture(path: Path = FIXTURE) -> dict:
|
||||
import yaml
|
||||
|
||||
data = yaml.safe_load(path.read_text())
|
||||
games = data.get("games") or []
|
||||
seen = set()
|
||||
for g in games:
|
||||
if not isinstance(g, dict) or not g.get("package"):
|
||||
raise ValueError(f"{path.name}: every game needs a package: {g!r}")
|
||||
if g["package"] in seen:
|
||||
raise ValueError(f"{path.name}: {g['package']} is listed twice")
|
||||
seen.add(g["package"])
|
||||
unknown = set(g) - {"package", "frame", "played", "added", "tested", "tags", "title", "art"}
|
||||
if unknown:
|
||||
raise ValueError(f"{path.name}: {g['package']}: unknown field(s) {sorted(unknown)}")
|
||||
if g.get("frame") not in (None, "internal", "sd", "outdated"):
|
||||
raise ValueError(f"{path.name}: {g['package']}: frame must be internal, sd or outdated")
|
||||
if (data.get("frame") or {}).get("running") not in (None, *seen):
|
||||
raise ValueError(f"{path.name}: frame.running isn't one of the games")
|
||||
return data
|
||||
|
||||
|
||||
def fake_sha(package: str, salt: str = "") -> str:
|
||||
import hashlib
|
||||
|
||||
return hashlib.sha1(f"showcase:{package}:{salt}".encode()).hexdigest()
|
||||
|
||||
|
||||
def steam_appid(package: str, title: str) -> int:
|
||||
return (zlib.crc32(f'"/home/steamos/Applications/quest-frame/{package}/launch.sh"{title}'.encode())
|
||||
| 0x80000000) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def _entry(spec: dict, tech: dict, now: float) -> dict:
|
||||
"""The library fields of one demo game, made the way pipeline.add_game / add_rift_game make them."""
|
||||
from frameport.analysis.detect import ANALYSIS_VERSION
|
||||
from frameport.core import library
|
||||
from frameport.patches.base import recipe_fingerprint
|
||||
from frameport.recommend import catalog, engine
|
||||
|
||||
pkg = spec["package"]
|
||||
a = library.analysis_from_dict(dict(tech["analysis"], package=pkg))
|
||||
rift = pkg.startswith("rift.")
|
||||
if not rift:
|
||||
a.extra["analysis_version"] = ANALYSIS_VERSION
|
||||
recipe = engine.suggest(a)
|
||||
title = spec.get("title") or recipe.title or a.label or pkg
|
||||
rdict = library.recipe_to_dict(recipe)
|
||||
fields = dict(title=title, name=title, data_bytes=tech.get("data_bytes") or 0, analysis=a.to_dict(),
|
||||
recipe=rdict, suggested=rdict, status=recipe.status, added=now - DAY * spec.get("added", 30),
|
||||
build={"sha256": fake_sha(pkg), "ok": True, "recipe_fp": recipe_fingerprint(rdict),
|
||||
"applied": sorted(p for p in rdict.get("patches") or {} if "." in p)})
|
||||
if rift:
|
||||
folder = f"D:/Games/PC VR/{title}"
|
||||
exe = tech.get("exe_rel") or tech.get("exe") or "Game.exe"
|
||||
entry = catalog.lookup(pkg)
|
||||
fields.update(kind="rift", apk=None, game_dir=folder, exe=exe.split("/", 1)[-1] if "/" in exe else exe,
|
||||
exe_confirmed=True, origin="D:/Games/PC VR", quest_package=entry.quest_package if entry
|
||||
else None, art_source="oculusdb")
|
||||
fields["build"].update(kind="rift", revive="3.2.0")
|
||||
else:
|
||||
folder = f"D:/Games/Quest/{title}"
|
||||
fields.update(apk=f"{folder}/{pkg}.apk", data_dir=f"{folder}/{pkg}" if tech.get("data_bytes") else None,
|
||||
origin="D:/Games/Quest")
|
||||
if spec.get("tags"):
|
||||
fields["tags"] = list(spec["tags"])
|
||||
if spec.get("played") is not None:
|
||||
fields["last_played"] = now - DAY * spec["played"]
|
||||
installed = spec.get("frame") is not None
|
||||
if installed:
|
||||
t = now - DAY * (spec.get("played", 3) + 0.4)
|
||||
fields["installs"] = {"frame": {"result": {"ok": True, "appid": steam_appid(pkg, title)}, "time": t}}
|
||||
if spec.get("tested", installed):
|
||||
fields["last_test"] = {"state": "RUNNING", "verdict": "pass",
|
||||
"milestone": "Game window created" if rift else "Submitting frames",
|
||||
"fps": None if rift else 72.0, "findings": [], "suggestions": [],
|
||||
"time": now - DAY * (spec.get("played", 3) + 0.39), "target": "frame"}
|
||||
return fields
|
||||
|
||||
|
||||
def _art(pkg: str, refresh: bool, offline: bool, log, pick: bool = False) -> str:
|
||||
"""Art + store details for one game: from the showcase cache, else fetched (and cached). Returns its source."""
|
||||
from frameport import pipeline
|
||||
from frameport.artwork import fetch
|
||||
from frameport.core import library
|
||||
|
||||
cached = CACHE / "games" / (pkg + ("@pick" if pick else ""))
|
||||
dest = fetch.artwork_dir(pkg)
|
||||
if cached.is_dir() and not refresh:
|
||||
for f in cached.iterdir():
|
||||
if f.is_file() and f.name != "details.json":
|
||||
shutil.copy2(f, dest / f.name)
|
||||
details = cached / "details.json"
|
||||
if details.exists():
|
||||
library.upsert_game(pkg, details=json.loads(details.read_text()))
|
||||
return "cache"
|
||||
if offline:
|
||||
return "none"
|
||||
entry = library.game(pkg)
|
||||
try:
|
||||
if entry.get("kind") == "rift":
|
||||
pipeline._rift_art(entry)
|
||||
elif pick: # what a user does when the store's art is a placeholder: the picker's Meta (OculusDB) result
|
||||
from frameport.artwork import sources
|
||||
|
||||
choice = next((c for c in sources.search(entry.get("title") or pkg) if c.get("package") == pkg), None)
|
||||
if not (choice and sources.apply_choice(pkg, choice)):
|
||||
log(f" {pkg}: the picker had no Meta result, store art instead")
|
||||
fetch.fetch(pkg, None, refresh=True)
|
||||
else:
|
||||
fetch.fetch(pkg, None, refresh=True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log(f" {pkg}: no art ({exc})")
|
||||
d = pipeline.fetch_details(pkg)
|
||||
d["fetched"] = FETCHED
|
||||
library.upsert_game(pkg, details=d)
|
||||
have = [f for f in dest.iterdir() if f.is_file() and not f.name.startswith("t_")] # (not thumbnails)
|
||||
if not have:
|
||||
return "none"
|
||||
if cached.exists():
|
||||
shutil.rmtree(cached)
|
||||
cached.mkdir(parents=True)
|
||||
for f in have:
|
||||
shutil.copy2(f, cached / f.name)
|
||||
(cached / "details.json").write_text(json.dumps(d, indent=1, sort_keys=True))
|
||||
return "fetched"
|
||||
|
||||
|
||||
PROFILES = ("demo", "fresh")
|
||||
SCAN_FILE = "showcase-scan.json" # the fresh profile's games, found by the pretend folder scan (fakes.scan_job)
|
||||
|
||||
|
||||
def build(home: Path, offline: bool = False, refresh: bool = False, log=print, profile: str = "demo") -> dict:
|
||||
"""Write the demo library into `home` (emptied first). Sets FRAMEPORT_HOME for this process.
|
||||
|
||||
profile "demo": the library in use (games installed on the pretend Frame, one running). "fresh": FramePort's
|
||||
first start (the install tutorial): an empty library, the welcome screen, a Frame with nothing installed and no
|
||||
game running; the demo games (art and store details already in place) wait in showcase-scan.json for the
|
||||
pretend folder scan, as a scan would find them (no install or play history)."""
|
||||
if profile not in PROFILES:
|
||||
raise ValueError(f"unknown profile {profile!r} ({', '.join(PROFILES)})")
|
||||
home = Path(home).resolve()
|
||||
if home == real_data_dir() or real_data_dir() in home.parents:
|
||||
raise SystemExit(f"refusing to build the demo library in FramePort's own data dir ({home})")
|
||||
if home.exists():
|
||||
shutil.rmtree(home)
|
||||
home.mkdir(parents=True)
|
||||
os.environ["FRAMEPORT_HOME"] = str(home)
|
||||
for var in ("FRAMEPORT_NO_UPDATE_CHECK", "FRAMEPORT_NO_CATALOG_UPDATE", "FRAMEPORT_NO_LINK_HANDLER"):
|
||||
os.environ[var] = "1"
|
||||
from frameport.artwork import thumbs
|
||||
from frameport.core import library
|
||||
|
||||
fixture = load_fixture()
|
||||
tech = json.loads(ANALYSES.read_text())
|
||||
now = time.time()
|
||||
missing = [g["package"] for g in fixture["games"] if g["package"] not in tech]
|
||||
if missing:
|
||||
raise SystemExit(f"demo-analyses.json has no analysis for {missing}")
|
||||
for spec in fixture["games"]:
|
||||
library.upsert_game(spec["package"], **_entry(spec, tech[spec["package"]], now))
|
||||
# settings: what a first start would set (no welcome, no migrations or catalog refresh, no update nags)
|
||||
from frameport import __version__
|
||||
|
||||
with library.edit() as data:
|
||||
s = data.setdefault("settings", {})
|
||||
s.update({"ui.theme": "portal", "ui.scale": 1.0, "ui.reduce_motion": False, "ui.welcome_done": True,
|
||||
"ui.language": "en",
|
||||
"catalog.auto_update": False, "update.auto_check": False, "recipes.app_version": __version__,
|
||||
"update.last_seen_version": __version__})
|
||||
# the pretend Frame
|
||||
installed = []
|
||||
for spec in fixture["games"]:
|
||||
where = spec.get("frame")
|
||||
if where:
|
||||
installed.append({"package": spec["package"], "drive": "sd" if where == "sd" else "internal",
|
||||
**({"sha256": fake_sha(spec["package"], "older")} if where == "outdated" else {})})
|
||||
state = {"installed": installed, **{k: v for k, v in (fixture.get("frame") or {}).items()}}
|
||||
(home / "showcase-frame.json").write_text(json.dumps(state, indent=1))
|
||||
# art + store details
|
||||
sources: dict[str, list[str]] = {}
|
||||
for spec in fixture["games"]:
|
||||
src = _art(spec["package"], refresh, offline, log, pick=spec.get("art") == "pick")
|
||||
sources.setdefault(src, []).append(spec["package"])
|
||||
try:
|
||||
thumbs.prewarm(spec["package"])
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# the managed tools are "installed" (no download toast in pictures): stand-in files
|
||||
tools = home / "showcase-tools"
|
||||
tools.mkdir()
|
||||
for var, name in (("FRAMEPORT_JAVA", "java"), ("FRAMEPORT_OVERPORT_JAR", "overport.jar"),
|
||||
("FRAMEPORT_APKSIGNER_JAR", "apksigner.jar")):
|
||||
(tools / name).write_bytes(b"")
|
||||
os.environ[var] = str(tools / name)
|
||||
if profile == "fresh":
|
||||
history = ("installs", "last_test", "last_played", "tags", "build")
|
||||
found = [{k: v for k, v in g.items() if k not in history} for g in library.games()]
|
||||
(home / SCAN_FILE).write_text(json.dumps(found))
|
||||
with library.edit() as data:
|
||||
data["games"] = {}
|
||||
data["settings"]["ui.welcome_done"] = False
|
||||
(home / "showcase-frame.json").write_text(json.dumps({"installed": [], "running": None,
|
||||
"battery": state.get("battery", 95)}, indent=1))
|
||||
log(f"demo library ({profile}): {len(fixture['games'])} games in {home} (art: "
|
||||
+ ", ".join(f"{k} {len(v)}" for k, v in sorted(sources.items())) + ")")
|
||||
if sources.get("none"):
|
||||
log(f" without art (placeholders): {', '.join(sources['none'])}")
|
||||
return {"home": str(home), "games": len(fixture["games"]), "art": sources}
|
||||
|
||||
|
||||
def build_for_render(home: Path, offline: bool = False, allow_missing_art: bool = False,
|
||||
profile: str = "demo") -> dict:
|
||||
"""build(), but a render must not go on with placeholder art (a store that didn't answer would otherwise put
|
||||
placeholders into the docs and the video): exits 4 unless allowed."""
|
||||
result = build(home, offline=offline, profile=profile)
|
||||
if result["art"].get("none") and not allow_missing_art:
|
||||
raise SystemExit(f"no art for {', '.join(result['art']['none'])} (a store didn't answer?): not rendering. "
|
||||
"Try again later, or pass --allow-missing-art")
|
||||
return result
|
||||
|
||||
|
||||
def tool_env(home: Path) -> dict:
|
||||
"""The environment variables a render needs for a built demo home (also for child processes)."""
|
||||
tools = Path(home) / "showcase-tools"
|
||||
return {"FRAMEPORT_HOME": str(home), "FRAMEPORT_NO_UPDATE_CHECK": "1", "FRAMEPORT_NO_CATALOG_UPDATE": "1",
|
||||
"FRAMEPORT_NO_LINK_HANDLER": "1", "FRAMEPORT_JAVA": str(tools / "java"),
|
||||
"FRAMEPORT_OVERPORT_JAR": str(tools / "overport.jar"),
|
||||
"FRAMEPORT_APKSIGNER_JAR": str(tools / "apksigner.jar")}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
sys.path.insert(0, str(REPO / "src"))
|
||||
ap = argparse.ArgumentParser()
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
b = sub.add_parser("build")
|
||||
b.add_argument("home", type=Path)
|
||||
b.add_argument("--offline", action="store_true", help="only cached art (no network)")
|
||||
b.add_argument("--refresh", action="store_true", help="fetch art + details again (updates the cache)")
|
||||
b.add_argument("--profile", choices=PROFILES, default="demo", help="demo (in use) or fresh (first start)")
|
||||
args = ap.parse_args()
|
||||
build(args.home, offline=args.offline, refresh=args.refresh, profile=args.profile)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,677 @@
|
||||
"""Pretend Frame for GUI renders (ui_smoke, docs screenshots, the demo tour): its files, screenshots, games, drives,
|
||||
monitor stream and Type on Frame, with no network and no device. Shared by scripts/ui_smoke.py and scripts/showcase/.
|
||||
|
||||
The demo library (scripts/showcase/demo_home.py) writes `showcase-frame.json` into the data dir: which games the
|
||||
pretend Frame has installed (and on which drive), the running game and its battery; without it the library's working
|
||||
Quest builds are "installed" (the 8 largest).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
|
||||
from frameport.core import library
|
||||
from frameport.core.paths import user_data_dir
|
||||
from frameport.ui.app import FramePortApp
|
||||
|
||||
FRAME_STATE = "showcase-frame.json"
|
||||
SHOTS_AT = time.mktime((2026, 10, 4, 21, 40, 0, 0, 0, -1)) # the newest sample screenshot (local time)
|
||||
|
||||
|
||||
def frame_state() -> dict:
|
||||
"""The demo library's pretend Frame ({installed: [{package, drive, sha256?}], running, battery}), else {}."""
|
||||
try:
|
||||
return json.loads((user_data_dir() / FRAME_STATE).read_text())
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
class FakeFS:
|
||||
"""--fake-frame's file system for the Files tab: a temp folder with sample files, served like SFTP."""
|
||||
|
||||
def __init__(self):
|
||||
import tempfile
|
||||
|
||||
self.home = tempfile.mkdtemp(prefix="fp-fake-frame-")
|
||||
samples = {"Videos": ["Earth from orbit (360).mp4", "Mars landing (VR180).mkv", "Concert 8K 3D.mp4"],
|
||||
"Downloads": ["Mods/", "readme.txt"], "Documents": ["Saves/", "Notes.pdf"]}
|
||||
sizes = {".mp4": 2_400_000_000, ".mkv": 1_100_000_000}
|
||||
for folder, names in samples.items():
|
||||
base = os.path.join(self.home, folder)
|
||||
os.makedirs(os.path.join(base, "Trips"), exist_ok=True)
|
||||
for n in names:
|
||||
if n.endswith("/"):
|
||||
os.makedirs(os.path.join(base, n), exist_ok=True)
|
||||
else:
|
||||
with open(os.path.join(base, n), "wb") as f:
|
||||
f.truncate(sizes.get(os.path.splitext(n)[1], 48_000)) # sparse: no real disk use
|
||||
# fixed dates (the Files tab shows them): a few days before the newest screenshot, a different one each
|
||||
for i, (root, dirs, files) in enumerate(sorted(os.walk(self.home), reverse=True)):
|
||||
for j, name in enumerate(sorted(dirs + files)):
|
||||
t = SHOTS_AT - 86400 * (2 + (i + j) % 5) - 3600 * ((i * 7 + j * 3) % 11)
|
||||
os.utime(os.path.join(root, name), (t, t))
|
||||
self.shots = self._screenshots()
|
||||
|
||||
def _screenshots(self) -> list[dict]:
|
||||
"""Sample Steam screenshots for the Screenshots tab, two days, a few games + SteamVR. They are the games' own
|
||||
in-game store screenshots (shot_*.jpg from the store details), never cover art: games installed on the
|
||||
pretend Frame first, the running one leading (Take screenshot adds one of it); SteamVR's own shots (taken in
|
||||
a game FramePort didn't install) come from another game's. Only a library without any store screenshots falls
|
||||
back to hero/wide art, else colour gradients."""
|
||||
from frameport.artwork import fetch
|
||||
|
||||
folder = os.path.join(self.home, "shots")
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
state = frame_state()
|
||||
on_frame = {i["package"] for i in state.get("installed") or []}
|
||||
running = state.get("running")
|
||||
real, covers = [], []
|
||||
for g in library.games():
|
||||
if g.get("kind") == "rift":
|
||||
continue
|
||||
shots_art = sorted(fetch.artwork_dir(g["package"]).glob("shot_*.jpg"))
|
||||
if shots_art:
|
||||
real.append((g, shots_art))
|
||||
else:
|
||||
covers.append((g, [p for p in fetch.files(g["package"]) if p.stem in ("hero", "landscape")]))
|
||||
games = real or covers
|
||||
games.sort(key=lambda ga: (ga[0]["package"] != running, ga[0]["package"] not in on_frame, -len(ga[1]),
|
||||
ga[0]["package"]))
|
||||
self.owners = [(g["package"], g.get("title") or g["package"], arts) for g, arts in games[:3]]
|
||||
rest = [arts for g, arts in games[3:] if g["package"] not in on_frame] or [arts for _g, arts in games[3:4]]
|
||||
self.owners.append((None, "SteamVR", rest[0] if rest else []))
|
||||
self._used = [0] * len(self.owners) # the next screenshot of each owner (no picture shown twice)
|
||||
# fixed dates (renders don't change from one day to the next): 6 shots on the first day, 4 on the one before
|
||||
# (--gestures drags across the first row)
|
||||
shots = []
|
||||
for i in range(10):
|
||||
t = SHOTS_AT - i * 2400 - (86400 if i >= 6 else 0)
|
||||
shots.append(self._shot(t, i, i % len(self.owners)))
|
||||
return shots
|
||||
|
||||
def _shot(self, t: float, i: int, owner: int) -> dict:
|
||||
"""One Steam screenshot: the owner's next store screenshot, whole (scaled to 1280x720)."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
pkg, title, arts = self.owners[owner]
|
||||
name = time.strftime("%Y%m%d%H%M%S", time.localtime(t)) + "_1.jpg"
|
||||
path = os.path.join(self.home, "shots", name)
|
||||
if arts:
|
||||
n = self._used[owner]
|
||||
self._used[owner] += 1
|
||||
with Image.open(arts[n % len(arts)]) as src:
|
||||
im = ImageOps.fit(src.convert("RGB"), (1280, 720))
|
||||
else:
|
||||
im = Image.linear_gradient("L").resize((640, 360)).convert("RGB")
|
||||
im = Image.merge("RGB", (im.getchannel(0).point(lambda v, i=i: (v + 40 * i) % 256),
|
||||
im.getchannel(1).point(lambda v: 255 - v), im.getchannel(2)))
|
||||
im.save(path, "JPEG", quality=85)
|
||||
return {"path": path, "thumb": None, "time": int(t), "width": 1920, "height": 1080,
|
||||
"size": os.path.getsize(path), "account": "1", "appid": "250820", "package": pkg, "title": title}
|
||||
|
||||
def take_screenshot(self) -> dict:
|
||||
"""Take screenshot: a new shot of the running game (its next store screenshot), newest of all."""
|
||||
time.sleep(1.2) # SteamVR captures, Steam saves
|
||||
t = max(s["time"] for s in self.shots) + 600
|
||||
shot = self._shot(t, len(self.shots) + 1, 0)
|
||||
self.shots.insert(0, shot)
|
||||
return {"taken": True, "path": shot["path"], "reason": None, "hmd": "Normal"}
|
||||
|
||||
def agent(self, command, **args):
|
||||
if command == "storage_targets":
|
||||
return {"targets": [{"id": n.lower(), "path": os.path.join(self.home, n), "android": a, "shared": True}
|
||||
for n, a in (("Videos", "/sdcard/Movies"), ("Downloads", "/sdcard/Download"),
|
||||
("Documents", "/sdcard/Documents"))]}
|
||||
if command == "list_screenshots":
|
||||
want = args.get("package")
|
||||
shots = [s for s in self.shots if want is None or (s["package"] or "") == want]
|
||||
games = {}
|
||||
for s in self.shots:
|
||||
games.setdefault(s["package"] or "", {"package": s["package"], "title": s["title"], "count": 0})
|
||||
games[s["package"] or ""]["count"] += 1
|
||||
return {"shots": shots, "total": len(shots), "games": list(games.values())}
|
||||
if command == "take_screenshot": # the Screenshots tab's button: a new shot of the running game
|
||||
return self.take_screenshot()
|
||||
raise RuntimeError(f"fake Frame: {command} not available")
|
||||
|
||||
@property
|
||||
def sftp(self):
|
||||
import paramiko
|
||||
|
||||
class SFTP:
|
||||
def listdir_attr(self, path):
|
||||
out = []
|
||||
for name in sorted(os.listdir(path)):
|
||||
a = paramiko.SFTPAttributes.from_stat(os.lstat(os.path.join(path, name)))
|
||||
a.filename = name
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
def stat(self, path):
|
||||
return paramiko.SFTPAttributes.from_stat(os.stat(path))
|
||||
|
||||
def get(self, remote, local, callback=None):
|
||||
import shutil
|
||||
|
||||
shutil.copyfile(remote, local)
|
||||
return SFTP()
|
||||
|
||||
|
||||
class FakeTarget:
|
||||
"""--fake-frame: a pretend Steam Frame with the library's working Quest builds installed (no network, no device),
|
||||
for documentation screenshots."""
|
||||
|
||||
def __init__(self, count: int = 8):
|
||||
from frameport.frame.connection import parse_target
|
||||
|
||||
self.label = "steamframe"
|
||||
self.frame = FakeFS()
|
||||
self.target = parse_target("steamos@steamframe.local")
|
||||
state = frame_state()
|
||||
if state.get("installed"): # the demo library says what's on the Frame
|
||||
sd_games = {i["package"] for i in state["installed"] if i.get("drive") == "sd"}
|
||||
self.games = [self._record(g, i.get("sha256")) for i in state["installed"]
|
||||
if (g := library.game(i["package"]))]
|
||||
else:
|
||||
works = [g for g in library.games() if g.get("kind") != "rift" and (g.get("build") or {}).get("sha256")
|
||||
and (g.get("recipe") or {}).get("status") in ("works", "issues")]
|
||||
works.sort(key=lambda g: -(g.get("data_bytes") or 0))
|
||||
self.games = [self._record(g) for g in works[:count]]
|
||||
sd_games = {self.games[1]["package"]} if len(self.games) > 1 else set()
|
||||
# --linux: the AppImage is on the Frame, but SteamOS lacks one of its libraries
|
||||
self.games += [{"package": g["package"], "kind": "linux", "title": g.get("title"), "apk_size": 2**26,
|
||||
"apk_present": True, "recipe": None, "exe": g.get("exe"),
|
||||
"missing_libraries": ["libwebkit2gtk-4.1.so.0"]}
|
||||
for g in library.games() if g.get("kind") == "linux" and g["package"] == LINUX_APPIMAGE]
|
||||
# GitHub #90: most games on internal storage, some on a microSD card
|
||||
sd = {"internal": False, "path": "/run/media/steamos/SD Card", "label": "SD Card"}
|
||||
for g in self.games:
|
||||
g["drive"] = sd if g["package"] in sd_games else \
|
||||
{"internal": True, "path": "/home/steamos", "label": "Internal storage"}
|
||||
g["drive_missing"] = False
|
||||
|
||||
@staticmethod
|
||||
def _record(g: dict, sha256: str | None = None) -> dict:
|
||||
"""The agent's list_installed record of a library game (sha256: a different build = "Update on Frame")."""
|
||||
rift = g.get("kind") == "rift"
|
||||
return {"package": g["package"], "kind": "rift" if rift else "quest", "title": g.get("title"),
|
||||
"apk_size": (g.get("data_bytes") or 0) + (0 if rift else 2**28),
|
||||
"sha256": sha256 or (g.get("build") or {}).get("sha256"),
|
||||
"recipe": {"patches": list((g.get("recipe") or {}).get("patches", []))}}
|
||||
|
||||
def launch(self, pkg: str) -> dict:
|
||||
"""Play: Steam on the pretend Frame starts the game (the "Starting … put the headset on" toast)."""
|
||||
return {"via": "shortcut", "steam": {"result": "started", "lines": []}}
|
||||
|
||||
def drives(self) -> list[dict]:
|
||||
sd_games = sum(1 for g in self.games if not g["drive"]["internal"])
|
||||
return [{"id": "internal", "path": "/home/steamos", "install_dir": "/home/steamos/Applications/quest-frame",
|
||||
"label": "Internal storage", "fstype": "ext4", "internal": True, "removable": False,
|
||||
"free_bytes": 312 * 2**30, "total_bytes": 460 * 2**30, "usable": True, "reason": "",
|
||||
"games": len(self.games) - sd_games},
|
||||
{"id": "/run/media/steamos/SD Card", "path": "/run/media/steamos/SD Card",
|
||||
"install_dir": "/run/media/steamos/SD Card/FramePort", "label": "SD Card", "fstype": "ext4",
|
||||
"internal": False, "removable": True, "free_bytes": 187 * 2**30, "total_bytes": 238 * 2**30,
|
||||
"usable": True, "reason": "", "games": sd_games},
|
||||
{"id": "/run/media/steamos/USB", "path": "/run/media/steamos/USB", "install_dir":
|
||||
"/run/media/steamos/USB/FramePort", "label": "USB", "fstype": "exfat", "internal": False,
|
||||
"removable": True, "free_bytes": 50 * 2**30, "total_bytes": 64 * 2**30, "usable": False,
|
||||
"reason": "exfat can't hold game data (no Unix permissions or symlinks); format the drive in "
|
||||
"SteamOS to install games on it", "games": 0}]
|
||||
|
||||
def move(self, package, dest, reporter) -> dict:
|
||||
reporter.stage("Move game files")
|
||||
for i in range(5):
|
||||
reporter.progress(i / 4, f"Copying {i / 2:.1f}/2.0 GiB")
|
||||
time.sleep(0.5)
|
||||
return {"state": "done", "package": package}
|
||||
|
||||
def set_desktop_entry(self, package, enabled) -> dict:
|
||||
for g in self.games:
|
||||
if g["package"] == package:
|
||||
g["desktop_entry"] = enabled
|
||||
return {"enabled": enabled}
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"hostname": "steamframe", "os": "SteamOS", "os_version": "3.8", "build_id": "20260922",
|
||||
"free_bytes": 312 * 2**30, "installed": self.games, "lepton": True,
|
||||
"proton": {"ready": {"display_name": "Proton 11 (ARM64)"}, "openxr": {"name": "SteamVR"}},
|
||||
"kernel_keys": {"keys": 31, "max_keys": 200},
|
||||
"battery": {"percent": frame_state().get("battery", 95), "status": "Discharging"}}
|
||||
|
||||
def installed(self) -> list[dict]:
|
||||
return self.games
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeKeyboardSession:
|
||||
"""--fake-frame: Type on Frame connects at once (nothing is sent anywhere)."""
|
||||
|
||||
def __init__(self, frame):
|
||||
self.closed = False
|
||||
|
||||
def key(self, name, action="down"):
|
||||
return True
|
||||
|
||||
def text(self, text):
|
||||
return ""
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeMonitorSession:
|
||||
"""--fake-frame: the Monitor tab's stream as synthetic samples, one per second, shaped like a real Quest game on
|
||||
the dev Frame (2026-10-07): 72 fps, the game's Android container, SteamVR/Steam as context. Two minutes are sent
|
||||
at once first, so the charts are full in screenshots. GAME = --game (else the library's first game)."""
|
||||
|
||||
GAME: str | None = None
|
||||
BACKFILL = 120
|
||||
# (name, group, CPU %, GPU %, memory); "GAME" = the game's package
|
||||
PROCS = [("GAME", "game", 9.8, 44.0, 1_350_000_000), ("vrcompositor", "steamvr", 1.4, 9.0, 80_000_000),
|
||||
("system_server", "game", 1.1, 0.0, 296_000_000), ("XRServiceLoopTh", "steamvr", 0.5, 0.0, 433_000_000),
|
||||
("steamwebhelper", "steam", 0.4, 0.0, 350_000_000), ("com.android.systemui", "game", 0.1, 0.0,
|
||||
229_000_000),
|
||||
("surfaceflinger", "game", 0.1, 0.4, 96_000_000), ("audioserver", "game", 0.1, 0.0, 31_000_000),
|
||||
("com.android.providers.media.module", "game", 0.1, 0.0, 130_000_000),
|
||||
("com.android.launcher3", "game", 0.0, 0.0, 194_000_000), ("main", "game", 0.0, 0.0, 178_000_000),
|
||||
("com.android.settings", "game", 0.0, 0.0, 172_000_000),
|
||||
("com.android.networkstack.process", "game", 0.0, 0.0, 130_000_000),
|
||||
("android.ext.services", "game", 0.0, 0.0, 111_000_000)] + \
|
||||
[("vrwebhelper", "steamvr", 0.3, 0.0, 160_000_000 + i * 9_000_000) for i in range(4)]
|
||||
|
||||
def __init__(self, frame, on_sample, on_end=None):
|
||||
import math
|
||||
|
||||
self.math, self.closed, self.on_sample = math, False, on_sample
|
||||
self.static = {"agent": 62, "cores": 8, "gpu_max_mhz": 903, "mem_total": 16 * 1024 ** 3, "fan": True,
|
||||
"clusters": [{"cpus": [0, 1], "max_mhz": 2265}, {"cpus": [2, 3, 4], "max_mhz": 3148},
|
||||
{"cpus": [5, 6], "max_mhz": 2956}, {"cpus": [7], "max_mhz": 3052}],
|
||||
"temp_groups": ["CPU", "GPU", "Memory", "Battery", "NPU", "Power ICs", "Modem", "Camera"]}
|
||||
self.t = 0
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
|
||||
def _sample(self) -> dict:
|
||||
m, t = self.math, self.t
|
||||
wave = lambda a, p, o=0: a * (1 + m.sin(t / p + o)) / 2 # noqa: E731
|
||||
state = frame_state()
|
||||
idle = not self.GAME and "running" in state and state["running"] is None # (a fresh Frame: no game)
|
||||
running = self.GAME or state.get("running")
|
||||
g = library.game(running) if running else (library.games() or [None])[0]
|
||||
game = g or {"package": "com.example.game", "title": "Example Game"}
|
||||
pkg = game["package"]
|
||||
procs = [{"pid": 570799 + i * 37, "ppid": 1, "name": pkg if n == "GAME" else n,
|
||||
"group": f"game:{pkg}" if grp == "game" else grp, "game": pkg if grp == "game" else None,
|
||||
"cpu": round(c * (0.85 + wave(0.3, 3, i)), 1), "gpu": round(gp * (0.9 + wave(0.2, 5, i)), 1),
|
||||
"rss": r, "age": 1500 + t, "uid": 1000, "critical": grp in ("steamvr", "steam"), "locked": False,
|
||||
"context": grp != "game"}
|
||||
for i, (n, grp, c, gp, r) in enumerate(self.PROCS) if not (idle and grp == "game")]
|
||||
return {
|
||||
"t": time.time() - max(0, self.BACKFILL - t), "dt": 1.0, "self_ms": 11.5,
|
||||
"cpu": {"total": round(15 + wave(4, 4), 1), "cores": [round(4 + wave(30, 3 + i, i), 1) for i in range(8)],
|
||||
"mhz": [2265, 1996, 1920, 518]},
|
||||
"gpu": {"busy": round(52 + wave(8, 5), 1), "mhz": 903},
|
||||
"mem": {"total": 15.3 * 1024 ** 3, "avail": int((8.3 - wave(0.15, 9)) * 1024 ** 3),
|
||||
"swap_total": 7.6 * 1024 ** 3, "swap_free": 7.4 * 1024 ** 3},
|
||||
"psi": {"cpu": 1.0, "memory": 0.0, "io": 0.1},
|
||||
"temps": {"CPU": round(48 + wave(1.5, 11), 1), "GPU": round(46.5 + wave(1, 13), 1), "Memory": 47.1,
|
||||
"Battery": 27.7, "NPU": 47.3, "Power ICs": 37.0, "Modem": 44.2, "Camera": 46.3},
|
||||
"zones": {"CPU": {"cpu7-top": 48.4, "cpu0": 44.0}, "GPU": {"gpuss-0": 46.5}},
|
||||
"fan": 8500 + int(wave(300, 7)),
|
||||
"power": {"system": round(7.3 + wave(0.6, 4), 2), "cpu": 0.85, "gpu": round(1.0 + wave(0.3, 5), 2),
|
||||
"npu": 0.1},
|
||||
"battery": {"percent": frame_state().get("battery", 95), "status": "Discharging", "plugged": False,
|
||||
"draining": True, "watts": -1.96, "empty_s": 22440},
|
||||
"net": {"wlan0": [int(2000 + wave(4000, 3)), 1000], "wlanap": [0, 0], "usb0": [0, 0]},
|
||||
"games": [{"package": pkg, "title": game.get("title") or pkg, "kind": "quest", "appid": 1,
|
||||
"elapsed": 1500 + t, "cpu": 9.4, "gpu": round(44 + wave(6, 5), 1), "mem": 3_390_000_000,
|
||||
"processes": 87, "fps": round(71.6 + wave(0.6, 2) - (9 if t % 41 == 30 else 0), 1),
|
||||
"frame_ms": 0.0}] if not idle else [],
|
||||
"procs": procs, "filter": "game"}
|
||||
|
||||
def _run(self) -> None:
|
||||
self.t = 0
|
||||
while not self.closed and self.t < 100000:
|
||||
self.on_sample(self._sample())
|
||||
if self.t >= self.BACKFILL: # the first two minutes at once (full charts), then one per second
|
||||
time.sleep(1)
|
||||
self.t += 1
|
||||
|
||||
def set_modules(self, m):
|
||||
# the hub asks for everything when the Monitor tab subscribes (the Frame card started the stream): send the
|
||||
# two minutes again so its charts are full in screenshots too
|
||||
if m == "all":
|
||||
self.t = 0
|
||||
return True
|
||||
|
||||
def set_interval(self, s): pass # noqa: E704
|
||||
def set_filter(self, w): pass # noqa: E704
|
||||
def pause(self, p): pass # noqa: E704
|
||||
|
||||
def kill(self, pid, sig="TERM", force=False):
|
||||
return {"ended": True, "pid": pid}
|
||||
|
||||
def end_game(self, package):
|
||||
return {"ended": True, "via": "steam"}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
FAKE_INSTALL_STAGES = ["Patching the game", "OVRPort (primary)", "Frame fixes (primary)", "sign (primary)",
|
||||
"validate (primary)", "Prepare Frame", "Upload APK"]
|
||||
|
||||
|
||||
def start_fake_install(app: FramePortApp, package: str) -> None:
|
||||
"""A running install job of `package` that reports the real stage names up to the upload (62 %) and then waits
|
||||
(it never ends: the smoke run exits with it)."""
|
||||
from frameport.ui.jobs import Job
|
||||
|
||||
hold, reached = threading.Event(), threading.Event()
|
||||
|
||||
def run(job):
|
||||
for stage in FAKE_INSTALL_STAGES:
|
||||
job.reporter.stage(stage)
|
||||
time.sleep(0.3) # past the job queue's notification throttle
|
||||
job.reporter.progress(0.62, "com.example.apk", speed="36.4 MB/s · ~1 min left")
|
||||
reached.set()
|
||||
hold.wait()
|
||||
|
||||
app.jobs.submit(Job(f"Install {app._title(package)} on Frame", run, package, "install"))
|
||||
reached.wait(10)
|
||||
|
||||
|
||||
def open_type_tab(app: FramePortApp) -> None:
|
||||
"""The Type on Frame tab, with one key 'pressed' so the screenshot shows it working."""
|
||||
app.type_on_frame()
|
||||
time.sleep(1.5)
|
||||
app.keyboard_view.press("Enter")
|
||||
|
||||
|
||||
def fake_live_stream(app: FramePortApp) -> None:
|
||||
"""The Live view while streaming: a local ffmpeg test picture through the real relay (no Frame needed). Web mode
|
||||
has no in-window player, so it's shown as playing in the browser (the bar's streaming layout)."""
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from frameport.install.livestream import LiveStream
|
||||
|
||||
view = app.live_view
|
||||
if view is None or shutil.which("ffmpeg") is None:
|
||||
return
|
||||
src = ["ffmpeg", "-loglevel", "error", "-re", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=30",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-c:v", "libx264", "-preset", "ultrafast",
|
||||
"-g", "30", "-pix_fmt", "yuv420p", "-c:a", "aac", "-f", "mp4",
|
||||
"-movflags", "empty_moov+default_base_moof+frag_keyframe", "-frag_duration", "100000", "-"]
|
||||
proc = subprocess.Popen(src, stdout=subprocess.PIPE)
|
||||
view.live = LiveStream(lambda: proc.stdout, proc.terminate).start()
|
||||
view.mode = "browser"
|
||||
view._refresh()
|
||||
|
||||
|
||||
def stop_fake_live(app: FramePortApp) -> None:
|
||||
if app.live_view is not None and app.live_view.live is not None:
|
||||
app.live_view.stop()
|
||||
|
||||
|
||||
def open_monitor_details(app: FramePortApp) -> None:
|
||||
"""The Monitor with its details row open."""
|
||||
app.go("monitor")
|
||||
time.sleep(2)
|
||||
if not app.monitor_view.details.visible:
|
||||
app.monitor_view.toggle_details()
|
||||
|
||||
|
||||
LINUX_APPIMAGE = "linux.venera" # --linux's packages
|
||||
LINUX_FOLDER = "linux.matineevr"
|
||||
|
||||
|
||||
def _elf(machine: int = 183, appimage: bool = False, extra: bytes = b"") -> bytes:
|
||||
"""A minimal ELF header (183 = aarch64): enough for FramePort's Linux app detection."""
|
||||
head = bytearray(64)
|
||||
head[:4], head[4], head[5] = b"\x7fELF", 2, 1
|
||||
if appimage:
|
||||
head[8:11] = b"AI\x02"
|
||||
head[18:20] = machine.to_bytes(2, "little")
|
||||
return bytes(head) + extra
|
||||
|
||||
|
||||
def add_fake_linux_apps() -> None:
|
||||
"""--linux: an AppImage and a VR app folder (with a helper program, so "Change program…" shows) in the library."""
|
||||
from frameport import pipeline
|
||||
|
||||
base = user_data_dir() / "smoke-linux"
|
||||
app = base / "MatineeVR"
|
||||
(app / "lib").mkdir(parents=True, exist_ok=True)
|
||||
(base / "Venera-2.4.2-aarch64.AppImage").write_bytes(_elf(appimage=True, extra=b"\0" * 4096))
|
||||
(app / "MatineeVR").write_bytes(_elf(extra=b"\0" * 8192))
|
||||
(app / "crashpad_handler").write_bytes(_elf())
|
||||
(app / "lib" / "libopenxr_loader.so.1").write_bytes(_elf(extra=b"xrCreateInstance"))
|
||||
pipeline.add_linux_app(base / "Venera-2.4.2-aarch64.AppImage")
|
||||
pipeline.add_linux_app(app)
|
||||
|
||||
|
||||
def install_fakes(game: str | None, monitor_session=None) -> None:
|
||||
"""--fake-frame: never reach a real Frame (start-up auto-connect, discovery, the 30 s poll); Type on Frame and
|
||||
the Monitor stream are fakes. `game` = the Monitor's game card (with its artwork)."""
|
||||
from frameport.frame import keyboard, monitor
|
||||
|
||||
keyboard.KeyboardSession = FakeKeyboardSession
|
||||
monitor.MonitorSession = monitor_session or FakeMonitorSession
|
||||
FakeMonitorSession.GAME = game
|
||||
FramePortApp.connect = lambda self, *a, **k: None
|
||||
FramePortApp.refresh_frame = lambda self, *a, **k: None
|
||||
install_first_run_fakes()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ first run (the install tutorial)
|
||||
# The setup command shows placeholders for the address and code (each PC has its own; never this PC's real address).
|
||||
PAIR_HOST, PAIR_PORT, PAIR_CODE = "<your-PC-address>", 8765, "<one-time-code>"
|
||||
TOOLS = {"ready": True} # False: the managed tools look missing until the (pretend) download finishes
|
||||
|
||||
|
||||
class FakePairingServer:
|
||||
"""The Frame page's setup command without a server: nothing listens and no firewall rule is touched. The
|
||||
`pairing_done` step hook plays the Frame running the command (on_paired → the pretend Frame connects)."""
|
||||
|
||||
def __init__(self, on_paired=None, host: str = "", **_kw):
|
||||
# host stays as given ("" = over the network; the Frame page words a set host as the USB-cable setup)
|
||||
self.on_paired, self.host = on_paired, host
|
||||
self.port, self.code = PAIR_PORT, PAIR_CODE
|
||||
self.requests, self.failures, self.paired, self.hint = 1, 0, [], "" # (requests: no firewall hint)
|
||||
self.running = False
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f"http://{self.host or PAIR_HOST}:{self.port}"
|
||||
|
||||
@property
|
||||
def one_liner(self) -> str:
|
||||
return f"curl -fsS {self.host or PAIR_HOST}:{self.port}/{self.code} | bash"
|
||||
|
||||
def start(self):
|
||||
self.running = True
|
||||
return self
|
||||
|
||||
def stop_soon(self) -> None:
|
||||
self.running = False
|
||||
|
||||
def stop(self) -> None:
|
||||
self.running = False
|
||||
|
||||
|
||||
def install_first_run_fakes() -> None:
|
||||
"""Fakes for a first start: no Frame discovery on the real network (a recording must not show a real device),
|
||||
the pretend setup command, and the managed tools' state (TOOLS)."""
|
||||
from frameport.frame import discovery, pairing
|
||||
from frameport.tools import toolchain
|
||||
|
||||
discovery.browse = lambda *a, **k: []
|
||||
pairing.PairingServer = FakePairingServer
|
||||
pairing.ensure_reachable = lambda server: "ok"
|
||||
if not getattr(toolchain.status, "_showcase", False):
|
||||
real_status = toolchain.status
|
||||
|
||||
def status(*a, **k):
|
||||
out = real_status(*a, **k)
|
||||
if not TOOLS["ready"]:
|
||||
for s in out:
|
||||
s.installed, s.version = False, None
|
||||
return out
|
||||
status._showcase = True
|
||||
toolchain.status = status
|
||||
|
||||
|
||||
def tools_job(app, pace: float = 1.0, delay: float = 0.0):
|
||||
"""The welcome screen's "Getting FramePort ready": a pretend download of Java, OVRPort and apksigner through the
|
||||
real job queue (app.update_tools while TOOLS["ready"] is False). `delay`: seconds at 0 % first."""
|
||||
from frameport.ui.jobs import Job
|
||||
|
||||
def run(job):
|
||||
rep = job.reporter
|
||||
rep.stage("Downloading tools")
|
||||
time.sleep(delay)
|
||||
parts = [("Java runtime (Temurin 21)", 48.0), ("OVRPort CLI", 21.0), ("apksigner", 1.6)]
|
||||
total = sum(mb for _n, mb in parts)
|
||||
done = 0.0
|
||||
for name, mb in parts:
|
||||
rep.stage(f"Downloading {name}")
|
||||
steps = max(3, int(mb / 4))
|
||||
for i in range(1, steps + 1):
|
||||
got = done + mb * i / steps
|
||||
rep.progress(got / total, f"{name}: {mb * i / steps:.1f} of {mb:.1f} MB")
|
||||
time.sleep(0.12 * pace)
|
||||
done += mb
|
||||
TOOLS["ready"] = True
|
||||
return "FramePort is ready"
|
||||
job = app.jobs.submit(Job("Download tools", run, None, "tools"))
|
||||
return job
|
||||
|
||||
|
||||
def scan_job(app, folder: str, entries: list[dict], pace: float = 1.0):
|
||||
"""Scan a folder: the demo games appear one by one through the real job queue (the folder picker is a native
|
||||
dialog a script can't drive; `entries` = the demo library saved aside by demo_home's "fresh" profile)."""
|
||||
from frameport.artwork import thumbs
|
||||
|
||||
def run(job):
|
||||
rep = job.reporter
|
||||
rep.stage("Looking for games")
|
||||
for i, e in enumerate(entries, 1):
|
||||
rep.progress(i / len(entries), e.get("title") or e["package"])
|
||||
library.upsert_game(e["package"], **{k: v for k, v in e.items() if k != "package"})
|
||||
try:
|
||||
thumbs.prewarm(e["package"])
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
time.sleep(0.12 * pace)
|
||||
library.set_setting("scan.roots", [folder])
|
||||
if app.route[0] == "welcome":
|
||||
library.set_setting("ui.welcome_done", True)
|
||||
return f"{len(entries)} games found in {folder}"
|
||||
return app.submit(f"Scan {folder.rstrip('/').rsplit('/', 1)[-1]}", run, None, "scan")
|
||||
|
||||
|
||||
def attach_fake_frame(app: FramePortApp, monitor_session=None) -> None:
|
||||
"""Connect `app` to a FakeTarget (the shared monitor stream, used by the Monitor tab and the Frame card, too)."""
|
||||
app.monitor_hub.session_factory = monitor_session or FakeMonitorSession
|
||||
app.target = FakeTarget()
|
||||
app.frame_info, app.frame_state = app.target.describe(), "connected"
|
||||
|
||||
|
||||
class FrozenMonitorSession(FakeMonitorSession):
|
||||
"""The fake stream for still pictures: the two minutes of history, then nothing new (every render of a page shows
|
||||
the same numbers, whenever the screenshot is taken)."""
|
||||
|
||||
def _run(self) -> None:
|
||||
self.t = 0
|
||||
while not self.closed:
|
||||
if self.t <= self.BACKFILL:
|
||||
self.on_sample(self._sample())
|
||||
self.t += 1
|
||||
else:
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
class LiveMonitorSession(FakeMonitorSession):
|
||||
"""The fake stream, livelier for videos: a sample every 0.6 s and a steady frame rate with a short, shallow dip
|
||||
now and then (also in the two minutes sent first), so the card's sparkline (5 s points) has a shape and visibly
|
||||
moves without the game looking like it struggles. Seeded: every recording gets the same curve."""
|
||||
|
||||
def _sample(self) -> dict:
|
||||
s = super()._sample()
|
||||
t = self.t
|
||||
rnd = random.Random(t)
|
||||
fps = 72 - abs(rnd.gauss(0, 0.6))
|
||||
if t % 45 in (20, 21, 22): # a short, shallow dip now and then
|
||||
fps = 66 + 2 * abs(t % 45 - 21) + rnd.uniform(-0.8, 0.8)
|
||||
for g in s["games"]:
|
||||
g["fps"] = round(fps, 1)
|
||||
return s
|
||||
|
||||
def _run(self) -> None:
|
||||
self.t = 0
|
||||
while not self.closed and self.t < 100000:
|
||||
self.on_sample(self._sample())
|
||||
if self.t >= self.BACKFILL:
|
||||
time.sleep(0.6)
|
||||
self.t += 1
|
||||
|
||||
def set_modules(self, m):
|
||||
"""Opening the Monitor tab adds modules: on film the stream just goes on, as the real one does (the tab's
|
||||
charts start there and grow live). Replaying the two minutes, as the stills' stream does, showed the charts
|
||||
racing to catch up."""
|
||||
return True
|
||||
|
||||
|
||||
def install_job(package: str, pace: float = 1.0):
|
||||
"""A pretend install of `package` for the real JobManager (app.submit): every stage the real one reports, an
|
||||
upload ticking at a plausible speed, the launch test passing. pace < 1 = faster."""
|
||||
def run(job):
|
||||
rep = job.reporter
|
||||
g = library.game(package) or {}
|
||||
title = g.get("title") or package
|
||||
rnd = random.Random(7)
|
||||
|
||||
def stage(name, secs, logs=()):
|
||||
rep.stage(name)
|
||||
for line in logs:
|
||||
rep.log(line)
|
||||
time.sleep(secs * pace)
|
||||
if g.get("kind") == "rift":
|
||||
stage("Prepare the game", 1.0)
|
||||
else:
|
||||
stage("Patching the game", 0.9)
|
||||
stage("OVRPort (primary)", 1.2, ["overport patch --version=latest"])
|
||||
stage("Frame fixes (primary)", 1.0, list((g.get("recipe") or {}).get("patches") or [])[-3:])
|
||||
stage("sign (primary)", 0.7)
|
||||
rep.stage("validate (primary)")
|
||||
for name in ("APK signature", "64-bit libraries", "OpenXR loader"):
|
||||
rep.check(name, True)
|
||||
time.sleep(0.25 * pace)
|
||||
stage("Prepare Frame", 0.7)
|
||||
total = max(g.get("data_bytes") or 0, 1.4e9)
|
||||
first, steps = 0.42, 14
|
||||
for name, file, lo, hi in (("Upload APK", f"{package}.apk", 0.0, first),
|
||||
("Upload data (3 files)", f"main.1.{package}.obb", first, 1.0)):
|
||||
rep.stage(name)
|
||||
for i in range(1, steps + 1):
|
||||
f = lo + (hi - lo) * i / steps
|
||||
speed = 34.0 + rnd.uniform(0, 4)
|
||||
left = (1 - f) * total / (speed * 1e6)
|
||||
rep.progress(f, file, speed=f"{speed:.1f} MB/s · ~{left:.0f} s left" if f < 1 else f"{speed:.1f} MB/s")
|
||||
time.sleep(0.22 * pace)
|
||||
stage("Artwork for the Steam library", 0.8)
|
||||
stage("Finalize install", 0.9)
|
||||
stage("Add to Steam library", 0.8)
|
||||
stage("Launch test (headless)", 1.8, ["process alive", "OpenXR session created", "frames paced: 72 fps"])
|
||||
job.summary = {"verdict": "pass", "findings": []}
|
||||
rep.stage("Launch test: passed")
|
||||
time.sleep(0.5 * pace)
|
||||
return f"{title} is ready on your Frame: put the headset on and launch it from your Steam library"
|
||||
return run
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Post-production for the demo tour, with ffmpeg only: screencast frames → a constant-frame-rate video, one clip per
|
||||
scene with its caption faded in, title and end cards, crossfades between everything, then the final MP4, a poster and
|
||||
the short looping WebP teaser for the README.
|
||||
|
||||
The filter graphs are built by pure functions (tested without ffmpeg); `run` executes a command and fails loudly.
|
||||
Cards and captions are small HTML pages rendered by the same Chromium (render_card), in the app's own colours.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
FFMPEG = shutil.which("ffmpeg") or "ffmpeg"
|
||||
FPS = 30
|
||||
SIZE = (1920, 1080)
|
||||
|
||||
|
||||
def run(args: list[str]) -> None:
|
||||
cmd = [FFMPEG, "-y", "-hide_banner", "-loglevel", "error", *map(str, args)]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"ffmpeg failed ({r.returncode}): {' '.join(cmd)}\n{r.stderr[-3000:]}")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ frames → video
|
||||
|
||||
def concat_list(frames: list[tuple[float, str]], end: float | None = None, min_frame: float = 1 / 120) -> str:
|
||||
"""An ffconcat script showing each screencast frame until the next one came (Chrome sends frames only on
|
||||
changes); the last one until `end` (wall-clock), else for one frame time."""
|
||||
lines = ["ffconcat version 1.0"]
|
||||
for i, (t, name) in enumerate(frames):
|
||||
nxt = frames[i + 1][0] if i + 1 < len(frames) else (end if end is not None else t + 1 / FPS)
|
||||
lines += [f"file '{name}'", f"duration {max(min_frame, nxt - t):.6f}"]
|
||||
if frames:
|
||||
lines.append(f"file '{frames[-1][1]}'") # ffconcat: the last entry's duration needs a following file
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def frames_to_video(folder: Path, out: Path, end: float | None = None, size: tuple[int, int] = SIZE) -> float:
|
||||
"""The screencast (folder/frames.json + JPEGs) as a constant-frame-rate H.264 file (high quality, an
|
||||
intermediate). Returns the wall-clock time of its first frame (scene times are relative to it)."""
|
||||
frames = [tuple(f) for f in json.loads((folder / "frames.json").read_text())]
|
||||
if not frames:
|
||||
raise RuntimeError("the screencast has no frames")
|
||||
(folder / "frames.ffconcat").write_text(concat_list(frames, end))
|
||||
w, h = size
|
||||
run(["-f", "concat", "-safe", "0", "-i", folder / "frames.ffconcat",
|
||||
"-vf", f"fps={FPS},scale={w}:{h}:flags=lanczos:force_original_aspect_ratio=decrease,"
|
||||
f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,format=yuv420p",
|
||||
"-c:v", "libx264", "-preset", "veryfast", "-crf", "12", out])
|
||||
return frames[0][0]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ scenes
|
||||
|
||||
def caption_window(duration: float, show: float = 4.2, fade: float = 0.45, lead: float = 0.35) -> tuple[float, float]:
|
||||
"""When a scene's caption is on screen: from `lead` s in, for `show` s (shorter scenes: until 0.6 s before
|
||||
their end), fading `fade` s in and out. Returns (start, end)."""
|
||||
start = min(lead, max(0.0, duration / 4))
|
||||
end = min(start + show, max(start + 2 * fade, duration - 0.6))
|
||||
return start, end
|
||||
|
||||
|
||||
def scene_filter(duration: float, fade: float = 0.45, size: tuple[int, int] = SIZE) -> str:
|
||||
"""The filter graph laying a caption (input 1, a still RGBA PNG looped) over a scene (input 0)."""
|
||||
start, end = caption_window(duration, fade=fade)
|
||||
return (f"[1:v]scale={size[0]}:{size[1]}:flags=lanczos,format=rgba,fade=t=in:st={start:.3f}:d={fade}:alpha=1,"
|
||||
f"fade=t=out:st={end - fade:.3f}:d={fade}:alpha=1[cap];"
|
||||
f"[0:v][cap]overlay=0:0:format=auto:shortest=1,format=yuv420p[v]")
|
||||
|
||||
|
||||
def cut_scene(raw: Path, start: float, duration: float, caption: Path | None, out: Path,
|
||||
size: tuple[int, int] = SIZE) -> None:
|
||||
"""One scene from the raw recording, with its caption."""
|
||||
if caption is None:
|
||||
run(["-ss", f"{start:.3f}", "-t", f"{duration:.3f}", "-i", raw, "-an",
|
||||
"-c:v", "libx264", "-preset", "veryfast", "-crf", "12", "-pix_fmt", "yuv420p", out])
|
||||
return
|
||||
run(["-ss", f"{start:.3f}", "-t", f"{duration:.3f}", "-i", raw,
|
||||
"-loop", "1", "-t", f"{duration:.3f}", "-i", caption,
|
||||
"-filter_complex", scene_filter(duration, size=size), "-map", "[v]", "-an", "-r", FPS,
|
||||
"-c:v", "libx264", "-preset", "veryfast", "-crf", "12", out])
|
||||
|
||||
|
||||
def card_clip(image: Path, duration: float, out: Path, zoom: float = 0.03) -> None:
|
||||
"""A title/end card: the still, slowly zooming in by `zoom` over its duration (alive, not frozen)."""
|
||||
frames = max(1, int(duration * FPS))
|
||||
w, h = SIZE
|
||||
run(["-loop", "1", "-t", f"{duration:.3f}", "-i", image,
|
||||
"-vf", f"scale={w * 2}:{h * 2},zoompan=z='1+{zoom}*on/{frames}':x='iw/2-(iw/zoom/2)':"
|
||||
f"y='ih/2-(ih/zoom/2)':d={frames}:s={w}x{h}:fps={FPS},format=yuv420p",
|
||||
"-frames:v", frames, "-c:v", "libx264", "-preset", "veryfast", "-crf", "12", out])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ joining
|
||||
|
||||
def xfade_offsets(durations: list[float], transition: float) -> list[float]:
|
||||
"""Where each crossfade starts on the joined timeline: clip k+1 begins `transition` s before clip k ends."""
|
||||
offsets, total = [], 0.0
|
||||
for d in durations[:-1]:
|
||||
total += d - transition
|
||||
offsets.append(round(total, 3))
|
||||
return offsets
|
||||
|
||||
|
||||
def xfade_graph(durations: list[float], transition: float, size: tuple[int, int] = SIZE) -> tuple[str, str]:
|
||||
"""(filter graph, output label) crossfading inputs 0..n-1 in order. Every input is brought to the same size,
|
||||
frame rate, timebase and pixel format first (xfade refuses anything else)."""
|
||||
w, h = size
|
||||
parts = [f"[{k}:v]fps={FPS},scale={w}:{h}:flags=lanczos,setsar=1,format=yuv420p,settb=AVTB[n{k}]"
|
||||
for k in range(len(durations))]
|
||||
prev = "[n0]"
|
||||
for k, off in enumerate(xfade_offsets(durations, transition), start=1):
|
||||
label = f"[x{k}]"
|
||||
parts.append(f"{prev}[n{k}]xfade=transition=fade:duration={transition}:offset={off}{label}")
|
||||
prev = label
|
||||
parts.append(f"{prev}format=yuv420p[vout]")
|
||||
return ";".join(parts), "[vout]"
|
||||
|
||||
|
||||
def joined_length(durations: list[float], transition: float) -> float:
|
||||
return sum(durations) - transition * (len(durations) - 1)
|
||||
|
||||
|
||||
def join(clips: list[Path], durations: list[float], out: Path, transition: float = 0.5, crf: int = 23,
|
||||
size: tuple[int, int] = SIZE, extra: list[str] | None = None) -> None:
|
||||
graph, label = xfade_graph(durations, transition, size)
|
||||
args = []
|
||||
for c in clips:
|
||||
args += ["-i", c]
|
||||
run([*args, "-filter_complex", graph, "-map", label, "-an", "-r", FPS, "-c:v", "libx264", "-preset", "slow",
|
||||
"-crf", crf, "-pix_fmt", "yuv420p", "-movflags", "+faststart", *(extra or []), out])
|
||||
|
||||
|
||||
def encode_within(clips: list[Path], durations: list[float], out: Path, budget_mb: float, transition: float = 0.5,
|
||||
crf: int = 22, max_crf: int = 32) -> int:
|
||||
"""The final MP4 at the best quality (lowest CRF) that fits `budget_mb`. Returns the CRF used."""
|
||||
while True:
|
||||
join(clips, durations, out, transition, crf)
|
||||
if out.stat().st_size <= budget_mb * 1e6 or crf >= max_crf:
|
||||
return crf
|
||||
crf += 2
|
||||
|
||||
|
||||
def poster(video: Path, at: float, out: Path) -> None:
|
||||
run(["-ss", f"{at:.2f}", "-i", video, "-frames:v", "1", "-q:v", "2", out])
|
||||
|
||||
|
||||
def teaser_webp(clips: list[Path], durations: list[float], out: Path, width: int = 960, fps: int = 15,
|
||||
budget_mb: float = 4.0, transition: float = 0.35) -> int:
|
||||
"""A looping animated WebP of the highlight clips (README: plays inline where an MP4 wouldn't). Lowers the
|
||||
quality until it fits `budget_mb`. Returns the quality used."""
|
||||
graph, label = xfade_graph(durations, transition)
|
||||
graph = graph.replace("format=yuv420p[vout]", f"fps={fps},scale={width}:-2:flags=lanczos[vout]")
|
||||
args = []
|
||||
for c in clips:
|
||||
args += ["-i", c]
|
||||
quality = 72
|
||||
while True:
|
||||
run([*args, "-filter_complex", graph, "-map", label, "-an", "-c:v", "libwebp_anim", "-lossless", "0",
|
||||
"-quality", quality, "-compression_level", "6", "-loop", "0", out])
|
||||
if out.stat().st_size <= budget_mb * 1e6 or quality <= 30:
|
||||
return quality
|
||||
quality -= 8
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ cards and captions
|
||||
|
||||
def theme_colors(name: str = "portal") -> dict:
|
||||
from frameport.ui import theme as T
|
||||
|
||||
T.set_theme(name)
|
||||
return {k: getattr(T, k) for k in ("BG", "SURFACE", "SURFACE_2", "BORDER", "TEXT", "TEXT_2", "TEXT_3", "ACCENT",
|
||||
"SECONDARY")}
|
||||
|
||||
|
||||
FONT_CSS = ('<link rel="preconnect" href="https://fonts.gstatic.com">'
|
||||
'<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=block" '
|
||||
'rel="stylesheet">')
|
||||
FONT = "'Roboto', 'Segoe UI', system-ui, sans-serif"
|
||||
|
||||
|
||||
def caption_html(title: str, subtitle: str, c: dict, left: int = 372, bottom: int = 56) -> str:
|
||||
"""A lower third: a dark glass panel with a blue→orange edge (the logo's two portals), title + one line."""
|
||||
e = html.escape
|
||||
return f"""<!doctype html><html><head><meta charset="utf-8">{FONT_CSS}<style>
|
||||
html,body{{margin:0;width:{SIZE[0]}px;height:{SIZE[1]}px;background:transparent;font-family:{FONT}}}
|
||||
.cap{{position:absolute;left:{left}px;bottom:{bottom}px;max-width:1180px;padding:26px 40px 28px 44px;
|
||||
border-radius:22px;background:rgba(12,14,20,.86);box-shadow:0 18px 50px rgba(0,0,0,.55),
|
||||
inset 0 0 0 1px rgba(255,255,255,.08);overflow:hidden}}
|
||||
.cap:before{{content:"";position:absolute;left:0;top:0;bottom:0;width:8px;
|
||||
background:linear-gradient(180deg,{c['SECONDARY']},{c['ACCENT']})}}
|
||||
h1{{margin:0;font-size:46px;font-weight:700;color:{c['TEXT']};letter-spacing:-.3px}}
|
||||
p{{margin:10px 0 0;font-size:28px;font-weight:400;color:{c['TEXT_2']}}}
|
||||
</style></head><body><div class="cap"><h1>{e(title)}</h1>{f'<p>{e(subtitle)}</p>' if subtitle else ''}</div>
|
||||
</body></html>"""
|
||||
|
||||
|
||||
def card_html(title: str, subtitle: str, footer: str, logo_svg: str, c: dict) -> str:
|
||||
"""A full-screen card: the logo, the two-colour wordmark, a line, a footer; a soft portal glow behind."""
|
||||
e = html.escape
|
||||
word = ('<span style="color:{a}">Frame</span><span style="color:{b}">Port</span>'
|
||||
.format(a=c["ACCENT"], b=c["SECONDARY"])) if title == "FramePort" else e(title)
|
||||
return f"""<!doctype html><html><head><meta charset="utf-8">{FONT_CSS}<style>
|
||||
html,body{{margin:0;width:{SIZE[0]}px;height:{SIZE[1]}px;background:{c['BG']};font-family:{FONT};overflow:hidden}}
|
||||
.glow{{position:absolute;inset:0;
|
||||
background:radial-gradient(ellipse 46% 52% at 42% 50%,{c['SECONDARY']}33,transparent 70%),
|
||||
radial-gradient(ellipse 46% 52% at 58% 50%,{c['ACCENT']}2e,transparent 70%)}}
|
||||
.wrap{{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center}}
|
||||
.logo{{width:220px;height:220px;filter:drop-shadow(0 18px 40px rgba(0,0,0,.6))}}
|
||||
.logo svg{{width:100%;height:100%}}
|
||||
h1{{margin:34px 0 0;font-size:112px;font-weight:900;letter-spacing:-2px;color:{c['TEXT']}}}
|
||||
p{{margin:18px 0 0;font-size:38px;color:{c['TEXT_2']};font-weight:400}}
|
||||
.foot{{position:absolute;bottom:64px;left:0;right:0;text-align:center;font-size:26px;color:{c['TEXT_3']}}}
|
||||
</style></head><body><div class="glow"></div><div class="wrap"><div class="logo">{logo_svg}</div>
|
||||
<h1>{word}</h1><p>{e(subtitle)}</p></div><div class="foot">{e(footer)}</div></body></html>"""
|
||||
|
||||
|
||||
def step_card_html(card: dict, c: dict) -> str:
|
||||
"""An instruction card for what happens outside FramePort (a download, a command on the Frame): an eyebrow
|
||||
(where you are), a heading, numbered steps, an optional command in a terminal box and a note. Steps and the note
|
||||
may mark words **bold** (a button or menu name)."""
|
||||
e = html.escape
|
||||
|
||||
def rich(text: str) -> str:
|
||||
return re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", e(text))
|
||||
steps = "".join(f'<li><span class="n">{i}</span><span>{rich(s)}</span></li>'
|
||||
for i, s in enumerate(card.get("steps") or [], 1))
|
||||
code = (f'<div class="code"><span class="prompt">$</span>{e(card["code"])}</div>' if card.get("code") else "")
|
||||
return f"""<!doctype html><html><head><meta charset="utf-8">{FONT_CSS}<style>
|
||||
html,body{{margin:0;width:{SIZE[0]}px;height:{SIZE[1]}px;background:{c['BG']};font-family:{FONT};overflow:hidden}}
|
||||
.glow{{position:absolute;inset:0;
|
||||
background:radial-gradient(ellipse 40% 55% at 12% 30%,{c['SECONDARY']}26,transparent 70%),
|
||||
radial-gradient(ellipse 45% 55% at 92% 80%,{c['ACCENT']}22,transparent 70%)}}
|
||||
.wrap{{position:absolute;left:180px;right:180px;top:0;bottom:0;display:flex;flex-direction:column;
|
||||
justify-content:center;gap:30px}}
|
||||
.eyebrow{{font:600 26px/1 'Roboto Mono','Consolas',monospace;letter-spacing:3px;text-transform:uppercase;
|
||||
color:{c['ACCENT']}}}
|
||||
h1{{margin:0;font-size:76px;font-weight:700;letter-spacing:-1px;color:{c['TEXT']};line-height:1.08}}
|
||||
.line{{margin:0;font-size:34px;color:{c['TEXT_2']};max-width:1400px;line-height:1.35}}
|
||||
ol{{list-style:none;margin:8px 0 0;padding:0;display:flex;flex-direction:column;gap:22px}}
|
||||
li{{display:flex;gap:26px;align-items:baseline;font-size:36px;color:{c['TEXT']};line-height:1.35}}
|
||||
li b{{color:{c['ACCENT']};font-weight:700}}
|
||||
.n{{flex:none;width:56px;height:56px;border-radius:50%;display:inline-flex;align-items:center;
|
||||
justify-content:center;font-weight:700;font-size:28px;color:{c['TEXT']};position:relative;top:-4px;
|
||||
background:linear-gradient(135deg,{c['SECONDARY']}66,{c['ACCENT']}88)}}
|
||||
.code{{margin-top:6px;align-self:flex-start;max-width:100%;padding:26px 36px;border-radius:18px;
|
||||
background:#05060A;border:2px solid {c['BORDER']};font:500 40px/1.3 'Roboto Mono','Consolas',monospace;
|
||||
color:#E8F1FF;box-shadow:0 20px 60px rgba(0,0,0,.5)}}
|
||||
.prompt{{color:{c['SECONDARY']};margin-right:22px}}
|
||||
.note{{margin:0;font-size:26px;color:{c['TEXT_3']};max-width:1400px}}
|
||||
.note b{{color:{c['TEXT_2']}}}
|
||||
.brand{{position:absolute;left:180px;bottom:54px;font-size:26px;font-weight:900;letter-spacing:-.3px}}
|
||||
</style></head><body><div class="glow"></div><div class="wrap">
|
||||
{f'<div class="eyebrow">{e(card["eyebrow"])}</div>' if card.get("eyebrow") else ''}
|
||||
<h1>{e(card["heading"])}</h1>
|
||||
{f'<p class="line">{rich(card["line"])}</p>' if card.get("line") else ''}
|
||||
{f'<ol>{steps}</ol>' if steps else ''}{code}
|
||||
{f'<p class="note">{rich(card["note"])}</p>' if card.get("note") else ''}
|
||||
</div><div class="brand"><span style="color:{c['ACCENT']}">Frame</span><span style="color:{c['SECONDARY']}">Port</span>
|
||||
</div></body></html>"""
|
||||
|
||||
|
||||
def render_card(playwright, page_html: str, out: Path, transparent: bool = False) -> Path:
|
||||
"""Render an HTML card to a PNG at the video size (fonts loaded first)."""
|
||||
browser = playwright.chromium.launch()
|
||||
try:
|
||||
page = browser.new_page(viewport={"width": SIZE[0], "height": SIZE[1]})
|
||||
page.set_content(page_html, wait_until="networkidle")
|
||||
page.evaluate("document.fonts.ready")
|
||||
page.screenshot(path=str(out), omit_background=transparent)
|
||||
finally:
|
||||
browser.close()
|
||||
return out
|
||||
@@ -0,0 +1,334 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record the showcase videos (docs/showcase/videos/<name>.yaml): the real GUI on the demo library with a pretend
|
||||
Frame, driven like a person would (a drawn pointer on eased paths), filmed with Chrome's screencast; then each scene
|
||||
captioned, instruction cards rendered for what happens outside FramePort (a download, a command on the Frame), title
|
||||
and end cards added and everything joined with crossfades.
|
||||
|
||||
python scripts/showcase/record_video.py # every video
|
||||
python scripts/showcase/record_video.py tour install # some
|
||||
python scripts/showcase/record_video.py install --draft # quick 720p check of a storyboard edit (work dir only)
|
||||
python scripts/showcase/record_video.py --changed-since <git rev> # the ones whose storyboard (or this code)
|
||||
# changed since then (CI)
|
||||
|
||||
Each video writes its `output` MP4 (+ .jpg poster) and, when it has `teaser` parts, its teaser WebP; a video.json
|
||||
timeline goes next to the work files (--work). --names prints what can be clicked after each scene, --scenes records
|
||||
only some scenes (with --draft). SHOWCASE_DEBUG=1 prints every step with its start time. See docs/SHOWCASE.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = HERE.parents[1]
|
||||
sys.path[:0] = [str(HERE.parent), str(REPO / "src")]
|
||||
|
||||
from showcase import demo_home # noqa: E402
|
||||
|
||||
VIDEOS = REPO / "docs" / "showcase" / "videos"
|
||||
VIDEO_KEYS = {"output", "teaser", "budget_mb", "poster_at", "start", "setup", "vars", "title", "end", "scenes"}
|
||||
START_KEYS = {"profile", "frame", "stream", "route"}
|
||||
SCENE_KEYS = {"name", "caption", "teaser", "hold", "steps", "card", "seconds"}
|
||||
CARD_KEYS = {"eyebrow", "heading", "line", "steps", "code", "note"}
|
||||
VIEWPORT = (1440, 810) # the layout size; filmed at 4/3 device pixels = 1920x1080
|
||||
TEASER_MB = 4.0
|
||||
|
||||
|
||||
def video_names() -> list[str]:
|
||||
return sorted(p.stem for p in VIDEOS.glob("*.yaml"))
|
||||
|
||||
|
||||
def load_video(name: str) -> dict:
|
||||
"""A storyboard, checked (StepError for anything malformed: before a recording starts, and in the tests)."""
|
||||
import yaml
|
||||
|
||||
from showcase import steps
|
||||
|
||||
path = VIDEOS / f"{name}.yaml"
|
||||
where = f"videos/{name}.yaml"
|
||||
data = yaml.safe_load(path.read_text())
|
||||
unknown = set(data) - VIDEO_KEYS
|
||||
if unknown:
|
||||
raise steps.StepError(f"{where}: unknown key(s) {sorted(unknown)}")
|
||||
if not str(data.get("output") or "").endswith(".mp4"):
|
||||
raise steps.StepError(f"{where}: output must be an .mp4 path")
|
||||
if data.get("teaser") is not None and not str(data["teaser"]).endswith(".webp"):
|
||||
raise steps.StepError(f"{where}: teaser must be a .webp path")
|
||||
start = data.get("start") or {}
|
||||
if set(start) - START_KEYS:
|
||||
raise steps.StepError(f"{where}: start: unknown key(s) {sorted(set(start) - START_KEYS)}")
|
||||
if start.get("profile", "demo") not in demo_home.PROFILES:
|
||||
raise steps.StepError(f"{where}: start.profile is one of {', '.join(demo_home.PROFILES)}")
|
||||
if start.get("frame", "connected") not in ("connected", "disconnected"):
|
||||
raise steps.StepError(f"{where}: start.frame is connected or disconnected")
|
||||
if start.get("stream", "live") not in ("live", "frozen"):
|
||||
raise steps.StepError(f"{where}: start.stream is live or frozen")
|
||||
steps.validate(data.get("setup") or [], f"{where} setup")
|
||||
seen = set()
|
||||
for sc in data.get("scenes") or []:
|
||||
name_ = sc.get("name")
|
||||
if not name_ or name_ in seen:
|
||||
raise steps.StepError(f"{where}: missing or repeated scene name {name_!r}")
|
||||
seen.add(name_)
|
||||
if set(sc) - SCENE_KEYS:
|
||||
raise steps.StepError(f"{where}: {name_}: unknown key(s) {sorted(set(sc) - SCENE_KEYS)}")
|
||||
if "card" in sc: # an instruction card: rendered, not filmed
|
||||
card = sc["card"]
|
||||
if not isinstance(card, dict) or not card.get("heading") or set(card) - CARD_KEYS:
|
||||
raise steps.StepError(f"{where}: {name_}: card needs a heading (keys: {', '.join(sorted(CARD_KEYS))})")
|
||||
if "steps" in sc or "caption" in sc or "teaser" in sc:
|
||||
raise steps.StepError(f"{where}: {name_}: a card scene has no steps, caption or teaser")
|
||||
if not isinstance(sc.get("seconds", 5), (int, float)) or sc.get("seconds", 5) <= 0:
|
||||
raise steps.StepError(f"{where}: {name_}: seconds must be positive")
|
||||
continue
|
||||
cap = sc.get("caption")
|
||||
if cap is not None and not (isinstance(cap, list) and 1 <= len(cap) <= 2):
|
||||
raise steps.StepError(f"{where}: {name_}: caption is [title] or [title, line]")
|
||||
teaser = sc.get("teaser")
|
||||
if teaser is not None and not (isinstance(teaser, list) and len(teaser) == 2 and teaser[1] > 0):
|
||||
raise steps.StepError(f"{where}: {name_}: teaser is [from, seconds]")
|
||||
steps.validate(sc.get("steps") or [], f"{where} {name_}")
|
||||
if not seen:
|
||||
raise steps.StepError(f"{where}: no scenes")
|
||||
for card in ("title", "end"):
|
||||
if not (data.get(card) or {}).get("heading"):
|
||||
raise steps.StepError(f"{where}: {card} needs a heading")
|
||||
return data
|
||||
|
||||
|
||||
def changed_videos(since: str) -> list[str]:
|
||||
"""The videos to record again after the commits since `since`: all when the recorder or the step language
|
||||
changed, else the ones whose storyboard changed."""
|
||||
out = subprocess.run(["git", "diff", "--name-only", since, "HEAD"], cwd=REPO, capture_output=True, text=True)
|
||||
if out.returncode != 0:
|
||||
return video_names() # (unknown base, e.g. a new branch): everything
|
||||
files = out.stdout.split()
|
||||
if any(f.startswith("scripts/showcase/") for f in files):
|
||||
return video_names()
|
||||
return sorted({Path(f).stem for f in files if f.startswith("docs/showcase/videos/") and f.endswith(".yaml")}
|
||||
& set(video_names()))
|
||||
|
||||
|
||||
def video_installs(session, pace: float = 0.5) -> None:
|
||||
"""Installs in a video run the scripted job (every real stage, nothing built or sent) through the real queue,
|
||||
and leave the game installed on the pretend Frame."""
|
||||
from frameport.core import library
|
||||
from showcase import fakes
|
||||
|
||||
app = session.app
|
||||
|
||||
def submit(pkg: str, to: str = "frame"):
|
||||
script = fakes.install_job(pkg, pace)
|
||||
|
||||
def run(job):
|
||||
message = script(job)
|
||||
g = library.game(pkg)
|
||||
if app.target is not None and g:
|
||||
app.target.games.append(fakes.FakeTarget._record(g))
|
||||
app.frame_info = app.target.describe()
|
||||
now = time.time()
|
||||
library.upsert_game(pkg, installs={"frame": {"result": {"ok": True}, "time": now}},
|
||||
last_test={"state": "RUNNING", "verdict": "pass", "milestone": "Submitting frames",
|
||||
"fps": 72.0, "findings": [], "suggestions": [], "time": now,
|
||||
"target": "frame"})
|
||||
return message
|
||||
return app.submit(f"Install {app._title(pkg)} on Frame", run, pkg, "install", to="frame")
|
||||
app._submit_install = submit
|
||||
|
||||
|
||||
def print_names(session, scene: str) -> None:
|
||||
names = sorted({(n["label"] or n["text"] or n["all"].splitlines()[-1] if n["all"] else "")[:60]
|
||||
for n in session.nodes() if n["tappable"]} - {""})
|
||||
print(f"NAMES after {scene}: {names}", flush=True)
|
||||
|
||||
|
||||
def record(name: str, args) -> int:
|
||||
"""Record one video in this process."""
|
||||
video = load_video(name)
|
||||
start = video.get("start") or {}
|
||||
scenes = video["scenes"]
|
||||
if args.scenes:
|
||||
want = args.scenes.split(",")
|
||||
scenes = [s for s in scenes if s["name"] in want]
|
||||
work = (args.work / name) if args.work else Path(tempfile.mkdtemp(prefix=f"fp-video-{name}-"))
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
home = (args.home / name) if args.home else Path(tempfile.mkdtemp(prefix="fp-video-home-"))
|
||||
demo_home.build_for_render(home, offline=args.offline, allow_missing_art=args.allow_missing_art,
|
||||
profile=start.get("profile", "demo"))
|
||||
|
||||
from showcase import postprod, steps
|
||||
from showcase.fakes import FrozenMonitorSession, LiveMonitorSession
|
||||
from showcase.web import Screencast, Server
|
||||
|
||||
variables = video.get("vars") or {}
|
||||
started = time.monotonic()
|
||||
step_log = (lambda msg: print(f"{time.monotonic() - started:7.1f} {msg}", flush=True)) \
|
||||
if os.environ.get("SHOWCASE_DEBUG") else None
|
||||
|
||||
def script(server) -> int:
|
||||
scale = 1.0 if args.draft else 4 / 3
|
||||
s = server.session(VIEWPORT, cursor=True, device_scale=scale)
|
||||
video_installs(s)
|
||||
if start.get("frame") == "disconnected":
|
||||
steps.HOOKS["disconnect"](s)
|
||||
steps.run(s, video.get("setup") or [], variables, log=step_log) # before filming: a failure stops here
|
||||
s.app.go(start.get("route", "library"))
|
||||
s.sleep(2.5)
|
||||
s.park()
|
||||
cast = Screencast(s, work / "frames", quality=80 if args.draft else 92)
|
||||
cast.start()
|
||||
s.sleep(0.8)
|
||||
timeline = []
|
||||
for sc in scenes:
|
||||
if "card" in sc: # rendered later: nothing to film
|
||||
timeline.append({"name": sc["name"], "card": True, "seconds": sc.get("seconds", 5)})
|
||||
continue
|
||||
t0 = time.time()
|
||||
print(f"SCENE {sc['name']}", flush=True)
|
||||
try:
|
||||
steps.run(s, sc.get("steps") or [], variables, log=step_log)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
server.errors.append(f"scene {sc['name']}: {exc!r}")
|
||||
s.sleep(sc.get("hold", 0.6))
|
||||
timeline.append({"name": sc["name"], "start": t0, "end": time.time()})
|
||||
if args.names:
|
||||
print_names(s, sc["name"])
|
||||
cast.stop()
|
||||
cast.write_index()
|
||||
s.close()
|
||||
return produce(server, timeline)
|
||||
|
||||
def produce(server, timeline) -> int:
|
||||
size = (1280, 720) if args.draft else postprod.SIZE
|
||||
filmed = [t for t in timeline if not t.get("card")]
|
||||
raw = work / "raw.mp4"
|
||||
first = postprod.frames_to_video(work / "frames", raw, end=filmed[-1]["end"], size=size) if filmed else 0
|
||||
colors = postprod.theme_colors("portal")
|
||||
logo = (REPO / "src" / "frameport" / "ui" / "icons" / "logo.svg").read_text()
|
||||
cards = work / "cards"
|
||||
cards.mkdir(exist_ok=True)
|
||||
|
||||
def end_card(which: str) -> tuple[Path, float]:
|
||||
c = video[which]
|
||||
png = postprod.render_card(server.playwright, postprod.card_html(
|
||||
c["heading"], c.get("line", ""), c.get("footer", ""), logo, colors), cards / f"{which}.png")
|
||||
clip = work / f"{which}.mp4"
|
||||
postprod.card_clip(png, c.get("seconds", 3.0), clip)
|
||||
return clip, c.get("seconds", 3.0)
|
||||
|
||||
clip, secs = end_card("title")
|
||||
clips, durations, scene_clips = [clip], [secs], {}
|
||||
by_name = {sc["name"]: sc for sc in scenes}
|
||||
for item in timeline:
|
||||
sc = by_name[item["name"]]
|
||||
if item.get("card"):
|
||||
png = postprod.render_card(server.playwright, postprod.step_card_html(sc["card"], colors),
|
||||
cards / f"card-{sc['name']}.png")
|
||||
clip = work / f"card-{sc['name']}.mp4"
|
||||
postprod.card_clip(png, item["seconds"], clip, zoom=0.015)
|
||||
clips.append(clip)
|
||||
durations.append(item["seconds"])
|
||||
continue
|
||||
start_s, length = item["start"] - first, item["end"] - item["start"]
|
||||
cap = None
|
||||
if sc.get("caption"):
|
||||
title, line = (sc["caption"] + [""])[:2]
|
||||
cap = postprod.render_card(server.playwright, postprod.caption_html(title, line, colors),
|
||||
cards / f"cap-{sc['name']}.png", transparent=True)
|
||||
clip = work / f"scene-{sc['name']}.mp4"
|
||||
postprod.cut_scene(raw, max(0.0, start_s), length, cap, clip, size=size)
|
||||
clips.append(clip)
|
||||
durations.append(length)
|
||||
scene_clips[sc["name"]] = (clip, length)
|
||||
item.update(clip_start=round(start_s, 3), seconds=round(length, 3))
|
||||
clip, secs = end_card("end")
|
||||
clips.append(clip)
|
||||
durations.append(secs)
|
||||
transition = 0.25 if args.draft else 0.5
|
||||
if args.draft:
|
||||
out = work / f"{name}-draft.mp4"
|
||||
postprod.join(clips, durations, out, transition=transition, crf=28, size=size)
|
||||
crf = 28
|
||||
else:
|
||||
out = REPO / video["output"]
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
crf = postprod.encode_within(clips, durations, out, float(video.get("budget_mb", 12)))
|
||||
postprod.poster(out, durations[0] + float(video.get("poster_at", 1.5)), out.with_suffix(".jpg"))
|
||||
parts, lengths = [], []
|
||||
for sc in scenes: # the teaser: each scene's `teaser` part (with its caption)
|
||||
if sc.get("teaser") and sc["name"] in scene_clips:
|
||||
frm, secs = sc["teaser"]
|
||||
part = work / f"teaser-{sc['name']}.mp4"
|
||||
postprod.run(["-ss", f"{frm:.2f}", "-t", f"{secs:.2f}", "-i", scene_clips[sc["name"]][0],
|
||||
"-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "14", part])
|
||||
parts.append(part)
|
||||
lengths.append(secs)
|
||||
if parts and video.get("teaser"):
|
||||
teaser = REPO / video["teaser"]
|
||||
teaser.parent.mkdir(parents=True, exist_ok=True)
|
||||
q = postprod.teaser_webp(parts, lengths, teaser, budget_mb=TEASER_MB)
|
||||
print(f"TEASER {teaser} ({teaser.stat().st_size / 1e6:.2f} MB, quality {q})", flush=True)
|
||||
# where each scene starts in the finished video (chapters)
|
||||
at = durations[0] - transition
|
||||
for item, d in zip(timeline, durations[1:-1], strict=True):
|
||||
item["at"] = round(at, 2)
|
||||
at += d - transition
|
||||
total = postprod.joined_length(durations, transition)
|
||||
(work / "video.json").write_text(json.dumps({"video": name, "scenes": timeline, "seconds": round(total, 2),
|
||||
"crf": crf, "output": str(out)}, indent=1))
|
||||
print(f"VIDEO {name}: {out} ({out.stat().st_size / 1e6:.2f} MB, {total:.1f} s, crf {crf}); work: {work}",
|
||||
flush=True)
|
||||
return 0
|
||||
|
||||
stream = FrozenMonitorSession if start.get("stream") == "frozen" else LiveMonitorSession
|
||||
return Server(monitor_session=stream).run(script)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("videos", nargs="*", help=f"video names (default: all of {', '.join(video_names())})")
|
||||
ap.add_argument("--changed-since", default=None, help="only videos whose storyboard (or the recorder) changed "
|
||||
"since this git revision")
|
||||
ap.add_argument("--scenes", default=None, help="comma-separated scene names (one video)")
|
||||
ap.add_argument("--draft", action="store_true", help="720p, quick, no teaser; nothing written to docs/")
|
||||
ap.add_argument("--names", action="store_true", help="print the clickable names after each scene")
|
||||
ap.add_argument("--work", type=Path, default=None, help="folder for frames and clips (<work>/<video>)")
|
||||
ap.add_argument("--home", type=Path, default=None, help="demo data dirs (<home>/<video>; default: temp)")
|
||||
ap.add_argument("--offline", action="store_true", help="use only cached art")
|
||||
ap.add_argument("--allow-missing-art", action="store_true", help="render even when a game got no art")
|
||||
args = ap.parse_args()
|
||||
names = args.videos or (changed_videos(args.changed_since) if args.changed_since else video_names())
|
||||
unknown = set(names) - set(video_names())
|
||||
if unknown:
|
||||
print(f"unknown video(s): {sorted(unknown)} (known: {', '.join(video_names())})", file=sys.stderr)
|
||||
return 2
|
||||
for name in names:
|
||||
load_video(name) # every storyboard checked before anything is recorded
|
||||
if not names:
|
||||
print("no video to record", flush=True)
|
||||
return 0
|
||||
if len(names) == 1:
|
||||
return record(names[0], args)
|
||||
# one process per video: each builds its own demo data dir (the app reads it per process)
|
||||
failed = []
|
||||
passed = [*(["--draft"] if args.draft else []), *(["--names"] if args.names else []),
|
||||
*(["--offline"] if args.offline else []), *(["--allow-missing-art"] if args.allow_missing_art else []),
|
||||
*(["--work", str(args.work)] if args.work else []), *(["--home", str(args.home)] if args.home else [])]
|
||||
for name in names:
|
||||
cmd = [sys.executable, __file__, name, *passed]
|
||||
print(f"RECORD {name}", flush=True)
|
||||
if subprocess.run(cmd).returncode != 0:
|
||||
failed.append(name)
|
||||
if failed:
|
||||
print(f"failed: {', '.join(failed)}", file=sys.stderr)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the docs screenshots (docs/showcase/shots.yaml) from the demo library with a pretend Frame, and write each
|
||||
into docs/images/ only when the picture really changed (anti-aliasing noise doesn't count).
|
||||
|
||||
python scripts/showcase/render_docs.py [--only library,game] [--check] [--out docs/images] [--offline]
|
||||
|
||||
--check renders into a temp folder and exits 1 if any docs image is out of date (CI). Needs the dev extras
|
||||
(flet-web, playwright + `playwright install chromium`). See docs/SHOWCASE.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = HERE.parents[1]
|
||||
sys.path[:0] = [str(HERE.parent), str(REPO / "src")]
|
||||
|
||||
from showcase import demo_home # noqa: E402
|
||||
|
||||
MANIFEST = REPO / "docs" / "showcase" / "shots.yaml"
|
||||
IMAGES = REPO / "docs" / "images"
|
||||
SHOT_KEYS = {"name", "docs", "steps", "viewport", "scale", "crop"}
|
||||
# a picture counts as changed when the mean difference per channel exceeds MEAN_LIMIT (0-255 scale) or more than
|
||||
# PIXEL_SHARE of its pixels differ by more than PIXEL_LIMIT in some channel. Measured: run-to-run noise (the live
|
||||
# card's sparkline) stays under 0.007 % of the pixels; the smallest real change seen (the sidebar card showing
|
||||
# another game) is 0.12 %
|
||||
MEAN_LIMIT, PIXEL_LIMIT, PIXEL_SHARE = 0.5, 24, 0.0004
|
||||
ATTEMPTS = 2 # a shot whose steps fail (e.g. the window never connected) is tried once more in a fresh window
|
||||
|
||||
|
||||
def load_manifest(path: Path = MANIFEST) -> dict:
|
||||
import yaml
|
||||
|
||||
from showcase import steps
|
||||
|
||||
data = yaml.safe_load(path.read_text())
|
||||
names = set()
|
||||
for shot in data.get("shots") or []:
|
||||
name = shot.get("name")
|
||||
if not name or not re.fullmatch(r"[a-z0-9-]+", name):
|
||||
raise steps.StepError(f"shots.yaml: bad shot name {name!r}")
|
||||
if name in names:
|
||||
raise steps.StepError(f"shots.yaml: {name} is listed twice")
|
||||
names.add(name)
|
||||
unknown = set(shot) - SHOT_KEYS
|
||||
if unknown:
|
||||
raise steps.StepError(f"shots.yaml: {name}: unknown key(s) {sorted(unknown)}")
|
||||
steps.validate(shot.get("steps") or [], f"shots.yaml {name}")
|
||||
crop = shot.get("crop")
|
||||
placed = "anchor" in (crop or {}) or {"x", "y"} <= set(crop or {})
|
||||
if crop and crop.get("dialog"):
|
||||
continue
|
||||
if crop is not None and not ({"width", "height"} <= set(crop) and placed):
|
||||
raise steps.StepError(f"shots.yaml: {name}: crop needs width, height and an anchor or x/y")
|
||||
return data
|
||||
|
||||
|
||||
def changed(old: Path, new: Path) -> bool:
|
||||
"""Whether `new` differs visibly from `old` (a missing or differently sized old picture counts as changed)."""
|
||||
from PIL import Image, ImageChops, ImageStat
|
||||
|
||||
if not old.exists():
|
||||
return True
|
||||
with Image.open(old) as a, Image.open(new) as b:
|
||||
if a.size != b.size:
|
||||
return True
|
||||
diff = ImageChops.difference(a.convert("RGB"), b.convert("RGB"))
|
||||
if max(ImageStat.Stat(diff).mean) > MEAN_LIMIT:
|
||||
return True
|
||||
strong = diff.convert("L").point(lambda v: 255 if v > PIXEL_LIMIT else 0)
|
||||
share = ImageStat.Stat(strong).mean[0] / 255
|
||||
return share > PIXEL_SHARE
|
||||
|
||||
|
||||
def optimise(path: Path) -> None:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(path) as im:
|
||||
im.load()
|
||||
im.convert("RGB").save(path, "PNG", optimize=True)
|
||||
|
||||
|
||||
def privacy_problems(home: Path) -> list[str]:
|
||||
"""Anything in the demo data dir that looks like someone's own data: this machine's home folder or user name, the
|
||||
real data dir, IP addresses (version numbers like 1.4.0.0 aside: only private/public ranges with a non-zero last
|
||||
part that aren't a known version are reported)."""
|
||||
needles = {str(Path.home()), str(demo_home.real_data_dir())}
|
||||
user = os.environ.get("USER") or os.environ.get("USERNAME")
|
||||
found = []
|
||||
ip = re.compile(r"(?<![\d.])(?:10|172|192|100)\.\d{1,3}\.\d{1,3}\.\d{1,3}(?![\d.])")
|
||||
for f in home.rglob("*"):
|
||||
if not f.is_file() or f.suffix.lower() not in (".json", ".txt", ".yaml", ".yml", ".conf", ".log", ""):
|
||||
continue
|
||||
try:
|
||||
text = f.read_text(errors="ignore")
|
||||
except OSError:
|
||||
continue
|
||||
rel = f.relative_to(home)
|
||||
for n in needles:
|
||||
if n and n in text.replace(str(home), ""):
|
||||
found.append(f"{rel}: contains {n}")
|
||||
if user and len(user) > 2 and re.search(rf"\b{re.escape(user)}\b", text.replace(str(home), "")):
|
||||
found.append(f"{rel}: contains the user name {user!r}")
|
||||
for m in ip.findall(text):
|
||||
found.append(f"{rel}: IP address {m}")
|
||||
return found
|
||||
|
||||
|
||||
def crop_box(session, crop: dict):
|
||||
from showcase.web import Box
|
||||
|
||||
if crop.get("dialog"):
|
||||
d, pad = session.dialog(), crop.get("pad", 0)
|
||||
return Box(d.x - pad, d.y - pad, d.w + 2 * pad, d.h + 2 * pad)
|
||||
if "anchor" in crop:
|
||||
a = session.find(crop["anchor"], timeout=10)
|
||||
return Box(a.x + crop.get("left", 0), a.y + crop.get("top", 0), crop["width"], crop["height"])
|
||||
return Box(crop["x"], crop["y"], crop["width"], crop["height"])
|
||||
|
||||
|
||||
def render(shots: list[dict], variables: dict, defaults: dict, out: Path, log=print, verify: bool = True):
|
||||
"""A script for web.Server.run: renders every shot into out/<name>.png."""
|
||||
from showcase import steps
|
||||
|
||||
def one(server, shot: dict, path: Path) -> None:
|
||||
"""Render one shot. Any failing step raises: no picture is taken of a page that didn't get where the steps
|
||||
lead (a window that never connected once produced an empty, unconnected Library)."""
|
||||
vw, vh = shot.get("viewport") or defaults.get("viewport") or (1280, 820)
|
||||
s = server.session((vw, vh))
|
||||
try:
|
||||
steps.run(s, shot.get("steps") or [], variables)
|
||||
s.park(away=True)
|
||||
box = crop_box(s, steps.substitute(shot["crop"], variables)) if shot.get("crop") else None
|
||||
s.shot(path, clip=box)
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
def attempt(server, shot: dict, path: Path) -> bool:
|
||||
"""One render into `path` (a failing step: one more try in a fresh window). False when both failed."""
|
||||
for n in range(1, ATTEMPTS + 1):
|
||||
try:
|
||||
one(server, shot, path)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
path.unlink(missing_ok=True)
|
||||
if n < ATTEMPTS:
|
||||
log(f"RETRY {shot['name']}: {exc!r}")
|
||||
else:
|
||||
server.errors.append(f"{shot['name']}: {exc!r}")
|
||||
return False
|
||||
|
||||
def script(server) -> int:
|
||||
"""Every shot is rendered twice, each in a fresh window, and kept only when both agree: the headless GPU
|
||||
now and then draws a glyph wrong ("7.θ W" for "7.30 W"), a fault the settling can't see. Disagreeing
|
||||
renders get a third: the one two of them match is kept."""
|
||||
failed = 0
|
||||
for shot in shots:
|
||||
t0 = time.monotonic()
|
||||
final = out / f"{shot['name']}.png"
|
||||
takes = []
|
||||
for k in range(3 if verify else 1):
|
||||
path = out / f".take{k}-{shot['name']}.png"
|
||||
if not attempt(server, shot, path):
|
||||
break
|
||||
takes.append(path)
|
||||
if not verify:
|
||||
path.replace(final)
|
||||
break
|
||||
agreed = next((a for i, a in enumerate(takes) for b in takes[i + 1:] if not changed(a, b)), None)
|
||||
if agreed is not None:
|
||||
agreed.replace(final)
|
||||
break
|
||||
else:
|
||||
server.errors.append(f"{shot['name']}: three renders, no two alike (an unstable page?)")
|
||||
for p in takes:
|
||||
p.unlink(missing_ok=True)
|
||||
if final.exists():
|
||||
log(f"SHOT {shot['name']} ({time.monotonic() - t0:.1f} s, {len(takes)} renders)")
|
||||
else:
|
||||
failed += 1
|
||||
return 1 if failed else 0
|
||||
return script
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--only", default=None, help="comma-separated shot names")
|
||||
ap.add_argument("--out", type=Path, default=IMAGES, help="where the images go (default docs/images)")
|
||||
ap.add_argument("--check", action="store_true", help="only report out-of-date images (exit 1 if any)")
|
||||
ap.add_argument("--home", type=Path, default=None, help="demo data dir (default: a temp folder)")
|
||||
ap.add_argument("--offline", action="store_true", help="use only cached art")
|
||||
ap.add_argument("--allow-missing-art", action="store_true", help="render even when a game got no art")
|
||||
ap.add_argument("--keep", type=Path, default=None, help="also keep every raw render in this folder")
|
||||
ap.add_argument("--fast", action="store_true", help="render each shot once (no second render to catch a "
|
||||
"misdrawn glyph); for trying out a manifest edit")
|
||||
args = ap.parse_args()
|
||||
|
||||
manifest = load_manifest()
|
||||
shots = manifest["shots"]
|
||||
if args.only:
|
||||
want = args.only.split(",")
|
||||
unknown = set(want) - {s["name"] for s in shots}
|
||||
if unknown:
|
||||
print(f"unknown shot(s): {sorted(unknown)}", file=sys.stderr)
|
||||
return 2
|
||||
shots = [s for s in shots if s["name"] in want]
|
||||
home = args.home or Path(tempfile.mkdtemp(prefix="fp-showcase-home-"))
|
||||
demo_home.build_for_render(home, offline=args.offline, allow_missing_art=args.allow_missing_art)
|
||||
problems = privacy_problems(home)
|
||||
if problems:
|
||||
print("refusing to render, the demo data contains personal-looking data:\n " + "\n ".join(problems),
|
||||
file=sys.stderr)
|
||||
return 3
|
||||
renders = Path(tempfile.mkdtemp(prefix="fp-showcase-shots-"))
|
||||
status_file = renders / "status.json"
|
||||
|
||||
def finish(server_code: int) -> int:
|
||||
"""After rendering (still in the server's script thread): compare, write, report."""
|
||||
report = {"written": [], "unchanged": [], "missing": [], "changed": []}
|
||||
for shot in shots:
|
||||
new = renders / f"{shot['name']}.png"
|
||||
if not new.exists():
|
||||
report["missing"].append(shot["name"])
|
||||
continue
|
||||
optimise(new)
|
||||
old = args.out / new.name
|
||||
if changed(old, new):
|
||||
report["changed"].append(shot["name"])
|
||||
if not args.check:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(new, old)
|
||||
report["written"].append(shot["name"])
|
||||
else:
|
||||
report["unchanged"].append(shot["name"])
|
||||
if args.keep:
|
||||
args.keep.mkdir(parents=True, exist_ok=True)
|
||||
for f in renders.glob("*.png"):
|
||||
shutil.copyfile(f, args.keep / f.name)
|
||||
status_file.write_text(json.dumps(report))
|
||||
print("RESULT " + json.dumps(report), flush=True)
|
||||
if report["missing"] or server_code:
|
||||
return 1
|
||||
return 1 if args.check and report["changed"] else 0
|
||||
|
||||
from showcase.web import Server
|
||||
|
||||
script = render(shots, manifest.get("vars") or {}, manifest.get("defaults") or {}, renders, verify=not args.fast)
|
||||
from showcase.fakes import FrozenMonitorSession
|
||||
|
||||
return Server(monitor_session=FrozenMonitorSession).run(lambda server: finish(script(server)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,302 @@
|
||||
"""The step language shared by the docs screenshots (docs/showcase/shots.yaml) and the demo tour (tour.yaml).
|
||||
|
||||
A step is a one-key mapping. App steps call the app the way its own handlers do; pointer steps move a real (drawn)
|
||||
mouse to things found by name (see web.Session.find); hooks run the pretend Frame's scripted events.
|
||||
|
||||
- go: monitor # a sidebar route (library, frame, files, screenshots, live, keyboard, …)
|
||||
- nav: "Monitor" # click that tab like a person (checked: the page really changed)
|
||||
- open_game: ${game} # or {package: …, advanced: true} = with Customize open
|
||||
- call: {fn: screenshots_view.viewer, args: [0]} # any app method (dotted path from the app)
|
||||
- pop_dialog: true # close the top dialog
|
||||
- theme: original # switch the colour theme live (what Settings → Appearance does)
|
||||
- hover: "Batman" # pointer: a name, {name, nth, dx, dy, exact} or [x, y]
|
||||
- click: "Monitor" # also right_click, double_click
|
||||
- drag: ["Videos", "Documents"] # press on the first target, move through the others, release
|
||||
- type: "arc" # keyboard; press: Escape
|
||||
- scroll: {dy: 600, at: "Patches"}
|
||||
- wait: 1.5 # seconds
|
||||
- wait_for: "Starting on Frame" # until something with that name shows (timeout 15 s)
|
||||
- settle: true # until the picture stops changing
|
||||
- park: true # pointer to a place that hovers nothing
|
||||
- hook: fake_install # or {name: fake_install, args: [${game}]}: see HOOKS
|
||||
|
||||
`${name}` in any string is replaced from the file's `vars:`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
from showcase import fakes
|
||||
|
||||
POINTER = {"hover", "move", "click", "right_click", "double_click"}
|
||||
ACTIONS = POINTER | {"nav", "go", "open_game", "call", "pop_dialog", "theme", "drag", "type", "press", "scroll", "wait",
|
||||
"wait_for", "settle", "park", "hook"}
|
||||
|
||||
|
||||
class StepError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def substitute(value, variables: dict):
|
||||
"""${name} → variables[name] in every string of a step (a whole-string reference keeps the value's type)."""
|
||||
if isinstance(value, str):
|
||||
m = re.fullmatch(r"\$\{(\w+)\}", value)
|
||||
if m:
|
||||
if m.group(1) not in variables:
|
||||
raise StepError(f"unknown variable ${{{m.group(1)}}}")
|
||||
return variables[m.group(1)]
|
||||
|
||||
def one(m):
|
||||
if m.group(1) not in variables:
|
||||
raise StepError(f"unknown variable ${{{m.group(1)}}}")
|
||||
return str(variables[m.group(1)])
|
||||
return re.sub(r"\$\{(\w+)\}", one, value)
|
||||
if isinstance(value, list):
|
||||
return [substitute(v, variables) for v in value]
|
||||
if isinstance(value, dict):
|
||||
return {k: substitute(v, variables) for k, v in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def validate(steps, where: str = "steps") -> None:
|
||||
"""Raises StepError for a malformed step list (checked before a render starts, and by the tests)."""
|
||||
if not isinstance(steps, list):
|
||||
raise StepError(f"{where}: a list of steps expected")
|
||||
for i, step in enumerate(steps):
|
||||
at = f"{where}[{i}]"
|
||||
if not isinstance(step, dict) or len(step) != 1:
|
||||
raise StepError(f"{at}: a step is a mapping with exactly one action, got {step!r}")
|
||||
(action, value), = step.items()
|
||||
if action not in ACTIONS:
|
||||
raise StepError(f"{at}: unknown action {action!r} (known: {', '.join(sorted(ACTIONS))})")
|
||||
if action == "hook":
|
||||
name = value.get("name") if isinstance(value, dict) else value
|
||||
if name not in HOOKS:
|
||||
raise StepError(f"{at}: unknown hook {name!r} (known: {', '.join(sorted(HOOKS))})")
|
||||
if action == "call" and not (isinstance(value, str) or isinstance(value, dict) and "fn" in value):
|
||||
raise StepError(f"{at}: call needs a method name or {{fn, args}}")
|
||||
if action == "drag" and not (isinstance(value, list) and len(value) >= 2):
|
||||
raise StepError(f"{at}: drag needs two or more targets")
|
||||
if action in ("wait",) and not isinstance(value, (int, float)):
|
||||
raise StepError(f"{at}: wait needs seconds")
|
||||
|
||||
|
||||
def _resolve(app, dotted: str):
|
||||
obj = app
|
||||
for part in dotted.split("."):
|
||||
obj = getattr(obj, part)
|
||||
return obj
|
||||
|
||||
|
||||
def run(session, steps: list, variables: dict | None = None, log=None) -> None:
|
||||
"""Run the steps on a web.Session. App calls run in this thread (the app serialises its own updates)."""
|
||||
app = session.app
|
||||
for step in substitute(steps, variables or {}):
|
||||
(action, v), = step.items()
|
||||
if log:
|
||||
log(f" {action}: {v}")
|
||||
if action == "go":
|
||||
app.go(v)
|
||||
elif action == "open_game":
|
||||
if isinstance(v, dict):
|
||||
app.open_game(v["package"], advanced=bool(v.get("advanced")))
|
||||
else:
|
||||
app.open_game(v)
|
||||
elif action == "call":
|
||||
fn, args = (v, []) if isinstance(v, str) else (v["fn"], v.get("args") or [])
|
||||
method = _resolve(app, fn)
|
||||
if asyncio.iscoroutinefunction(method): # (e.g. a FilePicker flow): the page's loop runs it
|
||||
app.page.run_task(method, *args)
|
||||
else:
|
||||
method(*args)
|
||||
elif action == "nav":
|
||||
_nav(session, v, log)
|
||||
elif action == "pop_dialog":
|
||||
app.page.pop_dialog()
|
||||
elif action == "theme":
|
||||
from frameport.core import library
|
||||
|
||||
library.set_setting("ui.theme", v)
|
||||
app.restyle(v)
|
||||
elif action in POINTER:
|
||||
if action in ("hover", "move"):
|
||||
session.move(v)
|
||||
elif action == "click":
|
||||
session.click(v)
|
||||
elif action == "right_click":
|
||||
session.click(v, button="right")
|
||||
else:
|
||||
session.click(v)
|
||||
session.sleep(0.08)
|
||||
session.page.mouse.down()
|
||||
session.page.mouse.up()
|
||||
elif action == "drag":
|
||||
session.drag(v)
|
||||
elif action == "type":
|
||||
session.type(v)
|
||||
elif action == "press":
|
||||
session.press(v)
|
||||
elif action == "scroll":
|
||||
session.scroll(v.get("dy", 300), v.get("at"))
|
||||
elif action == "wait":
|
||||
session.sleep(float(v))
|
||||
elif action == "wait_for":
|
||||
session.find(v, timeout=15)
|
||||
elif action == "settle":
|
||||
session.settle(**({} if v is True else {k: w for k, w in v.items() if k in ("timeout",)}))
|
||||
elif action == "park":
|
||||
session.park()
|
||||
elif action == "hook":
|
||||
name, args = (v, []) if isinstance(v, str) else (v["name"], v.get("args") or [])
|
||||
HOOKS[name](session, *args)
|
||||
|
||||
|
||||
def _nav(session, label: str, log=None) -> None:
|
||||
"""Click a sidebar tab like a person, then make sure the page really changed: its heading shows in the content
|
||||
area. A click whose handler died would otherwise leave the old page in the picture for the rest of a recording
|
||||
(seen on CI before property writes took FLET_LOCK; kept as a safety net): then the route is opened directly and
|
||||
a WARN line printed."""
|
||||
from frameport.ui import app as app_module
|
||||
from showcase.web import Box, NotFound
|
||||
|
||||
keys = {str(lbl).casefold(): key for key, lbl, _icon in app_module.NAV}
|
||||
key = keys.get(label.casefold())
|
||||
if key is None:
|
||||
raise StepError(f"nav: {label!r} is not a sidebar tab ({', '.join(sorted(keys))})")
|
||||
session.click(label)
|
||||
vw, _vh = session.viewport
|
||||
content = Box(260, 0, vw - 260, 160) # right of the sidebar, the page's title row
|
||||
for _ in range(2):
|
||||
try:
|
||||
session.find(label, within=content, timeout=2.5)
|
||||
return
|
||||
except NotFound:
|
||||
print(f"WARN nav {label}: the page didn't change after the click, opening it directly", flush=True)
|
||||
session.app.go(key)
|
||||
session.find(label, within=content, timeout=2.5)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ hooks: the pretend Frame's scripted events
|
||||
|
||||
def _fake_install(session, package: str, pace: float = 1.0, wait: bool = False) -> None:
|
||||
"""Install `package` on the pretend Frame through the real job queue (every real stage, an upload, a passing
|
||||
launch test). wait: until it's done."""
|
||||
app = session.app
|
||||
app.submit(f"Install {app._title(package)} on Frame", fakes.install_job(package, pace), package, "install",
|
||||
to="frame")
|
||||
if wait:
|
||||
_wait_jobs(session)
|
||||
|
||||
|
||||
def _wait_jobs(session, timeout: float = 60) -> None:
|
||||
deadline = time.time() + timeout
|
||||
session.sleep(0.5)
|
||||
while time.time() < deadline and any(j.active for j in session.app.jobs.jobs):
|
||||
session.sleep(0.3)
|
||||
|
||||
|
||||
def _held_install(session, package: str, fraction: float = 0.62) -> None:
|
||||
"""An install held mid-upload: the transit in the sidebar, the game page and Activity. It stays there until the
|
||||
window closes (Session.close cancels it)."""
|
||||
from frameport.ui.jobs import Job
|
||||
|
||||
app, reached = session.app, threading.Event()
|
||||
|
||||
def run(job):
|
||||
rep = job.reporter
|
||||
for stage in fakes.FAKE_INSTALL_STAGES:
|
||||
rep.stage(stage)
|
||||
time.sleep(0.3) # past the job queue's notification throttle
|
||||
rep.progress(fraction, f"{package}.apk", speed="36.4 MB/s · ~1 min left")
|
||||
reached.set()
|
||||
while True:
|
||||
rep.check_cancel()
|
||||
time.sleep(0.2)
|
||||
|
||||
app.jobs.submit(Job(f"Install {app._title(package)} on Frame", run, package, "install"))
|
||||
reached.wait(10)
|
||||
|
||||
|
||||
def _live_stream(session) -> None:
|
||||
fakes.fake_live_stream(session.app)
|
||||
|
||||
|
||||
def _stop_live(session) -> None:
|
||||
fakes.stop_fake_live(session.app)
|
||||
|
||||
|
||||
def _monitor_details(session) -> None:
|
||||
fakes.open_monitor_details(session.app)
|
||||
|
||||
|
||||
def _type_tab(session) -> None:
|
||||
fakes.open_type_tab(session.app)
|
||||
|
||||
|
||||
def _select_files(session, first: int = 1, count: int = 2) -> None:
|
||||
v = session.app.files_view
|
||||
for e in v.entries[first:first + count]:
|
||||
v._toggle(e.path, True)
|
||||
|
||||
|
||||
def _disconnect(session) -> None:
|
||||
"""The sidebar as before connecting (the tour connects in front of the camera)."""
|
||||
app = session.app
|
||||
app.target, app.frame_info, app.frame_state = None, None, "none"
|
||||
app._refresh_sidebar()
|
||||
app.refresh_view()
|
||||
|
||||
|
||||
def _connect(session, delay: float = 1.0) -> None:
|
||||
"""Connecting… then connected to the pretend Frame (the live card starts streaming)."""
|
||||
app = session.app
|
||||
app.frame_state = "connecting"
|
||||
app._refresh_sidebar()
|
||||
session.sleep(delay)
|
||||
fakes.attach_fake_frame(app, session.server.monitor_session)
|
||||
app.refresh_view()
|
||||
app._refresh_sidebar()
|
||||
|
||||
|
||||
def _settings_section(session, key: str) -> None:
|
||||
"""Settings, scrolled to one section (its index entry)."""
|
||||
app = session.app
|
||||
app.go("settings")
|
||||
session.sleep(1.0) # mounted first: scrolling an unmounted column does nothing
|
||||
app.page.run_task(app.settings_view.show_section, key)
|
||||
|
||||
|
||||
def _first_run(session, folder: str = "D:/Games", pace: float = 1.0, tools_missing: bool = True,
|
||||
tools_delay: float = 4.0) -> None:
|
||||
"""FramePort's first start (the "fresh" demo profile): the welcome screen's tool download is the pretend one
|
||||
(fakes.tools_job; it waits `tools_delay` s so filming catches it from the start), and "Scan a folder…" scans
|
||||
`folder` at once instead of opening the native folder picker (a script can't drive it): the demo games appear
|
||||
one by one."""
|
||||
import json
|
||||
|
||||
from frameport.core.paths import user_data_dir
|
||||
|
||||
app = session.app
|
||||
fakes.TOOLS["ready"] = not tools_missing
|
||||
app.update_tools = lambda update=False, quiet=False: fakes.tools_job(app, pace, tools_delay)
|
||||
entries = json.loads((user_data_dir() / "showcase-scan.json").read_text())
|
||||
app.pick_folder = lambda e=None: fakes.scan_job(app, folder, entries, pace)
|
||||
app.welcome_started = False
|
||||
app.library_view = None # (a Library built already would keep the real folder picker)
|
||||
|
||||
|
||||
def _pairing_done(session, delay: float = 1.5) -> None:
|
||||
"""The Frame ran the setup command: FramePort hears from it and connects (the pretend Frame)."""
|
||||
app = session.app
|
||||
if app.pairing is not None:
|
||||
app.pairing.stop()
|
||||
_connect(session, delay)
|
||||
|
||||
|
||||
HOOKS = {"fake_install": _fake_install, "wait_jobs": _wait_jobs, "held_install": _held_install,
|
||||
"live_stream": _live_stream, "stop_live": _stop_live, "monitor_details": _monitor_details,
|
||||
"type_tab": _type_tab, "select_files": _select_files, "disconnect": _disconnect, "connect": _connect,
|
||||
"settings_section": _settings_section, "first_run": _first_run, "pairing_done": _pairing_done}
|
||||
@@ -0,0 +1,534 @@
|
||||
"""Serve the real GUI in web mode with a pretend Frame and drive it with headless Chromium (Playwright), for docs
|
||||
screenshots and the demo tour.
|
||||
|
||||
`Server(...).run(script)` owns the main thread (Flet's `ft.run` must) and runs `script(server)` in a thread; the
|
||||
script opens browser sessions with `server.session(...)`: one Playwright context + page and the FramePortApp that
|
||||
page started (one app per browser session). Elements are found by name through Flutter's semantics tree (the
|
||||
accessibility DOM Flutter web builds on request): visible text, a tooltip or a semantics label; the pointer events
|
||||
still go to Flutter's canvas, so hover effects and gestures behave as with a real mouse.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import queue
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import flet as ft
|
||||
|
||||
from frameport.ui.app import FramePortApp
|
||||
from showcase import fakes
|
||||
|
||||
PORT = int(os.environ.get("FRAMEPORT_SHOWCASE_PORT", "8571"))
|
||||
CHROMIUM_ARGS = ["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--font-render-hinting=none"]
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
# Flutter builds its semantics DOM only once something asks for it (a screen reader): the placeholder button does.
|
||||
# The semantics nodes then sit above the canvas; with pointer-events off they don't take the mouse.
|
||||
_ENABLE_SEMANTICS = """() => {
|
||||
const p = document.querySelector('flt-semantics-placeholder');
|
||||
if (p) p.click();
|
||||
if (!document.getElementById('fp-sem-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = 'fp-sem-style';
|
||||
s.textContent = 'flt-semantics-host, flt-semantics, flt-semantics * { pointer-events: none !important; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
return !!p;
|
||||
}"""
|
||||
|
||||
# every named node: its own text, aria-label or the text of its children, with its box on screen
|
||||
_NODES = """() => [...document.querySelectorAll('flt-semantics')].map(e => {
|
||||
const r = e.getBoundingClientRect();
|
||||
const own = [...e.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join(' ').trim();
|
||||
return {label: (e.getAttribute('aria-label') || '').trim(), text: own, all: (e.innerText || '').trim(),
|
||||
role: e.getAttribute('role') || '', tappable: e.hasAttribute('flt-tappable'),
|
||||
x: r.x, y: r.y, w: r.width, h: r.height};
|
||||
}).filter(n => n.w > 0 && n.h > 0)"""
|
||||
|
||||
# the visible pointer for recordings (headless Chromium draws none): an arrow that follows the mouse, a ring on press
|
||||
CURSOR_JS = """(() => {
|
||||
if (window.__fpCursor) return;
|
||||
window.__fpCursor = true;
|
||||
const add = () => {
|
||||
const c = document.createElement('div');
|
||||
c.id = 'fp-cursor';
|
||||
c.innerHTML = '<svg width="28" height="28" viewBox="0 0 28 28"><path d="M4 2 L4 22 L9.5 17 L13 25 L16.5 23.5 ' +
|
||||
'L13 15.8 L20.5 15.8 Z" fill="#fff" stroke="#111" stroke-width="1.6" stroke-linejoin="round"/></svg>';
|
||||
Object.assign(c.style, {position: 'fixed', left: '-40px', top: '-40px', width: '28px', height: '28px',
|
||||
pointerEvents: 'none', zIndex: 2147483647, filter: 'drop-shadow(0 2px 3px rgba(0,0,0,.45))',
|
||||
transform: 'translate(-3px,-2px)'});
|
||||
document.documentElement.appendChild(c);
|
||||
const ring = (x, y) => {
|
||||
const r = document.createElement('div');
|
||||
Object.assign(r.style, {position: 'fixed', left: (x - 18) + 'px', top: (y - 18) + 'px', width: '36px',
|
||||
height: '36px', borderRadius: '50%', border: '3px solid rgba(255,140,40,.95)', pointerEvents: 'none',
|
||||
zIndex: 2147483646, transition: 'transform .45s ease-out, opacity .45s ease-out', transform: 'scale(.4)',
|
||||
opacity: '1'});
|
||||
document.documentElement.appendChild(r);
|
||||
requestAnimationFrame(() => { r.style.transform = 'scale(1.5)'; r.style.opacity = '0'; });
|
||||
setTimeout(() => r.remove(), 600);
|
||||
};
|
||||
const move = e => { c.style.left = e.clientX + 'px'; c.style.top = e.clientY + 'px'; };
|
||||
window.addEventListener('pointermove', move, true);
|
||||
window.addEventListener('mousemove', move, true);
|
||||
window.addEventListener('pointerdown', e => ring(e.clientX, e.clientY), true);
|
||||
};
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', add); else add();
|
||||
})();"""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Box:
|
||||
x: float
|
||||
y: float
|
||||
w: float
|
||||
h: float
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[float, float]:
|
||||
return self.x + self.w / 2, self.y + self.h / 2
|
||||
|
||||
|
||||
class NotFound(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
def names_of(node: dict) -> list[str]:
|
||||
"""What a semantics node is called: its label (tooltip), its own text and each line of its children's text
|
||||
(a card reads "Click to open…\\nQuest\\nBatman: Arkham Shadow\\nWorks")."""
|
||||
out = [node.get("label") or "", node.get("text") or ""]
|
||||
for key in ("label", "text", "all"):
|
||||
out += (node.get(key) or "").splitlines()
|
||||
return [s.strip().casefold() for s in out if s and s.strip()]
|
||||
|
||||
|
||||
def _contains(outer: dict, inner: dict) -> bool:
|
||||
"""outer's box holds inner's centre and is bigger: a container of inner (a list around its row)."""
|
||||
cx, cy = inner["x"] + inner["w"] / 2, inner["y"] + inner["h"] / 2
|
||||
return (outer["x"] <= cx <= outer["x"] + outer["w"] and outer["y"] <= cy <= outer["y"] + outer["h"]
|
||||
and outer["w"] * outer["h"] > inner["w"] * inner["h"] * 1.2)
|
||||
|
||||
|
||||
def innermost(nodes: list[dict]) -> list[dict]:
|
||||
"""The nodes that don't contain another one of them (a list's text includes its rows': the row wins)."""
|
||||
return [n for n in nodes if not any(m is not n and _contains(n, m) for m in nodes)]
|
||||
|
||||
|
||||
def pick(nodes: list[dict], name: str, nth: int = 0, exact: bool | None = None) -> dict | None:
|
||||
"""The nth node called `name`: exact names first, then names starting with it, then containing it (unless
|
||||
exact). Tappable nodes (buttons, cards) win, top to bottom and left to right; else the plain text itself, i.e.
|
||||
the smallest node (the containers around it carry its text too)."""
|
||||
want = name.strip().casefold()
|
||||
tests = [lambda s: s == want]
|
||||
if not exact:
|
||||
tests += [lambda s: s.startswith(want), lambda s: want in s]
|
||||
for test in tests:
|
||||
hits = [n for n in nodes if any(test(s) for s in names_of(n))]
|
||||
tappable = innermost([n for n in hits if n.get("tappable")])
|
||||
if tappable:
|
||||
tappable.sort(key=lambda n: (round(n["y"]), round(n["x"]), n["w"] * n["h"]))
|
||||
return tappable[nth] if nth < len(tappable) else None
|
||||
if hits:
|
||||
hits.sort(key=lambda n: (n["w"] * n["h"], round(n["y"]), round(n["x"])))
|
||||
return hits[nth] if nth < len(hits) else None
|
||||
return None
|
||||
|
||||
|
||||
def ease(t: float) -> float:
|
||||
"""Ease-in-out (smoothstep of a smoothstep): slow start, fast middle, gentle landing."""
|
||||
t = max(0.0, min(1.0, t))
|
||||
t = t * t * (3 - 2 * t)
|
||||
return t * t * (3 - 2 * t)
|
||||
|
||||
|
||||
def human_path(start: tuple[float, float], end: tuple[float, float], steps: int, bend: float = 0.12
|
||||
) -> list[tuple[float, float]]:
|
||||
"""Points from start to end along a slight arc (a quadratic Bezier whose control point sits `bend` of the
|
||||
distance off the straight line), spaced by `ease`: the path a hand takes, not a ruler line."""
|
||||
(x0, y0), (x1, y1) = start, end
|
||||
dx, dy = x1 - x0, y1 - y0
|
||||
dist = math.hypot(dx, dy)
|
||||
cx, cy = (x0 + x1) / 2 - dy * bend, (y0 + y1) / 2 + dx * bend # perpendicular offset
|
||||
if dist < 1:
|
||||
return [end] * max(1, steps)
|
||||
out = []
|
||||
for i in range(1, steps + 1):
|
||||
t = ease(i / steps)
|
||||
out.append(((1 - t) ** 2 * x0 + 2 * (1 - t) * t * cx + t * t * x1,
|
||||
(1 - t) ** 2 * y0 + 2 * (1 - t) * t * cy + t * t * y1))
|
||||
return out
|
||||
|
||||
|
||||
def move_duration(dist: float) -> float:
|
||||
"""Seconds for a pointer hop of `dist` px: ~0.45 s for short hops, up to ~0.9 s across the window."""
|
||||
return max(0.35, min(0.9, 0.3 + dist / 1800))
|
||||
|
||||
|
||||
class Session:
|
||||
"""One browser page showing one FramePortApp."""
|
||||
|
||||
def __init__(self, server: Server, ctx, page, app: FramePortApp, cursor: bool):
|
||||
self.server, self.ctx, self.page, self.app = server, ctx, page, app
|
||||
self.mouse_at = (0.0, 0.0)
|
||||
self.cursor = cursor
|
||||
self.semantics = False
|
||||
self.browser = None
|
||||
self.park_at: tuple[float, float] | None = None
|
||||
|
||||
def sleep(self, seconds: float) -> None:
|
||||
"""Wait while the browser keeps going (Playwright's event loop runs, so a screencast keeps its frames)."""
|
||||
if seconds > 0:
|
||||
self.page.wait_for_timeout(seconds * 1000)
|
||||
|
||||
# ------------------------------------------------------------ finding things
|
||||
def enable_semantics(self) -> None:
|
||||
if not self.semantics:
|
||||
self.semantics = bool(self.page.evaluate(_ENABLE_SEMANTICS))
|
||||
self.sleep(0.5)
|
||||
|
||||
def nodes(self) -> list[dict]:
|
||||
self.enable_semantics()
|
||||
return self.page.evaluate(_NODES)
|
||||
|
||||
def find(self, name: str, within: Box | None = None, nth: int = 0, exact: bool | None = None,
|
||||
timeout: float = 8.0) -> Box:
|
||||
"""The box of the element called `name` (its text, tooltip or label; exact match first, then the start of
|
||||
the text, then anywhere in it), optionally inside `within`; the smallest tappable one wins ties. Waits up
|
||||
to `timeout` s for it to appear."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
vw, vh = self.viewport
|
||||
nodes = [n for n in self.nodes() if 0 <= n["x"] + n["w"] / 2 <= vw and 0 <= n["y"] + n["h"] / 2 <= vh]
|
||||
if within:
|
||||
nodes = [n for n in nodes if within.x <= n["x"] + n["w"] / 2 <= within.x + within.w
|
||||
and within.y <= n["y"] + n["h"] / 2 <= within.y + within.h]
|
||||
hit = pick(nodes, name, nth, exact)
|
||||
if hit:
|
||||
return Box(hit["x"], hit["y"], hit["w"], hit["h"])
|
||||
if time.monotonic() > deadline:
|
||||
raise NotFound(f"no element named {name!r} on screen")
|
||||
self.sleep(0.3)
|
||||
|
||||
def dialog(self, timeout: float = 8.0) -> Box:
|
||||
"""The box of the topmost open dialog (Flutter labels a dialog's surface "Alert")."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
boxes = [n for n in self.nodes() if n["label"] == "Alert"]
|
||||
if boxes:
|
||||
n = boxes[-1]
|
||||
return Box(n["x"], n["y"], n["w"], n["h"])
|
||||
if time.monotonic() > deadline:
|
||||
raise NotFound("no dialog open")
|
||||
self.sleep(0.3)
|
||||
|
||||
def exists(self, name: str, timeout: float = 0.0) -> bool:
|
||||
try:
|
||||
self.find(name, timeout=timeout)
|
||||
return True
|
||||
except NotFound:
|
||||
return False
|
||||
|
||||
@property
|
||||
def viewport(self) -> tuple[int, int]:
|
||||
v = self.page.viewport_size
|
||||
return v["width"], v["height"]
|
||||
|
||||
# ------------------------------------------------------------ the pointer
|
||||
def point(self, target) -> tuple[float, float]:
|
||||
"""A target: a name (see find), a Box, an (x, y) pair, or {"name": …, "dx": …, "dy": …, "nth": …}
|
||||
(dx/dy: offset from the box's centre in px, or as a fraction of its size when |d| < 1)."""
|
||||
if isinstance(target, (tuple, list)) and len(target) == 2 and all(isinstance(v, (int, float)) for v in target):
|
||||
return float(target[0]), float(target[1])
|
||||
if isinstance(target, Box):
|
||||
return target.center
|
||||
if isinstance(target, str):
|
||||
return self.find(target).center
|
||||
if isinstance(target, dict):
|
||||
box = self.find(target["name"], nth=target.get("nth", 0), exact=target.get("exact"))
|
||||
cx, cy = box.center
|
||||
dx, dy = target.get("dx", 0), target.get("dy", 0)
|
||||
dx = dx * box.w if abs(dx) < 1 else dx
|
||||
dy = dy * box.h if abs(dy) < 1 else dy
|
||||
return cx + dx, cy + dy
|
||||
raise TypeError(f"not a target: {target!r}")
|
||||
|
||||
def move(self, target, duration: float | None = None, smooth: bool = True) -> tuple[float, float]:
|
||||
x, y = self.point(target)
|
||||
if not smooth:
|
||||
self.page.mouse.move(x, y)
|
||||
else:
|
||||
dist = math.hypot(x - self.mouse_at[0], y - self.mouse_at[1])
|
||||
duration = move_duration(dist) if duration is None else duration
|
||||
steps = max(2, int(duration * 60))
|
||||
t0 = time.monotonic()
|
||||
for i, (px, py) in enumerate(human_path(self.mouse_at, (x, y), steps)):
|
||||
self.page.mouse.move(px, py)
|
||||
wait = t0 + duration * (i + 1) / steps - time.monotonic()
|
||||
if wait > 0:
|
||||
self.sleep(wait)
|
||||
self.mouse_at = (x, y)
|
||||
return x, y
|
||||
|
||||
def click(self, target, button: str = "left", smooth: bool = True, pause: float = 0.15) -> None:
|
||||
self.move(target, smooth=smooth)
|
||||
if isinstance(target, (str, dict)): # the layout moved while the pointer travelled (a list reloaded): follow
|
||||
x, y = self.point(target)
|
||||
if math.hypot(x - self.mouse_at[0], y - self.mouse_at[1]) > 6:
|
||||
self.move((x, y), duration=0.25)
|
||||
self.sleep(pause)
|
||||
self.page.mouse.down(button=button)
|
||||
self.sleep(0.07)
|
||||
self.page.mouse.up(button=button)
|
||||
|
||||
def drag(self, points: list, smooth: bool = True) -> None:
|
||||
self.move(points[0], smooth=smooth)
|
||||
self.sleep(0.2)
|
||||
self.page.mouse.down()
|
||||
for p in points[1:]:
|
||||
self.move(p, smooth=smooth, duration=0.6)
|
||||
self.sleep(0.2)
|
||||
self.page.mouse.up()
|
||||
|
||||
def type(self, text: str, delay: float = 0.11) -> None:
|
||||
self.page.keyboard.type(text, delay=int(delay * 1000))
|
||||
|
||||
def press(self, key: str) -> None:
|
||||
self.page.keyboard.press(key)
|
||||
|
||||
def scroll(self, dy: float, at=None) -> None:
|
||||
if at is not None:
|
||||
self.move(at)
|
||||
for _ in range(max(1, int(abs(dy) // 100))):
|
||||
self.page.mouse.wheel(0, 100 if dy > 0 else -100)
|
||||
self.sleep(0.05)
|
||||
|
||||
def park(self, away: bool = False) -> None:
|
||||
"""The pointer somewhere it hovers nothing: the sidebar's empty part (videos: the drawn cursor stays in the
|
||||
picture), or with `away` off the page (still pictures: nothing hovered, whatever the layout)."""
|
||||
if away:
|
||||
self.page.mouse.move(-40, -40)
|
||||
self.mouse_at = (-40.0, -40.0)
|
||||
return
|
||||
if self.park_at is None: # just below the sidebar's last tab (Settings): nothing there takes the pointer
|
||||
try:
|
||||
tab = self.find("Settings", timeout=3)
|
||||
self.park_at = (tab.x + tab.w * 0.6, tab.y + tab.h + 44)
|
||||
except NotFound:
|
||||
self.park_at = self.server.park_point(self.viewport)
|
||||
self.page.mouse.move(*self.park_at)
|
||||
self.mouse_at = self.park_at
|
||||
|
||||
# ------------------------------------------------------------ pictures
|
||||
def settle(self, timeout: float = 8.0, interval: float = 0.15, quiet: int = 4, mask: list[Box] = ()) -> bool:
|
||||
"""Wait until the page stops changing: `quiet` screenshots in a row (interval apart) are identical (masked
|
||||
boxes, e.g. a live chart, ignored). False when it was still changing at `timeout`."""
|
||||
deadline, last, same = time.monotonic() + timeout, None, 0
|
||||
while time.monotonic() < deadline:
|
||||
png = self._raw(mask)
|
||||
same = same + 1 if png == last else 0
|
||||
if same >= quiet:
|
||||
return True
|
||||
last = png
|
||||
self.sleep(interval)
|
||||
return False
|
||||
|
||||
def _raw(self, mask: list[Box] = ()) -> bytes:
|
||||
if not mask:
|
||||
return self.page.screenshot(animations="disabled", caret="hide")
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
im = Image.open(BytesIO(self.page.screenshot(caret="hide")))
|
||||
d = ImageDraw.Draw(im)
|
||||
for b in mask:
|
||||
d.rectangle((b.x, b.y, b.x + b.w, b.y + b.h), fill=(0, 0, 0))
|
||||
return im.tobytes()
|
||||
|
||||
def shot(self, path: Path, clip: Box | None = None, settle: bool = True) -> Path:
|
||||
if settle:
|
||||
self.settle()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
kw = {"clip": {"x": clip.x, "y": clip.y, "width": clip.w, "height": clip.h}} if clip else {}
|
||||
self.page.screenshot(path=str(path), caret="hide", **kw)
|
||||
return path
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the window and leave nothing behind for the next one: the job queue is shared by every session
|
||||
(a pretend install would show in the next window's Activity), the live stream's ffmpeg and the monitor
|
||||
stream would run on, and a closed page must not get job events."""
|
||||
app = self.app
|
||||
try:
|
||||
app.jobs.unsubscribe(app._on_job)
|
||||
for job in list(app.jobs.jobs):
|
||||
if job.active:
|
||||
app.jobs.cancel(job)
|
||||
deadline = time.monotonic() + 5
|
||||
while any(j.active for j in app.jobs.jobs) and time.monotonic() < deadline:
|
||||
self.sleep(0.1)
|
||||
app.jobs.clear_finished()
|
||||
fakes.stop_fake_live(app)
|
||||
app.stop_monitor()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
for thing in (self.ctx, self.browser):
|
||||
try:
|
||||
if thing is not None:
|
||||
thing.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
class Server:
|
||||
"""The GUI on 127.0.0.1:PORT (web mode) with fakes installed; `run(script)` serves until the script returns."""
|
||||
|
||||
def __init__(self, port: int = PORT, fake_frame: bool = True, monitor_session=None, game: str | None = None,
|
||||
scale: float = 1.0):
|
||||
self.port, self.fake_frame, self.scale = port, fake_frame, scale
|
||||
self.monitor_session = monitor_session or fakes.FakeMonitorSession
|
||||
self.apps: queue.Queue = queue.Queue()
|
||||
self.errors: list[str] = []
|
||||
self.playwright = None
|
||||
self.game = game
|
||||
|
||||
def park_point(self, viewport: tuple[int, int]) -> tuple[float, float]:
|
||||
return 130 * self.scale, viewport[1] * 0.62
|
||||
|
||||
def _app_main(self, page: ft.Page) -> None:
|
||||
try:
|
||||
app = FramePortApp(page)
|
||||
if self.fake_frame:
|
||||
fakes.attach_fake_frame(app, self.monitor_session)
|
||||
except Exception: # noqa: BLE001
|
||||
self.errors.append("startup: " + traceback.format_exc())
|
||||
return
|
||||
self.apps.put(app)
|
||||
|
||||
def session(self, viewport: tuple[int, int], cursor: bool = False, video_dir: Path | None = None,
|
||||
device_scale: float = 1.0) -> Session:
|
||||
"""A new browser context + page (fresh app). `video_dir`: Playwright's own recorder (fallback capture)."""
|
||||
while not self.apps.empty(): # apps from sessions already closed
|
||||
self.apps.get_nowait()
|
||||
kw = {}
|
||||
if video_dir is not None:
|
||||
kw = {"record_video_dir": str(video_dir), "record_video_size": {"width": viewport[0],
|
||||
"height": viewport[1]}}
|
||||
# a browser of its own per window: windows sharing one browser (its GPU process) sometimes drew text with
|
||||
# glyphs from the wrong place ("/sdcard/ʍvies")
|
||||
browser = self.playwright.chromium.launch(args=CHROMIUM_ARGS)
|
||||
ctx = browser.new_context(viewport={"width": viewport[0], "height": viewport[1]},
|
||||
device_scale_factor=device_scale, **kw)
|
||||
if cursor:
|
||||
ctx.add_init_script(CURSOR_JS)
|
||||
page = ctx.new_page()
|
||||
page.goto(f"http://127.0.0.1:{self.port}", wait_until="networkidle", timeout=120_000)
|
||||
app = self.apps.get(timeout=120)
|
||||
s = Session(self, ctx, page, app, cursor)
|
||||
s.browser = browser
|
||||
# web fonts: text measured before they load wraps or overlaps ("Q / uest"): a text-heavy first screen (the
|
||||
# Settings page) takes them before the steps start
|
||||
s.sleep(1.0)
|
||||
app.go("settings")
|
||||
s.sleep(2.0)
|
||||
s.enable_semantics()
|
||||
s.park()
|
||||
return s
|
||||
|
||||
def run(self, script) -> int:
|
||||
"""Serve; `script(server) -> exit code` runs in a thread with the browser ready; the process ends with it."""
|
||||
from frameport.ui.app import serialize_flet_updates
|
||||
|
||||
serialize_flet_updates() # as the app's main() does: patches and property writes don't interleave
|
||||
if self.fake_frame:
|
||||
fakes.install_fakes(self.game, self.monitor_session)
|
||||
|
||||
def runner():
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
for _ in range(90):
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", self.port), timeout=1).close()
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
time.sleep(1.5)
|
||||
code = 1
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
self.playwright = p
|
||||
code = script(self) or 0
|
||||
except Exception: # noqa: BLE001
|
||||
self.errors.append("script: " + traceback.format_exc())
|
||||
for e in self.errors:
|
||||
print("ERROR", e, flush=True)
|
||||
os._exit(1 if self.errors else code)
|
||||
|
||||
from frameport.ui.app import assets_dir
|
||||
|
||||
threading.Thread(target=runner, daemon=True).start()
|
||||
ft.run(self._app_main, view=ft.AppView.WEB_BROWSER, port=self.port, assets_dir=assets_dir())
|
||||
return 1
|
||||
|
||||
|
||||
class Screencast:
|
||||
"""The page's frames as Chrome paints them (CDP Page.startScreencast: JPEGs with timestamps), written to a folder.
|
||||
Sharper than Playwright's own recorder (VP8 at a low bit rate). Chrome sends a frame only when the page changed,
|
||||
so the frames come with their times and are turned into a constant frame rate later (postprod.frames_to_video).
|
||||
Frames only arrive while Playwright runs (Session.sleep, mouse moves), never during time.sleep."""
|
||||
|
||||
def __init__(self, session: Session, folder: Path, quality: int = 92):
|
||||
import base64
|
||||
|
||||
self._b64 = base64.b64decode
|
||||
self.session, self.folder, self.quality = session, Path(folder), quality
|
||||
self.folder.mkdir(parents=True, exist_ok=True)
|
||||
self.frames: list[tuple[float, str]] = [] # (wall-clock time, file name)
|
||||
self.cdp = session.ctx.new_cdp_session(session.page)
|
||||
self.cdp.on("Page.screencastFrame", self._frame)
|
||||
self.running = False
|
||||
|
||||
def _frame(self, params: dict) -> None:
|
||||
name = f"{len(self.frames):06d}.jpg"
|
||||
(self.folder / name).write_bytes(self._b64(params["data"]))
|
||||
self.frames.append((float(params["metadata"].get("timestamp") or time.time()), name))
|
||||
try:
|
||||
self.cdp.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]})
|
||||
except Exception: # noqa: BLE001 (stopping)
|
||||
pass
|
||||
|
||||
def start(self) -> None:
|
||||
vw, vh = self.session.viewport
|
||||
scale = self.session.page.evaluate("window.devicePixelRatio") or 1
|
||||
self.cdp.send("Page.startScreencast", {"format": "jpeg", "quality": self.quality,
|
||||
"maxWidth": int(vw * scale), "maxHeight": int(vh * scale),
|
||||
"everyNthFrame": 1})
|
||||
self.running = True
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.running:
|
||||
self.session.sleep(0.3)
|
||||
self.cdp.send("Page.stopScreencast")
|
||||
self.running = False
|
||||
|
||||
def write_index(self) -> Path:
|
||||
"""frames.json: [[time, file], …] for postprod."""
|
||||
path = self.folder / "frames.json"
|
||||
path.write_text(json.dumps(self.frames))
|
||||
return path
|
||||
|
||||
|
||||
def call(session: Session, fn, *args, **kwargs):
|
||||
"""Run an app action from the script thread, logging (not raising) its errors so one broken step doesn't end a
|
||||
whole render."""
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except Exception: # noqa: BLE001
|
||||
session.server.errors.append(f"{getattr(fn, '__name__', fn)}: " + traceback.format_exc())
|
||||
return None
|
||||
@@ -17,9 +17,22 @@ import time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
import flet as ft # noqa: E402
|
||||
from showcase.fakes import ( # noqa: E402,F401
|
||||
LINUX_APPIMAGE,
|
||||
LINUX_FOLDER,
|
||||
add_fake_linux_apps,
|
||||
attach_fake_frame,
|
||||
fake_live_stream,
|
||||
install_fakes,
|
||||
open_monitor_details,
|
||||
open_type_tab,
|
||||
start_fake_install,
|
||||
stop_fake_live,
|
||||
)
|
||||
|
||||
from frameport.core import library # noqa: E402
|
||||
from frameport.ui.app import FramePortApp # noqa: E402
|
||||
@@ -28,339 +41,25 @@ PORT = int(os.environ.get("FRAMEPORT_SMOKE_PORT", "8557")) # two smoke runs at
|
||||
ERRORS: list[str] = []
|
||||
|
||||
|
||||
class FakeFS:
|
||||
"""--fake-frame's file system for the Files tab: a temp folder with sample files, served like SFTP."""
|
||||
|
||||
def __init__(self):
|
||||
import tempfile
|
||||
|
||||
self.home = tempfile.mkdtemp(prefix="fp-fake-frame-")
|
||||
samples = {"Videos": ["Earth from orbit (360).mp4", "Mars landing (VR180).mkv", "Concert 8K 3D.mp4"],
|
||||
"Downloads": ["Mods/", "readme.txt"], "Documents": ["Saves/", "Notes.pdf"]}
|
||||
sizes = {".mp4": 2_400_000_000, ".mkv": 1_100_000_000}
|
||||
for folder, names in samples.items():
|
||||
base = os.path.join(self.home, folder)
|
||||
os.makedirs(os.path.join(base, "Trips"), exist_ok=True)
|
||||
for n in names:
|
||||
if n.endswith("/"):
|
||||
os.makedirs(os.path.join(base, n), exist_ok=True)
|
||||
else:
|
||||
with open(os.path.join(base, n), "wb") as f:
|
||||
f.truncate(sizes.get(os.path.splitext(n)[1], 48_000)) # sparse: no real disk use
|
||||
self.shots = self._screenshots()
|
||||
|
||||
def _screenshots(self) -> list[dict]:
|
||||
"""Sample Steam screenshots for the Screenshots tab, two days, a few games + SteamVR: crops of the games' own
|
||||
store art (hero/landscape) when the library has some (docs screenshots), else colour gradients."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from frameport.artwork import fetch
|
||||
|
||||
folder = os.path.join(self.home, "shots")
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
games = []
|
||||
for g in library.games():
|
||||
if g.get("kind") == "rift":
|
||||
continue
|
||||
# the store's own screenshots look like real captures; else hero/wide art
|
||||
shots_art = sorted(fetch.artwork_dir(g["package"]).glob("shot_*.jpg"))
|
||||
games.append((g, shots_art or [p for p in fetch.files(g["package"]) if p.stem in ("hero", "landscape")],
|
||||
bool(shots_art)))
|
||||
games.sort(key=lambda ga: (not ga[2], -len(ga[1])))
|
||||
owners = [(g["package"], g.get("title") or g["package"], arts) for g, arts, _real in games[:3]]
|
||||
spare = games[3][1] if len(games) > 3 else [] # SteamVR's own shots (taken outside a FramePort game)
|
||||
owners.append((None, "SteamVR", spare))
|
||||
now, shots = time.time(), []
|
||||
for i in range(10):
|
||||
t = now - i * 2400 - (86400 if i >= 6 else 0)
|
||||
name = time.strftime("%Y%m%d%H%M%S", time.localtime(t)) + "_1.jpg"
|
||||
path = os.path.join(folder, name)
|
||||
pkg, title, arts = owners[i % len(owners)]
|
||||
if arts: # a different crop of the game's art per shot, so they don't all look alike
|
||||
with Image.open(arts[i % len(arts)]) as src:
|
||||
src = src.convert("RGB")
|
||||
zoom = 1.0 + 0.15 * (i % 3) * (src.width < 2 * src.height)
|
||||
w, h = int(src.width / zoom), int(src.height / zoom)
|
||||
x, y = (src.width - w) * (i % 2), (src.height - h) // 2
|
||||
im = ImageOps.fit(src.crop((x, y, x + w, y + h)), (1280, 720))
|
||||
else:
|
||||
im = Image.linear_gradient("L").resize((640, 360)).convert("RGB")
|
||||
im = Image.merge("RGB", (im.getchannel(0).point(lambda v, i=i: (v + 40 * i) % 256),
|
||||
im.getchannel(1).point(lambda v: 255 - v), im.getchannel(2)))
|
||||
im.save(path, "JPEG", quality=85)
|
||||
shots.append({"path": path, "thumb": None, "time": int(t), "width": 1920, "height": 1080,
|
||||
"size": os.path.getsize(path), "account": "1", "appid": "250820", "package": pkg,
|
||||
"title": title})
|
||||
return shots
|
||||
|
||||
def agent(self, command, **args):
|
||||
if command == "storage_targets":
|
||||
return {"targets": [{"id": n.lower(), "path": os.path.join(self.home, n), "android": a, "shared": True}
|
||||
for n, a in (("Videos", "/sdcard/Movies"), ("Downloads", "/sdcard/Download"),
|
||||
("Documents", "/sdcard/Documents"))]}
|
||||
if command == "list_screenshots":
|
||||
want = args.get("package")
|
||||
shots = [s for s in self.shots if want is None or (s["package"] or "") == want]
|
||||
games = {}
|
||||
for s in self.shots:
|
||||
games.setdefault(s["package"] or "", {"package": s["package"], "title": s["title"], "count": 0})
|
||||
games[s["package"] or ""]["count"] += 1
|
||||
return {"shots": shots, "total": len(shots), "games": list(games.values())}
|
||||
raise RuntimeError(f"fake Frame: {command} not available")
|
||||
|
||||
@property
|
||||
def sftp(self):
|
||||
import paramiko
|
||||
|
||||
class SFTP:
|
||||
def listdir_attr(self, path):
|
||||
out = []
|
||||
for name in sorted(os.listdir(path)):
|
||||
a = paramiko.SFTPAttributes.from_stat(os.lstat(os.path.join(path, name)))
|
||||
a.filename = name
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
def stat(self, path):
|
||||
return paramiko.SFTPAttributes.from_stat(os.stat(path))
|
||||
|
||||
def get(self, remote, local, callback=None):
|
||||
import shutil
|
||||
|
||||
shutil.copyfile(remote, local)
|
||||
return SFTP()
|
||||
PAINT_SECONDS = 3 # after a step, before its screenshot: Flutter paints (and a view's content loads)
|
||||
STEP_TIMEOUT = 240 # the longest a step may wait for its screenshot (a crashed browser mustn't hang the run)
|
||||
|
||||
|
||||
class FakeTarget:
|
||||
"""--fake-frame: a pretend Steam Frame with the library's working Quest builds installed (no network, no device),
|
||||
for documentation screenshots."""
|
||||
|
||||
def __init__(self, count: int = 8):
|
||||
from frameport.frame.connection import parse_target
|
||||
|
||||
self.label = "steamframe"
|
||||
self.frame = FakeFS()
|
||||
self.target = parse_target("steamos@steamframe.local")
|
||||
works = [g for g in library.games() if g.get("kind") != "rift" and (g.get("build") or {}).get("sha256")
|
||||
and (g.get("recipe") or {}).get("status") in ("works", "issues")]
|
||||
works.sort(key=lambda g: -(g.get("data_bytes") or 0))
|
||||
self.games = [{"package": g["package"], "kind": "quest", "title": g.get("title"),
|
||||
"apk_size": (g.get("data_bytes") or 0) + 2**28, "sha256": g["build"]["sha256"],
|
||||
"recipe": {"patches": (g.get("recipe") or {}).get("patches", [])}} for g in works[:count]]
|
||||
# --linux: the AppImage is on the Frame, but SteamOS lacks one of its libraries
|
||||
self.games += [{"package": g["package"], "kind": "linux", "title": g.get("title"), "apk_size": 2**26,
|
||||
"apk_present": True, "recipe": None, "exe": g.get("exe"),
|
||||
"missing_libraries": ["libwebkit2gtk-4.1.so.0"]}
|
||||
for g in library.games() if g.get("kind") == "linux" and g["package"] == LINUX_APPIMAGE]
|
||||
# GitHub #90: most games on internal storage, the second one on a microSD card
|
||||
sd = {"internal": False, "path": "/run/media/steamos/SD Card", "label": "SD Card"}
|
||||
for i, g in enumerate(self.games):
|
||||
g["drive"] = sd if i == 1 else {"internal": True, "path": "/home/steamos", "label": "Internal storage"}
|
||||
g["drive_missing"] = False
|
||||
|
||||
def drives(self) -> list[dict]:
|
||||
sd_games = sum(1 for g in self.games if not g["drive"]["internal"])
|
||||
return [{"id": "internal", "path": "/home/steamos", "install_dir": "/home/steamos/Applications/quest-frame",
|
||||
"label": "Internal storage", "fstype": "ext4", "internal": True, "removable": False,
|
||||
"free_bytes": 312 * 2**30, "total_bytes": 460 * 2**30, "usable": True, "reason": "",
|
||||
"games": len(self.games) - sd_games},
|
||||
{"id": "/run/media/steamos/SD Card", "path": "/run/media/steamos/SD Card",
|
||||
"install_dir": "/run/media/steamos/SD Card/FramePort", "label": "SD Card", "fstype": "ext4",
|
||||
"internal": False, "removable": True, "free_bytes": 187 * 2**30, "total_bytes": 238 * 2**30,
|
||||
"usable": True, "reason": "", "games": sd_games},
|
||||
{"id": "/run/media/steamos/USB", "path": "/run/media/steamos/USB", "install_dir":
|
||||
"/run/media/steamos/USB/FramePort", "label": "USB", "fstype": "exfat", "internal": False,
|
||||
"removable": True, "free_bytes": 50 * 2**30, "total_bytes": 64 * 2**30, "usable": False,
|
||||
"reason": "exfat can't hold game data (no Unix permissions or symlinks); format the drive in "
|
||||
"SteamOS to install games on it", "games": 0}]
|
||||
|
||||
def move(self, package, dest, reporter) -> dict:
|
||||
reporter.stage("Move game files")
|
||||
for i in range(5):
|
||||
reporter.progress(i / 4, f"Copying {i / 2:.1f}/2.0 GiB")
|
||||
time.sleep(0.5)
|
||||
return {"state": "done", "package": package}
|
||||
|
||||
def set_desktop_entry(self, package, enabled) -> dict:
|
||||
for g in self.games:
|
||||
if g["package"] == package:
|
||||
g["desktop_entry"] = enabled
|
||||
return {"enabled": enabled}
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"hostname": "steamframe", "os": "SteamOS", "os_version": "3.8", "build_id": "20260922",
|
||||
"free_bytes": 312 * 2**30, "installed": self.games, "lepton": True,
|
||||
"proton": {"ready": {"display_name": "Proton 11 (ARM64)"}, "openxr": {"name": "SteamVR"}},
|
||||
"kernel_keys": {"keys": 31, "max_keys": 200}}
|
||||
|
||||
def installed(self) -> list[dict]:
|
||||
return self.games
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeKeyboardSession:
|
||||
"""--fake-frame: Type on Frame connects at once (nothing is sent anywhere)."""
|
||||
|
||||
def __init__(self, frame):
|
||||
self.closed = False
|
||||
|
||||
def key(self, name, action="down"):
|
||||
return True
|
||||
|
||||
def text(self, text):
|
||||
return ""
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeMonitorSession:
|
||||
"""--fake-frame: the Monitor tab's stream as synthetic samples, one per second, shaped like a real Quest game on
|
||||
the dev Frame (2026-10-07): 72 fps, the game's Android container, SteamVR/Steam as context. Two minutes are sent
|
||||
at once first, so the charts are full in screenshots. GAME = --game (else the library's first game)."""
|
||||
|
||||
GAME: str | None = None
|
||||
BACKFILL = 120
|
||||
# (name, group, CPU %, GPU %, memory); "GAME" = the game's package
|
||||
PROCS = [("GAME", "game", 9.8, 44.0, 1_350_000_000), ("vrcompositor", "steamvr", 1.4, 9.0, 80_000_000),
|
||||
("system_server", "game", 1.1, 0.0, 296_000_000), ("XRServiceLoopTh", "steamvr", 0.5, 0.0, 433_000_000),
|
||||
("steamwebhelper", "steam", 0.4, 0.0, 350_000_000), ("com.android.systemui", "game", 0.1, 0.0,
|
||||
229_000_000),
|
||||
("surfaceflinger", "game", 0.1, 0.4, 96_000_000), ("audioserver", "game", 0.1, 0.0, 31_000_000),
|
||||
("com.android.providers.media.module", "game", 0.1, 0.0, 130_000_000),
|
||||
("com.android.launcher3", "game", 0.0, 0.0, 194_000_000), ("main", "game", 0.0, 0.0, 178_000_000),
|
||||
("com.android.settings", "game", 0.0, 0.0, 172_000_000),
|
||||
("com.android.networkstack.process", "game", 0.0, 0.0, 130_000_000),
|
||||
("android.ext.services", "game", 0.0, 0.0, 111_000_000)] + \
|
||||
[("vrwebhelper", "steamvr", 0.3, 0.0, 160_000_000 + i * 9_000_000) for i in range(4)]
|
||||
|
||||
def __init__(self, frame, on_sample, on_end=None):
|
||||
import math
|
||||
|
||||
self.math, self.closed, self.on_sample = math, False, on_sample
|
||||
self.static = {"agent": 62, "cores": 8, "gpu_max_mhz": 903, "mem_total": 16 * 1024 ** 3, "fan": True,
|
||||
"clusters": [{"cpus": [0, 1], "max_mhz": 2265}, {"cpus": [2, 3, 4], "max_mhz": 3148},
|
||||
{"cpus": [5, 6], "max_mhz": 2956}, {"cpus": [7], "max_mhz": 3052}],
|
||||
"temp_groups": ["CPU", "GPU", "Memory", "Battery", "NPU", "Power ICs", "Modem", "Camera"]}
|
||||
self.t = 0
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
|
||||
def _sample(self) -> dict:
|
||||
m, t = self.math, self.t
|
||||
wave = lambda a, p, o=0: a * (1 + m.sin(t / p + o)) / 2 # noqa: E731
|
||||
g = library.game(self.GAME) if self.GAME else (library.games() or [None])[0]
|
||||
game = g or {"package": "com.example.game", "title": "Example Game"}
|
||||
pkg = game["package"]
|
||||
procs = [{"pid": 570799 + i * 37, "ppid": 1, "name": pkg if n == "GAME" else n,
|
||||
"group": f"game:{pkg}" if grp == "game" else grp, "game": pkg if grp == "game" else None,
|
||||
"cpu": round(c * (0.85 + wave(0.3, 3, i)), 1), "gpu": round(gp * (0.9 + wave(0.2, 5, i)), 1),
|
||||
"rss": r, "age": 1500 + t, "uid": 1000, "critical": grp in ("steamvr", "steam"), "locked": False,
|
||||
"context": grp != "game"}
|
||||
for i, (n, grp, c, gp, r) in enumerate(self.PROCS)]
|
||||
return {
|
||||
"t": time.time() - max(0, self.BACKFILL - t), "dt": 1.0, "self_ms": 11.5,
|
||||
"cpu": {"total": round(15 + wave(4, 4), 1), "cores": [round(4 + wave(30, 3 + i, i), 1) for i in range(8)],
|
||||
"mhz": [2265, 1996, 1920, 518]},
|
||||
"gpu": {"busy": round(52 + wave(8, 5), 1), "mhz": 903},
|
||||
"mem": {"total": 15.3 * 1024 ** 3, "avail": int((8.3 - wave(0.15, 9)) * 1024 ** 3),
|
||||
"swap_total": 7.6 * 1024 ** 3, "swap_free": 7.4 * 1024 ** 3},
|
||||
"psi": {"cpu": 1.0, "memory": 0.0, "io": 0.1},
|
||||
"temps": {"CPU": round(48 + wave(1.5, 11), 1), "GPU": round(46.5 + wave(1, 13), 1), "Memory": 47.1,
|
||||
"Battery": 27.7, "NPU": 47.3, "Power ICs": 37.0, "Modem": 44.2, "Camera": 46.3},
|
||||
"zones": {"CPU": {"cpu7-top": 48.4, "cpu0": 44.0}, "GPU": {"gpuss-0": 46.5}},
|
||||
"fan": 8500 + int(wave(300, 7)),
|
||||
"power": {"system": round(7.3 + wave(0.6, 4), 2), "cpu": 0.85, "gpu": round(1.0 + wave(0.3, 5), 2),
|
||||
"npu": 0.1},
|
||||
"battery": {"percent": 95, "status": "Discharging", "plugged": False, "draining": True, "watts": -1.96,
|
||||
"empty_s": 22440},
|
||||
"net": {"wlan0": [int(2000 + wave(4000, 3)), 1000], "wlanap": [0, 0], "usb0": [0, 0]},
|
||||
"games": [{"package": pkg, "title": game.get("title") or pkg, "kind": "quest", "appid": 1,
|
||||
"elapsed": 1500 + t, "cpu": 9.4, "gpu": round(44 + wave(6, 5), 1), "mem": 3_390_000_000,
|
||||
"processes": 87, "fps": round(71.6 + wave(0.6, 2) - (9 if t % 41 == 30 else 0), 1),
|
||||
"frame_ms": 0.0}],
|
||||
"procs": procs, "filter": "game"}
|
||||
|
||||
def _run(self) -> None:
|
||||
for self.t in range(100000):
|
||||
if self.closed:
|
||||
return
|
||||
self.on_sample(self._sample())
|
||||
if self.t >= self.BACKFILL: # the first two minutes at once (full charts), then one per second
|
||||
time.sleep(1)
|
||||
|
||||
def set_interval(self, s): pass # noqa: E704
|
||||
def set_filter(self, w): pass # noqa: E704
|
||||
def pause(self, p): pass # noqa: E704
|
||||
|
||||
def kill(self, pid, sig="TERM", force=False):
|
||||
return {"ended": True, "pid": pid}
|
||||
|
||||
def end_game(self, package):
|
||||
return {"ended": True, "via": "steam"}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def open_type_tab(app: FramePortApp) -> None:
|
||||
"""The Type on Frame tab, with one key 'pressed' so the screenshot shows it working."""
|
||||
app.type_on_frame()
|
||||
time.sleep(1.5)
|
||||
app.keyboard_view.press("Enter")
|
||||
|
||||
|
||||
def open_monitor_details(app: FramePortApp) -> None:
|
||||
"""The Monitor with its details row open."""
|
||||
app.go("monitor")
|
||||
time.sleep(2)
|
||||
if not app.monitor_view.details.visible:
|
||||
app.monitor_view.toggle_details()
|
||||
|
||||
|
||||
LINUX_APPIMAGE = "linux.venera" # --linux's packages
|
||||
LINUX_FOLDER = "linux.matineevr"
|
||||
|
||||
|
||||
def _elf(machine: int = 183, appimage: bool = False, extra: bytes = b"") -> bytes:
|
||||
"""A minimal ELF header (183 = aarch64): enough for FramePort's Linux app detection."""
|
||||
head = bytearray(64)
|
||||
head[:4], head[4], head[5] = b"\x7fELF", 2, 1
|
||||
if appimage:
|
||||
head[8:11] = b"AI\x02"
|
||||
head[18:20] = machine.to_bytes(2, "little")
|
||||
return bytes(head) + extra
|
||||
|
||||
|
||||
def add_fake_linux_apps() -> None:
|
||||
"""--linux: an AppImage and a VR app folder (with a helper program, so "Change program…" shows) in the library."""
|
||||
from frameport import pipeline
|
||||
from frameport.core.paths import user_data_dir
|
||||
|
||||
base = user_data_dir() / "smoke-linux"
|
||||
app = base / "MatineeVR"
|
||||
(app / "lib").mkdir(parents=True, exist_ok=True)
|
||||
(base / "Venera-2.4.2-aarch64.AppImage").write_bytes(_elf(appimage=True, extra=b"\0" * 4096))
|
||||
(app / "MatineeVR").write_bytes(_elf(extra=b"\0" * 8192))
|
||||
(app / "crashpad_handler").write_bytes(_elf())
|
||||
(app / "lib" / "libopenxr_loader.so.1").write_bytes(_elf(extra=b"xrCreateInstance"))
|
||||
pipeline.add_linux_app(base / "Venera-2.4.2-aarch64.AppImage")
|
||||
pipeline.add_linux_app(app)
|
||||
|
||||
|
||||
STEP_SECONDS = 4 # per screen (the screenshot is taken ~3 s in)
|
||||
|
||||
|
||||
def driver(app: FramePortApp, steps: list[tuple[str, callable]], ready: threading.Event, done_step: list):
|
||||
def driver(app: FramePortApp, steps: list[tuple[str, callable]], ready: threading.Event, shot_done: threading.Event,
|
||||
done_step: list):
|
||||
"""Runs one step, hands it to the shooter ("ready") and waits until its screenshot and mouse actions are done
|
||||
("shot_done") before the next one: so a screenshot always shows its own step, however long the shooter takes."""
|
||||
for name, action in steps:
|
||||
try:
|
||||
action(app)
|
||||
except Exception: # noqa: BLE001
|
||||
ERRORS.append(f"{name}: {traceback.format_exc()}")
|
||||
done_step.append(name)
|
||||
shot_done.clear()
|
||||
ready.set()
|
||||
time.sleep(STEP_SECONDS)
|
||||
if not shot_done.wait(STEP_TIMEOUT):
|
||||
ERRORS.append(f"{name}: no screenshot within {STEP_TIMEOUT} s, stopping")
|
||||
return
|
||||
|
||||
|
||||
def find_button(root, text: str):
|
||||
@@ -400,7 +99,8 @@ def main() -> int:
|
||||
ap.add_argument("--no-test", action="store_true", help="with --frame: skip the launch-test job")
|
||||
ap.add_argument("--scale", type=float, default=1.0, help="UI scale to render at (e.g. 1.5)")
|
||||
ap.add_argument("--viewport", default="1280x820", help="browser size, e.g. 2560x1440")
|
||||
ap.add_argument("--update", action="store_true", help="pretend a new FramePort release exists (update UI)")
|
||||
ap.add_argument("--update", action="store_true", help="pretend a new FramePort release exists (update UI: "
|
||||
"changelog dialog, what's new bar + dialog, Settings changelog)")
|
||||
ap.add_argument("--fake-frame", action="store_true", help="pretend a Steam Frame is connected (no device needed)")
|
||||
ap.add_argument("--hover", default=None, help="x,y: move the mouse there before the Library screenshot")
|
||||
ap.add_argument("--install-questions", nargs="+", metavar="PKG", default=None,
|
||||
@@ -410,18 +110,18 @@ def main() -> int:
|
||||
"(a Frame cabled to this PC) and screenshot what follows")
|
||||
ap.add_argument("--docs", action="store_true", help="only the screens used in the docs (Library, --game, Frame)")
|
||||
ap.add_argument("--gestures", action="store_true", help="with --fake-frame: real mouse drags (drag-select) and "
|
||||
"right-clicks (menus) in Files, Screenshots and the Library; prints what got selected")
|
||||
"right-clicks (menus) in Files, Screenshots and the Library; prints what got selected "
|
||||
"(positions for --viewport 1440x900)")
|
||||
ap.add_argument("--only", default=None, help="comma-separated step names to keep (e.g. monitor,monitor-details)")
|
||||
ap.add_argument("--linux", action="store_true", help="add two pretend arm64 Linux apps and render their pages")
|
||||
ap.add_argument("--links", action="store_true", help="install links: the Add games menu, the paste dialog, the "
|
||||
"confirmation for a pretend FrameDrop manifest, Settings → Install links and (with --game) the "
|
||||
"VR / flat window choice")
|
||||
ap.add_argument("--themes", action="store_true", help="Settings' theme picker, then switch every theme while "
|
||||
"running (Library and --game in each)")
|
||||
args = ap.parse_args()
|
||||
if args.linux:
|
||||
add_fake_linux_apps()
|
||||
global STEP_SECONDS
|
||||
if args.hover:
|
||||
STEP_SECONDS = 7
|
||||
from frameport.ui import theme
|
||||
|
||||
theme.set_scale(args.scale)
|
||||
@@ -430,19 +130,25 @@ def main() -> int:
|
||||
game = args.game or (library.games()[0]["package"] if library.games() else None)
|
||||
steps = [("library", lambda a: a.navigate(0)), ("frame", lambda a: a.navigate(1)),
|
||||
("files", lambda a: a.go("files")), ("screenshots", lambda a: a.go("screenshots")),
|
||||
("live", lambda a: a.go("live")), ("keyboard", lambda a: a.go("keyboard")),
|
||||
("live", lambda a: a.go("live")), ("live-streaming", fake_live_stream),
|
||||
("keyboard", lambda a: (stop_fake_live(a), a.go("keyboard"))),
|
||||
("monitor", lambda a: a.go("monitor")), ("monitor-details", open_monitor_details),
|
||||
("tools", lambda a: a.go("settings"))]
|
||||
("tools", lambda a: a.go("settings")),
|
||||
# the index on the left: "This PC" scrolls the page there
|
||||
("settings-index", lambda a: a.page.run_task(a.settings_view.show_section, "pc"))]
|
||||
if game:
|
||||
steps.insert(1, ("game", lambda a: a.open_game(game)))
|
||||
steps.insert(2, ("game-customize", lambda a: a.open_game(game, advanced=True)))
|
||||
steps += [("share-dialog", lambda a: a.share_config_dialog(game)),
|
||||
("report-dialog", lambda a: (a.page.pop_dialog(), a.report_problem_dialog(game))),
|
||||
("custom-art-dialog", lambda a: (a.page.pop_dialog(), a.custom_artwork(game)))]
|
||||
# a pretend install of --game, mid-upload: the transit in the sidebar, the game page and Activity
|
||||
steps += [("transit-game", lambda a: (a.page.pop_dialog(), start_fake_install(a, game), a.open_game(game))),
|
||||
("transit-activity", lambda a: a.show_activity(True))]
|
||||
if args.fake_frame: # GitHub #90: the Move to… dialog (drives load in the background)
|
||||
steps.append(("move-dialog", lambda a: (a.page.pop_dialog(), a.move_game(game))))
|
||||
# last: the right-click menu stays open over whatever comes next
|
||||
steps.append(("library-menu", lambda a: (a.page.pop_dialog(), a.navigate(0), time.sleep(3),
|
||||
steps.append(("library-menu", lambda a: (a.show_activity(False), a.navigate(0), time.sleep(3),
|
||||
a.library_view.open_menu(game))))
|
||||
if args.docs:
|
||||
steps = [("library", lambda a: a.navigate(0))]
|
||||
@@ -458,10 +164,63 @@ def main() -> int:
|
||||
steps.append(("type-on-frame", lambda a: (a.page.pop_dialog(), open_type_tab(a))))
|
||||
steps.append(("monitor", lambda a: a.go("monitor")))
|
||||
steps.append(("power-confirm", lambda a: (a.page.pop_dialog(), a.frame_power("restart"))))
|
||||
mouse: dict[str, callable] = {} # step name -> mouse actions (Playwright page) after its screenshot
|
||||
if args.gestures:
|
||||
STEP_SECONDS = 14 # the mouse actions run after each step's screenshot, before the next step
|
||||
# step name -> mouse actions (Playwright page) after its screenshot, then a "-mouse" screenshot unless the
|
||||
# actions return True (they saved their own picture, e.g. an opened menu)
|
||||
mouse: dict[str, callable] = {}
|
||||
hover: dict[str, tuple[float, float]] = {} # step name -> where the mouse rests for its screenshot
|
||||
if args.hover:
|
||||
hover["library"] = tuple(float(v) for v in args.hover.split(","))
|
||||
if not args.docs and args.viewport == "1440x900": # menus that open from buttons (positions at this size)
|
||||
def open_and_shoot(x, y, name):
|
||||
def run(page):
|
||||
page.mouse.click(x, y)
|
||||
time.sleep(2)
|
||||
page.screenshot(path=str(args.out / f"{name}.png"))
|
||||
page.mouse.click(1420, 880) # outside the menu (Flutter's popup ignores Escape)
|
||||
return True
|
||||
return run
|
||||
mouse["library"] = open_and_shoot(1354, 54, "library-add-menu")
|
||||
# type to search: click an empty part of the header, then type (the "-mouse" shot shows "arc" + the matches)
|
||||
steps.insert(1, ("library-typed", lambda a: a.library_view.clear_search()))
|
||||
def typed(page):
|
||||
page.mouse.click(480, 60)
|
||||
time.sleep(0.5)
|
||||
page.keyboard.type("arc", delay=120)
|
||||
if args.fake_frame: # the matches' cover buttons: Install (Arcsmith, not installed), Update (Pinball FX)
|
||||
time.sleep(PAINT_SECONDS)
|
||||
for name, pt in (("library-install-hover", (742, 215)), ("library-install-button", (742, 276)),
|
||||
("library-update-button", (357, 276))):
|
||||
page.mouse.move(*pt, steps=8)
|
||||
time.sleep(1.2)
|
||||
page.screenshot(path=str(args.out / f"{name}.png"))
|
||||
page.mouse.move(1300, 700)
|
||||
mouse["library-typed"] = typed
|
||||
steps.insert(2, ("library-cleared", lambda a: a.library_view.clear_search()))
|
||||
if args.fake_frame: # the "On your Frame" shelf's first card, hovered: its Play button shows
|
||||
steps.insert(3, ("library-shelf-hover", lambda a: None))
|
||||
hover["library-shelf-hover"] = (403, 268)
|
||||
# the grid's first card: hovered (lift, zoom, the glass button), the pointer on its button, then Play:
|
||||
# the portal rings mid-ripple and the "Starting on Frame…" pill
|
||||
steps.insert(4, ("library-card-hover", lambda a: None))
|
||||
hover["library-card-hover"] = (357, 420)
|
||||
steps.insert(5, ("library-card-button", lambda a: None))
|
||||
hover["library-card-button"] = (357, 497)
|
||||
|
||||
def launch(page):
|
||||
page.mouse.move(357, 497)
|
||||
time.sleep(1.2)
|
||||
page.mouse.click(357, 497)
|
||||
for i in range(6): # the launch, frame by frame (rings, then the pill)
|
||||
time.sleep(0.15)
|
||||
page.screenshot(path=str(args.out / f"library-play-launch-{i}.png"))
|
||||
time.sleep(1.0)
|
||||
page.screenshot(path=str(args.out / "library-play-starting.png"))
|
||||
page.mouse.move(130, 520)
|
||||
return True
|
||||
mouse["library-card-button"] = launch
|
||||
if game:
|
||||
mouse["game"] = open_and_shoot(491, 306, "game-more-menu") # the hero's "…"
|
||||
if args.gestures: # the mouse actions run after each step's screenshot, before the next step
|
||||
def drag(*points):
|
||||
def run(page):
|
||||
page.mouse.move(*points[0])
|
||||
@@ -498,11 +257,12 @@ def main() -> int:
|
||||
"files-dragged": right_click(900, 320), # a selected one: "… 3 items"
|
||||
"files-menu": lambda page: (escape(page), time.sleep(0.5), right_click(900, 600)(page)),
|
||||
"files-space-menu": escape,
|
||||
"screenshots": drag((680, 280), (950, 280), (950, 430)), # 3 shots
|
||||
"screenshots-dragged": right_click(950, 430),
|
||||
"screenshots": drag((400, 300), (680, 300), (950, 300)), # 3 shots (the first row)
|
||||
"screenshots-dragged": right_click(950, 300),
|
||||
"screenshots-menu": escape,
|
||||
"library": drag((360, 300), (560, 300), (760, 300)), # 3 cards, select mode on
|
||||
"library-dragged": drag((560, 300), (760, 300))} # from a selected card: deselects 2
|
||||
# the grid's first row (below the "On your Frame" shelf)
|
||||
"library": drag((360, 560), (560, 560), (760, 560)), # 3 cards, select mode on
|
||||
"library-dragged": drag((560, 560), (760, 560))} # from a selected card: deselects 2
|
||||
if args.linux:
|
||||
def linux_filter(a, value):
|
||||
a.navigate(0)
|
||||
@@ -540,10 +300,7 @@ def main() -> int:
|
||||
ImageDraw.Draw(im).ellipse((72, 72, 184, 184), fill=(255, 214, 102, 255))
|
||||
im.save(icon)
|
||||
|
||||
def add_menu(a):
|
||||
a.navigate(0)
|
||||
time.sleep(2)
|
||||
steps = [("library", add_menu),
|
||||
steps = [("library", lambda a: a.navigate(0)),
|
||||
("links-paste", lambda a: a.pick_link()),
|
||||
("links-confirm", lambda a: (a.page.pop_dialog(), link_dialog._confirm(a, fake, sizes, False, icon))),
|
||||
("links-settings", lambda a: (a.page.pop_dialog(), a.go("settings")))]
|
||||
@@ -554,7 +311,31 @@ def main() -> int:
|
||||
time.sleep(2)
|
||||
page.screenshot(path=str(args.out / "library-add-menu.png"))
|
||||
page.mouse.click(120, 520) # outside the menu (Flutter's popup ignores Escape)
|
||||
mouse["library"] = add_menu_open # tall pages: run with e.g. --viewport 1280x3200
|
||||
return True
|
||||
# tall pages: run with e.g. --viewport 1280x3200 (at 1440x900 the tour's own Add games click is kept)
|
||||
mouse.setdefault("library", add_menu_open)
|
||||
if args.themes:
|
||||
from frameport.ui import theme as T
|
||||
from frameport.ui.app import themes_dir
|
||||
|
||||
T.load_user_themes(themes_dir()) # installed theme files are switched through too
|
||||
|
||||
def switch(name):
|
||||
def run(a):
|
||||
library.set_setting("ui.theme", name) # what the picker does
|
||||
a.restyle(name)
|
||||
return run
|
||||
|
||||
def appearance(a):
|
||||
"""Settings: Appearance is its first section."""
|
||||
a.go("settings")
|
||||
steps = [("appearance", appearance)]
|
||||
for name in [n for n in T.THEMES if n != T.THEME] + [T.THEME]:
|
||||
steps.append((f"{name}-switched", switch(name)))
|
||||
steps.append((f"{name}-appearance", appearance))
|
||||
steps.append((f"{name}-library", lambda a: a.navigate(0)))
|
||||
if game:
|
||||
steps.append((f"{name}-game", lambda a: a.open_game(game)))
|
||||
if args.usb_setup:
|
||||
def continue_usb(a):
|
||||
dialog = [d for d in a.page._dialogs.controls if d.open and type(d).__name__ == "AlertDialog"][-1]
|
||||
@@ -582,14 +363,48 @@ def main() -> int:
|
||||
steps = [("library", lambda a: a.navigate(0)), ("questions", open_questions),
|
||||
("after-1st-double", double_click), ("after-2nd-double", double_click), ("end", report)]
|
||||
if args.update:
|
||||
from frameport import updates
|
||||
from frameport import __version__, updates
|
||||
|
||||
notes = ("FramePort v9.9.9: Windows (x64), macOS (Apple Silicon) and Linux (x64, ARM64).\n\n## What's new\n\n"
|
||||
"- Self-update test release: the update dialog shows every version since yours\n"
|
||||
"- **Bold** and `code` in notes, and a [link](https://example.invalid)\n- A third bullet\n\n"
|
||||
"Already have FramePort? It offers this update itself (Library → **Update now**).\n\n## Install\n\n"
|
||||
"- footer that the changelog leaves out\n")
|
||||
fake = updates.Update(version="9.9.9", tag="v9.9.9", page="https://example.invalid", asset=None, asset_url=None,
|
||||
sums_url=None, wheel_url=None,
|
||||
notes="## What's new\n- Self-update test release\n- **Bold** and `code` in notes")
|
||||
sums_url=None, wheel_url=None, notes=notes, published="2026-10-08T10:00:00Z")
|
||||
major, minor, _patch = updates.parse_version(__version__)[:3]
|
||||
older = f"{major}.{max(minor - 1, 0)}"
|
||||
|
||||
def entry(version, date, body):
|
||||
return updates.ChangelogEntry(version=version, tag=f"v{version}", date=date, title=f"FramePort v{version}",
|
||||
body=body, page="https://example.invalid",
|
||||
dev=updates.is_dev_version(version))
|
||||
fake_log = [updates.entry_from_update(fake),
|
||||
entry("9.9.8", "2026-10-06", "- Install links from FrameDrop buttons\n- Faster uploads over USB"),
|
||||
entry("9.9.7", "2026-10-04", "- Monitor tab with live Frame stats"),
|
||||
entry(__version__, "2026-10-02", "- The version you have: **Live view** with sound\n"
|
||||
"- Files tab: drag and drop\n- Smaller fixes"),
|
||||
entry(f"{older}.3", "2026-09-30", "- Proton defaults to the newest stable build"),
|
||||
entry(f"{older}.2", "2026-09-28", "- Language packs")]
|
||||
updates.fetch_changelog = lambda force=False, need=None: list(fake_log) # no GitHub in screenshots
|
||||
|
||||
def news(a):
|
||||
a.updater._set(None)
|
||||
a.updater.news = updates.recent_history(fake_log, n=3)
|
||||
a.navigate(0)
|
||||
a.refresh_view()
|
||||
|
||||
def settings_updates(a):
|
||||
a.go("settings")
|
||||
# once the page is mounted: scrolling an unmounted column does nothing
|
||||
threading.Timer(1.0, lambda: a.page.run_task(a.settings_view.show_section, "updates")).start()
|
||||
steps += [("update-banner", lambda a: (a.updater._set(fake), a.navigate(0))),
|
||||
("update-dialog", lambda a: a.updater.show_dialog()),
|
||||
("update-settings", lambda a: (a.page.pop_dialog(), a.go("settings")))]
|
||||
("update-settings", lambda a: (a.page.pop_dialog(), settings_updates(a))),
|
||||
("update-whats-new-bar", lambda a: news(a)),
|
||||
("update-whats-new-dialog", lambda a: a.updater.show_news()),
|
||||
("update-settings-changelog", lambda a: (a.page.pop_dialog(), settings_updates(a),
|
||||
a.updater.show_history()))]
|
||||
if args.frame:
|
||||
from frameport.frame.connection import parse_target
|
||||
|
||||
@@ -615,55 +430,70 @@ def main() -> int:
|
||||
if args.only: # in the order given (e.g. frame-connected,monitor)
|
||||
by_name = dict(steps)
|
||||
steps = [(n, by_name[n]) for n in args.only.split(",") if n in by_name]
|
||||
ready, done = threading.Event(), []
|
||||
# a first screen while the web fonts load: shot before that, text measured with a fallback font wrapped or
|
||||
# overlapped ("Q / uest", a check mark over its pill's text); its picture is 00-warmup.png. Settings, not the
|
||||
# Library: opening the Library twice restarts its card loading and the next shot caught it empty
|
||||
steps.insert(0, ("warmup", lambda a: a.go("settings")))
|
||||
ready, shot_done, done = threading.Event(), threading.Event(), []
|
||||
|
||||
from frameport.ui.app import serialize_flet_updates
|
||||
|
||||
serialize_flet_updates() # as the app's main() does
|
||||
if args.fake_frame: # never reach a real Frame (start-up auto-connect, discovery, the 30 s poll)
|
||||
from frameport.frame import keyboard, monitor
|
||||
|
||||
keyboard.KeyboardSession = FakeKeyboardSession
|
||||
monitor.MonitorSession = FakeMonitorSession
|
||||
FakeMonitorSession.GAME = game # the game card shows --game (with its artwork)
|
||||
FramePortApp.connect = lambda self, *a, **k: None
|
||||
FramePortApp.refresh_frame = lambda self, *a, **k: None
|
||||
install_fakes(game)
|
||||
|
||||
def app_main(page: ft.Page):
|
||||
try:
|
||||
app = FramePortApp(page)
|
||||
if args.fake_frame:
|
||||
app.target = FakeTarget()
|
||||
app.frame_info, app.frame_state = app.target.describe(), "connected"
|
||||
attach_fake_frame(app)
|
||||
except Exception: # noqa: BLE001
|
||||
ERRORS.append("startup: " + traceback.format_exc())
|
||||
return
|
||||
threading.Thread(target=driver, args=(app, steps, ready, done), daemon=True).start()
|
||||
threading.Thread(target=driver, args=(app, steps, ready, shot_done, done), daemon=True).start()
|
||||
|
||||
def shooter():
|
||||
# wait until the app's web server listens (a fixed 6 s was too short with another smoke run on the machine)
|
||||
import socket
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
time.sleep(6)
|
||||
for _ in range(90):
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", PORT), timeout=1).close()
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
time.sleep(2)
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader"])
|
||||
page = browser.new_page(viewport={"width": vw, "height": vh})
|
||||
page.goto(f"http://127.0.0.1:{PORT}", wait_until="networkidle", timeout=120_000)
|
||||
shot = 0
|
||||
deadline = time.time() + 240 + 8 * len(steps)
|
||||
while len(done) < len(steps) and time.time() < deadline:
|
||||
if ready.wait(1):
|
||||
ready.clear()
|
||||
name = done[-1]
|
||||
time.sleep(3) # let Flutter paint
|
||||
if args.hover and name == "library":
|
||||
hx, hy = (float(v) for v in args.hover.split(","))
|
||||
page.mouse.move(hx, hy)
|
||||
shot = handled = 0
|
||||
while handled < len(steps): # one hand-off per step (see driver)
|
||||
if not ready.wait(STEP_TIMEOUT):
|
||||
ERRORS.append(f"browser: no step after {done[-1] if done else 'start'} "
|
||||
f"within {STEP_TIMEOUT} s")
|
||||
break
|
||||
ready.clear()
|
||||
name = done[-1]
|
||||
try:
|
||||
time.sleep(PAINT_SECONDS)
|
||||
if name in hover:
|
||||
page.mouse.move(*hover[name])
|
||||
time.sleep(1.5)
|
||||
page.screenshot(path=str(args.out / f"{shot:02d}-{name}.png"))
|
||||
shot += 1
|
||||
if name in mouse:
|
||||
mouse[name](page)
|
||||
time.sleep(2)
|
||||
if name in hover:
|
||||
page.mouse.move(130, 520) # the sidebar's empty part: nothing left hovered
|
||||
if name in mouse and mouse[name](page) is not True:
|
||||
time.sleep(PAINT_SECONDS) # e.g. typed search: the matching cards fade in
|
||||
page.screenshot(path=str(args.out / f"{shot:02d}-{name}-mouse.png"))
|
||||
shot += 1
|
||||
finally:
|
||||
handled += 1
|
||||
shot_done.set()
|
||||
browser.close()
|
||||
except Exception: # noqa: BLE001
|
||||
ERRORS.append("browser: " + traceback.format_exc())
|
||||
|
||||
|
After Width: | Height: | Size: 248 KiB |
@@ -110,3 +110,65 @@ def prewarm(package: str) -> None:
|
||||
src = pick(package, kinds)
|
||||
if src:
|
||||
thumb(src, width, src.stem)
|
||||
compute_tint(package)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------ cover tint
|
||||
TINT_ART = ("portrait", "square", "cover", "icon") # the library card's art (the cover people recognise)
|
||||
_tints: dict[str, str | None] = {} # package -> "#rrggbb" (None: no art / no usable colour)
|
||||
|
||||
|
||||
def tint_from_rgb(rgb: tuple[int, int, int]) -> str:
|
||||
"""A cover's dominant colour made to sit on the dark background: lightness 0.35-0.55, saturation at most 0.55."""
|
||||
import colorsys
|
||||
|
||||
h, lum, s = colorsys.rgb_to_hls(*(max(0, min(255, c)) / 255 for c in rgb))
|
||||
r, g, b = colorsys.hls_to_rgb(h, min(0.55, max(0.35, lum)), min(0.55, s))
|
||||
return "#{:02x}{:02x}{:02x}".format(*(round(c * 255) for c in (r, g, b)))
|
||||
|
||||
|
||||
def dominant_rgb(colors: list[tuple[int, tuple[int, int, int]]]) -> tuple[int, int, int] | None:
|
||||
"""The most common clearly coloured entry of [(count, rgb)] (saturation ≥ 0.25, neither near black nor near
|
||||
white); else the most common one overall. None for an empty list."""
|
||||
import colorsys
|
||||
|
||||
def colourful(rgb) -> bool:
|
||||
_, lum, s = colorsys.rgb_to_hls(*(c / 255 for c in rgb))
|
||||
return s >= 0.25 and 0.12 <= lum <= 0.88
|
||||
ranked = [rgb for _, rgb in sorted(colors, key=lambda c: -c[0])]
|
||||
return next((rgb for rgb in ranked if colourful(rgb)), ranked[0] if ranked else None)
|
||||
|
||||
|
||||
def compute_tint(package: str) -> str | None:
|
||||
"""The cover's tint, cached next to the thumbnails (t_tint_<sha8>.json, named after its source like a thumbnail)
|
||||
and in memory. Image work: call from a background thread (render paths use cached_tint)."""
|
||||
import json
|
||||
|
||||
src = pick(package, TINT_ART)
|
||||
value = None
|
||||
if src:
|
||||
out = src.parent / f"t_tint_{_digest(src)}.json"
|
||||
try:
|
||||
value = json.loads(out.read_text(encoding="utf-8")).get("tint")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(thumb(src, 400, src.stem)) as im:
|
||||
small = im.convert("RGB").resize((48, 48))
|
||||
q = small.quantize(colors=8)
|
||||
pal = q.getpalette() or []
|
||||
rgb = dominant_rgb([(n, tuple(pal[i * 3:i * 3 + 3])) for n, i in (q.getcolors() or [])])
|
||||
value = tint_from_rgb(rgb) if rgb else None
|
||||
for old in src.parent.glob("t_tint_*.json"):
|
||||
old.unlink(missing_ok=True)
|
||||
out.write_text(json.dumps({"tint": value}), encoding="utf-8")
|
||||
except Exception: # noqa: BLE001 (unreadable image: no tint)
|
||||
value = None
|
||||
_tints[package] = value
|
||||
return value
|
||||
|
||||
|
||||
def cached_tint(package: str) -> tuple[bool, str | None]:
|
||||
"""(known, tint) from memory only (no I/O, for render paths); known=False: compute_tint hasn't run yet."""
|
||||
return (package in _tints, _tints.get(package))
|
||||
@@ -15,6 +15,8 @@ from collections.abc import Callable
|
||||
from ..core import applog
|
||||
|
||||
MIN_AGENT = 62 # first agent with `_monitor`
|
||||
MIN_AGENT_MODULES = 65 # first agent that takes {"modules": [...]} (collects only what's asked for)
|
||||
MODULES = ("games", "procs", "cpu", "gpu", "mem", "temps", "power", "battery", "net", "disk") # agent MON_MODULES
|
||||
HISTORY = 120 # points per sparkline (2 min at 1 s)
|
||||
REPLY_TIMEOUT = 15.0
|
||||
|
||||
@@ -101,6 +103,18 @@ class MonitorSession:
|
||||
def pause(self, paused: bool) -> None:
|
||||
self.send({"pause": bool(paused)})
|
||||
|
||||
@property
|
||||
def supports_modules(self) -> bool:
|
||||
return int(self.static.get("agent") or 0) >= MIN_AGENT_MODULES
|
||||
|
||||
def set_modules(self, modules) -> bool:
|
||||
"""Ask the agent to collect only these modules (an iterable of MODULES names, or "all"). False (nothing sent)
|
||||
when the agent is older than MIN_AGENT_MODULES: it keeps sending everything."""
|
||||
if not self.supports_modules:
|
||||
return False
|
||||
self.send({"modules": "all" if modules == "all" else sorted(modules)})
|
||||
return True
|
||||
|
||||
def _request(self, msg: dict, timeout: float = REPLY_TIMEOUT) -> dict:
|
||||
rid = next(self._ids)
|
||||
slot = [threading.Event(), None]
|
||||
@@ -219,7 +233,7 @@ def fmt_duration(s: float | None) -> str:
|
||||
|
||||
|
||||
def fmt_pct(v: float | None) -> str:
|
||||
return "–" if v is None else f"{v:.0f} %"
|
||||
return "–" if v is None else f"{v:.0f}%"
|
||||
|
||||
|
||||
# (warn, error) thresholds; "low" metrics warn when the value falls below them
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
"""MonitorHub: one app-owned `_monitor` stream shared by every place that shows live Frame data (the Monitor tab, the
|
||||
sidebar's live Frame card). Subscribers name the modules they need and how often; the hub runs at most one
|
||||
MonitorSession with the union of the active subscribers' modules and the fastest interval, reconfigures it when
|
||||
subscribers change, fans every sample out, reconnects every RETRY_SECONDS after the stream was lost and stops it when
|
||||
nobody (unpaused) is left. No Flet here: callbacks run on the session's reader thread or the hub's own threads.
|
||||
|
||||
States passed to `on_state(name, state, detail)`: "connecting", "live", "lost" (detail = why; a retry is scheduled),
|
||||
"error" (detail = the exception; no automatic retry, `reconnect()` tries again)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..core import applog
|
||||
from . import monitor as M
|
||||
|
||||
RETRY_SECONDS = 5.0 # reconnect after the stream was lost, while someone subscribes
|
||||
ALL = "all"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Subscriber:
|
||||
name: str
|
||||
modules: frozenset | str # MODULES names or "all"
|
||||
interval: float
|
||||
on_sample: Callable[[dict], None]
|
||||
on_state: Callable[[str, str, object], None] | None = None
|
||||
paused: bool = False
|
||||
|
||||
|
||||
def norm_modules(modules) -> frozenset | str:
|
||||
if modules is None or modules == ALL:
|
||||
return ALL
|
||||
if isinstance(modules, str):
|
||||
return frozenset({modules})
|
||||
return frozenset(modules)
|
||||
|
||||
|
||||
def snap_interval(seconds: float) -> float:
|
||||
"""The agent only takes M.INTERVALS: the slowest one that is at least as fast as asked."""
|
||||
fits = [i for i in M.INTERVALS if i <= seconds + 1e-9]
|
||||
return float(max(fits) if fits else M.INTERVALS[0])
|
||||
|
||||
|
||||
def merge(subs: Iterable[Subscriber]) -> tuple[frozenset | str | None, float | None]:
|
||||
"""(modules, interval) one stream needs for the active (unpaused) subscribers: the union of their modules ("all"
|
||||
if any wants everything) and the fastest interval. (None, None) when nobody is active."""
|
||||
active = [s for s in subs if not s.paused]
|
||||
if not active:
|
||||
return None, None
|
||||
if any(s.modules == ALL for s in active):
|
||||
modules: frozenset | str = ALL
|
||||
else:
|
||||
modules = frozenset().union(*(s.modules for s in active))
|
||||
return modules, snap_interval(min(s.interval for s in active))
|
||||
|
||||
|
||||
def _timer(delay: float, fn: Callable[[], None]):
|
||||
t = threading.Timer(delay, fn)
|
||||
t.daemon = True
|
||||
t.start()
|
||||
return t
|
||||
|
||||
|
||||
def _thread(fn: Callable[[], None]) -> None:
|
||||
threading.Thread(target=fn, name="monitor-hub-connect", daemon=True).start()
|
||||
|
||||
|
||||
class MonitorHub:
|
||||
def __init__(self, get_target: Callable[[], object], session_factory=M.MonitorSession,
|
||||
retry_seconds: float = RETRY_SECONDS, spawn: Callable = _thread, timer: Callable = _timer):
|
||||
self.get_target = get_target
|
||||
self.session_factory = session_factory
|
||||
self.retry_seconds = retry_seconds
|
||||
self._spawn = spawn
|
||||
self._timer = timer
|
||||
self._lock = threading.RLock()
|
||||
self._subs: dict[str, Subscriber] = {}
|
||||
self.session = None
|
||||
self.static: dict = {}
|
||||
self.state, self.detail = "idle", None
|
||||
self._gen = 0
|
||||
self._connecting = False
|
||||
self._pending = None # generation whose connect waits for the lock to be released
|
||||
self._retry = None
|
||||
self._applied: tuple = (ALL, M.DEFAULT_INTERVAL) # what the live session runs with
|
||||
self._filter = "game"
|
||||
self._stream_paused = False
|
||||
self.closed = False
|
||||
|
||||
# ---------------------------------------------------------------- subscribers
|
||||
def subscribe(self, name: str, modules, interval: float, on_sample: Callable[[dict], None],
|
||||
on_state: Callable[[str, str, object], None] | None = None) -> None:
|
||||
with self._lock:
|
||||
self._subs[name] = Subscriber(name, norm_modules(modules), float(interval), on_sample, on_state)
|
||||
note = self._reconcile()
|
||||
self._after(note, name)
|
||||
|
||||
def update(self, name: str, modules=None, interval: float | None = None) -> None:
|
||||
with self._lock:
|
||||
sub = self._subs.get(name)
|
||||
if sub is None:
|
||||
return
|
||||
if modules is not None:
|
||||
sub.modules = norm_modules(modules)
|
||||
if interval is not None:
|
||||
sub.interval = float(interval)
|
||||
note = self._reconcile()
|
||||
self._after(note)
|
||||
|
||||
def unsubscribe(self, name: str) -> None:
|
||||
with self._lock:
|
||||
if self._subs.pop(name, None) is None:
|
||||
return
|
||||
note = self._reconcile()
|
||||
self._after(note)
|
||||
|
||||
def pause(self, name: str, paused: bool = True) -> None:
|
||||
"""A paused subscriber gets no samples and doesn't count towards the stream's modules/interval."""
|
||||
with self._lock:
|
||||
sub = self._subs.get(name)
|
||||
if sub is None or sub.paused == bool(paused):
|
||||
return
|
||||
sub.paused = bool(paused)
|
||||
note = self._reconcile()
|
||||
self._after(note, None if paused else name)
|
||||
|
||||
def subscribed(self, name: str) -> bool:
|
||||
return name in self._subs
|
||||
|
||||
def reconnect(self) -> None:
|
||||
"""Try again now (after an "error", or when the Frame connection came back)."""
|
||||
with self._lock:
|
||||
if self.session is not None or self._connecting or self.closed:
|
||||
return
|
||||
self._cancel_retry()
|
||||
note = self._reconcile()
|
||||
self._after(note)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self.closed = True
|
||||
self._subs.clear()
|
||||
self._stop()
|
||||
|
||||
# ---------------------------------------------------------- pass-through actions
|
||||
def set_filter(self, which: str) -> None:
|
||||
"""The process filter ("game" | "steam" | "all"); kept for reconnects."""
|
||||
with self._lock:
|
||||
self._filter = which
|
||||
session = self.session
|
||||
if session is not None:
|
||||
session.set_filter(which)
|
||||
|
||||
def pause_stream(self, paused: bool) -> None:
|
||||
"""Pause the agent's samples for every subscriber (the stream stays open; kept for reconnects)."""
|
||||
with self._lock:
|
||||
self._stream_paused = bool(paused)
|
||||
session = self.session
|
||||
if session is not None:
|
||||
session.pause(bool(paused))
|
||||
|
||||
def _live(self):
|
||||
session = self.session
|
||||
if session is None:
|
||||
raise M.MonitorUnavailable("the monitor isn't connected")
|
||||
return session
|
||||
|
||||
def kill(self, pid: int, sig: str = "TERM", force: bool = False) -> dict:
|
||||
return self._live().kill(pid, sig, force)
|
||||
|
||||
def end_game(self, package: str) -> dict:
|
||||
return self._live().end_game(package)
|
||||
|
||||
# ---------------------------------------------------------------- internals
|
||||
def _reconcile(self) -> list:
|
||||
"""Start, stop or reconfigure the stream for the current subscribers. Called with the lock held; returns the
|
||||
state notifications to send once it's released."""
|
||||
if self.closed:
|
||||
return []
|
||||
modules, interval = merge(self._subs.values())
|
||||
if modules is None:
|
||||
self._stop()
|
||||
return []
|
||||
if self.session is not None:
|
||||
self._configure(self.session, modules, interval)
|
||||
return []
|
||||
if self._connecting or self._retry is not None:
|
||||
return []
|
||||
return self._start()
|
||||
|
||||
def _configure(self, session, modules, interval) -> None:
|
||||
old_modules, old_interval = self._applied
|
||||
try:
|
||||
if interval != old_interval:
|
||||
session.set_interval(interval)
|
||||
if modules != old_modules:
|
||||
session.set_modules(modules)
|
||||
except Exception: # noqa: BLE001 - the stream ending is reported through on_end
|
||||
applog.log.exception("monitor hub: reconfigure failed")
|
||||
self._applied = (modules, interval)
|
||||
|
||||
def _start(self) -> list:
|
||||
self._connecting = True
|
||||
self._set_state("connecting", None)
|
||||
self._pending = self._gen # connected by _after() once the lock is released
|
||||
return self._targets()
|
||||
|
||||
def _connect(self, gen: int) -> None:
|
||||
try:
|
||||
target = self.get_target()
|
||||
if target is None:
|
||||
raise M.MonitorUnavailable("not connected to a Frame")
|
||||
session = self.session_factory(target.frame, lambda s, g=gen: self._on_sample(g, s),
|
||||
lambda why, g=gen: self._on_end(g, why))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
with self._lock:
|
||||
if gen != self._gen:
|
||||
return
|
||||
self._connecting = False
|
||||
self._set_state("error", exc)
|
||||
note = self._targets()
|
||||
self._notify(note)
|
||||
return
|
||||
with self._lock:
|
||||
self._connecting = False
|
||||
modules, interval = merge(self._subs.values())
|
||||
if gen != self._gen or self.closed or modules is None: # nobody left while connecting
|
||||
stale = True
|
||||
else:
|
||||
stale = False
|
||||
self.session = session
|
||||
self.static = getattr(session, "static", {}) or {}
|
||||
self._applied = (ALL, M.DEFAULT_INTERVAL) # the agent's defaults
|
||||
self._configure(session, modules, interval)
|
||||
if self._filter != "game":
|
||||
session.set_filter(self._filter)
|
||||
if self._stream_paused:
|
||||
session.pause(True)
|
||||
self._set_state("live", None)
|
||||
note = self._targets()
|
||||
if stale:
|
||||
session.close()
|
||||
return
|
||||
self._notify(note)
|
||||
|
||||
def _on_sample(self, gen: int, sample: dict) -> None:
|
||||
if gen != self._gen:
|
||||
return
|
||||
for sub in [s for s in list(self._subs.values()) if not s.paused]:
|
||||
try:
|
||||
sub.on_sample(sample)
|
||||
except Exception: # noqa: BLE001 - one subscriber's bug must not starve the others
|
||||
applog.log.exception("monitor hub: subscriber %s failed", sub.name)
|
||||
|
||||
def _on_end(self, gen: int, why: str) -> None:
|
||||
with self._lock:
|
||||
if gen != self._gen or self.closed:
|
||||
return
|
||||
self.session = None
|
||||
if merge(self._subs.values())[0] is None:
|
||||
return
|
||||
self._set_state("lost", why)
|
||||
note = self._targets()
|
||||
self._retry = self._timer(self.retry_seconds, lambda: self._retry_now(gen))
|
||||
self._notify(note)
|
||||
|
||||
def _retry_now(self, gen: int) -> None:
|
||||
with self._lock:
|
||||
if gen != self._gen or self.closed:
|
||||
return
|
||||
self._retry = None
|
||||
note = self._reconcile()
|
||||
self._after(note)
|
||||
|
||||
def _cancel_retry(self) -> None:
|
||||
if self._retry is not None:
|
||||
try:
|
||||
self._retry.cancel()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
self._retry = None
|
||||
|
||||
def _stop(self) -> None:
|
||||
"""No active subscriber: end the stream (and anything pending). Lock held."""
|
||||
self._gen += 1
|
||||
self._connecting = False
|
||||
self._cancel_retry()
|
||||
session, self.session = self.session, None
|
||||
self.state, self.detail = "idle", None
|
||||
if session is not None:
|
||||
try:
|
||||
session.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def _set_state(self, state: str, detail) -> None:
|
||||
self.state, self.detail = state, detail
|
||||
|
||||
def _targets(self) -> list:
|
||||
return [(s, self.state, self.detail) for s in self._subs.values() if not s.paused and s.on_state]
|
||||
|
||||
def _tell(self, name: str) -> None:
|
||||
"""Bring one (new or resumed) subscriber up to date with the stream's state."""
|
||||
sub = self._subs.get(name)
|
||||
if sub and sub.on_state and not sub.paused and self.state != "idle":
|
||||
self._notify([(sub, self.state, self.detail)])
|
||||
|
||||
def _after(self, note: list, name: str | None = None) -> None:
|
||||
"""Outside the lock: send state notifications (or bring `name` up to date), then start a queued connect."""
|
||||
if note:
|
||||
self._notify(note)
|
||||
elif name is not None:
|
||||
self._tell(name)
|
||||
with self._lock:
|
||||
gen, self._pending = self._pending, None
|
||||
if gen is not None:
|
||||
self._spawn(lambda: self._connect(gen))
|
||||
|
||||
@staticmethod
|
||||
def _notify(note: list) -> None:
|
||||
for sub, state, detail in note:
|
||||
try:
|
||||
sub.on_state(sub.name, state, detail)
|
||||
except Exception: # noqa: BLE001
|
||||
applog.log.exception("monitor hub: state handler of %s failed", sub.name)
|
||||
@@ -318,6 +318,7 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self._send(503, relay.ended.encode(), "text/plain")
|
||||
return
|
||||
init, gop, q = relay.subscribe()
|
||||
sent, why, t0 = 0, "the stream ended", time.time()
|
||||
try:
|
||||
deadline = time.time() + 30
|
||||
while init is None: # the source hasn't sent its init segment yet
|
||||
@@ -335,6 +336,9 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self._chunk(init)
|
||||
for f in gop:
|
||||
self._chunk(f)
|
||||
sent = len(gop)
|
||||
agent = self.headers.get("User-Agent", "?")[:60]
|
||||
log.info("live view: viewer joined (%s)", agent)
|
||||
while True:
|
||||
try:
|
||||
f = q.get(timeout=5)
|
||||
@@ -342,14 +346,18 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
if relay.ended:
|
||||
break
|
||||
continue
|
||||
if f is None:
|
||||
if f is None: # finish() or dropped for lagging CLIENT_QUEUE fragments behind
|
||||
why = "the stream ended" if relay.ended else "it fell too far behind"
|
||||
break
|
||||
self._chunk(f)
|
||||
sent += 1
|
||||
self.wfile.write(b"0\r\n\r\n")
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):
|
||||
pass
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc:
|
||||
why = f"it disconnected ({type(exc).__name__})"
|
||||
finally:
|
||||
relay.unsubscribe(q)
|
||||
if init is not None:
|
||||
log.info("live view: viewer left after %.1f s, %d fragments: %s", time.time() - t0, sent, why)
|
||||
|
||||
def _chunk(self, data: bytes) -> None:
|
||||
self.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")
|
||||
@@ -614,6 +622,13 @@ class FrameSource:
|
||||
|
||||
def start(frame, quality: str = DEFAULT_QUALITY) -> LiveStream:
|
||||
"""Start streaming the Frame's headset view; open `.url` in a browser to watch."""
|
||||
client = getattr(frame, "client", None)
|
||||
transport = client.get_transport() if client is not None else None
|
||||
if transport is None or not transport.is_active():
|
||||
# (e.g. the Frame slept: without this, the helper upload failed with "'NoneType' object has no attribute
|
||||
# 'exec_command'" and the start went on with the software encoder)
|
||||
raise ConnectionError("The Frame isn't connected (it may be asleep): connect it again on the Steam Frame "
|
||||
"page, then start the live view")
|
||||
src = FrameSource(frame, quality)
|
||||
live = LiveStream(src.open, src.close)
|
||||
live.relay.on_join = src.request_keyframe
|
||||
|
||||
@@ -149,3 +149,10 @@ def delete(frame, shots: list[dict]) -> int:
|
||||
for kind in ("thumb", "full"):
|
||||
(cache_dir(frame) / _cache_name(s, kind)).unlink(missing_ok=True)
|
||||
return len(r.get("deleted") or [])
|
||||
|
||||
|
||||
def take(frame, wait: float = 8) -> dict:
|
||||
"""Take a headset screenshot on the Frame (agent v66 `take_screenshot`: OpenVR's RequestScreenshot +
|
||||
SubmitScreenshot, saved by Steam under SteamVR like one taken in the headset): {taken, path, reason, hmd}.
|
||||
reason "steamvr" = SteamVR isn't running, "capture" = nothing captured (the headset sleeps)."""
|
||||
return frame.agent("take_screenshot", wait=wait)
|
||||
@@ -602,12 +602,7 @@ def set_recipe(package: str, recipe: Recipe) -> None:
|
||||
|
||||
|
||||
def reset_recipe(package: str) -> Recipe:
|
||||
if is_rift(library.game(package) or {}):
|
||||
entry = library.game(package)
|
||||
a = library.analysis_from_dict(entry["analysis"])
|
||||
recipe = engine.suggest(a)
|
||||
set_recipe(package, recipe)
|
||||
return recipe
|
||||
"""Back to the suggested recipe (catalog or heuristics) for the game's analysis (Quest and Rift alike)."""
|
||||
entry = library.game(package)
|
||||
recipe = engine.suggest(library.analysis_from_dict(entry["analysis"]))
|
||||
set_recipe(package, recipe)
|
||||
|
||||
@@ -307,7 +307,7 @@ TOGGLED_DEVICE = ("device.text_input_window",)
|
||||
|
||||
def entry_from_library(g: dict, status: str | None = None, notes: str | None = None,
|
||||
verified: dict | None = None) -> CatalogEntry:
|
||||
"""A catalog recipe from a library entry (what "Save as known-good" and "Share working config" publish)."""
|
||||
"""A catalog recipe from a library entry (what "Save as known-good" and "Share working recipe" publish)."""
|
||||
import time
|
||||
|
||||
from ..core import library
|
||||
|
||||
@@ -32,10 +32,10 @@ def advice(battery: dict | None, frame_work: bool, paused: str | None, warned: b
|
||||
|
||||
|
||||
def label(battery: dict | None) -> str:
|
||||
""" "76 %" / "76 % ⚡" (charging or plugged in); "" without a battery reading."""
|
||||
""" "76%" / "76% ⚡" (charging or plugged in); "" without a battery reading."""
|
||||
if not battery:
|
||||
return ""
|
||||
return f"{battery.get('percent', 0)} %" + (" ⚡" if charging(battery) else "")
|
||||
return f"{battery.get('percent', 0)}%" + (" ⚡" if charging(battery) else "")
|
||||
|
||||
|
||||
def icon(battery: dict) -> str:
|
||||
@@ -55,10 +55,10 @@ def low(battery: dict | None) -> bool:
|
||||
def message(kind: str, battery: dict) -> str:
|
||||
pct = battery.get("percent", 0)
|
||||
if kind == "pause":
|
||||
return tr("The Frame's battery is at {pct} %: installs paused so it doesn't switch off mid-upload. Plug it "
|
||||
return tr("The Frame's battery is at {pct}%: installs paused so it doesn't switch off mid-upload. Plug it "
|
||||
"in; the queue continues by itself.").format(pct=pct)
|
||||
if kind == "warn":
|
||||
return tr("The Frame's battery is at {pct} % and not charging. Plug it in (a strong charger, not a PC "
|
||||
"port): long installs can drain it, and FramePort pauses them at {pause} %.").format(
|
||||
return tr("The Frame's battery is at {pct}% and not charging. Plug it in (a strong charger, not a PC "
|
||||
"port): long installs can drain it, and FramePort pauses them at {pause}%.").format(
|
||||
pct=pct, pause=PAUSE_AT)
|
||||
return tr("The Frame is charging: continuing the installs.")
|
||||
@@ -0,0 +1,56 @@
|
||||
"""The sidebar's live Frame card (no Flet): what one monitor sample shows there — the running game (title, how long it
|
||||
has been playing, its frame rate and that rate's level) and the battery ring. The app subscribes the card to the
|
||||
shared MonitorHub (frame/monitor_hub.py) with only the "games" and "battery" modules, every CARD_INTERVAL seconds,
|
||||
while the setting `ui.live_frame_card` is on."""
|
||||
from __future__ import annotations
|
||||
|
||||
from ..frame import monitor as M
|
||||
from ..i18n import tr
|
||||
from . import battery as B
|
||||
|
||||
SETTING = "ui.live_frame_card"
|
||||
CARD_INTERVAL = 5.0 # seconds between samples (the agent collects only games + battery for it)
|
||||
CARD_MODULES = ("games", "battery")
|
||||
FPS_WINDOW = 120.0 # the sparkline covers the last 2 minutes
|
||||
FPS_BUCKET = 5.0 # one point per CARD_INTERVAL (faster samples, e.g. with the Monitor open, are averaged)
|
||||
FPS_POINTS = int(FPS_WINDOW // FPS_BUCKET)
|
||||
|
||||
|
||||
def fps_history() -> M.History:
|
||||
return M.History(size=FPS_POINTS, bucket=FPS_BUCKET)
|
||||
|
||||
|
||||
def now_playing(sample: dict | None, fps_series: list | None = None) -> dict | None:
|
||||
"""Display values for the card's "now playing" row, or None when no game runs: package, title, line ("playing ·
|
||||
27 min"), fps text ("72" / "–"), level (ok | warn | error by the fps against its presumed refresh rate) and the
|
||||
fps target (refresh rate) for the sparkline's guide."""
|
||||
games = (sample or {}).get("games") or []
|
||||
if not games:
|
||||
return None
|
||||
g = games[0]
|
||||
pkg = g.get("package") or ""
|
||||
elapsed = g.get("elapsed")
|
||||
line = tr("playing · {t}").format(t=M.fmt_duration(elapsed)) if elapsed is not None else tr("playing")
|
||||
fps = g.get("fps")
|
||||
series = list(fps_series or [])
|
||||
target = M.fps_target(series + ([fps] if fps is not None else []))
|
||||
lvl = M.level("fps_ratio", fps / target if fps is not None and target else None)
|
||||
return {"package": pkg, "title": g.get("title") or pkg, "line": line, "minutes": int(elapsed // 60)
|
||||
if elapsed is not None else None, "fps": fps, "fps_text": f"{fps:.0f}" if fps is not None else "–",
|
||||
"level": lvl if fps is not None else "none", "target": target}
|
||||
|
||||
|
||||
def battery_ring(bat: dict | None) -> dict | None:
|
||||
"""The battery ring: value (0..1), the "76" text and its level (warn when low on battery power, charging when it
|
||||
gains charge, ok otherwise). None without a reading."""
|
||||
if not bat or bat.get("percent") is None:
|
||||
return None
|
||||
pct = max(0, min(100, int(bat.get("percent") or 0)))
|
||||
level = "warn" if B.low(bat) else "charging" if B.charging(bat) else "ok"
|
||||
return {"value": pct / 100.0, "text": f"{pct}", "level": level}
|
||||
|
||||
|
||||
def uploading(job) -> bool:
|
||||
"""A job is sending files to the Frame (installer/files stages "Upload …"): the card pauses its samples meanwhile
|
||||
(the link is busy)."""
|
||||
return bool(job) and (getattr(job, "stage", "") or "").startswith("Upload")
|
||||
@@ -0,0 +1,176 @@
|
||||
"""FramePort's own icons (no Flet): the logo and 24 px line glyphs for what Material has no icon for (the Frame, a
|
||||
portal, launch tests …). They ship as SVG files in ui/icons and are copied into the GUI's assets folder (the user data
|
||||
dir) so they load like artwork: by URL in source runs and the web view, by file path in packaged apps
|
||||
(artwork.thumbs.asset_url). Glyphs are drawn in white and tinted by the GUI (components.icon)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
PREFIX = "fp:"
|
||||
# glyph names usable wherever the GUI takes an icon (components.icon turns them into a tinted image)
|
||||
FRAME = "fp:frame" # the Steam Frame headset
|
||||
PORT = "fp:port" # portal + arrow: build / convert a game
|
||||
PATCH = "fp:patch"
|
||||
CONTAINER = "fp:container" # Lepton's per-game container
|
||||
TEST = "fp:test" # launch test
|
||||
PC = "fp:pc" # on this PC / PC VR
|
||||
SYNC = "fp:sync" # update on Frame
|
||||
LIVE = "fp:live" # live view
|
||||
SHOT = "fp:shot" # screenshots
|
||||
KEYS = "fp:keys" # type on Frame
|
||||
RECIPE = "fp:recipe" # verified catalog recipe
|
||||
LINK = "fp:link" # Frame connection
|
||||
|
||||
SOURCE = Path(__file__).with_name("icons")
|
||||
FOLDER = "ui-icons" # inside the assets folder
|
||||
|
||||
|
||||
def is_glyph(icon) -> bool:
|
||||
return isinstance(icon, str) and icon.startswith(PREFIX)
|
||||
|
||||
|
||||
def install(assets: Path) -> Path:
|
||||
"""Copy the bundled SVGs into <assets>/ui-icons (only files that changed). Returns that folder."""
|
||||
target = assets / FOLDER
|
||||
for src in [*SOURCE.glob("*.svg"), *(SOURCE / "glyphs").glob("*.svg")]:
|
||||
dest = target / src.name
|
||||
data = src.read_bytes()
|
||||
try:
|
||||
if dest.read_bytes() == data:
|
||||
continue
|
||||
except OSError:
|
||||
pass
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data)
|
||||
return target
|
||||
|
||||
|
||||
PORTAL_REV = 2
|
||||
|
||||
|
||||
def portal_mark(assets: Path, near: str, far: str, hole: str) -> Path:
|
||||
"""The small tilted portal between "Frame" and "Port" in the wordmark, in a theme's colours: the rim runs from
|
||||
`near` (the side facing "Frame") to `far` (facing "Port"), around a dark hole. Written once per colour set."""
|
||||
near, far, hole = (c.upper() for c in (near, far, hole))
|
||||
dest = assets / FOLDER / f"portal{PORTAL_REV}-{near[1:]}-{far[1:]}-{hole[1:]}.svg" # REV: the drawing changed
|
||||
if not dest.is_file():
|
||||
rim = (f'<linearGradient id="r" gradientUnits="userSpaceOnUse" x1="2" y1="0" x2="14" y2="0">'
|
||||
f'<stop offset=".3" stop-color="{near}"/><stop offset=".7" stop-color="{far}"/></linearGradient>')
|
||||
ring = '<ellipse cx="8" cy="14" rx="4.4" ry="10.6" transform="rotate(14 8 14)"'
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(f'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="28" viewBox="0 0 16 28">'
|
||||
f'<defs>{rim}</defs>'
|
||||
f'{ring} fill="none" stroke="url(#r)" stroke-opacity=".35" stroke-width="5"/>'
|
||||
f'{ring} fill="{hole}" stroke="url(#r)" stroke-width="2.6"/></svg>\n', encoding="utf-8")
|
||||
return dest
|
||||
|
||||
|
||||
TRANSIT_REV = 2
|
||||
|
||||
# The logo's parts, whole (the logo shows the monitor's left half and the headset's right half): same 64-unit
|
||||
# coordinates, strokes and radii as icons/logo.svg, each cropped to its own viewBox.
|
||||
_MONITOR = ('<svg xmlns="http://www.w3.org/2000/svg" width="39" height="38" viewBox="3 11.5 39 38">'
|
||||
'<path d="M9 15h27a3 3 0 0 1 3 3v20a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3V18a3 3 0 0 1 3-3z" fill="{body}" '
|
||||
'stroke="{line}" stroke-width="3" stroke-linejoin="round"/>'
|
||||
'<rect x="10.5" y="19.5" width="24" height="17" rx="1" fill="{screen}" fill-opacity="0.35"/>'
|
||||
'<path d="M22.5 41v6M15.5 47h14" fill="none" stroke="{line}" stroke-width="3" stroke-linecap="round"/>'
|
||||
'</svg>\n')
|
||||
# the visor mirrored about its nose notch (x 44.25), lenses either side, a strap stub on both ends
|
||||
_HEADSET = ('<svg xmlns="http://www.w3.org/2000/svg" width="34" height="28" viewBox="27.25 17.5 34 28">'
|
||||
'<path d="M30 31.5H32M56.5 31.5H58.5" stroke="{line}" stroke-width="3.4" stroke-linecap="round"/>'
|
||||
'<path d="M39.5 21H49a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7'
|
||||
'a3 3 0 0 1-2.6 1.5H39.5a8 8 0 0 1-8-8v-5a8 8 0 0 1 8-8z" fill="{body}" stroke="{line}" stroke-width="3" '
|
||||
'stroke-linejoin="round"/>'
|
||||
'<ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="{lens}"/>'
|
||||
'<ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="{lens}"/></svg>\n')
|
||||
# the portal: dark hole with a keyline, a soft glow and the blue→orange rim, tilted 18°, on a soft drop shadow. In
|
||||
# the transit the game's cover passes through it: "portal_back" (shadow, hole, the rim's near = PC/blue half) is drawn
|
||||
# under the cover, "portal_front" (the rim's far = Frame/orange half) over it; "portal" is both in one picture (empty
|
||||
# states). The halves are arcs of the same ellipse; the near one runs a few degrees past the split under the far
|
||||
# one, so no seam shows where they meet.
|
||||
_P_CX, _P_CY, _P_RX, _P_RY = 32, 32, 4.5, 22
|
||||
_P_VIEW = "20 7 26 54" # the ring (+ glow) spans x 21.3-42.7, y 7.9-56.1; the shadow reaches x 45.2, y 60
|
||||
|
||||
|
||||
def _portal_arc(t0: float, t1: float) -> str:
|
||||
"""Path along the portal's ellipse (unrotated) from parameter angle t0 to t1 (degrees; y points down, so a
|
||||
growing angle runs clockwise), in arcs of at most 90° (one 180° arc is ambiguous)."""
|
||||
import math
|
||||
|
||||
def pt(t: float) -> str:
|
||||
r = math.radians(t)
|
||||
return f"{_P_CX + _P_RX * math.cos(r):.3f} {_P_CY + _P_RY * math.sin(r):.3f}"
|
||||
|
||||
steps = max(1, math.ceil((t1 - t0) / 90 - 1e-9))
|
||||
return f"M{pt(t0)}" + "".join(f"A{_P_RX} {_P_RY} 0 0 1 {pt(t0 + (t1 - t0) * i / steps)}"
|
||||
for i in range(1, steps + 1))
|
||||
|
||||
|
||||
def _portal_svg(back: bool, front: bool) -> str:
|
||||
"""The portal's back (shadow, hole, near half), front (far half) or both; colours as {near}/{far}/{hole}."""
|
||||
rot = f'transform="rotate(18 {_P_CX} {_P_CY})"'
|
||||
ell = f'cx="{_P_CX}" cy="{_P_CY}" rx="{_P_RX}" ry="{_P_RY}"'
|
||||
near, far = _portal_arc(86, 274), _portal_arc(-90, 90) # near = x < cx, 4° longer at both ends
|
||||
|
||||
def half(d: str) -> str: # keyline, glow and rim along one half
|
||||
return (f'<path d="{d}" fill="none" stroke="{{hole}}" stroke-width="5.8"/>'
|
||||
f'<path d="{d}" fill="none" stroke="url(#r)" stroke-opacity=".25" stroke-width="6.46"/>'
|
||||
f'<path d="{d}" fill="none" stroke="url(#r)" stroke-width="3.4"/>')
|
||||
|
||||
out = ['<defs><linearGradient id="r" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0">'
|
||||
'<stop offset=".3" stop-color="{near}"/><stop offset=".7" stop-color="{far}"/></linearGradient></defs>']
|
||||
if back:
|
||||
# the drop shadow: the ring a little lower and to the right, blurred by hand (flutter_svg ignores <filter>):
|
||||
# stacked translucent outlines, each wider and fainter
|
||||
out.append(f'<g transform="translate(.7 2) rotate(18 {_P_CX} {_P_CY})">')
|
||||
out += [f'<ellipse {ell} fill="#000" fill-opacity="{a}" stroke="#000" stroke-opacity="{a}" '
|
||||
f'stroke-width="{w}"/>' for w, a in ((6.8, .22), (8.6, .13), (10.4, .07))]
|
||||
out.append(f'</g><g {rot}><ellipse {ell} fill="{{hole}}"/>{half(near)}'
|
||||
f'<ellipse {ell} fill="url(#r)" fill-opacity="0.14"/></g>')
|
||||
if front:
|
||||
out.append(f'<g {rot}>{half(far)}</g>')
|
||||
w, h = _P_VIEW.split()[2:]
|
||||
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="{_P_VIEW}">'
|
||||
+ "".join(out) + "</svg>\n")
|
||||
|
||||
|
||||
_PORTAL, _PORTAL_BACK, _PORTAL_FRONT = _portal_svg(True, True), _portal_svg(True, False), _portal_svg(False, True)
|
||||
PORTAL_RING = (24, 50) # the ring's box in viewBox units, from the portal viewBox's top left (the track = 50 units)
|
||||
TRANSIT_SIZES = {"monitor": (39, 38), "headset": (34, 28), "portal": (26, 54)} # viewBox sizes (aspect ratios)
|
||||
|
||||
|
||||
def transit_parts(assets: Path, colors: dict) -> dict[str, Path]:
|
||||
"""The install transit's monitor, portal and headset: the logo's own shapes, whole, in a theme's colours.
|
||||
colors: line (strokes), body (inside the outlines, the logo's tile), screen (the monitor's screen), lens (the
|
||||
visor's lenses), near/far (the portal rim's PC and Frame sides), hole (the portal's inside). Written once per
|
||||
colour set; returns {"monitor", "portal", "portal_back", "portal_front", "headset"} → file (the three portal
|
||||
pictures share one viewBox, TRANSIT_SIZES["portal"]; the ring sits in its top-left PORTAL_RING box)."""
|
||||
c = {k: str(v).upper() for k, v in colors.items()}
|
||||
portal = ("near", "far", "hole")
|
||||
out = {}
|
||||
for name, svg, keys in (("monitor", _MONITOR, ("line", "body", "screen")),
|
||||
("headset", _HEADSET, ("line", "body", "lens")),
|
||||
("portal", _PORTAL, portal), ("portal_back", _PORTAL_BACK, portal),
|
||||
("portal_front", _PORTAL_FRONT, portal)):
|
||||
tag = "-".join(c[k].lstrip("#") for k in keys)
|
||||
dest = assets / FOLDER / f"transit{TRANSIT_REV}-{name}-{tag}.svg" # REV: the drawing changed
|
||||
if not dest.is_file():
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(svg.format(**{k: c[k] for k in keys}), encoding="utf-8")
|
||||
out[name] = dest
|
||||
return out
|
||||
|
||||
|
||||
def solid(name: str) -> str:
|
||||
"""The filled variant of a glyph for solid (accent-filled) buttons, where a thin outline in the dark ON_ACCENT
|
||||
colour faded into the fill: "fp:frame" → "fp:frame-solid" (lenses cut out, so the accent shows through as in the
|
||||
logo). Glyphs without one stay as they are."""
|
||||
if not is_glyph(name):
|
||||
return name
|
||||
filled = f"{name}-solid"
|
||||
return filled if (SOURCE / "glyphs" / f"{filled.removeprefix(PREFIX)}.svg").is_file() else name
|
||||
|
||||
|
||||
def path(name: str, assets: Path) -> Path:
|
||||
"""The installed file for a glyph ("fp:frame") or a logo file name ("logo")."""
|
||||
return assets / FOLDER / f"{name.removeprefix(PREFIX)}.svg"
|
||||
@@ -25,11 +25,11 @@ HELP: dict[str, str] = _Translated({
|
||||
"update_ready": "The copy on your Frame differs from what FramePort would install now (the recipe or your game "
|
||||
"files changed). Update to install the new build; saves are kept.",
|
||||
"check_exe": "This game's folder has several programs and FramePort isn't sure which one starts the game. Open the "
|
||||
"game (or right-click → Change executable) to pick it.",
|
||||
"game and use … → Change program… to pick it.",
|
||||
"platform_quest": "A Meta Quest game (APK). It's rebuilt for the Frame and runs in Lepton, Valve's Android "
|
||||
"container.",
|
||||
"platform_windows": "A Windows game without VR, added with \"Add one game folder…\". On the Frame, Proton runs it "
|
||||
"as a window (like Steam's own Windows games); it's in the Frame's Steam library.",
|
||||
"platform_windows": "A Windows game without VR, added with \"Add a PC game folder…\". On the Frame, Proton "
|
||||
"runs it as a window (like Steam's own Windows games); it's in the Frame's Steam library.",
|
||||
"platform_pcvr": "A Windows PC VR game (OpenXR, SteamVR or Oculus). It runs on this PC with SteamVR, or on the "
|
||||
"Frame with Proton. Oculus-only games also need Revive (Oculus → OpenXR).",
|
||||
"platform_android": "An ordinary Android app or game (no VR). It's installed unchanged and runs in Lepton, Valve's "
|
||||
@@ -39,8 +39,9 @@ HELP: dict[str, str] = _Translated({
|
||||
"platform_linux": "A native Linux program built for arm64 (aarch64), like the Frame's own CPU. It's installed "
|
||||
"unchanged and runs directly on SteamOS (no Android container, no Proton), started from the "
|
||||
"Frame's Steam library. VR apps use the Frame's OpenXR runtime.",
|
||||
"linux_app": "An AppImage, a folder or a .zip/.tar archive with a Linux program built for arm64 (aarch64). x86_64 "
|
||||
"builds can't run on the Frame. The app must bring the libraries SteamOS doesn't have.",
|
||||
"linux_app": "An AppImage, a folder or a .zip/.tar archive with a Linux program, best built for arm64 (aarch64). "
|
||||
"x86_64 builds run through FEX, Valve's x86 translator, but slower. The app must bring the "
|
||||
"libraries SteamOS doesn't have.",
|
||||
"appimage": "An AppImage is a Linux app packed into one file. FramePort unpacks it on the Frame once, so it starts "
|
||||
"without FUSE.",
|
||||
"select": "Pick several games and install them in one go. FramePort asks every question first, then works through "
|
||||
@@ -69,7 +70,7 @@ HELP: dict[str, str] = _Translated({
|
||||
"FrameDrop sideloader). FramePort reads the same links: it shows what the link offers, asks, "
|
||||
"downloads it, adds it to your library and installs it on the Frame. Only https links to "
|
||||
"public servers are used. Windows and Linux open these links in FramePort; on macOS, paste the "
|
||||
"link into Add games → Install from a link….",
|
||||
"link into Add games → Add from a link….",
|
||||
"linux_x86": "The Frame's CPU is arm64. Programs built for x86_64 PCs run through FEX, Valve's x86 translator, "
|
||||
"with the x86 libraries SteamOS ships for it (glibc, Mesa) - the way Steam on the Frame runs x86 "
|
||||
"Linux games. That works for many programs but is slower: use an arm64 build when there is one.",
|
||||
@@ -96,23 +97,27 @@ HELP: dict[str, str] = _Translated({
|
||||
"starts.",
|
||||
"cat_device": "Files and environment variables placed next to the game on the Frame.",
|
||||
# ---- Frame
|
||||
"developer_mode": "Developer Mode (on the Frame: Settings → System → Developer) lets FramePort find the Frame on "
|
||||
"your network and connect to it over SSH. The first-time setup command turns it on for you.",
|
||||
"developer_mode": "Developer Mode (on the Frame: Settings → System → Enable Developer Mode) lets FramePort find "
|
||||
"the Frame on your network and connect to it over SSH. The first-time setup command turns it on "
|
||||
"for you. With Developer Mode on you can also pair without the setup command: on the Frame open "
|
||||
"Settings → Developer → Pair new host, click Connect there and approve FramePort. That way needs "
|
||||
"no connection from the Frame into this PC.",
|
||||
"first_time_setup": "The command fetches a small setup script from this app over your local network. It turns on "
|
||||
"Developer Mode (which includes SSH), lets this app's key in and installs Lepton if needed. "
|
||||
"No password needed.",
|
||||
"Turning on Developer Mode closes the Frame's desktop; the setup finishes on its own and "
|
||||
"FramePort connects by itself. No password needed.",
|
||||
"password": "The Frame's desktop password, only needed the first time so FramePort can add its own key. After "
|
||||
"that it connects with the key.",
|
||||
"lepton": "Lepton is Valve's Android container on the Frame. Quest games run inside it, one container per game. "
|
||||
"It needs Developer Mode.",
|
||||
"proton": "Proton is Valve's Windows compatibility layer. On the Frame it runs PC VR games. "
|
||||
"Its ARM64 build isn't installed by default; FramePort can install it (Steam restarts once).",
|
||||
"Its arm64 build isn't installed by default; FramePort can install it (Steam restarts once).",
|
||||
"openxr": "The VR runtime games talk to. On the Frame that's SteamVR.",
|
||||
"kernel_keys": "Every game start on the Frame used to leak one kernel key, and after about 200 launches every game "
|
||||
"fails to start. FramePort switches that leak off, but keys already used only come back after a "
|
||||
"restart of the Frame.",
|
||||
"ui_scale": "Size of text and layout. Automatic follows Windows' display scaling halfway "
|
||||
"(150 % in Windows → 125 %) when FramePort runs under WSL, where the window doesn't get it from "
|
||||
"(150% in Windows → 125%) when FramePort runs under WSL, where the window doesn't get it from "
|
||||
"Windows itself.",
|
||||
"app_updates": "FramePort checks GitHub for a new release every few hours and shows it in the sidebar and the "
|
||||
"Library. \"Update now\" downloads it, checks its checksum (and on Windows its signature), closes "
|
||||
@@ -125,8 +130,17 @@ HELP: dict[str, str] = _Translated({
|
||||
"files": "Browse and manage files on the Frame (Files tab): upload from this PC, download, rename, delete. "
|
||||
"Videos, Downloads and Documents are shared by every Quest game (/sdcard/Movies, /sdcard/Download, "
|
||||
"/sdcard/Documents); each installed game also has its own storage (its /sdcard). Apps find files "
|
||||
"by browsing folders. Video players that list only their own folder (e.g. 4XVR's Internal "
|
||||
"by browsing folders. Video players that list only their own folder (for example 4XVR's Internal "
|
||||
"Storage = 4XPlayer): upload into that folder in the game's storage.",
|
||||
"live_view": "The picture plays right in this window where FramePort can (Windows and macOS), else in an mpv "
|
||||
"window if mpv is installed, else in your web browser — Play in picks one, and Open in browser "
|
||||
"always works too (full screen, Sound on in the player). "
|
||||
"It shows the headset's view with its sound whatever is running: "
|
||||
"Steam's menus, SteamVR or a game; while the headset sleeps the picture is black and updates about "
|
||||
"once a second. The Frame's hardware video encoder does the work (if it isn't available, the "
|
||||
"processor does, which costs a game more): stop the stream when you're done.",
|
||||
"type_on_frame": "This PC's keyboard works as a keyboard on your Frame while this tab is open. In the headset, "
|
||||
"select a text field (in a game or app, in Steam or on the desktop), then type here.",
|
||||
"free_space": "Deletes the rollback copies kept from each game's previous install and leftover uploads. The "
|
||||
"games and saves stay.",
|
||||
"install_drive": "Where new games go on the Frame: its internal storage or another drive, such as a microSD card "
|
||||
@@ -160,9 +174,9 @@ HELP: dict[str, str] = _Translated({
|
||||
"no GitHub token and no game files are involved.",
|
||||
"diag_bundle": "A zip with FramePort's logs, the game's recipe and analysis, launch-test logs and the Frame's "
|
||||
"runtime details — enough to debug without the game files. IP addresses, host and user names, "
|
||||
"home folders and Steam ids are replaced by placeholders. Attach it to a GitHub issue.",
|
||||
"home folders and Steam IDs are replaced by placeholders. Attach it to a GitHub issue.",
|
||||
"monitor_gpu": "How much of the time the Frame's graphics chip was busy, added up from every program that draws "
|
||||
"(the game, SteamVR's compositor, Steam). Near 100 % the game can't keep its frame rate.",
|
||||
"(the game, SteamVR's compositor, Steam). Near 100% the game can't keep its frame rate.",
|
||||
"monitor_pressure": "Memory in use by everything on the Frame. \"Waiting\" is the share of time programs had to "
|
||||
"wait for memory in the last 10 s: when it climbs, the Frame is running out and may freeze or "
|
||||
"close a game.",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 20 7.5v9L12 21l-8-4.5v-9z"/><path d="m4 7.5 8 4.5 8-4.5M12 12v9"/></svg>
|
||||
|
After Width: | Height: | Size: 264 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#FFFFFF" fill-rule="evenodd" d="M2 9.5A4.5 4.5 0 0 1 6.5 5h11A4.5 4.5 0 0 1 22 9.5v4a4.5 4.5 0 0 1-4.5 4.5h-2.2a3 3 0 0 1-2.55-1.42L12 15.3l-.75 1.28A3 3 0 0 1 8.7 18H6.5A4.5 4.5 0 0 1 2 13.5zM8.5 9.2a2.4 2.2 0 1 0 0 4.4a2.4 2.2 0 1 0 0-4.4zM15.5 9.2a2.4 2.2 0 1 0 0 4.4a2.4 2.2 0 1 0 0-4.4z"/></svg>
|
||||
|
After Width: | Height: | Size: 396 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9.5A3.5 3.5 0 0 1 6.5 6h11A3.5 3.5 0 0 1 21 9.5v4a3.5 3.5 0 0 1-3.5 3.5h-2.2a2 2 0 0 1-1.7-.95l-.75-1.2a1 1 0 0 0-1.7 0l-.75 1.2A2 2 0 0 1 8.7 17H6.5A3.5 3.5 0 0 1 3 13.5z"/></svg>
|
||||
|
After Width: | Height: | Size: 369 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="19" height="12" rx="2.5"/><path d="M6.5 10h.01M10 10h.01M13.5 10h.01M17.5 10h.01M8 14.5h8"/></svg>
|
||||
|
After Width: | Height: | Size: 302 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 9a14 14 0 0 1 19 0M5.6 12.4a9.5 9.5 0 0 1 12.8 0M8.7 15.8a5 5 0 0 1 6.6 0"/><path d="M12 19.5h.01"/></svg>
|
||||
|
After Width: | Height: | Size: 297 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="2"/><path d="M8.2 8.2a5.4 5.4 0 0 0 0 7.6M15.8 8.2a5.4 5.4 0 0 1 0 7.6M5.3 5.3a9.5 9.5 0 0 0 0 13.4M18.7 5.3a9.5 9.5 0 0 1 0 13.4"/></svg>
|
||||
|
After Width: | Height: | Size: 342 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.6" y="8.2" width="18.8" height="7.6" rx="3.8" transform="rotate(-45 12 12)"/><path d="M10.6 10.6h.01M13.4 10.6h.01M10.6 13.4h.01M13.4 13.4h.01"/></svg>
|
||||
|
After Width: | Height: | Size: 339 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="12" rx="2.5"/><path d="M12 16v4M8 20h8"/></svg>
|
||||
|
After Width: | Height: | Size: 261 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="7" cy="12" rx="4" ry="9.2" transform="rotate(15 7 12)"/><path d="M13.5 12H21M18 9l3 3-3 3"/></svg>
|
||||
|
After Width: | Height: | Size: 288 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 5.5A1.5 1.5 0 0 1 6.5 4H19v16H6.5A1.5 1.5 0 0 1 5 18.5z"/><path d="M5 17.5A1.5 1.5 0 0 1 6.5 16H19"/><path d="m9 9.5 2 2 3.5-3.5"/></svg>
|
||||
|
After Width: | Height: | Size: 326 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 8.5V6.5A2.5 2.5 0 0 1 6.5 4h2M15.5 4h2A2.5 2.5 0 0 1 20 6.5v2M20 15.5v2a2.5 2.5 0 0 1-2.5 2.5h-2M8.5 20h-2A2.5 2.5 0 0 1 4 17.5v-2"/><circle cx="12" cy="12" r="3.2"/></svg>
|
||||
|
After Width: | Height: | Size: 361 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.5 10A8 8 0 0 0 5.6 7.2L4 9"/><path d="M4 4.5V9h4.5"/><path d="M4.5 14a8 8 0 0 0 13.9 2.8L20 15"/><path d="M20 19.5V15h-4.5"/></svg>
|
||||
|
After Width: | Height: | Size: 321 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 3h6M10 3v6l-5 8.9A2 2 0 0 0 6.75 21h10.5A2 2 0 0 0 19 17.9L14 9V3"/><path d="M7.4 15h9.2"/></svg>
|
||||
|
After Width: | Height: | Size: 286 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><defs><linearGradient id="fp0" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".18"/><stop offset=".5" stop-color="#3AA8FF" stop-opacity="0"/><stop offset=".5" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".18"/></linearGradient><linearGradient id="fp1" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0"><stop offset=".3" stop-color="#3AA8FF"/><stop offset=".7" stop-color="#FF8A1F"/></linearGradient><clipPath id="fp2"><polygon points="-30,-30 49.14502116644019,-30 8.854978833559809,94 -30,94"/></clipPath><clipPath id="fp3"><polygon points="55.14502116644019,-30 94,-30 94,94 14.854978833559809,94"/></clipPath></defs><rect width="64" height="64" rx="15" fill="#101218"/><g clip-path="url(#fp2)"><g transform="translate(0 0)"><path d="M34 15H9a3 3 0 0 0-3 3v20a3 3 0 0 0 3 3h25z" fill="#ECEDF3" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><rect x="10.5" y="19.5" width="24" height="17" rx="1" fill="#3AA8FF" fill-opacity="1"/><path d="M18 41v6M11 47h14" stroke="#ECEDF3" stroke-width="3" stroke-linecap="round"/></g></g><g clip-path="url(#fp3)"><path d="M56.5 31.5H58.5" stroke="#ECEDF3" stroke-width="3.4" stroke-linecap="round"/><path d="M22 21h27a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7a3 3 0 0 1-2.6 1.5H22z" fill="#ECEDF3" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/><ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/></g><g transform="rotate(18 32 32)"><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="#08090C" stroke="#08090C" stroke-width="5.8"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="none" fill-opacity="0.14" stroke="url(#fp1)" stroke-width="3.4"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><defs><linearGradient id="fp0" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#3AA8FF" stop-opacity=".18"/><stop offset=".5" stop-color="#3AA8FF" stop-opacity="0"/><stop offset=".5" stop-color="#FF8A1F" stop-opacity="0"/><stop offset="1" stop-color="#FF8A1F" stop-opacity=".18"/></linearGradient><linearGradient id="fp1" gradientUnits="userSpaceOnUse" x1="26" y1="0" x2="38" y2="0"><stop offset=".3" stop-color="#3AA8FF"/><stop offset=".7" stop-color="#FF8A1F"/></linearGradient><clipPath id="fp2"><polygon points="-30,-30 49.14502116644019,-30 8.854978833559809,94 -30,94"/></clipPath><clipPath id="fp3"><polygon points="55.14502116644019,-30 94,-30 94,94 14.854978833559809,94"/></clipPath></defs><rect width="64" height="64" rx="15" fill="#101218"/><rect width="64" height="64" rx="15" fill="url(#fp0)"/><g clip-path="url(#fp2)"><g transform="translate(0 0)"><path d="M34 15H9a3 3 0 0 0-3 3v20a3 3 0 0 0 3 3h25z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><rect x="10.5" y="19.5" width="24" height="17" rx="1" fill="#3AA8FF" fill-opacity="0.35"/><path d="M18 41v6M11 47h14" stroke="#ECEDF3" stroke-width="3" stroke-linecap="round"/></g></g><g clip-path="url(#fp3)"><path d="M56.5 31.5H58.5" stroke="#ECEDF3" stroke-width="3.4" stroke-linecap="round"/><path d="M22 21h27a8 8 0 0 1 8 8v5a8 8 0 0 1-8 8H48.65a3 3 0 0 1-2.6-1.5l-1-1.7a.9.9 0 0 0-1.6 0l-1 1.7a3 3 0 0 1-2.6 1.5H22z" fill="#101218" stroke="#ECEDF3" stroke-width="3" stroke-linejoin="round"/><ellipse cx="39.5" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/><ellipse cx="49" cy="30.5" rx="4.2" ry="3.8" fill="#FF8A1F"/></g><g transform="rotate(18 32 32)"><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="#08090C" stroke="#08090C" stroke-width="5.8"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="none" stroke="url(#fp1)" stroke-opacity=".25" stroke-width="6.46"/><ellipse cx="32" cy="32" rx="4.5" ry="22" fill="url(#fp1)" fill-opacity="0.14" stroke="url(#fp1)" stroke-width="3.4"/></g></svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,135 @@
|
||||
"""Where the live view plays: inside FramePort's window, in an mpv window, or in the web browser.
|
||||
|
||||
- "app": flet-video's Video control (media_kit = libmpv) plays the relay's /stream.mp4 in the Live view. Windows and
|
||||
macOS (bundles and source runs: Flet's desktop clients there contain it). Not in Linux bundles: the plugin links
|
||||
libmpv.so.1, and a bundle built with it wouldn't start on systems without that exact library (pyproject installs
|
||||
flet-video only off Linux); a Linux source run can use it with Flet's "full" desktop client + libmpv.
|
||||
- "mpv": the mpv program, when installed, in its own low-latency window (Linux's way to a native player).
|
||||
- "browser": the MSE player page (install/live_player.py) in the default browser — always available, and where the
|
||||
others fall back to when they can't start or fail.
|
||||
The pure parts (availability, order, mpv settings) are unit-tested; the Video control is built only when available.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes.util
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
MODES = ("app", "mpv", "browser")
|
||||
SETTING = "ui.live_player" # "auto" (default) or one of MODES: the user's pick in the Live view
|
||||
|
||||
# mpv's low-latency profile, as properties (media_kit sets them before opening; `profile` itself is applied by the
|
||||
# command line, not reliably as a property): a live stream should show the newest picture, not buffer
|
||||
LOW_LATENCY = {
|
||||
"cache": "no",
|
||||
"cache-pause": "no",
|
||||
"audio-buffer": 0.05,
|
||||
"vd-lavc-threads": 1,
|
||||
"demuxer-lavf-o-add": "fflags=+nobuffer",
|
||||
"demuxer-lavf-probe-info": "nostreams",
|
||||
"demuxer-lavf-analyzeduration": 0.1,
|
||||
"video-sync": "audio",
|
||||
"interpolation": "no",
|
||||
"video-latency-hacks": "yes",
|
||||
"stream-buffer-size": "4k",
|
||||
}
|
||||
|
||||
|
||||
def stream_url(page_url: str) -> str:
|
||||
"""The relay's raw fragmented MP4 (what native players open) next to its player page."""
|
||||
return page_url.rstrip("/") + "/stream.mp4"
|
||||
|
||||
|
||||
def embedded_available(web: bool = False, platform: str | None = None, env: dict | None = None,
|
||||
has_module: Callable[[str], bool] | None = None,
|
||||
find_library: Callable[[str], str | None] | None = None) -> bool:
|
||||
"""Whether the Video control can play inside the window here (arguments: for tests)."""
|
||||
platform = platform or sys.platform
|
||||
env = os.environ if env is None else env
|
||||
has_module = has_module or (lambda name: importlib.util.find_spec(name) is not None)
|
||||
find_library = find_library or ctypes.util.find_library
|
||||
if web or env.get("FRAMEPORT_NO_EMBEDDED_PLAYER") or not has_module("flet_video"):
|
||||
return False
|
||||
if platform.startswith("linux"):
|
||||
# Flet's default Linux client is "light" (no video plugin): an unknown control would show instead
|
||||
return env.get("FLET_DESKTOP_FLAVOR") == "full" and bool(find_library("mpv"))
|
||||
return platform in ("win32", "darwin")
|
||||
|
||||
|
||||
def find_mpv(platform: str | None = None, which: Callable[[str], str | None] = shutil.which,
|
||||
exists: Callable[[str], bool] = os.path.isfile) -> str | None:
|
||||
"""The mpv program, if installed (macOS apps don't get Homebrew's folders on PATH: looked at directly)."""
|
||||
platform = platform or sys.platform
|
||||
found = which("mpv") or (which("mpv.exe") if platform == "win32" else None)
|
||||
if found:
|
||||
return found
|
||||
if platform == "darwin":
|
||||
for p in ("/opt/homebrew/bin/mpv", "/usr/local/bin/mpv", "/Applications/mpv.app/Contents/MacOS/mpv"):
|
||||
if exists(p):
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def order(choice: str, embedded: bool, mpv: bool) -> list[str]:
|
||||
"""The players to try, best first: the user's pick (if available here) first, then app → mpv → browser. The
|
||||
browser is always last, so a failing player ends up there."""
|
||||
avail = [m for m, ok in (("app", embedded), ("mpv", mpv), ("browser", True)) if ok]
|
||||
if choice in avail:
|
||||
avail.remove(choice)
|
||||
avail.insert(0, choice)
|
||||
return avail
|
||||
|
||||
|
||||
def mpv_args(exe: str, url: str, title: str) -> list[str]:
|
||||
return [exe, "--profile=low-latency", "--cache=no", "--force-window=immediate", f"--title={title}",
|
||||
"--keep-open=no", "--autofit=1280x720", "--no-terminal", url]
|
||||
|
||||
|
||||
class MpvWindow:
|
||||
"""The stream in an mpv window. `start()` raises when mpv quits at once (it couldn't open the stream)."""
|
||||
|
||||
def __init__(self, exe: str, url: str, title: str):
|
||||
self.exe, self.url, self.title = exe, url, title
|
||||
self.proc: subprocess.Popen | None = None
|
||||
|
||||
def start(self, settle: float = 2.5) -> MpvWindow:
|
||||
flags = 0x08000000 if sys.platform == "win32" else 0 # CREATE_NO_WINDOW: no console next to mpv's window
|
||||
self.proc = subprocess.Popen(mpv_args(self.exe, self.url, self.title), stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, creationflags=flags)
|
||||
deadline = time.time() + settle
|
||||
while time.time() < deadline:
|
||||
code = self.proc.poll()
|
||||
if code is not None:
|
||||
err = (self.proc.stderr.read() or b"").decode(errors="replace").strip() if self.proc.stderr else ""
|
||||
raise RuntimeError(f"mpv exited ({code}){': ' + err.splitlines()[-1] if err else ''}")
|
||||
time.sleep(0.1)
|
||||
return self
|
||||
|
||||
@property
|
||||
def alive(self) -> bool:
|
||||
return self.proc is not None and self.proc.poll() is None
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.alive:
|
||||
self.proc.terminate()
|
||||
try:
|
||||
self.proc.wait(3)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
|
||||
|
||||
def video_control(url: str, on_error: Callable, on_complete: Callable, muted: bool = False):
|
||||
"""The Video control for the stream (only when embedded_available()): no built-in controls (the Live view's bar
|
||||
has Stop, Sound and Open in browser), black around the picture, low-latency mpv settings."""
|
||||
import flet as ft
|
||||
import flet_video as ftv
|
||||
|
||||
return ftv.Video(playlist=[ftv.VideoMedia(url)], autoplay=True, controls=None, expand=True,
|
||||
fill_color=ft.Colors.BLACK, muted=muted, wakelock=False, title="FramePort live view",
|
||||
configuration=ftv.VideoConfiguration(mpv_properties=dict(LOW_LATENCY)),
|
||||
on_error=on_error, on_complete=on_complete)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""A game's menu (Library right-click, game page "…") as sections: a pure builder, no controls and no app.
|
||||
|
||||
Entries: (label, icon, handler) | Header(label) | None (divider). C.menu_items renders them (headers as small caps,
|
||||
compact rows). Flet 1.0's PopupMenuItem can't nest, so groups get a header instead of a submenu."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import NamedTuple
|
||||
|
||||
import flet as ft
|
||||
|
||||
from ..i18n import tr
|
||||
from . import glyphs as G
|
||||
|
||||
|
||||
class Header(NamedTuple):
|
||||
"""A group heading inside a menu (not clickable)."""
|
||||
label: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class MenuState:
|
||||
"""What the menu depends on, gathered by the app (FramePortApp.game_actions)."""
|
||||
quick: bool = True # True: Library right-click (quick_menu); False: the game page's full "…" menu
|
||||
connected: bool = False # a Frame is connected
|
||||
on_frame: bool = False # installed on the Frame (current or outdated)
|
||||
on_pc: bool = False # a PC VR game installed on this PC
|
||||
job: bool = False # a job runs (or waits) for this game
|
||||
plays: list = field(default_factory=list) # where it can be started now [(label, icon, handler)]
|
||||
installs: list = field(default_factory=list) # install/update/reinstall options [(label, icon, handler)]
|
||||
settings: bool = False # has Game settings
|
||||
programs: bool = False # "Change program…" makes sense
|
||||
selectable: bool = False # the Library view exists (Select)
|
||||
media_button: bool = False # the game page shows "Add videos" already
|
||||
movable: bool = False # the Frame knows which drive it's on (agent v63+, microSD): Move to…
|
||||
|
||||
|
||||
def menu_sections(g: dict, st: MenuState, act: Callable[[str], Callable]) -> list:
|
||||
"""The game's menu. `act(key)` gives the handler for an action key (tests pass `lambda k: k`)."""
|
||||
rift = g.get("kind") == "rift"
|
||||
linux = g.get("kind") == "linux" # installed as it is: nothing to analyze, convert or share as a recipe
|
||||
if st.quick:
|
||||
return quick_menu(st, act)
|
||||
job = st.job
|
||||
top: list = []
|
||||
if st.settings and not job:
|
||||
top.append((tr("Game settings…"), ft.Icons.TUNE_ROUNDED, act("settings")))
|
||||
if st.connected:
|
||||
top.append((tr("Screenshots"), G.SHOT, act("screenshots")))
|
||||
if st.on_frame and not rift and not linux and not job and not st.media_button:
|
||||
top.append((tr("Add videos and files"), ft.Icons.VIDEO_LIBRARY_OUTLINED, act("files")))
|
||||
if st.movable and st.on_frame and not job:
|
||||
top.append((tr("Move to…"), ft.Icons.DRIVE_FILE_MOVE_ROUNDED, act("move")))
|
||||
|
||||
artwork = [(tr("Find artwork…"), ft.Icons.IMAGE_SEARCH_ROUNDED, act("find_art")),
|
||||
(tr("Use your own artwork…"), ft.Icons.UPLOAD_FILE_OUTLINED, act("custom_art"))]
|
||||
if not job and st.on_frame:
|
||||
artwork.append((tr("Update Steam art on Frame"), ft.Icons.WALLPAPER_ROUNDED, act("steam_art")))
|
||||
|
||||
recipe = [] if linux else [
|
||||
(tr("Reset to suggested recipe…"), ft.Icons.SETTINGS_BACKUP_RESTORE_ROUNDED, act("reset_recipe")),
|
||||
(tr("Save as known-good recipe"), G.RECIPE, act("save_recipe")),
|
||||
(tr("Share working recipe…"), ft.Icons.SHARE_ROUNDED, act("share"))]
|
||||
|
||||
trouble: list = [] # launch tests and uninstalls are on the page's "Where it's installed" cards
|
||||
if not job and not rift and not linux:
|
||||
trouble.append((tr("Analyze again"), ft.Icons.MANAGE_SEARCH_ROUNDED, act("analyze")))
|
||||
if not job and not linux:
|
||||
trouble.append((tr("Check game files") if rift else tr("Rebuild only (no install)"), G.PORT, act("build")))
|
||||
if st.programs:
|
||||
trouble.append((tr("Change program…"), ft.Icons.SWAP_HORIZ_ROUNDED, act("program")))
|
||||
trouble += [(tr("Refresh store details"), ft.Icons.PUBLISHED_WITH_CHANGES_ROUNDED, act("details")),
|
||||
(tr("Collect logs"), ft.Icons.FOLDER_ZIP_OUTLINED, act("logs")),
|
||||
(tr("Report a problem…"), ft.Icons.BUG_REPORT_OUTLINED, act("report"))]
|
||||
|
||||
danger = [(tr("Remove from library…"), ft.Icons.REMOVE_CIRCLE_OUTLINE_ROUNDED, act("remove"))]
|
||||
|
||||
out: list = list(top)
|
||||
for head, items in ((tr("Artwork"), artwork), (tr("Recipe"), recipe), (tr("Troubleshoot"), trouble)):
|
||||
if items:
|
||||
out += [None, Header(head), *items]
|
||||
return out + [None, *danger]
|
||||
|
||||
|
||||
def quick_menu(st: MenuState, act: Callable[[str], Callable]) -> list:
|
||||
"""The Library's right-click menu: only the key actions, no section headers. "More actions…" opens the game
|
||||
page's full "…" menu (menu_sections with quick=False)."""
|
||||
opened = (tr("Open game page"), ft.Icons.OPEN_IN_NEW_ROUNDED, act("open"))
|
||||
if st.job:
|
||||
return [(tr("Show progress"), ft.Icons.SYNC_ROUNDED, act("progress")),
|
||||
(tr("Cancel"), ft.Icons.CLOSE_ROUNDED, act("cancel")), opened]
|
||||
out: list = [*st.plays[:1], opened]
|
||||
if st.selectable:
|
||||
out.append((tr("Select"), ft.Icons.CHECKLIST_ROUNDED, act("select")))
|
||||
out += st.installs[:1]
|
||||
if st.settings:
|
||||
out.append((tr("Game settings…"), ft.Icons.TUNE_ROUNDED, act("settings")))
|
||||
out += [None, (tr("More actions…"), ft.Icons.MORE_HORIZ_ROUNDED, act("more")), None]
|
||||
if st.on_frame:
|
||||
out.append((tr("Uninstall from Frame…"), ft.Icons.DELETE_OUTLINE_ROUNDED, act("uninstall_frame")))
|
||||
if st.on_pc:
|
||||
out.append((tr("Uninstall from this PC…"), ft.Icons.DELETE_OUTLINE_ROUNDED, act("uninstall_pc")))
|
||||
return out + [(tr("Remove from library…"), ft.Icons.REMOVE_CIRCLE_OUTLINE_ROUNDED, act("remove"))]
|
||||
|
||||
|
||||
def process_menu(p: dict, act: Callable[[str], Callable]) -> list:
|
||||
"""Monitor's right-click menu for a process row or a group row (`p` = the row). Harmless items first, then
|
||||
End…/Force quit…, End game… last; a process SteamOS protects shows that instead of the End items."""
|
||||
out: list = []
|
||||
if p.get("kind") == "group":
|
||||
n = p.get("count", 0)
|
||||
out += [(tr("Hide its processes") if p.get("expanded") else tr("Show its processes"),
|
||||
ft.Icons.UNFOLD_MORE_ROUNDED, act("toggle")),
|
||||
(tr("Copy name"), ft.Icons.CONTENT_COPY_ROUNDED, act("copy_name")), None]
|
||||
if p.get("locked"):
|
||||
out.append((tr("Protected by SteamOS"), ft.Icons.LOCK_OUTLINE_ROUNDED, None))
|
||||
else:
|
||||
out += [(tr("End all {n}…").format(n=n), ft.Icons.LOGOUT_ROUNDED, act("term")),
|
||||
(tr("Force quit all {n}…").format(n=n), ft.Icons.DANGEROUS_OUTLINED, act("kill"))]
|
||||
else:
|
||||
out += [(tr("Copy name"), ft.Icons.CONTENT_COPY_ROUNDED, act("copy_name")),
|
||||
(tr("Copy PID {pid}").format(pid=p.get("pid")), ft.Icons.CONTENT_COPY_ROUNDED, act("copy_pid")), None]
|
||||
if p.get("locked"):
|
||||
out.append((tr("Protected by SteamOS"), ft.Icons.LOCK_OUTLINE_ROUNDED, None))
|
||||
else:
|
||||
out += [(tr("End…"), ft.Icons.LOGOUT_ROUNDED, act("term")),
|
||||
(tr("Force quit…"), ft.Icons.DANGEROUS_OUTLINED, act("kill"))]
|
||||
if p.get("game"):
|
||||
out += [None, (tr("End game…"), ft.Icons.STOP_CIRCLE_OUTLINED, act("end_game"))]
|
||||
return out
|
||||
@@ -1,40 +1,223 @@
|
||||
"""Design tokens for the FramePort GUI (dark only): one accent, a neutral surface ramp, semantic state colours, an
|
||||
8-pt spacing scale and a small type scale. Every view takes its colours and sizes from here."""
|
||||
"""Design tokens for the FramePort GUI (dark only, the owner's choice): colour themes (an accent, a neutral surface
|
||||
ramp, semantic state colours), an 8-pt spacing scale and a small type scale. Every view takes its colours and sizes
|
||||
from here, reading them as `T.NAME` when it builds (never as a default argument or a module-level constant: those keep
|
||||
the colours of the theme that was active at import; module-level maps re-fill themselves through on_change()).
|
||||
|
||||
Themes: the built-ins below plus theme files the user installs (<data>/themes/*.json, docs/THEMES.md)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import flet as ft
|
||||
|
||||
# surfaces (darkest → lightest)
|
||||
BG = "#0E0F13" # window background
|
||||
SIDEBAR = "#121319"
|
||||
SURFACE = "#171920" # cards
|
||||
SURFACE_2 = "#1E2029" # raised / hover
|
||||
SURFACE_3 = "#262935" # inputs, chips
|
||||
BORDER = "#2C2F3B"
|
||||
BORDER_STRONG = "#3A3E4D"
|
||||
# Colour tokens of a theme:
|
||||
# surfaces: BG window, SIDEBAR, SURFACE cards, SURFACE_2 raised/hover, SURFACE_3 inputs/chips, BORDER(_STRONG)
|
||||
# text: TEXT, TEXT_2 secondary, TEXT_3 meta/disabled
|
||||
# ACCENT (+ ACCENT_SOFT tint, ON_ACCENT text on it): the main action and the current selection
|
||||
# SECONDARY (+ SECONDARY_SOFT): secondary actions, progress, switch tracks (with "dual" also the two-colour touches)
|
||||
# states OK/WARN/ERROR/INFO, PC = PC VR / "on this PC"
|
||||
TOKENS = ("BG", "SIDEBAR", "SURFACE", "SURFACE_2", "SURFACE_3", "BORDER", "BORDER_STRONG", "TEXT", "TEXT_2", "TEXT_3",
|
||||
"ACCENT", "ACCENT_SOFT", "ON_ACCENT", "SECONDARY", "SECONDARY_SOFT", "OK", "WARN", "ERROR", "INFO", "PC")
|
||||
|
||||
# text
|
||||
TEXT = "#ECEDF3"
|
||||
TEXT_2 = "#A9ADBD" # secondary
|
||||
TEXT_3 = "#737889" # meta / disabled
|
||||
# "portal" follows the logo: orange (the Frame's side) = actions and selection, blue (the PC's side) = secondary
|
||||
# actions, progress and the PC; "dual" adds the blue→orange touches (sidebar edge, wordmark, selected tab).
|
||||
# Status colours are picked so a warning never reads as the accent.
|
||||
_PORTAL = {
|
||||
"BG": "#0D0E12", "SIDEBAR": "#111217", "SURFACE": "#16181E", "SURFACE_2": "#1D1F27", "SURFACE_3": "#252832",
|
||||
"BORDER": "#2A2D37", "BORDER_STRONG": "#393D49",
|
||||
"TEXT": "#EDEEF2", "TEXT_2": "#A7ABB7", "TEXT_3": "#717583",
|
||||
"ACCENT": "#FF8A1F", "ACCENT_SOFT": "#3A2512", "ON_ACCENT": "#160C03",
|
||||
"SECONDARY": "#3AA8FF", "SECONDARY_SOFT": "#0F2A40",
|
||||
# INFO is a cyan of its own: next to PC (the portal blue) it tells data series apart (Monitor: Steam vs
|
||||
# SteamVR processes, CPU vs memory) and stays clear of OK's green
|
||||
"OK": "#3DD68C", "WARN": "#F2C94C", "ERROR": "#FF6166", "INFO": "#5CD0E6", "PC": "#3AA8FF",
|
||||
}
|
||||
BUILTIN: dict[str, dict] = {
|
||||
"portal": {"name": "Portal", "dual": True, "colors": _PORTAL},
|
||||
"portal_oled": {"name": "Portal (OLED)", "dual": True, "colors": {
|
||||
**_PORTAL, # true black behind everything; cards just lift off it
|
||||
"BG": "#000000", "SIDEBAR": "#000000", "SURFACE": "#0A0A0D", "SURFACE_2": "#121317", "SURFACE_3": "#1A1B21",
|
||||
"BORDER": "#1E1F26", "BORDER_STRONG": "#2B2D36", "ACCENT_SOFT": "#2B1A0A", "SECONDARY_SOFT": "#0A1F31"}},
|
||||
"original": {"name": "Original", "dual": False, "colors": { # FramePort's colours before the Portal theme
|
||||
"BG": "#0E0F13", "SIDEBAR": "#121319", "SURFACE": "#171920", "SURFACE_2": "#1E2029", "SURFACE_3": "#262935",
|
||||
"BORDER": "#2C2F3B", "BORDER_STRONG": "#3A3E4D",
|
||||
"TEXT": "#ECEDF3", "TEXT_2": "#A9ADBD", "TEXT_3": "#737889",
|
||||
"ACCENT": "#8B7CFF", "ACCENT_SOFT": "#2A2550", "ON_ACCENT": "#0E0F13",
|
||||
"SECONDARY": "#38BDF8", "SECONDARY_SOFT": "#12303F",
|
||||
"OK": "#4ADE80", "WARN": "#FBBF24", "ERROR": "#F87171", "INFO": "#60A5FA", "PC": "#38BDF8"}},
|
||||
}
|
||||
ALIASES = {"classic": "original"} # an earlier name
|
||||
USER_PREFIX = "user:"
|
||||
THEMES: dict[str, dict] = dict(BUILTIN) # + installed theme files (load_user_themes)
|
||||
DEFAULT_THEME = "portal"
|
||||
THEME = DEFAULT_THEME
|
||||
DUAL = True
|
||||
_listeners: list[Callable[[], None]] = []
|
||||
|
||||
# accent + states
|
||||
ACCENT = "#8B7CFF"
|
||||
ACCENT_SOFT = "#2A2550"
|
||||
ON_ACCENT = "#0E0F13"
|
||||
OK = "#4ADE80"
|
||||
WARN = "#FBBF24"
|
||||
ERROR = "#F87171"
|
||||
INFO = "#60A5FA"
|
||||
PC = "#38BDF8" # PC VR / "on this PC"
|
||||
# the active theme's tokens as module globals (set_theme() replaces them); declared for linters and readers
|
||||
BG = SIDEBAR = SURFACE = SURFACE_2 = SURFACE_3 = BORDER = BORDER_STRONG = ""
|
||||
TEXT = TEXT_2 = TEXT_3 = ACCENT = ACCENT_SOFT = ON_ACCENT = SECONDARY = SECONDARY_SOFT = ""
|
||||
OK = WARN = ERROR = INFO = PC = ""
|
||||
|
||||
|
||||
def theme_from_setting(value) -> str:
|
||||
"""Library setting ui.theme → a known theme id (unknown/missing/removed → the default)."""
|
||||
value = ALIASES.get(value, value)
|
||||
return value if value in THEMES else DEFAULT_THEME
|
||||
|
||||
|
||||
def on_change(callback: Callable[[], None]) -> None:
|
||||
"""Call `callback` after every set_theme() (and once now): for module-level maps that hold colours."""
|
||||
_listeners.append(callback)
|
||||
callback()
|
||||
|
||||
|
||||
def set_theme(name: str) -> None:
|
||||
"""Switch the colour tokens. Views built afterwards use the new colours (app.restyle() rebuilds the open ones)."""
|
||||
global THEME, DUAL
|
||||
THEME = theme_from_setting(name)
|
||||
DUAL = bool(THEMES[THEME]["dual"])
|
||||
globals().update(THEMES[THEME]["colors"])
|
||||
for callback in list(_listeners):
|
||||
callback()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------ theme files
|
||||
class ThemeError(ValueError):
|
||||
"""A theme file FramePort can't use; the message says why, in plain words."""
|
||||
|
||||
|
||||
_HEX = re.compile(r"#?([0-9a-fA-F]{6}|[0-9a-fA-F]{3})")
|
||||
|
||||
|
||||
def _hex(value, key: str) -> str:
|
||||
m = _HEX.fullmatch(str(value).strip()) if isinstance(value, str) else None
|
||||
if not m:
|
||||
raise ThemeError(f"{key}: \"{value}\" is not a color like #FF8A1F")
|
||||
h = m.group(1)
|
||||
return "#" + (h if len(h) == 6 else "".join(c * 2 for c in h)).upper()
|
||||
|
||||
|
||||
def _luminance(color: str) -> float:
|
||||
def ch(v):
|
||||
v /= 255
|
||||
return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
|
||||
r, g, b = (int(color[i:i + 2], 16) for i in (1, 3, 5))
|
||||
return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b)
|
||||
|
||||
|
||||
def contrast(a: str, b: str) -> float:
|
||||
la, lb = sorted((_luminance(a), _luminance(b)), reverse=True)
|
||||
return (la + 0.05) / (lb + 0.05)
|
||||
|
||||
|
||||
def parse_theme(data: dict, fallback_name: str = "Custom theme") -> dict:
|
||||
"""A theme file's content → a theme ({"name", "dual", "colors"}); raises ThemeError. Colours it leaves out come
|
||||
from its "base" built-in (default Portal); keys may be any case."""
|
||||
if not isinstance(data, dict):
|
||||
raise ThemeError("the file isn't a theme (expected a JSON object with \"colors\")")
|
||||
unknown = set(data) - {"name", "base", "dual", "colors", "description", "author", "version"}
|
||||
if unknown:
|
||||
raise ThemeError(f"unknown field(s): {', '.join(sorted(unknown))}")
|
||||
base_id = ALIASES.get(data.get("base") or DEFAULT_THEME, data.get("base") or DEFAULT_THEME)
|
||||
if base_id not in BUILTIN:
|
||||
raise ThemeError(f"base \"{data.get('base')}\" isn't a built-in theme ({', '.join(BUILTIN)})")
|
||||
base = BUILTIN[base_id]
|
||||
raw = data.get("colors") or {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ThemeError("\"colors\" must be an object of TOKEN: \"#RRGGBB\"")
|
||||
colors = dict(base["colors"])
|
||||
for key, value in raw.items():
|
||||
token = str(key).upper()
|
||||
if token not in TOKENS:
|
||||
raise ThemeError(f"unknown color \"{key}\" (known: {', '.join(TOKENS)})")
|
||||
colors[token] = _hex(value, token)
|
||||
# FramePort is dark only: a light window would leave Material's own parts (menus, inputs) unreadable
|
||||
if _luminance(colors["BG"]) > 0.05:
|
||||
raise ThemeError(f"BG {colors['BG']} is too light: FramePort themes are dark")
|
||||
if contrast(colors["TEXT"], colors["SURFACE"]) < 4.5:
|
||||
raise ThemeError(f"TEXT {colors['TEXT']} is hard to read on SURFACE {colors['SURFACE']}")
|
||||
name = str(data.get("name") or fallback_name).strip()[:40] or fallback_name
|
||||
dual = data.get("dual", base["dual"])
|
||||
if not isinstance(dual, bool):
|
||||
raise ThemeError("\"dual\" must be true or false")
|
||||
return {"name": name, "dual": dual, "colors": colors}
|
||||
|
||||
|
||||
def read_theme_file(path: Path) -> dict:
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError) as exc:
|
||||
raise ThemeError(f"can't read the file ({exc})") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ThemeError(f"not valid JSON (line {exc.lineno}: {exc.msg})") from exc
|
||||
return parse_theme(data, Path(path).stem.replace("_", " ").replace("-", " ").title())
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:40] or "theme"
|
||||
|
||||
|
||||
def load_user_themes(folder: Path) -> list[str]:
|
||||
"""(Re)load the installed theme files into THEMES. Returns problems with files that were skipped."""
|
||||
for key in [k for k in THEMES if k.startswith(USER_PREFIX)]:
|
||||
del THEMES[key]
|
||||
problems = []
|
||||
for f in sorted(Path(folder).glob("*.json")) if Path(folder).is_dir() else []:
|
||||
try:
|
||||
THEMES[USER_PREFIX + f.stem] = {**read_theme_file(f), "path": str(f)}
|
||||
except ThemeError as exc:
|
||||
problems.append(f"{f.name}: {exc}")
|
||||
return problems
|
||||
|
||||
|
||||
def install_theme(source: Path, folder: Path) -> str:
|
||||
"""Check a theme file and copy it into the themes folder (named after the theme). Returns its theme id."""
|
||||
theme = read_theme_file(source)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
dest = folder / f"{_slug(theme['name'])}.json"
|
||||
if Path(source).resolve() != dest.resolve():
|
||||
shutil.copyfile(source, dest)
|
||||
tid = USER_PREFIX + dest.stem
|
||||
THEMES[tid] = {**theme, "path": str(dest)}
|
||||
return tid
|
||||
|
||||
|
||||
def remove_theme(theme_id: str) -> None:
|
||||
"""Delete an installed theme file (built-ins can't be removed)."""
|
||||
theme = THEMES.get(theme_id)
|
||||
if not theme_id.startswith(USER_PREFIX) or not theme:
|
||||
raise ThemeError("only installed themes can be removed")
|
||||
Path(theme["path"]).unlink(missing_ok=True)
|
||||
del THEMES[theme_id]
|
||||
|
||||
|
||||
def theme_json(theme_id: str) -> str:
|
||||
"""A theme as a theme file (a starting point for your own)."""
|
||||
t = THEMES[theme_id]
|
||||
base = theme_id if theme_id in BUILTIN else DEFAULT_THEME
|
||||
return json.dumps({"name": f"My {t['name']}", "base": base, "dual": t["dual"], "colors": t["colors"]}, indent=2)
|
||||
|
||||
|
||||
set_theme(DEFAULT_THEME)
|
||||
|
||||
# spacing / shape / type (at 100 %; set_scale() multiplies them)
|
||||
_BASE = {"S1": 4, "S2": 8, "S3": 12, "S4": 16, "S5": 24, "S6": 32, "RADIUS": 12, "RADIUS_SM": 8,
|
||||
"T_TITLE": 28, "T_H2": 16, "T_BODY": 13, "T_META": 12, "T_SMALL": 11}
|
||||
# RADIUS cards/dialogs, RADIUS_SM buttons/inputs/thumbnails, RADIUS_XS small chips/tooltips; ICON_S/M/L icon sizes;
|
||||
# DIALOG_S/M/L dialog content widths; T_DISPLAY big headings (empty states, setup)
|
||||
_BASE = {"S1": 4, "S2": 8, "S3": 12, "S4": 16, "S5": 24, "S6": 32, "RADIUS": 12, "RADIUS_SM": 8, "RADIUS_XS": 6,
|
||||
"ICON_S": 16, "ICON_M": 20, "ICON_L": 24, "DIALOG_S": 440, "DIALOG_M": 600, "DIALOG_L": 880,
|
||||
"T_DISPLAY": 22, "T_TITLE": 28, "T_H2": 16, "T_BODY": 13, "T_META": 12, "T_SMALL": 11}
|
||||
S1, S2, S3, S4, S5, S6 = 4, 8, 12, 16, 24, 32
|
||||
RADIUS = 12
|
||||
RADIUS_SM = 8
|
||||
T_TITLE, T_H2, T_BODY, T_META, T_SMALL = 28, 16, 13, 12, 11
|
||||
RADIUS_XS = 6
|
||||
ICON_S, ICON_M, ICON_L = 16, 20, 24
|
||||
DIALOG_S, DIALOG_M, DIALOG_L = 440, 600, 880
|
||||
T_DISPLAY, T_TITLE, T_H2, T_BODY, T_META, T_SMALL = 22, 28, 16, 13, 12, 11
|
||||
SCALE = 1.0
|
||||
|
||||
|
||||
@@ -91,7 +274,7 @@ def soft(color: str, opacity: float = 0.14) -> str:
|
||||
def apply(page: ft.Page) -> None:
|
||||
scheme = ft.ColorScheme(
|
||||
primary=ACCENT, on_primary=ON_ACCENT, primary_container=ACCENT_SOFT, on_primary_container=TEXT,
|
||||
secondary=PC, on_secondary=ON_ACCENT, surface=SURFACE, on_surface=TEXT, on_surface_variant=TEXT_2,
|
||||
secondary=SECONDARY, on_secondary=ON_ACCENT, surface=SURFACE, on_surface=TEXT, on_surface_variant=TEXT_2,
|
||||
surface_container_lowest=BG, surface_container_low=SIDEBAR, surface_container=SURFACE,
|
||||
surface_container_high=SURFACE_2, surface_container_highest=SURFACE_3, outline=BORDER_STRONG,
|
||||
outline_variant=BORDER, error=ERROR, on_error=ON_ACCENT,
|
||||
@@ -108,13 +291,19 @@ def apply(page: ft.Page) -> None:
|
||||
text_theme=text_theme,
|
||||
divider_theme=ft.DividerTheme(color=BORDER, thickness=1, space=1),
|
||||
tooltip_theme=ft.TooltipTheme(
|
||||
decoration=ft.BoxDecoration(bgcolor=SURFACE_3, border_radius=6,
|
||||
decoration=ft.BoxDecoration(bgcolor=SURFACE_3, border_radius=RADIUS_XS,
|
||||
border=ft.Border.all(1, BORDER)),
|
||||
text_style=ft.TextStyle(color=TEXT, size=px(12)), wait_duration=400),
|
||||
expansion_tile_theme=ft.ExpansionTileTheme(
|
||||
shape=ft.RoundedRectangleBorder(radius=RADIUS), collapsed_shape=ft.RoundedRectangleBorder(
|
||||
radius=RADIUS), icon_color=TEXT_2, collapsed_icon_color=TEXT_3, text_color=TEXT,
|
||||
collapsed_text_color=TEXT),
|
||||
# menus lift off the dark page: border + shadow (right-click ContextMenus only get this theme)
|
||||
popup_menu_theme=ft.PopupMenuTheme(
|
||||
color=SURFACE_2, elevation=8, shadow_color="#000000",
|
||||
shape=ft.RoundedRectangleBorder(radius=RADIUS_SM, side=ft.BorderSide(1, BORDER_STRONG)),
|
||||
menu_padding=ft.Padding(0, px(4), 0, px(4)),
|
||||
label_text_style=ft.TextStyle(size=T_BODY, color=TEXT)),
|
||||
scaffold_bgcolor=BG, card_bgcolor=SURFACE, canvas_color=SURFACE_2)
|
||||
page.theme = page.dark_theme = theme
|
||||
page.theme_mode = ft.ThemeMode.DARK
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Install progress as a transit (no Flet): a job's stage names → one of six steps and an overall fraction, so the GUI
|
||||
can show the game crossing the portal from the PC to the Frame (components.Transit).
|
||||
|
||||
The stage names come from the install job (app._submit_install), build.py, pipeline.py and the installers; they are
|
||||
intentionally not translated so they can be mapped here."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
# step keys (stable) and their labels (translated when shown)
|
||||
STEPS = ("analyze", "patch", "sign", "upload", "install", "test")
|
||||
LABELS = {"analyze": "Analyze", "patch": "Patch", "sign": "Sign", "upload": "Upload", "install": "Install",
|
||||
"test": "Test"}
|
||||
|
||||
# a run starts over with these (a job that lost the Frame runs again from the beginning)
|
||||
_START = ("patching the game", "checking the game")
|
||||
# lower-case stage prefix → step index; the first match wins
|
||||
_PREFIXES = (
|
||||
("patching", 0), ("checking", 0), ("check game files", 0),
|
||||
("ovrport", 1), ("frame fixes", 1), ("revive", 1),
|
||||
("sign", 2), ("validate", 2),
|
||||
("prepare", 3), ("upload", 3),
|
||||
("artwork", 4), ("finalize", 4), ("add to steam", 4),
|
||||
("launch test", 5), ("starting steamvr", 5),
|
||||
)
|
||||
_DONE = ("installed",)
|
||||
WAITING = "Waiting for the Frame"
|
||||
|
||||
# the track: the portal stands still at the PC/Frame boundary. Analyze/Patch/Sign happen on the PC (the cover
|
||||
# approaches the portal), Upload is the crossing (the cover passes under the portal), Install/Test on the Frame (or
|
||||
# this PC's Steam) carry it on to the destination. Positions are fractions of the track.
|
||||
PORTAL_AT = 0.5
|
||||
CROSSING = 0.06 # half the crossing's share of the track, either side of the portal
|
||||
_LOCAL, _UPLOAD = 3, 4 # steps before the upload; the upload's own end
|
||||
# the steps row's column weights, so the Upload column sits under the portal
|
||||
STEP_WEIGHTS = (139, 139, 139, 166, 208, 208)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransitState:
|
||||
step: int # index into STEPS (len(STEPS) = everything done)
|
||||
fraction: float # overall progress 0..1
|
||||
label: str # the step's key ("upload" …), "done" when finished
|
||||
detail: str # what happens right now: the stage, or the upload's % and speed
|
||||
waiting: bool # the queue waits for the Frame
|
||||
failed: bool
|
||||
target: str # "frame" | "pc"
|
||||
|
||||
|
||||
def step_of(stage: str) -> int | None:
|
||||
"""The step a stage name belongs to (None: unknown, keeps the previous step)."""
|
||||
low = (stage or "").strip().lower()
|
||||
if low.startswith(_DONE):
|
||||
return len(STEPS)
|
||||
for prefix, index in _PREFIXES:
|
||||
if low.startswith(prefix):
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def _is_waiting(stage: str) -> bool:
|
||||
from ..i18n import tr
|
||||
|
||||
return bool(stage) and stage in (WAITING, tr(WAITING))
|
||||
|
||||
|
||||
def transit_state(state: str = "running", stage: str = "", stages: list[str] | None = None,
|
||||
fraction: float | None = None, speed: str = "", message: str = "", kind: str = "install",
|
||||
to: str = "frame") -> TransitState:
|
||||
"""Where a job is on its way: the furthest step of the current run (a second build variant's OVRPort after the
|
||||
first one's validate doesn't move it back), the upload's own fraction inside the Upload step, and 1.0 when the
|
||||
job is done (also when the launch test is off and it ends at "Installed")."""
|
||||
stages = list(stages or [])
|
||||
waiting = _is_waiting(stage)
|
||||
step = 0
|
||||
for s in stages:
|
||||
if s.strip().lower().startswith(_START):
|
||||
step = 0 # a new run
|
||||
index = step_of(s)
|
||||
if index is not None:
|
||||
step = max(step, index)
|
||||
if kind == "test" and not any(step_of(s) is not None for s in stages):
|
||||
step = 5 # a launch test on its own: everything before it is done
|
||||
current = None if waiting else step_of(stage)
|
||||
within = 0.0
|
||||
if fraction is not None and current == step and step < len(STEPS):
|
||||
within = min(1.0, max(0.0, float(fraction)))
|
||||
done = state == "done" or step >= len(STEPS)
|
||||
if done:
|
||||
step, within = len(STEPS), 0.0
|
||||
overall = 1.0 if done else (step + within) / len(STEPS)
|
||||
if waiting:
|
||||
detail = WAITING
|
||||
elif current == 3 and fraction is not None:
|
||||
detail = " · ".join(x for x in (f"{fraction:.0%}", speed) if x)
|
||||
else:
|
||||
detail = stage or message
|
||||
return TransitState(step=step, fraction=overall, label="done" if done else STEPS[step], detail=detail,
|
||||
waiting=waiting, failed=state == "failed", target="pc" if to == "pc" else "frame")
|
||||
|
||||
|
||||
def position(fraction: float) -> float:
|
||||
"""Where the cover rides on the track (0..1) for an overall fraction (TransitState.fraction): the local steps
|
||||
bring it from the start to just before the portal (PORTAL_AT − CROSSING), the upload carries it across, Install
|
||||
and Test from just after the portal to the end; done = 1. Monotonic in `fraction`."""
|
||||
x = min(1.0, max(0.0, float(fraction))) * len(STEPS) # steps done, with the current one's share
|
||||
before, after = PORTAL_AT - CROSSING, PORTAL_AT + CROSSING
|
||||
if x <= _LOCAL:
|
||||
return x / _LOCAL * before
|
||||
if x <= _UPLOAD:
|
||||
return before + (x - _LOCAL) * (after - before)
|
||||
return after + (x - _UPLOAD) / (len(STEPS) - _UPLOAD) * (1.0 - after)
|
||||
|
||||
|
||||
def job_state(job) -> TransitState:
|
||||
"""transit_state() for a ui.jobs.Job."""
|
||||
return transit_state(job.state, job.stage, job.stages, job.fraction, job.speed, job.message, job.kind,
|
||||
getattr(job, "to", "frame"))
|
||||
|
||||
|
||||
class Monotonic:
|
||||
"""Keeps one place's bar from moving back within a run: the installer reports the upload's fraction over all its
|
||||
files (APK, then data), but a new stage clears the job's fraction until the first tick ("Upload data" started at
|
||||
the Upload step's 0 % after the APK had filled it). The fraction never decreases for the same job unless the step
|
||||
goes back (the job started over, e.g. after the Frame was lost)."""
|
||||
|
||||
def __init__(self):
|
||||
self.key = None
|
||||
self.step = -1
|
||||
self.best = 0.0
|
||||
|
||||
def follow(self, key, state: TransitState) -> TransitState:
|
||||
if key != self.key or state.step < self.step:
|
||||
self.key, self.best = key, 0.0
|
||||
self.step = state.step
|
||||
self.best = max(self.best, state.fraction)
|
||||
return state if state.fraction == self.best else replace(state, fraction=self.best)
|
||||
@@ -1,5 +1,6 @@
|
||||
"""The GUI side of self-update: finds new releases in the background, shows them (sidebar card, Library bar, a dialog
|
||||
with the release notes) and updates in one click. frameport.updates does the work."""
|
||||
with the changelog of every version since the installed one) and updates in one click; after an update, a Library bar
|
||||
offers "What's new" once. frameport.updates does the work."""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
@@ -10,11 +11,12 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import flet as ft
|
||||
|
||||
from .. import __version__, updates
|
||||
from .. import REPO_URL, __version__, updates
|
||||
from ..core import applog, library
|
||||
from ..errors import explain
|
||||
from ..i18n import tr
|
||||
from . import components as C
|
||||
from . import glyphs as G
|
||||
from . import theme as T
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -27,19 +29,43 @@ class Updater:
|
||||
def __init__(self, app: FramePortApp):
|
||||
self.app = app
|
||||
self.found: updates.Update | None = None
|
||||
self.changes: list[updates.ChangelogEntry] = [] # the found update's changelog (fetched with it)
|
||||
self.news: list[updates.ChangelogEntry] = [] # changes since the last start (after an update), shown once
|
||||
self.restart = None # callable: what to do once the job queue is idle (install + quit)
|
||||
self.preparing = False
|
||||
self._version = C.meta("", color=T.ON_ACCENT)
|
||||
self.build_card()
|
||||
|
||||
def build_card(self) -> None:
|
||||
"""The sidebar's "Update available" card (again after a theme change; keeps what it shows)."""
|
||||
old = getattr(self, "card", None)
|
||||
self._version = C.meta(getattr(self, "_version", None) and self._version.value or "", color=T.ON_ACCENT)
|
||||
self.card = ft.Container(
|
||||
ft.Row([ft.Icon(ft.Icons.SYSTEM_UPDATE_ROUNDED, size=T.px(18), color=T.ON_ACCENT),
|
||||
ft.Column([C.body(tr("Update available"), T.ON_ACCENT, weight=ft.FontWeight.W_600), self._version],
|
||||
spacing=0, expand=True)], spacing=T.S2),
|
||||
padding=T.S3, border_radius=T.RADIUS_SM, bgcolor=T.ACCENT, ink=True, visible=False,
|
||||
padding=T.S3, border_radius=T.RADIUS_SM, bgcolor=T.ACCENT, ink=True, visible=bool(old and old.visible),
|
||||
tooltip=tr("A new FramePort version is ready to install"), on_click=lambda e: self.show_dialog())
|
||||
|
||||
# ---------------------------------------------------------------- checking
|
||||
def start(self) -> None:
|
||||
threading.Thread(target=self._loop, daemon=True).start()
|
||||
threading.Thread(target=self._load_news, daemon=True).start()
|
||||
|
||||
def _load_news(self) -> None:
|
||||
"""First start of a newer version (also after "Install updates automatically"): the Library offers its
|
||||
changes once. Offline: nothing now, tried again at the next start."""
|
||||
try:
|
||||
news = updates.pending_news()
|
||||
except Exception: # noqa: BLE001
|
||||
applog.log.exception("loading what's new failed")
|
||||
return
|
||||
if news:
|
||||
self.news = news
|
||||
self.app.refresh_view()
|
||||
|
||||
def dismiss_news(self) -> None:
|
||||
self.news = []
|
||||
self.app.refresh_view()
|
||||
|
||||
def _loop(self) -> None:
|
||||
time.sleep(FIRST_CHECK_DELAY)
|
||||
@@ -63,6 +89,8 @@ class Updater:
|
||||
self.app.run_bg(work)
|
||||
|
||||
def _set(self, up: updates.Update | None) -> None:
|
||||
"""Called from background threads (it may fetch the releases list for the changelog)."""
|
||||
self.changes = updates.changelog_for(up) if up else []
|
||||
self.found = up
|
||||
self.card.visible = bool(up)
|
||||
self._version.value = tr("FramePort {version} · click to install").format(version=up.version) if up else ""
|
||||
@@ -93,13 +121,14 @@ class Updater:
|
||||
return
|
||||
page = self.app.page
|
||||
kind = updates.install_kind()
|
||||
how = {"bundle": "FramePort downloads it, checks it, closes and opens again as the new version. Your games, "
|
||||
"settings and Frame connection stay as they are.",
|
||||
"source": "Updates this source checkout (git pull + uv sync), then restarts FramePort.",
|
||||
"wheel": "Reinstalls FramePort from the release, then restarts it."}[kind]
|
||||
notes = up.notes.strip() or tr("No release notes.")
|
||||
how = {"bundle": tr("FramePort downloads it, checks it, closes and opens again as the new version. Your "
|
||||
"games, settings and Frame connection stay as they are."),
|
||||
"source": tr("Updates this source checkout (git pull + uv sync), then restarts FramePort."),
|
||||
"wheel": tr("Reinstalls FramePort from the release, then restarts it.")}[kind]
|
||||
changes = self.changes if self.changes and self.changes[0].version == up.version \
|
||||
else [updates.entry_from_update(up)]
|
||||
|
||||
def later(e):
|
||||
def skip(e):
|
||||
updates.skip(up.version)
|
||||
self._set(None)
|
||||
page.pop_dialog()
|
||||
@@ -107,23 +136,38 @@ class Updater:
|
||||
def go(e):
|
||||
page.pop_dialog()
|
||||
self.install()
|
||||
page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(tr("FramePort {version} is available").format(version=up.version), color=T.TEXT,
|
||||
weight=ft.FontWeight.W_600),
|
||||
bgcolor=T.SURFACE_2,
|
||||
content=ft.Container(ft.Column([
|
||||
C.body(tr("You have {version}. {how}").format(version=__version__, how=how), T.TEXT_2),
|
||||
ft.Container(ft.Markdown(notes, selectable=True, extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
|
||||
md_style_sheet=_notes_style(),
|
||||
on_tap_link=lambda e: page.launch_url(e.data)),
|
||||
padding=T.S3, border_radius=T.RADIUS_SM, bgcolor=T.SURFACE,
|
||||
border=ft.Border.all(1, T.BORDER)),
|
||||
], spacing=T.S3, scroll=ft.ScrollMode.AUTO, tight=True, horizontal_alignment=ft.CrossAxisAlignment.STRETCH),
|
||||
width=T.px(560), height=T.px(min(420, 130 + 26 * len(notes.splitlines())))),
|
||||
actions=[C.ghost(tr("Skip this version"), on_click=later),
|
||||
intro = C.body(tr("You have {version}. {how}").format(version=__version__, how=how), T.TEXT_2)
|
||||
if len(changes) > 1:
|
||||
intro = ft.Column([intro, C.meta(tr("What changed in the {n} versions since yours:")
|
||||
.format(n=len(changes)))], spacing=T.S2, tight=True)
|
||||
page.show_dialog(C.dialog(
|
||||
tr("FramePort {version} is available").format(version=up.version),
|
||||
_changes_column(page, changes, intro), size="l", height=_changes_height(changes, 100),
|
||||
actions=[C.ghost(tr("Skip this version"), on_click=skip),
|
||||
C.ghost(tr("Release page"), ft.Icons.OPEN_IN_NEW_ROUNDED, lambda e: page.launch_url(up.page)),
|
||||
C.primary(tr("Update now"), ft.Icons.SYSTEM_UPDATE_ROUNDED, go)]))
|
||||
|
||||
def show_news(self) -> None:
|
||||
"""The Library's "See what's new…" after an update: the changes since the version that ran before."""
|
||||
news, page = self.news, self.app.page
|
||||
self.dismiss_news()
|
||||
if news:
|
||||
page.show_dialog(_changes_dialog(page, tr("What's new in FramePort {version}").format(version=__version__),
|
||||
news))
|
||||
|
||||
def show_history(self) -> None:
|
||||
"""Settings → Updates → "What's new…": the installed version and a few before it."""
|
||||
def work():
|
||||
entries = updates.recent_history(updates.fetch_changelog(need=__version__))
|
||||
page = self.app.page
|
||||
if not entries:
|
||||
self.app.toast(tr("The changelog couldn't be loaded (no internet connection?)"), error=True,
|
||||
action=tr("Releases"), on_action=lambda e: page.launch_url(f"{REPO_URL}/releases"))
|
||||
return
|
||||
self.app.page.run_thread(lambda: page.show_dialog(_changes_dialog(page, tr("FramePort changelog"),
|
||||
entries, current=__version__)))
|
||||
self.app.run_bg(work)
|
||||
|
||||
# ---------------------------------------------------------------- dev builds
|
||||
def install_dev(self) -> None:
|
||||
"""Settings → "Install the latest dev build": the rolling `dev` pre-release the maintainer publishes for
|
||||
@@ -136,35 +180,28 @@ class Updater:
|
||||
if up.version == __version__:
|
||||
self.app.toast(tr("You already have the latest dev build ({version})").format(version=up.version))
|
||||
return
|
||||
self.app.page.run_thread(lambda: self._confirm_dev(up))
|
||||
changes = updates.changelog_for(up) # the dev build + releases since the installed version
|
||||
self.app.page.run_thread(lambda: self._confirm_dev(up, changes))
|
||||
self.app.run_bg(work)
|
||||
|
||||
def _confirm_dev(self, up: updates.Update) -> None:
|
||||
def _confirm_dev(self, up: updates.Update, changes: list[updates.ChangelogEntry] | None = None) -> None:
|
||||
page = self.app.page
|
||||
notes = up.notes.strip() or tr("No notes.")
|
||||
changes = changes or [updates.entry_from_update(up)]
|
||||
|
||||
def go(e):
|
||||
page.pop_dialog()
|
||||
self.found = up
|
||||
self.changes = changes
|
||||
self.install()
|
||||
page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(tr("Install dev build {version}?").format(version=up.version), color=T.TEXT,
|
||||
weight=ft.FontWeight.W_600),
|
||||
bgcolor=T.SURFACE_2,
|
||||
content=ft.Container(ft.Column([
|
||||
C.callout(C.body(tr("Dev builds let you test fixes before they're released. They're less tested "
|
||||
"than releases and may have bugs. You get the next release as a normal update "
|
||||
"(you have {version}).").format(version=__version__), T.TEXT), "warn"),
|
||||
ft.Container(ft.Markdown(notes, selectable=True, extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
|
||||
md_style_sheet=_notes_style(),
|
||||
on_tap_link=lambda e: page.launch_url(e.data)),
|
||||
padding=T.S3, border_radius=T.RADIUS_SM, bgcolor=T.SURFACE,
|
||||
border=ft.Border.all(1, T.BORDER)),
|
||||
], spacing=T.S3, scroll=ft.ScrollMode.AUTO, tight=True, horizontal_alignment=ft.CrossAxisAlignment.STRETCH),
|
||||
width=T.px(560), height=T.px(min(440, 190 + 26 * len(notes.splitlines())))),
|
||||
warn = C.callout(C.body(tr("Dev builds let you test fixes before they're released. They're less tested "
|
||||
"than releases and may have bugs. You get the next release as a normal update "
|
||||
"(you have {version}).").format(version=__version__), T.TEXT), "warn")
|
||||
page.show_dialog(C.dialog(
|
||||
tr("Install dev build {version}?").format(version=up.version),
|
||||
_changes_column(page, changes, warn), size="l", height=_changes_height(changes, 160),
|
||||
actions=[C.ghost(tr("Cancel"), on_click=lambda e: page.pop_dialog()),
|
||||
C.ghost(tr("Build page"), ft.Icons.OPEN_IN_NEW_ROUNDED, lambda e: page.launch_url(up.page)),
|
||||
C.primary(tr("Install dev build"), ft.Icons.SCIENCE_OUTLINED, go)]))
|
||||
C.primary(tr("Install dev build"), G.TEST, go)]))
|
||||
|
||||
# ---------------------------------------------------------------- installing
|
||||
def install(self) -> None:
|
||||
@@ -209,7 +246,7 @@ class Updater:
|
||||
raise RuntimeError(tr("{value} failed ({returncode})")
|
||||
.format(value=cmd[0], returncode=out.returncode))
|
||||
self.restart = self._restart_process
|
||||
rep.stage("Restarting")
|
||||
rep.stage(tr("Restarting"))
|
||||
return tr("FramePort {version} is ready: restarting").format(version=up.version)
|
||||
self.app.submit(tr("Update FramePort to {version}").format(version=up.version), run, None, kind="app-update",
|
||||
open_panel=True)
|
||||
@@ -259,17 +296,77 @@ def _notes_style() -> ft.MarkdownStyleSheet:
|
||||
h3_text_style=text(size=15, weight=ft.FontWeight.W_600), blockquote_text_style=text(T.TEXT_2))
|
||||
|
||||
|
||||
def _entry_section(page: ft.Page, entry: updates.ChangelogEntry, expanded: bool,
|
||||
current: str | None = None) -> ft.Container:
|
||||
"""One version of a changelog: a header (version, tags, date) that opens and closes its notes."""
|
||||
notes = ft.Container(
|
||||
ft.Markdown(entry.body.strip() or tr("No release notes."), selectable=True,
|
||||
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB, md_style_sheet=_notes_style(),
|
||||
on_tap_link=lambda e: page.launch_url(e.data)),
|
||||
padding=ft.Padding(T.S4, 0, T.S4, T.S3), visible=expanded)
|
||||
chevron = ft.Icon(ft.Icons.EXPAND_MORE_ROUNDED if expanded else ft.Icons.CHEVRON_RIGHT_ROUNDED, size=T.px(18),
|
||||
color=T.TEXT_3)
|
||||
tags = ([C.pill(tr("dev build"), T.WARN)] if entry.dev else []) + \
|
||||
([C.pill(tr("installed"), T.OK)] if current and entry.version == current else [])
|
||||
box = ft.Container(bgcolor=T.SURFACE, border=ft.Border.all(1, T.BORDER), border_radius=T.RADIUS_SM)
|
||||
|
||||
def toggle(e):
|
||||
notes.visible = not notes.visible
|
||||
chevron.icon = ft.Icons.EXPAND_MORE_ROUNDED if notes.visible else ft.Icons.CHEVRON_RIGHT_ROUNDED
|
||||
C.update(box)
|
||||
head = ft.Container(
|
||||
ft.Row([chevron, ft.Text(tr("FramePort {version}").format(version=entry.version), size=T.px(15),
|
||||
weight=ft.FontWeight.W_600, color=T.TEXT), *tags, ft.Container(expand=True),
|
||||
C.meta(entry.date)], spacing=T.S2, vertical_alignment=ft.CrossAxisAlignment.CENTER),
|
||||
padding=ft.Padding(T.S3, T.S2, T.S3, T.S2), border_radius=T.RADIUS_SM, ink=True, on_click=toggle)
|
||||
box.content = ft.Column([head, notes], spacing=0, tight=True,
|
||||
horizontal_alignment=ft.CrossAxisAlignment.STRETCH)
|
||||
return box
|
||||
|
||||
|
||||
def _changes_column(page: ft.Page, entries: list[updates.ChangelogEntry], intro: ft.Control | None = None,
|
||||
current: str | None = None) -> ft.Column:
|
||||
"""A scrollable changelog, newest first: the newest version open, older ones as one-line headers."""
|
||||
return ft.Column(([intro] if intro is not None else [])
|
||||
+ [_entry_section(page, e, i == 0, current) for i, e in enumerate(entries)],
|
||||
spacing=T.S2, scroll=ft.ScrollMode.AUTO, tight=True,
|
||||
horizontal_alignment=ft.CrossAxisAlignment.STRETCH)
|
||||
|
||||
|
||||
def _changes_height(entries: list[updates.ChangelogEntry], extra: int) -> float:
|
||||
"""Tall enough for the newest version's notes and the other headers, at most 480 (then it scrolls)."""
|
||||
lines = len(entries[0].body.splitlines()) if entries else 1
|
||||
return T.px(min(480, extra + 26 * lines + 50 * len(entries)))
|
||||
|
||||
|
||||
def _changes_dialog(page: ft.Page, title: str, entries: list[updates.ChangelogEntry],
|
||||
current: str | None = None) -> ft.AlertDialog:
|
||||
return C.dialog(title, _changes_column(page, entries, None, current), size="l",
|
||||
height=_changes_height(entries, 20),
|
||||
actions=[C.ghost(tr("All releases"), ft.Icons.OPEN_IN_NEW_ROUNDED,
|
||||
lambda e: page.launch_url(f"{REPO_URL}/releases")),
|
||||
C.primary(tr("Close"), on_click=lambda e: page.pop_dialog())])
|
||||
|
||||
|
||||
def library_bar(app: FramePortApp) -> ft.Control | None:
|
||||
"""The Library's "update available" bar (None when there's nothing to show)."""
|
||||
up = app.updater.found if getattr(app, "updater", None) else None
|
||||
"""The Library's "update available" bar, else the "what's new" bar after an update (None: nothing to show)."""
|
||||
updater = getattr(app, "updater", None)
|
||||
up = updater.found if updater else None
|
||||
if not up and updater and updater.news:
|
||||
return C.callout(ft.Row([
|
||||
C.body(tr("FramePort was updated to {version}.").format(version=__version__), T.TEXT,
|
||||
expand=True),
|
||||
C.primary(tr("See what's new…"), ft.Icons.NEW_RELEASES_OUTLINED, lambda e: updater.show_news()),
|
||||
C.ghost(tr("Dismiss"), on_click=lambda e: updater.dismiss_news()),
|
||||
], spacing=T.S3), "ok", ft.Icons.NEW_RELEASES_OUTLINED)
|
||||
if not up:
|
||||
return None
|
||||
return C.callout(ft.Row([
|
||||
C.body(tr("FramePort {version} is available (you have {version2}).")
|
||||
.format(version=up.version, version2=__version__), T.TEXT, expand=True),
|
||||
C.primary(tr("Update now"), ft.Icons.SYSTEM_UPDATE_ROUNDED, lambda e: app.updater.install()),
|
||||
C.ghost(tr("What's new"), on_click=lambda e: app.updater.show_dialog()),
|
||||
C.ghost(tr("Later"), on_click=lambda e: (updates.skip(up.version), app.updater._set(None))),
|
||||
C.ghost(tr("What's new…"), on_click=lambda e: app.updater.show_dialog()),
|
||||
C.ghost(tr("Not now"), on_click=lambda e: (updates.snooze(up.version), app.updater._set(None))),
|
||||
], spacing=T.S3), "info", ft.Icons.SYSTEM_UPDATE_ROUNDED)
|
||||
|
||||
|
||||
|
||||
@@ -15,13 +15,22 @@ from ..jobs import Job
|
||||
if TYPE_CHECKING:
|
||||
from ..app import FramePortApp
|
||||
|
||||
CHECK_ICON = {True: (ft.Icons.CHECK_CIRCLE_ROUNDED, T.OK), False: (ft.Icons.CANCEL_ROUNDED, T.ERROR),
|
||||
None: (ft.Icons.WARNING_AMBER_ROUNDED, T.WARN)}
|
||||
STATE_STYLE = {"queued": (ft.Icons.SCHEDULE_ROUNDED, T.TEXT_3, tr("Waiting")),
|
||||
"running": (ft.Icons.SYNC_ROUNDED, T.ACCENT, tr("Working")),
|
||||
"done": (ft.Icons.CHECK_CIRCLE_ROUNDED, T.OK, tr("Done")),
|
||||
"failed": (ft.Icons.ERROR_ROUNDED, T.ERROR, tr("Failed")),
|
||||
"cancelled": (ft.Icons.DO_NOT_DISTURB_ON_OUTLINED, T.TEXT_3, tr("Cancelled"))}
|
||||
CHECK_ICON: dict = {}
|
||||
STATE_STYLE: dict[str, tuple] = {}
|
||||
|
||||
|
||||
def _fill_styles() -> None:
|
||||
"""(Re)fill the maps with the active theme's colours, in place."""
|
||||
CHECK_ICON.update({True: (ft.Icons.CHECK_CIRCLE_ROUNDED, T.OK), False: (ft.Icons.CANCEL_ROUNDED, T.ERROR),
|
||||
None: (ft.Icons.WARNING_AMBER_ROUNDED, T.WARN)})
|
||||
STATE_STYLE.update({"queued": (ft.Icons.SCHEDULE_ROUNDED, T.TEXT_3, tr("Waiting")),
|
||||
"running": (ft.Icons.SYNC_ROUNDED, T.ACCENT, tr("Working")),
|
||||
"done": (ft.Icons.CHECK_CIRCLE_ROUNDED, T.OK, tr("Done")),
|
||||
"failed": (ft.Icons.ERROR_ROUNDED, T.ERROR, tr("Failed")),
|
||||
"cancelled": (ft.Icons.DO_NOT_DISTURB_ON_OUTLINED, T.TEXT_3, tr("Canceled"))})
|
||||
|
||||
|
||||
T.on_change(_fill_styles)
|
||||
|
||||
|
||||
def _dur(job: Job) -> str:
|
||||
@@ -31,18 +40,14 @@ def _dur(job: Job) -> str:
|
||||
return f"{s // 60}:{s % 60:02d}"
|
||||
|
||||
|
||||
|
||||
def _progress_text(job: Job) -> str:
|
||||
"""Speed first: the line is ellipsized, and the file name matters least."""
|
||||
return " · ".join(x for x in (job.speed, job.message) if x)
|
||||
|
||||
class ActivityPanel:
|
||||
def __init__(self, app: FramePortApp):
|
||||
self.app = app
|
||||
self.expanded: set[int] = set()
|
||||
self.logs: set[int] = set()
|
||||
self._tiles: dict[int, tuple[tuple, ft.Control]] = {} # job id -> (state key, tile)
|
||||
self._live: dict[int, tuple] = {} # running job id -> (progress bar, message, stage text, log text or None)
|
||||
self._live: dict[int, tuple] = {} # running job id -> (transit, log text or None)
|
||||
self._transits: dict[int, C.Transit] = {} # running job id -> its transit, kept across tile rebuilds
|
||||
# job id -> (log text, its scrolling column): kept across tile rebuilds so reading the log doesn't jump
|
||||
self._logviews: dict[int, tuple[ft.Text, ft.Column]] = {}
|
||||
self._lock = threading.Lock() # refresh() runs from job threads and the UI thread
|
||||
@@ -95,11 +100,9 @@ class ActivityPanel:
|
||||
self._tiles[j.id] = cached
|
||||
rebuilt = True
|
||||
elif running and j.id in self._live:
|
||||
bar, msg, meta, log = self._live[j.id]
|
||||
bar.value = j.fraction
|
||||
msg.value = _progress_text(j)
|
||||
meta.value = j.stage or ""
|
||||
live += [bar, msg, meta]
|
||||
transit, log = self._live[j.id]
|
||||
transit.set(j, **self.app.transit_info(j))
|
||||
live.append(transit.control)
|
||||
if log is not None and len(j.log) != getattr(log, "_lines", -1): # only when it grew
|
||||
log.value = "\n".join(j.log[-400:])
|
||||
log._lines = len(j.log)
|
||||
@@ -119,6 +122,8 @@ class ActivityPanel:
|
||||
return
|
||||
self._layout = layout
|
||||
self._tiles = {j.id: self._tiles[j.id] for j in jobs}
|
||||
self._transits = {jid: t for jid, t in self._transits.items()
|
||||
if any(j.id == jid and j.state == "running" for j in jobs)}
|
||||
self._logviews = {jid: v for jid, v in self._logviews.items() if jid in self._tiles}
|
||||
if self.app.jobs.paused == "frame":
|
||||
pinned.insert(0, self._paused_notice())
|
||||
@@ -161,11 +166,10 @@ class ActivityPanel:
|
||||
icon, color, word = ft.Icons.WARNING_AMBER_ROUNDED, T.WARN, tr("Installed · launch test failed")
|
||||
running = job.state == "running"
|
||||
expanded = running or job.id in self.expanded
|
||||
meta = C.meta(job.stage if running and job.stage else
|
||||
(job.error or word) + (f" · {_dur(job)}" if job.finished else ""),
|
||||
T.ERROR if job.state == "failed" else T.TEXT_2, max_lines=2)
|
||||
meta = C.meta((job.error or word) + (f" · {_dur(job)}" if job.finished else ""),
|
||||
T.ERROR if job.state == "failed" else T.TEXT_2, max_lines=2, visible=not running)
|
||||
head = ft.Row([
|
||||
ft.ProgressRing(width=T.px(18), height=T.px(18), stroke_width=T.px(2), color=T.ACCENT) if running
|
||||
C.spinner() if running
|
||||
else ft.Icon(icon, color=color, size=T.px(20)),
|
||||
ft.Column([C.body(job.title, T.TEXT, weight=ft.FontWeight.W_600, max_lines=2,
|
||||
overflow=ft.TextOverflow.ELLIPSIS), meta],
|
||||
@@ -174,11 +178,13 @@ class ActivityPanel:
|
||||
if job.active else []),
|
||||
], vertical_alignment=ft.CrossAxisAlignment.START, spacing=T.S3)
|
||||
parts: list[ft.Control] = [head]
|
||||
if running:
|
||||
bar = C.progress_bar(job.fraction)
|
||||
msg = C.meta(_progress_text(job), max_lines=1, overflow=ft.TextOverflow.ELLIPSIS)
|
||||
parts += [bar, msg]
|
||||
self._live[job.id] = (bar, msg, meta, None)
|
||||
if running: # the game on its way through the portal, with the six steps
|
||||
transit = self._transits.get(job.id)
|
||||
if transit is None:
|
||||
transit = self._transits[job.id] = C.Transit(heading=False)
|
||||
transit.set(job, **self.app.transit_info(job))
|
||||
parts.append(transit.control)
|
||||
self._live[job.id] = (transit, None)
|
||||
if expanded:
|
||||
if job.stages:
|
||||
parts.append(ft.Column([
|
||||
@@ -202,21 +208,22 @@ class ActivityPanel:
|
||||
C.ghost(tr("Hide log") if show_log else tr("Show log"), ft.Icons.TERMINAL_ROUNDED,
|
||||
lambda e: self._toggle(self.logs, job.id)),
|
||||
C.ghost(tr("Copy log"), ft.Icons.CONTENT_COPY_ROUNDED, lambda e: self.app.copy(self.job_text(job))),
|
||||
*([C.ghost(tr("Full launch log"), ft.Icons.DESCRIPTION_ROUNDED,
|
||||
*([C.ghost(tr("Full launch log"), ft.Icons.DESCRIPTION_OUTLINED,
|
||||
lambda e: self.app.show_log_file(job.log_path, job.title))] if job.log_path else []),
|
||||
], spacing=0, wrap=True))
|
||||
if show_log:
|
||||
log, col = self._log_view(job)
|
||||
log.value = "\n".join(job.log[-400:])
|
||||
if running:
|
||||
self._live[job.id] = (*self._live[job.id][:3], log)
|
||||
self._live[job.id] = (self._live[job.id][0], log)
|
||||
else:
|
||||
col.auto_scroll = False
|
||||
parts.append(ft.Container(col, bgcolor=T.BG, border_radius=T.RADIUS_SM, padding=T.S2,
|
||||
height=T.px(240)))
|
||||
return ft.Container(ft.Column(parts, spacing=T.S2), bgcolor=T.SURFACE, border_radius=T.RADIUS,
|
||||
border=ft.Border.all(1, T.ACCENT if running else T.BORDER), padding=T.S3,
|
||||
on_click=None if running else lambda e: self._toggle(self.expanded, job.id))
|
||||
on_click=None if running else lambda e: self._toggle(self.expanded, job.id),
|
||||
ink=not running)
|
||||
|
||||
def _log_view(self, job: Job) -> tuple[ft.Text, ft.Column]:
|
||||
"""The job's log view, the same one for the job's whole life: rebuilding it on every new stage or check reset
|
||||
|
||||
@@ -123,7 +123,7 @@ def _open(app: FramePortApp, package: str, g: dict | None, values: dict) -> None
|
||||
choices = list(spec[0])
|
||||
if v not in [c for c, _ in choices]:
|
||||
choices.append((v, str(v))) # a value set elsewhere (CLI, catalog) stays selectable
|
||||
return ft.Dropdown(value=str(v), width=T.px(220), dense=True, border_color=T.BORDER,
|
||||
return C.dropdown(value=str(v), width=T.px(220),
|
||||
options=[ft.DropdownOption(key=str(c), text=tr(label)) for c, label in choices],
|
||||
on_select=lambda e: set_value(key, e.control.value))
|
||||
|
||||
@@ -201,12 +201,8 @@ def _open(app: FramePortApp, package: str, g: dict | None, values: dict) -> None
|
||||
if show_adv else []),
|
||||
], spacing=T.S3, scroll=ft.ScrollMode.AUTO, tight=True)
|
||||
title = tr("Game settings · {title}").format(title=app._title(package) if g else package)
|
||||
app.page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(title, weight=ft.FontWeight.W_600), bgcolor=T.SURFACE_2,
|
||||
shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
content=ft.Container(content, width=T.px(640), height=T.px(560)),
|
||||
actions=[C.ghost(tr("Reset to recommended"), ft.Icons.RESTART_ALT_ROUNDED, reset),
|
||||
C.ghost(tr("Cancel"), on_click=lambda e: app.page.pop_dialog()),
|
||||
C.primary(tr("Save"), on_click=save)],
|
||||
actions_alignment=ft.MainAxisAlignment.END))
|
||||
app.page.show_dialog(C.dialog(
|
||||
title, content, [C.ghost(tr("Reset to recommended"), ft.Icons.RESTART_ALT_ROUNDED, reset),
|
||||
C.ghost(tr("Cancel"), on_click=lambda e: app.page.pop_dialog()),
|
||||
C.primary(tr("Save"), on_click=save)], height=T.px(560)))
|
||||
apply_visibility()
|
||||
@@ -19,9 +19,7 @@ if TYPE_CHECKING:
|
||||
|
||||
def show_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
g = library.game(package)
|
||||
term = ft.TextField(value=g.get("title") or package, dense=True, expand=True, border_radius=T.RADIUS_SM,
|
||||
bgcolor=T.SURFACE_3, border_color=ft.Colors.TRANSPARENT, focused_border_color=T.ACCENT,
|
||||
content_padding=ft.Padding(T.px(12), T.px(8), T.px(12), T.px(8)), text_size=T.T_BODY)
|
||||
term = C.search(value=g.get("title") or package, expand=True)
|
||||
results = ft.GridView(max_extent=T.px(190), child_aspect_ratio=0.8, spacing=T.S3, run_spacing=T.S3,
|
||||
height=T.px(400))
|
||||
status = C.meta("")
|
||||
@@ -43,7 +41,7 @@ def show_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
if installed:
|
||||
app.toast(tr("Artwork updated for {get}. The Frame's Steam library still shows the old art.")
|
||||
.format(get=g.get('title')),
|
||||
action=tr("Update on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
else:
|
||||
app.toast(tr("Artwork updated for {get}").format(get=g.get('title')))
|
||||
app.run_bg(work)
|
||||
@@ -56,7 +54,7 @@ def show_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
def work():
|
||||
found = sources.search(term.value.strip())
|
||||
results.controls = [ft.Container(ft.Column([
|
||||
ft.Container(C.art_fill(r["preview"], radius=T.px(8), height=T.px(120)), height=T.px(120)),
|
||||
ft.Container(C.art_fill(r["preview"], radius=T.RADIUS_SM, height=T.px(120)), height=T.px(120)),
|
||||
C.body(r["name"] or "", T.TEXT, size=T.T_META, max_lines=2, overflow=ft.TextOverflow.ELLIPSIS),
|
||||
C.meta(r["source"]),
|
||||
], spacing=T.px(4)), padding=T.S2, border_radius=T.RADIUS_SM, bgcolor=T.SURFACE, ink=True,
|
||||
@@ -80,20 +78,19 @@ def show_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
if src and src != "none" and installed:
|
||||
app.toast(tr("Artwork updated ({src}). The Frame's Steam library still shows the old art.")
|
||||
.format(src=src),
|
||||
action=tr("Update on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
else:
|
||||
app.toast(tr("Artwork: {value}").format(value=src or 'none found'))
|
||||
app.run_bg(work)
|
||||
|
||||
term.on_submit = search
|
||||
app.page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(tr("Artwork for {get}").format(get=g.get('title')), weight=ft.FontWeight.W_600),
|
||||
content=ft.Container(ft.Column([
|
||||
app.page.show_dialog(C.dialog(
|
||||
tr("Artwork for {get}").format(get=g.get('title')),
|
||||
ft.Column([
|
||||
ft.Row([term, C.secondary(tr("Search"), ft.Icons.SEARCH_ROUNDED, search)], spacing=T.S2),
|
||||
status, results,
|
||||
], spacing=T.S3, tight=True), width=T.px(660)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
actions=[C.ghost(tr("Use your own images…"), ft.Icons.UPLOAD_FILE_ROUNDED,
|
||||
], spacing=T.S3, tight=True),
|
||||
actions=[C.ghost(tr("Use your own images…"), ft.Icons.UPLOAD_FILE_OUTLINED,
|
||||
lambda e: (app.page.pop_dialog(), show_custom_art_dialog(app, package))),
|
||||
C.ghost(tr("Find automatically"), ft.Icons.AUTO_AWESOME_ROUNDED, auto),
|
||||
C.ghost(tr("Close"), on_click=lambda e: app.page.pop_dialog())]))
|
||||
@@ -125,7 +122,7 @@ def show_custom_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
app.refresh_view()
|
||||
if installed:
|
||||
app.toast(tr("{message} The Frame's Steam library still shows the old art.").format(message=message),
|
||||
action=tr("Update on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
else:
|
||||
app.toast(message)
|
||||
|
||||
@@ -155,16 +152,16 @@ def show_custom_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
art = thumbs.url(package, (kind,), 400)
|
||||
if art and kind in ("logo", "icon"): # shown whole (a logo is often very wide, an icon small)
|
||||
box = ft.Container(ft.Image(src=art, fit=ft.BoxFit.CONTAIN), height=T.px(110), padding=T.S2,
|
||||
border_radius=T.px(8), bgcolor=T.SURFACE_3, alignment=ft.Alignment.CENTER)
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3, alignment=ft.Alignment.CENTER)
|
||||
else:
|
||||
box = (C.art_fill(art, radius=T.px(8), height=T.px(110)) if art else
|
||||
box = (C.art_fill(art, radius=T.RADIUS_SM, height=T.px(110)) if art else
|
||||
ft.Container(C.meta(tr("None")), height=T.px(110), alignment=ft.Alignment.CENTER,
|
||||
border_radius=T.px(8), bgcolor=T.SURFACE_3))
|
||||
buttons = [C.ghost(tr("Choose…"), ft.Icons.UPLOAD_FILE_ROUNDED,
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3))
|
||||
buttons = [C.ghost(tr("Choose…"), ft.Icons.UPLOAD_FILE_OUTLINED,
|
||||
lambda e, k=kind, lb=label: app.page.run_task(choose, k, lb))]
|
||||
if art:
|
||||
buttons.append(ft.IconButton(ft.Icons.DELETE_OUTLINE_ROUNDED, icon_size=T.px(18), icon_color=T.TEXT_3,
|
||||
tooltip=tr("Remove"), on_click=lambda e, k=kind, lb=label: remove(k, lb)))
|
||||
buttons.append(C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Remove"),
|
||||
lambda e, k=kind, lb=label: remove(k, lb), color=T.TEXT_3))
|
||||
return ft.Container(ft.Column([
|
||||
box,
|
||||
C.body(label, T.TEXT, size=T.T_META, weight=ft.FontWeight.W_600),
|
||||
@@ -178,14 +175,13 @@ def show_custom_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
C.update(grid)
|
||||
|
||||
grid.controls = [slot(*s) for s in custom_slots()]
|
||||
app.page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(tr("Your own artwork for {title}").format(title=g.get("title")), weight=ft.FontWeight.W_600),
|
||||
content=ft.Container(ft.Column([
|
||||
app.page.show_dialog(C.dialog(
|
||||
tr("Your own artwork for {title}").format(title=g.get("title")),
|
||||
ft.Column([
|
||||
C.body(tr("Choose PNG, JPEG or WebP images. Steam fills any missing shape from the ones you choose; "
|
||||
"FramePort never replaces your images automatically.")),
|
||||
grid,
|
||||
], spacing=T.S3, tight=True), width=T.px(660)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
], spacing=T.S3, tight=True),
|
||||
actions=[C.ghost(tr("Search the stores instead"), ft.Icons.IMAGE_SEARCH_ROUNDED,
|
||||
lambda e: (app.page.pop_dialog(), show_art_dialog(app, package))),
|
||||
C.ghost(tr("Close"), on_click=lambda e: app.page.pop_dialog())]))
|
||||
@@ -42,6 +42,18 @@ def show_exe_dialog(app: FramePortApp, package: str, remaining: int = 0,
|
||||
cands = extra.get("exe_candidates") or [{"path": g.get("exe"), "score": 0, "reasons": [], "size": 0}]
|
||||
current = g.get("exe") or cands[0]["path"]
|
||||
group = ft.RadioGroup(value=current, content=ft.Column(spacing=T.S2))
|
||||
rows: dict[str, ft.Container] = {}
|
||||
|
||||
def paint(e=None):
|
||||
for path, row in rows.items():
|
||||
C.selected_style(row, path == group.value, idle_bg=T.SURFACE)
|
||||
if e is not None:
|
||||
C.update(group)
|
||||
|
||||
def choose(path):
|
||||
group.value = path
|
||||
paint(True)
|
||||
group.on_change = paint
|
||||
for i, c in enumerate(cands):
|
||||
tags = [C.pill(r, T.OK if r in ("Unreal game build", "Unity game (next to its data)", "name matches the game",
|
||||
"named in the Oculus manifest") else
|
||||
@@ -50,7 +62,7 @@ def show_exe_dialog(app: FramePortApp, package: str, remaining: int = 0,
|
||||
if i == 0:
|
||||
tags.insert(0, C.pill(tr("Best guess"), T.ACCENT, ft.Icons.AUTO_AWESOME_ROUNDED))
|
||||
folder, _, name = c["path"].rpartition("/")
|
||||
group.content.controls.append(ft.Container(ft.Row([
|
||||
rows[c["path"]] = row = C.hoverable(ft.Container(ft.Row([
|
||||
ft.Radio(value=c["path"], active_color=T.ACCENT),
|
||||
ft.Column([
|
||||
ft.Row([C.body(name, T.TEXT, weight=ft.FontWeight.W_600), C.meta(_size(c.get("size") or 0))],
|
||||
@@ -59,8 +71,9 @@ def show_exe_dialog(app: FramePortApp, package: str, remaining: int = 0,
|
||||
ft.Row(tags, spacing=T.px(6), wrap=True) if tags else ft.Container(),
|
||||
], spacing=T.px(4), expand=True),
|
||||
], vertical_alignment=ft.CrossAxisAlignment.START), padding=ft.Padding(T.S2, T.S2, T.S3, T.S2),
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE if c["path"] != current else T.ACCENT_SOFT,
|
||||
on_click=lambda e, p=c["path"]: (setattr(group, "value", p), group.update())))
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE, on_click=lambda e, p=c["path"]: choose(p)))
|
||||
group.content.controls.append(row)
|
||||
paint()
|
||||
|
||||
def use(e):
|
||||
choice = group.value
|
||||
@@ -88,12 +101,10 @@ def show_exe_dialog(app: FramePortApp, package: str, remaining: int = 0,
|
||||
"as crash reporters or updaters are the wrong choice).") if linux else
|
||||
tr("FramePort found more than one program that could start this game. Pick the one you'd double-click to "
|
||||
"play it. Oculus builds usually work better with Revive than Steam builds."))
|
||||
app.page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Row([ft.Text(title, weight=ft.FontWeight.W_600, expand=True)]
|
||||
+ ([C.meta(tr("{remaining} more after this").format(remaining=remaining))] if remaining else [])),
|
||||
content=ft.Container(ft.Column([C.body(lead), group], spacing=T.S4, scroll=ft.ScrollMode.AUTO, tight=True),
|
||||
width=T.px(620), height=min(120 + 96 * len(cands), 520)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
app.page.show_dialog(C.dialog(
|
||||
title, ft.Column([C.body(lead), group], spacing=T.S4, scroll=ft.ScrollMode.AUTO, tight=True),
|
||||
title_actions=[C.meta(tr("{remaining} more after this").format(remaining=remaining))] if remaining else None,
|
||||
height=T.px(min(120 + 96 * len(cands), 520)),
|
||||
modal=True, on_dismiss=pick(lambda e: on_done() if on_done else None), # closed (Esc) = decide later
|
||||
actions=[C.ghost(tr("Decide later"), on_click=pick(later)),
|
||||
C.primary(tr("Use this program"), on_click=pick(use))]))
|
||||
@@ -23,7 +23,7 @@ from .files_dialog import human
|
||||
if TYPE_CHECKING:
|
||||
from ..app import FramePortApp
|
||||
|
||||
SHARED_ICONS = {"videos": ft.Icons.MOVIE_OUTLINED, "downloads": ft.Icons.DOWNLOAD_OUTLINED,
|
||||
SHARED_ICONS = {"videos": ft.Icons.MOVIE_OUTLINED, "downloads": ft.Icons.DOWNLOAD_ROUNDED,
|
||||
"documents": ft.Icons.DESCRIPTION_OUTLINED}
|
||||
VIDEO_EXT = {".mp4", ".mkv", ".webm", ".mov", ".avi", ".m4v", ".ts"}
|
||||
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"}
|
||||
@@ -47,7 +47,7 @@ def dropzone_available() -> bool:
|
||||
|
||||
def file_icon(name: str, is_dir: bool) -> str:
|
||||
if is_dir:
|
||||
return ft.Icons.FOLDER_ROUNDED
|
||||
return ft.Icons.FOLDER_OUTLINED
|
||||
ext = Path(name).suffix.lower()
|
||||
if ext in VIDEO_EXT:
|
||||
return ft.Icons.MOVIE_OUTLINED
|
||||
@@ -84,21 +84,24 @@ class FilesView:
|
||||
self.listing = ft.Column(spacing=0, scroll=ft.ScrollMode.AUTO, expand=True)
|
||||
self.status = C.meta("")
|
||||
self.toolbar = ft.Row([
|
||||
C.primary(tr("Upload files"), ft.Icons.UPLOAD_FILE_ROUNDED, self.upload_files),
|
||||
C.secondary(tr("Upload folder"), ft.Icons.DRIVE_FOLDER_UPLOAD_ROUNDED, self.upload_folder),
|
||||
C.ghost(tr("New folder"), ft.Icons.CREATE_NEW_FOLDER_OUTLINED, lambda e: self.new_folder()),
|
||||
C.primary(tr("Upload files…"), ft.Icons.UPLOAD_FILE_OUTLINED, self.upload_files),
|
||||
C.secondary(tr("Upload folder…"), ft.Icons.DRIVE_FOLDER_UPLOAD_OUTLINED, self.upload_folder),
|
||||
C.ghost(tr("New folder…"), ft.Icons.CREATE_NEW_FOLDER_OUTLINED, lambda e: self.new_folder()),
|
||||
C.icon_btn(ft.Icons.REFRESH_ROUNDED, tr("Refresh"), lambda e: self.load()),
|
||||
], spacing=T.S2, wrap=True, run_spacing=T.S2)
|
||||
self.hidden_switch = C.switch(tr("Show hidden files"), wrap=False, value=False, on_change=self._toggle_hidden)
|
||||
self.selected: set[str] = set() # paths of checked entries in the current folder
|
||||
self.checks: dict[str, ft.Checkbox] = {}
|
||||
self.rows: dict[str, tuple] = {} # path → (row, quiet checkbox, quiet actions)
|
||||
self.hot: set[str] = set() # rows under the mouse or with keyboard focus inside
|
||||
self._select_mode = False
|
||||
self.select_all = ft.Checkbox(value=False, active_color=T.ACCENT, check_color=T.ON_ACCENT,
|
||||
tooltip=tr("Select all"), on_change=self._toggle_all)
|
||||
self.sel_label = C.body("", T.TEXT, weight=ft.FontWeight.W_500)
|
||||
self.sel_bar = ft.Container(ft.Row([
|
||||
self.sel_label, ft.Container(expand=True),
|
||||
C.secondary(tr("Download"), ft.Icons.DOWNLOAD_ROUNDED, self._download_selected),
|
||||
C.ghost(tr("Delete"), ft.Icons.DELETE_OUTLINE_ROUNDED, lambda e: self._delete_selected()),
|
||||
C.secondary(tr("Download…"), ft.Icons.DOWNLOAD_ROUNDED, self._download_selected),
|
||||
C.ghost(tr("Delete…"), ft.Icons.DELETE_OUTLINE_ROUNDED, lambda e: self._delete_selected()),
|
||||
C.ghost(tr("Clear"), ft.Icons.CLOSE_ROUNDED, lambda e: self._clear_selection()),
|
||||
], spacing=T.S2), padding=ft.Padding(T.S3, T.px(6), T.S2, T.px(6)), border_radius=T.RADIUS_SM,
|
||||
bgcolor=T.ACCENT_SOFT, visible=False)
|
||||
@@ -124,9 +127,18 @@ class FilesView:
|
||||
if not (app.target and app.frame_state == "connected"):
|
||||
return ft.Column([
|
||||
app.top_bar(tr("Files"), tr("Videos, documents, mods and saves on your Steam Frame")),
|
||||
C.empty_state(ft.Icons.FOLDER_OFF_OUTLINED, tr("Connect your Frame first"),
|
||||
tr("Files on the Frame can be browsed once FramePort is connected to it."),
|
||||
C.primary(tr("Connect"), ft.Icons.LINK_ROUNDED, lambda e: app.go("frame")))], expand=True)
|
||||
C.empty_state(ft.Icons.FOLDER_OPEN_ROUNDED, tr("Your Frame's files, from this PC"),
|
||||
tr("Connect to your Steam Frame to browse its videos, downloads and each game's "
|
||||
"storage."),
|
||||
C.primary(tr("Connect"), ft.Icons.LINK_ROUNDED, lambda e: app.go("frame")),
|
||||
features=[
|
||||
(ft.Icons.VIDEO_LIBRARY_OUTLINED, tr("Videos for your players"),
|
||||
tr("Upload movies straight into a player's own folder.")),
|
||||
(ft.Icons.SAVE_ROUNDED, tr("Game storage and saves"),
|
||||
tr("Browse each installed game's files and download your saves.")),
|
||||
(ft.Icons.DRIVE_FOLDER_UPLOAD_OUTLINED, tr("Files and whole folders"),
|
||||
tr("Upload from this PC, download, rename and tidy up.")),
|
||||
])], expand=True)
|
||||
if self.root is None:
|
||||
self.root = ft.Column([
|
||||
app.top_bar(tr("Files"), tr("Videos, documents, mods and saves on your Steam Frame")),
|
||||
@@ -175,12 +187,14 @@ class FilesView:
|
||||
|
||||
def _location_row(self, loc: dict, icon: str, sub: str = "") -> ft.Control:
|
||||
selected = self.loc is not None and self.loc["id"] == loc["id"]
|
||||
return ft.Container(
|
||||
ft.Row([ft.Icon(icon, size=T.px(18), color=T.ACCENT if selected else T.TEXT_2),
|
||||
ft.Column([C.body(loc["label"], T.TEXT if selected else T.TEXT_2, weight=ft.FontWeight.W_500),
|
||||
*([C.meta(sub)] if sub else [])], spacing=0, expand=True)], spacing=T.S2),
|
||||
ic = ft.Icon(icon, size=T.px(18))
|
||||
label = C.body(loc["label"], weight=ft.FontWeight.W_500)
|
||||
box = ft.Container(
|
||||
ft.Row([ic, ft.Column([label, *([C.meta(sub)] if sub else [])], spacing=0, expand=True)], spacing=T.S2),
|
||||
padding=ft.Padding(T.S2, T.px(6), T.S2, T.px(6)), border_radius=T.RADIUS_SM, ink=True,
|
||||
bgcolor=T.ACCENT_SOFT if selected else None, on_click=lambda e, loc_=loc: self.open_location(loc_))
|
||||
on_click=lambda e, loc_=loc: self.open_location(loc_))
|
||||
C.selected_style(box, selected, ic, label) # like the sidebar: the portal fade with a white icon
|
||||
return box
|
||||
|
||||
def _render_locations(self) -> None:
|
||||
rows = [self._location_row(loc_, SHARED_ICONS.get(loc_["id"], ft.Icons.FOLDER_OUTLINED), loc_["android"])
|
||||
@@ -279,16 +293,15 @@ class FilesView:
|
||||
for i, (label, p) in enumerate(crumbs(loc["path"], self.path, loc["label"])):
|
||||
if i:
|
||||
self.crumb_row.controls.append(ft.Icon(ft.Icons.CHEVRON_RIGHT_ROUNDED, size=T.px(16), color=T.TEXT_3))
|
||||
self.crumb_row.controls.append(ft.TextButton(label, on_click=lambda e, p=p: self.cd(p),
|
||||
style=ft.ButtonStyle(color=T.TEXT if p == self.path
|
||||
else T.TEXT_2)))
|
||||
self.crumb_row.controls.append(C.ghost(label, on_click=lambda e, p=p: self.cd(p),
|
||||
color=T.TEXT if p == self.path else T.TEXT_2))
|
||||
android = loc.get("android")
|
||||
rel = posixpath.relpath(self.path, loc["path"]) if self.path != loc["path"] else ""
|
||||
self.where.value = (tr("Games see this folder as {value}")
|
||||
.format(value=posixpath.join(android, rel) if rel else android)
|
||||
if android else self.path)
|
||||
rows = []
|
||||
self.checks = {}
|
||||
self.checks, self.rows, self.hot = {}, {}, set()
|
||||
if self.path != loc["path"]:
|
||||
rows.append(self._row(None))
|
||||
rows += [self._row(e) for e in self.entries]
|
||||
@@ -311,27 +324,34 @@ class FilesView:
|
||||
padding=ft.Padding(T.S3, T.px(8), T.S3, T.px(8)), border_radius=T.RADIUS_SM, ink=True,
|
||||
on_click=lambda ev: self.cd(posixpath.dirname(self.path)))
|
||||
when = time.strftime("%Y-%m-%d %H:%M", time.localtime(e.mtime)) if e.mtime else ""
|
||||
info = (("folder" if e.is_dir else human(e.size)) + (tr(" · link") if e.link else "")
|
||||
info = ((tr("folder") if e.is_dir else human(e.size)) + (tr(" · link") if e.link else "")
|
||||
+ (f" · {when}" if when else ""))
|
||||
actions = [C.icon_btn(ft.Icons.DOWNLOAD_ROUNDED, tr("Download to this PC"),
|
||||
actions = [C.icon_btn(ft.Icons.DOWNLOAD_ROUNDED, tr("Download to this PC…"),
|
||||
lambda ev, x=e: self._download_later([x]))]
|
||||
if not self._protected(e):
|
||||
actions += [C.icon_btn(ft.Icons.DRIVE_FILE_RENAME_OUTLINE_ROUNDED, tr("Rename"),
|
||||
actions += [C.icon_btn(ft.Icons.DRIVE_FILE_RENAME_OUTLINE_OUTLINED, tr("Rename…"),
|
||||
lambda ev, x=e: self.rename(x)),
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Delete"), lambda ev, x=e: self.delete([x]))]
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Delete…"), lambda ev, x=e: self.delete([x]))]
|
||||
check = ft.Checkbox(value=e.path in self.selected, active_color=T.ACCENT, check_color=T.ON_ACCENT,
|
||||
on_change=lambda ev, p=e.path: self._toggle(p, ev.control.value),
|
||||
disabled=self._protected(e))
|
||||
self.checks[e.path] = check
|
||||
# quiet rows: the checkbox and the actions show on hover, keyboard focus or when something is selected
|
||||
for c in (check, *actions):
|
||||
c.on_focus = lambda ev, p=e.path: self._focus(p, True)
|
||||
c.on_blur = lambda ev, p=e.path: self._focus(p, False)
|
||||
quiet_check, quiet_actions = C.quiet(check), C.quiet(*actions)
|
||||
row = ft.Container(
|
||||
ft.Row([check,
|
||||
ft.Row([quiet_check,
|
||||
ft.Icon(file_icon(e.name, e.is_dir), size=T.px(20), color=T.ACCENT if e.is_dir else T.TEXT_2),
|
||||
ft.Column([C.body(e.name, T.TEXT, weight=ft.FontWeight.W_500, max_lines=1,
|
||||
overflow=ft.TextOverflow.ELLIPSIS), C.meta(info)], spacing=0, expand=True),
|
||||
*actions], spacing=T.S3),
|
||||
quiet_actions], spacing=T.S3),
|
||||
padding=ft.Padding(T.S3, T.px(6), T.S2, T.px(6)), border_radius=T.RADIUS_SM, ink=e.is_dir,
|
||||
on_click=(lambda ev, p=e.path: self.cd(p)) if e.is_dir else None,
|
||||
on_hover=lambda ev, p=e.path: self.drag.hover(p, ev.data in (True, "true")))
|
||||
on_hover=lambda ev, p=e.path: self._hover(p, ev.data in (True, "true")))
|
||||
self.rows[e.path] = (row, quiet_check, quiet_actions)
|
||||
self._paint_row(e.path)
|
||||
return ft.GestureDetector(content=row, on_secondary_tap_down=lambda ev, x=e: self.open_menu(x,
|
||||
ev.global_position))
|
||||
|
||||
@@ -340,8 +360,8 @@ class FilesView:
|
||||
"""[(label, icon, handler) | None] for a right-click on entry `e` (None = on the folder's empty space). With
|
||||
several entries selected and `e` among them, the actions act on the whole selection."""
|
||||
if e is None:
|
||||
return [(tr("Upload files…"), ft.Icons.UPLOAD_FILE_ROUNDED, self.upload_files),
|
||||
(tr("Upload folder…"), ft.Icons.DRIVE_FOLDER_UPLOAD_ROUNDED, self.upload_folder),
|
||||
return [(tr("Upload files…"), ft.Icons.UPLOAD_FILE_OUTLINED, self.upload_files),
|
||||
(tr("Upload folder…"), ft.Icons.DRIVE_FOLDER_UPLOAD_OUTLINED, self.upload_folder),
|
||||
(tr("New folder…"), ft.Icons.CREATE_NEW_FOLDER_OUTLINED, lambda ev: self.new_folder()),
|
||||
None,
|
||||
*([(tr("Select all"), ft.Icons.SELECT_ALL_ROUNDED, lambda ev: self._select_all())]
|
||||
@@ -360,7 +380,7 @@ class FilesView:
|
||||
else tr("Download to this PC…"), ft.Icons.DOWNLOAD_ROUNDED,
|
||||
lambda ev: self._download_later(items)))
|
||||
if not several and not self._protected(e):
|
||||
out.append((tr("Rename…"), ft.Icons.DRIVE_FILE_RENAME_OUTLINE_ROUNDED, lambda ev: self.rename(e)))
|
||||
out.append((tr("Rename…"), ft.Icons.DRIVE_FILE_RENAME_OUTLINE_OUTLINED, lambda ev: self.rename(e)))
|
||||
if not several:
|
||||
out.append((tr("Copy path"), ft.Icons.CONTENT_COPY_ROUNDED, lambda ev: self.app.copy(self._shown_path(
|
||||
e.path))))
|
||||
@@ -408,8 +428,35 @@ class FilesView:
|
||||
if check is not None and check.value != on:
|
||||
check.value = on
|
||||
C.update(check)
|
||||
if self._paint_row(path):
|
||||
C.update(self.rows[path][0])
|
||||
self._update_selection()
|
||||
|
||||
# ---------------------------------------------------------------- quiet rows
|
||||
def _hover(self, path: str, inside: bool) -> None:
|
||||
self.drag.hover(path, inside)
|
||||
self._set_hot(path, inside)
|
||||
|
||||
def _focus(self, path: str, on: bool) -> None:
|
||||
self._set_hot(path, on)
|
||||
|
||||
def _set_hot(self, path: str, on: bool) -> None:
|
||||
(self.hot.add if on else self.hot.discard)(path)
|
||||
if path in self.rows and self._paint_row(path):
|
||||
C.update(self.rows[path][0])
|
||||
|
||||
def _paint_row(self, path: str) -> bool:
|
||||
"""Properties only: the selected look and whether the checkbox/actions show. True when something changed."""
|
||||
row, quiet_check, quiet_actions = self.rows[path]
|
||||
on = path in self.selected
|
||||
before = (row.bgcolor, row.gradient is not None)
|
||||
C.selected_style(row, on)
|
||||
changed = before != (row.bgcolor, row.gradient is not None)
|
||||
show = on or path in self.hot or bool(self.selected)
|
||||
changed |= C.reveal(quiet_check, show)
|
||||
changed |= C.reveal(quiet_actions, on or path in self.hot)
|
||||
return changed
|
||||
|
||||
def _toggle_all(self, e) -> None:
|
||||
self.selected = {x.path for x in self.entries if self._selectable(x)} if e.control.value else set()
|
||||
self._render_listing()
|
||||
@@ -435,6 +482,11 @@ class FilesView:
|
||||
self.sel_label.value = (tr("{n} selected").format(n=n)
|
||||
+ (tr(" · {human} in files").format(human=human(size)) if size else ""))
|
||||
self.sel_bar.visible = bool(n)
|
||||
if bool(n) != self._select_mode: # select mode starts/ends: every row's checkbox shows/hides
|
||||
self._select_mode = bool(n)
|
||||
changed = [path for path in self.rows if self._paint_row(path)]
|
||||
if render and changed:
|
||||
C.update(self.listing)
|
||||
self.select_all.value = bool(self.entries) and n == len([x for x in self.entries if self._selectable(x)])
|
||||
if render:
|
||||
for c in (self.sel_bar, self.select_all):
|
||||
@@ -509,7 +561,7 @@ class FilesView:
|
||||
|
||||
def delete(self, items: list) -> None:
|
||||
names = ", ".join(x.name for x in items[:3]) + (" …" if len(items) > 3 else "")
|
||||
what = tr("folder and everything in it") if any(x.is_dir for x in items) else "file"
|
||||
what = tr("folder and everything in it") if any(x.is_dir for x in items) else tr("file")
|
||||
C.confirm(self.app.page, tr("Delete {names}?").format(names=names),
|
||||
tr("This deletes the {what} on the Frame. It can't be undone.").format(what=what),
|
||||
tr("Delete"), lambda: (self.selected.difference_update(x.path for x in items),
|
||||
@@ -531,14 +583,12 @@ class FilesView:
|
||||
|
||||
def _ask_name(self, heading: str, label: str, value: str, ok: str, on_ok) -> None:
|
||||
page = self.app.page
|
||||
field = ft.TextField(label=label, value=value, autofocus=True, width=T.px(380))
|
||||
field = C.field(label=label, value=value, autofocus=True, width=T.DIALOG_S)
|
||||
|
||||
def go(e=None):
|
||||
page.pop_dialog()
|
||||
if (field.value or "").strip():
|
||||
on_ok(field.value.strip())
|
||||
field.on_submit = go
|
||||
page.show_dialog(ft.AlertDialog(title=ft.Text(heading, color=T.TEXT, weight=ft.FontWeight.W_600),
|
||||
bgcolor=T.SURFACE_2, content=field,
|
||||
actions=[C.ghost(tr("Cancel"), on_click=lambda e: page.pop_dialog()),
|
||||
C.primary(ok, on_click=go)]))
|
||||
page.show_dialog(C.dialog(heading, field, [C.ghost(tr("Cancel"), on_click=lambda e: page.pop_dialog()),
|
||||
C.primary(ok, on_click=go)], size="s"))
|
||||
@@ -96,14 +96,11 @@ def human(n: int) -> str:
|
||||
|
||||
def show_files_dialog(app: FramePortApp, package: str, title: str) -> None:
|
||||
status = C.meta(tr("Reading the file list from the Frame…"))
|
||||
ring = ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2), color=T.ACCENT)
|
||||
ring = C.spinner()
|
||||
body = ft.Column([ft.Row([ring, status],
|
||||
spacing=T.S2)], spacing=T.S3, expand=True)
|
||||
dialog = ft.AlertDialog(
|
||||
title=ft.Text(tr("Files on the Frame — {title}").format(title=title), weight=ft.FontWeight.W_600),
|
||||
content=ft.Container(body, width=T.px(760), height=T.px(560)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
actions=[C.ghost(tr("Close"), on_click=lambda e: app.page.pop_dialog())])
|
||||
dialog = C.dialog(tr("Files on the Frame — {title}").format(title=title), body,
|
||||
[C.ghost(tr("Close"), on_click=lambda e: app.page.pop_dialog())], size="l", height=T.px(560))
|
||||
app.page.show_dialog(dialog)
|
||||
|
||||
def load():
|
||||
@@ -113,19 +110,15 @@ def show_files_dialog(app: FramePortApp, package: str, title: str) -> None:
|
||||
trees = [(r, build_tree(r["name"], r["files"])) for r in result["roots"]]
|
||||
expanded: set[str] = set()
|
||||
rows = ft.ListView(spacing=0, expand=True)
|
||||
search = ft.TextField(hint_text=tr("Filter files (e.g. .pak, Binaries)"), dense=True, expand=True,
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3, border_color=ft.Colors.TRANSPARENT,
|
||||
focused_border_color=T.ACCENT,
|
||||
content_padding=ft.Padding(T.px(12), T.px(8), T.px(12), T.px(8)),
|
||||
text_size=T.T_BODY, prefix_icon=ft.Icons.SEARCH_ROUNDED)
|
||||
search = C.search(hint_text=tr("Filter files (for example .pak, Binaries)"), expand=True)
|
||||
|
||||
def row(depth: int, node: Node | int, root_key: str) -> ft.Control:
|
||||
pad = ft.Padding(8 + depth * 18, T.px(3), T.px(8), T.px(3))
|
||||
pad = ft.Padding(T.px(8 + depth * 18), T.px(3), T.px(8), T.px(3))
|
||||
if isinstance(node, int):
|
||||
return ft.Container(C.meta(tr("… {node} more (use the filter to find them)").format(node=node)),
|
||||
padding=pad)
|
||||
key = f"{root_key}\0{node.path}"
|
||||
icon = (ft.Icons.FOLDER_OPEN_ROUNDED if key in expanded else ft.Icons.FOLDER_ROUNDED) if node.is_dir \
|
||||
icon = (ft.Icons.FOLDER_OPEN_ROUNDED if key in expanded else ft.Icons.FOLDER_OUTLINED) if node.is_dir \
|
||||
else ft.Icons.INSERT_DRIVE_FILE_OUTLINED
|
||||
chevron = ft.Icon(ft.Icons.EXPAND_MORE_ROUNDED if key in expanded else ft.Icons.CHEVRON_RIGHT_ROUNDED,
|
||||
size=T.px(16), color=T.TEXT_3) if node.is_dir else ft.Container(width=T.px(16))
|
||||
@@ -138,7 +131,7 @@ def show_files_dialog(app: FramePortApp, package: str, title: str) -> None:
|
||||
ft.Container(C.meta(note, T.TEXT_3, no_wrap=True, overflow=ft.TextOverflow.ELLIPSIS),
|
||||
tooltip=note or None, expand=True),
|
||||
C.meta(info),
|
||||
], spacing=T.px(6)), padding=pad, border_radius=T.px(6), ink=node.is_dir,
|
||||
], spacing=T.px(6)), padding=pad, border_radius=T.RADIUS_XS, ink=node.is_dir,
|
||||
on_click=(lambda e, k=key: toggle(k)) if node.is_dir else None)
|
||||
|
||||
def render():
|
||||
|
||||
@@ -10,6 +10,7 @@ from ...core import library
|
||||
from ...errors import explain
|
||||
from ...i18n import tr, tr_n
|
||||
from .. import components as C
|
||||
from .. import glyphs as G
|
||||
from .. import theme as T
|
||||
from ..battery import label as battery_label
|
||||
from ..help import HELP
|
||||
@@ -28,11 +29,11 @@ class FrameView:
|
||||
t = app.target
|
||||
free = (info.get("free_bytes") or 0) / 2**30
|
||||
return C.card(ft.Row([
|
||||
ft.Container(ft.Icon(ft.Icons.VIEW_IN_AR_ROUNDED, size=T.px(34), color=T.ACCENT), width=T.px(72),
|
||||
height=T.px(72), border_radius=T.px(18), bgcolor=T.ACCENT_SOFT, alignment=ft.Alignment.CENTER),
|
||||
ft.Container(C.as_icon(G.FRAME, T.px(34), T.ACCENT), width=T.px(72),
|
||||
height=T.px(72), border_radius=T.RADIUS, bgcolor=T.ACCENT_SOFT, alignment=ft.Alignment.CENTER),
|
||||
ft.Column([
|
||||
ft.Row([C.title(info.get("hostname") or t.label, 22), C.pill(tr("Connected"), T.OK, ft.Icons.CIRCLE)],
|
||||
spacing=T.S3),
|
||||
ft.Row([C.title(info.get("hostname") or t.label, T.T_DISPLAY),
|
||||
C.pill(tr("Connected"), T.OK, ft.Icons.CIRCLE)], spacing=T.S3),
|
||||
C.body(tr("{user}@{host} · {get} {get2} (build {get3})")
|
||||
.format(user=t.target.user, host=t.target.host, get=info.get('os'),
|
||||
get2=info.get('os_version'), get3=info.get('build_id'))),
|
||||
@@ -43,45 +44,78 @@ class FrameView:
|
||||
], spacing=T.px(4), expand=True),
|
||||
ft.Column([
|
||||
C.secondary(tr("Refresh"), ft.Icons.REFRESH_ROUNDED, lambda e: app.refresh_frame()),
|
||||
C.secondary(tr("Type on Frame"), ft.Icons.KEYBOARD_ROUNDED, lambda e: app.type_on_frame(),
|
||||
tooltip=tr("Use this computer's keyboard on the Frame")),
|
||||
C.ghost(tr("Switch Frame…"), ft.Icons.SWAP_HORIZ_ROUNDED, lambda e: app.disconnect()),
|
||||
C.secondary(tr("Type on Frame"), G.KEYS, lambda e: app.type_on_frame(),
|
||||
tooltip=tr("Use this PC's keyboard on the Frame")),
|
||||
C.ghost(tr("Switch Frame…"), ft.Icons.SWAP_HORIZ_ROUNDED, lambda e: self.switch_frame()),
|
||||
C.ghost(tr("Disconnect"), ft.Icons.LINK_OFF_ROUNDED, lambda e: app.disconnect()),
|
||||
], spacing=T.S2, horizontal_alignment=ft.CrossAxisAlignment.END),
|
||||
], spacing=T.S4), padding=T.S5)
|
||||
|
||||
def switch_frame(self) -> None:
|
||||
"""A small picker of the remembered Frames (click one to connect), or "Find another Frame…" = the setup and
|
||||
discovery page."""
|
||||
from ...frame.connection import saved_targets
|
||||
|
||||
app = self.app
|
||||
page = app.page
|
||||
current = getattr(getattr(app.target, "target", None), "host", None)
|
||||
|
||||
def pick(target):
|
||||
page.pop_dialog()
|
||||
app.connect(target)
|
||||
|
||||
def find(e):
|
||||
page.pop_dialog()
|
||||
app.disconnect()
|
||||
rows = []
|
||||
for f in saved_targets():
|
||||
here = f.host == current
|
||||
rows.append(ft.Container(ft.Row([
|
||||
C.as_icon(G.FRAME, T.px(22), T.ACCENT),
|
||||
ft.Column([C.body(f.label, T.TEXT, weight=ft.FontWeight.W_500),
|
||||
C.meta(f"{f.user}@{f.host}")], spacing=T.px(2), expand=True),
|
||||
C.pill(tr("Connected"), T.OK, ft.Icons.CIRCLE) if here else
|
||||
C.secondary(tr("Connect"), on_click=lambda e, f=f: pick(f)),
|
||||
], spacing=T.S3), padding=ft.Padding(T.S3, T.px(8), T.S2, T.px(8)), bgcolor=T.SURFACE_3,
|
||||
border_radius=T.RADIUS_SM))
|
||||
if not rows:
|
||||
rows = [C.body(tr("No other Frames remembered yet."))]
|
||||
page.show_dialog(C.dialog(
|
||||
tr("Switch Frame"), ft.Column(rows, spacing=T.S2, tight=True, scroll=ft.ScrollMode.AUTO),
|
||||
[C.ghost(tr("Cancel"), on_click=lambda e: page.pop_dialog()),
|
||||
C.secondary(tr("Find another Frame…"), ft.Icons.SEARCH_ROUNDED, find)], size="s"))
|
||||
|
||||
def readiness(self, info: dict) -> ft.Control:
|
||||
app = self.app
|
||||
rows = []
|
||||
items = []
|
||||
lepton = info.get("lepton")
|
||||
rows.append(C.status_row(bool(lepton), tr("Quest games (Lepton)"),
|
||||
tr("Ready") if lepton
|
||||
else tr("Valve's Android runtime isn't installed (needs Developer Mode)"),
|
||||
None if lepton else C.secondary(tr("Install"), ft.Icons.DOWNLOAD_ROUNDED,
|
||||
lambda e: app.install_lepton()),
|
||||
help="lepton"))
|
||||
items.append(C.Check(bool(lepton), tr("Quest games (Lepton)"),
|
||||
tr("Ready") if lepton
|
||||
else tr("Valve's Android runtime isn't installed (needs Developer Mode)"),
|
||||
"lepton", (tr("Install"), ft.Icons.DOWNLOAD_ROUNDED, app.install_lepton)))
|
||||
pr = info.get("proton") or {}
|
||||
ready, sug = pr.get("ready"), pr.get("suggested")
|
||||
if pr:
|
||||
rows.append(C.status_row(
|
||||
items.append(C.Check(
|
||||
bool(ready), tr("PC VR games (Proton)"),
|
||||
tr("{display_name} installed").format(display_name=ready['display_name']) if ready else
|
||||
(tr("{display_name} can be installed (about 1 GiB; Steam restarts once)")
|
||||
.format(display_name=sug['display_name']) if sug else
|
||||
tr("Not offered by Steam on this Frame yet")),
|
||||
C.secondary(tr("Test"), ft.Icons.SCIENCE_OUTLINED, lambda e: app.test_proton()) if ready else
|
||||
C.primary(tr("Install"), ft.Icons.DOWNLOAD_ROUNDED, lambda e: app.install_proton(), disabled=not sug),
|
||||
help="proton"))
|
||||
"proton", (tr("Install…"), ft.Icons.DOWNLOAD_ROUNDED, app.install_proton) if sug else None,
|
||||
C.secondary(tr("Test"), G.TEST, lambda e: app.test_proton()) if ready else None))
|
||||
xr = (pr.get("openxr") or {}).get("name")
|
||||
rows.append(C.status_row(bool(xr), tr("OpenXR runtime"), xr or tr("None found"), help="openxr"))
|
||||
items.append(C.Check(bool(xr), tr("OpenXR runtime"), xr or tr("None found"), "openxr"))
|
||||
keys = info.get("kernel_keys") or {}
|
||||
if keys.get("max_keys"):
|
||||
high = keys["keys"] > keys["max_keys"] * 0.75
|
||||
rows.append(C.status_row(not high if keys["keys"] < keys["max_keys"] else False, tr("Game launch capacity"),
|
||||
f"{keys['keys']}/{keys['max_keys']} kernel keys used"
|
||||
+ (tr(" · restart the Frame soon to reset it") if high else ""),
|
||||
help="kernel_keys"))
|
||||
return C.section(tr("Ready to play"), C.card(ft.Column(rows, spacing=0),
|
||||
padding=ft.Padding(T.S4, T.S2, T.S4, T.S2)))
|
||||
items.append(C.Check(not high if keys["keys"] < keys["max_keys"] else False, tr("Game launch capacity"),
|
||||
tr("{used}/{max} kernel keys used").format(used=keys["keys"], max=keys["max_keys"])
|
||||
+ (tr(" · restart the Frame soon to reset it") if high else ""),
|
||||
"kernel_keys",
|
||||
(tr("Restart the Frame…"), ft.Icons.RESTART_ALT_ROUNDED,
|
||||
lambda: app.frame_power("restart"))))
|
||||
return C.section(tr("Ready to play"), C.card(C.checklist(items), padding=ft.Padding(T.S4, T.S2, T.S4, T.S2)))
|
||||
|
||||
def storage(self, info: dict) -> ft.Control:
|
||||
"""Drives games can go on (GitHub #90) and where new games go. The list comes from the Frame in the
|
||||
@@ -90,9 +124,9 @@ class FrameView:
|
||||
|
||||
app = self.app
|
||||
current = drives.install_dest()
|
||||
pick = ft.Dropdown(label=tr("Install new games to"), value=current or drives.INTERNAL, width=T.px(380),
|
||||
dense=True, border_color=T.BORDER, text_size=T.T_BODY, disabled=True,
|
||||
options=[ft.DropdownOption(key=drives.INTERNAL, text=tr("Internal storage"))])
|
||||
pick = C.dropdown(label=tr("Install new games to"), value=current or drives.INTERNAL, width=T.px(380),
|
||||
dense=True, text_size=T.T_BODY, disabled=True,
|
||||
options=[ft.DropdownOption(key=drives.INTERNAL, text=tr("Internal storage"))])
|
||||
rows = ft.Column([C.meta(tr("Looking for drives…"))], spacing=T.px(6))
|
||||
|
||||
def choose(e):
|
||||
@@ -122,7 +156,7 @@ class FrameView:
|
||||
state = tr_n("{n} game", "{n} games", d.get("games", 0)) if d.get("usable") else \
|
||||
tr("can't hold games: {reason}").format(reason=d.get("reason") or "")
|
||||
lines.append(ft.Row([
|
||||
ft.Icon(ft.Icons.SD_CARD_ROUNDED if d.get("removable") else ft.Icons.STORAGE_ROUNDED,
|
||||
ft.Icon(ft.Icons.SD_CARD_ROUNDED if d.get("removable") else ft.Icons.STORAGE_OUTLINED,
|
||||
size=T.px(18), color=T.TEXT_2 if d.get("usable") else T.TEXT_3),
|
||||
C.body(name(d), T.TEXT if d.get("usable") else T.TEXT_3, expand=True),
|
||||
C.meta(" · ".join(filter(None, [d.get("fstype"), free, state]))),
|
||||
@@ -152,7 +186,7 @@ class FrameView:
|
||||
send = C.ghost(tr("Files"), ft.Icons.FOLDER_OPEN_ROUNDED, lambda e: self.app.go("files"),
|
||||
tooltip=C.tip(HELP["files"]))
|
||||
return C.section(tr("Installed games ({len})").format(len=len(items)), body,
|
||||
action=ft.Row([send, C.ghost(tr("Free up space"), ft.Icons.CLEANING_SERVICES_ROUNDED,
|
||||
action=ft.Row([send, C.ghost(tr("Free up space…"), ft.Icons.CLEANING_SERVICES_OUTLINED,
|
||||
lambda e: self.app.cleanup_frame(),
|
||||
tooltip=C.tip(HELP["free_space"]))], spacing=T.S2, tight=True)
|
||||
if items else send)
|
||||
@@ -186,7 +220,7 @@ class FrameView:
|
||||
sub += C.drive_note(drive_of(d))
|
||||
title = display_title(games[pkg], tw) if in_lib else (d.get("title") or pkg)
|
||||
rows.append(ft.Container(ft.Row([
|
||||
C.art_fill(art, radius=T.px(8), width=T.px(44), height=T.px(44)),
|
||||
C.art_fill(art, radius=T.RADIUS_SM, width=T.px(44), height=T.px(44)),
|
||||
ft.Column([C.body(title, T.TEXT, weight=ft.FontWeight.W_500), C.meta(sub)],
|
||||
spacing=T.px(2), expand=True),
|
||||
# same slots on every row: games without settings (PC VR, 2D apps) get an invisible spacer
|
||||
@@ -197,7 +231,7 @@ class FrameView:
|
||||
lambda e, p=pkg, t=title: show_files_dialog(app, p, t)),
|
||||
C.icon_btn(ft.Icons.PLAY_ARROW_ROUNDED, tr("Play: starts the game through the Frame's Steam (put the "
|
||||
"headset on)"), lambda e, p=pkg: app.play(p, "frame"), color=T.ACCENT),
|
||||
C.icon_btn(ft.Icons.SCIENCE_OUTLINED, C.tip(tr("Launch test. ") + HELP["launch_test"]),
|
||||
C.icon_btn(G.TEST, C.tip(tr("Launch test. ") + HELP["launch_test"]),
|
||||
lambda e, p=pkg: app.test_game(p, "frame")),
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, C.tip(tr("Uninstall. ") + HELP["uninstall"]),
|
||||
lambda e, p=pkg: app.uninstall(p, "frame")),
|
||||
@@ -213,7 +247,7 @@ class FrameView:
|
||||
|
||||
app = self.app
|
||||
found = ft.Column(spacing=T.S2)
|
||||
searching = ft.Row([ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2), color=T.ACCENT),
|
||||
searching = ft.Row([C.spinner(),
|
||||
C.meta(tr("Looking for Frames on your network…"))], spacing=T.S2)
|
||||
|
||||
def discover():
|
||||
@@ -224,20 +258,20 @@ class FrameView:
|
||||
res = browse(4)
|
||||
items = []
|
||||
for f in res:
|
||||
label = {"devkit": "SteamOS · Developer Mode", "frameport": "Set up for FramePort",
|
||||
"saved": "Remembered", "scan": "SSH found by network scan"}.get(f.source, f.source)
|
||||
label = {"devkit": tr("SteamOS · Developer Mode"), "frameport": tr("Set up for FramePort"),
|
||||
"saved": tr("Remembered"), "scan": tr("SSH found by network scan")}.get(f.source, f.source)
|
||||
items.append(ft.Container(ft.Row([
|
||||
ft.Icon(ft.Icons.VIEW_IN_AR_ROUNDED if f.source != "scan" else ft.Icons.DEVICES_OTHER_ROUNDED,
|
||||
color=T.ACCENT),
|
||||
C.as_icon(G.FRAME if f.source != "scan" else ft.Icons.DEVICES_OTHER_ROUNDED, T.px(24), T.ACCENT),
|
||||
ft.Column([C.body(f.name if f.source != "scan" else f.host, T.TEXT, weight=ft.FontWeight.W_500),
|
||||
C.meta(f"{f.host} · {label}")], spacing=T.px(2), expand=True),
|
||||
C.primary(tr("Connect"), on_click=lambda e, f=f: app.connect(parse_target(f"{f.user}@{f.host}"),
|
||||
devkit=f.source == "devkit")),
|
||||
], spacing=T.S3), padding=ft.Padding(T.S3, T.px(8), T.S2, T.px(8)), bgcolor=T.SURFACE_2,
|
||||
border_radius=T.RADIUS_SM))
|
||||
found.controls = items or [C.body(tr("No Frames found. New Frame? Use first-time setup (step 1). Otherwise "
|
||||
"make sure Developer Mode is on (Settings → System → Developer) and "
|
||||
"the Frame is on the same network."))]
|
||||
found.controls = items or [ft.Row([C.body(tr("No Frames found. New Frame? Use first-time setup (step "
|
||||
"1). Otherwise turn on Developer Mode and keep the Frame on "
|
||||
"the same network."), expand=True),
|
||||
C.help_icon("developer_mode")], spacing=T.px(4))]
|
||||
found.controls.append(C.ghost(tr("Search again"), ft.Icons.REFRESH_ROUNDED, lambda e: app.run_bg(discover)))
|
||||
C.update(found)
|
||||
|
||||
@@ -267,7 +301,7 @@ class FrameView:
|
||||
if server.requests or not server.running or app.pairing is not server:
|
||||
return
|
||||
server.hint = firewall_hint(server.port) or tr(
|
||||
"Check that the Frame and this computer are on the same network.")
|
||||
"Check that the Frame and this PC are on the same network.")
|
||||
if app.route[0] == "frame" and app.pairing is server:
|
||||
show_command()
|
||||
app.run_bg(check_network)
|
||||
@@ -286,12 +320,12 @@ class FrameView:
|
||||
tr("On the Frame, open Steam's Settings (Steam button → Settings)."),
|
||||
tr("Go to System and turn on \"Enable Developer Mode\". A Developer page appears in Settings; nothing "
|
||||
"else changes, your games and data stay as they are."),
|
||||
tr("Connect the Frame's USB-C port to this computer with a USB cable (a data cable, not a charge-only "
|
||||
tr("Connect the Frame's USB-C port to this PC with a USB cable (a data cable, not a charge-only "
|
||||
"one)."),
|
||||
]
|
||||
dlg = ft.AlertDialog(
|
||||
title=ft.Text(tr("Turn on Developer Mode first"), weight=ft.FontWeight.W_600),
|
||||
content=ft.Container(ft.Column([
|
||||
dlg = C.dialog(
|
||||
tr("Turn on Developer Mode first"),
|
||||
ft.Column([
|
||||
C.body(tr("The Frame only offers its USB connection in Developer Mode:"), T.TEXT),
|
||||
*[ft.Row([ft.Container(ft.Text(str(i), weight=ft.FontWeight.W_700, color=T.ACCENT),
|
||||
width=T.px(24), height=T.px(24), border_radius=T.px(12),
|
||||
@@ -300,8 +334,7 @@ class FrameView:
|
||||
vertical_alignment=ft.CrossAxisAlignment.START)
|
||||
for i, text in enumerate(steps, 1)],
|
||||
C.meta(tr("FramePort then finds the Frame on the cable by itself.")),
|
||||
], spacing=T.S3, tight=True), width=T.px(480)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
], spacing=T.S3, tight=True), size="s",
|
||||
actions=[C.ghost(tr("Cancel"), on_click=lambda ev: close()),
|
||||
C.primary(tr("Done: look for the cable"), ft.Icons.USB_ROUNDED, go)])
|
||||
app.page.show_dialog(dlg)
|
||||
@@ -313,11 +346,11 @@ class FrameView:
|
||||
from ...frame import usb
|
||||
from ...frame.connection import FrameTarget, server_key
|
||||
|
||||
status = ft.Row([ft.ProgressRing(width=T.px(14), height=T.px(14), stroke_width=T.px(2), color=T.ACCENT),
|
||||
status = ft.Row([C.spinner(),
|
||||
C.meta(tr("Waiting for the cable…"))], spacing=T.S2)
|
||||
pair_box.controls = [
|
||||
C.body(tr("Looking for the Frame on a USB cable (Developer Mode on, USB-C port connected to this "
|
||||
"computer)."), T.TEXT),
|
||||
"PC)."), T.TEXT),
|
||||
status,
|
||||
]
|
||||
C.update(pair_box)
|
||||
@@ -356,7 +389,7 @@ class FrameView:
|
||||
over_usb = bool(getattr(app.pairing, "host", ""))
|
||||
pair_box.controls = [
|
||||
C.body(tr("On the Frame: SteamVR dashboard → Launch a program → Desktop, then app menu → System → "
|
||||
"Konsole, and run (it reaches this computer over the USB cable):") if over_usb else
|
||||
"Konsole, and run (it reaches this PC over the USB cable):") if over_usb else
|
||||
tr("On the Frame: SteamVR dashboard → Launch a program → Desktop, then app menu → System → "
|
||||
"Konsole, and run:"), T.TEXT),
|
||||
ft.Container(ft.Row([ft.Text(line, font_family="monospace", selectable=True, size=T.px(12),
|
||||
@@ -364,12 +397,11 @@ class FrameView:
|
||||
C.icon_btn(ft.Icons.CONTENT_COPY_ROUNDED, tr("Copy"), lambda e: app.copy(line))]),
|
||||
padding=ft.Padding(T.S3, T.S2, T.S2, T.S2), bgcolor=T.BG, border_radius=T.RADIUS_SM,
|
||||
border=ft.Border.all(1, T.BORDER)),
|
||||
ft.Row([ft.ProgressRing(width=T.px(14), height=T.px(14), stroke_width=T.px(2), color=T.ACCENT),
|
||||
ft.Row([C.spinner(),
|
||||
C.meta(tr("Waiting for your Frame… (code {code})").format(code=app.pairing.code))],
|
||||
spacing=T.S2),
|
||||
C.meta(tr("It trusts this app, turns on Developer Mode and installs Lepton if needed. Turning on "
|
||||
"Developer Mode closes the desktop; the setup finishes on its own and FramePort connects "
|
||||
"by itself. You only do this once.")),
|
||||
ft.Row([C.meta(tr("You only do this once: FramePort connects by itself when the setup has finished."),
|
||||
expand=True), C.help_icon("first_time_setup")], spacing=T.px(4)),
|
||||
]
|
||||
hint = getattr(app.pairing, "hint", "")
|
||||
if hint and not app.pairing.requests: # nothing reached us yet: what may block it, and the other way in
|
||||
@@ -377,9 +409,9 @@ class FrameView:
|
||||
C.body(tr("Nothing has reached FramePort from the Frame yet (curl says “timed out”)?"), T.TEXT,
|
||||
weight=ft.FontWeight.W_600),
|
||||
C.body(hint, T.TEXT),
|
||||
C.meta(tr("Or turn on Developer Mode on the Frame (Settings → System → Developer): it then shows "
|
||||
"up under step 2. Open Settings → Developer → Pair new host on the Frame, click Connect "
|
||||
"there and approve FramePort. That way needs no connection into this computer.")),
|
||||
ft.Row([C.meta(tr("Or turn on Developer Mode on the Frame (Settings → System → Enable Developer "
|
||||
"Mode) and pair it under step 2: that needs no connection into this PC."),
|
||||
expand=True), C.help_icon("developer_mode")], spacing=T.px(4)),
|
||||
], spacing=T.S2), "warn"))
|
||||
if update:
|
||||
C.update(pair_box) # (a redraw of the page may have replaced it)
|
||||
@@ -387,12 +419,9 @@ class FrameView:
|
||||
if app.pairing and app.pairing.running:
|
||||
show_command(update=False)
|
||||
|
||||
style = dict(dense=True, border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3, border_color=ft.Colors.TRANSPARENT,
|
||||
focused_border_color=T.ACCENT, content_padding=ft.Padding(T.px(12), T.px(10), T.px(12), T.px(10)),
|
||||
text_size=T.T_BODY)
|
||||
addr = ft.TextField(hint_text=tr("steamos@frame.local or an IP address"), width=T.px(320), **style)
|
||||
pw = ft.TextField(hint_text=tr("Password (first time only)"), password=True, can_reveal_password=True,
|
||||
width=T.px(240), tooltip=C.tip(HELP["password"]), **style)
|
||||
addr = C.field(hint_text=tr("steamos@frame.local or an IP address"), width=T.px(320))
|
||||
pw = C.field(hint_text=tr("Password (first time only)"), password=True, can_reveal_password=True,
|
||||
width=T.px(240), tooltip=C.tip(HELP["password"]))
|
||||
saved = saved_targets()
|
||||
offline = None
|
||||
if getattr(app, "_not_paired", False): # it answered, but doesn't know FramePort yet
|
||||
@@ -407,9 +436,8 @@ class FrameView:
|
||||
C.secondary(tr("Try again"), ft.Icons.REFRESH_ROUNDED,
|
||||
lambda e: app.connect(saved[0]))]), "warn")
|
||||
elif app.frame_state == "connecting":
|
||||
connecting = tr("Connecting to {value}…").format(value=saved[0].label if saved else 'your Frame')
|
||||
offline = C.callout(ft.Row([ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2),
|
||||
color=T.ACCENT),
|
||||
connecting = tr("Connecting to {value}…").format(value=saved[0].label if saved else tr("your Frame"))
|
||||
offline = C.callout(ft.Row([C.spinner(),
|
||||
C.body(connecting, T.TEXT)],
|
||||
spacing=T.S3), "info")
|
||||
import time as _time
|
||||
|
||||
@@ -16,6 +16,7 @@ from ...i18n import tr, tr_n
|
||||
from ...patches import base
|
||||
from ...recommend import catalog, engine
|
||||
from .. import components as C
|
||||
from .. import glyphs as G
|
||||
from .. import theme as T
|
||||
from ..help import HELP
|
||||
|
||||
@@ -93,13 +94,15 @@ class GameView:
|
||||
if self.rift and pkg in app.pc_installs():
|
||||
chips.append(C.install_badge("on_pc"))
|
||||
actions = self.actions()
|
||||
return ft.Container(
|
||||
self._wash = ft.Container(left=0, right=0, top=0, bottom=0, border_radius=T.RADIUS) # cover tint (_tint)
|
||||
self._hero = ft.Container(
|
||||
ft.Stack([
|
||||
C.art_fill(art, radius=T.px(16), hero=True, left=0, right=0, top=0, bottom=0,
|
||||
C.art_fill(art, radius=T.RADIUS, hero=True, left=0, right=0, top=0, bottom=0,
|
||||
placeholder_icon=C.platform_icon(g)),
|
||||
ft.Container(left=0, right=0, top=0, bottom=0, border_radius=T.px(16), gradient=ft.LinearGradient(
|
||||
ft.Container(left=0, right=0, top=0, bottom=0, border_radius=T.RADIUS, gradient=ft.LinearGradient(
|
||||
begin=ft.Alignment.CENTER_LEFT, end=ft.Alignment.CENTER_RIGHT,
|
||||
colors=[T.soft(T.BG, 0.97), T.soft(T.BG, 0.80), T.soft(T.BG, 0.25)], stops=[0.0, 0.45, 1.0])),
|
||||
self._wash,
|
||||
ft.Container(ft.Row([
|
||||
ft.Column([
|
||||
C.ghost(tr("Library"), ft.Icons.ARROW_BACK_ROUNDED, lambda e: app.go("library")),
|
||||
@@ -113,26 +116,52 @@ class GameView:
|
||||
], spacing=T.S2, expand=True),
|
||||
]), padding=ft.Padding(T.S4, T.S3, T.S5, T.S5), left=0, right=0, top=0, bottom=0),
|
||||
]),
|
||||
height=T.px(330), border_radius=T.px(16), border=ft.Border.all(1, T.BORDER))
|
||||
height=T.px(330), border_radius=T.RADIUS, border=ft.Border.all(1, T.BORDER))
|
||||
return self._hero
|
||||
|
||||
def _tint(self, tint: str | None) -> None:
|
||||
"""The cover's colour (thumbs.compute_tint, already clamped dark): a soft glow around and inside the hero and
|
||||
a very faint wash at the top of the page. Properties only, so it can arrive after the page is on screen."""
|
||||
if not tint:
|
||||
return
|
||||
self._hero.shadow = ft.BoxShadow(blur_radius=T.px(90), spread_radius=0, color=T.soft(tint, 0.18),
|
||||
offset=ft.Offset(0, T.px(10)))
|
||||
# from the lower left, behind the title and buttons (dark enough there for the text: ≤ 0.18 on the BG fade)
|
||||
self._wash.gradient = ft.RadialGradient(center=ft.Alignment(-0.7, 1.0), radius=1.3,
|
||||
colors=[T.soft(tint, 0.18), T.soft(tint, 0.0)])
|
||||
self._backdrop.gradient = ft.LinearGradient(begin=ft.Alignment.TOP_CENTER, end=ft.Alignment.BOTTOM_CENTER,
|
||||
colors=[T.soft(tint, 0.08), T.soft(tint, 0.0)])
|
||||
|
||||
def _fill_tint(self) -> None:
|
||||
"""Background thread: compute a missing tint, then colour this page if it is still the one shown."""
|
||||
tint = thumbs.compute_tint(self.package)
|
||||
app = self.app
|
||||
if tint and app.route[0] == "game" and app.route[1:2] == (self.package,) and app.game_view is self:
|
||||
self._tint(tint)
|
||||
C.update(self._hero, self._backdrop)
|
||||
|
||||
def actions(self) -> ft.Control:
|
||||
app, g, pkg = self.app, self.g, self.package
|
||||
job = app.jobs.busy_with(pkg)
|
||||
if job:
|
||||
pct = (f" {job.fraction:.0%}" if job.fraction is not None else "") + \
|
||||
(f" · {job.speed.split(' · ')[0]}" if job.speed else "")
|
||||
# the install as a transit: the game crossing the portal; app._on_job updates it on every tick
|
||||
transit = C.Transit()
|
||||
transit.set(job, **app.transit_info(job))
|
||||
app.hero_transit = (pkg, transit)
|
||||
return ft.Row([
|
||||
ft.FilledButton(content=ft.Row([ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2),
|
||||
color=T.ON_ACCENT),
|
||||
ft.Text(f"{job.stage or 'Queued'}{pct}", color=T.ON_ACCENT,
|
||||
weight=ft.FontWeight.W_600)], spacing=T.px(10), tight=True),
|
||||
on_click=lambda e: app.show_activity(True),
|
||||
style=ft.ButtonStyle(bgcolor=T.ACCENT, shape=ft.RoundedRectangleBorder(radius=T.px(8)),
|
||||
padding=ft.Padding(T.px(22), T.px(18), T.px(22), T.px(18)))),
|
||||
ft.Container(transit.control, width=T.px(460), padding=ft.Padding(T.S4, T.S3, T.S4, T.S3),
|
||||
bgcolor=T.soft(T.SURFACE, 0.92), border=ft.Border.all(1, T.BORDER),
|
||||
border_radius=T.RADIUS_SM, ink=True, tooltip=tr("Activity"),
|
||||
on_click=lambda e: app.show_activity(True)),
|
||||
C.ghost(tr("Cancel"), ft.Icons.CLOSE_ROUNDED, lambda e: app.jobs.cancel(job)),
|
||||
], spacing=T.S2)
|
||||
], spacing=T.S2, vertical_alignment=ft.CrossAxisAlignment.END)
|
||||
app.hero_transit = None
|
||||
buttons: list[ft.Control] = []
|
||||
for i, (label, icon, handler, disabled, tip) in enumerate(app.play_options(g) + app.install_options(g)):
|
||||
plays = app.play_options(g)
|
||||
for i, (label, icon, handler, disabled, tip) in enumerate(plays + app.install_options(g)):
|
||||
if i < len(plays) and not disabled:
|
||||
handler = self._starting(i, handler, tr("Starting on Frame…") if label == tr("Play on Frame")
|
||||
else tr("Starting on this PC…"))
|
||||
buttons.append(C.primary(label, icon, handler, disabled, tip, big=True) if i == 0 else
|
||||
C.secondary(label, icon, handler, disabled, tip))
|
||||
if C.is_media_player(g) and g.get("kind") != "rift" and app.frame_state == "connected" and \
|
||||
@@ -141,9 +170,39 @@ class GameView:
|
||||
lambda e: app.go("files", pkg), False,
|
||||
tr("Opens this player's storage on the Frame (Files tab): upload videos "
|
||||
"into the folder it lists")))
|
||||
more = ft.PopupMenuButton(icon=ft.Icons.MORE_HORIZ_ROUNDED, icon_color=T.TEXT_2, bgcolor=T.SURFACE_2,
|
||||
tooltip=tr("More actions"), items=C.menu_items(app.game_actions(pkg, quick=False)))
|
||||
return ft.Row(buttons + [more], spacing=T.S2, wrap=True)
|
||||
more = C.menu_button(C.menu_items(app.game_actions(pkg, quick=False)), icon=ft.Icons.MORE_HORIZ_ROUNDED,
|
||||
icon_color=T.TEXT_2, tooltip=tr("More actions"))
|
||||
# the same menu, opened from code (Library right-click → "More actions…", app.open_game_menu): a
|
||||
# PopupMenuButton can't be opened programmatically, a ContextMenu can (no mouse triggers of its own)
|
||||
self.more_menu = ft.ContextMenu(content=more, items=C.menu_items(app.game_actions(pkg, quick=False)),
|
||||
secondary_trigger=None, tertiary_trigger=None)
|
||||
self.hero_buttons = ft.Row(buttons + [self.more_menu], spacing=T.S2, wrap=True)
|
||||
return self.hero_buttons
|
||||
|
||||
def _starting(self, i: int, handler, text: str):
|
||||
"""A Play button that starts the game, then says "Starting on Frame…" with a spinner for as long as a card's
|
||||
Play shows it (CoverButton.STARTING_S) — the click visibly did something while Steam brings the game up."""
|
||||
def go(e):
|
||||
handler(e)
|
||||
row = self.hero_buttons
|
||||
old = row.controls[i]
|
||||
busy = (C.primary(text, C.spinner("s", T.ON_ACCENT), lambda e: None, big=True) if i == 0 else
|
||||
C.secondary(text, C.spinner("s"), lambda e: None))
|
||||
row.controls[i] = busy
|
||||
C.update(row)
|
||||
|
||||
async def restore():
|
||||
import asyncio
|
||||
|
||||
await asyncio.sleep(C.CoverButton.STARTING_S)
|
||||
if row.controls[i] is busy:
|
||||
row.controls[i] = old
|
||||
C.update(row)
|
||||
try:
|
||||
e.control.page.run_task(restore)
|
||||
except Exception: # noqa: BLE001 - the page went away meanwhile
|
||||
pass
|
||||
return go
|
||||
|
||||
# ---------------------------------------------------------------- sections
|
||||
def where(self) -> ft.Control:
|
||||
@@ -157,10 +216,10 @@ class GameView:
|
||||
return ", ".join(tr(base.get(i).title) if i in base.REGISTRY else i for i in ids)
|
||||
changed = "; ".join(filter(None, [tr("on: {names}").format(names=names(diff[0])) if diff[0] else "",
|
||||
tr("off: {names}").format(names=names(diff[1])) if diff[1] else ""]))
|
||||
frame_line = {"installed": "Installed",
|
||||
"outdated": (f"Installed · patch settings changed since ({changed}) — update to apply" if diff
|
||||
else "Installed · a newer build is ready"),
|
||||
"missing": "Not installed", None: "Frame not connected"}[st]
|
||||
frame_line = {"installed": tr("Installed"),
|
||||
"outdated": (tr("Installed · patch settings changed since ({changed}) — update to apply")
|
||||
.format(changed=changed) if diff else tr("Installed · a newer build is ready")),
|
||||
"missing": tr("Not installed"), None: tr("Frame not connected")}[st]
|
||||
frame_ok = st in ("installed", "outdated")
|
||||
# Oculus/LibOVR Rift games need Revive, which can't run on the Frame — be honest about it
|
||||
patches = (g.get("recipe") or {}).get("patches", {})
|
||||
@@ -183,15 +242,15 @@ class GameView:
|
||||
else tr("Runs directly — no Revive needed") if self.rift else
|
||||
tr("Runs natively on SteamOS, started from the Frame's Steam library") if self.linux else "")
|
||||
cards.append(self.target_card(
|
||||
ft.Icons.VIEW_IN_AR_ROUNDED, tr("Steam Frame"), frame_line, frame_color, frame_sub,
|
||||
[C.icon_btn(ft.Icons.SCIENCE_OUTLINED, C.tip(tr("Launch test on the Frame. ") + HELP["launch_test"]),
|
||||
G.FRAME, tr("Steam Frame"), frame_line, frame_color, frame_sub,
|
||||
[C.icon_btn(G.TEST, C.tip(tr("Launch test on the Frame. ") + HELP["launch_test"]),
|
||||
lambda e: app.test_game(pkg, "frame"), not frame_ok),
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, C.tip(tr("Uninstall from the Frame. ") + HELP["uninstall"]),
|
||||
lambda e: app.uninstall(pkg, "frame"), not frame_ok)] if frame_ok else []))
|
||||
if self.rift:
|
||||
dep = app.pc_installs().get(pkg)
|
||||
cards.append(self.target_card(
|
||||
ft.Icons.COMPUTER_ROUNDED, tr("This PC (Steam + Revive)"),
|
||||
G.PC, tr("This PC (Steam + Revive)"),
|
||||
(tr("In your Steam library · launch settings changed — update it") if C.pc_outdated(g, dep) else
|
||||
tr("In your Steam library")) if dep else tr("Not installed"),
|
||||
(T.WARN if C.pc_outdated(g, dep) else T.PC) if dep else T.TEXT_3,
|
||||
@@ -199,15 +258,15 @@ class GameView:
|
||||
.format(value=dep.get('revive_version') or '', value2=dep.get('backend') or 'openxr')
|
||||
if dep.get("revive_win") else tr("The repack's own Revive · runs the game directly")
|
||||
if dep.get("launch") == "repack" else tr("Runs the game directly")) if dep else "",
|
||||
[C.icon_btn(ft.Icons.SCIENCE_OUTLINED, tr("Launch test on this PC"),
|
||||
[C.icon_btn(G.TEST, tr("Launch test on this PC"),
|
||||
lambda e: app.test_game(pkg, "pc")),
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Remove from this PC's Steam library"),
|
||||
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Uninstall from this PC…"),
|
||||
lambda e: app.uninstall(pkg, "pc"))] if dep else []))
|
||||
return C.section(tr("Where it's installed"), ft.Row(cards, spacing=T.S3), help="where")
|
||||
|
||||
def target_card(self, icon, name, line, color, sub, buttons) -> ft.Control:
|
||||
return C.card(ft.Row([
|
||||
ft.Container(ft.Icon(icon, color=color, size=T.px(22)), width=T.px(44), height=T.px(44),
|
||||
ft.Container(C.as_icon(icon, T.px(22), color), width=T.px(44), height=T.px(44),
|
||||
border_radius=T.px(10), bgcolor=T.soft(color, 0.14), alignment=ft.Alignment.CENTER),
|
||||
ft.Column([C.body(name, T.TEXT, weight=ft.FontWeight.W_600), C.body(line, color, size=T.T_META)]
|
||||
+ ([C.meta(sub)] if sub else []), spacing=T.px(2), expand=True),
|
||||
@@ -227,18 +286,18 @@ class GameView:
|
||||
"them. Look for a build of the app that includes them, then install that one."),
|
||||
T.TEXT),
|
||||
C.meta(", ".join(missing), T.TEXT_2, selectable=True)], spacing=T.px(4)), "error",
|
||||
ft.Icons.EXTENSION_OFF_ROUNDED))
|
||||
ft.Icons.EXTENSION_OFF_OUTLINED))
|
||||
if self.rift and g.get("exe_confirmed") is False:
|
||||
out.append(C.callout(ft.Row([
|
||||
C.body(tr("FramePort picked {value} to start this game, but there are other candidates. "
|
||||
"Check it before installing.").format(value=g.get('exe', '').rsplit('/', 1)[-1]),
|
||||
T.TEXT, expand=True),
|
||||
C.secondary(tr("Check"), ft.Icons.TERMINAL_ROUNDED, lambda e: self.app.choose_exe(pkg))]), "warn",
|
||||
C.secondary(tr("Check…"), ft.Icons.TERMINAL_ROUNDED, lambda e: self.app.choose_exe(pkg))]), "warn",
|
||||
ft.Icons.HELP_OUTLINE_ROUNDED))
|
||||
if self.rift and extra.get("platform_sdk"):
|
||||
out.append(C.callout(tr("Uses the Oculus Platform SDK: it checks your Oculus license. Normally that "
|
||||
"needs the Oculus app on this PC with a license you own, so it may quit right "
|
||||
"after starting on the headset. You can still try it."), "warn"))
|
||||
out.append(C.callout(tr("Uses the Oculus Platform SDK, which checks your Oculus license: it needs the "
|
||||
"Oculus app on this PC and may quit right after starting. You can still try it."),
|
||||
"warn"))
|
||||
installed = C.install_state(g, self.app.frame_info) in ("installed", "outdated")
|
||||
if should_ask_to_share(g, installed):
|
||||
def dismiss(e):
|
||||
@@ -262,12 +321,12 @@ class GameView:
|
||||
from ... import pipeline
|
||||
|
||||
pipeline.apply_catalog_update(pkg)
|
||||
self.app.toast(tr("New config applied: use Update on Frame to install it"))
|
||||
self.app.toast(tr("New recipe applied: use Update on Frame to install it"))
|
||||
self.app.render()
|
||||
out.append(C.callout(ft.Row([
|
||||
C.body(tr("A newer known-good config for this game is available (you changed this game's settings, "
|
||||
C.body(tr("A newer known-good recipe for this game is available (you changed this game's settings, "
|
||||
"so it wasn't applied by itself)."), T.TEXT, expand=True),
|
||||
C.secondary(tr("Use the new config"), ft.Icons.AUTO_FIX_HIGH_OUTLINED, take_update)],
|
||||
C.secondary(tr("Use the new recipe"), ft.Icons.AUTO_FIX_HIGH_ROUNDED, take_update)],
|
||||
vertical_alignment=ft.CrossAxisAlignment.CENTER), "info", ft.Icons.NEW_RELEASES_OUTLINED))
|
||||
if g.get("steam_art_stale") and installed:
|
||||
out.append(C.callout(ft.Row([
|
||||
@@ -286,7 +345,7 @@ class GameView:
|
||||
out.append(C.callout(tr("This game's data file (.obb) wasn't found next to the APK. Put the .obb files "
|
||||
"in a folder named {package} (or obb/) next to the APK and add the folder again; "
|
||||
"without it the game hangs at start.").format(package=pkg), "error",
|
||||
ft.Icons.FOLDER_OFF_ROUNDED))
|
||||
ft.Icons.FOLDER_OFF_OUTLINED))
|
||||
web = (extra.get("web_wrapper") or None) if not self.rift and not self.linux else None
|
||||
if web:
|
||||
out.append(C.callout(ft.Column([
|
||||
@@ -312,8 +371,8 @@ class GameView:
|
||||
for r in counterparts(g, self.games):
|
||||
other_rift = r.get("kind") == "rift"
|
||||
links.append(C.ghost(tr("Also in your library: {value} version")
|
||||
.format(value='Rift' if other_rift else 'Quest'),
|
||||
ft.Icons.COMPUTER_ROUNDED if other_rift else ft.Icons.VIEW_IN_AR_ROUNDED,
|
||||
.format(value=tr("Rift") if other_rift else tr("Quest")),
|
||||
G.PC if other_rift else G.FRAME,
|
||||
lambda e, p=r["package"]: self.app.open_game(p), color=T.ACCENT))
|
||||
if links:
|
||||
out.append(ft.Row(links, spacing=T.S2, wrap=True))
|
||||
@@ -331,7 +390,7 @@ class GameView:
|
||||
if "details" in self.g:
|
||||
return None
|
||||
return C.section(tr("About this game"), C.card(ft.Row([
|
||||
ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2), color=T.ACCENT),
|
||||
C.spinner(),
|
||||
C.meta(tr("Looking up the store description and screenshots…"))], spacing=T.S2)))
|
||||
parts: list[ft.Control] = []
|
||||
if shots:
|
||||
@@ -362,15 +421,14 @@ class GameView:
|
||||
def more(e):
|
||||
state["open"] = not state["open"]
|
||||
body.value = text if state["open"] else short
|
||||
e.control.text = tr("Show less") if state["open"] else tr("Show more")
|
||||
e.control.content = tr("Show less") if state["open"] else tr("Show more")
|
||||
body.update()
|
||||
e.control.update()
|
||||
parts.append(ft.TextButton(tr("Show more"), on_click=more, style=ft.ButtonStyle(color=T.ACCENT)))
|
||||
parts.append(C.ghost(tr("Show more"), on_click=more, color=T.ACCENT))
|
||||
links = det.store_links(d)
|
||||
if links:
|
||||
parts.append(ft.Row([ft.TextButton(label, icon=ft.Icons.OPEN_IN_NEW_ROUNDED, url=url,
|
||||
style=ft.ButtonStyle(color=T.ACCENT)) for label, url in links],
|
||||
spacing=T.S2, wrap=True))
|
||||
parts.append(ft.Row([C.ghost(label, ft.Icons.OPEN_IN_NEW_ROUNDED, color=T.ACCENT, url=url)
|
||||
for label, url in links], spacing=T.S2, wrap=True))
|
||||
src = ", ".join({"oculusdb": "Meta store (OculusDB)", "steam": "Steam store"}.get(s, s)
|
||||
for s in d.get("sources") or [])
|
||||
return C.section(tr("About this game"), C.card(ft.Column(parts, spacing=T.S4)),
|
||||
@@ -389,13 +447,12 @@ class GameView:
|
||||
counter.value = f"{state['i'] + 1} / {len(shots)}"
|
||||
img.update()
|
||||
counter.update()
|
||||
page.show_dialog(ft.AlertDialog(
|
||||
content=ft.Container(ft.Column([img, ft.Row([
|
||||
page.show_dialog(C.viewer(
|
||||
ft.Container(ft.Column([img, ft.Row([
|
||||
C.icon_btn(ft.Icons.CHEVRON_LEFT_ROUNDED, tr("Previous"), lambda e: show(-1)), counter,
|
||||
C.icon_btn(ft.Icons.CHEVRON_RIGHT_ROUNDED, tr("Next"), lambda e: show(1)),
|
||||
ft.Container(expand=True), C.ghost(tr("Close"), on_click=lambda e: page.pop_dialog())])],
|
||||
spacing=T.S2, tight=True), width=T.px(1100)),
|
||||
bgcolor=T.BG, shape=ft.RoundedRectangleBorder(radius=T.RADIUS), content_padding=T.S3))
|
||||
spacing=T.S2, tight=True), width=T.px(1100))))
|
||||
|
||||
def tags(self) -> ft.Control:
|
||||
from .library import all_tags, auto_tags, normalize_tag, user_tags
|
||||
@@ -420,10 +477,8 @@ class GameView:
|
||||
else:
|
||||
e.control.update()
|
||||
|
||||
field = ft.TextField(hint_text=tr("Add a tag"), dense=True, width=T.px(150), text_size=T.T_META,
|
||||
border_radius=T.px(20), bgcolor=T.SURFACE_3, border_color=ft.Colors.TRANSPARENT,
|
||||
focused_border_color=T.ACCENT,
|
||||
content_padding=ft.Padding(T.px(12), T.px(6), T.px(12), T.px(6)), on_submit=add)
|
||||
field = C.field(hint_text=tr("Add a tag"), width=T.px(150), text_size=T.T_META, border_radius=T.px(20),
|
||||
content_padding=ft.Padding(T.px(12), T.px(6), T.px(12), T.px(6)), on_submit=add)
|
||||
|
||||
def fill():
|
||||
mine = user_tags(self.g)
|
||||
@@ -432,7 +487,7 @@ class GameView:
|
||||
spacing=T.px(4), tight=True),
|
||||
bgcolor=T.ACCENT_SOFT, border_radius=T.px(20),
|
||||
padding=ft.Padding(T.px(10), T.px(5), T.px(8), T.px(5)),
|
||||
on_click=lambda e, t=t: remove(t), tooltip=tr("Remove tag"))
|
||||
on_click=lambda e, t=t: remove(t), tooltip=tr("Remove tag"), ink=True)
|
||||
for t in mine]
|
||||
chips += [ft.Container(C.meta(t), border=ft.Border.all(1, T.BORDER), border_radius=T.px(20),
|
||||
padding=ft.Padding(T.px(10), T.px(5), T.px(10), T.px(5)),
|
||||
@@ -442,7 +497,8 @@ class GameView:
|
||||
suggestions = [t for t in all_tags(self.games) if t in used and t not in mine][:6]
|
||||
chips.append(field)
|
||||
chips += [ft.Container(C.meta("+ " + t, T.ACCENT), padding=ft.Padding(T.px(6), T.px(5), T.px(6), T.px(5)),
|
||||
on_click=lambda e, t=t: save(user_tags(self.g) + [t]), tooltip=tr("Add this tag"))
|
||||
on_click=lambda e, t=t: save(user_tags(self.g) + [t]), tooltip=tr("Add this tag"),
|
||||
border_radius=T.px(20), ink=True)
|
||||
for t in suggestions]
|
||||
row.controls = chips
|
||||
fill()
|
||||
@@ -497,7 +553,7 @@ class GameView:
|
||||
visible = [p for p in on if not p.default_on or p.category in ("pcvr",)]
|
||||
if entry and recipe.source.startswith("catalog"):
|
||||
lead = f"Known-good recipe for this game, tested {entry.verified.get('date', '')}".strip(", ")
|
||||
icon, color = ft.Icons.VERIFIED_ROUNDED, T.OK
|
||||
icon, color = G.RECIPE, T.OK
|
||||
elif recipe.source == "user":
|
||||
lead, icon, color = tr("Your custom recipe"), ft.Icons.TUNE_ROUNDED, T.ACCENT
|
||||
else:
|
||||
@@ -505,7 +561,7 @@ class GameView:
|
||||
ft.Icons.AUTO_AWESOME_ROUNDED, T.ACCENT
|
||||
chips = [ft.Container(C.body(tr(p.title), T.TEXT, size=T.T_META),
|
||||
tooltip=C.tip(tr(recipe.reasons.get(p.id) or p.description)),
|
||||
bgcolor=T.SURFACE_3, border_radius=T.px(6),
|
||||
bgcolor=T.SURFACE_3, border_radius=T.RADIUS_XS,
|
||||
padding=ft.Padding(T.px(10), T.px(5), T.px(10), T.px(5)))
|
||||
for p in visible]
|
||||
base_count = len(on) - len(visible)
|
||||
@@ -541,7 +597,7 @@ class GameView:
|
||||
return C.section(
|
||||
tr("What FramePort will do"),
|
||||
C.card(ft.Column([
|
||||
ft.Row([ft.Icon(icon, color=color, size=T.px(18)), C.body(lead, T.TEXT, weight=ft.FontWeight.W_500,
|
||||
ft.Row([C.as_icon(icon, T.px(18), color), C.body(lead, T.TEXT, weight=ft.FontWeight.W_500,
|
||||
expand=True)], spacing=T.S2),
|
||||
ft.Row(chips, spacing=T.S2, run_spacing=T.S2, wrap=True) if chips else
|
||||
(ft.Container() if as_is else C.meta(tr("Nothing to patch: it runs as is."))),
|
||||
@@ -661,10 +717,9 @@ class GameView:
|
||||
rows.append(ft.Container(ft.Row([
|
||||
ft.Column([C.body(tr(p.title), T.TEXT, weight=ft.FontWeight.W_500), *sub],
|
||||
spacing=T.px(3), expand=True),
|
||||
ft.Dropdown(value=current, width=T.px(280), dense=True, border_color=T.BORDER,
|
||||
text_size=T.T_BODY,
|
||||
options=[ft.DropdownOption(key=k, text=tr(label)) for k, label in choices],
|
||||
on_select=choose(p.id, p.params[0].key)),
|
||||
C.dropdown(value=current, width=T.px(280),
|
||||
options=[ft.DropdownOption(key=k, text=tr(label)) for k, label in choices],
|
||||
on_select=choose(p.id, p.params[0].key)),
|
||||
], spacing=T.S3), padding=ft.Padding(T.S4, T.px(10), T.S4, T.px(10)), border=ft.Border(
|
||||
top=ft.BorderSide(1, T.BORDER))))
|
||||
continue
|
||||
@@ -672,15 +727,13 @@ class GameView:
|
||||
pass
|
||||
elif cat == "adapter":
|
||||
val = recipe.params(p.id).get("value", p.params[0].default)
|
||||
extra = ft.TextField(value=str(val), width=T.px(90), dense=True, text_size=T.T_BODY,
|
||||
border_color=T.BORDER, on_blur=set_value(p.id, p.params[0].kind))
|
||||
extra = C.field(value=str(val), width=T.px(90), on_blur=set_value(p.id, p.params[0].kind))
|
||||
elif p.params:
|
||||
q = p.params[0]
|
||||
multi = q.kind == "text"
|
||||
extra = ft.TextField(value=str(recipe.params(p.id).get(q.key, q.default) or ""), hint_text=q.help,
|
||||
width=T.px(260), dense=True, multiline=multi, min_lines=1,
|
||||
max_lines=4 if multi else 1, text_size=T.T_BODY, border_color=T.BORDER,
|
||||
on_blur=set_param(p.id, q.key))
|
||||
extra = C.field(value=str(recipe.params(p.id).get(q.key, q.default) or ""), hint_text=q.help,
|
||||
width=T.px(260), multiline=multi, min_lines=1, max_lines=4 if multi else 1,
|
||||
on_blur=set_param(p.id, q.key))
|
||||
rows.append(ft.Container(ft.Row([
|
||||
ft.Column([ft.Row([C.body(tr(p.title), T.TEXT, weight=ft.FontWeight.W_500)]
|
||||
+ ([C.pill(tr("experimental"), T.WARN, tooltip=C.tip(HELP["experimental"]))]
|
||||
@@ -737,7 +790,7 @@ class GameView:
|
||||
ft.Container(ft.Column(rows, spacing=T.S2), padding=ft.Padding(T.S4, 0, T.S4, T.S4))],
|
||||
bgcolor=T.SURFACE, collapsed_bgcolor=T.SURFACE)
|
||||
if self.rift:
|
||||
rows += [C.kv(tr("Folder"), g.get("game_dir") or ""), C.kv(tr("Executable"), g.get("exe") or ""),
|
||||
rows += [C.kv(tr("Folder"), g.get("game_dir") or ""), C.kv(tr("Program"), g.get("exe") or ""),
|
||||
C.kv(tr("Type"), f"{a['abis'][0]} · {a['graphics']}"),
|
||||
C.kv(tr("Size"), tr("{value:.1f} GiB")
|
||||
.format(value=(a.get('extra', {}).get('data_bytes') or 0) / 2**30))]
|
||||
@@ -761,6 +814,7 @@ class GameView:
|
||||
tr("It was removed from the library."),
|
||||
C.primary(tr("Back to library"), on_click=lambda e: self.app.go("library")))
|
||||
about = self.about()
|
||||
self._backdrop = ft.Container(left=0, right=0, top=0, height=T.px(560)) # the cover tint's page wash
|
||||
body = [self.hero(), *self.notes(), self.where(), *([about] if about else []), self.tags(),
|
||||
self.recipe_summary()]
|
||||
if self.advanced and not self.linux: # (a Linux app has no patches)
|
||||
@@ -771,7 +825,13 @@ class GameView:
|
||||
def remember(e):
|
||||
app.game_scroll = e.pixels
|
||||
col = ft.Column([ft.Container(ft.Column(body, spacing=T.S5), padding=ft.Padding(0, 0, T.S3, T.S6))],
|
||||
scroll=ft.ScrollMode.AUTO, expand=True, on_scroll=remember, scroll_interval=100)
|
||||
scroll=ft.ScrollMode.AUTO, on_scroll=remember, scroll_interval=100,
|
||||
left=0, right=0, top=0, bottom=0)
|
||||
app.game_view = self
|
||||
known, tint = thumbs.cached_tint(self.package)
|
||||
self._tint(tint)
|
||||
if not known:
|
||||
app.page.run_thread(self._fill_tint)
|
||||
offset = getattr(app, "game_scroll", 0.0)
|
||||
if offset > 0: # back to where the user was, once the new page is on screen
|
||||
def restore():
|
||||
@@ -780,7 +840,7 @@ class GameView:
|
||||
except Exception: # noqa: BLE001 - the page changed again meanwhile
|
||||
pass
|
||||
threading.Timer(0.08, restore).start()
|
||||
return col
|
||||
return ft.Stack([self._backdrop, col], expand=True)
|
||||
|
||||
|
||||
def _known(pid: str) -> bool:
|
||||
|
||||
@@ -14,12 +14,23 @@ import flet as ft
|
||||
from ...errors import explain
|
||||
from ...i18n import tr
|
||||
from .. import components as C
|
||||
from .. import glyphs as G
|
||||
from .. import theme as T
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..app import FramePortApp
|
||||
|
||||
|
||||
def keyboard_tips() -> list[tuple[str, str, str]]:
|
||||
"""How typing on the Frame works (its empty state, and tips under the typing box)."""
|
||||
return [(ft.Icons.TOUCH_APP_ROUNDED, tr("Pick the field in the headset"),
|
||||
tr("Select a text field in the game first: typing goes where it has focus.")),
|
||||
(G.KEYS, tr("Every key goes through"),
|
||||
tr("Letters, Enter, Backspace, arrows, Esc and shortcuts reach the headset.")),
|
||||
(ft.Icons.CONTENT_PASTE_ROUNDED, tr("Paste long text"),
|
||||
tr("Put a password, link or note in the box and press Type it."))]
|
||||
|
||||
|
||||
class KeyboardView:
|
||||
def __init__(self, app: FramePortApp):
|
||||
self.app = app
|
||||
@@ -39,20 +50,21 @@ class KeyboardView:
|
||||
on_click=lambda e: self.focus_keys())
|
||||
self.listener = ft.KeyboardListener(self.pad, autofocus=True, on_key_down=self._forward("down"),
|
||||
on_key_up=self._forward("up"), on_key_repeat=self._forward("repeat"))
|
||||
self.paste = ft.TextField(hint_text=tr("Or paste text to type it in one go"), expand=True, dense=True,
|
||||
border_color=T.BORDER, on_submit=self._send_text)
|
||||
self.paste = C.field(hint_text=tr("Or paste text to type it in one go"), expand=True,
|
||||
on_submit=self._send_text)
|
||||
self.reconnect = C.secondary(tr("Reconnect"), ft.Icons.REFRESH_ROUNDED, lambda e: self.start())
|
||||
|
||||
# ---------------------------------------------------------------- building
|
||||
def mount(self) -> ft.Control:
|
||||
app = self.app
|
||||
heading, sub = tr("Type on Frame"), tr("Use this computer's keyboard on the Frame")
|
||||
heading, sub = tr("Type on Frame"), tr("Use this PC's keyboard on the Frame")
|
||||
if not (app.target and app.frame_state == "connected"):
|
||||
return ft.Column([
|
||||
app.top_bar(heading, sub),
|
||||
C.empty_state(ft.Icons.KEYBOARD_ROUNDED, tr("Connect your Frame first"),
|
||||
tr("Typing on the Frame works once FramePort is connected to it."),
|
||||
C.primary(tr("Connect"), ft.Icons.LINK_ROUNDED, lambda e: app.go("frame")))], expand=True)
|
||||
C.empty_state(G.KEYS, tr("Type in VR with your PC's keyboard"),
|
||||
tr("Connect to your Steam Frame to type into the headset from here."),
|
||||
C.primary(tr("Connect"), ft.Icons.LINK_ROUNDED, lambda e: app.go("frame")),
|
||||
features=keyboard_tips())], expand=True)
|
||||
if self.root is None:
|
||||
self.root = ft.Column([
|
||||
app.top_bar(heading, sub),
|
||||
@@ -60,12 +72,14 @@ class KeyboardView:
|
||||
ft.Row([self.status, self.reconnect], spacing=T.S3,
|
||||
vertical_alignment=ft.CrossAxisAlignment.CENTER),
|
||||
self.listener,
|
||||
ft.Row([self.paste, C.secondary(tr("Type it"), ft.Icons.SEND_ROUNDED, self._send_text)],
|
||||
ft.Row([self.paste, C.secondary(tr("Type it"), ft.Icons.SEND_OUTLINED, self._send_text)],
|
||||
spacing=T.S2),
|
||||
ft.Row([C.meta(tr("In the headset, select a text field, then type here."), T.TEXT_2),
|
||||
C.help_icon("type_on_frame", 16)], spacing=T.px(2), tight=True,
|
||||
vertical_alignment=ft.CrossAxisAlignment.CENTER),
|
||||
], spacing=T.S3)),
|
||||
C.callout(tr("This computer's keyboard works as a keyboard on your Frame while this tab is open. In "
|
||||
"the headset, select a text field (in a game or app, in Steam or on the desktop), then "
|
||||
"type here.")),
|
||||
ft.Row([C.feature_card(*tip) for tip in keyboard_tips()], wrap=True, spacing=T.S3,
|
||||
run_spacing=T.S3, vertical_alignment=ft.CrossAxisAlignment.START),
|
||||
], spacing=T.S4, horizontal_alignment=ft.CrossAxisAlignment.STRETCH)
|
||||
self.start()
|
||||
return self.root
|
||||
|
||||
@@ -13,6 +13,7 @@ from ...artwork import thumbs
|
||||
from ...core import library
|
||||
from ...i18n import tr, tr_n
|
||||
from .. import components as C
|
||||
from .. import glyphs as G
|
||||
from .. import theme as T
|
||||
from ..help import HELP
|
||||
|
||||
@@ -140,6 +141,70 @@ def filter_games(games: list[dict], f: dict, frame_info: dict | None = None,
|
||||
return sorted(out, key=key)
|
||||
|
||||
|
||||
# type to search: Flet sends Flutter's key labels ("A" for a and A, "1", " ", "-", "Arrow Left", "Numpad 1", "F5"),
|
||||
# not the typed character, so shifted symbols follow the US layout (what the label alone can tell)
|
||||
_SHIFTED = dict(zip("1234567890-=[];'`\\,./", "!@#$%^&*()_+{}:\"~|<>?", strict=True))
|
||||
_NAMED_CHARS = {"space": " ", **{f"numpad{d}": d for d in "0123456789"}, "numpadadd": "+",
|
||||
"numpadsubtract": "-", "numpadmultiply": "*", "numpaddivide": "/", "numpaddecimal": "."}
|
||||
|
||||
|
||||
def typed_char(key: str, shift: bool = False, ctrl: bool = False, alt: bool = False,
|
||||
meta: bool = False) -> str | None:
|
||||
"""The character a key press types (for the Library's type-to-search), None for shortcuts (Ctrl/Alt/Meta held),
|
||||
modifiers, navigation, function and other named keys."""
|
||||
if not key or ctrl or alt or meta:
|
||||
return None
|
||||
if len(key) == 1:
|
||||
if key.isalpha():
|
||||
return key.upper() if shift else key.lower()
|
||||
if shift and key in _SHIFTED:
|
||||
return _SHIFTED[key]
|
||||
return key if key.isprintable() else None
|
||||
return _NAMED_CHARS.get(key.lower().replace(" ", "").replace("_", ""))
|
||||
|
||||
|
||||
def should_capture(route: str, dialog_open: bool, field_focused: bool, char: str | None, query: str = "") -> bool:
|
||||
"""Whether a typed character goes to the Library's search: only on the Library itself, with no dialog open and
|
||||
the search not already focused (it types there itself); a leading space is ignored (Space on a focused button)."""
|
||||
return (route == "library" and not dialog_open and not field_focused and char is not None
|
||||
and not (char == " " and not query))
|
||||
|
||||
|
||||
SHELF_MAX = 8
|
||||
|
||||
|
||||
def filters_active(f: dict) -> bool:
|
||||
"""A search or any filter other than the defaults (the sort order isn't a filter)."""
|
||||
return bool((f.get("q") or "").strip() or f.get("tags")) or any(
|
||||
f.get(k, DEFAULT_FILTERS[k]) != DEFAULT_FILTERS[k] for k in ("where", "platform", "status"))
|
||||
|
||||
|
||||
def shelf_divider() -> ft.Control:
|
||||
"""The line between the "On your Frame" shelf and the grid of every game: a label and a 2 px rule (the portal's
|
||||
blue→orange in dual themes), so the shelf doesn't read as the grid's first row. Part of the shelf: it hides
|
||||
with it."""
|
||||
rule = ft.Container(height=T.px(2), expand=True, border_radius=T.px(1),
|
||||
gradient=C.portal_gradient(opacity=0.55) if T.DUAL else None,
|
||||
bgcolor=None if T.DUAL else T.BORDER_STRONG)
|
||||
label = ft.Text(tr("All games").upper(), size=T.T_SMALL, weight=ft.FontWeight.W_600, color=T.TEXT_2,
|
||||
style=ft.TextStyle(letter_spacing=1.2))
|
||||
return ft.Container(ft.Row([label, rule], spacing=T.S3, vertical_alignment=ft.CrossAxisAlignment.CENTER),
|
||||
padding=ft.Padding(0, T.S2, T.S2, 0))
|
||||
|
||||
|
||||
def shelf_games(games: list[dict], f: dict, frame_info: dict | None, connected: bool, select_mode: bool = False,
|
||||
limit: int = SHELF_MAX) -> list[dict]:
|
||||
"""The "On your Frame" shelf: games installed on the connected Frame (outdated ones too), most recently used
|
||||
first, at most `limit`. Empty (the shelf hides) without a connected Frame and while searching or filtering. It
|
||||
stays in select mode (`select_mode` is ignored): hiding it when a drag-select starts moved the grid up under the
|
||||
mouse, and the drag selected the wrong cards."""
|
||||
if not connected or filters_active(f):
|
||||
return []
|
||||
on = [g for g in games if C.install_state(g, frame_info) in ("installed", "outdated")]
|
||||
on.sort(key=lambda g: (-last_used(g), (g.get("title") or g["package"]).lower()))
|
||||
return on[:limit]
|
||||
|
||||
|
||||
def load_filters() -> dict:
|
||||
saved = library.setting("ui.library") or {}
|
||||
return {**DEFAULT_FILTERS, "tags": [], **{k: v for k, v in saved.items() if k in DEFAULT_FILTERS and k != "q"}}
|
||||
@@ -152,13 +217,52 @@ def save_filters(f: dict) -> None:
|
||||
# ------------------------------------------------------------------------------------------ view
|
||||
BATCH = 8
|
||||
CARD_ART = ("portrait", "square", "cover", "icon") # store art first; cover = FramePort's own (no store art)
|
||||
def card_shadow(hover: bool = False) -> ft.BoxShadow:
|
||||
"""Library cards float on the dark background; hovering lifts them further."""
|
||||
SHELF_ART = ("landscape", "hero", "banner", "portrait", "square", "cover", "icon") # wide first
|
||||
def card_shadow(hover: bool = False) -> ft.BoxShadow | list[ft.BoxShadow]:
|
||||
"""Library cards float on the dark background; hovering lifts them further, with a faint accent glow."""
|
||||
if hover:
|
||||
return ft.BoxShadow(blur_radius=36, spread_radius=2, color=T.soft("#000000", 0.75), offset=ft.Offset(0, 14))
|
||||
return [ft.BoxShadow(blur_radius=36, spread_radius=2, color=T.soft("#000000", 0.75), offset=ft.Offset(0, 16)),
|
||||
ft.BoxShadow(blur_radius=30, spread_radius=-2, color=T.soft(T.ACCENT, 0.22), offset=ft.Offset(0, 4))]
|
||||
return ft.BoxShadow(blur_radius=22, spread_radius=1, color=T.soft("#000000", 0.55), offset=ft.Offset(0, 8))
|
||||
|
||||
|
||||
def card_hover(tile: ft.Container, art: ft.Control, scrim: ft.Control | None, on: bool, reduce: bool) -> None:
|
||||
"""A cover card under the pointer: lifts, its art zooms in a little inside the frame and darkens behind the round
|
||||
button (scrim), the shadow deepens. Reduce motion: only the shadow and scrim change."""
|
||||
if not reduce:
|
||||
tile.scale = 1.02 if on else 1.0
|
||||
tile.offset = ft.Offset(0, -0.015 if on else 0)
|
||||
art.scale = 1.07 if on else 1.0
|
||||
if scrim is not None:
|
||||
scrim.opacity = 1 if on else 0
|
||||
tile.shadow = card_shadow(on)
|
||||
|
||||
|
||||
def hover_motion(tile: ft.Container, art: ft.Control) -> None:
|
||||
"""The animations card_hover relies on (set once when the card is built)."""
|
||||
tile.scale, tile.offset = 1.0, ft.Offset(0, 0)
|
||||
tile.animate_scale = ft.Animation(220, ft.AnimationCurve.EASE_OUT)
|
||||
tile.animate_offset = ft.Animation(220, ft.AnimationCurve.EASE_OUT)
|
||||
tile.clip_behavior = ft.ClipBehavior.ANTI_ALIAS # the zoomed art stays inside the rounded frame
|
||||
art.scale = 1.0
|
||||
art.animate_scale = ft.Animation(600, ft.AnimationCurve.EASE_OUT)
|
||||
|
||||
|
||||
def art_frame(cover: ft.Control) -> ft.Container:
|
||||
"""The cover in its own rounded clip, filling the card: the hover zoom (card_hover) stays inside the frame. The
|
||||
card's own clip didn't hold the scaled art, and a strip of it showed below the bottom fade."""
|
||||
return ft.Container(cover, left=0, right=0, top=0, bottom=0, border_radius=T.RADIUS,
|
||||
clip_behavior=ft.ClipBehavior.ANTI_ALIAS)
|
||||
|
||||
|
||||
def scrim() -> ft.Container:
|
||||
"""The darkening behind a card's round button while hovered (a soft radial dim, strongest in the middle)."""
|
||||
return ft.Container(left=0, right=0, top=0, bottom=0, opacity=0,
|
||||
animate_opacity=ft.Animation(220, ft.AnimationCurve.EASE_OUT),
|
||||
gradient=ft.RadialGradient(colors=[T.soft("#000000", 0.5), T.soft("#000000", 0.15)],
|
||||
radius=0.8))
|
||||
|
||||
|
||||
def quick_icon(kind: str) -> str:
|
||||
"""The symbol on a card's round quick button (app.quick_action's kind)."""
|
||||
return {"play": ft.Icons.PLAY_ARROW_ROUNDED, "update": ft.Icons.UPGRADE_ROUNDED,
|
||||
@@ -173,12 +277,23 @@ class LibraryView:
|
||||
self.f = app.lib_filters
|
||||
self.cards: dict[str, tuple[tuple, ft.Control]] = {} # package -> (state key, card)
|
||||
self.checks: dict[str, ft.Control] = {} # package -> selection checkbox overlay
|
||||
self.marks: dict[str, tuple] = {} # package -> (card tile, selection fade overlay, hovered?)
|
||||
self.selected: set[str] = set()
|
||||
self.select_mode = False
|
||||
self.sel_bar = ft.Container(visible=False)
|
||||
self.resume_bar = ft.Container(visible=False)
|
||||
self.update_bar = ft.Container(visible=False) # "FramePort x.y is available" (ui/updater.py)
|
||||
self.games: list[dict] = []
|
||||
self.tw: set[str] = set()
|
||||
# "On your Frame": a row of wide cards above the grid (shelf_games); cards are kept per game and only rebuilt
|
||||
# when what they show changes
|
||||
self.shelf_cards: dict[str, tuple[tuple, ft.Control]] = {}
|
||||
self.shelf_row = ft.Row(spacing=T.S4, scroll=ft.ScrollMode.AUTO)
|
||||
self.shelf = ft.Container(ft.Column([
|
||||
C.h2(tr("On your Frame")),
|
||||
ft.Container(self.shelf_row, padding=ft.Padding(0, 0, 0, T.S2)),
|
||||
shelf_divider(),
|
||||
], spacing=T.S3, tight=True), visible=False)
|
||||
self._lock = threading.Lock()
|
||||
self._search_timer: threading.Timer | None = None
|
||||
self._gen = 0
|
||||
@@ -186,12 +301,11 @@ class LibraryView:
|
||||
run_spacing=T.S4, padding=ft.Padding(0, T.S2, T.S2, T.S5))
|
||||
self.count = C.meta("")
|
||||
self.subtitle = C.body("", max_lines=1, overflow=ft.TextOverflow.ELLIPSIS)
|
||||
self.search = ft.TextField(
|
||||
value=self.f["q"], hint_text=tr("Search games and tags"), prefix_icon=ft.Icons.SEARCH_ROUNDED, dense=True,
|
||||
width=T.px(260), border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3, border_color=ft.Colors.TRANSPARENT,
|
||||
focused_border_color=T.ACCENT, content_padding=ft.Padding(T.px(12), T.px(8), T.px(12), T.px(8)),
|
||||
text_size=T.T_BODY,
|
||||
on_change=self._on_search)
|
||||
# typing anywhere on the Library goes here (app._on_key); search_focused tracks where keys already land
|
||||
self.search_focused = False
|
||||
self.search = C.search(value=self.f["q"], hint_text=tr("Type to search games and tags"), width=T.px(260),
|
||||
on_change=self._on_search, on_focus=lambda e: self._focus(True),
|
||||
on_blur=lambda e: self._focus(False))
|
||||
# an X that clears the search at once (shown only while there is text)
|
||||
# a small clickable icon, not an IconButton: its 40 px minimum size made the field taller and pushed the
|
||||
# text off-centre
|
||||
@@ -208,33 +322,22 @@ class LibraryView:
|
||||
lambda pkg, on: self.toggle_selected(pkg) if (pkg in self.selected) != on else None,
|
||||
can_select=lambda pkg: pkg in self.cards,
|
||||
on_start=lambda: None if self.select_mode else self.set_select_mode(True))
|
||||
self.menu = ft.ContextMenu(content=ft.GestureDetector(content=self.grid, expand=True,
|
||||
on_pan_start=self.drag.start, on_pan_end=self.drag.end),
|
||||
secondary_trigger=None, tertiary_trigger=None, expand=True)
|
||||
self.menu = ft.ContextMenu(content=ft.Column([
|
||||
self.shelf,
|
||||
ft.GestureDetector(content=self.grid, expand=True, on_pan_start=self.drag.start, on_pan_end=self.drag.end),
|
||||
], spacing=T.S4, expand=True), secondary_trigger=None, tertiary_trigger=None, expand=True)
|
||||
self.body = ft.Container(self.menu, expand=True)
|
||||
add = ft.PopupMenuButton(
|
||||
content=ft.Container(ft.Row([ft.Icon(ft.Icons.ADD_ROUNDED, color=T.ON_ACCENT, size=T.px(18)),
|
||||
ft.Text(tr("Add games"), color=T.ON_ACCENT, weight=ft.FontWeight.W_600,
|
||||
size=T.px(13))],
|
||||
spacing=T.px(6), tight=True),
|
||||
bgcolor=T.ACCENT, border_radius=T.RADIUS_SM,
|
||||
padding=ft.Padding(T.px(14), T.px(9), T.px(16), T.px(9))),
|
||||
items=[ft.PopupMenuItem(content=ft.Text(tr("Scan a folder…")), icon=ft.Icons.FOLDER_OPEN_ROUNDED,
|
||||
on_click=app.pick_folder),
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Add one game folder…")),
|
||||
icon=ft.Icons.CREATE_NEW_FOLDER_ROUNDED, on_click=app.pick_game_folder),
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Add an APK file…")), icon=ft.Icons.ANDROID_ROUNDED,
|
||||
on_click=app.pick_apk),
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Add a Windows program (.exe)…")),
|
||||
icon=ft.Icons.DESKTOP_WINDOWS_ROUNDED, on_click=app.pick_windows_exe),
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Install from a link…")), icon=ft.Icons.LINK_ROUNDED,
|
||||
on_click=app.pick_link),
|
||||
ft.PopupMenuItem(), # divider: native Linux apps (GitHub #31)
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Add a Linux app…")), icon=ft.Icons.TERMINAL_ROUNDED,
|
||||
on_click=app.pick_linux_app),
|
||||
ft.PopupMenuItem(content=ft.Text(tr("Add a Linux app folder…")), icon=ft.Icons.FOLDER_ROUNDED,
|
||||
on_click=app.pick_linux_folder)],
|
||||
bgcolor=T.SURFACE_2, tooltip="")
|
||||
add = C.primary_menu(tr("Add games"), ft.Icons.ADD_ROUNDED, C.menu_items([
|
||||
(tr("Scan a folder…"), ft.Icons.FOLDER_OPEN_ROUNDED, app.pick_folder),
|
||||
(tr("Add a PC game folder…"), G.PC, app.pick_game_folder),
|
||||
(tr("Add an APK…"), ft.Icons.ANDROID_ROUNDED, app.pick_apk),
|
||||
(tr("Add a Windows program…"), ft.Icons.WEB_ASSET_ROUNDED, app.pick_windows_exe),
|
||||
(tr("Add from a link…"), ft.Icons.LINK_ROUNDED, app.pick_link),
|
||||
None, # native Linux apps (GitHub #31)
|
||||
(tr("Add a Linux app…"), ft.Icons.TERMINAL_ROUNDED, app.pick_linux_app),
|
||||
(tr("Add a Linux app folder…"), ft.Icons.FOLDER_OUTLINED, app.pick_linux_folder),
|
||||
None,
|
||||
(tr("Rescan folders"), ft.Icons.REFRESH_ROUNDED, app.rescan)]))
|
||||
self.rescan_btn = C.secondary(tr("Rescan folders"), ft.Icons.REFRESH_ROUNDED, app.rescan,
|
||||
tooltip=C.tip(HELP["rescan"]))
|
||||
self.update_all_btn = C.secondary(tr("Update all"), ft.Icons.SYSTEM_UPDATE_ALT_ROUNDED,
|
||||
@@ -293,18 +396,25 @@ class LibraryView:
|
||||
games = library.games()
|
||||
self.games = games
|
||||
pc = set(local_installs())
|
||||
tw = twins(games)
|
||||
tw = self.tw = twins(games)
|
||||
self._update_header(games, pc)
|
||||
self.update_update_bar()
|
||||
self.update_resume_bar() # also after Dismiss / Resume and when installs finish or fail
|
||||
if not games:
|
||||
self.body.content = C.empty_state(
|
||||
ft.Icons.LIBRARY_ADD_ROUNDED, tr("Add your games"),
|
||||
tr("Point FramePort at a folder with Android games (APK + OBB, e.g. Quest games) or PC VR games "
|
||||
"(one folder per game, or a folder of them). It finds them, works out what each needs and "
|
||||
"fetches artwork."),
|
||||
C.primary(tr("Scan a folder"), ft.Icons.FOLDER_OPEN_ROUNDED, self.app.pick_folder, big=True),
|
||||
C.secondary(tr("Add an APK file"), ft.Icons.ANDROID_ROUNDED, self.app.pick_apk))
|
||||
ft.Icons.LIBRARY_ADD_OUTLINED, tr("Add your games"),
|
||||
tr("Point FramePort at a folder with Quest or Android games (APK + OBB) or PC VR games. It "
|
||||
"finds them, works out what each needs and fetches artwork."),
|
||||
C.primary(tr("Scan a folder…"), ft.Icons.FOLDER_OPEN_ROUNDED, self.app.pick_folder, big=True),
|
||||
C.secondary(tr("Add an APK file…"), ft.Icons.ANDROID_ROUNDED, self.app.pick_apk),
|
||||
features=[
|
||||
(G.FRAME, tr("Quest games"),
|
||||
tr("Converted for the Steam Frame, then installed over Wi-Fi or USB.")),
|
||||
(G.PC, tr("PC VR games"),
|
||||
tr("Rift games on the Frame through Proton, or on this PC.")),
|
||||
(ft.Icons.APPS_ROUNDED, tr("Android and Linux apps"),
|
||||
tr("Ordinary Android apps and Linux programs run there too.")),
|
||||
])
|
||||
self.cards.clear()
|
||||
C.update(self.root)
|
||||
return
|
||||
@@ -341,8 +451,11 @@ class LibraryView:
|
||||
for pkg, chk in self.checks.items():
|
||||
chk.visible = on
|
||||
chk.content.value = pkg in self.selected
|
||||
for pkg in self.marks:
|
||||
self._paint_card(pkg)
|
||||
self._update_sel_bar()
|
||||
C.update(self.grid, self.sel_bar, self.select_btn)
|
||||
self._update_shelf()
|
||||
C.update(self.grid, self.sel_bar, self.select_btn, self.shelf)
|
||||
|
||||
def toggle_selected(self, pkg: str) -> None:
|
||||
self.selected.symmetric_difference_update({pkg})
|
||||
@@ -350,8 +463,19 @@ class LibraryView:
|
||||
if chk:
|
||||
chk.content.value = pkg in self.selected
|
||||
C.update(chk)
|
||||
if pkg in self.marks:
|
||||
self._paint_card(pkg)
|
||||
C.update(self.marks[pkg][0])
|
||||
self._update_sel_bar()
|
||||
|
||||
def _paint_card(self, pkg: str) -> None:
|
||||
"""A card's border + selection fade (properties only): selected = 2 px accent + the portal fade, hovered =
|
||||
1 px accent, else the plain border."""
|
||||
tile, overlay, hovered = self.marks[pkg]
|
||||
on = self.select_mode and pkg in self.selected
|
||||
C.selected_style(overlay, on, subtle=True)
|
||||
tile.border = ft.Border.all(2 if on else 1, T.ACCENT if on or hovered else T.BORDER)
|
||||
|
||||
def select_visible(self) -> None:
|
||||
shown = filter_games(self.games, self.f, self.app.frame_info, set(self.app.pc_installs()))
|
||||
self.selected |= {g["package"] for g in shown if g["package"] in self.cards}
|
||||
@@ -372,11 +496,11 @@ class LibraryView:
|
||||
ft.Container(expand=True),
|
||||
C.ghost(tr("Select all shown"), on_click=lambda e: self.select_visible()),
|
||||
C.ghost(tr("Clear"), on_click=lambda e: (self.selected.clear(), self.set_select_mode(True))),
|
||||
*([C.secondary(tr("Install {len} on this PC").format(len=len(rift)), ft.Icons.COMPUTER_ROUNDED,
|
||||
*([C.secondary(tr("Install {len} on this PC").format(len=len(rift)), G.PC,
|
||||
lambda e: app.install_many(sorted(rift), "pc"), disabled=not winhost.available())]
|
||||
if rift else []),
|
||||
C.primary(tr("Install {n} on Frame").format(n=n) if n else tr("Install on Frame"),
|
||||
ft.Icons.VIEW_IN_AR_ROUNDED,
|
||||
G.FRAME,
|
||||
lambda e: app.install_many(sorted(self.selected), "frame"),
|
||||
disabled=not n or app.frame_state != "connected",
|
||||
tooltip=None if app.frame_state == "connected" else tr("Connect your Frame first")),
|
||||
@@ -421,8 +545,36 @@ class LibraryView:
|
||||
C.update(self.search)
|
||||
self._apply(update=True)
|
||||
|
||||
def _focus(self, on: bool) -> None:
|
||||
self.search_focused = on
|
||||
|
||||
def type_key(self, char: str | None, backspace: bool = False) -> None:
|
||||
"""A key typed while the search isn't focused (app._on_key): add it (or remove the last character), filter
|
||||
like typing in the field, and focus the field so the next keys go there directly."""
|
||||
value = self.search.value or ""
|
||||
self.search.value = value[:-1] if backspace else value + (char or "")
|
||||
self.set_query(self.search.value)
|
||||
C.update(self.search)
|
||||
try:
|
||||
self.app.page.run_task(self._focus_at_end)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
async def _focus_at_end(self) -> None:
|
||||
await self.search.focus()
|
||||
n = len(self.search.value or "")
|
||||
try: # Flutter selects nothing on a programmatic focus; put the cursor after the typed text
|
||||
self.search.selection = ft.TextSelection(base_offset=n, extent_offset=n)
|
||||
C.update(self.search)
|
||||
except Exception: # noqa: BLE001 (older Flet: no selection property; the cursor goes to the end anyway)
|
||||
pass
|
||||
|
||||
def _on_search(self, e):
|
||||
self.f["q"] = e.control.value
|
||||
self.set_query(e.control.value)
|
||||
|
||||
def set_query(self, value: str) -> None:
|
||||
"""The search text changed: show/hide the clear X, filter after a short pause (debounced)."""
|
||||
self.f["q"] = value
|
||||
if self.search.suffix.visible != bool(self.f["q"]):
|
||||
self.search.suffix.visible = bool(self.f["q"])
|
||||
C.update(self.search)
|
||||
@@ -446,8 +598,74 @@ class LibraryView:
|
||||
self.grid.controls = [self.cards[g["package"]][1] for g in shown if g["package"] in self.cards]
|
||||
n = len(self.games)
|
||||
self.count.value = tr("Showing {len} of {n}").format(len=len(shown), n=n) if len(shown) != n else ""
|
||||
self._update_shelf()
|
||||
if update:
|
||||
C.update(self.grid, self.count)
|
||||
C.update(self.grid, self.count, self.shelf)
|
||||
|
||||
# ---------------------------------------------------------------- "On your Frame" shelf
|
||||
def _update_shelf(self) -> None:
|
||||
"""Show the shelf's games (properties + reused cards; a card is rebuilt only when what it shows changed)."""
|
||||
app = self.app
|
||||
games = shelf_games(self.games, self.f, app.frame_info, app.frame_state == "connected", self.select_mode)
|
||||
controls = []
|
||||
for g in games:
|
||||
pkg = g["package"]
|
||||
key = (display_title(g, self.tw), C.install_state(g, app.frame_info), bool(app.jobs.busy_with(pkg)),
|
||||
thumbs.url(pkg, SHELF_ART, T.px(640), wait=False))
|
||||
old = self.shelf_cards.get(pkg)
|
||||
if not old or old[0] != key:
|
||||
old = self.shelf_cards[pkg] = (key, self.shelf_card(g, *key))
|
||||
controls.append(old[1])
|
||||
for pkg in set(self.shelf_cards) - {g["package"] for g in games}:
|
||||
self.shelf_cards.pop(pkg, None)
|
||||
self.shelf_row.controls = controls
|
||||
self.shelf.visible = bool(controls)
|
||||
|
||||
def shelf_card(self, g: dict, title: str, state: str | None, busy: bool, art: str | None) -> ft.Control:
|
||||
"""A wide cover: title, "Update ready" when the Frame runs an older build, Play on hover; click opens the
|
||||
game, right-click shows its menu (the same as the grid's)."""
|
||||
app = self.app
|
||||
pkg = g["package"]
|
||||
w, h = T.px(264), T.px(148)
|
||||
button = C.CoverButton(ft.Icons.PLAY_ARROW_ROUNDED, tr("Play on Frame"), lambda e: app.play(pkg, "frame"),
|
||||
T.px(48), launch=tr("Starting on Frame…"), reduce_motion=app.reduce_motion)
|
||||
quick = ft.Container(button.control, left=0, right=0, top=0, bottom=T.px(36), alignment=ft.Alignment.CENTER,
|
||||
opacity=0, animate_opacity=ft.Animation(180, ft.AnimationCurve.EASE_OUT), visible=not busy)
|
||||
badges = [C.install_badge("outdated")] if state == "outdated" else []
|
||||
if busy:
|
||||
badges = [C.pill(tr("Working…"), T.ACCENT, ft.Icons.SYNC_ROUNDED, solid=True)]
|
||||
cover = C.art_fill(art, placeholder_icon=C.platform_icon(g))
|
||||
shade = scrim()
|
||||
tile = ft.Container(
|
||||
ft.Stack([
|
||||
art_frame(cover),
|
||||
shade,
|
||||
ft.Container(C.bottom_fade(None, 0.92), left=0, right=0, bottom=0, top=T.px(48)),
|
||||
*([ft.Container(ft.Row(badges, spacing=T.px(4)), left=T.px(10), top=T.px(10))] if badges else []),
|
||||
ft.Container(button.status, left=0, right=0, top=0, bottom=T.px(36)), # below the button (clicks)
|
||||
quick,
|
||||
ft.Container(ft.Text(title, size=T.px(14), weight=ft.FontWeight.W_700, color=T.TEXT, max_lines=1,
|
||||
overflow=ft.TextOverflow.ELLIPSIS),
|
||||
left=T.px(12), right=T.px(12), bottom=T.px(10)),
|
||||
]),
|
||||
width=w, height=h, border_radius=T.RADIUS, bgcolor=T.SURFACE, border=ft.Border.all(1, T.BORDER),
|
||||
shadow=card_shadow(),
|
||||
tooltip=ft.Tooltip(message=tr("Click to open · right-click for quick actions"), wait_duration=1500),
|
||||
on_click=lambda e: app.open_game(pkg))
|
||||
hover_motion(tile, cover)
|
||||
|
||||
def hover(e):
|
||||
on = e.data in (True, "true")
|
||||
card_hover(tile, cover, shade, on, app.reduce_motion)
|
||||
tile.border = ft.Border.all(1, T.ACCENT if on else T.BORDER)
|
||||
quick.opacity = 1 if on else 0
|
||||
button.show(on)
|
||||
tile.update()
|
||||
tile.on_hover = hover
|
||||
# (padding: room for the hover lift and shadow inside the scrolling row, which clips)
|
||||
return ft.Container(ft.GestureDetector(content=tile,
|
||||
on_secondary_tap_down=lambda e: self.open_menu(pkg, e.global_position)),
|
||||
padding=ft.Padding(T.px(2), T.px(6), T.px(2), T.px(8)))
|
||||
|
||||
# ---------------------------------------------------------------- header / filter bar
|
||||
def _update_hint(self):
|
||||
@@ -456,7 +674,7 @@ class LibraryView:
|
||||
self.hint.content = C.callout(ft.Row([
|
||||
C.body(tr("Connect your Steam Frame to install games and see what's on it."), T.TEXT, expand=True),
|
||||
C.ghost(tr("Connect"), ft.Icons.ARROW_FORWARD_ROUNDED, lambda e: app.go("frame"), color=T.ACCENT)]),
|
||||
"info", ft.Icons.VIEW_IN_AR_ROUNDED)
|
||||
"info", G.FRAME)
|
||||
self.hint.visible = True
|
||||
else:
|
||||
self.hint.visible = False
|
||||
@@ -503,28 +721,18 @@ class LibraryView:
|
||||
C.update(self.subtitle, self.hint, self.filters)
|
||||
|
||||
def _seg(self, key: str, options: list[tuple[str, str]]) -> ft.Control:
|
||||
items = []
|
||||
for value, label in options:
|
||||
on = self.f.get(key) == value
|
||||
items.append(ft.Container(
|
||||
ft.Text(label, size=T.T_META, weight=ft.FontWeight.W_600, color=T.TEXT if on else T.TEXT_2),
|
||||
padding=ft.Padding(T.px(12), T.px(6), T.px(12), T.px(6)), border_radius=T.px(20),
|
||||
bgcolor=T.SURFACE_3 if on else None,
|
||||
on_click=lambda e, v=value: self._set(key, v), ink=True))
|
||||
return ft.Container(ft.Row(items, spacing=T.px(2), tight=True), padding=T.px(3), border_radius=T.px(22),
|
||||
border=ft.Border.all(1, T.BORDER))
|
||||
return C.segmented(options, self.f.get(key), lambda v: self._set(key, v))
|
||||
|
||||
def _menu_chip(self, key: str, label: str, options: list[tuple[str, str]]) -> ft.Control:
|
||||
current = dict(options).get(self.f.get(key), options[0][1])
|
||||
return ft.PopupMenuButton(
|
||||
return C.menu_button(
|
||||
content=ft.Container(ft.Row([C.meta(label + ":"), C.body(current, T.TEXT, size=T.T_META),
|
||||
ft.Icon(ft.Icons.EXPAND_MORE_ROUNDED, size=T.px(16), color=T.TEXT_2)],
|
||||
spacing=T.px(4), tight=True),
|
||||
padding=ft.Padding(T.px(12), T.px(7), T.px(8), T.px(7)), border_radius=T.px(20),
|
||||
border=ft.Border.all(1, T.BORDER)),
|
||||
items=[ft.PopupMenuItem(content=ft.Text(text), checked=self.f.get(key) == value,
|
||||
on_click=lambda e, v=value: self._set(key, v)) for value, text in options],
|
||||
bgcolor=T.SURFACE_2, tooltip="")
|
||||
items=[C.check_item(text, self.f.get(key) == value, lambda e, v=value: self._set(key, v))
|
||||
for value, text in options])
|
||||
|
||||
def _toggle_tag(self, tag: str):
|
||||
tags = list(self.f.get("tags") or [])
|
||||
@@ -534,13 +742,13 @@ class LibraryView:
|
||||
def _tag_menu(self, games: list[dict]) -> ft.Control:
|
||||
chosen = self.f.get("tags") or []
|
||||
label = ", ".join(chosen) if chosen else tr("Any")
|
||||
items = [ft.PopupMenuItem(content=ft.Text(t), checked=t in chosen, on_click=lambda e, t=t: self._toggle_tag(t))
|
||||
for t in all_tags(games)]
|
||||
items = [C.check_item(t, t in chosen, lambda e, t=t: self._toggle_tag(t)) for t in all_tags(games)]
|
||||
if chosen:
|
||||
items.append(ft.PopupMenuItem(content=ft.Text(tr("Clear tags")), icon=ft.Icons.CLEAR_ROUNDED,
|
||||
on_click=lambda e: self._set("tags", [])))
|
||||
return ft.PopupMenuButton(
|
||||
content=ft.Container(ft.Row([ft.Icon(ft.Icons.SELL_OUTLINED, size=T.px(14), color=T.TEXT_2),
|
||||
items += C.menu_items([None, (tr("Clear tags"), ft.Icons.CLOSE_ROUNDED, lambda e: self._set("tags", []))])
|
||||
return C.menu_button(
|
||||
content=ft.Container(ft.Row([ft.Container(ft.Icon(ft.Icons.SELL_OUTLINED, size=T.px(14), color=T.TEXT_2),
|
||||
width=T.px(16), height=T.px(16),
|
||||
alignment=ft.Alignment.CENTER), # sized: overlapped the label
|
||||
C.meta(tr("Tags:")),
|
||||
C.body(label if len(label) < 28
|
||||
else tr("{len} selected").format(len=len(chosen)), T.TEXT,
|
||||
@@ -549,7 +757,7 @@ class LibraryView:
|
||||
spacing=T.px(4), tight=True),
|
||||
padding=ft.Padding(T.px(12), T.px(7), T.px(8), T.px(7)), border_radius=T.px(20),
|
||||
border=ft.Border.all(1, T.ACCENT if chosen else T.BORDER)),
|
||||
items=items, bgcolor=T.SURFACE_2, tooltip=C.tip(HELP["tags"]))
|
||||
items=items, tooltip=C.tip(HELP["tags"]))
|
||||
|
||||
# ---------------------------------------------------------------- cards
|
||||
def _key(self, g: dict, pc: set[str], tw: set[str]) -> tuple:
|
||||
@@ -559,6 +767,12 @@ class LibraryView:
|
||||
pkg in pc, bool(job), self.app.quick_action(g)[0], thumbs.url(pkg, CARD_ART),
|
||||
self.app.frame_state)
|
||||
|
||||
def starting_text(self, g: dict) -> str:
|
||||
"""What a cover's Play button says while the game starts (Play goes to the Frame first, as play_options)."""
|
||||
app = self.app
|
||||
on_frame = app.frame_state == "connected" and C.install_state(g, app.frame_info) in ("installed", "outdated")
|
||||
return tr("Starting on Frame…") if on_frame else tr("Starting on this PC…")
|
||||
|
||||
def card(self, g: dict, pc: set[str], tw: set[str]) -> ft.Control:
|
||||
app = self.app
|
||||
pkg = g["package"]
|
||||
@@ -577,38 +791,40 @@ class LibraryView:
|
||||
if on_pc:
|
||||
badges.append(C.install_badge("on_pc"))
|
||||
if rift and g.get("exe_confirmed") is False:
|
||||
badges.append(C.pill(tr("Check exe"), T.WARN, ft.Icons.HELP_OUTLINE_ROUNDED, overlay=True,
|
||||
badges.append(C.pill(tr("Check program"), T.WARN, ft.Icons.HELP_OUTLINE_ROUNDED, overlay=True,
|
||||
tooltip=C.tip(HELP["check_exe"])))
|
||||
label, _, help_key = C.platform(g)
|
||||
platform = C.pill(label, T.PC if rift else T.TEXT, C.platform_icon(g), overlay=True,
|
||||
tooltip=C.tip(HELP[help_key]))
|
||||
check = ft.Container(ft.Checkbox(value=pkg in self.selected, active_color=T.ACCENT, check_color=T.ON_ACCENT,
|
||||
on_change=lambda e: self.toggle_selected(pkg)),
|
||||
bgcolor=T.soft("#000000", 0.6), border_radius=T.px(8), left=T.px(6), top=T.px(40),
|
||||
bgcolor=T.soft("#000000", 0.6), border_radius=T.RADIUS_SM, left=T.px(6), top=T.px(40),
|
||||
visible=self.select_mode)
|
||||
self.checks[pkg] = check
|
||||
overlay = ft.Container(left=0, right=0, top=0, bottom=0, border_radius=T.RADIUS) # the selected fade
|
||||
quick_label, quick_kind = app.quick_action(g)
|
||||
circle = ft.Container(
|
||||
ft.Icon(quick_icon(quick_kind), size=T.px(56), color=T.ON_ACCENT),
|
||||
width=T.px(96), height=T.px(96), border_radius=T.px(48), bgcolor=T.ACCENT, alignment=ft.Alignment.CENTER,
|
||||
shadow=ft.BoxShadow(blur_radius=28, spread_radius=2, color=T.soft("#000000", 0.6), offset=ft.Offset(0, 6)),
|
||||
tooltip=ft.Tooltip(message=quick_label, wait_duration=800), ink=True,
|
||||
on_click=lambda e: app.primary_action(pkg),
|
||||
scale=0.85, animate_scale=ft.Animation(160, ft.AnimationCurve.EASE_OUT)) if quick_label else None
|
||||
# one big round Play / Install button in the middle of the cover, shown on hover
|
||||
quick = ft.Container(circle, left=0, right=0, top=0, bottom=T.px(56), alignment=ft.Alignment.CENTER,
|
||||
opacity=0, animate_opacity=ft.Animation(160, ft.AnimationCurve.EASE_OUT)) \
|
||||
if circle else None
|
||||
# one round Play / Install button in the middle of the cover, shown on hover
|
||||
button = C.CoverButton(quick_icon(quick_kind), quick_label, lambda e: app.primary_action(pkg), T.px(60),
|
||||
launch=self.starting_text(g) if quick_kind == "play" else None,
|
||||
reduce_motion=app.reduce_motion) if quick_label else None
|
||||
quick = ft.Container(button.control, left=0, right=0, top=0, bottom=T.px(56), alignment=ft.Alignment.CENTER,
|
||||
opacity=0, animate_opacity=ft.Animation(180, ft.AnimationCurve.EASE_OUT)) \
|
||||
if button else None
|
||||
dim = state == "missing" and not on_pc
|
||||
cover = C.art_fill(art, opacity=0.5 if dim else 1.0,
|
||||
placeholder_icon=C.platform_icon(g))
|
||||
shade = scrim() if button else None
|
||||
tile = ft.Container(
|
||||
ft.Stack([
|
||||
C.art_fill(art, left=0, right=0, top=0, bottom=0, opacity=0.5 if dim else 1.0,
|
||||
placeholder_icon=C.platform_icon(g)),
|
||||
art_frame(cover),
|
||||
*([shade] if shade else []),
|
||||
ft.Container(C.bottom_fade(None, 0.92), left=0, right=0, bottom=0, top=T.px(90)),
|
||||
# platform + state badges in one row that wraps: on a narrow card "On Frame" covered "Android"
|
||||
ft.Container(ft.Row([platform, *badges], spacing=T.px(4), run_spacing=T.px(4), wrap=True),
|
||||
left=T.px(10), right=T.px(10), top=T.px(10)),
|
||||
*([quick] if quick else []),
|
||||
overlay,
|
||||
# the pill's layer below the button's: above it, the (empty) layer took the button's clicks
|
||||
*([ft.Container(button.status, left=0, right=0, top=0, bottom=T.px(56)), quick] if quick else []),
|
||||
check,
|
||||
ft.Container(ft.Column([
|
||||
ft.Text(display_title(g, tw), size=T.px(14), weight=ft.FontWeight.W_700, color=T.TEXT, max_lines=2,
|
||||
@@ -618,23 +834,28 @@ class LibraryView:
|
||||
], spacing=T.px(4)), left=T.px(12), right=T.px(12), bottom=T.px(12)),
|
||||
], expand=True),
|
||||
border_radius=T.RADIUS, bgcolor=T.SURFACE, border=ft.Border.all(1, T.BORDER), expand=True,
|
||||
scale=1.0, animate_scale=ft.Animation(140, ft.AnimationCurve.EASE_OUT),
|
||||
shadow=card_shadow(),
|
||||
tooltip=ft.Tooltip(message=tr("Click to open · right-click for quick actions · drag across cards to "
|
||||
"select several"), wait_duration=1500),
|
||||
on_click=lambda e: self.toggle_selected(pkg) if self.select_mode else app.open_game(pkg))
|
||||
hover_motion(tile, cover)
|
||||
|
||||
def hover(e):
|
||||
on = e.data in (True, "true")
|
||||
self.drag.hover(pkg, on)
|
||||
tile.scale = 1.03 if on else 1.0
|
||||
tile.border = ft.Border.all(1, T.ACCENT if on else T.BORDER)
|
||||
tile.shadow = card_shadow(on)
|
||||
self.marks[pkg] = (tile, overlay, on)
|
||||
self._paint_card(pkg)
|
||||
show = on and not self.select_mode
|
||||
card_hover(tile, cover, shade, on, app.reduce_motion)
|
||||
if shade:
|
||||
shade.opacity = 1 if show else 0
|
||||
if quick:
|
||||
quick.opacity = 1 if on and not self.select_mode else 0
|
||||
circle.scale = 1.0 if on else 0.85
|
||||
quick.opacity = 1 if show else 0
|
||||
button.show(show)
|
||||
tile.update()
|
||||
tile.on_hover = hover
|
||||
self.marks[pkg] = (tile, overlay, False)
|
||||
self._paint_card(pkg)
|
||||
# no key=: Flet freezes keyed controls, and cards change in place (hover, state); the grid only ever holds
|
||||
# the matching cards in order (see _apply), which is what fixed search and sorting
|
||||
return ft.GestureDetector(content=tile, expand=True,
|
||||
|
||||
@@ -25,8 +25,8 @@ def kind_label(kind: str | None) -> str:
|
||||
|
||||
def show_paste_dialog(app: FramePortApp) -> None:
|
||||
"""Add games → "Install from link…": paste a FrameDrop/FramePort button link, a manifest or a file URL."""
|
||||
field = ft.TextField(label=tr("Link"), hint_text="https://framedropvr.com/install?manifest=…", autofocus=True,
|
||||
width=T.px(560), border_color=T.BORDER)
|
||||
field = C.field(label=tr("Link"), hint_text="https://framedropvr.com/install?manifest=…", autofocus=True,
|
||||
expand=True)
|
||||
|
||||
def go(e=None):
|
||||
text = (field.value or "").strip()
|
||||
@@ -35,14 +35,14 @@ def show_paste_dialog(app: FramePortApp) -> None:
|
||||
app.page.pop_dialog()
|
||||
open_link(app, text, pasted=True)
|
||||
field.on_submit = go
|
||||
app.page.show_dialog(ft.AlertDialog(
|
||||
title=ft.Text(tr("Install from a link")), bgcolor=T.SURFACE_2,
|
||||
content=ft.Column([
|
||||
app.page.show_dialog(C.dialog(
|
||||
tr("Install from a link"),
|
||||
ft.Column([
|
||||
C.body(tr("Paste the address of an \"Install with FrameDrop\" button (right-click it → Copy link), a "
|
||||
"FramePort or FrameDrop manifest (.json) or a direct link to an APK, a Linux build (.zip) or a "
|
||||
"Windows program (.exe).")),
|
||||
ft.Row([field, C.help_icon("install_links")]),
|
||||
], tight=True, spacing=T.S3, width=T.px(600)),
|
||||
], tight=True, spacing=T.S3),
|
||||
actions=[C.ghost(tr("Cancel"), on_click=lambda e: app.page.pop_dialog()),
|
||||
C.primary(tr("Continue"), ft.Icons.ARROW_FORWARD_ROUNDED, on_click=go)]))
|
||||
|
||||
@@ -57,7 +57,7 @@ def open_link(app: FramePortApp, text: str, pasted: bool = False) -> None:
|
||||
return
|
||||
|
||||
def run(job: Job):
|
||||
job.reporter.stage("Reading the install link")
|
||||
job.reporter.stage(tr("Reading the install link"))
|
||||
m = deeplink.fetch_manifest(req)
|
||||
sizes = {f.url: deeplink.head_size(f.url) for f in m.files}
|
||||
icon = deeplink.fetch_icon(m) # FramePort's manifest extension (None without one)
|
||||
@@ -122,7 +122,7 @@ def download_and_install(app: FramePortApp, m: deeplink.Manifest, icon=None) ->
|
||||
def run(job: Job):
|
||||
rep = job.reporter
|
||||
path = deeplink.download(m, rep)
|
||||
rep.stage("Adding to the library")
|
||||
rep.stage(tr("Adding to the library"))
|
||||
g = pipeline.add_from_link(m, path, rep, icon=icon)
|
||||
pkg = g["package"]
|
||||
try:
|
||||
|
||||