Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af798c0bf3 | ||
|
|
ed714c9d65 | ||
|
|
832b401630 |
No files matched your search
@@ -159,8 +159,6 @@ 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: Demo tour (docs/media, rendered by the showcase workflow)
|
||||
run: if [ -f docs/media/frameport-tour.mp4 ]; then cp docs/media/frameport-tour.mp4 out/FramePort-tour.mp4; fi
|
||||
- name: Checksums
|
||||
run: cd out && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
|
||||
- name: Publish release
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
name: showcase
|
||||
# Docs screenshots and the demo tour, 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:
|
||||
video:
|
||||
description: "Also record the demo tour (docs/media/frameport-tour.mp4 + the README teaser)"
|
||||
type: boolean
|
||||
default: false
|
||||
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: Record the tour this time?
|
||||
id: video
|
||||
env:
|
||||
INPUT_VIDEO: ${{ inputs.video }}
|
||||
BEFORE: ${{ github.event.before }}
|
||||
run: |
|
||||
record=false
|
||||
if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then
|
||||
[ "$INPUT_VIDEO" = true ] && record=true
|
||||
elif git diff --name-only "$BEFORE" "$GITHUB_SHA" 2>/dev/null \
|
||||
| grep -qE '^(docs/showcase/tour\.yaml|scripts/showcase/)'; then
|
||||
record=true # the storyboard or the recorder changed (UI tweaks alone don't re-record ~10 MB)
|
||||
fi
|
||||
echo "record=$record" >> "$GITHUB_OUTPUT"
|
||||
echo "record the tour: $record"
|
||||
- name: Demo tour
|
||||
if: steps.video.outputs.record == 'true'
|
||||
run: uv run python scripts/showcase/record_tour.py --work showcase-out/tour
|
||||
|
||||
- name: Keep the renders
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: showcase
|
||||
path: |
|
||||
showcase-out/screenshots
|
||||
showcase-out/tour/tour.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${{ steps.video.outputs.record == 'true' && ' and the demo tour' || '' }}"
|
||||
title: "Update docs screenshots${{ steps.video.outputs.record == 'true' && ' and the demo tour' || '' }}"
|
||||
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,20 +10,8 @@ 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` (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
|
||||
`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
|
||||
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
|
||||
@@ -65,14 +53,6 @@ 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
|
||||
@@ -81,31 +61,10 @@ 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`/`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
|
||||
`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
|
||||
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;
|
||||
@@ -238,15 +197,9 @@ 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`), changelog dialog, job
|
||||
then 6 h), sidebar card (hidden control, toggled), Library bar (`library_bar`), notes dialog (`ft.Markdown`), job
|
||||
`app-update` that restarts only when no other job is active, `apply_pending_at_start()` in `main()` for
|
||||
"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)]
|
||||
"Install updates automatically"; Settings → Updates. 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.
|
||||
@@ -280,17 +233,11 @@ 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 + demo video (docs/SHOWCASE.md): never by hand. `uv run python scripts/showcase/render_docs.py`
|
||||
renders `docs/showcase/shots.yaml` into `docs/images/` (only visibly changed files are rewritten; `--check` for CI)
|
||||
and `scripts/showcase/record_tour.py [--draft]` records `docs/showcase/tour.yaml` into
|
||||
`docs/media/frameport-tour.mp4` + `docs/images/tour-teaser.webp`. Both build the demo library first
|
||||
(`demo_home.py`: 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. 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 tour when its files change, or on dispatch) and opens PR
|
||||
`showcase/update`; releases attach `FramePort-tour.mp4`. `scripts/scrub_library.py` (the owner's own library) is
|
||||
only for private screenshots now.
|
||||
- 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.
|
||||
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
|
||||
|
||||
@@ -9,9 +9,7 @@
|
||||
|
||||
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) (about 90 seconds, 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))
|
||||
@@ -20,8 +18,6 @@ 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.
|
||||
@@ -113,7 +109,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 recipe…** (it fills in the
|
||||
**Tested something? Share it.** In FramePort open the game → **…** → **Share working config…** (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 = 66
|
||||
AGENT_VERSION = 64
|
||||
HOME = os.path.expanduser("~")
|
||||
STEAM = os.path.join(HOME, ".local/share/Steam")
|
||||
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
|
||||
@@ -2082,11 +2082,6 @@ 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:
|
||||
@@ -2096,112 +2091,6 @@ 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"])
|
||||
@@ -4832,8 +4721,6 @@ 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)
|
||||
@@ -4878,20 +4765,6 @@ 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 = []
|
||||
@@ -5163,7 +5036,6 @@ 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
|
||||
@@ -5195,15 +5067,7 @@ 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),
|
||||
"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
|
||||
"fan": bool(self.fan), "intervals": list(MON_INTERVALS), "filters": list(MON_FILTERS)}
|
||||
|
||||
# -------------------------------------------------------------------- games
|
||||
def deployments(self, now):
|
||||
@@ -5410,73 +5274,53 @@ 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)}
|
||||
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]
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
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 = "scan" in plan and (now - self.scan_at >= SCAN_SECONDS or not self.procs)
|
||||
scan = now - self.scan_at >= SCAN_SECONDS or not self.procs
|
||||
if scan:
|
||||
self.scan(now, wall)
|
||||
self.scan_at = now
|
||||
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:
|
||||
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:
|
||||
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
|
||||
@@ -5563,10 +5407,9 @@ 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}, {"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."""
|
||||
{"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."""
|
||||
import threading
|
||||
|
||||
mon = monitor or Monitor()
|
||||
@@ -5608,8 +5451,6 @@ 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
|
||||
|
||||
@@ -5,10 +5,10 @@ e7554c6343ee2989b0a273ee6230e65c25bfe6499eefd00de19f5f0fee58754f ./arm64-v8a/li
|
||||
383054f8b3b41dde76d062c71856cd3163655e50009c08454bc1793f393ead65 ./arm64-v8a/libfpg.so
|
||||
8a8f6b1da8952cb3933a5b53558424a5fc56043b2527a16bb6dd62a00d2de01a ./arm64-v8a/libframe_xrshim.so
|
||||
fc559dbe0b87eecc3641256837293260cefb7c2ce7b21d808d10edd2a2dba9fc ./arm64-v8a/libglshim.so
|
||||
cc5b493cadefe76ad13fd096d3f8494a140ba593e0e1692db12d284bc548c1cf ./arm64-v8a/libopenxr_loader_generic.so
|
||||
05692ee7129538dff04ae8260caf9a8f2cbd595b706fcfa188a029f282720345 ./arm64-v8a/libopenxr_loader_generic.so
|
||||
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
|
||||
aa4dc0020c77e12d41ef6ce80b23ad90c9cb7e882338eddf2261efe8645cf38d ./arm64-v8a/libvrapi.so
|
||||
c10412dd76a65a1d587b7ed226367d1a6f2bec238c733c97ee67eb8870c868e8 ./armeabi-v7a/libopenxr_loader_generic.so
|
||||
ab0fa11c3aa1e37c538ba374026640a925ef31e6709765d4058a44cf4c4e9b31 ./armeabi-v7a/libopenxr_loader_generic.so
|
||||
1871eae093432d277da4bc751bf5f3269dfcf11f9168260b0c3caadb0dedb19d ./dex/oculusos-stubs.dex
|
||||
1aa733117cf57ccff7cf23f0425dbfd73b0332a3ef1c905ceeca0ccd0449c4e0 ./linux-arm64/XR_APILAYER_FRAMEPORT_timefix.json
|
||||
28c2430a02bbd8902c5bfb9562c6fd0e318654f9e05c095bfeb94b0450ab1b07 ./linux-arm64/libxr_frameport_timefix.so
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package: com.PixelToys.BattleSisters
|
||||
title: BattleSisters
|
||||
status: works
|
||||
notes: Starts in VR; controller buttons and vibration work.
|
||||
details: Unity 2019.4 with Unity's built-in Oculus support. frame.unity_oculus_check starts VR (Meta's system-app check),
|
||||
adds the frame wait its legacy loop never makes (without it the GPU hung, black screen) and lets Unity's Oculus
|
||||
input accept Lepton's device model (it only reported controllers on a device named "Oculus ...", so buttons were
|
||||
dead). haptic_fix stops the first controller vibration from freezing the Frame (OVRPort's loader read its duration
|
||||
in nanoseconds as seconds and the game ran out of memory).
|
||||
notes: Plays; controller buttons and vibration work, hands follow the controllers (pose_time_fix).
|
||||
details: Unity 2019.4 with Unity's built-in Oculus support. frame.unity_oculus_check starts VR (Meta's system-app
|
||||
check), adds the frame wait its legacy loop never makes (without it the GPU hung, black screen) and lets Unity's
|
||||
Oculus input accept Lepton's device model (it only reported controllers on a device named "Oculus ...", so buttons
|
||||
were dead). haptic_fix stops the first controller vibration from freezing the Frame (OVRPort's loader read its
|
||||
duration in nanoseconds as seconds and the game ran out of memory). With pose_time_fix the hands follow the controllers
|
||||
- OVRPlugin asked for hand poses at Android's monotonic "now", which on SteamOS 0.4.5 is 2.56 s behind the runtime's
|
||||
XrTime, so the hands lagged far behind.
|
||||
tested_version: 1.2.4
|
||||
engine: Unity
|
||||
xr: VrApi
|
||||
@@ -18,9 +20,10 @@ frame:
|
||||
- frame.unity_gl_shim
|
||||
adapter:
|
||||
haptic_fix: 1
|
||||
pose_time_fix: 1
|
||||
verified:
|
||||
date: '2026-10-06'
|
||||
date: '2026-10-08'
|
||||
issue: 48
|
||||
updated: '2026-10-06'
|
||||
min_app: 0.11.1
|
||||
updated: '2026-10-08'
|
||||
min_app: 0.12.1
|
||||
source_hint: Battle Sister
|
||||
@@ -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 recipe…** opens a prefilled GitHub issue so your
|
||||
Tried an untested game? Its page asks how it runs; **Share working config…** 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 recipe** (game menu, `frameport share-recipe <pkg>`): saves the recipe as a user catalog entry and
|
||||
- **Share working config** (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… works with a lone APK too. Its data is found when the data folder sits next
|
||||
- **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
|
||||
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 recipe can be shared from the app (**Share working recipe…**).
|
||||
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…**).
|
||||
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`.
|
||||
|
||||
|
||||
@@ -99,7 +99,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…** adds a single Windows program; the Frame runs it through Proton (as a
|
||||
- **Add games → Add a Windows program (.exe)…** 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 +114,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 → Add from a link…** takes the button's address (right-click → Copy link), a `framedrop://` or
|
||||
- **Add games → Install 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,8 +125,7 @@ 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. 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
|
||||
game" text when no store has them. 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.
|
||||
@@ -140,7 +139,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): while the tab is
|
||||
- **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
|
||||
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.
|
||||
@@ -191,7 +190,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 a PC game folder…**. FramePort finds the game's program and asks when there is more than one
|
||||
**Add games → Add one 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.
|
||||
|
||||
@@ -202,7 +201,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 a PC game folder…** with the game's folder (pick the program that
|
||||
**Windows games without VR:** **Add games → Add one 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).
|
||||
@@ -250,7 +249,7 @@ Command line: `frameport frame send <files> --dest videos` (`frameport frame sto
|
||||
|
||||
## Sharing a working game, reporting a problem
|
||||
|
||||
- **Share working recipe…** (game menu): opens a prefilled GitHub issue with the game's patches and settings. Accepted
|
||||
- **Share working config…** (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,
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
# "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.
|
||||
@@ -86,6 +86,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| Black flat window, then a GPU hang: kernel `hangcheck detected gpu lockup` (offending task the game), `zink: DEVICE LOST`, Unity render-thread crash; `outside of frame bounds` thousands of times a second (e.g. BattleSisters, Unity 2019.4) | Unity 2019 on its built-in VR (no `libOculusXRPlugin.so`) uses the same legacy frame loop as Unity 2017: no `xrWaitFrame`, the render thread floods the GPU | `frame.unity_oculus_check` adds the ovrpshim frame wait for these too (revision 2) |
|
||||
| Unity built-in VR game (with `frame.unity_oculus_check`) freezes at a scene switch: the log stops after `Boot: Activating Scene: …`, the process stays alive, every thread sleeps (e.g. Sniper Elite VR, Unity 2019.4) | The shim's `xrWaitFrame` blocks until the previously waited frame is begun; Unity skipped beginning it at the scene switch and its render thread then waited for the main thread (gdb: UnityMain in vrclient `CSxrSession::StartNextFrame` ← `ovrp_WaitToBeginFrame` ← `fpov_Update2`). OVRPlugin also only begins the frame index it waited for | `frame.unity_oculus_check` revision 5: libunity.so's `ovrp_BeginFrame`/`ovrp_EndFrame` go through the shim, which waits ≤ 50 ms for the last waited frame to begin, else skips the wait (log `the last waited frame wasn't begun`), and gives a begin/end of another index the waited one |
|
||||
| Unity built-in VR game: the hands/weapons trail the controllers by centimetres when moving (headset fine, 72 fps), e.g. Sniper Elite VR | Unity's physics-step `ovrp_Update2` (prediction 0) makes OVRPlugin locate the nodes at the monotonic clock's "now", the XrTime base on a Quest but 0.05–0.9 s behind the Frame's XrTime; the runtime extrapolates backwards and the render-step reads after it get those poses too. A larger prediction is capped by OVRPlugin (~0.07 s) | `frame.unity_oculus_check` revision 5 holds the physics-step update back: both steps read the render update's display-time poses |
|
||||
| OVRPlugin game: the hands lag behind the controllers (also with `ovrp_hold_physics` on or off; rendering fine), e.g. BattleSisters | OVRPlugin passes its monotonic-clock "now" on as the OpenXR time (OVRPort's dispatcher converts XR_KHR_convert_timespec_time 1:1: the Frame's runtime lacks it, and FrameBridge's emulation is never asked), but the Frame's XrTime runs ahead of CLOCK_MONOTONIC (2.56 s on SteamOS 0.4.5): with `pose_debug=1` the hand spaces show `time - predicted display time -2564 ms`; BattleSisters also asks for its head at XrTime 0.1 s every frame | `adapter.pose_time_fix` (FrameBridge, suggested for Unity built-in OVRPlugin games): a located time nearer the monotonic clock than XrTime's "now" is moved by the clock offset measured at xrWaitFrame, one more than 0.5 s before the display time goes to "now" (log `pose_time_fix: …`; `pose_debug=1` counts both per 5 s). Once a build has this FrameBridge it is toggled in settings.conf (no rebuild) |
|
||||
| Unreal game stuck on a loading image after the intro, frames keep coming (72 fps), no crash (e.g. Vader Immortal) | suspect: a Meta Platform SDK request no message ever answers | diagnostics: `frame.ovr_trace` (opt-in) logs every `ovr_*` call, the answers `ovr_PopMessage` returns and every 10 s the unanswered requests (`fp_ovrtrace` in launch.log). Never fake an entitlement answer |
|
||||
| Own-engine game crashes in `libVkLayer_fossilize.so` (Fossilize's recording thread, e.g. Roblox) | same as Deadpool VR: uninitialised pointers in what Fossilize records | `frame.vk_sanitize` now also covers own-engine libraries that load `libvulkan.so` by name |
|
||||
| Crash right after the game gets focus, in `vrclient.so … UpdateActionStateInternal` / `sxr_xrSyncActions` (e.g. Myst) | a race in the Frame runtime's input code on the first sync after focus (not every launch) | adapter `sync_guard` (input syncs one at a time with event polling, paused 250 ms after FOCUSED) |
|
||||
@@ -103,7 +104,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 → Add 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 → Install 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) |
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
# Screenshots and the demo video
|
||||
|
||||
The pictures in the docs and the demo tour are rendered by scripts, never taken by hand. Two 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 90 s) | `docs/showcase/tour.yaml` | `docs/media/frameport-tour.mp4` (+ `.jpg` poster), `docs/images/tour-teaser.webp` (README) |
|
||||
|
||||
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 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).
|
||||
|
||||
## 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_tour.py --draft # quick 720p check of a storyboard edit
|
||||
uv run python scripts/showcase/record_tour.py # the real thing → docs/media + the teaser
|
||||
```
|
||||
|
||||
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.
|
||||
`record_tour.py --names` prints what can be clicked after each scene, which helps when writing steps. The video is
|
||||
encoded at the best quality that fits 12 MB, the teaser at 4 MB.
|
||||
|
||||
## 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
|
||||
- open_game: ${game} # or {package: …, advanced: true}
|
||||
- call: {fn: settings_dialog, args: ["${game}"]} # any app method
|
||||
- hover: "Batman: Arkham Shadow" # the pointer: by name…
|
||||
- hover: {name: "Batman: Arkham Shadow", dy: 0.3} # …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: "Batman: Arkham Shadow · 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.
|
||||
|
||||
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`
|
||||
- `live_stream`: a test picture through the real relay.
|
||||
- `monitor_details`, `type_tab`, `select_files` and `settings_section`.
|
||||
|
||||
In the tour, 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. The tour only when `tour.yaml` or the scripts changed, or when
|
||||
it's ticked on a manual run (so UI tweaks don't re-commit a 10 MB video).
|
||||
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 the committed tour as `FramePort-tour.mp4`.
|
||||
|
||||
## Gallery
|
||||
|
||||
These are renders the README doesn't show (yet):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
@@ -1,61 +0,0 @@
|
||||
# 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).
|
||||
@@ -1,28 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 5.2 KiB |
@@ -1,26 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 5.3 KiB |
@@ -1,21 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 104 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 84 KiB |
|
Before Width: | Height: | Size: 418 KiB After Width: | Height: | Size: 365 KiB |
|
Before Width: | Height: | Size: 506 KiB |
|
Before Width: | Height: | Size: 730 KiB After Width: | Height: | Size: 917 KiB |
|
Before Width: | Height: | Size: 145 KiB |
|
Before Width: | Height: | Size: 226 KiB After Width: | Height: | Size: 188 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 100 KiB |
|
Before Width: | Height: | Size: 752 KiB After Width: | Height: | Size: 916 KiB |
|
Before Width: | Height: | Size: 607 KiB After Width: | Height: | Size: 643 KiB |
|
Before Width: | Height: | Size: 935 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 291 KiB |
@@ -1,63 +0,0 @@
|
||||
# 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.camouflaj.manta # the game the Monitor tab and the sidebar's live card show
|
||||
|
||||
games:
|
||||
- package: com.camouflaj.manta
|
||||
frame: internal
|
||||
played: 0.05
|
||||
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: 3.1
|
||||
- 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
|
||||
@@ -1,109 +0,0 @@
|
||||
# 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, running 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)"
|
||||
@@ -1,133 +0,0 @@
|
||||
# The demo tour: scripts/showcase/record_tour.py plays these scenes in one window on the demo library (with a
|
||||
# pretend Frame), records them, captions each one and joins them with crossfades into docs/media/frameport-tour.mp4
|
||||
# (+ docs/images/tour-teaser.webp from the `teaser` parts). Steps: scripts/showcase/steps.py; the pointer moves like
|
||||
# a hand (eased, slightly curved) and is drawn into the picture.
|
||||
#
|
||||
# caption: [title, line] the lower third shown at the start of the scene
|
||||
# teaser: [from, seconds] the part of this scene that goes into the README's teaser
|
||||
# hold: seconds to keep filming after the last step (default 0.6)
|
||||
|
||||
vars:
|
||||
game: com.camouflaj.manta # installed and running 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: "Riven"
|
||||
- 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: "GPU"
|
||||
- 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: "Batman: Arkham Shadow · 2026-10-04 21:50"
|
||||
- wait: 0.8
|
||||
- click: "Batman: Arkham Shadow · 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
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"name": "Ember & Ice",
|
||||
"base": "portal",
|
||||
"dual": true,
|
||||
"colors": {
|
||||
"ACCENT": "#FF5A36",
|
||||
"ACCENT_SOFT": "#3A1710",
|
||||
"SECONDARY": "#5CE1E6",
|
||||
"SECONDARY_SOFT": "#0E3033",
|
||||
"PC": "#5CE1E6",
|
||||
"INFO": "#5CE1E6"
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,8 @@ static int controller_fix = 1;
|
||||
static int swapchain_fix = 1;
|
||||
static int rect_clamp = 1;
|
||||
static int pose_consistency = 0; // repeat xrLocateViews queries for one display time get the same poses (GitHub #8) // clamp submitted image rects to their swapchain (SteamVR rejects a 1 px overrun)
|
||||
static int pose_time_fix; // poses asked for at CLOCK_MONOTONIC "now" or far in the past: at XrTime "now" (pose_time.c)
|
||||
static int pose_debug; // diagnostics: requested pose times vs the predicted display time (pose_time.c)
|
||||
static int layer_fix = 1;
|
||||
static int mutable_fix = 0;
|
||||
static int swap_eyes = 0;
|
||||
@@ -160,6 +162,8 @@ static void read_settings(const char *path) {
|
||||
if (sscanf(line, "swapchain_fix=%f", &value) == 1) swapchain_fix = value != 0;
|
||||
if (sscanf(line, "rect_clamp=%f", &value) == 1) rect_clamp = value != 0;
|
||||
if (sscanf(line, "pose_consistency=%f", &value) == 1) pose_consistency = value != 0;
|
||||
if (sscanf(line, "pose_debug=%f", &value) == 1) pose_debug = value != 0;
|
||||
if (sscanf(line, "pose_time_fix=%f", &value) == 1) pose_time_fix = value != 0;
|
||||
if (sscanf(line, "layer_fix=%f", &value) == 1) layer_fix = value != 0;
|
||||
if (sscanf(line, "mutable_fix=%f", &value) == 1) mutable_fix = value != 0;
|
||||
if (sscanf(line, "swap_eyes=%f", &value) == 1) swap_eyes = value != 0;
|
||||
@@ -753,6 +757,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetSystemProperties(XrInstance instance, XrSyst
|
||||
}
|
||||
|
||||
#include "flip_vk.c"
|
||||
#include "pose_time.c"
|
||||
|
||||
// XR_KHR_convert_timespec_time for runtimes that lack it (Frame): XrTime is derived from the monotonic clock
|
||||
// using the offset measured at the last xrWaitFrame. The runtime's own implementation is preferred.
|
||||
@@ -762,10 +767,14 @@ static PFN_xrConvertTimeToTimespecTimeKHR runtime_time_to_timespec;
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL emu_timespec_to_time(XrInstance instance, const struct timespec *ts, XrTime *time) {
|
||||
if (runtime_timespec_to_time) {
|
||||
XrResult r = runtime_timespec_to_time(instance, ts, time);
|
||||
if (r != XR_ERROR_FUNCTION_UNSUPPORTED) return r;
|
||||
if (r != XR_ERROR_FUNCTION_UNSUPPORTED) {
|
||||
if (XR_SUCCEEDED(r) && time) pose_time_note("xrConvertTimespecTimeToTimeKHR (runtime)", 0, 0, *time);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
if (!ts || !time) return XR_ERROR_VALIDATION_FAILURE;
|
||||
*time = (XrTime)((int64_t)ts->tv_sec * 1000000000ll + ts->tv_nsec + (xr_time_calibrated ? xr_time_offset : 0));
|
||||
pose_time_note("xrConvertTimespecTimeToTimeKHR", 0, 0, *time);
|
||||
return XR_SUCCESS;
|
||||
}
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL emu_time_to_timespec(XrInstance instance, XrTime time, struct timespec *ts) {
|
||||
@@ -781,6 +790,8 @@ static XRAPI_ATTR XrResult XRAPI_CALL emu_time_to_timespec(XrInstance instance,
|
||||
}
|
||||
|
||||
XRAPI_ATTR XrResult XRAPI_CALL xrLocateSpace(XrSpace space, XrSpace baseSpace, XrTime time, XrSpaceLocation *location) {
|
||||
time = pose_time_fixed(time);
|
||||
pose_time_note("xrLocateSpace", (uint64_t)(uintptr_t)space, (uint64_t)(uintptr_t)baseSpace, time);
|
||||
if (emulate_scene && location) {
|
||||
XrPosef pose; XrSpaceLocationFlags flags;
|
||||
if (locate_fake(space, baseSpace, time, &pose, &flags)) {
|
||||
@@ -796,6 +807,14 @@ XRAPI_ATTR XrResult XRAPI_CALL xrLocateSpace(XrSpace space, XrSpace baseSpace, X
|
||||
static XrResult locate_spaces_common(const char *name, XrSession session, const XrSpacesLocateInfo *info,
|
||||
XrSpaceLocations *locations) {
|
||||
int any_fake = 0;
|
||||
XrSpacesLocateInfo moved;
|
||||
if (info && pose_time_fix) {
|
||||
moved = *info;
|
||||
moved.time = pose_time_fixed(info->time);
|
||||
info = &moved;
|
||||
}
|
||||
if (info) pose_time_note(name, info->spaceCount ? (uint64_t)(uintptr_t)info->spaces[0] : 0,
|
||||
(uint64_t)(uintptr_t)info->baseSpace, info->time);
|
||||
if (emulate_scene && info && locations) {
|
||||
any_fake = fake_space_index(info->baseSpace) >= 0;
|
||||
for (uint32_t i = 0; i < info->spaceCount && !any_fake; ++i) any_fake = fake_space_index(info->spaces[i]) >= 0;
|
||||
@@ -1079,6 +1098,8 @@ XRAPI_ATTR XrResult XRAPI_CALL xrWaitFrame(XrSession session, const XrFrameWaitI
|
||||
// predictedDisplayTime is about one display period ahead of "now".
|
||||
xr_time_offset = (int64_t)(state->predictedDisplayTime - state->predictedDisplayPeriod) - mono;
|
||||
xr_time_calibrated = 1;
|
||||
last_display_period = state->predictedDisplayPeriod;
|
||||
pose_time_note_offset((long long)(state->predictedDisplayTime - mono));
|
||||
if (layer_debug) debug_aim_vs_grip(state->predictedDisplayTime);
|
||||
}
|
||||
return result;
|
||||
@@ -1143,6 +1164,13 @@ XRAPI_ATTR XrResult XRAPI_CALL xrLocateViews(XrSession session, const XrViewLoca
|
||||
uint32_t capacity, uint32_t *count, XrView *views) {
|
||||
PFN_xrLocateViews fn = (PFN_xrLocateViews)lookup(active_instance, "xrLocateViews");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
XrViewLocateInfo moved;
|
||||
if (info && pose_time_fix) {
|
||||
moved = *info;
|
||||
moved.displayTime = pose_time_fixed(info->displayTime);
|
||||
info = &moved;
|
||||
}
|
||||
if (info) pose_time_note("xrLocateViews", (uint64_t)(uintptr_t)info->space, 0, info->displayTime);
|
||||
int cacheable = pose_consistency && info && state && count && views && capacity > 0;
|
||||
if (cacheable && pose_cache_lookup(session, info, state, capacity, count, views)) return XR_SUCCESS;
|
||||
XrResult result = fn(session, info, state, capacity, count, views);
|
||||
@@ -1257,6 +1285,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
|
||||
__atomic_exchange_n(&input_sync_ok, 0, __ATOMIC_RELAXED), input_last_sync_result,
|
||||
__atomic_exchange_n(&input_bool_reads, 0, __ATOMIC_RELAXED),
|
||||
__atomic_exchange_n(&input_bool_true, 0, __ATOMIC_RELAXED));
|
||||
pose_time_report();
|
||||
frames = 0; drift_sum = drift_max = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Included by frame_adapter.c: the times games locate poses at (pose_time_fix, pose_debug).
|
||||
//
|
||||
// pose_debug (diagnostics): every ~5 s, per located space (xrLocateSpace/xrLocateSpaces) and for xrLocateViews, the
|
||||
// number of calls and the min/max of (requested time - the last xrWaitFrame's predictedDisplayTime); for
|
||||
// xrConvertTimespecTimeToTimeKHR the same for its answers, plus the spread of the XrTime-vs-CLOCK_MONOTONIC offset
|
||||
// measured at xrWaitFrame.
|
||||
|
||||
static XrDuration last_display_period;
|
||||
|
||||
#define PT_SLOTS 12
|
||||
typedef struct {
|
||||
const char *kind;
|
||||
uint64_t space, base;
|
||||
int count;
|
||||
long long min, max; // ns relative to the last predicted display time
|
||||
} pt_stat;
|
||||
static pt_stat pt_stats[PT_SLOTS];
|
||||
static int pt_overflow;
|
||||
static long long pt_offset_min, pt_offset_max;
|
||||
static int pt_offset_count;
|
||||
static pthread_mutex_t pt_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static void pose_time_note(const char *kind, uint64_t space, uint64_t base, XrTime time) {
|
||||
if (!pose_debug || !last_predicted_time) return;
|
||||
long long d = (long long)(time - last_predicted_time);
|
||||
pthread_mutex_lock(&pt_lock);
|
||||
int i = 0;
|
||||
while (i < PT_SLOTS && pt_stats[i].count &&
|
||||
!(pt_stats[i].kind == kind && pt_stats[i].space == space && pt_stats[i].base == base))
|
||||
++i;
|
||||
if (i == PT_SLOTS) {
|
||||
++pt_overflow;
|
||||
} else {
|
||||
pt_stat *s = &pt_stats[i];
|
||||
if (!s->count) s->kind = kind, s->space = space, s->base = base, s->min = s->max = d;
|
||||
if (d < s->min) s->min = d;
|
||||
if (d > s->max) s->max = d;
|
||||
++s->count;
|
||||
}
|
||||
pthread_mutex_unlock(&pt_lock);
|
||||
}
|
||||
|
||||
static void pose_time_note_offset(long long offset) {
|
||||
if (!pose_debug) return;
|
||||
pthread_mutex_lock(&pt_lock);
|
||||
if (!pt_offset_count || offset < pt_offset_min) pt_offset_min = offset;
|
||||
if (!pt_offset_count || offset > pt_offset_max) pt_offset_max = offset;
|
||||
++pt_offset_count;
|
||||
pthread_mutex_unlock(&pt_lock);
|
||||
}
|
||||
|
||||
// pose_time_fix: Meta's OVRPlugin takes "now" from CLOCK_MONOTONIC and passes it on as an XrTime unchanged (no
|
||||
// conversion reaches FrameBridge: OVRPort's dispatcher answers XR_KHR_convert_timespec_time itself, 1:1, since the
|
||||
// Frame's runtime lacks it). On a Quest XrTime is the monotonic clock; on the Frame it runs ahead (2.56 s measured on
|
||||
// SteamOS 0.4.5, 0.05-0.9 s seen on older builds), so every "now" pose (Unity's physics step, OVRInput's controller
|
||||
// poses) was located that far in the past and the hands trailed the controllers (BattleSisters, Sniper Elite VR).
|
||||
// A located time nearer the monotonic clock than XrTime's "now" is taken as a monotonic timestamp and moved to the
|
||||
// same moment in XrTime (offset measured at xrWaitFrame); a time more than PT_PAST_LIMIT before the predicted display
|
||||
// time that isn't one (BattleSisters asks for its head at XrTime 0.1 s) is located at "now".
|
||||
#define PT_PAST_LIMIT 500000000ll // 0.5 s: no runtime keeps a longer pose history; real past queries are far shorter
|
||||
#define PT_MIN_OFFSET 5000000ll // XrTime and the monotonic clock this close: nothing to tell apart or to fix
|
||||
static int pt_fixed_mono, pt_fixed_past;
|
||||
static long long pt_fixed_min;
|
||||
|
||||
static XrTime pose_time_fixed(XrTime time) {
|
||||
if (!pose_time_fix || !last_predicted_time || !xr_time_calibrated) return time;
|
||||
int64_t offset = xr_time_offset; // XrTime "now" minus the monotonic clock
|
||||
if (offset < PT_MIN_OFFSET && offset > -PT_MIN_OFFSET) return time;
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
long long mono = (long long)ts.tv_sec * 1000000000ll + ts.tv_nsec;
|
||||
long long d_mono = (long long)time - mono, d_xr = (long long)time - (mono + offset);
|
||||
long long abs_mono = d_mono < 0 ? -d_mono : d_mono, abs_xr = d_xr < 0 ? -d_xr : d_xr;
|
||||
XrTime fixed;
|
||||
int kind;
|
||||
if (abs_mono < PT_PAST_LIMIT && abs_mono < abs_xr) {
|
||||
fixed = (XrTime)(time + offset), kind = 0; // a monotonic timestamp
|
||||
} else if ((long long)(time - last_predicted_time) < -PT_PAST_LIMIT) {
|
||||
fixed = (XrTime)(mono + offset), kind = 1; // far in the past: now
|
||||
} else {
|
||||
return time;
|
||||
}
|
||||
if (pose_debug) {
|
||||
long long d = (long long)(time - last_predicted_time);
|
||||
pthread_mutex_lock(&pt_lock);
|
||||
if (!(pt_fixed_mono + pt_fixed_past) || d < pt_fixed_min) pt_fixed_min = d;
|
||||
++*(kind ? &pt_fixed_past : &pt_fixed_mono);
|
||||
pthread_mutex_unlock(&pt_lock);
|
||||
}
|
||||
static int logged[2];
|
||||
if (logged[kind]++ < 3)
|
||||
LOG("pose_time_fix: pose asked for at %.1f ms from the predicted display time (%s) located at %.1f ms",
|
||||
(long long)(time - last_predicted_time) / 1e6, kind ? "far in the past" : "a monotonic-clock time",
|
||||
(long long)(fixed - last_predicted_time) / 1e6);
|
||||
return fixed;
|
||||
}
|
||||
|
||||
// called from the pacing statistics in xrEndFrame
|
||||
static void pose_time_report(void) {
|
||||
if (!pose_debug) return;
|
||||
pthread_mutex_lock(&pt_lock);
|
||||
LOG("pose_debug: period %.2f ms; XrTime - monotonic at xrWaitFrame (%d): %.2f..%.2f ms", last_display_period / 1e6,
|
||||
pt_offset_count, pt_offset_min / 1e6, pt_offset_max / 1e6);
|
||||
for (int i = 0; i < PT_SLOTS && pt_stats[i].count; ++i)
|
||||
LOG("pose_debug: %s space=0x%llx base=0x%llx: %d calls, time - predicted display time %.2f..%.2f ms",
|
||||
pt_stats[i].kind, (unsigned long long)pt_stats[i].space, (unsigned long long)pt_stats[i].base,
|
||||
pt_stats[i].count, pt_stats[i].min / 1e6, pt_stats[i].max / 1e6);
|
||||
if (pt_overflow) LOG("pose_debug: %d calls not counted (more than %d spaces)", pt_overflow, PT_SLOTS);
|
||||
if (pt_fixed_mono + pt_fixed_past)
|
||||
LOG("pose_debug: pose_time_fix moved %d monotonic-clock times and %d far-past times (earliest asked %.2f ms)",
|
||||
pt_fixed_mono, pt_fixed_past, pt_fixed_min / 1e6);
|
||||
memset(pt_stats, 0, sizeof(pt_stats));
|
||||
pt_overflow = pt_offset_count = pt_fixed_mono = pt_fixed_past = 0;
|
||||
pthread_mutex_unlock(&pt_lock);
|
||||
}
|
||||
@@ -22,10 +22,6 @@ 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 recipe can be shared from the app (**Share working recipe…**).\n"
|
||||
"suggests patches for them, and a working config can be shared from the app (**Share working config…**).\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,9 +69,6 @@ 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
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
#!/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"
|
||||
|
||||
|
||||
def build(home: Path, offline: bool = False, refresh: bool = False, log=print) -> dict:
|
||||
"""Write the demo library into `home` (emptied first). Sets FRAMEPORT_HOME for this process."""
|
||||
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)
|
||||
log(f"demo library: {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) -> 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)
|
||||
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)")
|
||||
args = ap.parse_args()
|
||||
build(args.home, offline=args.offline, refresh=args.refresh)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,556 +0,0 @@
|
||||
"""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: crops of the games' own
|
||||
store art (hero/landscape) when the library has some (docs screenshots), else colour gradients."""
|
||||
|
||||
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])))
|
||||
running = frame_state().get("running")
|
||||
if running: # the running game's shots first (Take screenshot adds one of it)
|
||||
games.sort(key=lambda ga: ga[0]["package"] != running)
|
||||
self.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)
|
||||
self.owners.append((None, "SteamVR", spare))
|
||||
# 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, *self.owners[i % len(self.owners)]))
|
||||
return shots
|
||||
|
||||
def _shot(self, t: float, i: int, pkg: str | None, title: str, arts: list) -> dict:
|
||||
"""One Steam screenshot (a crop of the game's art; a different one per i, so they don't all look alike)."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
name = time.strftime("%Y%m%d%H%M%S", time.localtime(t)) + "_1.jpg"
|
||||
path = os.path.join(self.home, "shots", name)
|
||||
if arts:
|
||||
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)
|
||||
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 (another crop of its art), 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, *self.owners[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
|
||||
running = self.GAME or frame_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)]
|
||||
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}],
|
||||
"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
|
||||
|
||||
|
||||
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 frame rate with a few-second stutter now and
|
||||
then (also in the two minutes sent first), so the card's sparkline (5 s points) has a shape and visibly moves.
|
||||
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.8))
|
||||
if (t // 8) % 3 == 1: # 8 samples of stutter in every 24
|
||||
fps = 56 + 6 * abs(((t % 8) - 4) / 4) + rnd.uniform(-1.5, 1.5)
|
||||
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 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
|
||||
|
||||
@@ -1,232 +0,0 @@
|
||||
"""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 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 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
|
||||
@@ -1,224 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record the demo tour (docs/showcase/tour.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 captioned, given title
|
||||
and end cards and joined with crossfades.
|
||||
|
||||
python scripts/showcase/record_tour.py [--scenes library,install] [--draft] [--names]
|
||||
|
||||
Writes docs/media/frameport-tour.mp4 (+ .jpg poster) and docs/images/tour-teaser.webp, and a tour.json timeline
|
||||
next to the work files (--work, default a temp folder). --draft: 720p, quick encode, no teaser, into --work only
|
||||
(for checking a storyboard edit). --names prints what can be clicked after each scene (writing steps).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
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
|
||||
|
||||
TOUR = REPO / "docs" / "showcase" / "tour.yaml"
|
||||
MEDIA = REPO / "docs" / "media"
|
||||
TEASER = REPO / "docs" / "images" / "tour-teaser.webp"
|
||||
SCENE_KEYS = {"name", "caption", "teaser", "hold", "steps"}
|
||||
VIEWPORT = (1440, 810) # the layout size; filmed at 4/3 device pixels = 1920x1080
|
||||
BUDGET_MB, TEASER_MB = 12.0, 4.0
|
||||
|
||||
|
||||
def load_tour(path: Path = TOUR) -> dict:
|
||||
import yaml
|
||||
|
||||
from showcase import steps
|
||||
|
||||
data = yaml.safe_load(path.read_text())
|
||||
seen = set()
|
||||
for sc in data.get("scenes") or []:
|
||||
name = sc.get("name")
|
||||
if not name or name in seen:
|
||||
raise steps.StepError(f"tour.yaml: missing or repeated scene name {name!r}")
|
||||
seen.add(name)
|
||||
unknown = set(sc) - SCENE_KEYS
|
||||
if unknown:
|
||||
raise steps.StepError(f"tour.yaml: {name}: unknown key(s) {sorted(unknown)}")
|
||||
cap = sc.get("caption")
|
||||
if cap is not None and not (isinstance(cap, list) and 1 <= len(cap) <= 2):
|
||||
raise steps.StepError(f"tour.yaml: {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"tour.yaml: {name}: teaser is [from, seconds]")
|
||||
steps.validate(sc.get("steps") or [], f"tour.yaml {name}")
|
||||
for card in ("title", "end"):
|
||||
if not (data.get(card) or {}).get("heading"):
|
||||
raise steps.StepError(f"tour.yaml: {card} needs a heading")
|
||||
return data
|
||||
|
||||
|
||||
def tour_installs(session, pace: float = 0.5) -> None:
|
||||
"""Installs in the tour 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 main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--scenes", default=None, help="comma-separated scene names (default: all)")
|
||||
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 (default: temp)")
|
||||
ap.add_argument("--home", type=Path, default=None, help="demo data dir (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")
|
||||
ap.add_argument("--out", type=Path, default=MEDIA, help="where frameport-tour.mp4 goes")
|
||||
ap.add_argument("--teaser", type=Path, default=TEASER, help="where the teaser WebP goes")
|
||||
args = ap.parse_args()
|
||||
|
||||
tour = load_tour()
|
||||
scenes = tour["scenes"]
|
||||
if args.scenes:
|
||||
want = args.scenes.split(",")
|
||||
scenes = [s for s in scenes if s["name"] in want]
|
||||
work = args.work or Path(tempfile.mkdtemp(prefix="fp-tour-"))
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
home = args.home or Path(tempfile.mkdtemp(prefix="fp-tour-home-"))
|
||||
demo_home.build_for_render(home, offline=args.offline, allow_missing_art=args.allow_missing_art)
|
||||
|
||||
from showcase import postprod, steps
|
||||
from showcase.fakes import LiveMonitorSession
|
||||
from showcase.web import Screencast, Server
|
||||
|
||||
variables = tour.get("vars") or {}
|
||||
|
||||
def script(server) -> int:
|
||||
scale = 1.0 if args.draft else 4 / 3
|
||||
s = server.session(VIEWPORT, cursor=True, device_scale=scale)
|
||||
tour_installs(s)
|
||||
cast = Screencast(s, work / "frames", quality=80 if args.draft else 92)
|
||||
s.app.go("library")
|
||||
s.sleep(2.5)
|
||||
s.park()
|
||||
cast.start()
|
||||
s.sleep(0.8)
|
||||
timeline = []
|
||||
for sc in scenes:
|
||||
t0 = time.time()
|
||||
print(f"SCENE {sc['name']}", flush=True)
|
||||
try:
|
||||
steps.run(s, sc.get("steps") or [], variables)
|
||||
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
|
||||
raw = work / "raw.mp4"
|
||||
first = postprod.frames_to_video(work / "frames", raw, end=timeline[-1]["end"], size=size)
|
||||
colors = postprod.theme_colors("portal")
|
||||
logo = (REPO / "src" / "frameport" / "ui" / "icons" / "logo.svg").read_text()
|
||||
cards = work / "cards"
|
||||
cards.mkdir(exist_ok=True)
|
||||
clips, durations, scene_clips = [], [], {}
|
||||
for which in ("title",):
|
||||
c = tour[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)
|
||||
clips.append(clip)
|
||||
durations.append(c.get("seconds", 3.0))
|
||||
by_name = {sc["name"]: sc for sc in scenes}
|
||||
for item in timeline:
|
||||
sc = by_name[item["name"]]
|
||||
start, 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), length, cap, clip, size=size)
|
||||
clips.append(clip)
|
||||
durations.append(length)
|
||||
scene_clips[sc["name"]] = (clip, length)
|
||||
item.update(clip_start=round(start, 3), seconds=round(length, 3))
|
||||
c = tour["end"]
|
||||
png = postprod.render_card(server.playwright, postprod.card_html(
|
||||
c["heading"], c.get("line", ""), c.get("footer", ""), logo, colors), cards / "end.png")
|
||||
postprod.card_clip(png, c.get("seconds", 3.0), work / "end.mp4")
|
||||
clips.append(work / "end.mp4")
|
||||
durations.append(c.get("seconds", 3.0))
|
||||
# the final cut
|
||||
if args.draft:
|
||||
out = work / "tour-draft.mp4"
|
||||
postprod.join(clips, durations, out, transition=0.25, crf=28, size=size)
|
||||
crf = 28
|
||||
else:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
out = args.out / "frameport-tour.mp4"
|
||||
crf = postprod.encode_within(clips, durations, out, BUDGET_MB)
|
||||
postprod.poster(out, durations[0] + 1.5, args.out / "frameport-tour.jpg")
|
||||
# the teaser: each scene's `teaser` part (with its caption)
|
||||
parts, lengths = [], []
|
||||
for sc in scenes:
|
||||
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:
|
||||
args.teaser.parent.mkdir(parents=True, exist_ok=True)
|
||||
q = postprod.teaser_webp(parts, lengths, args.teaser, budget_mb=TEASER_MB)
|
||||
print(f"TEASER {args.teaser} ({args.teaser.stat().st_size / 1e6:.2f} MB, quality {q})", flush=True)
|
||||
total = postprod.joined_length(durations, 0.25 if args.draft else 0.5)
|
||||
(work / "tour.json").write_text(json.dumps({"scenes": timeline, "seconds": round(total, 2), "crf": crf,
|
||||
"video": str(out)}, indent=1))
|
||||
print(f"TOUR {out} ({out.stat().st_size / 1e6:.2f} MB, {total:.1f} s, crf {crf}); work: {work}", flush=True)
|
||||
return 0
|
||||
|
||||
return Server(monitor_session=LiveMonitorSession).run(script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,219 +0,0 @@
|
||||
#!/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
|
||||
MEAN_LIMIT, PIXEL_LIMIT, PIXEL_SHARE = 0.5, 24, 0.002
|
||||
|
||||
|
||||
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):
|
||||
"""A script for web.Server.run: renders every shot into out/<name>.png."""
|
||||
from showcase import steps
|
||||
from showcase.web import call
|
||||
|
||||
def script(server) -> int:
|
||||
failed = 0
|
||||
for shot in shots:
|
||||
t0 = time.monotonic()
|
||||
vw, vh = shot.get("viewport") or defaults.get("viewport") or (1280, 820)
|
||||
s = server.session((vw, vh))
|
||||
try:
|
||||
call(s, 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(out / f"{shot['name']}.png", clip=box)
|
||||
log(f"SHOT {shot['name']} ({time.monotonic() - t0:.1f} s)")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
server.errors.append(f"{shot['name']}: {exc!r}")
|
||||
failed += 1
|
||||
finally:
|
||||
s.close()
|
||||
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")
|
||||
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)
|
||||
from showcase.fakes import FrozenMonitorSession
|
||||
|
||||
return Server(monitor_session=FrozenMonitorSession).run(lambda server: finish(script(server)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,274 +0,0 @@
|
||||
"""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 (a Flet update race under load) would otherwise leave the old page in the
|
||||
picture for the rest of a recording; then the route is opened directly (and a warning 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)
|
||||
|
||||
|
||||
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}
|
||||
@@ -1,531 +0,0 @@
|
||||
"""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."""
|
||||
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,22 +17,9 @@ 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
|
||||
@@ -41,25 +28,339 @@ PORT = int(os.environ.get("FRAMEPORT_SMOKE_PORT", "8557")) # two smoke runs at
|
||||
ERRORS: list[str] = []
|
||||
|
||||
|
||||
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 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()
|
||||
|
||||
|
||||
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."""
|
||||
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):
|
||||
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()
|
||||
if not shot_done.wait(STEP_TIMEOUT):
|
||||
ERRORS.append(f"{name}: no screenshot within {STEP_TIMEOUT} s, stopping")
|
||||
return
|
||||
time.sleep(STEP_SECONDS)
|
||||
|
||||
|
||||
def find_button(root, text: str):
|
||||
@@ -99,8 +400,7 @@ 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: "
|
||||
"changelog dialog, what's new bar + dialog, Settings changelog)")
|
||||
ap.add_argument("--update", action="store_true", help="pretend a new FramePort release exists (update UI)")
|
||||
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,
|
||||
@@ -110,18 +410,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 "
|
||||
"(positions for --viewport 1440x900)")
|
||||
"right-clicks (menus) in Files, Screenshots and the Library; prints what got selected")
|
||||
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)
|
||||
@@ -130,25 +430,19 @@ 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")), ("live-streaming", fake_live_stream),
|
||||
("keyboard", lambda a: (stop_fake_live(a), a.go("keyboard"))),
|
||||
("live", lambda a: a.go("live")), ("keyboard", lambda a: a.go("keyboard")),
|
||||
("monitor", lambda a: a.go("monitor")), ("monitor-details", open_monitor_details),
|
||||
("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"))]
|
||||
("tools", lambda a: a.go("settings"))]
|
||||
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.show_activity(False), a.navigate(0), time.sleep(3),
|
||||
steps.append(("library-menu", lambda a: (a.page.pop_dialog(), a.navigate(0), time.sleep(3),
|
||||
a.library_view.open_menu(game))))
|
||||
if args.docs:
|
||||
steps = [("library", lambda a: a.navigate(0))]
|
||||
@@ -164,63 +458,10 @@ 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"))))
|
||||
# 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)
|
||||
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
|
||||
|
||||
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])
|
||||
@@ -257,12 +498,11 @@ 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((400, 300), (680, 300), (950, 300)), # 3 shots (the first row)
|
||||
"screenshots-dragged": right_click(950, 300),
|
||||
"screenshots": drag((680, 280), (950, 280), (950, 430)), # 3 shots
|
||||
"screenshots-dragged": right_click(950, 430),
|
||||
"screenshots-menu": escape,
|
||||
# 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
|
||||
"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
|
||||
if args.linux:
|
||||
def linux_filter(a, value):
|
||||
a.navigate(0)
|
||||
@@ -300,7 +540,10 @@ def main() -> int:
|
||||
ImageDraw.Draw(im).ellipse((72, 72, 184, 184), fill=(255, 214, 102, 255))
|
||||
im.save(icon)
|
||||
|
||||
steps = [("library", lambda a: a.navigate(0)),
|
||||
def add_menu(a):
|
||||
a.navigate(0)
|
||||
time.sleep(2)
|
||||
steps = [("library", add_menu),
|
||||
("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")))]
|
||||
@@ -311,31 +554,7 @@ 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)
|
||||
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)))
|
||||
mouse["library"] = add_menu_open # tall pages: run with e.g. --viewport 1280x3200
|
||||
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]
|
||||
@@ -363,48 +582,14 @@ 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 __version__, updates
|
||||
from frameport import 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=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()
|
||||
sums_url=None, wheel_url=None,
|
||||
notes="## What's new\n- Self-update test release\n- **Bold** and `code` in notes")
|
||||
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(), 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()))]
|
||||
("update-settings", lambda a: (a.page.pop_dialog(), a.go("settings")))]
|
||||
if args.frame:
|
||||
from frameport.frame.connection import parse_target
|
||||
|
||||
@@ -430,67 +615,55 @@ 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]
|
||||
# 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(), []
|
||||
ready, done = threading.Event(), []
|
||||
|
||||
if args.fake_frame: # never reach a real Frame (start-up auto-connect, discovery, the 30 s poll)
|
||||
install_fakes(game)
|
||||
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
|
||||
|
||||
def app_main(page: ft.Page):
|
||||
try:
|
||||
app = FramePortApp(page)
|
||||
if args.fake_frame:
|
||||
attach_fake_frame(app)
|
||||
app.target = FakeTarget()
|
||||
app.frame_info, app.frame_state = app.target.describe(), "connected"
|
||||
except Exception: # noqa: BLE001
|
||||
ERRORS.append("startup: " + traceback.format_exc())
|
||||
return
|
||||
threading.Thread(target=driver, args=(app, steps, ready, shot_done, done), daemon=True).start()
|
||||
threading.Thread(target=driver, args=(app, steps, ready, 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
|
||||
|
||||
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)
|
||||
time.sleep(6)
|
||||
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 = 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])
|
||||
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)
|
||||
time.sleep(1.5)
|
||||
page.screenshot(path=str(args.out / f"{shot:02d}-{name}.png"))
|
||||
shot += 1
|
||||
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
|
||||
if name in mouse:
|
||||
mouse[name](page)
|
||||
time.sleep(2)
|
||||
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())
|
||||
|
||||
|
Before Width: | Height: | Size: 248 KiB |
@@ -110,65 +110,3 @@ 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,8 +15,6 @@ 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
|
||||
|
||||
@@ -103,18 +101,6 @@ 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]
|
||||
@@ -233,7 +219,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
|
||||
|
||||
@@ -1,327 +0,0 @@
|
||||
"""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,7 +318,6 @@ 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
|
||||
@@ -336,9 +335,6 @@ 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)
|
||||
@@ -346,18 +342,14 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
if relay.ended:
|
||||
break
|
||||
continue
|
||||
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"
|
||||
if f is None:
|
||||
break
|
||||
self._chunk(f)
|
||||
sent += 1
|
||||
self.wfile.write(b"0\r\n\r\n")
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as exc:
|
||||
why = f"it disconnected ({type(exc).__name__})"
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):
|
||||
pass
|
||||
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")
|
||||
@@ -622,13 +614,6 @@ 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,10 +149,3 @@ 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)
|
||||
@@ -129,6 +129,15 @@ SETTINGS = [
|
||||
"Repeat xrLocateViews queries for the same display time get the first, fully tracked answer again. Games that "
|
||||
"ask several times per frame got slightly different poses and rendered parts of the frame with different heads: "
|
||||
"judder (e.g. I Am Cat; proposed by Klownicle, GitHub #8)."),
|
||||
("pose_time_fix", "int", 0, "Locate poses at the right time",
|
||||
"Poses a game asks for at a CLOCK_MONOTONIC time, or more than 0.5 s before the frame's display time, are located "
|
||||
"at the same moment in the runtime's time (or now). Meta's OVRPlugin passes the monotonic clock on as the "
|
||||
"OpenXR time, which on the Frame runs seconds behind the runtime's clock, so its \"now\" poses (Unity's physics "
|
||||
"step, controller poses) came from the past: hands trailing the controllers (e.g. BattleSisters, Sniper Elite "
|
||||
"VR)."),
|
||||
("pose_debug", "int", 0, "Pose time diagnostics (log)",
|
||||
"Every 5 s, logs per located space how far the requested times are from the frame's predicted display time, and "
|
||||
"the runtime clock's offset from the monotonic clock. No effect on the game."),
|
||||
("haptic_fix", "int", 0, "Fix controller vibration freezes",
|
||||
"Routes OVRPlugin through FramePort's extension shim, which turns Meta's amplitude-envelope vibrations into "
|
||||
"plain ones: OVRPort's loader reads their nanosecond duration as seconds and allocates gigabytes, freezing the "
|
||||
@@ -210,6 +219,9 @@ UI: dict[str, dict] = {
|
||||
"pose_consistency": dict(group="picture", level="advanced", label="Steadier head tracking",
|
||||
help="For games that judder or shimmer while you hold your head still (e.g. I Am Cat).",
|
||||
control=("switch",)),
|
||||
"pose_time_fix": dict(group="controllers", level="advanced", label="Fix hands lagging behind controllers",
|
||||
help="For games whose hands trail the controllers when you move them (e.g. BattleSisters).",
|
||||
control=("switch",)),
|
||||
"haptic_fix": dict(group="controllers", level="advanced", label="Fix freezes when controllers vibrate",
|
||||
help="For games that freeze the Frame when a controller vibrates (e.g. Lucky's Tale). Needs a "
|
||||
"rebuild.",
|
||||
@@ -291,7 +303,7 @@ UI: dict[str, dict] = {
|
||||
"foveation_fix", "hide_space_warp", "swapchain_fix", "layer_fix", "gl_hide_multiview", "mutable_fix",
|
||||
"flip_quads", "swap_eyes", "vk_validation", "rect_clamp", "gl_hide_msrtt", "strip_color_bias", "snapshot",
|
||||
"strip_depth", "respace_kick", "layer_debug", "eye_debug", "input_diag", "release_wait", "vk_hide_fdm",
|
||||
"ovrp_begin_gate", "ovrp_hold_physics")},
|
||||
"ovrp_begin_gate", "ovrp_hold_physics", "pose_debug")},
|
||||
}
|
||||
|
||||
|
||||
@@ -321,6 +333,11 @@ class AdapterSetting(Patch):
|
||||
return Suggestion(True, "Meta's OVRPlugin vibrates controllers through OVRPort's loader, which turns some "
|
||||
"vibrations into gigabyte allocations that freeze the Frame (e.g. Lucky's Tale, "
|
||||
"BattleSisters): vibrations are converted before they reach it.", {"value": 1})
|
||||
if (self.key == "pose_time_fix" and a.engine == "Unity" and "libOVRPlugin.so" in a.libs
|
||||
and not a.extra.get("oculus_xr_plugin") and "libOculusXRPlugin.so" not in a.libs):
|
||||
return Suggestion(True, "Unity's built-in Oculus support reads controller poses through OVRPlugin at its "
|
||||
"monotonic \"now\", seconds in the past on the Frame: they are located at the "
|
||||
"right time (e.g. BattleSisters, Sniper Elite VR).", {"value": 1})
|
||||
if self.key == "equirect_emul" and uses_equirect_layers(a):
|
||||
return Suggestion(True, "The game draws 360° layers (e.g. a video player's theatre or 360° videos), which "
|
||||
"the Frame's runtime can't show: show them as panels around you.", {"value": 1})
|
||||
@@ -357,6 +374,7 @@ class AdapterSetting(Patch):
|
||||
"vk_query_slots": lambda a: a.engine == "Unreal" and ap.is_vulkan(a),
|
||||
"vk_validation": lambda a: a.engine == "Unreal",
|
||||
"haptic_fix": lambda a: "libOVRPlugin.so" in a.libs,
|
||||
"pose_time_fix": lambda a: "libOVRPlugin.so" in a.libs,
|
||||
"vk_spec_fixes": lambda a: a.engine == "Unreal" and ap.is_vulkan(a),
|
||||
"controller_models": ap.may_use_render_models,
|
||||
**{k: ap.is_gles for k in ("equirect_emul", "equirect_face", "equirect_res", "equirect_flip",
|
||||
|
||||
@@ -602,7 +602,12 @@ def set_recipe(package: str, recipe: Recipe) -> None:
|
||||
|
||||
|
||||
def reset_recipe(package: str) -> Recipe:
|
||||
"""Back to the suggested recipe (catalog or heuristics) for the game's analysis (Quest and Rift alike)."""
|
||||
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
|
||||
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 recipe" publish)."""
|
||||
"""A catalog recipe from a library entry (what "Save as known-good" and "Share working config" 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.")
|
||||
@@ -1,56 +0,0 @@
|
||||
"""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")
|
||||
@@ -1,176 +0,0 @@
|
||||
"""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 and use … → Change program… to pick it.",
|
||||
"game (or right-click → Change executable) 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 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_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_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,9 +39,8 @@ 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, 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.",
|
||||
"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.",
|
||||
"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 "
|
||||
@@ -70,7 +69,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 → Add from a link….",
|
||||
"link into Add games → Install 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.",
|
||||
@@ -97,27 +96,23 @@ 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 → 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.",
|
||||
"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.",
|
||||
"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. "
|
||||
"Turning on Developer Mode closes the Frame's desktop; the setup finishes on its own and "
|
||||
"FramePort connects by itself. No password needed.",
|
||||
"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 "
|
||||
@@ -130,17 +125,8 @@ 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 (for example 4XVR's Internal "
|
||||
"by browsing folders. Video players that list only their own folder (e.g. 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 "
|
||||
@@ -174,9 +160,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.",
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 264 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 396 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 369 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 302 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 297 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 342 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 339 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 261 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 288 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 326 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 361 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 321 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 286 B |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 1.9 KiB |
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 2.0 KiB |
@@ -1,135 +0,0 @@
|
||||
"""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)
|
||||
@@ -1,131 +0,0 @@
|
||||
"""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,223 +1,40 @@
|
||||
"""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)."""
|
||||
"""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."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import flet as ft
|
||||
|
||||
# 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")
|
||||
# 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"
|
||||
|
||||
# "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]] = []
|
||||
# text
|
||||
TEXT = "#ECEDF3"
|
||||
TEXT_2 = "#A9ADBD" # secondary
|
||||
TEXT_3 = "#737889" # meta / disabled
|
||||
|
||||
# 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)
|
||||
# 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"
|
||||
|
||||
# spacing / shape / type (at 100 %; set_scale() multiplies them)
|
||||
# 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}
|
||||
_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}
|
||||
S1, S2, S3, S4, S5, S6 = 4, 8, 12, 16, 24, 32
|
||||
RADIUS = 12
|
||||
RADIUS_SM = 8
|
||||
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
|
||||
T_TITLE, T_H2, T_BODY, T_META, T_SMALL = 28, 16, 13, 12, 11
|
||||
SCALE = 1.0
|
||||
|
||||
|
||||
@@ -274,7 +91,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=SECONDARY, on_secondary=ON_ACCENT, surface=SURFACE, on_surface=TEXT, on_surface_variant=TEXT_2,
|
||||
secondary=PC, 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,
|
||||
@@ -291,19 +108,13 @@ 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=RADIUS_XS,
|
||||
decoration=ft.BoxDecoration(bgcolor=SURFACE_3, border_radius=6,
|
||||
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
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
"""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,6 +1,5 @@
|
||||
"""The GUI side of self-update: finds new releases in the background, shows them (sidebar card, Library bar, a dialog
|
||||
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."""
|
||||
with the release notes) and updates in one click. frameport.updates does the work."""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
@@ -11,12 +10,11 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import flet as ft
|
||||
|
||||
from .. import REPO_URL, __version__, updates
|
||||
from .. import __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:
|
||||
@@ -29,43 +27,19 @@ 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.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._version = C.meta("", 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=bool(old and old.visible),
|
||||
padding=T.S3, border_radius=T.RADIUS_SM, bgcolor=T.ACCENT, ink=True, visible=False,
|
||||
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)
|
||||
@@ -89,8 +63,6 @@ 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 ""
|
||||
@@ -121,14 +93,13 @@ class Updater:
|
||||
return
|
||||
page = self.app.page
|
||||
kind = updates.install_kind()
|
||||
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)]
|
||||
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.")
|
||||
|
||||
def skip(e):
|
||||
def later(e):
|
||||
updates.skip(up.version)
|
||||
self._set(None)
|
||||
page.pop_dialog()
|
||||
@@ -136,38 +107,23 @@ class Updater:
|
||||
def go(e):
|
||||
page.pop_dialog()
|
||||
self.install()
|
||||
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),
|
||||
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),
|
||||
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
|
||||
@@ -180,28 +136,35 @@ class Updater:
|
||||
if up.version == __version__:
|
||||
self.app.toast(tr("You already have the latest dev build ({version})").format(version=up.version))
|
||||
return
|
||||
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.page.run_thread(lambda: self._confirm_dev(up))
|
||||
self.app.run_bg(work)
|
||||
|
||||
def _confirm_dev(self, up: updates.Update, changes: list[updates.ChangelogEntry] | None = None) -> None:
|
||||
def _confirm_dev(self, up: updates.Update) -> None:
|
||||
page = self.app.page
|
||||
changes = changes or [updates.entry_from_update(up)]
|
||||
notes = up.notes.strip() or tr("No notes.")
|
||||
|
||||
def go(e):
|
||||
page.pop_dialog()
|
||||
self.found = up
|
||||
self.changes = changes
|
||||
self.install()
|
||||
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),
|
||||
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())))),
|
||||
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"), G.TEST, go)]))
|
||||
C.primary(tr("Install dev build"), ft.Icons.SCIENCE_OUTLINED, go)]))
|
||||
|
||||
# ---------------------------------------------------------------- installing
|
||||
def install(self) -> None:
|
||||
@@ -246,7 +209,7 @@ class Updater:
|
||||
raise RuntimeError(tr("{value} failed ({returncode})")
|
||||
.format(value=cmd[0], returncode=out.returncode))
|
||||
self.restart = self._restart_process
|
||||
rep.stage(tr("Restarting"))
|
||||
rep.stage("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)
|
||||
@@ -296,77 +259,17 @@ 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, 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)
|
||||
"""The Library's "update available" bar (None when there's nothing to show)."""
|
||||
up = app.updater.found if getattr(app, "updater", None) else None
|
||||
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("Not now"), on_click=lambda e: (updates.snooze(up.version), app.updater._set(None))),
|
||||
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))),
|
||||
], spacing=T.S3), "info", ft.Icons.SYSTEM_UPDATE_ROUNDED)
|
||||
|
||||
|
||||
|
||||
@@ -15,22 +15,13 @@ from ..jobs import Job
|
||||
if TYPE_CHECKING:
|
||||
from ..app import FramePortApp
|
||||
|
||||
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)
|
||||
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"))}
|
||||
|
||||
|
||||
def _dur(job: Job) -> str:
|
||||
@@ -40,14 +31,18 @@ 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 -> (transit, log text or None)
|
||||
self._transits: dict[int, C.Transit] = {} # running job id -> its transit, kept across tile rebuilds
|
||||
self._live: dict[int, tuple] = {} # running job id -> (progress bar, message, stage text, log text or None)
|
||||
# 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
|
||||
@@ -100,9 +95,11 @@ class ActivityPanel:
|
||||
self._tiles[j.id] = cached
|
||||
rebuilt = True
|
||||
elif running and j.id in self._live:
|
||||
transit, log = self._live[j.id]
|
||||
transit.set(j, **self.app.transit_info(j))
|
||||
live.append(transit.control)
|
||||
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]
|
||||
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)
|
||||
@@ -122,8 +119,6 @@ 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())
|
||||
@@ -166,10 +161,11 @@ 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.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)
|
||||
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)
|
||||
head = ft.Row([
|
||||
C.spinner() if running
|
||||
ft.ProgressRing(width=T.px(18), height=T.px(18), stroke_width=T.px(2), color=T.ACCENT) 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],
|
||||
@@ -178,13 +174,11 @@ class ActivityPanel:
|
||||
if job.active else []),
|
||||
], vertical_alignment=ft.CrossAxisAlignment.START, spacing=T.S3)
|
||||
parts: list[ft.Control] = [head]
|
||||
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 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 expanded:
|
||||
if job.stages:
|
||||
parts.append(ft.Column([
|
||||
@@ -208,22 +202,21 @@ 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_OUTLINED,
|
||||
*([C.ghost(tr("Full launch log"), ft.Icons.DESCRIPTION_ROUNDED,
|
||||
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][0], log)
|
||||
self._live[job.id] = (*self._live[job.id][:3], 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),
|
||||
ink=not running)
|
||||
on_click=None if running else lambda e: self._toggle(self.expanded, job.id))
|
||||
|
||||
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 C.dropdown(value=str(v), width=T.px(220),
|
||||
return ft.Dropdown(value=str(v), width=T.px(220), dense=True, border_color=T.BORDER,
|
||||
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,8 +201,12 @@ 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(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)))
|
||||
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))
|
||||
apply_visibility()
|
||||
@@ -19,7 +19,9 @@ if TYPE_CHECKING:
|
||||
|
||||
def show_art_dialog(app: FramePortApp, package: str) -> None:
|
||||
g = library.game(package)
|
||||
term = C.search(value=g.get("title") or package, expand=True)
|
||||
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)
|
||||
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("")
|
||||
@@ -41,7 +43,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 Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update 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)
|
||||
@@ -54,7 +56,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.RADIUS_SM, height=T.px(120)), height=T.px(120)),
|
||||
ft.Container(C.art_fill(r["preview"], radius=T.px(8), 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,
|
||||
@@ -78,19 +80,20 @@ 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 Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update 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(C.dialog(
|
||||
tr("Artwork for {get}").format(get=g.get('title')),
|
||||
ft.Column([
|
||||
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([
|
||||
ft.Row([term, C.secondary(tr("Search"), ft.Icons.SEARCH_ROUNDED, search)], spacing=T.S2),
|
||||
status, results,
|
||||
], spacing=T.S3, tight=True),
|
||||
actions=[C.ghost(tr("Use your own images…"), ft.Icons.UPLOAD_FILE_OUTLINED,
|
||||
], 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,
|
||||
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())]))
|
||||
@@ -122,7 +125,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 Steam art on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
action=tr("Update on Frame"), on_action=lambda e: app.update_steam_art(package))
|
||||
else:
|
||||
app.toast(message)
|
||||
|
||||
@@ -152,16 +155,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.RADIUS_SM, bgcolor=T.SURFACE_3, alignment=ft.Alignment.CENTER)
|
||||
border_radius=T.px(8), bgcolor=T.SURFACE_3, alignment=ft.Alignment.CENTER)
|
||||
else:
|
||||
box = (C.art_fill(art, radius=T.RADIUS_SM, height=T.px(110)) if art else
|
||||
box = (C.art_fill(art, radius=T.px(8), height=T.px(110)) if art else
|
||||
ft.Container(C.meta(tr("None")), height=T.px(110), alignment=ft.Alignment.CENTER,
|
||||
border_radius=T.RADIUS_SM, bgcolor=T.SURFACE_3))
|
||||
buttons = [C.ghost(tr("Choose…"), ft.Icons.UPLOAD_FILE_OUTLINED,
|
||||
border_radius=T.px(8), bgcolor=T.SURFACE_3))
|
||||
buttons = [C.ghost(tr("Choose…"), ft.Icons.UPLOAD_FILE_ROUNDED,
|
||||
lambda e, k=kind, lb=label: app.page.run_task(choose, k, lb))]
|
||||
if art:
|
||||
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))
|
||||
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)))
|
||||
return ft.Container(ft.Column([
|
||||
box,
|
||||
C.body(label, T.TEXT, size=T.T_META, weight=ft.FontWeight.W_600),
|
||||
@@ -175,13 +178,14 @@ 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(C.dialog(
|
||||
tr("Your own artwork for {title}").format(title=g.get("title")),
|
||||
ft.Column([
|
||||
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([
|
||||
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),
|
||||
], spacing=T.S3, tight=True), width=T.px(660)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
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,18 +42,6 @@ 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
|
||||
@@ -62,7 +50,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("/")
|
||||
rows[c["path"]] = row = C.hoverable(ft.Container(ft.Row([
|
||||
group.content.controls.append(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))],
|
||||
@@ -71,9 +59,8 @@ 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, on_click=lambda e, p=c["path"]: choose(p)))
|
||||
group.content.controls.append(row)
|
||||
paint()
|
||||
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())))
|
||||
|
||||
def use(e):
|
||||
choice = group.value
|
||||
@@ -101,10 +88,12 @@ 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(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)),
|
||||
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),
|
||||
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_ROUNDED,
|
||||
SHARED_ICONS = {"videos": ft.Icons.MOVIE_OUTLINED, "downloads": ft.Icons.DOWNLOAD_OUTLINED,
|
||||
"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_OUTLINED
|
||||
return ft.Icons.FOLDER_ROUNDED
|
||||
ext = Path(name).suffix.lower()
|
||||
if ext in VIDEO_EXT:
|
||||
return ft.Icons.MOVIE_OUTLINED
|
||||
@@ -84,24 +84,21 @@ 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_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.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.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)
|
||||
@@ -127,18 +124,9 @@ 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_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)
|
||||
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)
|
||||
if self.root is None:
|
||||
self.root = ft.Column([
|
||||
app.top_bar(tr("Files"), tr("Videos, documents, mods and saves on your Steam Frame")),
|
||||
@@ -187,14 +175,12 @@ 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"]
|
||||
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),
|
||||
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),
|
||||
padding=ft.Padding(T.S2, T.px(6), T.S2, T.px(6)), border_radius=T.RADIUS_SM, ink=True,
|
||||
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
|
||||
bgcolor=T.ACCENT_SOFT if selected else None, on_click=lambda e, loc_=loc: self.open_location(loc_))
|
||||
|
||||
def _render_locations(self) -> None:
|
||||
rows = [self._location_row(loc_, SHARED_ICONS.get(loc_["id"], ft.Icons.FOLDER_OUTLINED), loc_["android"])
|
||||
@@ -293,15 +279,16 @@ 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(C.ghost(label, on_click=lambda e, p=p: self.cd(p),
|
||||
color=T.TEXT if p == self.path else T.TEXT_2))
|
||||
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)))
|
||||
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.rows, self.hot = {}, {}, set()
|
||||
self.checks = {}
|
||||
if self.path != loc["path"]:
|
||||
rows.append(self._row(None))
|
||||
rows += [self._row(e) for e in self.entries]
|
||||
@@ -324,34 +311,27 @@ 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 = ((tr("folder") if e.is_dir else human(e.size)) + (tr(" · link") if e.link else "")
|
||||
info = (("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_OUTLINED, tr("Rename…"),
|
||||
actions += [C.icon_btn(ft.Icons.DRIVE_FILE_RENAME_OUTLINE_ROUNDED, 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([quiet_check,
|
||||
ft.Row([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),
|
||||
quiet_actions], spacing=T.S3),
|
||||
*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._hover(p, ev.data in (True, "true")))
|
||||
self.rows[e.path] = (row, quiet_check, quiet_actions)
|
||||
self._paint_row(e.path)
|
||||
on_hover=lambda ev, p=e.path: self.drag.hover(p, ev.data in (True, "true")))
|
||||
return ft.GestureDetector(content=row, on_secondary_tap_down=lambda ev, x=e: self.open_menu(x,
|
||||
ev.global_position))
|
||||
|
||||
@@ -360,8 +340,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_OUTLINED, self.upload_files),
|
||||
(tr("Upload folder…"), ft.Icons.DRIVE_FOLDER_UPLOAD_OUTLINED, self.upload_folder),
|
||||
return [(tr("Upload files…"), ft.Icons.UPLOAD_FILE_ROUNDED, self.upload_files),
|
||||
(tr("Upload folder…"), ft.Icons.DRIVE_FOLDER_UPLOAD_ROUNDED, 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())]
|
||||
@@ -380,7 +360,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_OUTLINED, lambda ev: self.rename(e)))
|
||||
out.append((tr("Rename…"), ft.Icons.DRIVE_FILE_RENAME_OUTLINE_ROUNDED, 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))))
|
||||
@@ -428,35 +408,8 @@ 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()
|
||||
@@ -482,11 +435,6 @@ 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):
|
||||
@@ -561,7 +509,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 tr("file")
|
||||
what = tr("folder and everything in it") if any(x.is_dir for x in items) else "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),
|
||||
@@ -583,12 +531,14 @@ class FilesView:
|
||||
|
||||
def _ask_name(self, heading: str, label: str, value: str, ok: str, on_ok) -> None:
|
||||
page = self.app.page
|
||||
field = C.field(label=label, value=value, autofocus=True, width=T.DIALOG_S)
|
||||
field = ft.TextField(label=label, value=value, autofocus=True, width=T.px(380))
|
||||
|
||||
def go(e=None):
|
||||
page.pop_dialog()
|
||||
if (field.value or "").strip():
|
||||
on_ok(field.value.strip())
|
||||
field.on_submit = 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"))
|
||||
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)]))
|
||||
@@ -96,11 +96,14 @@ 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 = C.spinner()
|
||||
ring = ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2), color=T.ACCENT)
|
||||
body = ft.Column([ft.Row([ring, status],
|
||||
spacing=T.S2)], spacing=T.S3, expand=True)
|
||||
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))
|
||||
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())])
|
||||
app.page.show_dialog(dialog)
|
||||
|
||||
def load():
|
||||
@@ -110,15 +113,19 @@ 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 = C.search(hint_text=tr("Filter files (for example .pak, Binaries)"), 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)
|
||||
|
||||
def row(depth: int, node: Node | int, root_key: str) -> ft.Control:
|
||||
pad = ft.Padding(T.px(8 + depth * 18), T.px(3), T.px(8), T.px(3))
|
||||
pad = ft.Padding(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_OUTLINED) if node.is_dir \
|
||||
icon = (ft.Icons.FOLDER_OPEN_ROUNDED if key in expanded else ft.Icons.FOLDER_ROUNDED) 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))
|
||||
@@ -131,7 +138,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.RADIUS_XS, ink=node.is_dir,
|
||||
], spacing=T.px(6)), padding=pad, border_radius=T.px(6), ink=node.is_dir,
|
||||
on_click=(lambda e, k=key: toggle(k)) if node.is_dir else None)
|
||||
|
||||
def render():
|
||||
|
||||
@@ -10,7 +10,6 @@ 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
|
||||
@@ -29,11 +28,11 @@ class FrameView:
|
||||
t = app.target
|
||||
free = (info.get("free_bytes") or 0) / 2**30
|
||||
return C.card(ft.Row([
|
||||
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.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.Column([
|
||||
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),
|
||||
ft.Row([C.title(info.get("hostname") or t.label, 22), 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'))),
|
||||
@@ -44,78 +43,45 @@ 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"), 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()),
|
||||
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()),
|
||||
], 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
|
||||
items = []
|
||||
rows = []
|
||||
lepton = info.get("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)))
|
||||
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"))
|
||||
pr = info.get("proton") or {}
|
||||
ready, sug = pr.get("ready"), pr.get("suggested")
|
||||
if pr:
|
||||
items.append(C.Check(
|
||||
rows.append(C.status_row(
|
||||
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")),
|
||||
"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))
|
||||
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"))
|
||||
xr = (pr.get("openxr") or {}).get("name")
|
||||
items.append(C.Check(bool(xr), tr("OpenXR runtime"), xr or tr("None found"), "openxr"))
|
||||
rows.append(C.status_row(bool(xr), tr("OpenXR runtime"), xr or tr("None found"), help="openxr"))
|
||||
keys = info.get("kernel_keys") or {}
|
||||
if keys.get("max_keys"):
|
||||
high = keys["keys"] > keys["max_keys"] * 0.75
|
||||
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)))
|
||||
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)))
|
||||
|
||||
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
|
||||
@@ -124,9 +90,9 @@ class FrameView:
|
||||
|
||||
app = self.app
|
||||
current = drives.install_dest()
|
||||
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"))])
|
||||
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"))])
|
||||
rows = ft.Column([C.meta(tr("Looking for drives…"))], spacing=T.px(6))
|
||||
|
||||
def choose(e):
|
||||
@@ -156,7 +122,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_OUTLINED,
|
||||
ft.Icon(ft.Icons.SD_CARD_ROUNDED if d.get("removable") else ft.Icons.STORAGE_ROUNDED,
|
||||
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]))),
|
||||
@@ -186,7 +152,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_OUTLINED,
|
||||
action=ft.Row([send, C.ghost(tr("Free up space"), ft.Icons.CLEANING_SERVICES_ROUNDED,
|
||||
lambda e: self.app.cleanup_frame(),
|
||||
tooltip=C.tip(HELP["free_space"]))], spacing=T.S2, tight=True)
|
||||
if items else send)
|
||||
@@ -220,7 +186,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.RADIUS_SM, width=T.px(44), height=T.px(44)),
|
||||
C.art_fill(art, radius=T.px(8), 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
|
||||
@@ -231,7 +197,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(G.TEST, C.tip(tr("Launch test. ") + HELP["launch_test"]),
|
||||
C.icon_btn(ft.Icons.SCIENCE_OUTLINED, 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")),
|
||||
@@ -247,7 +213,7 @@ class FrameView:
|
||||
|
||||
app = self.app
|
||||
found = ft.Column(spacing=T.S2)
|
||||
searching = ft.Row([C.spinner(),
|
||||
searching = ft.Row([ft.ProgressRing(width=T.px(16), height=T.px(16), stroke_width=T.px(2), color=T.ACCENT),
|
||||
C.meta(tr("Looking for Frames on your network…"))], spacing=T.S2)
|
||||
|
||||
def discover():
|
||||
@@ -258,20 +224,20 @@ class FrameView:
|
||||
res = browse(4)
|
||||
items = []
|
||||
for f in res:
|
||||
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)
|
||||
label = {"devkit": "SteamOS · Developer Mode", "frameport": "Set up for FramePort",
|
||||
"saved": "Remembered", "scan": "SSH found by network scan"}.get(f.source, f.source)
|
||||
items.append(ft.Container(ft.Row([
|
||||
C.as_icon(G.FRAME if f.source != "scan" else ft.Icons.DEVICES_OTHER_ROUNDED, T.px(24), T.ACCENT),
|
||||
ft.Icon(ft.Icons.VIEW_IN_AR_ROUNDED if f.source != "scan" else ft.Icons.DEVICES_OTHER_ROUNDED,
|
||||
color=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 [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 = 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.append(C.ghost(tr("Search again"), ft.Icons.REFRESH_ROUNDED, lambda e: app.run_bg(discover)))
|
||||
C.update(found)
|
||||
|
||||
@@ -301,7 +267,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 PC are on the same network.")
|
||||
"Check that the Frame and this computer are on the same network.")
|
||||
if app.route[0] == "frame" and app.pairing is server:
|
||||
show_command()
|
||||
app.run_bg(check_network)
|
||||
@@ -320,12 +286,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 PC with a USB cable (a data cable, not a charge-only "
|
||||
tr("Connect the Frame's USB-C port to this computer with a USB cable (a data cable, not a charge-only "
|
||||
"one)."),
|
||||
]
|
||||
dlg = C.dialog(
|
||||
tr("Turn on Developer Mode first"),
|
||||
ft.Column([
|
||||
dlg = ft.AlertDialog(
|
||||
title=ft.Text(tr("Turn on Developer Mode first"), weight=ft.FontWeight.W_600),
|
||||
content=ft.Container(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),
|
||||
@@ -334,7 +300,8 @@ 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), size="s",
|
||||
], spacing=T.S3, tight=True), width=T.px(480)),
|
||||
bgcolor=T.SURFACE_2, shape=ft.RoundedRectangleBorder(radius=T.RADIUS),
|
||||
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)
|
||||
@@ -346,11 +313,11 @@ class FrameView:
|
||||
from ...frame import usb
|
||||
from ...frame.connection import FrameTarget, server_key
|
||||
|
||||
status = ft.Row([C.spinner(),
|
||||
status = ft.Row([ft.ProgressRing(width=T.px(14), height=T.px(14), stroke_width=T.px(2), color=T.ACCENT),
|
||||
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 "
|
||||
"PC)."), T.TEXT),
|
||||
"computer)."), T.TEXT),
|
||||
status,
|
||||
]
|
||||
C.update(pair_box)
|
||||
@@ -389,7 +356,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 PC over the USB cable):") if over_usb else
|
||||
"Konsole, and run (it reaches this computer 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),
|
||||
@@ -397,11 +364,12 @@ 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([C.spinner(),
|
||||
ft.Row([ft.ProgressRing(width=T.px(14), height=T.px(14), stroke_width=T.px(2), color=T.ACCENT),
|
||||
C.meta(tr("Waiting for your Frame… (code {code})").format(code=app.pairing.code))],
|
||||
spacing=T.S2),
|
||||
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)),
|
||||
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.")),
|
||||
]
|
||||
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
|
||||
@@ -409,9 +377,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),
|
||||
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)),
|
||||
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.")),
|
||||
], spacing=T.S2), "warn"))
|
||||
if update:
|
||||
C.update(pair_box) # (a redraw of the page may have replaced it)
|
||||
@@ -419,9 +387,12 @@ class FrameView:
|
||||
if app.pairing and app.pairing.running:
|
||||
show_command(update=False)
|
||||
|
||||
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"]))
|
||||
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)
|
||||
saved = saved_targets()
|
||||
offline = None
|
||||
if getattr(app, "_not_paired", False): # it answered, but doesn't know FramePort yet
|
||||
@@ -436,8 +407,9 @@ 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 tr("your Frame"))
|
||||
offline = C.callout(ft.Row([C.spinner(),
|
||||
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),
|
||||
C.body(connecting, T.TEXT)],
|
||||
spacing=T.S3), "info")
|
||||
import time as _time
|
||||
|
||||