Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d39e439ff | ||
|
|
2868087467 | ||
|
|
09119e775f | ||
|
|
f209880fd0 | ||
|
|
455020cb1f | ||
|
|
466efdb873 | ||
|
|
e363db0e4e | ||
|
|
5f4f8f2ea7 | ||
|
|
e331f5e5a1 | ||
|
|
c6dad191fb | ||
|
|
8ea1c53ec3 | ||
|
|
d34eb1bf45 | ||
|
|
bcea090e73 | ||
|
|
37d57a1f88 | ||
|
|
d974e872ba | ||
|
|
dfe9d71971 | ||
|
|
05b417a29b | ||
|
|
a48c84ed4a | ||
|
|
d1f1968317 | ||
|
|
83994aab7b | ||
|
|
5866c2f040 | ||
|
|
dd038f8e46 | ||
|
|
3fdda096a9 | ||
|
|
575b3cfa61 | ||
|
|
aa4a382c1b | ||
|
|
684225422c | ||
|
|
08960c9eec | ||
|
|
f0c21af220 | ||
|
|
8602ee3add | ||
|
|
7d34eca5d7 | ||
|
|
fcf3aec4c0 | ||
|
|
9911151d8d | ||
|
|
4e8c6e534b | ||
|
|
b15747a604 | ||
|
|
eb7127718b | ||
|
|
90a014d161 | ||
|
|
efb0f2e22d | ||
|
|
270979949f | ||
|
|
52ebafab78 | ||
|
|
6118705c37 | ||
|
|
5247f5e512 | ||
|
|
8bcc574f99 | ||
|
|
c323402895 | ||
|
|
6fa3e2c2d2 | ||
|
|
af513c1b5a | ||
|
|
c7b164e6cd | ||
|
|
5dfa6c8197 | ||
|
|
e362519261 | ||
|
|
c1c657c0a9 | ||
|
|
edbd90745b | ||
|
|
3735c5bfa7 | ||
|
|
f1fda9bdee | ||
|
|
b2f63601c0 | ||
|
|
35e80c6d1c | ||
|
|
4a2b1f3795 | ||
|
|
14c47aa2a0 | ||
|
|
b5c52004c8 | ||
|
|
9f3f4b6f62 | ||
|
|
0e35735a2a | ||
|
|
20c7620393 | ||
|
|
173d82a238 | ||
|
|
914eaed71c | ||
|
|
289d308b57 | ||
|
|
8b9f636cce | ||
|
|
9c8a87e90d | ||
|
|
82f60ed428 | ||
|
|
569bf733e9 | ||
|
|
cb11ffdd2d | ||
|
|
a33a3a71e4 | ||
|
|
63751a79ad | ||
|
|
86b94a9e64 | ||
|
|
77fe78d874 | ||
|
|
5d4bb53b8a | ||
|
|
99069ba5fe | ||
|
|
37bd657299 | ||
|
|
f48daa71c8 | ||
|
|
8bc0749b42 | ||
|
|
1c67dd20d7 | ||
|
|
1100580c2c | ||
|
|
31adc34a19 | ||
|
|
b4ca795003 | ||
|
|
8556221b08 | ||
|
|
dadd9ec164 | ||
|
|
c171047adf | ||
|
|
afbe9db409 | ||
|
|
49794b4973 | ||
|
|
1f62653118 | ||
|
|
8ae09f238b | ||
|
|
644fdefa66 | ||
|
|
14cf212a60 | ||
|
|
db9a6f1875 | ||
|
|
ce8525bee8 | ||
|
|
01b9e9f1d0 | ||
|
|
33af5408fd | ||
|
|
67d99dd6c0 | ||
|
|
7fc262f9c3 | ||
|
|
27cd6b3703 | ||
|
|
ffce798754 | ||
|
|
acdb929a99 | ||
|
|
95d69a5512 | ||
|
|
3a0007118c | ||
|
|
aa194be09a |
@@ -0,0 +1,128 @@
|
||||
---
|
||||
name: build-firmware
|
||||
description: Compile the espresso_frame ESP32-C6 firmware (firmware/) for both board variants without Docker -- a native, non-container ESP-IDF v6.0 install. Use when asked to build the firmware, verify a firmware/main/*.c change actually compiles, or check both the devkit and xiao board targets.
|
||||
---
|
||||
|
||||
Compiles `firmware/` (ESP-IDF, targeting ESP32-C6) locally, without
|
||||
Docker -- CI's `firmware-build-check.yml`/`firmware-release-build.yml`
|
||||
build inside the `espressif/idf:release-v6.0` container image, but
|
||||
**this sandbox cannot run containers at all**: `docker.io` installs and
|
||||
`dockerd` starts fine even as root, but the sandbox strips
|
||||
`cap_sys_admin` (and blocks the bare `unshare` syscall) from the
|
||||
capability set regardless of uid, which container image-layer
|
||||
extraction and namespace setup both require. Confirmed by hand:
|
||||
`docker run hello-world` fails to extract even the tiny hello-world
|
||||
layer ("failed to extract layer... operation not permitted" with the
|
||||
overlayfs snapshotter; "unshare: operation not permitted" even with
|
||||
the vfs storage driver instead). This is a hard restriction of the
|
||||
sandbox itself, not a permissions/setup problem -- don't spend time
|
||||
re-trying `--privileged`-equivalent flags or alternate storage drivers,
|
||||
none of it routes around a missing `cap_sys_admin`.
|
||||
|
||||
The workaround: skip containers entirely and install ESP-IDF the same
|
||||
way a developer would set it up on their own machine (`git clone` +
|
||||
ESP-IDF's own `install.sh`) -- that path needs nothing this sandbox
|
||||
disallows, just normal file/process operations.
|
||||
|
||||
## Setup (once per fresh container)
|
||||
|
||||
```bash
|
||||
bash .claude/skills/build-firmware/setup.sh
|
||||
```
|
||||
|
||||
Installs (via real `apt-get` -- this container actually has root and a
|
||||
working package manager, unlike run-server's Chromium bootstrap which
|
||||
had neither):
|
||||
- OS build deps: `python3`/`venv`/`pip`, `cmake`, `ninja-build`,
|
||||
`flex`/`bison`/`gperf`, `build-essential`, `libusb-1.0-0`.
|
||||
- ESP-IDF itself: a shallow, single-branch, recursive-submodule clone
|
||||
of `release/v6.0` (~700MB) into `~/.espressif-idf/esp-idf` -- matches
|
||||
the IDF version CI's Docker image pins. Only clones once; re-running
|
||||
`setup.sh` never touches an existing checkout.
|
||||
- The esp32c6 toolchain + Python venv, via ESP-IDF's own
|
||||
`./install.sh esp32c6` -- scoped to just this project's one target
|
||||
(see `firmware/README.md`'s board table), not every chip ESP-IDF
|
||||
supports, to keep the download/disk footprint down. `install.sh` is
|
||||
already idempotent on its own, so `setup.sh` always calls it rather
|
||||
than duplicating that check -- a re-run costs a few seconds once
|
||||
everything's cached.
|
||||
|
||||
Takes a few minutes on a cold run (mostly `install.sh`'s own pip/tool
|
||||
downloads), well under a minute on a re-run. Needs real root (`apt-get
|
||||
install`) -- if this container ever runs as non-root, this setup
|
||||
doesn't apply as-is (would need the same non-root apt-download +
|
||||
`dpkg-deb -x` extraction dance `run-server`'s `setup.sh` uses for
|
||||
Chromium).
|
||||
|
||||
Disk: budget ~4GB free before starting (esp-idf checkout + toolchain +
|
||||
Python env land around 3.4GB in `~/.espressif`, plus the ~700MB
|
||||
checkout itself). Confirmed working with as little as ~7GB free.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
bash .claude/skills/build-firmware/build.sh # devkit (default)
|
||||
bash .claude/skills/build-firmware/build.sh xiao
|
||||
bash .claude/skills/build-firmware/build.sh both # both variants
|
||||
```
|
||||
|
||||
Each board gets its own build directory and generated sdkconfig (see
|
||||
`firmware/build_for_board.sh`'s own comment) -- building one never
|
||||
disturbs the other. `build.sh` auto-runs `set-target esp32c6` the very
|
||||
first time a board is built (no generated sdkconfig yet); later builds
|
||||
skip straight to `idf.py build`. Extra arguments pass straight through
|
||||
to `idf.py`, e.g.:
|
||||
|
||||
```bash
|
||||
bash .claude/skills/build-firmware/build.sh xiao flash -p /dev/ttyUSB0
|
||||
```
|
||||
|
||||
`flash`/`monitor` need an actual attached device and serial port --
|
||||
this sandbox has neither, so those only work when this skill runs
|
||||
somewhere hardware is actually plugged in (a real dev machine, or a
|
||||
differently-configured environment with device passthrough).
|
||||
|
||||
A clean build of one board takes ~30s once the target's already been
|
||||
configured (~1,000 build steps total split across both boards, most of
|
||||
it ESP-IDF's own components -- this project's own `firmware/main/*.c`
|
||||
and `firmware/components/*` sources are a small fraction of that and
|
||||
compile in a few seconds). Output lands at
|
||||
`firmware/build/espresso_frame.bin` (devkit) or
|
||||
`firmware/build_xiao/espresso_frame.bin` (xiao) -- both paths are
|
||||
gitignored (`firmware/.gitignore`... actually the repo root
|
||||
`.gitignore`'s "ESP-IDF firmware build output" section), so nothing
|
||||
here needs cleaning up before a commit.
|
||||
|
||||
## Verified
|
||||
|
||||
Both board variants (`devkit` set-target esp32c6 + build, `xiao`
|
||||
set-target esp32c6 + build) built successfully end-to-end using this
|
||||
exact setup.sh/build.sh pair, producing real
|
||||
`espresso_frame.bin` images with normal free-space margins (41%/36%
|
||||
of their respective app partitions) and no errors -- only one
|
||||
pre-existing, unrelated warning (`battery.c`'s unused `TAG` when that
|
||||
file's logging is compiled out). This is a real compile check, not
|
||||
just a syntax read -- if a future change breaks the build, this skill
|
||||
will actually catch it.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **`docker: ... unshare: operation not permitted` / `failed to
|
||||
extract layer ... operation not permitted`**: expected in this
|
||||
sandbox, see the top of this file. Don't debug it further -- use this
|
||||
skill's native install instead.
|
||||
- **`ESP-IDF not found at ... -- run setup.sh first`**: `build.sh`'s
|
||||
own check for a missing `$IDF_DIR/export.sh` -- run `setup.sh` (see
|
||||
above) before the first build.
|
||||
- **`idf.py: command not found` if you try to run it directly**: same
|
||||
gotcha `firmware/build_for_board.sh` already documents -- `idf.py` is
|
||||
normally a shell *function* from ESP-IDF's `export.sh`, not on PATH
|
||||
as a real executable, so it isn't inherited into a script's own
|
||||
subshell even after sourcing `export.sh` in your interactive shell
|
||||
first. Use `build.sh` (or `build_for_board.sh`, which calls
|
||||
`python "$IDF_PATH/tools/idf.py"` directly) instead of typing
|
||||
`idf.py` in a fresh script/subshell.
|
||||
- **Disk pressure during `install.sh`**: this environment runs close to
|
||||
full (single-digit GB free is normal, not a sign of a leak) --
|
||||
`df -h /` before running `setup.sh` if a build mysteriously fails
|
||||
partway with a "no space left on device"-shaped error.
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds (or flashes/monitors, if a serial port is actually attached)
|
||||
# the espresso_frame firmware for one board variant, via the project's
|
||||
# own firmware/build_for_board.sh -- this script just sources the
|
||||
# ESP-IDF environment first and auto-runs `set-target esp32c6` on a
|
||||
# board's very first build (a fresh clone has no generated sdkconfig
|
||||
# yet, same reasoning as CI's own build steps -- see firmware/README.md's
|
||||
# "Building for the Seeed XIAO ESP32-C6" section).
|
||||
#
|
||||
# Usage:
|
||||
# build.sh # build devkit (default)
|
||||
# build.sh devkit
|
||||
# build.sh xiao
|
||||
# build.sh both # build both board variants
|
||||
# build.sh xiao flash -p /dev/ttyUSB0 # only meaningful with real hardware attached
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
firmware_dir="$(git -C "$script_dir" rev-parse --show-toplevel)/firmware"
|
||||
|
||||
IDF_DIR="$HOME/.espressif-idf/esp-idf"
|
||||
if [ ! -f "$IDF_DIR/export.sh" ]; then
|
||||
echo "ESP-IDF not found at $IDF_DIR -- run setup.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
# export.sh is chatty and assumes an interactive shell prompt in spots;
|
||||
# redirect its own stdout, not ours, so build.sh's actual output (and a
|
||||
# real failure's stderr) stays visible.
|
||||
source "$IDF_DIR/export.sh" > /dev/null
|
||||
|
||||
cd "$firmware_dir"
|
||||
|
||||
build_one() {
|
||||
local board="$1"
|
||||
shift
|
||||
local sdkconfig
|
||||
case "$board" in
|
||||
devkit) sdkconfig="sdkconfig" ;;
|
||||
xiao) sdkconfig="sdkconfig.xiao_local" ;;
|
||||
*) echo "Unknown board '$board' -- expected 'devkit' or 'xiao'" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
if [ ! -f "$sdkconfig" ]; then
|
||||
echo "==> $board: no generated sdkconfig yet, setting target esp32c6"
|
||||
./build_for_board.sh "$board" set-target esp32c6
|
||||
fi
|
||||
|
||||
local args=("$@")
|
||||
if [ ${#args[@]} -eq 0 ]; then
|
||||
args=(build)
|
||||
fi
|
||||
./build_for_board.sh "$board" "${args[@]}"
|
||||
}
|
||||
|
||||
board="${1:-devkit}"
|
||||
shift || true
|
||||
|
||||
if [ "$board" = "both" ]; then
|
||||
build_one devkit "$@"
|
||||
build_one xiao "$@"
|
||||
else
|
||||
build_one "$board" "$@"
|
||||
fi
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-time (idempotent) environment bootstrap for compiling the
|
||||
# espresso_frame firmware (firmware/) without Docker -- see this
|
||||
# skill's SKILL.md for why not Docker, even though that's what CI uses.
|
||||
# Re-run any time; every step is safe/fast to repeat once already done.
|
||||
set -euo pipefail
|
||||
|
||||
IDF_ROOT="$HOME/.espressif-idf"
|
||||
IDF_DIR="$IDF_ROOT/esp-idf"
|
||||
# Matches the espressif/idf:release-v6.0 image CI's
|
||||
# firmware-build-check.yml/firmware-release-build.yml use -- keep this
|
||||
# in sync with those workflow files if the project's pinned IDF version
|
||||
# ever changes.
|
||||
IDF_BRANCH="release/v6.0"
|
||||
|
||||
# 1. OS packages ESP-IDF's own install.sh needs (python3 + venv/pip,
|
||||
# cmake, ninja, a C toolchain for the odd host-side code generator, git
|
||||
# for the clone below, flex/bison/gperf for mbedtls/etc.'s generated
|
||||
# parsers, libusb for esptool's USB/JTAG bits even though this skill
|
||||
# doesn't flash real hardware). Installed via apt with real root --
|
||||
# unlike run-server's Chromium bootstrap, this container actually has
|
||||
# root and a working apt, so no non-root extraction dance is needed
|
||||
# here.
|
||||
PKGS="git python3 python3-venv python3-pip cmake ninja-build ccache libusb-1.0-0 wget flex bison gperf build-essential"
|
||||
missing=()
|
||||
for pkg in $PKGS; do
|
||||
dpkg -s "$pkg" >/dev/null 2>&1 || missing+=("$pkg")
|
||||
done
|
||||
if [ ${#missing[@]} -gt 0 ]; then
|
||||
echo "installing OS packages: ${missing[*]}"
|
||||
apt-get update
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y "${missing[@]}"
|
||||
fi
|
||||
|
||||
# 2. ESP-IDF checkout -- shallow, single branch, recursive submodules
|
||||
# also shallow (~700MB total, vs. several GB for a full clone). Only
|
||||
# clones once; re-running this script never re-clones or resets it, so
|
||||
# any local changes you made for debugging survive a re-run.
|
||||
if [ ! -d "$IDF_DIR/.git" ]; then
|
||||
echo "cloning esp-idf $IDF_BRANCH into $IDF_DIR ..."
|
||||
mkdir -p "$IDF_ROOT"
|
||||
git clone --branch "$IDF_BRANCH" --depth 1 --shallow-submodules --recursive \
|
||||
https://github.com/espressif/esp-idf.git "$IDF_DIR"
|
||||
else
|
||||
echo "esp-idf already cloned at $IDF_DIR"
|
||||
fi
|
||||
|
||||
# 3. Toolchain + Python virtualenv, scoped to esp32c6 only -- this
|
||||
# project's one target (see firmware/README.md's board table). Scoping
|
||||
# avoids downloading toolchains for every chip ESP-IDF supports, which
|
||||
# matters given this container's disk headroom. install.sh is already
|
||||
# idempotent on its own (checks what's present and skips it), so this
|
||||
# always calls it rather than trying to duplicate that check here --
|
||||
# a re-run only costs a few seconds once everything's cached.
|
||||
echo "running esp-idf install.sh esp32c6 (fast if already installed) ..."
|
||||
(cd "$IDF_DIR" && ./install.sh esp32c6)
|
||||
|
||||
echo "setup complete -> $IDF_DIR/export.sh (build.sh sources this for you)"
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
name: make-widget
|
||||
description: Scaffold a new widget type for the espresso_frame server (the ~14-file checklist a widget type touches -- config table, grid footprint, render module, registry, migration, config-save + endpoints, dialog template + JS, script tag, WIDGET_LABELS, docs, saved-layout config allowlist, tests). Use when asked to add a new widget type to a frame's panel (e.g. "add a text widget", "add an RSS widget", "add a weather-only widget").
|
||||
---
|
||||
|
||||
Adding a widget type is a very consistent, repeated pattern in this
|
||||
codebase (`photos`/`calendar`/`whiteboard`/`tasks`/`static`) -- see
|
||||
`docs/widgets.md` for the system's actual data model/rendering/dialog
|
||||
architecture (read that first if you haven't). This skill is the
|
||||
checklist of every file that pattern touches, so nothing gets silently
|
||||
dropped (the static-image widget shipped without a `docs/widgets.md`
|
||||
update; this skill exists so that doesn't keep happening).
|
||||
|
||||
**For a complete worked example touching every item below**, `git show
|
||||
35e80c6 --stat` (the static-image widget's commit) in this repo.
|
||||
|
||||
All paths below are relative to `server/`.
|
||||
|
||||
## Before writing any code: shape decisions
|
||||
|
||||
Answer these first -- they determine which existing widget type is the
|
||||
closest template to copy from:
|
||||
|
||||
- **Live upstream to poll, or self-contained/user-authored?** Calendar/
|
||||
whiteboard/tasks fetch from somewhere external on a throttle
|
||||
(`checked_at` + `get_or_refresh_*` in `routers/common.py`). Photos'
|
||||
queue and the static image widget don't -- their content is set once
|
||||
via the dialog (an upload, a pick) and just sits there until changed.
|
||||
A text widget is almost certainly this second shape.
|
||||
- **Single source, or multi-source merge?** Calendar/tasks merge
|
||||
several *people's* data (`FrameCalendar`/`FrameTaskList`, owner-adds/
|
||||
anyone-mutes). Only reach for that shape if the new type genuinely
|
||||
needs to combine several linked users' own data -- most new widget
|
||||
types are single-owner/single-config and don't need it.
|
||||
- **Any button actions**, or is `ACTIONS = {}` correct (nothing to
|
||||
advance/back/force)? Tasks and static image are both `{}`.
|
||||
- **Minimum sane grid footprint** -- how small can this widget be
|
||||
before its content is illegible/pointless?
|
||||
|
||||
Pick your template accordingly:
|
||||
|
||||
| New widget shape | Copy from |
|
||||
|---|---|
|
||||
| Self-contained, user-authored/uploaded, no fetch, no actions | `app/widgets/static_image.py` |
|
||||
| Single external source, throttled fetch, one "check_now" action | `app/widgets/whiteboard.py` |
|
||||
| Multi-source merge, owner-adds/anyone-mutes permissions | `app/widgets/tasks.py` (simpler) or `calendar.py` (also has size-tier rendering) |
|
||||
| Stateful queue/rotation with advance/back | `app/widgets/photos.py` |
|
||||
|
||||
## The checklist
|
||||
|
||||
1. **`app/models.py`** -- new `<Type>WidgetConfig` table, `widget_id`
|
||||
`Mapped[int]` primary key `ForeignKey("widgets.id", ondelete="CASCADE")`,
|
||||
plus whatever fields the type needs. Add it to the `WIDGET_CONFIG_MODELS`
|
||||
dict at the bottom of the file.
|
||||
2. **`app/grid.py`** -- add an entry to `MIN_FOOTPRINT`.
|
||||
3. **`app/widgets/<type>.py`** -- new module exposing:
|
||||
- `render(db, frame, widget, target_w, target_h, is_normal_wake=True) -> Image.Image`
|
||||
-- RGB, exactly `target_w x target_h`, **never raises** for a
|
||||
foreseeable failure (missing config, fetch error) -- fall back to
|
||||
`._shared.placeholder_image(target_w, target_h, [lines])` instead.
|
||||
- `ACTIONS: dict[str, Callable[[Session, Frame, Widget], None]]`
|
||||
- `ACTION_LABELS: dict[str, str]`
|
||||
4. **`app/widgets/__init__.py`** -- import the new module, add it to
|
||||
`WIDGET_TYPES`.
|
||||
5. **`app/migration.py`** -- new `_migration_N`. A brand-new table with
|
||||
no legacy data to carry forward is just
|
||||
`Base.metadata.create_all(bind=conn)` (see `_migration_20`) -- it
|
||||
only creates the one new table, existing ones are untouched. Register
|
||||
`(N, _migration_N)` as the new last entry in `MIGRATIONS`.
|
||||
6. **`app/routers/api_widgets.py`**:
|
||||
- Add any new `Form(...)` fields to `api_widget_config_save`'s
|
||||
signature, and a new `elif widget.widget_type == "<type>":` branch
|
||||
inside its body. Reuse an existing field name (e.g. `display_mode`)
|
||||
where the semantics genuinely match -- fields are namespaced by
|
||||
which widget type actually reads them, not by name collision, so
|
||||
this is safe (see the comment above `display_mode` in that
|
||||
function).
|
||||
- Add type-specific endpoints as needed (upload/source-select/etc.).
|
||||
Use `require_widget_control` for widget-wide settings a dialog Save
|
||||
button changes; use `require_widget_view` (not control) for the
|
||||
owner-adds/anyone-mutes multi-source pattern, matching
|
||||
`api_widget_calendar_select`/`api_widget_task_list_select`.
|
||||
- Add a `GET .../preview/<type>` endpoint mirroring the others --
|
||||
`render_preview_png` (the full palette/dither pipeline) for
|
||||
image-like content, or a dedicated `render_<type>_preview_png` in a
|
||||
rendering module for text/graphics content (see
|
||||
`calendar_render.render_tasks_preview_png`).
|
||||
7. **`app/routers/frame_pages.py`** -- import the new config model, add
|
||||
an `if widget.widget_type == "<type>":` branch in `widget_dialog()`
|
||||
returning `templates.TemplateResponse("_widget_dialog_<type>.html", {...})`.
|
||||
8. **`app/templates/_widget_dialog_<type>.html`** -- the dialog
|
||||
fragment: settings card(s) + `<img class="preview-img"
|
||||
id="<type>-preview">` + a refresh button, using the existing
|
||||
`.card`/`.card-title`/`.sub`/`.checkbox-row` classes from
|
||||
`theme.css` rather than inventing new ones.
|
||||
9. **`app/static/widget_dialog_<type>.js`** -- an `init<Type>Dialog()`/
|
||||
`close<Type>Dialog()` pair (not a page-load script -- see any
|
||||
existing `widget_dialog_*.js`'s header comment for the contract).
|
||||
`window.fetch` already CSRF-injects (see `common.js`), so POSTs don't
|
||||
need a manual header. **Never build user-supplied text into the DOM
|
||||
via `innerHTML` string interpolation** -- use `textContent`/
|
||||
`createElement` (a filename, a task summary, anything another linked
|
||||
user's account could have set is a stored-XSS vector otherwise).
|
||||
10. **`app/templates/frame_layout.html`** -- add
|
||||
`<script src="/static/widget_dialog_<type>.js"></script>` next to
|
||||
the other widget dialog scripts.
|
||||
11. **`app/static/frame_layout.js`** -- add the type to both
|
||||
`DIALOG_INIT` and `DIALOG_CLOSE`.
|
||||
12. **`app/static/common.js`** -- add a `WIDGET_LABELS` entry (the
|
||||
human label shown in the add-widget button, the widget box, and the
|
||||
button-assignment picker in `frame_config.js`).
|
||||
13. **`docs/widgets.md`** -- update every place that enumerates widget
|
||||
types: the intro sentence, the `widget_type` column-value list, the
|
||||
`MIN_FOOTPRINT` prose line, the `app/widgets/` module list. This is
|
||||
the project's own "start here" doc per `CLAUDE.md` -- don't ship a
|
||||
widget without it staying accurate.
|
||||
14. **`app/routers/api_layouts.py`** -- add a `"<type>": (...)` entry to
|
||||
`LAYOUT_CONFIG_FIELDS` listing the config columns that are an
|
||||
authored *setting* (as opposed to runtime/cache state like a fetch
|
||||
cache or queue position, which a saved layout deliberately leaves
|
||||
out -- see the dict's own comment). Skipping this doesn't error or
|
||||
warn anywhere: the widget just silently saves/applies with an empty
|
||||
`{}` config forever, resetting to defaults on every layout apply or
|
||||
hold-to-cycle. This actually shipped missing for the weather widget
|
||||
-- caught only because a user noticed layout-cycling kept resetting
|
||||
its city/mode.
|
||||
|
||||
## Tests (`server/tests/`)
|
||||
|
||||
- `test_widgets_<type>.py` -- unit-level `render()` tests, no HTTP:
|
||||
correct size/mode with no config, with config, at
|
||||
`grid.MIN_FOOTPRINT`'s smallest box, `ACTIONS == {}` if passive.
|
||||
Mirror `test_widgets_static.py` (self-contained) or
|
||||
`test_widgets_tasks.py` (fetch-backed, monkeypatches the fetch call).
|
||||
- `test_widget_config_and_queue_endpoints.py` -- add a
|
||||
`_add_<type>_widget` helper plus an HTTP-level
|
||||
`test_config_save_updates_a_<type>_widget` test, and tests for any new
|
||||
endpoints (upload/select/preview: 400 before configured, 200 after,
|
||||
400 for the wrong widget type via `_require_widget_type`).
|
||||
- `test_migrations.py` -- add the new table to
|
||||
`test_expected_columns_exist_on_current_schema`'s spot-check
|
||||
(`inspector.get_table_names()` or `inspector.get_columns(...)`).
|
||||
- Owner-adds/anyone-mutes multi-source table? Add cases to
|
||||
`test_permission_boundaries.py` following its existing
|
||||
calendar-select/task-list-select pattern (owner can add, non-owner
|
||||
can mute but not add, 404 for an unrelated widget id, 400 for the
|
||||
wrong widget type).
|
||||
- Any pure-logic helper module (decoding, parsing -- like
|
||||
`app/image_upload.py`) gets its own `test_<module>.py`: no HTTP, no
|
||||
DB, just the function.
|
||||
- `test_saved_layouts.py` -- a `test_save_and_apply_round_trip_<type>_settings`
|
||||
test: set every field the new `LAYOUT_CONFIG_FIELDS` entry lists,
|
||||
save a layout, assert the `SavedLayoutWidget.config` snapshot has them
|
||||
all, delete the frame's widgets, apply the layout back, assert the
|
||||
new widget's config matches -- and that any runtime/cache field
|
||||
(`checked_at`, a fetch cache, a queue) was *not* carried over. See
|
||||
`test_save_and_apply_round_trip_weather_settings` for the pattern.
|
||||
|
||||
Run the full suite before calling it done:
|
||||
|
||||
```bash
|
||||
cd server && .venv/bin/pytest -q
|
||||
```
|
||||
|
||||
Comfortably under 30s for the whole suite (~200+ tests) -- there's no
|
||||
reason to skip this or run a subset.
|
||||
|
||||
## Browser verification (required, not optional)
|
||||
|
||||
Per `CLAUDE.md`, reading the JS is not enough -- this project has
|
||||
shipped UI bugs (mobile viewport CSS collapse, a dialog's status message
|
||||
landing behind its own backdrop, a JSON/form body mismatch) that only
|
||||
showed up live. Use the `run-server` skill:
|
||||
|
||||
- Clear existing widgets and add one of the new type
|
||||
(`POST /api/frames/1/widgets`), resize it (`PATCH`), open its dialog
|
||||
(`click .widget-box-settings`), exercise its actual settings/upload
|
||||
flow through the real UI controls (not just a raw `fetch` in `eval` --
|
||||
that only proves the endpoint works, not that the button is wired to
|
||||
it), and check `console-errors` for anything beyond the expected
|
||||
favicon 404.
|
||||
- Check the full composited panel preview
|
||||
(`#frame-preview-thumb` on `/frames/{id}/config`) actually shows the
|
||||
new widget's content -- not just its own dialog's `preview/<type>`
|
||||
image, which only proves the render function works in isolation.
|
||||
- Screenshot **both** desktop (`viewport 1280 900`) and mobile
|
||||
(the driver's default) widths -- the layout genuinely forks at the
|
||||
860px breakpoint in `theme.css`.
|
||||
|
||||
## Commit
|
||||
|
||||
One commit for the whole widget (models + migration + render + router +
|
||||
UI + tests + docs) -- this project's convention is one feature per
|
||||
commit, not split by layer. No `Co-Authored-By: Claude` trailer (see
|
||||
root `CLAUDE.md`).
|
||||
@@ -0,0 +1,2 @@
|
||||
# Generated by setup.sh -- bakes in this host's /tmp paths, not portable.
|
||||
env.sh
|
||||
@@ -0,0 +1,234 @@
|
||||
---
|
||||
name: run-server
|
||||
description: Build, run, and drive the espresso_frame FastAPI server (server/) -- start it against a scratch DB, browser-test its UI, run its pytest suite. Use when asked to start the server, take a screenshot of a frame page, click through the web UI, or verify a server/UI change actually works.
|
||||
---
|
||||
|
||||
The espresso_frame server is a FastAPI app (`app.main:app`) with a
|
||||
server-rendered Jinja UI. For agent/automated use it's driven by a
|
||||
Playwright REPL at `.claude/skills/run-server/driver.py`, run under
|
||||
tmux -- `chromium-cli` isn't available in this container, so this
|
||||
driver replaces it (same command vocabulary: nav/wait-for/click/fill/
|
||||
screenshot/eval/console-errors).
|
||||
|
||||
This container ships with **no Python, Node, Docker, or browser, and
|
||||
no sudo**. `setup.sh` bootstraps everything non-root; it's the bulk of
|
||||
what makes this skill non-obvious. Run it once per fresh container.
|
||||
|
||||
Commands below (`setup.sh`, `start-server.sh`, `stop-server.sh`,
|
||||
`env.sh`, `driver.py`) are invoked from the **repo root** via their
|
||||
`.claude/skills/run-server/` path -- the scripts `cd` into `server/`
|
||||
themselves. Anything under `.venv/` (the venv itself, `pytest`,
|
||||
`uvicorn`) lives inside `server/`, so those commands need `server/`
|
||||
prefixed or `cd server` first.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
None to install manually -- `setup.sh` does it all without root, using
|
||||
only `curl`/`apt-get download`/`dpkg-deb -x` (never `apt-get install`,
|
||||
which needs root). It downloads ~450MB total (Python, Chromium, tmux,
|
||||
shared libs) on first run.
|
||||
|
||||
```bash
|
||||
bash .claude/skills/run-server/setup.sh
|
||||
```
|
||||
|
||||
Re-running is safe and fast -- every step checks whether it already
|
||||
happened (venv exists? chromium downloaded? libs extracted? tmux
|
||||
present?) before doing any work.
|
||||
|
||||
This creates:
|
||||
- `.venv/` -- Python 3.12 + `requirements.txt` + `playwright`, via `uv`
|
||||
(a static Rust binary that fetches its own Python -- no compiler
|
||||
needed, install via `curl -LsSf https://astral.sh/uv/install.sh | sh`)
|
||||
- `~/.cache/ms-playwright/` -- Chromium (full `chrome` + headless-shell)
|
||||
- `/tmp/run-server-chromium-deps/` -- Chromium's + tmux's shared libs
|
||||
and fonts, extracted (not installed) from `.deb` files
|
||||
- `.claude/skills/run-server/env.sh` -- the `PATH`/`LD_LIBRARY_PATH`/
|
||||
`FONTCONFIG_PATH`/`RUN_SERVER_CHROME_BIN` exports the driver needs
|
||||
(gitignored -- host-specific `/tmp` paths, regenerated by setup.sh)
|
||||
|
||||
## Run (agent path)
|
||||
|
||||
**1. Start the server** against a scratch DB (never the real
|
||||
deployment's data -- see `CLAUDE.md`):
|
||||
|
||||
```bash
|
||||
bash .claude/skills/run-server/start-server.sh
|
||||
# -> server PID <pid> up on http://127.0.0.1:8420 (log: /tmp/run-server-scratch/server.log)
|
||||
```
|
||||
|
||||
Optional args: `start-server.sh [scratch-dir] [port]` (defaults
|
||||
`/tmp/run-server-scratch` / `8420`).
|
||||
|
||||
**2. Drive it**, wrapped in tmux so you can send one command at a time
|
||||
and read the response before sending the next. `tmux` itself was
|
||||
extracted the same non-root way as Chromium's libs (see Prerequisites)
|
||||
and needs `LD_LIBRARY_PATH` set in *this* shell too, not just inside
|
||||
the pane -- source `env.sh` before the first `tmux` call:
|
||||
|
||||
```bash
|
||||
source .claude/skills/run-server/env.sh
|
||||
tmux new-session -d -s runserver -x 200 -y 50
|
||||
tmux send-keys -t runserver \
|
||||
'source .claude/skills/run-server/env.sh && server/.venv/bin/python .claude/skills/run-server/driver.py' Enter
|
||||
timeout 20 bash -c 'until tmux capture-pane -t runserver -p | grep -q "driver>"; do sleep 0.3; done'
|
||||
|
||||
# Every fresh scratch DB starts with no users -- bootstrap-admin
|
||||
# completes first-run /setup and logs in (see Commands table):
|
||||
tmux send-keys -t runserver 'bootstrap-admin' Enter
|
||||
timeout 15 bash -c 'until tmux capture-pane -t runserver -p | grep -q "bootstrapped admin"; do sleep 0.3; done'
|
||||
|
||||
tmux send-keys -t runserver 'nav /frames/1/config' Enter
|
||||
tmux send-keys -t runserver 'wait-for #frame-preview-thumb' Enter
|
||||
tmux send-keys -t runserver 'screenshot before' Enter
|
||||
tmux capture-pane -t runserver -p
|
||||
```
|
||||
|
||||
Poll for a specific marker between `send-keys` and `capture-pane`
|
||||
(`driver>`, `bootstrapped admin`, `screenshot:`, ...) rather than a
|
||||
fixed `sleep` -- it's faster and fails loudly instead of capturing a
|
||||
half-rendered screen. Give each poll its own `timeout` (~15-20s); don't
|
||||
chain many polling loops inside one shell invocation -- see Gotchas.
|
||||
|
||||
Screenshots land in `/tmp/run-server-shots/` (override:
|
||||
`SCREENSHOT_DIR`). **Actually look at them** -- a blank or error-page
|
||||
screenshot is a failure to launch, not success.
|
||||
|
||||
**Test every UI change at both a desktop and a mobile viewport.** The
|
||||
driver defaults to a desktop size (1280x900); switch with `viewport`.
|
||||
The app's mobile breakpoint is 860px (`theme.css`) -- below that the
|
||||
sidebar goes off-canvas behind a hamburger (`.mobile-bar`). A page that
|
||||
looks right at 1280px can still overflow, overlap the mobile bar, or
|
||||
mis-center a `<dialog>` at phone widths -- screenshot both:
|
||||
|
||||
```bash
|
||||
tmux send-keys -t runserver 'viewport 1280 900' Enter # desktop (also the default)
|
||||
tmux send-keys -t runserver 'screenshot desktop-x' Enter
|
||||
tmux send-keys -t runserver 'viewport 390 844' Enter # iPhone-ish mobile width
|
||||
tmux send-keys -t runserver 'screenshot mobile-x' Enter
|
||||
```
|
||||
|
||||
### Driver commands
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `nav <path-or-url>` | navigate (relative paths resolve against `http://127.0.0.1:8420`, override with `RUN_SERVER_BASE_URL`) |
|
||||
| `wait-for <selector>` | wait up to 10s for a selector (plain CSS -- see Gotchas for attribute selectors) |
|
||||
| `click <selector>` | click an element |
|
||||
| `fill <selector> <value>` | fill an input |
|
||||
| `press <key>` | keyboard press (e.g. `Enter`) |
|
||||
| `screenshot [name]` | → `/tmp/run-server-shots/<name>.png` |
|
||||
| `eval <js>` | evaluate JS in the page, prints JSON |
|
||||
| `console-errors` | prints all captured console/page errors as a JSON array |
|
||||
| `viewport [w] [h]` | resize the viewport, default `390 844` -- use `1280 900` for desktop (see Gotchas re: real touch input) |
|
||||
| `is-open <dialog-selector>` | prints `true`/`false` for a `<dialog>` element's `.open` -- use this instead of `wait-for sel[open]` |
|
||||
| `bootstrap-admin [user] [pass]` | completes first-run `/setup` (defaults `admin`/`testpassword123`); links frame #1 and logs in |
|
||||
| `quit` | closes the browser, exits the driver |
|
||||
|
||||
**3. Stop the server** when done:
|
||||
|
||||
```bash
|
||||
bash .claude/skills/run-server/stop-server.sh
|
||||
tmux kill-session -t runserver
|
||||
```
|
||||
|
||||
## Run (human path)
|
||||
|
||||
```bash
|
||||
cd server
|
||||
DATABASE_URL="sqlite:////tmp/dev.db" CONFIG_PATH="/tmp/dev-config.json" \
|
||||
.venv/bin/uvicorn app.main:app --reload --port 8420
|
||||
```
|
||||
|
||||
Open `http://localhost:8420` in a real browser. `start.sh` (the Docker
|
||||
entrypoint) is not this -- it also launches the Node whiteboard
|
||||
render-service sidecar, which needs Node (not installed here) and
|
||||
isn't needed for most UI testing.
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
cd server && .venv/bin/pytest
|
||||
```
|
||||
|
||||
Uses its own tempfile SQLite per run (`tests/conftest.py`) -- no setup
|
||||
needed beyond the venv.
|
||||
|
||||
---
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`viewport` only resizes the window -- it does not emulate touch
|
||||
input.** `click` still dispatches a mouse click, not a tap; there's
|
||||
no touch-delay, no `:hover`-stickiness-after-tap, no `hasTouch`
|
||||
context. It catches real bugs (layout overflow, off-canvas sidebar,
|
||||
a `<dialog>` mis-centering at phone widths) but won't catch anything
|
||||
that's specifically a touch-vs-mouse event difference. Good enough
|
||||
for CSS/layout verification; not a substitute for testing on an
|
||||
actual phone if a change touches touch-specific interaction.
|
||||
|
||||
- **`chrome-headless-shell` (Playwright's default headless target)
|
||||
crashes on basic calls in this container**, e.g. `page.set_content()`
|
||||
returns `TargetClosedError`, even after every `ldd`-reported missing
|
||||
library is resolved. The full `chrome` binary (`chromium-*/chrome-linux64/chrome`)
|
||||
+ `--no-sandbox` is stable; `driver.py` and `setup.sh` both use it,
|
||||
not the headless-shell default.
|
||||
|
||||
- **Missing fonts silently break `fill()`, not just rendering.** Before
|
||||
`fontconfig`/`libfontconfig1` were extracted and `fonts.conf` pointed
|
||||
at the extracted font dir, `page.fill()` ran with no error but left
|
||||
inputs empty (`input_value()` returned `""`), and all text rendered
|
||||
invisible in screenshots. It looks like a scripting bug, not a
|
||||
missing-lib problem -- if `fill` silently no-ops, suspect fonts
|
||||
before suspecting the selector or a race.
|
||||
|
||||
- **No `apt-get install` / `playwright install-deps` (no root) and no
|
||||
`apt-get update` into the real `/var/lib/apt/lists` (root-owned).**
|
||||
Worked around by redirecting apt's state dirs to a scratch,
|
||||
user-writable path (`-o Dir::State::Lists=... -o Dir::Cache=...`),
|
||||
which makes plain `update` and `install --download-only --print-uris`
|
||||
work as a non-root user; then `dpkg-deb -x <deb> <root>` (extract,
|
||||
not install) needs no root either. `setup.sh` does this for
|
||||
Chromium's deps *and* for `tmux` itself, which also isn't
|
||||
preinstalled.
|
||||
|
||||
- **`wait-for` with an attribute selector like `#frame-preview-dialog[open]`
|
||||
is unreliable through `tmux send-keys`** -- shell/tmux escaping of
|
||||
`[`/`]` easily mangles it (seen: a real 10s Playwright timeout from a
|
||||
garbled selector, not a fast failure). Use the app-specific `is-open
|
||||
<selector>` command instead of `wait-for sel[open]` to check a
|
||||
`<dialog>`'s open state.
|
||||
|
||||
- **Don't chain many `tmux send-keys` + polling-`timeout` loops inside
|
||||
one shell invocation.** Each poll can legitimately take up to its own
|
||||
timeout (e.g. 15s) if a selector is wrong; five or six chained in one
|
||||
command can add up past this tool's own command timeout even though
|
||||
each individual step is fine. Send one or two commands per shell
|
||||
call and check the pane before continuing.
|
||||
|
||||
- **A crashed `chrome-headless-shell` process can leave a large core
|
||||
dump file** (`server/core`, ~170MB, from the crash described above)
|
||||
if core dumps are enabled. It's not part of the app -- delete it, and
|
||||
use full `chrome` (as `driver.py` does) to avoid triggering it again.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **`error while loading shared libraries: libglib-2.0.so.0` (or similar)
|
||||
when launching Chromium directly**: `LD_LIBRARY_PATH` isn't set --
|
||||
source `.claude/skills/run-server/env.sh` first, or run through
|
||||
`driver.py`, which reads `RUN_SERVER_CHROME_BIN` from it.
|
||||
- **`fc-list` prints nothing after extracting fonts**: `fonts.conf`'s
|
||||
`<dir>` entries still point at the real (unpopulated) `/usr/share/fonts`.
|
||||
`setup.sh` patches this with `sed`; if you extracted packages by hand,
|
||||
do the same.
|
||||
- **`E: Could not open lock file ... Permission denied` from `apt-get`**:
|
||||
you're missing the `-o Dir::State::Lists=... -o Dir::Cache=...`
|
||||
overrides -- plain `apt-get update`/`install` always needs root here.
|
||||
- **`tmux: command not found`**: not preinstalled and no sudo; run
|
||||
`setup.sh`, which fetches it the same non-root way as Chromium's libs.
|
||||
- **`tmux: error while loading shared libraries: libutempter.so.0`**:
|
||||
you sourced `env.sh` inside the driver's tmux pane but not in the
|
||||
shell that *invokes* `tmux` itself -- `tmux` was extracted from the
|
||||
same non-root `.deb` set as Chromium and needs `LD_LIBRARY_PATH` too.
|
||||
`source .claude/skills/run-server/env.sh` before the first `tmux`
|
||||
command, not just inside `send-keys`.
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""REPL driver for the espresso_frame server's web UI.
|
||||
|
||||
Playwright-based since chromium-cli isn't available in this container.
|
||||
Reads one command per line from stdin, prints a result line -- built
|
||||
for tmux send-keys/capture-pane use by an agent. Vocabulary mirrors
|
||||
chromium-cli where it overlaps (nav/wait-for/click/fill/screenshot/
|
||||
eval/console-errors).
|
||||
|
||||
Requires setup.sh to have run first (Python venv + Playwright Chromium
|
||||
+ the non-root shared-lib/font extraction). Run via:
|
||||
|
||||
.claude/skills/run-server/env.sh sourced, then
|
||||
server/.venv/bin/python .claude/skills/run-server/driver.py
|
||||
|
||||
See SKILL.md for the full agent-path invocation (tmux wrapping etc).
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
SHOT_DIR = os.environ.get("SCREENSHOT_DIR", "/tmp/run-server-shots")
|
||||
os.makedirs(SHOT_DIR, exist_ok=True)
|
||||
BASE = os.environ.get("RUN_SERVER_BASE_URL", "http://127.0.0.1:8420")
|
||||
|
||||
|
||||
def find_chrome() -> str:
|
||||
override = os.environ.get("RUN_SERVER_CHROME_BIN")
|
||||
if override and os.path.exists(override):
|
||||
return override
|
||||
matches = glob.glob(os.path.expanduser("~/.cache/ms-playwright/chromium-*/chrome-linux64/chrome"))
|
||||
if not matches:
|
||||
sys.exit("chrome binary not found -- run setup.sh first")
|
||||
return matches[0]
|
||||
|
||||
|
||||
pw = sync_playwright().start()
|
||||
# The FULL `chrome` binary, not chrome-headless-shell (Playwright's
|
||||
# default headless target): chrome-headless-shell crashed on basic
|
||||
# calls like set_content() in this container even once every
|
||||
# ldd-reported missing lib was resolved. Full chrome + --no-sandbox is
|
||||
# stable here.
|
||||
browser = pw.chromium.launch(executable_path=find_chrome(), args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1280, "height": 900})
|
||||
console_errors: list[str] = []
|
||||
page.on("console", lambda msg: console_errors.append(msg.text) if msg.type == "error" else None)
|
||||
page.on("pageerror", lambda exc: console_errors.append(str(exc)))
|
||||
# Playwright auto-DISMISSES native confirm()/alert() dialogs by default
|
||||
# (returns false) -- several destructive actions in this app (remove
|
||||
# widget, clear all widgets) gate on `confirm()`, so without this a
|
||||
# `click` on one of those buttons would silently no-op. Auto-accept
|
||||
# instead, since a driver testing a "yes, do the destructive thing"
|
||||
# flow needs the confirm to actually go through.
|
||||
page.on("dialog", lambda dialog: dialog.accept())
|
||||
|
||||
|
||||
def cmd_nav(arg):
|
||||
url = arg if arg.startswith("http") else BASE + arg
|
||||
page.goto(url)
|
||||
print("nav ->", page.url)
|
||||
|
||||
|
||||
def cmd_wait_for(arg):
|
||||
page.wait_for_selector(arg, timeout=10000)
|
||||
print("found:", arg)
|
||||
|
||||
|
||||
def cmd_click(arg):
|
||||
page.click(arg)
|
||||
print("clicked:", arg)
|
||||
|
||||
|
||||
def cmd_fill(arg):
|
||||
sel, _, value = arg.partition(" ")
|
||||
page.fill(sel, value)
|
||||
print("filled:", sel, "=", value)
|
||||
|
||||
|
||||
def cmd_press(arg):
|
||||
page.keyboard.press(arg)
|
||||
print("pressed:", arg)
|
||||
|
||||
|
||||
def cmd_screenshot(arg):
|
||||
name = arg or f"ss-{len(os.listdir(SHOT_DIR))}"
|
||||
path = os.path.join(SHOT_DIR, name + ".png")
|
||||
page.screenshot(path=path)
|
||||
print("screenshot:", path)
|
||||
|
||||
|
||||
def cmd_eval(arg):
|
||||
try:
|
||||
print(json.dumps(page.evaluate(arg)))
|
||||
except Exception as e:
|
||||
print("ERROR:", e)
|
||||
|
||||
|
||||
def cmd_console_errors(_arg):
|
||||
print(json.dumps(console_errors))
|
||||
|
||||
|
||||
def cmd_viewport(arg):
|
||||
"""Resize the viewport. No args -> 390x844 (iPhone-ish mobile
|
||||
width); the page itself starts at 1280x900 (desktop) on launch, so
|
||||
`viewport 1280 900` gets back to that. The app's mobile breakpoint
|
||||
is 860px (see theme.css) -- anything under that exercises the
|
||||
off-canvas sidebar/mobile-bar layout."""
|
||||
parts = arg.split()
|
||||
width = int(parts[0]) if len(parts) > 0 else 390
|
||||
height = int(parts[1]) if len(parts) > 1 else 844
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
print("viewport:", width, "x", height)
|
||||
|
||||
|
||||
def cmd_is_open(arg):
|
||||
"""App-specific: print whether a <dialog> element is open (true/false)."""
|
||||
print(json.dumps(page.eval_on_selector(arg, "el => el.open")))
|
||||
|
||||
|
||||
def cmd_bootstrap_admin(arg):
|
||||
"""App-specific: complete first-run /setup (username/password args,
|
||||
default admin/testpassword123). Every scratch DB starts with no
|
||||
users, and /setup is the only way in -- it also auto-links the
|
||||
pre-existing frame #1 (created by migrations) to the new admin, so
|
||||
/frames/1/... is reachable right after this."""
|
||||
parts = arg.split()
|
||||
username = parts[0] if len(parts) > 0 else "admin"
|
||||
password = parts[1] if len(parts) > 1 else "testpassword123"
|
||||
page.goto(BASE + "/setup")
|
||||
page.fill("input[name=username]", username)
|
||||
page.fill("input[name=password]", password)
|
||||
page.click("button[type=submit]")
|
||||
page.wait_for_load_state("networkidle")
|
||||
print("bootstrapped admin, now at:", page.url)
|
||||
|
||||
|
||||
def cmd_quit(_arg):
|
||||
browser.close()
|
||||
pw.stop()
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
COMMANDS = {
|
||||
"nav": cmd_nav,
|
||||
"wait-for": cmd_wait_for,
|
||||
"click": cmd_click,
|
||||
"fill": cmd_fill,
|
||||
"press": cmd_press,
|
||||
"screenshot": cmd_screenshot,
|
||||
"eval": cmd_eval,
|
||||
"console-errors": cmd_console_errors,
|
||||
"viewport": cmd_viewport,
|
||||
"is-open": cmd_is_open,
|
||||
"bootstrap-admin": cmd_bootstrap_admin,
|
||||
"quit": cmd_quit,
|
||||
}
|
||||
|
||||
print("run-server driver -- commands:", ", ".join(COMMANDS), flush=True)
|
||||
print("driver>", end=" ", flush=True)
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
print("driver>", end=" ", flush=True)
|
||||
continue
|
||||
cmd, _, rest = line.partition(" ")
|
||||
fn = COMMANDS.get(cmd)
|
||||
if fn is None:
|
||||
print("unknown command:", cmd, "-- try one of:", ", ".join(COMMANDS))
|
||||
else:
|
||||
try:
|
||||
fn(rest)
|
||||
except Exception as e:
|
||||
print("ERROR:", e)
|
||||
print("driver>", end=" ", flush=True)
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-time (idempotent) environment bootstrap for running the
|
||||
# espresso_frame FastAPI server and browser-driving its UI, in a
|
||||
# container that ships with NO Python/Node/Docker/browser and NO sudo.
|
||||
# Re-run any time; every step checks whether it already happened.
|
||||
set -euo pipefail
|
||||
cd "$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/server"
|
||||
|
||||
UV_BIN="$HOME/.local/bin/uv"
|
||||
DEPS_ROOT="/tmp/run-server-chromium-deps"
|
||||
APT_WORK="/tmp/apt-work-run-server"
|
||||
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ENV_FILE="$SKILL_DIR/env.sh"
|
||||
|
||||
# 1. uv: a static Rust binary that can fetch its own Python build with
|
||||
# no C compiler needed (this container has none).
|
||||
if [ ! -x "$UV_BIN" ]; then
|
||||
echo "installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
fi
|
||||
|
||||
# 2. Python 3.12 + venv + server deps
|
||||
if [ ! -x .venv/bin/uvicorn ]; then
|
||||
echo "creating venv + installing server deps..."
|
||||
"$UV_BIN" python install 3.12
|
||||
"$UV_BIN" venv --python 3.12 .venv
|
||||
"$UV_BIN" pip install -r requirements.txt
|
||||
fi
|
||||
|
||||
# 3. Playwright (Python) + its Chromium download (~280MB: full chrome +
|
||||
# chrome-headless-shell + ffmpeg)
|
||||
if ! .venv/bin/python -c "import playwright" 2>/dev/null; then
|
||||
echo "installing playwright..."
|
||||
"$UV_BIN" pip install playwright
|
||||
fi
|
||||
if ! ls "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux64/chrome >/dev/null 2>&1; then
|
||||
echo "downloading chromium..."
|
||||
.venv/bin/playwright install chromium
|
||||
fi
|
||||
|
||||
# 4. Chromium's shared libs + fonts. `playwright install-deps` and
|
||||
# `apt-get install` both need root; neither is available. Instead:
|
||||
# download the .deb files directly (apt-get download works read-only
|
||||
# without root once given a user-writable state dir) and extract
|
||||
# (not install) them with dpkg-deb -x, which needs no root either.
|
||||
if [ ! -f "$DEPS_ROOT/usr/lib/x86_64-linux-gnu/libglib-2.0.so.0" ]; then
|
||||
echo "fetching chromium's shared libs + fonts (non-root)..."
|
||||
mkdir -p "$APT_WORK/lists" "$APT_WORK/cache/archives/partial" "$APT_WORK/debs" "$DEPS_ROOT"
|
||||
|
||||
apt-get -o Dir::State::Lists="$APT_WORK/lists" -o Dir::Cache="$APT_WORK/cache" \
|
||||
-o Dir::Etc::SourceParts=/dev/null update
|
||||
|
||||
PKGS="libglib2.0-0t64 libnspr4 libnss3 libatk1.0-0t64 libatk-bridge2.0-0t64
|
||||
libdbus-1-3 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1
|
||||
libxkbcommon0 libasound2t64 libatspi2.0-0t64 libcups2t64 libcairo2
|
||||
libpango-1.0-0 libpangocairo-1.0-0 libx11-6 libxcb1 libxext6
|
||||
fonts-liberation fontconfig libfontconfig1"
|
||||
# ^ first row: what chrome-headless-shell's ldd reported missing.
|
||||
# second row: what the FULL chrome binary additionally needed (we use
|
||||
# full chrome, not headless-shell -- see Gotchas in SKILL.md).
|
||||
|
||||
apt-get -o Dir::State::Lists="$APT_WORK/lists" -o Dir::Cache="$APT_WORK/cache" \
|
||||
-o Dir::Etc::SourceParts=/dev/null install --download-only --reinstall -y \
|
||||
--print-uris $PKGS | grep -oP "^'[^']+'" | tr -d "'" > "$APT_WORK/urls.txt"
|
||||
|
||||
(cd "$APT_WORK/debs" && xargs -n1 -P8 curl -sS -O --max-time 30) < "$APT_WORK/urls.txt"
|
||||
for f in "$APT_WORK"/debs/*.deb; do dpkg-deb -x "$f" "$DEPS_ROOT"; done
|
||||
|
||||
# fonts.conf as shipped points at the real /usr/share/fonts, which is
|
||||
# root-owned and has nothing extracted into it. Point it at our
|
||||
# extracted copy instead, and give it a writable cache dir.
|
||||
mkdir -p /tmp/run-server-fontcache
|
||||
sed -i "s#<dir>/usr/share/fonts</dir>#<dir>$DEPS_ROOT/usr/share/fonts</dir>#" \
|
||||
"$DEPS_ROOT/etc/fonts/fonts.conf"
|
||||
sed -i "s#<cachedir>.*</cachedir>#<cachedir>/tmp/run-server-fontcache</cachedir>#" \
|
||||
"$DEPS_ROOT/etc/fonts/fonts.conf"
|
||||
|
||||
PATH="$DEPS_ROOT/usr/bin:$PATH" \
|
||||
LD_LIBRARY_PATH="$DEPS_ROOT/usr/lib/x86_64-linux-gnu:$DEPS_ROOT/lib/x86_64-linux-gnu" \
|
||||
FONTCONFIG_PATH="$DEPS_ROOT/etc/fonts" \
|
||||
"$DEPS_ROOT/usr/bin/fc-cache" -f
|
||||
fi
|
||||
|
||||
# 5. tmux -- also missing, also no apt/sudo. Same non-root download +
|
||||
# dpkg-deb -x trick, into the same extracted root (so its `usr/bin` is
|
||||
# already on PATH via env.sh).
|
||||
if [ ! -f "$DEPS_ROOT/usr/bin/tmux" ]; then
|
||||
echo "fetching tmux (non-root)..."
|
||||
mkdir -p "$APT_WORK/lists" "$APT_WORK/cache/archives/partial" "$APT_WORK/debs" "$DEPS_ROOT"
|
||||
apt-get -o Dir::State::Lists="$APT_WORK/lists" -o Dir::Cache="$APT_WORK/cache" \
|
||||
-o Dir::Etc::SourceParts=/dev/null install --download-only --reinstall -y \
|
||||
--print-uris tmux | grep -oP "^'[^']+'" | tr -d "'" > "$APT_WORK/tmux_urls.txt"
|
||||
(cd "$APT_WORK/debs" && xargs -n1 -P3 curl -sS -O --max-time 30) < "$APT_WORK/tmux_urls.txt"
|
||||
for f in $(sed -E 's#.*/##' "$APT_WORK/tmux_urls.txt"); do dpkg-deb -x "$APT_WORK/debs/$f" "$DEPS_ROOT"; done
|
||||
fi
|
||||
|
||||
CHROME_BIN="$(ls "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux64/chrome | head -1)"
|
||||
|
||||
cat > "$ENV_FILE" <<EOF
|
||||
# Generated by setup.sh. Source this before running driver.py (it
|
||||
# needs LD_LIBRARY_PATH/FONTCONFIG_PATH set before the Chromium
|
||||
# subprocess launches -- driver.py does not source it for you).
|
||||
# start-server.sh does NOT need this file -- uvicorn has no such deps.
|
||||
export PATH="\$HOME/.local/bin:$DEPS_ROOT/usr/bin:\$PATH"
|
||||
export LD_LIBRARY_PATH="$DEPS_ROOT/usr/lib/x86_64-linux-gnu:$DEPS_ROOT/lib/x86_64-linux-gnu"
|
||||
export FONTCONFIG_PATH="$DEPS_ROOT/etc/fonts"
|
||||
export RUN_SERVER_CHROME_BIN="$CHROME_BIN"
|
||||
EOF
|
||||
|
||||
echo "setup complete -> $ENV_FILE"
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Background-launch the server against a scratch DB/config -- never the
|
||||
# real deployment's data (see CLAUDE.md). Waits for readiness, prints
|
||||
# the PID and log path. Usage: ./start-server.sh [scratch-dir] [port]
|
||||
set -euo pipefail
|
||||
cd "$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/server"
|
||||
|
||||
SCRATCH="${1:-/tmp/run-server-scratch}"
|
||||
PORT="${2:-8420}"
|
||||
mkdir -p "$SCRATCH"
|
||||
|
||||
DATABASE_URL="sqlite:///$SCRATCH/test.db" \
|
||||
CONFIG_PATH="$SCRATCH/config.json" \
|
||||
LOG_PATH="$SCRATCH/app.log" \
|
||||
.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port "$PORT" \
|
||||
> "$SCRATCH/server.log" 2>&1 &
|
||||
PID=$!
|
||||
echo "$PID" > "$SCRATCH/server.pid"
|
||||
|
||||
for _ in $(seq 1 30); do
|
||||
curl -sf -o /dev/null "http://127.0.0.1:$PORT/" && break
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
if ! curl -sf -o /dev/null "http://127.0.0.1:$PORT/"; then
|
||||
echo "server did not become ready -- check $SCRATCH/server.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "server PID $PID up on http://127.0.0.1:$PORT (log: $SCRATCH/server.log, db: $SCRATCH/test.db)"
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: ./stop-server.sh [scratch-dir]
|
||||
SCRATCH="${1:-/tmp/run-server-scratch}"
|
||||
if [ -f "$SCRATCH/server.pid" ]; then
|
||||
kill "$(cat "$SCRATCH/server.pid")" 2>/dev/null || true
|
||||
rm -f "$SCRATCH/server.pid"
|
||||
echo "stopped"
|
||||
else
|
||||
echo "no $SCRATCH/server.pid -- nothing to stop"
|
||||
fi
|
||||
@@ -0,0 +1,51 @@
|
||||
name: Firmware build check
|
||||
|
||||
# Fires on every push touching firmware source, unlike
|
||||
# firmware-release-build.yml (which only builds+publishes when
|
||||
# firmware/version.txt itself is bumped -- the "cut a release" signal).
|
||||
# This just verifies both board variants still compile; nothing else in
|
||||
# CI catches a firmware/** push that breaks the build until someone
|
||||
# happens to bump the version next.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "firmware/**"
|
||||
- ".gitea/workflows/firmware-build-check.yml"
|
||||
|
||||
jobs:
|
||||
build-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Same docker create/cp/start pattern as firmware-release-build.yml
|
||||
# (see that file's own comment for why -- the runner's job
|
||||
# workspace lives in a named Docker volume, not a real host path,
|
||||
# so a nested `docker run -v "$PWD:..."` bind-mounts nothing
|
||||
# useful). No release/artifact step here -- this only needs to
|
||||
# prove `idf.py build` still succeeds for each board.
|
||||
- name: Build (devkit -- ESP32-C6-DevKitC-1)
|
||||
run: |
|
||||
cid=$(docker create -w /workspace/firmware espressif/idf:release-v6.0 bash -c '
|
||||
git config --global --add safe.directory /workspace &&
|
||||
. "$IDF_PATH/export.sh" &&
|
||||
./build_for_board.sh devkit set-target esp32c6 &&
|
||||
./build_for_board.sh devkit build
|
||||
')
|
||||
docker cp "$PWD/." "$cid:/workspace"
|
||||
docker start -a "$cid"
|
||||
docker rm "$cid"
|
||||
|
||||
- name: Build (xiao -- Seeed XIAO ESP32-C6)
|
||||
run: |
|
||||
cid=$(docker create -w /workspace/firmware espressif/idf:release-v6.0 bash -c '
|
||||
git config --global --add safe.directory /workspace &&
|
||||
. "$IDF_PATH/export.sh" &&
|
||||
./build_for_board.sh xiao set-target esp32c6 &&
|
||||
./build_for_board.sh xiao build
|
||||
')
|
||||
docker cp "$PWD/." "$cid:/workspace"
|
||||
docker start -a "$cid"
|
||||
docker rm "$cid"
|
||||
@@ -8,7 +8,27 @@ on:
|
||||
- ".gitea/workflows/server-docker-build.yml"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: server
|
||||
run: pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run tests
|
||||
working-directory: server
|
||||
run: pytest
|
||||
|
||||
build-and-push:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -32,3 +52,41 @@ jobs:
|
||||
tags: |
|
||||
git.thumeit.com/tfaour/espresso-frame-server:latest
|
||||
git.thumeit.com/tfaour/espresso-frame-server:${{ gitea.sha }}
|
||||
|
||||
deploy:
|
||||
needs: build-and-push
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy over SSH
|
||||
env:
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
|
||||
DEPLOY_PORT: ${{ secrets.DEPLOY_PORT || '22' }}
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "$DEPLOY_SSH_KEY" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh-keyscan -p "$DEPLOY_PORT" "$DEPLOY_HOST" >> ~/.ssh/known_hosts 2>/dev/null
|
||||
ssh -i ~/.ssh/deploy_key -p "$DEPLOY_PORT" -o StrictHostKeyChecking=yes \
|
||||
espressoframe_deployer@"$DEPLOY_HOST" bash -s <<'REMOTE'
|
||||
set -e
|
||||
cd ~/espresso-frame
|
||||
docker compose down --remove-orphans
|
||||
docker compose pull
|
||||
# "down" returning doesn't guarantee the OS/docker-proxy has
|
||||
# actually released port 8420 yet -- an immediate "up -d" right
|
||||
# after (especially with "pull" a no-op because the image was
|
||||
# already cached) can lose that race and fail with "port is
|
||||
# already allocated", even though the exact same "up -d" run a
|
||||
# few seconds later succeeds every time. Retry instead of
|
||||
# guessing at a fixed sleep long enough to always cover it.
|
||||
for i in $(seq 1 10); do
|
||||
if docker compose up -d; then
|
||||
exit 0
|
||||
fi
|
||||
echo "docker compose up -d failed (attempt $i/10) -- retrying in 3s"
|
||||
sleep 3
|
||||
done
|
||||
echo "docker compose up -d did not succeed after 10 attempts"
|
||||
exit 1
|
||||
REMOTE
|
||||
|
||||
+12
-1
@@ -17,6 +17,13 @@ server/**/__pycache__/
|
||||
server/.venv/
|
||||
server/*.egg-info/
|
||||
server/data/
|
||||
server/.pytest_cache/
|
||||
# render-service/ (whiteboard mode's Node sidecar) -- installed fresh
|
||||
# inside the Docker image, never committed. No package-lock.json exists
|
||||
# yet either (no Node/npm available in this project's dev environment to
|
||||
# generate one -- see render-service/README.md); if one's added later, do
|
||||
# NOT ignore it, lockfiles belong in git.
|
||||
server/render-service/node_modules/
|
||||
# Real deploy config, copied from docker-compose.yml.example -- holds the
|
||||
# Immich API key, must never be committed.
|
||||
server/docker-compose.yml
|
||||
@@ -27,4 +34,8 @@ server/docker-compose.yml
|
||||
.idea/
|
||||
*.swp
|
||||
.DS_Store
|
||||
.claude/
|
||||
.claude/*
|
||||
# ...except Claude Code skills (e.g. agent-run instructions for this
|
||||
# app) -- those are project tooling worth sharing, not personal/local
|
||||
# state like settings.local.json or worktrees/.
|
||||
!.claude/skills/
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# espresso_frame
|
||||
|
||||
A DIY e-ink photo frame: an ESP32-C6 (`firmware/`, ESP-IDF) driving a
|
||||
Waveshare 7.3" E Ink Spectra 6 panel (800x480, 6-color, SPI), paired with a
|
||||
self-hosted FastAPI server (`server/`) that pulls from Immich, does all
|
||||
image processing (crop/dither/quantize/pack), and serves a placeable
|
||||
photos/calendar/whiteboard/weather widget system to the device.
|
||||
|
||||
CURRENT TODO
|
||||
-sharing layouts with linked users
|
||||
-a "coming up this week" widget
|
||||
-on reset dismiss the menu.
|
||||
|
||||
Start here, don't re-derive from scratch:
|
||||
- [`docs/architecture.md`](docs/architecture.md) -- how firmware and
|
||||
server talk (sequence diagram, boot flow).
|
||||
- [`docs/widgets.md`](docs/widgets.md) -- the server-side widget system
|
||||
(data model, grid placement, compositor, button-action dispatch).
|
||||
- [`docs/hardware.md`](docs/hardware.md) -- wiring.
|
||||
- [`server/README.md`](server/README.md), [`firmware/README.md`](firmware/README.md)
|
||||
-- per-component setup, config, and a lot of accumulated gotchas
|
||||
(Immich API shape, TLS trust-anchor details, button GPIO wakeup
|
||||
quirks, etc.) -- check these before assuming something is a new bug.
|
||||
|
||||
## Conventions specific to this repo
|
||||
|
||||
- **No `Co-Authored-By: Claude` trailers in commits.** Attribution lives
|
||||
in the root [`README.md`](README.md) instead (see its last line) --
|
||||
the maintainer's explicit preference, not the default.
|
||||
- **Copyleft dependencies need an explicit flag, not a silent decision.**
|
||||
Before adding anything LGPL/GPL/AGPL (or unclear), verify the actual
|
||||
license via `pip show`/package metadata -- including transitive deps,
|
||||
not just the top-level package -- and present the finding and tradeoff
|
||||
in plain text rather than picking an approach unilaterally (hand-rolling
|
||||
an alternative, swapping packages, silently accepting it). This project
|
||||
has knowingly accepted AGPL-3.0-or-later exposure once already
|
||||
(`icalendar-searcher`, a transitive dep of `caldav`) as a deliberate,
|
||||
explicit call -- not a precedent for skipping the check next time.
|
||||
- **Scope new auth/access-control broadly, not just to the literal
|
||||
endpoint named.** When a request changes the trust model (e.g. adding
|
||||
public-internet exposure), apply the new gate to every endpoint serving
|
||||
real data or performing a real action, and call out anything you're
|
||||
tempted to exclude and why. This repo shipped a token gate once that
|
||||
covered `/api/*` but left `/frame/image` -- the actual photo bytes --
|
||||
open; caught immediately in production.
|
||||
- **Commit and push once a task is verified working, without waiting to
|
||||
be asked separately.** Once tests pass (and, for UI changes, the
|
||||
browser check has been done), stage the relevant files, write a normal
|
||||
commit message, and push to the current branch -- the maintainer's
|
||||
standing authorization for the commit/push step itself. This doesn't
|
||||
relax anything else: still run `git status`/review the diff before
|
||||
staging, still never force-push/amend a pushed commit/skip hooks, and
|
||||
still surface anything that looks like it needs a real decision (e.g.
|
||||
a change that would trigger `main`'s deploy workflow, see below)
|
||||
instead of pushing through it silently.
|
||||
|
||||
## Working in this repo
|
||||
|
||||
- **Server tests**: `cd server && pytest` (SQLite, fixtures wipe/reseed
|
||||
between tests -- see `tests/conftest.py`). Migration changes need a
|
||||
matching test in `tests/test_migrations.py`; anything touching
|
||||
`require_frame_view`/`require_frame_control` boundaries needs a
|
||||
same-shape permission test (see `tests/test_permission_boundaries.py`
|
||||
and `tests/test_button_actions.py` for the pattern: owner, linked user,
|
||||
unrelated user, logged out).
|
||||
- **UI changes**: verify in a real browser (Playwright), not just by
|
||||
reading the JS -- this project has hit multiple bugs that only showed up
|
||||
live (mobile viewport CSS collapse, a dialog's status message landing
|
||||
behind its own backdrop, a JSON/form-urlencoded body mismatch). Spin up
|
||||
`uvicorn app.main:app` against a scratch `DATABASE_URL`/`CONFIG_PATH`
|
||||
sqlite file, don't touch the real deployment's data. `.claude/skills/run-server/`
|
||||
(`/run-server`) has a driver for exactly this.
|
||||
- **New/changed UI must work at both desktop and mobile widths --
|
||||
screenshot both, don't assume one implies the other.** The layout
|
||||
genuinely forks at the 860px breakpoint (`theme.css`): the sidebar
|
||||
goes off-canvas behind a hamburger below it. A dialog, header
|
||||
control, or new widget that looks right at a wide viewport can
|
||||
overflow, overlap the mobile bar, or mis-center at phone widths.
|
||||
`run-server`'s driver has a `viewport` command for exactly this
|
||||
(defaults to a phone size; switch to `1280 900` for desktop).
|
||||
- **Deploy**: Gitea Actions at `git.thumeit.com/tfaour/espresso_frame`
|
||||
(`.gitea/workflows/server-docker-build.yml`: `test` -> `build-and-push`
|
||||
-> `deploy` on any push to `main` touching `server/**`; `deploy` SSHes
|
||||
into the host as `espressoframe_deployer` and runs `docker compose pull
|
||||
&& docker compose up -d`). A separate workflow
|
||||
(`firmware-release-build.yml`) builds+publishes firmware binaries as
|
||||
Gitea release assets when `firmware/version.txt` changes. Poll CI status
|
||||
with `curl https://git.thumeit.com/api/v1/repos/tfaour/espresso_frame/actions/tasks`
|
||||
rather than asking the user to check.
|
||||
- **Device-facing paths are frozen.** `/frame/image`, `/frame/advance`,
|
||||
`/frame/back`, `/frame/config`, `/frame/battery`, `/frame/firmware` and
|
||||
their exact JSON key names (`refresh_interval_s`, `firmware_version`,
|
||||
etc.) are baked into deployed firmware -- never rename or restructure
|
||||
these without a firmware-side migration story to match.
|
||||
@@ -24,9 +24,10 @@ time in deep sleep.
|
||||
- ESP32-C6 dev board (8MB flash)
|
||||
- [Waveshare 7.3" E Ink Spectra 6 (E6)](https://www.waveshare.com/7.3inch-e-paper-hat-e.htm) panel -- 800x480, 6-color, SPI
|
||||
|
||||
See [`docs/hardware.md`](docs/hardware.md) for wiring and
|
||||
See [`docs/hardware.md`](docs/hardware.md) for wiring,
|
||||
[`docs/architecture.md`](docs/architecture.md) for how the two halves talk
|
||||
to each other.
|
||||
to each other, and [`docs/widgets.md`](docs/widgets.md) for the server's
|
||||
placeable photos/calendar/whiteboard widget system.
|
||||
|
||||
## Getting started
|
||||
|
||||
|
||||
+19
-8
@@ -22,17 +22,17 @@ sequenceDiagram
|
||||
Frame->>Frame: Connect to home WiFi
|
||||
alt next-photo button pressed
|
||||
Frame->>Server: POST /frame/advance
|
||||
Server->>Server: Force-advance to next queued photo, reset interval clock
|
||||
Server->>Server: Run every action assigned to NEXT, in order<br/>(may span several widgets -- see docs/widgets.md)
|
||||
else back-photo button pressed
|
||||
Frame->>Server: POST /frame/back
|
||||
Server->>Server: Return to previously-current photo (bounded history),<br/>reset interval clock
|
||||
Server->>Server: Run every action assigned to BACK, in order
|
||||
else normal wake
|
||||
Frame->>Server: GET /frame/image
|
||||
Server->>Server: Advance only if refresh_interval_s has elapsed<br/>since the current photo was set -- otherwise a no-op
|
||||
Server->>Server: Render every widget on the panel into its own region<br/>(each independently idempotent -- a photo widget only<br/>actually advances once its own refresh_interval_s has elapsed)
|
||||
end
|
||||
Server->>Immich: List album assets / download preview / faces
|
||||
Server->>Immich: List album assets / download preview / faces<br/>(once per photo widget on the panel)
|
||||
Immich-->>Server: JPEG + face bounding boxes
|
||||
Server->>Server: Crop (face-aware) + quantize (dither) + pack 4bpp
|
||||
Server->>Server: Composite every widget's region onto one canvas,<br/>then enhance/overlay/quantize (dither)/pack 4bpp once
|
||||
Server-->>Frame: 192,000 raw bytes, streamed
|
||||
Frame->>Frame: Write to panel SPI buffer, compute CRC32
|
||||
alt CRC unchanged since last physical refresh
|
||||
@@ -45,6 +45,17 @@ sequenceDiagram
|
||||
Frame->>Frame: Deep sleep (server-configured interval, or a short<br/>retry interval on any failure)
|
||||
```
|
||||
|
||||
The device-facing endpoints above (`/frame/image`, `/frame/advance`,
|
||||
`/frame/back`, `/frame/config`) are frozen -- baked into deployed firmware
|
||||
-- and unchanged by any of this. What *does* change server-side: a frame's
|
||||
panel isn't a single fixed "mode" anymore, it holds an arbitrary
|
||||
arrangement of independently placed/sized widgets (photos/calendar/
|
||||
whiteboard, including several of the same type), each rendered into its
|
||||
own region and composited together, with NEXT/BACK each mapped to their
|
||||
own ordered list of per-widget actions rather than one fixed meaning. See
|
||||
[`docs/widgets.md`](widgets.md) for the widget system's data model,
|
||||
placement grid, and button-action dispatch.
|
||||
|
||||
## Firmware boot flow
|
||||
|
||||
1. **No stored config** (first boot, or NVS erased): bring up the display,
|
||||
@@ -91,9 +102,9 @@ sequenceDiagram
|
||||
- Deep sleep for the server-configured interval on success, or a
|
||||
shorter retry interval on any failure.
|
||||
|
||||
The menu/reset button's soft-reset and factory-reset tiers (held ~3s
|
||||
or ~15s) are handled earlier, before any of this, and never return --
|
||||
see [`firmware/README.md`](../firmware/README.md#managing-the-queue-soft-resetting-and-factory-resetting).
|
||||
The menu/reset button's soft-reset (quick press) and factory-reset
|
||||
(held ~15s) tiers are handled earlier, before any of this, and never
|
||||
return -- see [`firmware/README.md`](../firmware/README.md#managing-the-queue-soft-resetting-and-factory-resetting).
|
||||
|
||||
See [`docs/hardware.md`](hardware.md) for wiring and
|
||||
[`server/README.md`](../server/README.md) for the server side.
|
||||
|
||||
+4
-4
@@ -40,10 +40,10 @@ pressed):
|
||||
photo; see
|
||||
[`firmware/README.md`](../firmware/README.md#going-back-to-the-previous-photo).
|
||||
- **Menu / reset (GPIO1)**: one button, three actions by hold duration --
|
||||
a quick press overlays a "scan to manage" QR code on the current photo
|
||||
for 30 seconds; holding ~3s then releasing soft-resets the device
|
||||
(config kept); holding ~15s factory-resets it (clears WiFi/server
|
||||
config, reprovisions); see
|
||||
a quick press soft-resets the device (config kept); holding ~3s then
|
||||
releasing overlays a "scan to manage" QR code on the current photo for
|
||||
30 seconds; holding ~15s factory-resets it (clears WiFi/server config,
|
||||
reprovisions); see
|
||||
[`firmware/README.md`](../firmware/README.md#managing-the-queue-soft-resetting-and-factory-resetting).
|
||||
|
||||
All three pins were picked because they're within GPIO 0-7 -- the only
|
||||
|
||||
+578
@@ -0,0 +1,578 @@
|
||||
# Widget system
|
||||
|
||||
A frame's panel isn't one fixed "mode" anymore -- it holds N independently
|
||||
placed/sized widgets (photos/calendar/whiteboard/tasks/static image/text/
|
||||
weather/battery), like arranging icons on an Android home screen. A frame
|
||||
can hold several widgets of the same type (e.g. two photo widgets pointed
|
||||
at different Immich albums side by side).
|
||||
This replaced an earlier design where `Frame.mode` picked exactly one
|
||||
full-panel renderer; that column and the other per-mode `Frame` columns
|
||||
it left behind (`album_id`, `calendar_*`, `whiteboard_*`, etc.) were
|
||||
dropped in migration 41, once every phase of the rollout had shipped
|
||||
(see "Known gaps" below for what's still open).
|
||||
|
||||
The device-facing contract is unchanged by any of this: `GET /frame/image`,
|
||||
`POST /frame/advance`, `POST /frame/back` are the same frozen paths
|
||||
firmware has always called (see `docs/architecture.md`) -- what changed is
|
||||
entirely server-side, in how those endpoints decide what to render and what
|
||||
a button press does.
|
||||
|
||||
## Data model
|
||||
|
||||
- `Widget` (`server/app/models.py`): `id`, `frame_id`, `widget_type`
|
||||
(`"photos"` | `"calendar"` | `"whiteboard"` | `"tasks"` | `"static"` |
|
||||
`"text"` | `"weather"` | `"battery"`), `x`/`y`/`w`/`h`
|
||||
(grid cells), `sort_order`. Widgets never overlap (enforced server-side in
|
||||
`routers/api_widgets.py`, re-validated regardless of what the client
|
||||
already checked) -- that's what keeps compositing simple: no z-order,
|
||||
no blending, just N independent regions pasted onto one shared canvas.
|
||||
Also carries an optional per-widget border (`border_style` -- `"none"`
|
||||
| `"solid"` | `"dashed"` | `"dotted"` | `"fancy"`, `border_thickness`,
|
||||
`border_color_index`, an index into the frame's palette so a border
|
||||
always renders as one of the panel's exact 6 ink colors) directly on
|
||||
`Widget` itself rather than a per-type config table, since every
|
||||
widget type can have one regardless of `widget_type`. Drawn by
|
||||
`image_pipeline.draw_widget_border` onto each widget's own region in
|
||||
`routers/device.py`'s `_render_widgets`, before that region is pasted
|
||||
onto the shared canvas -- one central integration point instead of
|
||||
every `app/widgets/*.py` module needing to know about it. Set via the
|
||||
gear-icon dialog's shared "Border" card (`_widget_border_fields.html`,
|
||||
included by every `_widget_dialog_*.html` template) and
|
||||
`POST .../widgets/{id}/border`, its own endpoint (not folded into
|
||||
`api_widget_config_save`) since that endpoint's per-type dispatch is
|
||||
keyed on a config row via `widget_locked`, and border fields live on
|
||||
`Widget` itself, not any per-type config table.
|
||||
Also carries `font_scale` (one of `panel_style.FONT_SCALE_CHOICES` --
|
||||
`1.0`/`1.25`/`1.5`, labeled Normal/Large/X-Large), a per-widget
|
||||
legibility control: calendar and tasks widgets pack in the most body
|
||||
text at the smallest default sizes, so their gear-icon dialogs get a
|
||||
"Text size" card (`_widget_font_scale_fields.html`) the other types
|
||||
don't. Same Widget-level-property-not-config-field reasoning as
|
||||
border, and its own `POST .../widgets/{id}/font-scale` endpoint for
|
||||
the same reason. `panel_style.scaled_size(value, font_scale)` is the
|
||||
one shared multiply-and-round point every classic (`calendar_render.py`)
|
||||
and modern (`html_render.py`/`calendar_html_render.py`) size calc
|
||||
routes through immediately after its own tier lookup/floor, so row
|
||||
heights and per-view row caps (already derived from the font size, not
|
||||
a fixed constant) automatically re-fit around the bigger text instead
|
||||
of overflowing their box.
|
||||
- Per-type 1:1 extension tables -- `PhotoWidgetConfig`,
|
||||
`CalendarWidgetConfig`, `WhiteboardWidgetConfig`, `TaskWidgetConfig`,
|
||||
`StaticWidgetConfig`, `TextWidgetConfig`, `WeatherWidgetConfig`,
|
||||
`BatteryWidgetConfig`, each keyed by `widget_id` with
|
||||
`ondelete="CASCADE"` -- rather than one wide table with every type's
|
||||
mostly-irrelevant columns. `TextWidgetConfig.content` is parsed rich
|
||||
text (paragraphs of styled runs), never raw HTML -- see
|
||||
`server/app/text_content.py`'s module docstring for why that parse
|
||||
step is the widget's actual stored-XSS sanitization boundary.
|
||||
`PhotoWidgetConfig`
|
||||
mirrors `app/photo_queue.py`'s attribute names exactly, so that module's
|
||||
advance/back/queue logic ports across widget instances unchanged.
|
||||
`PhotoWidgetConfig.locked` (migration 27) freezes `current_asset_id`
|
||||
against both the timer-elapsed auto-advance
|
||||
(`photo_queue.get_current`) and the advance/back button actions
|
||||
(`app/widgets/photos.py`'s `ACTIONS`) until unlocked -- toggled via a
|
||||
"Lock this photo" button in the widget's own dialog
|
||||
(`POST .../widgets/{id}/lock`), shown as a lock badge on the widget's
|
||||
box on the Layout tab canvas.
|
||||
`TaskWidgetConfig` used to be a handful of `tasks_*` columns bolted onto
|
||||
`CalendarWidgetConfig` (a week-view-only, single-list task list); split
|
||||
into its own widget type (migration 17) so a task list can be placed
|
||||
and sized independent of any calendar's view/footprint, then (migration
|
||||
18) given the same multi-source shape a calendar widget already has.
|
||||
`WeatherWidgetConfig` similarly lifts `CalendarWidgetConfig`'s embedded
|
||||
weather strip (still present and unchanged, `weather_*` columns) out
|
||||
into its own placeable widget type (migration 24) -- see "Weather
|
||||
widget" below. `BatteryWidgetConfig` (migration 25) is the odd one out
|
||||
-- its actual content (`Frame.battery_percent`/`battery_as_of`) isn't
|
||||
in this table at all, already existing frame-level state set by
|
||||
`routers/device.py`'s `frame_battery` regardless of whether a battery
|
||||
widget is even placed; the config row only holds a display-mode
|
||||
setting (`"compact"` | `"detailed"`).
|
||||
- `FrameCalendar`/`FrameTaskList` are keyed by `widget_id` (not
|
||||
`frame_id`) since a frame can now have more than one independent
|
||||
calendar/tasks widget, each with its own included set. Identical
|
||||
shape and permission model (owner-added, anyone-linked-can-mute, see
|
||||
"Per-widget config UI" below) -- `FrameTaskList` just has no `"ics"`
|
||||
calendar_key variant, since a plain ICS subscription has no VTODO
|
||||
(task) collection.
|
||||
- `FrameButtonAction` (`id`, `frame_id`, `button` [`"next"`|`"back"`],
|
||||
`widget_id`, `action`, `sort_order`) -- see "Button actions" below.
|
||||
|
||||
## Placement: a grid, not freeform pixels
|
||||
|
||||
`app/grid.py` is pure grid math, no I/O. The grid is `GRID_LONG=8` x
|
||||
`GRID_SHORT=5` cells, defined relative to the panel's long/short axis
|
||||
(not "landscape" specifically) so it stays valid across
|
||||
`image_pipeline.logical_render_size(orientation)`'s genuine width/height
|
||||
swap for portrait -- landscape orientations are 8 cols x 5 rows, portrait
|
||||
are 5 cols x 8 rows, same cell size either way. **Changing a frame's
|
||||
orientation invalidates its existing layout** (an 8x5 arrangement isn't
|
||||
valid on a 5x8 grid) -- the server resets to one full-panel widget on an
|
||||
orientation change rather than trying to remap coordinates.
|
||||
|
||||
Each widget type has a minimum grid footprint (`grid.MIN_FOOTPRINT`):
|
||||
photos 1x1, calendar 3x2 (a crammed calendar is illegible regardless of
|
||||
size-tier scaling), whiteboard 2x2, tasks 2x2, static image 1x1, text 2x1,
|
||||
weather 2x2 (its hourly/daily strips need the room; current/multi_city
|
||||
modes would tolerate smaller, but every mode shares one footprint value),
|
||||
battery 1x1 (just an icon + a percent, legible even at a single cell,
|
||||
like photos/static -- though see `MIN_FOOTPRINT`'s own comment in
|
||||
`grid.py` on a mobile-width gear-icon click-target gap at that size,
|
||||
already pre-existing for photos/static too). Enforced both client-side
|
||||
(UX, in the Layout tab's drag/resize canvas -- `static/frame_layout.js`)
|
||||
and server-side (`routers/api_widgets.py`) -- the client is never trusted
|
||||
alone.
|
||||
|
||||
## Rendering: one shared compositor
|
||||
|
||||
`app/widgets/` is the render/action registry -- one module per
|
||||
`widget_type` (`photos.py`, `calendar.py`, `whiteboard.py`, `tasks.py`,
|
||||
`static_image.py`, `text.py`, `weather.py`, `battery.py`), each exposing:
|
||||
|
||||
- `render(db, frame, widget, target_w, target_h, is_normal_wake) -> Image`:
|
||||
an unquantized RGB image exactly `target_w x target_h`, the widget's
|
||||
content composed into its own region. Never raises for a foreseeable
|
||||
failure (an Immich hiccup, an unconfigured widget) -- falls back to a
|
||||
small placeholder within its own region instead, so one widget having a
|
||||
bad moment doesn't blank the whole panel.
|
||||
- `ACTIONS: dict[str, Callable]` -- named button actions this type
|
||||
supports (`"advance"`/`"back"` for photos and calendar, `"check_now"`
|
||||
for whiteboard and weather -- both throttled external fetches with a
|
||||
forced-refetch action). Empty for tasks, static image, text, and
|
||||
battery -- nothing to advance/back/force for a passive checklist, a
|
||||
fixed uploaded image, a fixed block of authored text, or a number the
|
||||
device itself pushes on every wake.
|
||||
- `ACTION_LABELS: dict[str, str]` -- human labels for the button-
|
||||
assignment UI.
|
||||
|
||||
`routers/device.py`'s `_render_widgets` loads every `Widget` row for the
|
||||
frame, maps each one's grid rect to pixels (`grid.cell_to_pixels`), calls
|
||||
its module's `render()`, and hands the whole list of `(rect, image)`
|
||||
regions to `image_pipeline.render_panel` -- which pastes every region onto
|
||||
one shared canvas, then runs enhance/manage-overlay/quantize/dither/pack
|
||||
**once** over the composited result. Quantizing the whole canvas together
|
||||
(not each region separately before pasting) is what keeps the 6-color
|
||||
e-ink dithering pattern consistent across a widget boundary instead of a
|
||||
visible seam at the edge.
|
||||
|
||||
Calendar widgets pick from discrete size tiers (`calendar_render.py`'s
|
||||
`_SIZE_TIERS`) for font size/margins/row heights based on their actual
|
||||
grid footprint, rather than continuously scaling constants tuned for a
|
||||
full ~800x480 canvas -- falls back to agenda view if a widget is too small
|
||||
for month view to stay legible.
|
||||
|
||||
### "Modern" render style (experimental)
|
||||
|
||||
Every widget type except photos has a `render_style` column (`"classic"`
|
||||
default | `"modern"`) that swaps its hand-drawn PIL primitives for an
|
||||
HTML/CSS render: a Jinja2 template (`app/templates/widget_html/`) drawn
|
||||
through a persistent headless-Chromium browser (`app/html_render.py`,
|
||||
Playwright) instead of `ImageDraw` -- gradients, shadows, and soft icon
|
||||
shading PIL can't easily do. Calendar's own modern-style builders (all
|
||||
four view modes) live in `app/calendar_html_render.py` rather than
|
||||
`html_render.py` itself, mirroring `calendar_render.py`'s own separation
|
||||
from the simpler widget types.
|
||||
|
||||
Every modern-style builder runs its own `ordered_dither` (Bayer/ordered,
|
||||
not Floyd-Steinberg) before returning, committing the widget to exact
|
||||
palette colors *before* compositing -- safe to mix with photo/other
|
||||
classic-rendered widgets on the same frame without a Floyd-Steinberg
|
||||
seam at the boundary, because ordered dithering has no cross-pixel error
|
||||
term the way Floyd-Steinberg's diffusion does (see `html_render.py`'s
|
||||
module docstring). No `Frame`-level dithering setting was needed to make
|
||||
this work.
|
||||
|
||||
Not offered for the **photos** widget -- a real photograph isn't a
|
||||
synthesized dashboard card, and photos has a different concern instead:
|
||||
its own independent palette/dithering strength (`Frame.photo_palette_rgb`
|
||||
/ `photo_dither_strength`, a second "Photos configuration" card in
|
||||
Advanced Configuration, separate from the main `palette_rgb`/
|
||||
`dither_strength` every other widget uses). `widgets/photos.py`'s
|
||||
`render()` quantizes itself against these before returning, so a frame
|
||||
can tune the rest of its widgets' look (e.g. a calibrated palette for
|
||||
modern-style dashboard widgets) independently of what actually looks
|
||||
best for real photographs, with no `render_panel` changes needed --
|
||||
see that module's own docstring for the one small, accepted edge case
|
||||
(a border on a photos widget whose palette genuinely diverges from the
|
||||
frame's main one).
|
||||
|
||||
Playwright/Chromium is a real, heavyweight runtime dependency imported
|
||||
lazily only when a widget actually uses modern style. Its browser binary
|
||||
is fetched by `start.sh` at container startup rather than baked into the
|
||||
image (see `server/Dockerfile`'s own comment) -- a single ~181MB
|
||||
`chrome-headless-shell` binary can't be split across Docker layers the
|
||||
way this project's pip/npm installs were, and confirmed-failed to push
|
||||
to the registry as a build-time layer; cached on the `/data` volume
|
||||
(`PLAYWRIGHT_BROWSERS_PATH`) so only the very first boot on a fresh
|
||||
volume actually downloads it. Still real-panel-unverified -- treat every
|
||||
"modern" style as experimental regardless of deploy status.
|
||||
|
||||
Per-widget-type notes:
|
||||
|
||||
- **weather**: `current`/`daily` modes only -- `hourly`/`multi_city`
|
||||
always render classic regardless of this setting (see the Weather
|
||||
widget section below).
|
||||
- **calendar**: all four view modes (agenda/today_tomorrow/week/month)
|
||||
have a modern builder -- the only widget type with full modern-style
|
||||
coverage from the start, rather than a partial rollout like weather's.
|
||||
Month view's "falls back to agenda below a size threshold" behavior
|
||||
(`_month_view_fits`) is honored identically in both styles.
|
||||
- **battery/text/tasks**: full coverage (both battery modes; text reuses
|
||||
its own `_fit()` shrink-to-fit sizing logic, only the drawing differs).
|
||||
- **static image/whiteboard**: modern style is the *first* visual chrome
|
||||
either widget type has ever had (classic draws the image with zero
|
||||
frame/card at all) -- a rounded-corner, shadowed card
|
||||
(`framed_image.html.jinja`, shared between the two) wrapping the
|
||||
already-composed image. Left alone by the "bold minimal" pass below --
|
||||
it never had the reskinned-classic problem the other widgets did.
|
||||
|
||||
### "Bold minimal": a real redesign, not just a reskin
|
||||
|
||||
The initial modern-style rollout (above) mostly translated each widget's
|
||||
*existing* classic layout into HTML/CSS -- same gradient header banner,
|
||||
same rounded-shadowed white card, prettier chrome around an unchanged
|
||||
composition. A second pass reworked weather (`current`/`daily`),
|
||||
calendar (all four views), tasks, and battery into an actual different
|
||||
visual language, picked from several divergent directions rendered
|
||||
through the real pipeline and reviewed with the maintainer (not chosen
|
||||
unilaterally -- see the "Reverted e-ink quantization attempt"-style
|
||||
caution about visual changes needing more than one look). Text and
|
||||
static/whiteboard were deliberately left as they were (see their notes
|
||||
just above) -- text already had zero chrome and its styling is
|
||||
user-authored content, not this system's to redesign; the framed-image
|
||||
card was already minimal.
|
||||
|
||||
What changed, as a consistent language across every redesigned widget:
|
||||
|
||||
- **No card.** No rounded-corner white box, no drop shadow, no outer
|
||||
border -- content sits directly on the shared white canvas. `theme
|
||||
["radius"]`/`theme["shadow"]` are now unused by every redesigned
|
||||
widget's builder (still resolved, for signature uniformity with
|
||||
`resolve_theme`, but nothing reads them) -- a theme's radius/shadow
|
||||
fields now only affect the *un*-redesigned modern widgets (static
|
||||
image/whiteboard's `framed_image.html.jinja`).
|
||||
- **A slim accent rule instead of a gradient banner.** Every widget that
|
||||
used to have a colored header bar with white text on it (weather's
|
||||
`build_daily`, tasks, calendar's four views) now has a thin (~4-8px)
|
||||
accent-colored rounded rule, with the header text as plain ink below
|
||||
it instead of white text on top of it -- only that thin rule dithers
|
||||
at the theme's richer `accent_amplitude` via `ordered_dither_regions`
|
||||
now, not the header text sitting on it, which reads as a legibility
|
||||
improvement, not just a visual one (see "Rich accent hues" below).
|
||||
- **A dominant hero value, not a centered icon+number of equal weight.**
|
||||
Weather's `build_current` and battery's icon+percent used to be drawn
|
||||
at roughly the same size, centered as a unit; both now put the numeric
|
||||
value (temperature / battery percent) at a clearly dominant size, with
|
||||
the icon small and secondary above it -- closer to a phone home-screen
|
||||
widget than a dashboard tile.
|
||||
- **Padding/type sizes as a proportion of widget size, clamped to a
|
||||
floor/ceiling, not a fixed pixel value.** So a 1-2 grid-cell widget
|
||||
doesn't get comically large padding relative to its content, and a
|
||||
near-full-panel widget doesn't get comically small padding either --
|
||||
see `html_render._clamp` and every redesigned `build_*`'s own
|
||||
`pad`/size calculations (`base = min(target_w, target_h)`, then a
|
||||
fraction of `base` clamped to tuned floor/ceiling values).
|
||||
|
||||
**A hairline color this palette can't actually render.** Auditing the
|
||||
month view's grid during this pass turned up a real, pre-existing bug
|
||||
carried forward unnoticed since the very first modern-style rollout:
|
||||
`.day-cell`/`.day-section`/`.col` divider borders used a pale gray
|
||||
(`#e2e6ec`) -- but `DEFAULT_PALETTE_RGB` has no gray in it at all (black/
|
||||
white/yellow/red/blue/green only), so a color that close to white always
|
||||
nearest-matches to pure white regardless of Bayer bias, at any amplitude
|
||||
-- confirmed by sampling actual rendered pixels, not just eyeballing a
|
||||
screenshot. The month grid's week-row dividers now use real solid black
|
||||
(`RULE`-equivalent, matching how the *classic* PIL renderer always drew
|
||||
them -- see `calendar_render.RULE`); the day-section/week-column dividers
|
||||
were simply dropped instead, since the accent rule + spacing at the
|
||||
start of the next section/column already read as a clear boundary
|
||||
without a line at all once you could actually render one.
|
||||
|
||||
### Themes for modern-style widgets
|
||||
|
||||
`Frame.theme` (String, default `"classic"`, one Advanced Configuration
|
||||
`<select>`) picks a curated visual preset for every modern-style widget
|
||||
on that frame -- font family, corner radius, drop shadow, and an accent
|
||||
hue for widgets with a header/accent region. Presets live in
|
||||
`app/theme_tokens.py`'s `THEMES` dict; `resolve_theme(theme_name,
|
||||
widget_kind, palette_rgb)` turns one into concrete, ready-to-render
|
||||
values (`accent_hex`/`accent_hex_dark`, resolved `font_regular`/
|
||||
`font_bold` file paths, `radius`, `shadow`, `accent_amplitude`). Inspired
|
||||
by [Tesserae](https://github.com/dmellok/tesserae)'s (AGPL-3.0) own
|
||||
three-layer CSS custom-property theme system -- this is an original
|
||||
reimplementation of that *architecture*, not a copy of its token file
|
||||
(see this repo's `CLAUDE.md` on copyleft dependencies).
|
||||
|
||||
**What a theme actually changes, in practice**: the accent color (now a
|
||||
slim rule rather than a full header band -- see "Bold minimal" above) is
|
||||
still the most visible change on widgets that have one, but `font_family`
|
||||
applies to *every* text element in the widget, not just the header title
|
||||
-- day labels, temperatures, task rows, event times, day numbers all
|
||||
switch fonts too (e.g. "Moss" is serif, "Ochre" a slab serif), often
|
||||
more noticeable than the accent color on text-heavy widgets. `radius`/
|
||||
`shadow` only affect static image/whiteboard's card now (every other
|
||||
modern-style widget dropped its card in the "bold minimal" pass); text
|
||||
never used them (no card from the start) and weather/battery/tasks/
|
||||
calendar no longer have a card for them to apply to either.
|
||||
|
||||
**A theme is purely stylistic, never functional color-coding.** Battery's
|
||||
charge-level red/yellow/green, calendar/tasks' per-owner event color
|
||||
chips, and text's user-authored inline run colors are status/identity
|
||||
signals, not style choices -- no theme may recolor them, and every
|
||||
`build_*`/`resolve_theme` call site that touches those stays on its own
|
||||
existing logic untouched. Text's own per-widget `font_family` setting
|
||||
(a user's explicit content-level choice, same carve-out reasoning) is
|
||||
similarly never overridden by a theme -- `build_text` accepts a
|
||||
`theme_name` param for signature uniformity with every other modern-
|
||||
style builder but deliberately ignores it.
|
||||
|
||||
**Rich accent hues, not just the 6 exact panel inks.** A theme's
|
||||
`accent_hex` can be any arbitrary color (e.g. terracotta, moss, slate) --
|
||||
`html_render.ordered_dither_regions(rendered, palette_rgb,
|
||||
base_amplitude, accent_regions=[(rect, amplitude), ...])` dithers the
|
||||
whole widget at the existing safe default (`ordered_dither`'s tuned 48,
|
||||
unchanged, still icon/text-legible) and then *separately* re-dithers
|
||||
just the accent rectangle (a header bar's already-computed pixel rect)
|
||||
at a theme's higher `accent_amplitude` (~130) and pastes it back. Safe
|
||||
to do per-region for the same reason `ordered_dither` itself is safe
|
||||
per-widget: ordered (Bayer) dithering has no cross-pixel error term, so
|
||||
a region's result depends only on its own pixels. A single higher
|
||||
amplitude applied to the *whole* widget instead was tried and rejected --
|
||||
it washes out pale content (a weather icon's white cloud body nearly
|
||||
vanished in testing); confining the higher amplitude to just the accent
|
||||
rect avoids that while still letting the rect approximate a rich hue via
|
||||
denser stippling instead of flatly snapping to one nearest ink (what
|
||||
happens to a rich hue at the base amplitude).
|
||||
|
||||
**"classic" is a deliberately no-visual-change default.** Its
|
||||
`accent_hex` is `None`, meaning "keep this widget kind's own pre-theme
|
||||
look exactly": weather's header was always a fixed blue gradient (now
|
||||
`theme_tokens._CLASSIC_WEATHER_GRADIENT`, byte-identical to the old
|
||||
module-level `ACCENT_START`/`ACCENT_END` constants this system
|
||||
replaced); tasks/calendar's header was always a flat single ink resolved
|
||||
through `panel_style.THEME` (still is, just via `resolve_theme` now).
|
||||
Widget kinds with no ink of their own (battery/text/static/whiteboard)
|
||||
fall back to black, though none of their templates currently have an
|
||||
accent-colored surface for it to visibly affect.
|
||||
|
||||
Which widgets get the richer accent-region treatment: weather's
|
||||
`build_daily` (the slim rule, when `city_label` is set), tasks, and
|
||||
calendar's four view builders -- each computes its own small accent-rule
|
||||
pixel rect (a fixed-height band, not the old full header_h) and passes
|
||||
just that to `ordered_dither_regions`. Weather's `build_current` and
|
||||
battery have no accent surface at all (no header of any kind -- see
|
||||
"Bold minimal" above) and static/whiteboard's shared `build_framed_image`
|
||||
is unchanged from the original rollout; all three call plain
|
||||
`ordered_dither` with no accent region.
|
||||
|
||||
## Button actions
|
||||
|
||||
Each physical button (NEXT/BACK) runs the `(widget, action)` binding of
|
||||
every widget on the frame that has one -- **at most one binding per
|
||||
widget per button** (a widget can't be bound to two different actions on
|
||||
the same button). On a press, `routers/device.py`'s `_run_button_actions`
|
||||
runs every widget's assigned action for that button (each in its own
|
||||
`widget_locked` span -- never nested, since the underlying per-frame lock
|
||||
isn't reentrant), catching and logging any single action's failure
|
||||
without blocking the rest, then re-renders and returns the whole composed
|
||||
panel once at the end regardless of which actions succeeded. Which
|
||||
widget's action runs first never matters -- each only touches its own
|
||||
state, and the shared re-render happens once, after all of them finish.
|
||||
|
||||
The UI for this lives in each widget's own gear-icon config dialog (the
|
||||
"Button actions" card, `templates/_widget_button_fields.html` +
|
||||
`static/widget_dialog_button_actions.js`, `POST
|
||||
/api/frames/{id}/widgets/{widget_id}/button-actions`) -- not a frame-level
|
||||
tab, since assigning a widget's next/back behavior is naturally part of
|
||||
configuring that widget. The card only renders for widget types with a
|
||||
non-empty `ACTIONS` (photos, calendar, whiteboard, weather); tasks/
|
||||
static/text/battery have nothing to bind so the card is omitted for
|
||||
them. An empty selection ("(none)") clears that button's binding for the
|
||||
widget.
|
||||
|
||||
A newly-created widget (including the one auto-migrated from a frame's
|
||||
old `mode` on upgrade) gets a sensible default binding reproducing its
|
||||
old button behavior -- see `widgets.default_button_actions` (called from
|
||||
both `migration.py`'s backfill and `api_widgets.py`'s
|
||||
`api_widget_create`), so a widget is never left with nothing bound until
|
||||
someone deliberately reassigns it.
|
||||
|
||||
### Hold-for-global-action
|
||||
|
||||
Holding NEXT or BACK past a configurable duration (`Frame.hold_duration_ms`,
|
||||
minimum 3000ms, set on the Configuration tab) triggers a **global**
|
||||
action instead of the per-widget one -- not scoped to any widget, e.g.
|
||||
cycling through the user's saved layouts. See `app/global_actions.py`'s
|
||||
`GLOBAL_ACTIONS`/`GLOBAL_ACTION_LABELS` registry and
|
||||
`routers/device.py`'s `/frame/global-next`/`/frame/global-back` (the
|
||||
device calls these instead of `/frame/advance`/`/frame/back` once it
|
||||
detects a long press -- see `firmware/main/next_button.c`/`back_button.c`).
|
||||
`Frame.next_hold_action`/`back_hold_action` pick which registry entry (if
|
||||
any) each button's hold triggers; unset is a silent no-op, same
|
||||
convention as an unbound short-press button.
|
||||
|
||||
## Per-widget config UI
|
||||
|
||||
Each widget has a gear-icon button on the Layout canvas that opens a
|
||||
`<dialog>` with that widget's own settings (album, calendar/task-list
|
||||
inclusion, whiteboard source, etc.) -- not a per-frame tab, since a
|
||||
frame can now have several widgets of the same type with independent
|
||||
settings. The
|
||||
dialog HTML is injected server-rendered (`routers/frame_pages.py`'s
|
||||
`widget_dialog`, dispatching on `widget.widget_type`); its JS is a
|
||||
top-level, always-loaded file (`static/widget_dialog_*.js`) exposing
|
||||
`init<Type>Dialog()`/`close<Type>Dialog()`, since dynamically-injected
|
||||
HTML can't carry executable `<script>` tags. While a dialog is open,
|
||||
`window.FRAME_API` is repointed at that widget's own API base
|
||||
(`/api/frames/{id}/widgets/{widget_id}`) and restored on close;
|
||||
`window.FRAME_BASE_API` stays pointed at the frame-level base throughout
|
||||
for the always-present header/status-bar JS.
|
||||
|
||||
## Saved layouts
|
||||
|
||||
A user can snapshot a frame's whole widget arrangement -- every widget's
|
||||
type/placement/settings, calendar/task sources, and button-action
|
||||
bindings -- under a name (`SavedLayout` + `SavedLayoutWidget` +
|
||||
`SavedLayoutSource` + `SavedLayoutButtonAction`, `server/app/models.py`),
|
||||
then switch back to it later, or apply it to a *different* frame. Saved
|
||||
layouts are owned by the **user**, not any one frame -- the same set
|
||||
shows up (with a per-frame `compatible` flag) on every frame that user
|
||||
controls whose grid matches (`grid.grid_dims(orientation)`'s cols/rows,
|
||||
landscape-class 8x5 vs. portrait-class 5x8), not just the frame it was
|
||||
captured from.
|
||||
|
||||
Saving only captures an authored *setting*, never runtime/cache state --
|
||||
a photo widget's current queue position, a calendar's fetch cache, a
|
||||
whiteboard's rendered-image cache, etc. are deliberately left out (see
|
||||
`routers/api_layouts.py`'s `LAYOUT_CONFIG_FIELDS` allowlist per
|
||||
`widget_type`), so applying a layout feels like a fresh widget of that
|
||||
type with its settings pre-filled, not a resurrection of stale state
|
||||
from whenever it was saved. A static-image widget's uploaded bytes are
|
||||
the one exception carried through verbatim (`SavedLayoutWidget.image`).
|
||||
Saving again under a name the user already has overwrites that layout's
|
||||
snapshot in place rather than erroring or creating a duplicate --
|
||||
`SavedLayout`'s own docstring.
|
||||
|
||||
Applying a layout to a frame (`api_layout_apply`, `require_frame_control`)
|
||||
deletes every widget currently on that frame and recreates the saved
|
||||
arrangement from scratch, remapping calendar/task sources and button
|
||||
bindings onto the newly-created widget ids -- same "act unconditionally
|
||||
on the server, confirm on the client" posture as the Layout tab's own
|
||||
"Clear all". A source whose owning user account no longer exists is
|
||||
silently dropped rather than left dangling (config is JSON, not
|
||||
FK-checked, so nothing else would catch that).
|
||||
|
||||
The web UI lives in the Layout tab's "Saved layouts" card
|
||||
(`static/saved_layouts.js`, `GET`/`POST /api/frames/{id}/layouts`,
|
||||
`PATCH`/`DELETE /api/layouts/{id}`, `POST
|
||||
/api/frames/{id}/layouts/{id}/apply`) -- name + Save, then a list of
|
||||
saved layouts each with Apply/rename/delete, incompatible ones shown
|
||||
greyed-out with a "different orientation" badge rather than hidden.
|
||||
|
||||
## Weather widget
|
||||
|
||||
A standalone widget type (`models.WeatherWidgetConfig`, `app/widgets/
|
||||
weather.py`) -- distinct from, and unrelated in code to,
|
||||
`CalendarWidgetConfig`'s own embedded weather strip (still present,
|
||||
still Open-Meteo-only, still working exactly as before). Four display
|
||||
modes (`WeatherWidgetConfig.mode`, switchable in the widget's dialog like
|
||||
`calendar_view`):
|
||||
|
||||
- `current` -- one city's current temp + a condition icon.
|
||||
- `hourly` -- one city, a row of ticks across the day at a configurable
|
||||
interval (`hourly_interval_hours`: 3/4/6/12).
|
||||
- `daily` -- one city, a multi-day strip (`daily_days`, 1-14).
|
||||
- `multi_city` -- several cities' current-day high/low/icon side by
|
||||
side -- the calendar widget's embedded strip, as a standalone
|
||||
widget's whole content instead of a strip above an agenda day.
|
||||
|
||||
**Render style** (`WeatherWidgetConfig.render_style`, `"classic"` default
|
||||
| `"modern"`, experimental) -- see "Modern render style" above; weather's
|
||||
own modern coverage is `current`/`daily` only, `hourly`/`multi_city`
|
||||
always render classic regardless of this setting.
|
||||
|
||||
`current`/`hourly`/`daily` share one configured location
|
||||
(`city_label`/`city_latitude`/`city_longitude`, set via `POST .../
|
||||
weather-location`, geocoded through `weather.geocode_city`); `multi_city`
|
||||
has its own list (`cities`, add/remove via `POST .../weather-widget-
|
||||
cities/add`|`remove` -- named to avoid colliding with the calendar
|
||||
widget's own, differently-scoped `weather-cities/add`|`remove` routes,
|
||||
which share the same `{widget_id}`-parameterized path shape).
|
||||
|
||||
**Providers** (`app/weather/`, a dispatch registry over pluggable
|
||||
implementations mirroring `app/widgets/` itself): `WeatherWidgetConfig.
|
||||
provider` selects which of `app/weather.PROVIDERS` actually fetches --
|
||||
`"open_meteo"` (worldwide, no API key), `"nws"` (api.weather.gov, US
|
||||
only, no API key, approximates "current" with the first hourly forecast
|
||||
period rather than a real station observation), or `"ec"` (Environment
|
||||
Canada, api.weather.gc.ca's MSC GeoMet OGC API, Canada only, no API key).
|
||||
Every provider function returns already-normalized `{"category": ...}`
|
||||
entries (one of `clear`/`partly_cloudy`/`cloudy`/`fog`/`rain`/`snow`/
|
||||
`thunderstorm`) so `app/weather_render.py`'s drawing code never needs to
|
||||
know which provider supplied an entry. `geocode_city` (name -> lat/lon)
|
||||
always goes through Open-Meteo's free geocoder regardless of which
|
||||
provider is chosen to fetch with the result.
|
||||
|
||||
EC's `citypageweather-realtime` collection is only queryable by bounding
|
||||
box (OGC API - Features), not a direct by-coordinate endpoint -- unlike
|
||||
Open-Meteo/NWS's simple lat/lon REST, `app/weather/ec.py`'s
|
||||
`_nearest_site` widens the box progressively and picks the closest site
|
||||
by straight-line distance, rejecting anything beyond 300 km (calibrated
|
||||
against a real bug caught in development: an unconditional "nearest
|
||||
site, however far" matched a Miami, FL query to a site in Ontario,
|
||||
1824 km away, once the box widened enough to cover the whole country).
|
||||
|
||||
`app/weather_render.py` holds every weather-related drawing primitive:
|
||||
`draw_weather_icon`/`draw_weather_row` (extracted out of
|
||||
`calendar_render.py`, which still imports `draw_weather_row` for its own
|
||||
embedded strip, unchanged) plus this widget's own `build_current`/
|
||||
`build_hourly`/`build_daily`/`build_multi_city`, dispatched by `build()`
|
||||
-- the weather analogue of `calendar_render.py`'s own `_build_tasks`/
|
||||
`render_tasks_preview_png` relationship. Icons are hand-drawn (no custom
|
||||
font/icon asset), styled after Environment Canada's own icon set
|
||||
(pointed sun rays, a puffy cloud, teardrop rain, dendrite snowflakes, a
|
||||
zigzag bolt) but filled with the panel's *exact* ink RGB values rather
|
||||
than an arbitrary bitmap's anti-aliased colors -- a flat fill that's
|
||||
already a palette color quantizes with zero dithering error to diffuse,
|
||||
where a fetched/vendored icon's colors (almost never an exact match)
|
||||
dither into a visible speckle at these small on-panel sizes (confirmed
|
||||
by actually running one through the real quantize pass during
|
||||
development). Used for every provider's rendering, not just when EC is
|
||||
selected as the provider.
|
||||
|
||||
## Battery widget
|
||||
|
||||
The simplest widget type (`models.BatteryWidgetConfig`, `app/widgets/
|
||||
battery.py`): shows this frame's own last-reported battery level. Unlike
|
||||
every other widget type, there's no live upstream to poll and nothing to
|
||||
cache -- the content is `Frame.battery_percent`/`battery_as_of`, set by
|
||||
`routers/device.py`'s `frame_battery` on every device wake-on-battery
|
||||
report, which already existed for the Device panel's own history chart
|
||||
regardless of whether a battery widget is placed anywhere. The widget's
|
||||
own config is just a display mode: `"compact"` (icon + percent) or
|
||||
`"detailed"` (default, adds `routers/common.py`'s existing
|
||||
`battery_estimate_s` time-remaining estimate and the last report's age).
|
||||
`render()` falls back to a "No reports yet" placeholder for a frame that
|
||||
has never reported (never run on battery, or not yet claimed by a
|
||||
device) rather than showing a stale or fabricated number. The battery
|
||||
icon fill color (red/yellow/green by percent) uses the same exact-panel-
|
||||
ink-RGB approach as the weather icons above and `manage_overlay.py`'s own
|
||||
battery glyph on the "scan to manage" overlay -- a separate, unrelated
|
||||
piece of code with its own fixed small size, not shared with this
|
||||
widget, but drawing from the same thresholds/colors so a battery glyph
|
||||
reads the same wherever one shows up on a panel.
|
||||
|
||||
## Known gaps
|
||||
|
||||
The original 8-phase rollout plan's last phase is done: migration 41
|
||||
dropped the legacy per-mode `Frame` columns (`mode`, `album_id`,
|
||||
`current_asset_id`, all `calendar_*`, all `whiteboard_*`, `queue`, etc.)
|
||||
-- see its own docstring in `app/migration.py` for the raw-SQL backfill
|
||||
safety net that ran first, and `server/README.md` no longer describes
|
||||
photos/calendar/whiteboard as per-frame "modes".
|
||||
|
||||
Still open:
|
||||
|
||||
- Whiteboard rendering is tagged **(alpha)** in the UI -- not fully
|
||||
reliable yet, treat it as experimental if extending it.
|
||||
+47
-28
@@ -66,8 +66,9 @@ Under **ESPresso Frame Configuration**:
|
||||
| `FRAME_NEXT_BUTTON_GPIO` | 2 | Next-photo button GPIO (-1 to disable). Must be 0-7 (ESP32-C6's deep-sleep-wakeup-capable pins) |
|
||||
| `FRAME_BACK_BUTTON_GPIO` | 0 | Back-photo button GPIO (-1 to disable). Must be 0-7 |
|
||||
| `FRAME_COMBO_BUTTON_GPIO` | 1 | Menu/reset button GPIO (-1 to disable). Must be 0-7 |
|
||||
| `FRAME_COMBO_SOFT_RESET_HOLD_MS` | 3000 | How long the combo button must be held (then released) to soft-reset |
|
||||
| `FRAME_COMBO_MENU_HOLD_MS` | 3000 | How long the combo button must be held (then released) to show the management menu |
|
||||
| `FRAME_COMBO_FACTORY_RESET_HOLD_MS` | 15000 | How long the combo button must be held to factory-reset |
|
||||
| `FRAME_HOLD_ACTION_MS` | 3000 | **Fallback only** -- how long NEXT/BACK must be held to trigger a global action instead of a short press; see below |
|
||||
| `FRAME_BATTERY_ADC_GPIO` | -1 (disabled) | Battery voltage-divider ADC GPIO; see the Battery section below |
|
||||
| `FRAME_VBUS_SENSE_GPIO` | -1 (disabled) | USB-power sense GPIO for hiding the battery indicator on mains |
|
||||
|
||||
@@ -84,6 +85,34 @@ reflashing. The Kconfig value only applies before the device has ever
|
||||
successfully reached a configured server, or if the response doesn't
|
||||
include a valid interval.
|
||||
|
||||
### Holding NEXT/BACK for a global action
|
||||
|
||||
Past `FRAME_HOLD_ACTION_MS`, holding NEXT or BACK stops meaning "advance/
|
||||
back this widget" and instead triggers whatever frame-wide action (if
|
||||
any) is configured for that button's hold on the server's Configuration
|
||||
tab -- e.g. cycling through saved layouts (see
|
||||
`server/app/global_actions.py`). Fires immediately at the threshold,
|
||||
without waiting for release -- same convention as the combo button's
|
||||
factory-reset tier below.
|
||||
|
||||
Same "fallback only" caveat as `FRAME_SLEEP_INTERVAL_S` above, but with
|
||||
one more wrinkle: the server's actual `hold_duration_ms` (set on the
|
||||
Configuration tab, `GET /frame/config`'s response) can't be used for
|
||||
*this* wake's button decision -- that decision happens in `main.c`
|
||||
before WiFi even connects, but `/frame/config` isn't fetched until near
|
||||
the end of the wake cycle (after the image fetch, deliberately -- see
|
||||
`frame_client_run`'s own comment on why). So the device always acts on
|
||||
whatever value the *previous* wake fetched (persisted in NVS via
|
||||
`frame_config_set_hold_duration_ms`), falling back to
|
||||
`FRAME_HOLD_ACTION_MS` only before it's ever successfully fetched one.
|
||||
In practice this means changing the duration on the Configuration tab
|
||||
takes effect starting with the wake *after* the next one, not
|
||||
immediately.
|
||||
|
||||
Holding a button through the poll loop keeps the device awake and
|
||||
connected longer than a normal short-press wake -- the same tradeoff
|
||||
already accepted for the combo button's menu/reset holds below.
|
||||
|
||||
### WiFi fast-connect
|
||||
|
||||
After a successful home-WiFi connection, the device caches the AP's
|
||||
@@ -118,10 +147,9 @@ two-step setup screen:
|
||||
portal's config page (`http://192.168.4.1/` by default), for a
|
||||
one-scan shortcut once you've joined the AP.
|
||||
|
||||
The config page asks for your home WiFi SSID/password, the "Tools
|
||||
The config page asks for your home WiFi SSID/password and the "Tools
|
||||
Server" address (`host:port` of the [server](../server/) -- **not** your
|
||||
Immich server; see below for the `https://` form), and an optional
|
||||
"Access Token" (see below -- usually blank). Saving hands your browser
|
||||
Immich server; see below for the `https://` form). Saving hands your browser
|
||||
off to the server's claim page (after ~7 seconds, giving your phone
|
||||
time to rejoin its normal WiFi while the device reboots) so the frame
|
||||
gets linked to your account; the device meanwhile connects to your home
|
||||
@@ -183,19 +211,6 @@ certificate was actually issued for -- a bare LAN IP address
|
||||
(`https://192.168.1.50`) will fail the handshake even against a
|
||||
perfectly valid cert for a different name.
|
||||
|
||||
## Access token
|
||||
|
||||
Usually blank. Current servers issue each frame its own private token
|
||||
automatically on first contact (delivered via `GET /frame/config`,
|
||||
persisted in NVS, preferred by `build_url()` from then on -- and baked
|
||||
into the manage-menu/share QR codes so scanning them just works). The
|
||||
captive portal's "Access Token" field only matters when pointing this
|
||||
firmware at an *older* (pre-multi-frame) server whose `MANAGEMENT_TOKEN`
|
||||
is set: paste that shared value and the device sends it (`?token=...`)
|
||||
until a newer server replaces it with a per-frame one. Re-provisioning
|
||||
clears any stored per-frame token -- a fresh identity handshake with
|
||||
whatever server you point it at next.
|
||||
|
||||
## Skipping to the next photo
|
||||
|
||||
Wire a momentary push button between GPIO2 and GND (internal pull-up,
|
||||
@@ -204,6 +219,8 @@ device (if asleep) and tells the server to advance to the next photo
|
||||
right away, regardless of the configured refresh interval -- no long hold
|
||||
needed, since advancing is easily reversible by pressing again. See
|
||||
`FRAME_NEXT_BUTTON_GPIO` above to change the pin or disable the feature.
|
||||
Holding it past `FRAME_HOLD_ACTION_MS` instead means something else
|
||||
entirely -- see "Holding NEXT/BACK for a global action" above.
|
||||
|
||||
Normal wakes and reboots never advance the photo on their own -- the
|
||||
server decides when to advance based on its own clock (see
|
||||
@@ -223,7 +240,8 @@ disable the feature.
|
||||
|
||||
If there's nothing to go back to yet (freshly provisioned, or you've
|
||||
already gone back as far as there is history), it's a no-op -- the
|
||||
current photo stays exactly as it was, no flash on the panel.
|
||||
current photo stays exactly as it was, no flash on the panel. Same
|
||||
long-hold caveat as the next-photo button above.
|
||||
|
||||
## Battery (XIAO ESP32-C6)
|
||||
|
||||
@@ -262,9 +280,13 @@ One more button, wired between GPIO1 and GND (same wiring style as the
|
||||
other buttons), covers three actions -- disambiguated purely by how
|
||||
long it's held:
|
||||
|
||||
**A quick press** wakes the device and overlays several corners of
|
||||
whatever photo is currently showing, leaving the middle of the photo
|
||||
visible and unchanged:
|
||||
**A quick press** soft-resets the device -- `esp_restart()`, keeping the
|
||||
stored WiFi/server config. Useful for recovering a hung device without
|
||||
losing setup.
|
||||
|
||||
**Holding it ~3 seconds, then releasing** wakes the device (if asleep)
|
||||
and overlays several corners of whatever photo is currently showing,
|
||||
leaving the middle of the photo visible and unchanged:
|
||||
|
||||
- **Top-right**: a QR code -- "SCAN TO MANAGE" -- linking to the
|
||||
server's config page.
|
||||
@@ -283,8 +305,9 @@ for faces Immich hasn't been told a name for; no face detection happens
|
||||
on the device or the server, this is entirely Immich's own People
|
||||
feature). A third press exits immediately rather than waiting out the
|
||||
30-second timer. Holding the button during this stage doesn't trigger
|
||||
either reset tier below -- the hold-duration read only ever happens
|
||||
once, right when the device first wakes, before any menu is shown.
|
||||
the factory-reset tier below -- the hold-duration read only ever
|
||||
happens once, right when the device first wakes, before any menu is
|
||||
shown.
|
||||
|
||||
The device stays awake for the whole menu interaction (up to three
|
||||
physical refreshes: the base overlay, the escalated one, and
|
||||
@@ -292,17 +315,13 @@ reverting), so this costs meaningfully more power than a normal wake --
|
||||
expected for a deliberate, occasional action, same tradeoff as the
|
||||
other buttons.
|
||||
|
||||
**Holding it ~3 seconds, then releasing** soft-resets the device --
|
||||
`esp_restart()`, keeping the stored WiFi/server config. Useful for
|
||||
recovering a hung device without losing setup.
|
||||
|
||||
**Holding it ~15 seconds** (whether or not you're still holding it --
|
||||
this fires immediately, it doesn't wait for release) clears the stored
|
||||
WiFi/server config and restarts into provisioning. From either power-on
|
||||
or while the device is deep-asleep, since this GPIO is armed as a
|
||||
wakeup source.
|
||||
|
||||
See `FRAME_COMBO_BUTTON_GPIO`, `FRAME_COMBO_SOFT_RESET_HOLD_MS`, and
|
||||
See `FRAME_COMBO_BUTTON_GPIO`, `FRAME_COMBO_MENU_HOLD_MS`, and
|
||||
`FRAME_COMBO_FACTORY_RESET_HOLD_MS` above to change the pin or hold
|
||||
durations, or disable all three actions.
|
||||
|
||||
|
||||
@@ -154,13 +154,12 @@ menu "ESPresso Frame Configuration"
|
||||
Button wired between this GPIO and GND (active-low, internal
|
||||
pull-up enabled in firmware -- no external resistor needed).
|
||||
One pin, three actions depending on how long it's held:
|
||||
a quick press shows the management menu (same as before);
|
||||
holding it FRAME_COMBO_SOFT_RESET_HOLD_MS then releasing
|
||||
soft-resets the device (reboots, keeps the stored WiFi/
|
||||
server config); holding it all the way to
|
||||
FRAME_COMBO_FACTORY_RESET_HOLD_MS clears the stored config
|
||||
and restarts into provisioning, regardless of whether it's
|
||||
released yet. Must be GPIO 0-7 for the same deep-sleep-
|
||||
a quick press soft-resets the device (reboots, keeps the
|
||||
stored WiFi/server config); holding it FRAME_COMBO_MENU_HOLD_MS
|
||||
then releasing shows the management menu; holding it all the
|
||||
way to FRAME_COMBO_FACTORY_RESET_HOLD_MS clears the stored
|
||||
config and restarts into provisioning, regardless of whether
|
||||
it's released yet. Must be GPIO 0-7 for the same deep-sleep-
|
||||
wakeup reason as FRAME_NEXT_BUTTON_GPIO above; defaults to
|
||||
a different pin than the other buttons. Set to -1 to
|
||||
disable the feature entirely (also disables the management
|
||||
@@ -168,14 +167,14 @@ menu "ESPresso Frame Configuration"
|
||||
reconfiguring then only works by erasing NVS over USB, see
|
||||
firmware/README.md).
|
||||
|
||||
config FRAME_COMBO_SOFT_RESET_HOLD_MS
|
||||
int "Soft-reset hold duration (ms)"
|
||||
config FRAME_COMBO_MENU_HOLD_MS
|
||||
int "Management-menu hold duration (ms)"
|
||||
default 3000
|
||||
depends on FRAME_COMBO_BUTTON_GPIO >= 0
|
||||
help
|
||||
How long the menu/reset button must be held before releasing
|
||||
it triggers a soft reset (reboot, config kept). Long enough
|
||||
to be clearly distinct from a quick menu-opening press.
|
||||
it shows the management menu instead of soft-resetting. Long
|
||||
enough to be clearly distinct from a quick reset tap.
|
||||
|
||||
config FRAME_COMBO_FACTORY_RESET_HOLD_MS
|
||||
int "Factory-reset hold duration (ms)"
|
||||
@@ -185,8 +184,25 @@ menu "ESPresso Frame Configuration"
|
||||
How long the menu/reset button must be held continuously
|
||||
before the device clears its stored config and reboots into
|
||||
provisioning, regardless of release. Comfortably longer than
|
||||
FRAME_COMBO_SOFT_RESET_HOLD_MS so the two tiers can't be
|
||||
confused for each other.
|
||||
FRAME_COMBO_MENU_HOLD_MS so the two tiers can't be confused
|
||||
for each other.
|
||||
|
||||
config FRAME_HOLD_ACTION_MS
|
||||
int "Next/back hold-for-global-action duration (ms)"
|
||||
default 3000
|
||||
range 3000 10000
|
||||
help
|
||||
How long the NEXT or BACK button must be held before it
|
||||
triggers a frame-wide action (see server/app/global_actions.py
|
||||
-- e.g. cycling saved layouts) instead of that button's normal
|
||||
short-press behavior. Only a first-boot/never-connected
|
||||
fallback: once the device has fetched GET /frame/config at
|
||||
least once, the server's own Frame.hold_duration_ms (set on
|
||||
the Configuration tab) overrides this on every later boot --
|
||||
see wifi_provisioning.h's frame_config_get_hold_duration_ms.
|
||||
Floor matches the server's own minimum, so a long-held button
|
||||
never means something different depending on which value
|
||||
happened to apply.
|
||||
|
||||
config FRAME_BATTERY_ADC_GPIO
|
||||
int "Battery voltage-divider ADC GPIO (-1 to disable)"
|
||||
|
||||
+40
-18
@@ -1,3 +1,5 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_sleep.h"
|
||||
@@ -5,6 +7,8 @@
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include "wifi_provisioning.h"
|
||||
|
||||
#include "back_button.h"
|
||||
|
||||
static const char *TAG = "back_button";
|
||||
@@ -14,6 +18,7 @@ static const char *TAG = "back_button";
|
||||
#define BACK_BUTTON_GPIO ((gpio_num_t)CONFIG_FRAME_BACK_BUTTON_GPIO)
|
||||
#define BACK_BUTTON_DEBOUNCE_MS 20
|
||||
#define BACK_BUTTON_DEBOUNCE_CHECKS 3
|
||||
#define BACK_BUTTON_POLL_MS 100
|
||||
|
||||
void back_button_init(void)
|
||||
{
|
||||
@@ -36,7 +41,7 @@ void back_button_init(void)
|
||||
esp_sleep_enable_gpio_wakeup_on_hp_periph_powerdown(1ULL << BACK_BUTTON_GPIO, ESP_GPIO_WAKEUP_GPIO_LOW);
|
||||
}
|
||||
|
||||
bool back_button_check(void)
|
||||
back_button_result_t back_button_check(void)
|
||||
{
|
||||
/* A quick tap can easily release before this runs (~0.4-0.5s into
|
||||
* boot, confirmed on hardware -- a live gpio_get_level() check here
|
||||
@@ -44,32 +49,49 @@ bool back_button_check(void)
|
||||
* status register is latched at the moment of waking and isn't
|
||||
* cleared until the next sleep entry, so it reliably reflects a tap
|
||||
* regardless of how quickly it was released. */
|
||||
if (esp_sleep_get_gpio_wakeup_status() & (1ULL << BACK_BUTTON_GPIO)) {
|
||||
ESP_LOGI(TAG, "Back-photo button caused this wake, going back");
|
||||
return true;
|
||||
}
|
||||
bool caused_wake = esp_sleep_get_gpio_wakeup_status() & (1ULL << BACK_BUTTON_GPIO);
|
||||
|
||||
/* Not a GPIO-wakeup-from-this-pin boot (normal timer wake, or a fresh
|
||||
* power-on/reflash) -- fall back to a live, debounced level check so
|
||||
* holding the button down while powering on also works. */
|
||||
if (gpio_get_level(BACK_BUTTON_GPIO) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < BACK_BUTTON_DEBOUNCE_CHECKS; i++) {
|
||||
vTaskDelay(pdMS_TO_TICKS(BACK_BUTTON_DEBOUNCE_MS));
|
||||
if (!caused_wake) {
|
||||
/* Not a GPIO-wakeup-from-this-pin boot (normal timer wake, or a
|
||||
* fresh power-on/reflash) -- fall back to a live, debounced level
|
||||
* check so holding the button down while powering on also
|
||||
* works. */
|
||||
if (gpio_get_level(BACK_BUTTON_GPIO) != 0) {
|
||||
return false; /* noise, not a real press */
|
||||
return BACK_BUTTON_NOT_PRESSED;
|
||||
}
|
||||
for (int i = 0; i < BACK_BUTTON_DEBOUNCE_CHECKS; i++) {
|
||||
vTaskDelay(pdMS_TO_TICKS(BACK_BUTTON_DEBOUNCE_MS));
|
||||
if (gpio_get_level(BACK_BUTTON_GPIO) != 0) {
|
||||
return BACK_BUTTON_NOT_PRESSED; /* noise, not a real press */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Back-photo button held during power-on, going back");
|
||||
return true;
|
||||
/* Confirmed pressed -- measure how long, same reasoning/pattern as
|
||||
* next_button_check(). */
|
||||
uint32_t hold_threshold_ms;
|
||||
if (frame_config_get_hold_duration_ms(&hold_threshold_ms) != ESP_OK) {
|
||||
hold_threshold_ms = CONFIG_FRAME_HOLD_ACTION_MS;
|
||||
}
|
||||
|
||||
uint32_t elapsed_ms = 0;
|
||||
while (gpio_get_level(BACK_BUTTON_GPIO) == 0) {
|
||||
if (elapsed_ms >= hold_threshold_ms) {
|
||||
ESP_LOGI(TAG, "Back button held past %ums, triggering global hold action",
|
||||
(unsigned)hold_threshold_ms);
|
||||
return BACK_BUTTON_HOLD;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(BACK_BUTTON_POLL_MS));
|
||||
elapsed_ms += BACK_BUTTON_POLL_MS;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Back-photo button short press (%ums), going back", (unsigned)elapsed_ms);
|
||||
return BACK_BUTTON_SHORT_PRESS;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
void back_button_init(void) {}
|
||||
bool back_button_check(void) { return false; }
|
||||
back_button_result_t back_button_check(void) { return BACK_BUTTON_NOT_PRESSED; }
|
||||
|
||||
#endif
|
||||
|
||||
@@ -12,9 +12,23 @@
|
||||
*/
|
||||
void back_button_init(void);
|
||||
|
||||
typedef enum {
|
||||
BACK_BUTTON_NOT_PRESSED,
|
||||
/** A short press -- same immediate-response reasoning as the
|
||||
* next-photo button. */
|
||||
BACK_BUTTON_SHORT_PRESS,
|
||||
/** Held past the configured hold duration (see
|
||||
* wifi_provisioning.h's frame_config_get_hold_duration_ms) --
|
||||
* triggers a frame-wide action instead (see
|
||||
* server/app/global_actions.py, frame_client.h's FETCH_GLOBAL_BACK).
|
||||
* Fires immediately at the threshold, without waiting for release. */
|
||||
BACK_BUTTON_HOLD,
|
||||
} back_button_result_t;
|
||||
|
||||
/**
|
||||
* Returns whether the back-photo button is currently held, debounced with
|
||||
* a couple of short re-checks to reject noise. Same immediate-response
|
||||
* reasoning as the next-photo button -- no long hold-to-confirm gate.
|
||||
* Checks the back-photo button and, if it's pressed at all, blocks
|
||||
* polling its level until either it's released (BACK_BUTTON_SHORT_PRESS)
|
||||
* or the hold duration elapses (BACK_BUTTON_HOLD) -- same pattern as
|
||||
* next_button_check(). Evaluated once per wake.
|
||||
*/
|
||||
bool back_button_check(void);
|
||||
back_button_result_t back_button_check(void);
|
||||
|
||||
@@ -53,8 +53,8 @@ bool combo_button_check(void)
|
||||
return false; /* not pressed, and didn't cause this wake either */
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Combo button held -- quick press for menu, %dms for soft reset, %dms for factory reset",
|
||||
CONFIG_FRAME_COMBO_SOFT_RESET_HOLD_MS, CONFIG_FRAME_COMBO_FACTORY_RESET_HOLD_MS);
|
||||
ESP_LOGI(TAG, "Combo button held -- quick press for soft reset, %dms for menu, %dms for factory reset",
|
||||
CONFIG_FRAME_COMBO_MENU_HOLD_MS, CONFIG_FRAME_COMBO_FACTORY_RESET_HOLD_MS);
|
||||
|
||||
int elapsed_ms = 0;
|
||||
while (gpio_get_level(COMBO_BUTTON_GPIO) == 0) {
|
||||
@@ -70,13 +70,13 @@ bool combo_button_check(void)
|
||||
}
|
||||
}
|
||||
|
||||
if (elapsed_ms >= CONFIG_FRAME_COMBO_SOFT_RESET_HOLD_MS) {
|
||||
ESP_LOGW(TAG, "Held %dms and released, soft-restarting (config kept)", elapsed_ms);
|
||||
esp_restart();
|
||||
if (elapsed_ms >= CONFIG_FRAME_COMBO_MENU_HOLD_MS) {
|
||||
ESP_LOGI(TAG, "Held %dms and released, showing management menu", elapsed_ms);
|
||||
return true;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Quick press (%dms), showing management menu", elapsed_ms);
|
||||
return true;
|
||||
ESP_LOGW(TAG, "Quick press (%dms), soft-restarting (config kept)", elapsed_ms);
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
bool combo_button_is_pressed(void)
|
||||
|
||||
@@ -16,11 +16,11 @@ void combo_button_init(void);
|
||||
* Checks the combined menu/reset button and acts on how long it was
|
||||
* held, evaluated once per wake:
|
||||
* - Not pressed: returns false immediately.
|
||||
* - Released before CONFIG_FRAME_COMBO_SOFT_RESET_HOLD_MS (a quick
|
||||
* press): returns true -- caller should show the management menu.
|
||||
* - Released between the soft-reset and factory-reset thresholds: a
|
||||
* soft reset (esp_restart(), stored WiFi/server config kept) --
|
||||
* - Released before CONFIG_FRAME_COMBO_MENU_HOLD_MS (a quick press):
|
||||
* a soft reset (esp_restart(), stored WiFi/server config kept) --
|
||||
* never returns.
|
||||
* - Released between the menu and factory-reset thresholds: returns
|
||||
* true -- caller should show the management menu.
|
||||
* - Held through CONFIG_FRAME_COMBO_FACTORY_RESET_HOLD_MS: a factory
|
||||
* reset (frame_config_clear() + esp_restart(), fires immediately
|
||||
* without waiting for release) -- never returns.
|
||||
|
||||
@@ -95,18 +95,15 @@ static void save_wifi_cache(esp_netif_t *netif)
|
||||
}
|
||||
|
||||
/* Builds a full URL from cfg->toolsserver + a path (no leading slash),
|
||||
* appending cfg->access_token as ?token= if one's set. toolsserver is
|
||||
* normally a bare "host:port", defaulting to plain http; it may instead
|
||||
* carry an explicit "http://" or "https://" prefix to pick the scheme,
|
||||
* e.g. "https://frame.example.com" if a reverse proxy is terminating
|
||||
* TLS in front of the tools server. Every URL carries ?id= (the device's
|
||||
* MAC-derived identity -- how a multi-frame server tells frames apart
|
||||
* and how an unknown frame self-registers) plus &token=: the server-
|
||||
* issued per-frame device token once one has been delivered via
|
||||
* /frame/config, else the provisioned access token (the legacy shared
|
||||
* secret, also what a pre-multi-frame server still expects). This is
|
||||
* the one chokepoint all requests go through, so every caller gets both
|
||||
* for free instead of needing to remember to add them. */
|
||||
* appending cfg->device_token as &token= once one's been delivered.
|
||||
* toolsserver is normally a bare "host:port", defaulting to plain http;
|
||||
* it may instead carry an explicit "http://" or "https://" prefix to
|
||||
* pick the scheme, e.g. "https://frame.example.com" if a reverse proxy
|
||||
* is terminating TLS in front of the tools server. Every URL carries
|
||||
* ?id= (the device's MAC-derived identity -- how a multi-frame server
|
||||
* tells frames apart and how an unknown frame self-registers) plus
|
||||
* &token=. This is the one chokepoint all requests go through, so every
|
||||
* caller gets both for free instead of needing to remember to add them. */
|
||||
static void build_url(char *out, size_t out_size, const frame_config_t *cfg, const char *path)
|
||||
{
|
||||
const char *toolsserver = cfg->toolsserver;
|
||||
@@ -123,9 +120,8 @@ static void build_url(char *out, size_t out_size, const frame_config_t *cfg, con
|
||||
len += (size_t)snprintf(out + len, out_size - len, "?id=%s", device_id);
|
||||
}
|
||||
|
||||
const char *token = cfg->device_token[0] != '\0' ? cfg->device_token : cfg->access_token;
|
||||
if (token[0] != '\0' && len < out_size) {
|
||||
snprintf(out + len, out_size - len, "&token=%s", token);
|
||||
if (cfg->device_token[0] != '\0' && len < out_size) {
|
||||
snprintf(out + len, out_size - len, "&token=%s", cfg->device_token);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +272,14 @@ esp_err_t frame_wifi_connect_sta(const frame_config_t *cfg)
|
||||
typedef struct {
|
||||
bool reachable;
|
||||
uint32_t refresh_interval_s; /* CONFIG_FRAME_SLEEP_INTERVAL_S if absent/unparseable */
|
||||
/* How long NEXT/BACK must be held to trigger a global action instead
|
||||
* of a short press (see next_button.h/back_button.h) --
|
||||
* CONFIG_FRAME_HOLD_ACTION_MS if absent/unparseable (older server) or
|
||||
* unreachable. Persisted via frame_config_set_hold_duration_ms() for
|
||||
* the *next* boot's button-hold decision -- this fetch happens too
|
||||
* late in the cycle for its own boot's decision, see that function's
|
||||
* own doc comment. */
|
||||
uint32_t hold_duration_ms;
|
||||
char firmware_version[32]; /* server's uploaded OTA image version; empty if none/unreachable */
|
||||
/* Per-frame token the server pushes until this device has
|
||||
* authenticated with it once; empty when absent. Persisted via
|
||||
@@ -370,6 +374,7 @@ static frame_server_config_t fetch_frame_config(const frame_config_t *cfg)
|
||||
frame_server_config_t result = {
|
||||
.reachable = false,
|
||||
.refresh_interval_s = CONFIG_FRAME_SLEEP_INTERVAL_S,
|
||||
.hold_duration_ms = CONFIG_FRAME_HOLD_ACTION_MS,
|
||||
};
|
||||
result.firmware_version[0] = '\0';
|
||||
result.device_token[0] = '\0';
|
||||
@@ -419,6 +424,10 @@ static frame_server_config_t fetch_frame_config(const frame_config_t *cfg)
|
||||
ESP_LOGW(TAG, "'%s' response missing refresh_interval_s, using fallback %ds", url,
|
||||
(int)result.refresh_interval_s);
|
||||
}
|
||||
uint32_t hold_ms;
|
||||
if (json_extract_uint(body, "hold_duration_ms", &hold_ms)) {
|
||||
result.hold_duration_ms = hold_ms;
|
||||
}
|
||||
json_extract_string(body, "firmware_version", result.firmware_version, sizeof(result.firmware_version));
|
||||
json_extract_string(body, "device_token", result.device_token, sizeof(result.device_token));
|
||||
|
||||
@@ -443,12 +452,13 @@ static size_t http_read_fn(uint8_t *chunk, size_t chunk_size, void *ctx_)
|
||||
return n > 0 ? (size_t)n : 0;
|
||||
}
|
||||
|
||||
/* GETs /frame/image (FETCH_NORMAL), or POSTs /frame/advance or
|
||||
* /frame/back to force a move in either direction (FETCH_ADVANCE /
|
||||
* FETCH_BACK -- the next-photo / back-photo buttons). manage=true (the
|
||||
* manage button) appends &manage=1, telling the server to bake its
|
||||
* overlay into this same response instead of returning the bare
|
||||
* content -- see server/app/routers/device.py. Returning non-ESP_OK
|
||||
/* GETs /frame/image (FETCH_NORMAL), or POSTs /frame/advance, /frame/back,
|
||||
* /frame/global-next, or /frame/global-back to force a move/action
|
||||
* (FETCH_ADVANCE / FETCH_BACK -- a short press; FETCH_GLOBAL_NEXT /
|
||||
* FETCH_GLOBAL_BACK -- a held press, see next_button.h/back_button.h).
|
||||
* manage=true (the manage button) appends &manage=1, telling the server
|
||||
* to bake its overlay into this same response instead of returning the
|
||||
* bare content -- see server/app/routers/device.py. Returning non-ESP_OK
|
||||
* means the panel was never actually refreshed -- epd_display_stream()
|
||||
* (see epd7in3e.c) refuses to trigger a physical refresh on a short/
|
||||
* wrong-size stream, so a failure here always leaves the visible screen
|
||||
@@ -460,6 +470,10 @@ static esp_err_t fetch_and_display(const frame_config_t *cfg, fetch_action_t act
|
||||
path = "frame/advance";
|
||||
} else if (action == FETCH_BACK) {
|
||||
path = "frame/back";
|
||||
} else if (action == FETCH_GLOBAL_NEXT) {
|
||||
path = "frame/global-next";
|
||||
} else if (action == FETCH_GLOBAL_BACK) {
|
||||
path = "frame/global-back";
|
||||
}
|
||||
|
||||
char url[256];
|
||||
@@ -720,6 +734,11 @@ void frame_client_run(const frame_config_t *cfg, fetch_action_t action, bool sho
|
||||
report_battery(cfg, battery_percent);
|
||||
frame_server_config_t server_cfg = fetch_frame_config(cfg);
|
||||
sleep_seconds = server_cfg.reachable ? server_cfg.refresh_interval_s : CONFIG_FRAME_RETRY_INTERVAL_S;
|
||||
if (server_cfg.reachable) {
|
||||
/* For next boot's button-hold decision, not this one -- see
|
||||
* frame_config_get_hold_duration_ms()'s own doc comment. */
|
||||
frame_config_set_hold_duration_ms(server_cfg.hold_duration_ms);
|
||||
}
|
||||
|
||||
/* One-time identity handshake: the server pushes this frame's
|
||||
* own token until we've authenticated with it once. Persist it
|
||||
|
||||
@@ -9,14 +9,19 @@
|
||||
* Which photo-fetch behavior this wake cycle should use -- normally the
|
||||
* idempotent GET /frame/image (the server decides on its own whether to
|
||||
* advance, based on its configured refresh interval, so a plain
|
||||
* wake/reboot never skips a photo just by asking), or POST
|
||||
* /frame/advance / POST /frame/back to force a move in either direction
|
||||
* (the next-photo / back-photo buttons).
|
||||
* wake/reboot never skips a photo just by asking), POST /frame/advance /
|
||||
* POST /frame/back to force a move in either direction (a short press of
|
||||
* the next-photo / back-photo buttons), or POST /frame/global-next /
|
||||
* POST /frame/global-back to run whatever frame-wide action (if any) is
|
||||
* configured for a held press (see next_button.h/back_button.h's
|
||||
* *_HOLD result and app/global_actions.py server-side).
|
||||
*/
|
||||
typedef enum {
|
||||
FETCH_NORMAL,
|
||||
FETCH_ADVANCE,
|
||||
FETCH_BACK,
|
||||
FETCH_GLOBAL_NEXT,
|
||||
FETCH_GLOBAL_BACK,
|
||||
} fetch_action_t;
|
||||
|
||||
/**
|
||||
|
||||
+13
-4
@@ -40,12 +40,21 @@ void app_main(void)
|
||||
back_button_init();
|
||||
combo_button_init();
|
||||
|
||||
bool next_pressed = next_button_check();
|
||||
bool back_pressed = back_button_check();
|
||||
next_button_result_t next_result = next_button_check();
|
||||
back_button_result_t back_result = back_button_check();
|
||||
/* Next takes priority over back if somehow both read pressed at once
|
||||
* (e.g. both held through a power-on) -- an arbitrary but
|
||||
* deterministic tie-break, not expected to matter in practice. */
|
||||
fetch_action_t action = next_pressed ? FETCH_ADVANCE : back_pressed ? FETCH_BACK : FETCH_NORMAL;
|
||||
* deterministic tie-break, not expected to matter in practice. Same
|
||||
* priority applies whether the winning button resolved to a short
|
||||
* press or a hold. */
|
||||
fetch_action_t action;
|
||||
if (next_result != NEXT_BUTTON_NOT_PRESSED) {
|
||||
action = (next_result == NEXT_BUTTON_HOLD) ? FETCH_GLOBAL_NEXT : FETCH_ADVANCE;
|
||||
} else if (back_result != BACK_BUTTON_NOT_PRESSED) {
|
||||
action = (back_result == BACK_BUTTON_HOLD) ? FETCH_GLOBAL_BACK : FETCH_BACK;
|
||||
} else {
|
||||
action = FETCH_NORMAL;
|
||||
}
|
||||
/* Soft-resets or clears config + restarts internally for a medium/
|
||||
* long hold and never returns in those cases -- only returns here
|
||||
* for "not pressed" (false) or "quick press" (true, show the menu). */
|
||||
|
||||
+45
-18
@@ -1,3 +1,5 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_sleep.h"
|
||||
@@ -5,6 +7,8 @@
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include "wifi_provisioning.h"
|
||||
|
||||
#include "next_button.h"
|
||||
|
||||
static const char *TAG = "next_button";
|
||||
@@ -14,6 +18,7 @@ static const char *TAG = "next_button";
|
||||
#define NEXT_BUTTON_GPIO ((gpio_num_t)CONFIG_FRAME_NEXT_BUTTON_GPIO)
|
||||
#define NEXT_BUTTON_DEBOUNCE_MS 20
|
||||
#define NEXT_BUTTON_DEBOUNCE_CHECKS 3
|
||||
#define NEXT_BUTTON_POLL_MS 100
|
||||
|
||||
void next_button_init(void)
|
||||
{
|
||||
@@ -40,7 +45,7 @@ void next_button_init(void)
|
||||
esp_sleep_enable_gpio_wakeup_on_hp_periph_powerdown(1ULL << NEXT_BUTTON_GPIO, ESP_GPIO_WAKEUP_GPIO_LOW);
|
||||
}
|
||||
|
||||
bool next_button_check(void)
|
||||
next_button_result_t next_button_check(void)
|
||||
{
|
||||
/* A quick tap can easily release before this runs (~0.4-0.5s into
|
||||
* boot, confirmed on hardware -- a live gpio_get_level() check here
|
||||
@@ -48,32 +53,54 @@ bool next_button_check(void)
|
||||
* status register is latched at the moment of waking and isn't
|
||||
* cleared until the next sleep entry, so it reliably reflects a tap
|
||||
* regardless of how quickly it was released. */
|
||||
if (esp_sleep_get_gpio_wakeup_status() & (1ULL << NEXT_BUTTON_GPIO)) {
|
||||
ESP_LOGI(TAG, "Next-photo button caused this wake, forcing advance");
|
||||
return true;
|
||||
}
|
||||
bool caused_wake = esp_sleep_get_gpio_wakeup_status() & (1ULL << NEXT_BUTTON_GPIO);
|
||||
|
||||
/* Not a GPIO-wakeup-from-this-pin boot (normal timer wake, or a fresh
|
||||
* power-on/reflash) -- fall back to a live, debounced level check so
|
||||
* holding the button down while powering on also works. */
|
||||
if (gpio_get_level(NEXT_BUTTON_GPIO) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < NEXT_BUTTON_DEBOUNCE_CHECKS; i++) {
|
||||
vTaskDelay(pdMS_TO_TICKS(NEXT_BUTTON_DEBOUNCE_MS));
|
||||
if (!caused_wake) {
|
||||
/* Not a GPIO-wakeup-from-this-pin boot (normal timer wake, or a
|
||||
* fresh power-on/reflash) -- fall back to a live, debounced level
|
||||
* check so holding the button down while powering on also
|
||||
* works. */
|
||||
if (gpio_get_level(NEXT_BUTTON_GPIO) != 0) {
|
||||
return false; /* noise, not a real press */
|
||||
return NEXT_BUTTON_NOT_PRESSED;
|
||||
}
|
||||
for (int i = 0; i < NEXT_BUTTON_DEBOUNCE_CHECKS; i++) {
|
||||
vTaskDelay(pdMS_TO_TICKS(NEXT_BUTTON_DEBOUNCE_MS));
|
||||
if (gpio_get_level(NEXT_BUTTON_GPIO) != 0) {
|
||||
return NEXT_BUTTON_NOT_PRESSED; /* noise, not a real press */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Next-photo button held during power-on, forcing advance");
|
||||
return true;
|
||||
/* Confirmed pressed (either the wake cause, or debounced during
|
||||
* power-on) -- measure how long, same polling pattern as
|
||||
* combo_button.c's own hold-tier detection. Reads the last hold
|
||||
* duration the server reported (persisted from a previous cycle,
|
||||
* see frame_config_get_hold_duration_ms's own doc comment), falling
|
||||
* back to the Kconfig default before the device has ever fetched
|
||||
* one. */
|
||||
uint32_t hold_threshold_ms;
|
||||
if (frame_config_get_hold_duration_ms(&hold_threshold_ms) != ESP_OK) {
|
||||
hold_threshold_ms = CONFIG_FRAME_HOLD_ACTION_MS;
|
||||
}
|
||||
|
||||
uint32_t elapsed_ms = 0;
|
||||
while (gpio_get_level(NEXT_BUTTON_GPIO) == 0) {
|
||||
if (elapsed_ms >= hold_threshold_ms) {
|
||||
ESP_LOGI(TAG, "Next button held past %ums, triggering global hold action",
|
||||
(unsigned)hold_threshold_ms);
|
||||
return NEXT_BUTTON_HOLD;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(NEXT_BUTTON_POLL_MS));
|
||||
elapsed_ms += NEXT_BUTTON_POLL_MS;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Next-photo button short press (%ums), forcing advance", (unsigned)elapsed_ms);
|
||||
return NEXT_BUTTON_SHORT_PRESS;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
void next_button_init(void) {}
|
||||
bool next_button_check(void) { return false; }
|
||||
next_button_result_t next_button_check(void) { return NEXT_BUTTON_NOT_PRESSED; }
|
||||
|
||||
#endif
|
||||
|
||||
@@ -12,10 +12,27 @@
|
||||
*/
|
||||
void next_button_init(void);
|
||||
|
||||
typedef enum {
|
||||
NEXT_BUTTON_NOT_PRESSED,
|
||||
/** A short press -- advancing a photo is low-stakes and should feel
|
||||
* immediate, so this fires the moment the button releases (or right
|
||||
* away for a wake-triggered press, once it's confirmed not a hold). */
|
||||
NEXT_BUTTON_SHORT_PRESS,
|
||||
/** Held past the configured hold duration (see
|
||||
* wifi_provisioning.h's frame_config_get_hold_duration_ms) --
|
||||
* triggers a frame-wide action instead (see
|
||||
* server/app/global_actions.py, frame_client.h's FETCH_GLOBAL_NEXT).
|
||||
* Fires immediately at the threshold, without waiting for release --
|
||||
* same convention as combo_button.c's factory-reset tier. */
|
||||
NEXT_BUTTON_HOLD,
|
||||
} next_button_result_t;
|
||||
|
||||
/**
|
||||
* Returns whether the next-photo button is currently held, debounced with
|
||||
* a couple of short re-checks to reject noise. No long hold-to-confirm
|
||||
* gate -- advancing a photo is low-stakes and should feel immediate, so
|
||||
* this returns right away either way.
|
||||
* Checks the next-photo button and, if it's pressed at all (either what
|
||||
* caused this wake, per the latched wakeup-status register, or held
|
||||
* through a debounced power-on check), blocks polling its level until
|
||||
* either it's released (NEXT_BUTTON_SHORT_PRESS) or the hold duration
|
||||
* elapses (NEXT_BUTTON_HOLD, returned immediately, not waiting for
|
||||
* release). Evaluated once per wake.
|
||||
*/
|
||||
bool next_button_check(void);
|
||||
next_button_result_t next_button_check(void);
|
||||
|
||||
@@ -36,9 +36,8 @@ static void build_ota_url(char *out, size_t out_size, const frame_config_t *cfg)
|
||||
len += (size_t)snprintf(out + len, out_size - len, "?id=%s", device_id);
|
||||
}
|
||||
|
||||
const char *token = cfg->device_token[0] != '\0' ? cfg->device_token : cfg->access_token;
|
||||
if (token[0] != '\0' && len < out_size) {
|
||||
snprintf(out + len, out_size - len, "&token=%s", token);
|
||||
if (cfg->device_token[0] != '\0' && len < out_size) {
|
||||
snprintf(out + len, out_size - len, "&token=%s", cfg->device_token);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,11 +97,6 @@
|
||||
<input type="text" id="toolsserver" name="toolsserver" placeholder="e.g. 192.168.1.50:8080 or https://frame.example.com" maxlength="128" required>
|
||||
</div>
|
||||
|
||||
<div class="input-group">
|
||||
<label for="access_token">Access Token (optional — only for older servers)</label>
|
||||
<input type="text" id="access_token" name="access_token" placeholder="usually blank; current servers issue one automatically" maxlength="64">
|
||||
</div>
|
||||
|
||||
<p style="font-size: 13px; color: #555;">After saving, this page will
|
||||
take you to the server to claim your frame — reconnect to
|
||||
your normal WiFi if it doesn't happen automatically.</p>
|
||||
|
||||
@@ -73,20 +73,10 @@ esp_err_t frame_config_load(frame_config_t *out)
|
||||
return pass_err;
|
||||
}
|
||||
|
||||
/* Also optional -- most deployments won't set a server-side
|
||||
* MANAGEMENT_TOKEN at all, in which case this stays empty and the
|
||||
* manage-menu QR just links to the page with no ?token=. */
|
||||
len = sizeof(out->access_token);
|
||||
esp_err_t token_err = nvs_get_str(handle, "access_token", out->access_token, &len);
|
||||
if (token_err != ESP_OK && token_err != ESP_ERR_NVS_NOT_FOUND) {
|
||||
nvs_close(handle);
|
||||
return token_err;
|
||||
}
|
||||
|
||||
/* Optional: absent until the server has pushed a per-frame token
|
||||
* (see frame_config_set_device_token). */
|
||||
len = sizeof(out->device_token);
|
||||
token_err = nvs_get_str(handle, "device_token", out->device_token, &len);
|
||||
esp_err_t token_err = nvs_get_str(handle, "device_token", out->device_token, &len);
|
||||
if (token_err != ESP_OK && token_err != ESP_ERR_NVS_NOT_FOUND) {
|
||||
nvs_close(handle);
|
||||
return token_err;
|
||||
@@ -131,9 +121,6 @@ esp_err_t frame_config_save(const frame_config_t *cfg)
|
||||
if (err == ESP_OK) {
|
||||
err = nvs_set_str(handle, "toolsserver", cfg->toolsserver);
|
||||
}
|
||||
if (err == ESP_OK) {
|
||||
err = nvs_set_str(handle, "access_token", cfg->access_token);
|
||||
}
|
||||
if (err == ESP_OK) {
|
||||
/* Re-provisioning restarts the identity handshake: the server
|
||||
* (possibly a different one now) re-issues a device token when
|
||||
@@ -191,7 +178,6 @@ void frame_config_clear(void)
|
||||
nvs_erase_key(handle, "sta_ssid");
|
||||
nvs_erase_key(handle, "sta_pass");
|
||||
nvs_erase_key(handle, "toolsserver");
|
||||
nvs_erase_key(handle, "access_token");
|
||||
nvs_erase_key(handle, "device_token");
|
||||
nvs_erase_key(handle, "connected_once");
|
||||
nvs_commit(handle);
|
||||
@@ -234,6 +220,29 @@ void frame_config_invalidate_last_display_crc32(void)
|
||||
nvs_close(handle);
|
||||
}
|
||||
|
||||
esp_err_t frame_config_get_hold_duration_ms(uint32_t *out)
|
||||
{
|
||||
nvs_handle_t handle;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &handle);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
err = nvs_get_u32(handle, "hold_ms", out);
|
||||
nvs_close(handle);
|
||||
return err;
|
||||
}
|
||||
|
||||
void frame_config_set_hold_duration_ms(uint32_t ms)
|
||||
{
|
||||
nvs_handle_t handle;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle) != ESP_OK) {
|
||||
return;
|
||||
}
|
||||
nvs_set_u32(handle, "hold_ms", ms);
|
||||
nvs_commit(handle);
|
||||
nvs_close(handle);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------
|
||||
* WiFi fast-connect cache
|
||||
* ---------------------------------------------------------------------- */
|
||||
@@ -429,7 +438,6 @@ static esp_err_t save_config_post_handler(httpd_req_t *req)
|
||||
extract_form_value(body, "ssid", cfg.sta_ssid, sizeof(cfg.sta_ssid));
|
||||
extract_form_value(body, "password", cfg.sta_password, sizeof(cfg.sta_password));
|
||||
extract_form_value(body, "toolsserver", cfg.toolsserver, sizeof(cfg.toolsserver));
|
||||
extract_form_value(body, "access_token", cfg.access_token, sizeof(cfg.access_token));
|
||||
|
||||
if (strlen(cfg.sta_ssid) == 0 || strlen(cfg.toolsserver) == 0) {
|
||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "SSID and Tools Server are required");
|
||||
@@ -443,8 +451,7 @@ static esp_err_t save_config_post_handler(httpd_req_t *req)
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Saved config: ssid='%s' toolsserver='%s' access_token=%s", cfg.sta_ssid, cfg.toolsserver,
|
||||
strlen(cfg.access_token) ? "set" : "none");
|
||||
ESP_LOGI(TAG, "Saved config: ssid='%s' toolsserver='%s'", cfg.sta_ssid, cfg.toolsserver);
|
||||
|
||||
/* The success page hands the browser off to the server's claim page,
|
||||
* carrying this device's id -- how a frame gets linked to a user
|
||||
|
||||
@@ -17,11 +17,10 @@ typedef struct {
|
||||
char sta_ssid[FRAME_CFG_SSID_MAX_LEN + 1];
|
||||
char sta_password[FRAME_CFG_PASSWORD_MAX_LEN + 1];
|
||||
char toolsserver[FRAME_CFG_SERVER_MAX_LEN + 1];
|
||||
char access_token[FRAME_CFG_TOKEN_MAX_LEN + 1]; /* optional; legacy shared MANAGEMENT_TOKEN */
|
||||
/* Per-frame token issued by the server via GET /frame/config after
|
||||
* this device first introduces itself by id -- preferred over
|
||||
* access_token once present (see frame_client.c's build_url). Not
|
||||
* set at the captive portal; empty until the server pushes one. */
|
||||
* this device first introduces itself by id (see frame_client.c's
|
||||
* build_url). Not set at the captive portal; empty until the server
|
||||
* pushes one. */
|
||||
char device_token[FRAME_CFG_TOKEN_MAX_LEN + 1];
|
||||
} frame_config_t;
|
||||
|
||||
@@ -94,6 +93,27 @@ void frame_config_set_last_display_crc32(uint32_t crc32);
|
||||
*/
|
||||
void frame_config_invalidate_last_display_crc32(void);
|
||||
|
||||
/**
|
||||
* Returns the hold_duration_ms the server most recently reported via GET
|
||||
* /frame/config (see frame_client.c's fetch_frame_config/frame_client_run)
|
||||
* -- how long NEXT/BACK must be held before next_button_check()/
|
||||
* back_button_check() treat it as a hold-for-global-action instead of a
|
||||
* short press. Returns ESP_ERR_NVS_NOT_FOUND if the device has never
|
||||
* fetched one yet (fresh install/factory reset); caller should fall back
|
||||
* to CONFIG_FRAME_HOLD_ACTION_MS in that case.
|
||||
*
|
||||
* Deliberately a *previous* cycle's value: this cycle's own button
|
||||
* decision happens in main.c before WiFi even connects, but
|
||||
* /frame/config isn't fetched until near the end of frame_client_run
|
||||
* (after the image fetch, for connection-warmth/timeout reasons -- see
|
||||
* its own comment) -- so there's no same-cycle fresh value to use yet.
|
||||
*/
|
||||
esp_err_t frame_config_get_hold_duration_ms(uint32_t *out);
|
||||
|
||||
/** Persists the hold duration reported by the server, for the *next*
|
||||
* boot's button-hold decision to use. */
|
||||
void frame_config_set_hold_duration_ms(uint32_t ms);
|
||||
|
||||
/**
|
||||
* Returns this device's provisioning AP identity: a fixed SSID (from
|
||||
* Kconfig) and a password that's generated once on first use and persisted
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.3.0
|
||||
1.4.2
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
__pycache__/
|
||||
**/__pycache__/
|
||||
.venv/
|
||||
*.egg-info/
|
||||
data/
|
||||
render-service/node_modules/
|
||||
.git/
|
||||
+106
-6
@@ -2,18 +2,118 @@ FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# tzdata: python:3.12-slim doesn't include it by default, so the zoneinfo
|
||||
# database backing the web UI's "Timezone" setting (used by "Quiet hours")
|
||||
# would have no named zones to resolve without this -- ZoneInfo() would
|
||||
# raise for anything other than "UTC".
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends tzdata \
|
||||
# tzdata/fonts/Node.js all from Debian's own repo in one layer -- no
|
||||
# external curl/gnupg dance needed (see below for why that changed).
|
||||
# tzdata: python:3.12-slim doesn't include it by default, so the
|
||||
# zoneinfo database backing the web UI's "Timezone" setting (used by
|
||||
# "Quiet hours") would have no named zones to resolve without this --
|
||||
# ZoneInfo() would raise for anything other than "UTC".
|
||||
# fontconfig/fonts-dejavu-core: whiteboard mode's render-service/ (own
|
||||
# README there) needs something to render whiteboard text with.
|
||||
#
|
||||
# Node.js: whiteboard frame mode's render-service/ runs as a second
|
||||
# process in this same container rather than a separate compose service
|
||||
# -- it's a lightweight, stateless, localhost-only sidecar with nothing
|
||||
# worth independently scaling or restarting. Used to be installed via
|
||||
# NodeSource's setup script (Debian's own nodejs package was too old for
|
||||
# jsdom's minimum back when this base image tracked Debian bookworm) --
|
||||
# switched to Debian's own `nodejs`/`npm` packages after NodeSource's
|
||||
# deb.nodesource.com started intermittently 403ing on both its setup_*.x
|
||||
# scripts *and* its GPG key (a live NodeSource-side S3/CDN issue,
|
||||
# confirmed 2026-07-27 by hitting deb.nodesource.com directly -- some
|
||||
# setup_NN.x paths 403, others 200, no consistent pattern, so no
|
||||
# NodeSource-hosted install path could be trusted not to silently break
|
||||
# again). This base image now tracks Debian trixie, whose own `nodejs`
|
||||
# package is 20.19.2 -- inside jsdom 29's stated engines range
|
||||
# (`^20.19.0 || ^22.13.0 || >=24.0.0`) and well above express/resvg-js's
|
||||
# much lower floors -- so there's no longer a version gap to route
|
||||
# around NodeSource for. One less external dependency, and no more
|
||||
# curl-piped-into-bash (that pattern is also what let the NodeSource
|
||||
# failure go undetected here in the first place: `curl -f ... | bash -`
|
||||
# on a 403 hands bash an empty, "successful" script instead of failing
|
||||
# the RUN outright).
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tzdata fontconfig fonts-dejavu-core nodejs npm \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# EXPERIMENTAL. System libs a headless Chromium needs (app/html_render.py, the weather widget's
|
||||
# opt-in "modern" render style), trimmed from Playwright's own full
|
||||
# `install-deps chromium` list to just what a headless (no Xvfb),
|
||||
# Latin-text-plus-emoji use case needs: dropped xvfb (only needed for a
|
||||
# *headed* browser) and the CJK/Cyrillic/Thai locale font packages
|
||||
# (fonts-ipafont-gothic, fonts-wqy-zenhei, fonts-tlwg-loma-otf,
|
||||
# xfonts-cyrillic, xfonts-scalable, fonts-freefont-ttf, fonts-unifont) --
|
||||
# fonts-noto-color-emoji is the one that actually matters here (real
|
||||
# color emoji in the weather icons, vs. WeasyPrint/Pango's monochrome
|
||||
# fallback glyphs in this feature's original spike).
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 libatspi2.0-0t64 \
|
||||
libcairo2 libcups2t64 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0t64 \
|
||||
libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 \
|
||||
libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 \
|
||||
fonts-noto-color-emoji libfontconfig1 libfreetype6 fonts-liberation \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
# Split across several layers rather than one `pip install -r
|
||||
# requirements.txt` -- same Cloudflare single-blob/layer payload-size
|
||||
# limit as render-service's npm installs below. The single combined
|
||||
# layer was measured at ~113MB unpacked, over the limit on its own.
|
||||
# Isolating the largest packages gets every layer's unpacked size well
|
||||
# clear of 100MB (sqlalchemy ~15MB, pillow ~19MB, pypdfium2 ~8MB, the
|
||||
# remaining `-r requirements.txt` layer ~71MB). Each package version here
|
||||
# still comes from requirements.txt (`pip install -r` for everything that
|
||||
# doesn't need its own layer skips these, since pip sees them already
|
||||
# satisfied); the explicit versions below just control *when* each
|
||||
# installs -- same "single source of truth, just splitting *when* it
|
||||
# installs" tradeoff as the npm section's --no-save comment below.
|
||||
RUN pip install --no-cache-dir sqlalchemy==2.0.51
|
||||
RUN pip install --no-cache-dir pillow==12.3.0
|
||||
RUN pip install --no-cache-dir pypdfium2==5.12.1
|
||||
RUN pip install --no-cache-dir playwright==1.61.0
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# The headless Chromium binary itself is deliberately NOT installed
|
||||
# here at build time. `playwright install chromium-headless-shell`
|
||||
# unpacks to ~262MB, and its single `chrome-headless-shell` binary alone
|
||||
# (measured: 181MB) is one file -- unlike the pip/npm splits above
|
||||
# (independently-installable smaller packages moved into their own
|
||||
# layers), a single 181MB file can't be divided across multiple <100MB
|
||||
# Docker layers by any ordinary COPY/RUN restructuring; the whole file
|
||||
# lands in whichever layer's diff contains it, which confirmed-failed
|
||||
# to push to this project's registry (the same Cloudflare single-blob/
|
||||
# layer limit that forced the pip/npm splits elsewhere in this file --
|
||||
# see their comments). Fix: start.sh downloads it at container startup
|
||||
# instead, cached on the /data volume (PLAYWRIGHT_BROWSERS_PATH below)
|
||||
# so it survives restarts/redeploys and only ever downloads once per
|
||||
# volume, not once per image layer. Trade-off: first boot on a fresh
|
||||
# volume needs network access to Playwright's CDN -- true of Immich/
|
||||
# weather API access too, so not a new requirement for this server.
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/data/.playwright-browsers
|
||||
|
||||
# render-service/'s dependencies installed as several separate layers
|
||||
# rather than one `npm install` covering all of them -- a from-scratch
|
||||
# push of this image once hit Cloudflare's payload-size limit on a
|
||||
# single blob/layer upload (the registry sits behind it), and splitting
|
||||
# a big layer into several smaller ones is the direct fix for exactly
|
||||
# that failure mode, independent of anything about the registry itself.
|
||||
# --no-save: package.json already fully declares these (with the exact
|
||||
# same version pins used here) as the single source of truth for what
|
||||
# this service depends on -- these calls are just about *when* each one
|
||||
# gets installed for layer-size reasons, not re-deciding what's needed.
|
||||
COPY render-service/package.json ./render-service/package.json
|
||||
WORKDIR /app/render-service
|
||||
RUN npm install --omit=dev --no-save express@^5.2.1 && npm cache clean --force
|
||||
RUN npm install --omit=dev --no-save jsdom@^29.1.1 && npm cache clean --force
|
||||
RUN npm install --omit=dev --no-save @excalidraw/[email protected] && npm cache clean --force
|
||||
RUN npm install --omit=dev --no-save @resvg/[email protected] && npm cache clean --force
|
||||
WORKDIR /app
|
||||
|
||||
COPY render-service/server.js ./render-service/server.js
|
||||
COPY app ./app
|
||||
COPY start.sh .
|
||||
RUN chmod +x start.sh
|
||||
|
||||
EXPOSE 8420
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8420"]
|
||||
CMD ["./start.sh"]
|
||||
|
||||
+92
-18
@@ -37,13 +37,10 @@ algorithm itself -- it just streams the response straight to the panel.
|
||||
instead (see `firmware/README.md`'s HTTPS section).
|
||||
5. **Each frame gets its own device token automatically** -- the server
|
||||
issues it on the frame's first check-in, so there's nothing to
|
||||
configure. The captive portal's **Access Token** field only matters
|
||||
when pointing new firmware at an old (pre-multi-frame) server.
|
||||
`MANAGEMENT_TOKEN` in `docker-compose.yml` is likewise now only the
|
||||
*migration* credential: a frame flashed with pre-multi-frame
|
||||
firmware authenticates with it until it's updated and bound (the
|
||||
Admin page shows the migration state per frame and a "Close legacy
|
||||
window" button for when it's done).
|
||||
configure. `MANAGEMENT_TOKEN` in `docker-compose.yml` is optional and
|
||||
only matters pre-setup: if set, it's the credential that gates who
|
||||
gets to be the one to run first-run setup on a freshly deployed
|
||||
server, before any admin account exists.
|
||||
6. **Optional: auto-update firmware from Gitea releases.** If you're
|
||||
pushing this repo to a Gitea instance, `.gitea/workflows/firmware-release-build.yml`
|
||||
builds both supported boards and publishes them as release assets
|
||||
@@ -91,11 +88,19 @@ algorithm itself -- it just streams the response straight to the panel.
|
||||
again until a recharge is detected and it crosses again. No SMTP
|
||||
configured, or no email on the relevant account, and both features
|
||||
silently no-op rather than erroring.
|
||||
- **Server logs.** `/admin/logs` shows the tail of the process's own
|
||||
log file (`LOG_PATH` env var, default `/data/server.log` -- the same
|
||||
`/data` volume as the database and legacy config, so it survives
|
||||
container restarts/redeploys; `LOG_LEVEL` env var, default `INFO`).
|
||||
Rotates at ~2MB x 3 backups; the page only reads the current file,
|
||||
"Download full log" streams it raw. There's no log shipping/
|
||||
aggregation beyond this -- it's a single-container deployment, so
|
||||
the file *is* the log.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Pages: `/` (routing hub), `/setup`, `/login`, `/claim`, `/settings`,
|
||||
`/admin`, `/frames/{id}` (Photos), `/frames/{id}/config`,
|
||||
`/admin`, `/admin/logs`, `/frames/{id}` (Photos), `/frames/{id}/config`,
|
||||
`/frames/{id}/stats`, `/m/{manage_token}`.
|
||||
|
||||
### Device protocol (`/frame/*` -- paths frozen; auth = `?id=` + `?token=`)
|
||||
@@ -121,9 +126,11 @@ Pages: `/` (routing hub), `/setup`, `/login`, `/claim`, `/settings`,
|
||||
this response may grow.
|
||||
- `GET /frame/photo-info` -- location/date overlay text for the manage
|
||||
menu (city + abbreviated US/CAN region or country, `MM/DD/YY`).
|
||||
- `GET /frame/share/{asset_id}` -- creates a 30-minute public Immich
|
||||
share link and 302s to it; scoped to the photo currently showing or
|
||||
queued on *this* frame only.
|
||||
- `GET /frame/share/{manage_token}` -- creates a 30-minute public Immich
|
||||
share link covering every photo widget's currently-showing photo on
|
||||
*this* frame and 302s to it. Authenticated by the frame's own
|
||||
`manage_token` (see the manage QR below), not device credentials -- a
|
||||
phone scanning the QR has no way to supply `?id=`/`?token=`.
|
||||
- `GET /frame/face-labels` -- up to 4 named faces with 800x480
|
||||
positions, flattened (`name_0`/`x_0`/`y_0`, ...) for the device's
|
||||
flat-scalar parser.
|
||||
@@ -200,19 +207,70 @@ Pages: `/` (routing hub), `/setup`, `/login`, `/claim`, `/settings`,
|
||||
in the web UI (or using "Show next") only rearranges what's already in
|
||||
that lookahead; it doesn't add or remove photos from the album.
|
||||
- Auth in one breath: browsers use sessions (+CSRF), devices use
|
||||
per-frame tokens (`?id=` + `?token=`), the manage QR uses its own
|
||||
limited token, and `MANAGEMENT_TOKEN` survives only as the migration
|
||||
credential for pre-multi-frame firmware. `/frame/share` stays scoped
|
||||
to photos this frame is actually showing or has queued, not any
|
||||
Immich asset ID someone might guess -- a second layer a leaked device
|
||||
token alone wouldn't bypass.
|
||||
- Calendar frame mode (`app/calendar_feed.py`) expands recurring events
|
||||
per-frame tokens (`?id=` + `?token=`), the manage QR and the
|
||||
scan-to-download QR both use the frame's own `manage_token` (device
|
||||
tokens don't work for either -- neither is ever called by firmware,
|
||||
both are opened by a phone that has no way to supply `?id=`/`?token=`),
|
||||
and `MANAGEMENT_TOKEN` is only ever the pre-setup claim gate (see
|
||||
step 5 above).
|
||||
- The calendar widget (`app/calendar_feed.py`) expands recurring events
|
||||
(RRULE/EXDATE/DST) via [`recurring-ical-events`](https://pypi.org/project/recurring-ical-events/),
|
||||
which is LGPL-3.0-or-later -- the only non-permissively-licensed
|
||||
dependency here. It's used as an ordinary `pip install` runtime import,
|
||||
never vendored or modified, so this project's own code stays under its
|
||||
own license; LGPL's copyleft terms apply to that library itself, not
|
||||
to code that merely links against it dynamically.
|
||||
- CalDAV account support (`app/caldav_client.py`, alongside the plain ICS
|
||||
subscription) wraps the `caldav` PyPI package. `caldav` itself is
|
||||
dual-licensed GPL-3.0-or-later/Apache-2.0, but it hard-depends on
|
||||
`icalendar-searcher`, which is **AGPL-3.0-or-later** -- the strongest
|
||||
copyleft in this project's dependency tree, and the one whose
|
||||
network-use clause is written specifically for server applications
|
||||
like this one (not just "don't vendor/modify it," which was enough
|
||||
reasoning for the LGPL dependency above). Taking this on was an
|
||||
explicit, informed call by the project owner, not a default -- anyone
|
||||
redistributing this project (vs. just self-hosting it) should
|
||||
re-evaluate that tradeoff for their own situation before doing so.
|
||||
- The whiteboard widget (`app/webdav_client.py`, `app/whiteboard.py`)
|
||||
fetches a Nextcloud Whiteboard (or any WebDAV server's) `.whiteboard`
|
||||
file -- which turns out to be Excalidraw scene JSON (elements/appState/
|
||||
files), not an image -- and renders it via `render-service/`, a small
|
||||
Node.js sidecar using Excalidraw's own real export code
|
||||
(`@excalidraw/utils`'s `exportToSvg`) plus `@resvg/resvg-js` (a native
|
||||
Rust SVG rasterizer, no headless browser) to turn that into a PNG. That
|
||||
sidecar runs as a **second process inside this same container**
|
||||
(`Dockerfile` installs Node, `start.sh` launches it in the background
|
||||
before `exec`-ing uvicorn), reachable only at `127.0.0.1:3001` from the
|
||||
Python process -- not a second docker-compose service, since it's
|
||||
lightweight, stateless, and has nothing worth independently scaling or
|
||||
restarting. License check (after getting burned once already in this
|
||||
same file, on the CalDAV dependency below, into checking transitive
|
||||
deps and not just top-level ones): Excalidraw, `@excalidraw/utils`,
|
||||
every one of its own runtime dependencies, `@resvg/resvg-js`
|
||||
(MPL-2.0 -- weak/file-level copyleft, doesn't extend to code that just
|
||||
calls into it), `jsdom`, and `express` are all MIT/Apache-2.0/Zlib/
|
||||
MPL-2.0 -- no repeat of the AGPL surprise. **Not runtime-tested against
|
||||
a real `npm install`/`docker build`** -- this project's dev environment
|
||||
has no Node.js/npm, only network access to the npm registry API (used
|
||||
to verify the above and pick real, current dependency versions). See
|
||||
`render-service/README.md` for exactly what is and isn't verified.
|
||||
- Calendar event titles can contain emoji, which `ImageFont.load_default()`
|
||||
(used for every other bit of text this project renders) has no glyphs
|
||||
for -- PIL/FreeType substitute a visible ".notdef" tofu box rather than
|
||||
skipping the codepoint. `app/calendar_render.py` draws emoji runs with
|
||||
a vendored font instead (Google's Noto Emoji, OFL-1.1 -- license text
|
||||
at `app/fonts/OFL.txt`), the one deliberate exception to this project's
|
||||
usual "no new font/icon assets" default elsewhere in calendar_render.py
|
||||
-- there's no way to hand-draw arbitrary emoji with primitives the way
|
||||
the weather icons are. Full color (`app/fonts/NotoColorEmoji.ttf`,
|
||||
embedded CBDT bitmap glyphs) is tried first and confirmed to hold up
|
||||
fine through the panel's own Floyd-Steinberg dithering; a deployment
|
||||
whose Pillow/FreeType wasn't built with embedded color bitmap support
|
||||
falls back to a monochrome outline font (`app/fonts/NotoEmoji.ttf`)
|
||||
instead of crashing or rendering nothing. Color glyphs are only stored
|
||||
at one embedded bitmap size (109px), so they're rasterized once at
|
||||
that size and scaled down to the target row height rather than drawn
|
||||
directly like normal vector text.
|
||||
- The 6-color palette RGB values in `app/image_pipeline.py`
|
||||
(`DEFAULT_PALETTE_RGB`) are approximations, not measured values
|
||||
(Waveshare doesn't publish exact color primaries for this panel).
|
||||
@@ -252,3 +310,19 @@ CONFIG_PATH=./data/config.json uvicorn app.main:app --reload --host 0.0.0.0 --po
|
||||
`--host 0.0.0.0` matters here: without it, uvicorn defaults to
|
||||
`127.0.0.1` (localhost-only), which the ESP32 can't reach over the LAN.
|
||||
The Docker image already binds `0.0.0.0` by default.
|
||||
|
||||
## Running tests
|
||||
|
||||
```
|
||||
pip install -r requirements-dev.txt
|
||||
pytest
|
||||
```
|
||||
|
||||
Runs against a fresh temp SQLite database (`tests/conftest.py` sets
|
||||
`DATABASE_URL` before anything imports `app.db`), with every table wiped
|
||||
and reseeded (frame #1 + server settings, same as a real fresh install)
|
||||
between tests -- no Docker, Node, or a real Immich/CalDAV/WebDAV server
|
||||
needed; a few tests spin up small local HTTP servers as fixtures to
|
||||
stand in for those. Also runs as its own job in
|
||||
`.gitea/workflows/server-docker-build.yml`, gating the image build/push
|
||||
-- a failing test suite blocks the push, not just decorates it.
|
||||
|
||||
+44
-76
@@ -1,14 +1,18 @@
|
||||
"""Authentication: password hashing, user sessions + CSRF, the legacy
|
||||
shared-token gate, and device resolution.
|
||||
"""Authentication: password hashing, user sessions + CSRF, the pre-setup
|
||||
claim gate, and device resolution.
|
||||
|
||||
Three independent credential classes:
|
||||
- User sessions (cookie "session", server-side sessions table, per-
|
||||
session CSRF token required on mutating requests) -- humans.
|
||||
- The legacy shared MANAGEMENT_TOKEN (env-only). Still accepted on
|
||||
browser routes so the deployed frame's on-panel manage QR (which
|
||||
embeds ?token=) keeps working until Phase C replaces it with the
|
||||
limited /m/ page; CSRF doesn't apply to it (it's explicit per-request
|
||||
credential, not an ambient cookie a cross-site request could ride).
|
||||
- MANAGEMENT_TOKEN (env-only, optional). Only meaningful before any user
|
||||
account exists yet (fresh install, or freshly migrated, before
|
||||
/setup has been run): if set, it gates who gets to be the one to run
|
||||
/setup and claim the first admin account; once a user exists, sessions
|
||||
are the only way in. Not a standing bearer credential -- the on-panel
|
||||
manage QR now embeds a frame's own per-frame manage_token (/m/, see
|
||||
routers/manage.py) rather than this shared one; CSRF doesn't apply to
|
||||
it either way (it's an explicit per-request credential, not an ambient
|
||||
cookie a cross-site request could ride).
|
||||
- Device credentials (?id= + ?token=, see require_device below).
|
||||
"""
|
||||
|
||||
@@ -250,17 +254,16 @@ def require_frame_control(
|
||||
|
||||
|
||||
def management_token() -> str:
|
||||
"""The legacy shared secret. Env-only, never stored -- same as the old
|
||||
server, where the env var overrode anything on disk on every load."""
|
||||
"""The pre-setup claim-gate secret. Env-only, never stored -- same as
|
||||
the old server, where the env var overrode anything on disk on every
|
||||
load."""
|
||||
return os.environ.get("MANAGEMENT_TOKEN", "")
|
||||
|
||||
|
||||
def browser_token_valid(request: Request) -> bool:
|
||||
"""The legacy shared-token check. No MANAGEMENT_TOKEN configured means
|
||||
token-holders don't exist -- but unlike Phase A this no longer means
|
||||
"open": once users exist, sessions are the primary gate and this is
|
||||
only the compatibility path for the deployed frame's manage QR
|
||||
(?token=) until Phase C. Empty token => not valid (sessions rule)."""
|
||||
"""Whether the request carries the current MANAGEMENT_TOKEN, via
|
||||
query param or cookie. Only meaningful pre-setup (see require_browser
|
||||
below) -- empty configured token => not valid (nothing to match)."""
|
||||
token = management_token()
|
||||
if not token:
|
||||
return False
|
||||
@@ -270,12 +273,12 @@ def browser_token_valid(request: Request) -> bool:
|
||||
|
||||
def require_browser(request: Request, db: Session = Depends(get_db)) -> User | None:
|
||||
"""Dependency for the web UI's /api/* routes: a real user session
|
||||
(CSRF-checked on mutations, returns the User), or the legacy shared
|
||||
token (returns None -- token bearers act as an anonymous operator,
|
||||
exactly the pre-user model). While NO users exist yet (fresh install
|
||||
or freshly migrated, before /setup has been run) the API stays open
|
||||
if no MANAGEMENT_TOKEN is set -- the Phase A/legacy behavior --
|
||||
since there's nobody to log in as yet."""
|
||||
(CSRF-checked on mutations, returns the User). While NO users exist
|
||||
yet (fresh install, or freshly migrated, before /setup has been run)
|
||||
the API instead stays open if no MANAGEMENT_TOKEN is set, or opens
|
||||
to whoever supplies it if one is -- there's nobody to log in as yet,
|
||||
so this is purely the claim gate for who gets to run /setup. Once a
|
||||
user exists, only a session gets in."""
|
||||
session = current_session(request, db)
|
||||
if session is not None:
|
||||
if request.method not in ("GET", "HEAD", "OPTIONS") and not _csrf_ok(request, session):
|
||||
@@ -283,10 +286,9 @@ def require_browser(request: Request, db: Session = Depends(get_db)) -> User | N
|
||||
user = db.get(User, session.user_id)
|
||||
if user is not None:
|
||||
return user
|
||||
if browser_token_valid(request):
|
||||
return None
|
||||
if not users_exist(db) and not management_token():
|
||||
return None
|
||||
if not users_exist(db):
|
||||
if not management_token() or browser_token_valid(request):
|
||||
return None
|
||||
raise HTTPException(401, "Not logged in")
|
||||
|
||||
|
||||
@@ -326,63 +328,29 @@ def _register_frame(db: Session, device_id: str) -> Frame:
|
||||
|
||||
def require_device(request: Request, db: Session = Depends(get_db)) -> Frame:
|
||||
"""Resolves and authenticates the frame behind a /frame/* request.
|
||||
|
||||
New firmware sends ?id=<12-hex-mac>&token=<per-frame device token>.
|
||||
Deployed legacy firmware sends only ?token=<shared MANAGEMENT_TOKEN>
|
||||
(or nothing, on an open server) -- those requests resolve to the
|
||||
unique legacy_token_enabled frame for as long as that migration
|
||||
window stays open. The first id-bearing request arriving with legacy
|
||||
credentials while the legacy frame has no device_id yet BINDS that id
|
||||
to it -- that's the moment the deployed frame comes back up on new
|
||||
firmware after its OTA, and it must not register as a second frame.
|
||||
"""
|
||||
Firmware sends ?id=<12-hex-mac>&token=<per-frame device token>."""
|
||||
device_id = request.query_params.get("id", "").strip().lower()
|
||||
token = request.query_params.get("token", "")
|
||||
legacy = management_token()
|
||||
legacy_ok = not legacy or token == legacy
|
||||
|
||||
if device_id:
|
||||
frame = db.scalars(select(Frame).where(Frame.device_id == device_id)).first()
|
||||
if frame is None:
|
||||
legacy_frame = db.scalars(
|
||||
select(Frame).where(Frame.legacy_token_enabled == True) # noqa: E712
|
||||
).first()
|
||||
if legacy_frame is not None and legacy_frame.device_id is None and legacy_ok:
|
||||
legacy_frame.device_id = device_id
|
||||
frame = legacy_frame
|
||||
logger.info("Bound device id %s to legacy frame #%d", device_id, frame.id)
|
||||
else:
|
||||
frame = _register_frame(db, device_id)
|
||||
else:
|
||||
token_ok = bool(token) and token == frame.device_token
|
||||
if token_ok and not frame.device_token_ack:
|
||||
frame.device_token_ack = True
|
||||
logger.info("Frame #%d acknowledged its device token", frame.id)
|
||||
if not token_ok:
|
||||
if frame.legacy_token_enabled and legacy_ok:
|
||||
pass
|
||||
elif not frame.device_token_ack:
|
||||
# Handshake window: the device registered but hasn't
|
||||
# received its token yet (the wake cycle fetches the
|
||||
# image BEFORE polling /frame/config, where the token
|
||||
# is delivered) -- the id stays the credential, same
|
||||
# trust level as the open registration that created
|
||||
# the row. Closes permanently on the first
|
||||
# authenticated request.
|
||||
pass
|
||||
else:
|
||||
raise HTTPException(401, "Missing or invalid access token")
|
||||
if not device_id:
|
||||
raise HTTPException(401, "Missing device id")
|
||||
|
||||
frame = db.scalars(select(Frame).where(Frame.device_id == device_id)).first()
|
||||
if frame is None:
|
||||
frame = _register_frame(db, device_id)
|
||||
else:
|
||||
if not legacy_ok:
|
||||
token_ok = bool(token) and token == frame.device_token
|
||||
if token_ok and not frame.device_token_ack:
|
||||
frame.device_token_ack = True
|
||||
logger.info("Frame #%d acknowledged its device token", frame.id)
|
||||
elif not token_ok and frame.device_token_ack:
|
||||
raise HTTPException(401, "Missing or invalid access token")
|
||||
frame = db.scalars(
|
||||
select(Frame).where(Frame.legacy_token_enabled == True) # noqa: E712
|
||||
).first()
|
||||
if frame is None:
|
||||
# Nothing to resolve a no-id request to. migration.py always
|
||||
# creates frame #1 at startup, so this only happens if it was
|
||||
# deleted -- treat like an unknown device.
|
||||
raise HTTPException(401, "No frame accepts legacy credentials")
|
||||
# else: handshake window -- the device registered but hasn't
|
||||
# received its token yet (the wake cycle fetches the image
|
||||
# BEFORE polling /frame/config, where the token is delivered) --
|
||||
# the id stays the credential, same trust level as the open
|
||||
# registration that created the row. Closes permanently on the
|
||||
# first authenticated request.
|
||||
|
||||
frame.last_seen = time.time()
|
||||
db.commit()
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""CalDAV account support: discovering which calendars an account exposes,
|
||||
and fetching one calendar's events or tasks -- the second way (alongside
|
||||
calendar_feed.py's single-file ICS subscription) a user can link a
|
||||
calendar for calendar frame mode (Nextcloud, Fastmail, iCloud, Radicale,
|
||||
Baikal, ...). Task lists (VTODO collections) are CalDAV-only -- a plain
|
||||
ICS subscription doesn't meaningfully have one -- see fetch_tasks.
|
||||
|
||||
Thin wrapper around the `caldav` PyPI package (RFC 4791 client). NOTE ON
|
||||
LICENSING: `caldav` itself is dual-licensed GPL-3.0-or-later / Apache-2.0,
|
||||
but it hard-depends on `icalendar-searcher`, which is AGPL-3.0-or-later --
|
||||
the strongest copyleft license in this project's dependency tree, and the
|
||||
one whose network-use clause is specifically written for server
|
||||
applications like this one. This was an explicit, informed call by the
|
||||
project owner to accept that exposure rather than hand-roll a CalDAV
|
||||
client -- see the server README's Notes section. Anyone redistributing
|
||||
this project (as opposed to just self-hosting it) should reread that
|
||||
tradeoff for their own situation.
|
||||
|
||||
Pure functions -- no ORM, no FastAPI Depends -- same testability
|
||||
philosophy as calendar_feed.py. Event parsing/expansion reuses
|
||||
icalendar + recurring_ical_events directly (rather than trusting each
|
||||
CalDAV server's own possibly-inconsistent RRULE expansion) so a CalDAV
|
||||
calendar and an ICS subscription behave identically once fetched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
|
||||
import caldav
|
||||
import icalendar
|
||||
import recurring_ical_events
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
HTTP_TIMEOUT_S = 15
|
||||
|
||||
|
||||
class CalDavError(Exception):
|
||||
"""Discovery or fetch failed -- network, auth, or an unexpected
|
||||
server response. Raised loudly; callers (Settings' discover
|
||||
endpoint, calendar_feed.merge_events) decide what to do. Wraps
|
||||
whatever the caldav package/its transport raised, since that
|
||||
exception hierarchy isn't something call sites should need to know
|
||||
about directly."""
|
||||
|
||||
|
||||
def discover_calendars(base_url: str, username: str, password: str) -> list[dict]:
|
||||
"""[{"href": absolute_calendar_url, "display_name": str}, ...] for
|
||||
every calendar in this account. base_url is the server's CalDAV
|
||||
entry point (e.g. "https://cloud.example.com/remote.php/dav/" for
|
||||
Nextcloud) -- the caller supplies it directly, same idiom as the
|
||||
plain ICS subscription URL."""
|
||||
try:
|
||||
client = caldav.DAVClient(url=base_url, username=username, password=password, timeout=HTTP_TIMEOUT_S)
|
||||
calendars = client.principal().calendars()
|
||||
except Exception as e:
|
||||
raise CalDavError(str(e)) from e
|
||||
|
||||
result = []
|
||||
for cal in calendars:
|
||||
try:
|
||||
display_name = cal.get_display_name() or cal.name
|
||||
except Exception:
|
||||
display_name = None
|
||||
result.append({"href": str(cal.url), "display_name": display_name or str(cal.url)})
|
||||
return result
|
||||
|
||||
|
||||
def fetch_calendar_events(calendar_url: str, username: str, password: str,
|
||||
window_start: date, window_end: date) -> list[dict]:
|
||||
"""One CalDAV calendar's events in [window_start, window_end] -- same
|
||||
event dict shape as calendar_feed.fetch_source_events (no
|
||||
"owner_display_name"; the caller adds that).
|
||||
|
||||
Deliberately does NOT use the calendar-query REPORT's server-side
|
||||
time-range filter (caldav.Calendar.date_search) -- RFC 4791 leaves
|
||||
that corner case underspecified and real servers disagree on it
|
||||
(the caldav package's own docs warn "servers often behave
|
||||
differently when presented with a search request"; confirmed here
|
||||
too, once against a real server, as a calendar whose events just
|
||||
silently never came back despite discovery/auth both working
|
||||
fine). Instead this fetches every event in the calendar unfiltered
|
||||
(get_events() is a plain "list VEVENTs" REPORT with no time-range
|
||||
element -- the much more universally-supported case) and does 100%
|
||||
of the date-window filtering/recurrence-expansion client-side via
|
||||
icalendar + recurring_ical_events, exactly like calendar_feed.py
|
||||
already does for plain ICS feeds. Heavier per-fetch (the whole
|
||||
calendar, not just the window) but far more reliable."""
|
||||
try:
|
||||
client = caldav.DAVClient(url=calendar_url, username=username, password=password, timeout=HTTP_TIMEOUT_S)
|
||||
calendar = caldav.Calendar(client=client, url=calendar_url)
|
||||
objects = calendar.get_events()
|
||||
except Exception as e:
|
||||
raise CalDavError(str(e)) from e
|
||||
|
||||
events: list[dict] = []
|
||||
for obj in objects:
|
||||
try:
|
||||
ical = icalendar.Calendar.from_ical(obj.data)
|
||||
occurrences = recurring_ical_events.of(ical).between(window_start, window_end)
|
||||
except Exception as e: # one malformed resource shouldn't blank the whole calendar
|
||||
logger.warning("Could not parse a CalDAV event from %s: %s", calendar_url, e)
|
||||
continue
|
||||
for occ in occurrences:
|
||||
dtstart = occ.get("DTSTART")
|
||||
dtend = occ.get("DTEND")
|
||||
if dtstart is None:
|
||||
continue
|
||||
start_dt = dtstart.dt
|
||||
end_dt = dtend.dt if dtend is not None else start_dt
|
||||
all_day = not isinstance(start_dt, datetime)
|
||||
events.append({
|
||||
"summary": str(occ.get("SUMMARY") or "(untitled)"),
|
||||
"start": start_dt.isoformat(),
|
||||
"end": end_dt.isoformat(),
|
||||
"all_day": all_day,
|
||||
})
|
||||
return events
|
||||
|
||||
|
||||
def fetch_tasks(calendar_url: str, username: str, password: str,
|
||||
completed_since: datetime | None = None) -> list[dict]:
|
||||
"""Outstanding VTODOs from one CalDAV task list, plus -- when
|
||||
completed_since is given -- ones completed at or after that cutoff
|
||||
(see routers/common.py's get_or_refresh_tasks_for_widget, which
|
||||
passes "now - 24h" when TaskWidgetConfig.show_completed is on;
|
||||
None, the default, means completed tasks are dropped entirely, the
|
||||
original behavior). {"summary", "due" (ISO date/datetime string or
|
||||
None), "completed_at" (ISO datetime string, or None for an
|
||||
outstanding task)}, ... . Outstanding tasks sort first (by due date,
|
||||
no-due-date last), any included completed ones after (most recently
|
||||
completed first).
|
||||
|
||||
Fetches every task including completed ones and filters/sorts
|
||||
client-side rather than trusting get_todos()'s own
|
||||
include_completed/sort_keys server-side filtering, same reasoning as
|
||||
fetch_calendar_events not trusting the time-range REPORT filter --
|
||||
a simpler filter than a time range, but not worth re-litigating
|
||||
which server-side filters are reliable one at a time."""
|
||||
try:
|
||||
client = caldav.DAVClient(url=calendar_url, username=username, password=password, timeout=HTTP_TIMEOUT_S)
|
||||
calendar = caldav.Calendar(client=client, url=calendar_url)
|
||||
objects = calendar.get_todos(include_completed=True)
|
||||
except Exception as e:
|
||||
raise CalDavError(str(e)) from e
|
||||
|
||||
outstanding: list[dict] = []
|
||||
completed: list[dict] = []
|
||||
for obj in objects:
|
||||
try:
|
||||
ical = icalendar.Calendar.from_ical(obj.data)
|
||||
except Exception as e: # one malformed resource shouldn't blank the whole list
|
||||
logger.warning("Could not parse a CalDAV task from %s: %s", calendar_url, e)
|
||||
continue
|
||||
for component in ical.walk("VTODO"):
|
||||
status = str(component.get("STATUS") or "NEEDS-ACTION").upper()
|
||||
summary = str(component.get("SUMMARY") or "(untitled)")
|
||||
if status == "COMPLETED":
|
||||
completed_prop = component.get("COMPLETED")
|
||||
completed_dt = completed_prop.dt if completed_prop is not None else None
|
||||
if completed_since is None or completed_dt is None or completed_dt < completed_since:
|
||||
continue
|
||||
completed.append({"summary": summary, "due": None, "completed_at": completed_dt.isoformat()})
|
||||
else:
|
||||
due = component.get("DUE")
|
||||
outstanding.append({
|
||||
"summary": summary,
|
||||
"due": due.dt.isoformat() if due is not None else None,
|
||||
"completed_at": None,
|
||||
})
|
||||
outstanding.sort(key=lambda t: (t["due"] is None, t["due"] or ""))
|
||||
completed.sort(key=lambda t: t["completed_at"], reverse=True)
|
||||
return outstanding + completed
|
||||
|
||||
|
||||
@dataclass
|
||||
class TaskSource:
|
||||
"""One task list to merge in -- CalDAV only, no ICS variant (a plain
|
||||
ICS subscription has no VTODO collection to speak of).
|
||||
owner_display_name tags every task pulled from this source so a
|
||||
merged checklist can show whose task is whose; color_index (2-5,
|
||||
into image_pipeline.DEFAULT_PALETTE_RGB) is this list's manually
|
||||
pinned color, or None for calendar_render.py's auto-cycle-by-owner-
|
||||
name fallback -- see models.FrameTaskList."""
|
||||
|
||||
owner_display_name: str
|
||||
url: str
|
||||
username: str
|
||||
password: str
|
||||
color_index: int | None = None
|
||||
|
||||
|
||||
def merge_tasks(sources: list[TaskSource], completed_since: datetime | None = None) -> tuple[list[dict], str]:
|
||||
"""Fetches each source independently -- one broken list never blanks
|
||||
another's tasks. Returns (merged_tasks, fetch_summary); fetch_summary
|
||||
is "" when every source succeeded, else "N of M task lists
|
||||
unavailable" (same no-naming-names posture as calendar_feed.
|
||||
merge_events). No cross-list duplicate collapsing (unlike
|
||||
merge_events) -- a task synced to two lists at once is rare enough,
|
||||
and lower-stakes than a duplicated calendar event, not to be worth
|
||||
the same de-dup machinery."""
|
||||
merged: list[dict] = []
|
||||
failures = 0
|
||||
for source in sources:
|
||||
try:
|
||||
tasks = fetch_tasks(source.url, source.username, source.password, completed_since=completed_since)
|
||||
except CalDavError:
|
||||
failures += 1
|
||||
continue
|
||||
for task in tasks:
|
||||
merged.append({
|
||||
**task,
|
||||
"owner_display_name": source.owner_display_name,
|
||||
"color_index": source.color_index,
|
||||
})
|
||||
|
||||
outstanding = [t for t in merged if t["completed_at"] is None]
|
||||
completed = [t for t in merged if t["completed_at"] is not None]
|
||||
outstanding.sort(key=lambda t: (t["due"] is None, t["due"] or ""))
|
||||
completed.sort(key=lambda t: t["completed_at"], reverse=True)
|
||||
summary = f"{failures} of {len(sources)} task lists unavailable" if failures else ""
|
||||
return outstanding + completed, summary
|
||||
+63
-18
@@ -1,10 +1,11 @@
|
||||
"""Fetch, parse, and merge per-user ICS calendar feeds for calendar frame
|
||||
mode (see routers/device.py's RENDERERS["calendar"] and calendar_render.py).
|
||||
"""Fetch, parse, and merge per-user calendar feeds -- ICS subscriptions
|
||||
and (via caldav_client.py) CalDAV collections -- for calendar frame mode
|
||||
(see routers/device.py's RENDERERS["calendar"] and calendar_render.py).
|
||||
|
||||
Pure functions -- no ORM, no FastAPI Depends. Callers (routers/common.py's
|
||||
get_or_refresh_calendar_events) supply plain (owner_display_name, url)
|
||||
pairs, not ORM objects, so this module stays testable against fixture .ics
|
||||
text with no database or app involved.
|
||||
get_or_refresh_calendar_events) supply plain CalendarSource values, not
|
||||
ORM objects, so this module stays testable against fixture .ics text with
|
||||
no database or app involved.
|
||||
|
||||
Recurring events (RRULE/EXDATE/RDATE, DST-aware) are expanded via
|
||||
recurring-ical-events rather than hand-rolled -- that's genuinely fiddly
|
||||
@@ -16,12 +17,15 @@ code under LGPL terms).
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
|
||||
import httpx
|
||||
import icalendar
|
||||
import recurring_ical_events
|
||||
|
||||
from . import caldav_client
|
||||
|
||||
HTTP_TIMEOUT_S = 15.0
|
||||
FETCH_MAX_BYTES = 10 * 1024 * 1024 # sanity cap -- a real feed is KB, not MB
|
||||
|
||||
@@ -83,27 +87,68 @@ def fetch_source_events(url: str, window_start: date, window_end: date) -> list[
|
||||
return events
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CalendarSource:
|
||||
"""One calendar to merge in: either a plain ICS subscription (kind
|
||||
"ics", url is the feed itself) or one CalDAV collection (kind
|
||||
"caldav", url is the calendar's own URL, username/password its
|
||||
account credentials) -- see caldav_client.py. owner_display_name
|
||||
tags every event pulled from this source so a merged agenda can show
|
||||
whose event is whose. color_index (2-5, into
|
||||
image_pipeline.DEFAULT_PALETTE_RGB) is this calendar's manually
|
||||
pinned color, or None to fall back on calendar_render.py's old
|
||||
auto-cycle-by-owner-name behavior -- see models.FrameCalendar."""
|
||||
|
||||
owner_display_name: str
|
||||
kind: str
|
||||
url: str
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
color_index: int | None = None
|
||||
|
||||
|
||||
def merge_events(
|
||||
sources: list[tuple[str, str]], window_start: date, window_end: date
|
||||
sources: list[CalendarSource], window_start: date, window_end: date
|
||||
) -> tuple[list[dict], str]:
|
||||
"""sources: [(owner_display_name, ics_url), ...]. Fetches each
|
||||
independently -- one broken feed never blanks another's events.
|
||||
Returns (merged_time_sorted_events, fetch_summary); fetch_summary is
|
||||
"" when every source succeeded, else "N of M calendars unavailable"
|
||||
(never *which* source -- naming whose feed is down to everyone who
|
||||
looks at a shared household display is a bigger overshare than the
|
||||
outage itself)."""
|
||||
"""Fetches each source independently -- one broken feed never blanks
|
||||
another's events. Returns (merged_time_sorted_events, fetch_summary);
|
||||
fetch_summary is "" when every source succeeded, else "N of M
|
||||
calendars unavailable" (never *which* source -- naming whose feed is
|
||||
down to everyone who looks at a shared household display is a bigger
|
||||
overshare than the outage itself).
|
||||
|
||||
Events sharing the exact same (summary, start, end, all_day) across
|
||||
different calendars -- e.g. a shared family event synced onto more
|
||||
than one person's calendar -- collapse into one entry rather than
|
||||
showing as duplicate rows. Every merged event carries a "sources"
|
||||
list ([{"owner_display_name", "color_index"}, ...], length 1 for an
|
||||
ordinary non-duplicated event) that calendar_render.py draws a
|
||||
color indicator per entry of, so a collapsed event still visibly
|
||||
shows every calendar it came from."""
|
||||
merged: list[dict] = []
|
||||
by_key: dict[tuple, dict] = {}
|
||||
failures = 0
|
||||
for owner_display_name, url in sources:
|
||||
for source in sources:
|
||||
try:
|
||||
events = fetch_source_events(url, window_start, window_end)
|
||||
except CalendarFetchError:
|
||||
if source.kind == "caldav":
|
||||
events = caldav_client.fetch_calendar_events(
|
||||
source.url, source.username, source.password, window_start, window_end
|
||||
)
|
||||
else:
|
||||
events = fetch_source_events(source.url, window_start, window_end)
|
||||
except (CalendarFetchError, caldav_client.CalDavError):
|
||||
failures += 1
|
||||
continue
|
||||
for event in events:
|
||||
event["owner_display_name"] = owner_display_name
|
||||
merged.append(event)
|
||||
source_entry = {"owner_display_name": source.owner_display_name, "color_index": source.color_index}
|
||||
key = (event["summary"], event["start"], event["end"], event["all_day"])
|
||||
existing = by_key.get(key)
|
||||
if existing is None:
|
||||
event["sources"] = [source_entry]
|
||||
by_key[key] = event
|
||||
merged.append(event)
|
||||
else:
|
||||
existing["sources"].append(source_entry)
|
||||
|
||||
merged.sort(key=lambda e: e["start"])
|
||||
summary = f"{failures} of {len(sources)} calendars unavailable" if failures else ""
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
"""Calendar widget's "modern" render style -- all four view modes
|
||||
(agenda/today_tomorrow/week/month), mirroring calendar_render.py's own
|
||||
_build dispatch shape exactly so app/widgets/calendar.py and the
|
||||
calendar preview endpoint can call either module identically. Kept in
|
||||
its own module rather than joining app/html_render.py's other build_*
|
||||
functions, mirroring calendar_render.py's own separation from the
|
||||
simpler widgets (calendar is the one case where html_render.py growing
|
||||
a 5th unrelated builder starts to hurt readability).
|
||||
|
||||
Reuses calendar_render's own private helpers (_events_on_day/_event_
|
||||
colors/_event_start/_fmt_time/_weather_for_day/_month_view_fits/
|
||||
_add_months) so a modern-style view's event list/colors/times/weather/
|
||||
month-grid math match the classic renderer's data exactly -- only the
|
||||
drawing differs, same relationship weather's build_current/build_daily
|
||||
have with weather_render.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar as calendar_module
|
||||
from datetime import date, datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from . import html_render, panel_style, theme_tokens
|
||||
from .calendar_render import (
|
||||
MARGIN,
|
||||
WEEKDAY_NAMES,
|
||||
_add_months,
|
||||
_event_colors,
|
||||
_event_start,
|
||||
_events_on_day,
|
||||
_fmt_time,
|
||||
_month_view_fits,
|
||||
_weather_for_day,
|
||||
)
|
||||
|
||||
|
||||
def _weather_row(weather_cities, day, units) -> list[dict]:
|
||||
entries = _weather_for_day(weather_cities, day)
|
||||
return [
|
||||
{"emoji": html_render.CATEGORY_EMOJI.get(e["category"], ""), "high": round(e["high"]), "low": round(e["low"])}
|
||||
for e in entries
|
||||
]
|
||||
|
||||
|
||||
def _day_section_data(day: date, events: list[dict], tz: ZoneInfo, palette_rgb, weather_cities,
|
||||
weather_units: str, owners_seen: list[str], rows_avail_h: int, row_h: int) -> dict:
|
||||
"""One day's {header, weather_entries, rows, more_count} -- shared by
|
||||
build_agenda/build_today_tomorrow/build_week's vertical layout, same
|
||||
reuse relationship calendar_render._draw_agenda_day has with
|
||||
_build_agenda/_build_today_tomorrow. `rows_avail_h` is the *rows*
|
||||
area's own pixel budget only -- the caller has already reserved a
|
||||
separate, uniform header_h (which is where weather actually renders,
|
||||
see the day-header macro) for every section, so this function
|
||||
doesn't need to account for weather space itself."""
|
||||
header = day.strftime("%A, %B ") + str(day.day)
|
||||
weather_entries = _weather_row(weather_cities, day, weather_units)
|
||||
max_rows = max(0, rows_avail_h // row_h)
|
||||
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
rows = []
|
||||
for event in day_events[:max_rows]:
|
||||
colors = _event_colors(event, owners_seen, palette_rgb)
|
||||
time_str = "All day" if event["all_day"] else _fmt_time(_event_start(event, tz))
|
||||
rows.append({"colors": [html_render._rgb_to_hex(c) for c in colors], "time": time_str,
|
||||
"summary": event["summary"]})
|
||||
return {"header": header, "weather_entries": weather_entries, "rows": rows,
|
||||
"more_count": max(0, len(day_events) - max_rows)}
|
||||
|
||||
|
||||
def build_agenda(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", theme_name: str | None = None,
|
||||
font_scale: float = 1.0) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of calendar_render._build_agenda.
|
||||
|
||||
Bold-minimal: no card/border/shadow (theme["radius"]/theme["shadow"]
|
||||
are unused, same carve-out as weather's build_current/build_daily --
|
||||
see docs/widgets.md). The day header is plain ink text under a slim
|
||||
accent-colored rule instead of white text on a full gradient band --
|
||||
only that thin rule dithers at the theme's richer accent_amplitude
|
||||
now, not the header text sitting on top of it, which is a legibility
|
||||
improvement over the old design, not just a visual one."""
|
||||
theme = theme_tokens.resolve_theme(theme_name, "calendar", palette_rgb)
|
||||
day = datetime.now(tz).date() + timedelta(days=browse_offset)
|
||||
title_size = panel_style.scaled_size(max(14, min(target_w, target_h) // 12), font_scale)
|
||||
body_size = panel_style.scaled_size(max(11, min(target_w, target_h) // 20), font_scale)
|
||||
weather_size = max(10, body_size - 2)
|
||||
row_h = body_size + 14
|
||||
unit_suffix = "F" if weather_units == "fahrenheit" else "C"
|
||||
accent_h = round(html_render._clamp(min(target_w, target_h) * 0.025, 4, 8))
|
||||
|
||||
# Single day -- no cross-section alignment concern, so header_h can
|
||||
# simply reflect whether THIS day actually has weather (unlike
|
||||
# build_today_tomorrow/build_week's vertical layout, which must
|
||||
# reserve the same header_h for every stacked section regardless).
|
||||
has_weather = bool(_weather_row(weather_cities, day, weather_units))
|
||||
header_h = accent_h + 10 + title_size + ((weather_size + 10) if has_weather else 0)
|
||||
|
||||
owners_seen: list[str] = []
|
||||
data = _day_section_data(day, events, tz, palette_rgb, weather_cities, weather_units, owners_seen,
|
||||
target_h - header_h - MARGIN, row_h)
|
||||
|
||||
template = html_render._jinja_env.get_template("calendar_agenda.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=panel_style.GUTTER,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
header=data["header"], title_size=title_size, header_h=header_h, accent_h=accent_h,
|
||||
accent_start=theme["accent_hex"], weather_entries=data["weather_entries"],
|
||||
weather_size=weather_size, unit_suffix=unit_suffix, rows=data["rows"],
|
||||
more_count=data["more_count"], row_h=row_h, body_size=body_size,
|
||||
)
|
||||
rendered = html_render.render_html_to_image(html, target_w, target_h)
|
||||
gutter = panel_style.GUTTER
|
||||
accent_rect = (gutter, gutter, target_w - gutter, gutter + accent_h)
|
||||
return html_render.ordered_dither_regions(
|
||||
rendered, palette_rgb, accent_regions=[(accent_rect, theme["accent_amplitude"])]
|
||||
)
|
||||
|
||||
|
||||
def build_today_tomorrow(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", theme_name: str | None = None,
|
||||
font_scale: float = 1.0) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of calendar_render._build_today_tomorrow
|
||||
-- two day-sections stacked (see _day_section_data). Bold-minimal, no
|
||||
card (see build_agenda's docstring) -- each section's own slim accent
|
||||
rule dithers richer via ordered_dither_regions, not its header text."""
|
||||
theme = theme_tokens.resolve_theme(theme_name, "calendar", palette_rgb)
|
||||
start_day = datetime.now(tz).date() + timedelta(days=browse_offset)
|
||||
section_h = target_h // 2
|
||||
title_size = panel_style.scaled_size(max(13, section_h // 8), font_scale)
|
||||
body_size = panel_style.scaled_size(max(10, min(target_w, target_h) // 26), font_scale)
|
||||
weather_size = max(9, body_size - 2)
|
||||
row_h = body_size + 12
|
||||
unit_suffix = "F" if weather_units == "fahrenheit" else "C"
|
||||
accent_h = round(html_render._clamp(min(target_w, target_h) * 0.02, 3, 6))
|
||||
|
||||
day_dates = [start_day + timedelta(days=i) for i in range(2)]
|
||||
# Uniform across both stacked sections regardless of which day(s)
|
||||
# actually have weather -- see _day_section_data's own docstring for
|
||||
# why a per-day header height misaligns where rows start.
|
||||
any_weather = any(_weather_row(weather_cities, d, weather_units) for d in day_dates)
|
||||
header_h = accent_h + 8 + title_size + ((weather_size + 8) if any_weather else 0)
|
||||
|
||||
owners_seen: list[str] = []
|
||||
days = [
|
||||
_day_section_data(d, events, tz, palette_rgb, weather_cities, weather_units, owners_seen,
|
||||
section_h - header_h, row_h)
|
||||
for d in day_dates
|
||||
]
|
||||
|
||||
template = html_render._jinja_env.get_template("calendar_today_tomorrow.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=panel_style.GUTTER,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
days=days, title_size=title_size, header_h=header_h, accent_h=accent_h,
|
||||
accent_start=theme["accent_hex"], weather_size=weather_size,
|
||||
unit_suffix=unit_suffix, row_h=row_h, body_size=body_size,
|
||||
)
|
||||
rendered = html_render.render_html_to_image(html, target_w, target_h)
|
||||
gutter = panel_style.GUTTER
|
||||
accent_regions = [
|
||||
((gutter, gutter + i * section_h, target_w - gutter, gutter + i * section_h + accent_h),
|
||||
theme["accent_amplitude"])
|
||||
for i in range(len(days))
|
||||
]
|
||||
return html_render.ordered_dither_regions(rendered, palette_rgb, accent_regions=accent_regions)
|
||||
|
||||
|
||||
def build_week(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
week_start: int, palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", days: int = 7, layout: str = "horizontal",
|
||||
start_offset: int = 0, theme_name: str | None = None, font_scale: float = 1.0) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of calendar_render._build_week -- both
|
||||
the vertical (stacked day-sections, reusing build_today_tomorrow's
|
||||
template with an arbitrary day count) and horizontal (side-by-side
|
||||
columns) layouts. Each header (per-section or per-column) dithers
|
||||
richer via ordered_dither_regions."""
|
||||
theme = theme_tokens.resolve_theme(theme_name, "calendar", palette_rgb)
|
||||
gutter = panel_style.GUTTER
|
||||
today = datetime.now(tz).date()
|
||||
if days == 7:
|
||||
days_since_start = (today.weekday() - week_start) % 7
|
||||
week_first_day = today - timedelta(days=days_since_start) + timedelta(days=days * browse_offset)
|
||||
else:
|
||||
week_first_day = today + timedelta(days=start_offset) + timedelta(days=days * browse_offset)
|
||||
unit_suffix = "F" if weather_units == "fahrenheit" else "C"
|
||||
owners_seen: list[str] = []
|
||||
|
||||
if layout == "vertical":
|
||||
section_h = target_h // days
|
||||
title_size = panel_style.scaled_size(max(11, min(20, section_h // 6)), font_scale)
|
||||
body_size = panel_style.scaled_size(max(9, min(target_w, target_h) // (18 + days)), font_scale)
|
||||
weather_size = max(8, body_size - 2)
|
||||
row_h = body_size + 10
|
||||
accent_h = round(html_render._clamp(min(target_w, target_h) * 0.018, 3, 5))
|
||||
day_dates = [week_first_day + timedelta(days=i) for i in range(days)]
|
||||
# Uniform across all `days` stacked sections -- see
|
||||
# _day_section_data's own docstring for why a per-day header
|
||||
# height misaligns where rows start.
|
||||
any_weather = any(_weather_row(weather_cities, d, weather_units) for d in day_dates)
|
||||
header_h = accent_h + 6 + title_size + ((weather_size + 6) if any_weather else 0)
|
||||
day_sections = [
|
||||
_day_section_data(d, events, tz, palette_rgb, weather_cities, weather_units, owners_seen,
|
||||
section_h - header_h, row_h)
|
||||
for d in day_dates
|
||||
]
|
||||
template = html_render._jinja_env.get_template("calendar_today_tomorrow.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=gutter,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
days=day_sections, title_size=title_size, header_h=header_h, accent_h=accent_h,
|
||||
accent_start=theme["accent_hex"], weather_size=weather_size,
|
||||
unit_suffix=unit_suffix, row_h=row_h, body_size=body_size,
|
||||
)
|
||||
rendered = html_render.render_html_to_image(html, target_w, target_h)
|
||||
accent_regions = [
|
||||
((gutter, gutter + i * section_h, target_w - gutter, gutter + i * section_h + accent_h),
|
||||
theme["accent_amplitude"])
|
||||
for i in range(len(day_sections))
|
||||
]
|
||||
return html_render.ordered_dither_regions(rendered, palette_rgb, accent_regions=accent_regions)
|
||||
|
||||
header_size = panel_style.scaled_size(max(10, min(16, (target_w // days) // 6)), font_scale)
|
||||
chip_size = max(9, header_size - 3)
|
||||
weather_size = max(8, chip_size - 1)
|
||||
col_w = max(1, (target_w - panel_style.GUTTER * 2) // days)
|
||||
row_h = chip_size + 8
|
||||
accent_h = round(html_render._clamp(min(target_w, target_h) * 0.02, 3, 6))
|
||||
# Reserve weather-line room in every column's header uniformly
|
||||
# (whether or not THIS specific day has a cached forecast) -- a
|
||||
# per-column height that depends on that day's own data would
|
||||
# misalign where each column's event rows start across the week
|
||||
# grid the moment any single day lacks a forecast entry.
|
||||
header_h = header_size + 8 + (weather_size + 4 if weather_cities else 0)
|
||||
max_rows = max(0, (target_h - panel_style.GUTTER * 2 - accent_h - 6 - header_h) // row_h)
|
||||
|
||||
cols = []
|
||||
for i in range(days):
|
||||
day = week_first_day + timedelta(days=i)
|
||||
label = day.strftime("%a %-d") if day != today else f"★ {day.strftime('%a %-d')}"
|
||||
weather_entries = _weather_row(weather_cities, day, weather_units)
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
rows = []
|
||||
for event in day_events[:max_rows]:
|
||||
color = html_render._rgb_to_hex(_event_colors(event, owners_seen, palette_rgb)[0])
|
||||
summary = event["summary"] if event["all_day"] else f"{_fmt_time(_event_start(event, tz))[:-3]} {event['summary']}"
|
||||
rows.append({"color": color, "summary": summary})
|
||||
cols.append({
|
||||
"label": label, "weather": weather_entries[0] if weather_entries else None,
|
||||
"rows": rows, "more_count": max(0, len(day_events) - max_rows),
|
||||
})
|
||||
|
||||
template = html_render._jinja_env.get_template("calendar_week_horizontal.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=gutter,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
cols=cols, header_size=header_size, chip_size=chip_size,
|
||||
header_h=header_h, accent_h=accent_h, weather_size=weather_size, unit_suffix=unit_suffix,
|
||||
accent_start=theme["accent_hex"],
|
||||
)
|
||||
rendered = html_render.render_html_to_image(html, target_w, target_h)
|
||||
accent_rect = (gutter, gutter, target_w - gutter, gutter + accent_h)
|
||||
return html_render.ordered_dither_regions(rendered, palette_rgb, accent_regions=[(accent_rect, theme["accent_amplitude"])])
|
||||
|
||||
|
||||
def build_month(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
week_start: int, palette_rgb: list | None = None, theme_name: str | None = None,
|
||||
font_scale: float = 1.0) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of calendar_render._build_month --
|
||||
density dots per day, not literal event text, same reasoning as the
|
||||
classic renderer (real text at typical month-cell size is close to
|
||||
unreadable on a 6-color dithered e-ink panel). The per-owner event
|
||||
dots are identity-coding (like every other calendar view's chips) and
|
||||
are never touched by a theme.
|
||||
|
||||
Bold-minimal: no card (see build_agenda's docstring); the old flat
|
||||
accent-colored weekday-name band is now a slim accent rule above
|
||||
plain bold weekday labels, matching every other calendar view's
|
||||
header treatment -- only that rule dithers at the theme's richer
|
||||
accent_amplitude via ordered_dither_regions. "Today" is still called
|
||||
out with a small accent-filled pill around its day number (a
|
||||
genuinely small accent surface, not a band, so it was left alone)."""
|
||||
theme = theme_tokens.resolve_theme(theme_name, "calendar", palette_rgb)
|
||||
gutter = panel_style.GUTTER
|
||||
today = datetime.now(tz).date()
|
||||
target_month = _add_months(date(today.year, today.month, 1), browse_offset)
|
||||
weeks_dates = list(
|
||||
calendar_module.Calendar(firstweekday=week_start).monthdatescalendar(target_month.year, target_month.month)
|
||||
)
|
||||
day_names = [n[:3] for n in (WEEKDAY_NAMES[week_start:] + WEEKDAY_NAMES[:week_start])]
|
||||
|
||||
header_size = panel_style.scaled_size(max(11, min(16, target_h // 30)), font_scale)
|
||||
day_size = panel_style.scaled_size(max(10, min(15, target_w // 55)), font_scale)
|
||||
dot_size = max(4, day_size // 2)
|
||||
accent_h = round(html_render._clamp(min(target_w, target_h) * 0.02, 3, 6))
|
||||
|
||||
owners_seen: list[str] = []
|
||||
weeks = []
|
||||
for week in weeks_dates:
|
||||
row = []
|
||||
for day in week:
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
dots = [html_render._rgb_to_hex(_event_colors(e, owners_seen, palette_rgb)[0]) for e in day_events[:4]]
|
||||
row.append({
|
||||
"day_num": day.day, "in_month": day.month == target_month.month,
|
||||
"is_today": day == today, "dots": dots, "more_count": max(0, len(day_events) - 4),
|
||||
})
|
||||
weeks.append(row)
|
||||
|
||||
template = html_render._jinja_env.get_template("calendar_month.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=gutter,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
day_names=day_names, weeks=weeks, accent_h=accent_h,
|
||||
header_size=header_size, day_size=day_size, dot_size=dot_size, accent_start=theme["accent_hex"],
|
||||
)
|
||||
rendered = html_render.render_html_to_image(html, target_w, target_h)
|
||||
accent_rect = (gutter, gutter, target_w - gutter, gutter + accent_h)
|
||||
return html_render.ordered_dither_regions(rendered, palette_rgb,
|
||||
accent_regions=[(accent_rect, theme["accent_amplitude"])])
|
||||
|
||||
|
||||
def build(events: list[dict], view: str, browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
week_start: int, palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", week_days: int = 7, week_layout: str = "horizontal",
|
||||
week_start_offset: int = 0, theme_name: str | None = None, font_scale: float = 1.0) -> Image.Image:
|
||||
"""Dispatches to the right build_* -- mirrors calendar_render._build's
|
||||
exact "month falls back to agenda when it doesn't fit" resolution, so
|
||||
a narrow month-mode widget set to modern style still gets a sensible
|
||||
modern view instead of erroring or silently reverting to classic."""
|
||||
effective_view = view
|
||||
if view == "month" and not _month_view_fits(target_w, target_h):
|
||||
effective_view = "agenda"
|
||||
|
||||
if effective_view == "agenda":
|
||||
return build_agenda(events, browse_offset, target_w, target_h, tz, palette_rgb, weather_cities,
|
||||
weather_units, theme_name, font_scale)
|
||||
if effective_view == "today_tomorrow":
|
||||
return build_today_tomorrow(events, browse_offset, target_w, target_h, tz, palette_rgb, weather_cities,
|
||||
weather_units, theme_name, font_scale)
|
||||
if effective_view == "week":
|
||||
return build_week(events, browse_offset, target_w, target_h, tz, week_start, palette_rgb, weather_cities,
|
||||
weather_units, week_days, week_layout, week_start_offset, theme_name, font_scale)
|
||||
return build_month(events, browse_offset, target_w, target_h, tz, week_start, palette_rgb, theme_name, font_scale)
|
||||
+716
-125
@@ -1,50 +1,103 @@
|
||||
"""Renders calendar frame mode's three views (agenda/week/month) into the
|
||||
panel's packed format, following image_pipeline.render_placeholder's own
|
||||
precedent: build an RGB canvas with ImageDraw/ImageFont, then the same
|
||||
_quantize/_transpose_and_pack every other renderer ends on.
|
||||
"""Renders calendar frame mode's three views (agenda/week/month), and the
|
||||
separate standalone tasks widget (see models.TaskWidgetConfig -- a task
|
||||
list used to be a calendar-widget-only week-view slot, split out into
|
||||
its own widget type so it isn't tied to a calendar's view/footprint),
|
||||
into the panel's packed format, following image_pipeline.
|
||||
render_placeholder's own precedent: build an RGB canvas with
|
||||
ImageDraw/ImageFont, then the same _quantize/_transpose_and_pack every
|
||||
other renderer ends on.
|
||||
|
||||
Event dicts here are calendar_feed.py's shape: {"summary", "start", "end"
|
||||
(ISO 8601 strings), "all_day", "owner_display_name"}.
|
||||
(ISO 8601 strings), "all_day", "sources": [{"owner_display_name",
|
||||
"color_index"}, ...]} -- more than one entry in "sources" means
|
||||
merge_events collapsed several calendars' identical (same title/time)
|
||||
events into one, see _event_colors/panel_style.draw_color_chip below.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar as calendar_module
|
||||
import io
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from . import panel_style
|
||||
from .image_pipeline import (
|
||||
DEFAULT_PALETTE_RGB,
|
||||
_apply_manage_overlay,
|
||||
_quantize,
|
||||
_transpose_and_pack,
|
||||
compose_into,
|
||||
draw_text,
|
||||
logical_render_size,
|
||||
)
|
||||
from .weather import weather_category
|
||||
from .weather_render import draw_weather_row
|
||||
|
||||
CALENDAR_VIEWS = ["agenda", "week", "month"]
|
||||
CALENDAR_VIEW_LABELS = {"agenda": "Agenda (today)", "week": "Week", "month": "Month"}
|
||||
CALENDAR_VIEWS = ["agenda", "today_tomorrow", "week", "month"]
|
||||
CALENDAR_VIEW_LABELS = {"agenda": "Agenda (today)", "today_tomorrow": "Agenda (today & tomorrow)",
|
||||
"week": "Week", "month": "Month"}
|
||||
WEEKDAY_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
|
||||
|
||||
MARGIN = 20
|
||||
# MARGIN carries panel_style.CONTENT_MARGIN's value unchanged (not
|
||||
# re-tuned). BG/FG are this module's own plain black/white -- checkbox
|
||||
# outlines, month-view grid hairlines -- not a text-emphasis concern (no
|
||||
# MUTED gray here anymore -- see panel_style's module docstring for why:
|
||||
# a mid-gray fill has no close palette match and dithers into speckle
|
||||
# once the whole canvas is quantized. Secondary text now reads through
|
||||
# size/weight alone, always exact black).
|
||||
MARGIN = panel_style.CONTENT_MARGIN
|
||||
BG = (255, 255, 255)
|
||||
FG = (0, 0, 0)
|
||||
MUTED = (110, 110, 110)
|
||||
RULE = (200, 200, 200)
|
||||
# Structural dividers/grid lines (between stacked day sections, week
|
||||
# columns, month cells) stay a plain black rule -- gray dithers away to
|
||||
# near-invisible once quantized to the 6-color e-ink palette. Headers
|
||||
# no longer use this: see panel_style.draw_header_bar/theme_color.
|
||||
RULE = (0, 0, 0)
|
||||
|
||||
# Cycled per distinct owner_display_name so a merged multi-person calendar
|
||||
# can visually tell whose event is whose -- the panel's own non-black/
|
||||
# white ink colors, skipping black/white (index 0/1 in DEFAULT_PALETTE_RGB)
|
||||
# since those are already the page's text/background.
|
||||
# Fallback for any event whose calendar has no manually pinned color
|
||||
# (event["color_index"] is None): cycled per distinct owner_display_name
|
||||
# so a merged multi-person calendar can still visually tell whose event
|
||||
# is whose -- the panel's own non-black/white ink colors, skipping
|
||||
# black/white (index 0/1 in DEFAULT_PALETTE_RGB) since those are already
|
||||
# the page's text/background.
|
||||
OWNER_COLORS = DEFAULT_PALETTE_RGB[2:]
|
||||
|
||||
|
||||
def _owner_color(owner_display_name: str, owners_seen: list[str]) -> tuple[int, int, int]:
|
||||
if owner_display_name not in owners_seen:
|
||||
owners_seen.append(owner_display_name)
|
||||
return OWNER_COLORS[owners_seen.index(owner_display_name) % len(OWNER_COLORS)]
|
||||
def _event_colors(event: dict, owners_seen: list[str], palette_rgb: list | None) -> list[tuple[int, int, int]]:
|
||||
"""One color per contributing calendar (event["sources"] -- see
|
||||
calendar_feed.merge_events, which collapses events sharing the exact
|
||||
same title/time across different calendars into one entry with
|
||||
several sources, e.g. a shared family event synced onto more than
|
||||
one person's calendar). Usually just one color; more than one is
|
||||
what tells the "same event, more than one calendar" case apart from
|
||||
an ordinary single-calendar event at render time -- see
|
||||
panel_style.draw_color_chip. Each source's own manually pinned color
|
||||
(FrameCalendar.color_index -- see routers/api_widgets.py's
|
||||
api_widget_calendar_color) resolves against whichever palette this frame
|
||||
actually renders with, so a pinned "Blue" stays this frame's actual
|
||||
blue; a source with no color pinned falls back to the old
|
||||
auto-cycle-by-owner-name behavior. owners_seen is shared across every
|
||||
event/source in a render so that cycle stays consistent view-wide."""
|
||||
sources = event.get("sources") or [
|
||||
{"owner_display_name": event.get("owner_display_name"), "color_index": event.get("color_index")}
|
||||
]
|
||||
colors = []
|
||||
for source in sources:
|
||||
color_index = source.get("color_index")
|
||||
if color_index is not None:
|
||||
palette = palette_rgb or DEFAULT_PALETTE_RGB
|
||||
colors.append(tuple(palette[color_index]))
|
||||
continue
|
||||
owner_display_name = source.get("owner_display_name")
|
||||
if owner_display_name not in owners_seen:
|
||||
owners_seen.append(owner_display_name)
|
||||
colors.append(OWNER_COLORS[owners_seen.index(owner_display_name) % len(OWNER_COLORS)])
|
||||
return colors
|
||||
|
||||
|
||||
def _event_start(event: dict, tz: ZoneInfo) -> datetime | date:
|
||||
@@ -82,11 +135,184 @@ def _fmt_time(dt: datetime) -> str:
|
||||
return text if text else "12:00 AM"
|
||||
|
||||
|
||||
def _fmt_task_due(due: str | None) -> str:
|
||||
""""2026-07-25" or "2026-07-25T14:00:00+00:00" -> "Jul 25" -- tasks
|
||||
only need a compact reminder of when they're due, not the precision
|
||||
an event's own start/end time gets."""
|
||||
if not due:
|
||||
return ""
|
||||
try:
|
||||
dt = datetime.fromisoformat(due)
|
||||
except ValueError:
|
||||
return ""
|
||||
d = dt.date() if isinstance(dt, datetime) else dt
|
||||
return d.strftime("%b %-d")
|
||||
|
||||
|
||||
# Neither Inter (panel_style.font_bold/font_regular, this module's own
|
||||
# body/title font -- see MARGIN/BG/FG comment above) nor PIL's bundled
|
||||
# default font has emoji glyphs, and PIL/FreeType don't skip an
|
||||
# unsupported codepoint, they substitute a ".notdef" tofu box (a visible
|
||||
# filled rectangle) -- reads as a rendering glitch, not "emoji not
|
||||
# supported". So event titles get drawn with two fonts: the normal
|
||||
# text font for everything else, and one of these for actual emoji runs
|
||||
# (see _split_emoji_runs/_draw_mixed_line) -- both Noto Emoji, OFL-1.1,
|
||||
# vendored at app/fonts/ (license alongside at app/fonts/OFL.txt).
|
||||
#
|
||||
# Color (NotoColorEmoji.ttf) is tried first: full-color CBDT bitmap
|
||||
# glyphs, which the panel's own Floyd-Steinberg dithering turns into a
|
||||
# recognizable (if slightly speckled) color rendering rather than a flat
|
||||
# monochrome shape -- confirmed by actually rendering a test agenda row
|
||||
# through the real quantizer, not just theorizing about it. Its one
|
||||
# real quirk: CBDT stores glyphs at a single embedded bitmap size
|
||||
# (_COLOR_EMOJI_NATIVE_SIZE), so every glyph is rasterized once at that
|
||||
# size and scaled down to the target row height, unlike normal vector
|
||||
# text which draws directly at whatever size is asked for.
|
||||
#
|
||||
# NotoEmoji.ttf (monochrome, vector) is the fallback for a deployment
|
||||
# whose Pillow/FreeType wasn't built with embedded color bitmap support
|
||||
# -- confirmed working locally, but that's a build-time detail this
|
||||
# project doesn't control everywhere it might run, so a rendering
|
||||
# failure falls back instead of showing nothing/crashing.
|
||||
_COLOR_EMOJI_FONT_PATH = Path(__file__).parent / "fonts" / "NotoColorEmoji.ttf"
|
||||
_MONO_EMOJI_FONT_PATH = Path(__file__).parent / "fonts" / "NotoEmoji.ttf"
|
||||
_COLOR_EMOJI_NATIVE_SIZE = 109
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _color_emoji_font() -> ImageFont.FreeTypeFont | None:
|
||||
try:
|
||||
return ImageFont.truetype(str(_COLOR_EMOJI_FONT_PATH), _COLOR_EMOJI_NATIVE_SIZE)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _mono_emoji_font(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(_MONO_EMOJI_FONT_PATH), size)
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def _emoji_glyph(run_text: str, target_h: int) -> Image.Image:
|
||||
"""One emoji run (consecutive emoji collapse into a single run, see
|
||||
_split_emoji_runs) as an RGBA image target_h tall, ready to
|
||||
alpha-composite onto the canvas. Tries color first, falls back to
|
||||
monochrome (rendered directly at target_h, since that font is
|
||||
vector) if the color font failed to load or this Pillow/FreeType
|
||||
build can't decode its embedded bitmaps. Cached -- the same emoji
|
||||
recurs across a household's events, and rasterizing+scaling isn't
|
||||
free."""
|
||||
color_font = _color_emoji_font()
|
||||
if color_font is not None:
|
||||
try:
|
||||
probe = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
|
||||
raw_w = max(1, round(probe.textlength(run_text, font=color_font)))
|
||||
tmp = Image.new("RGBA", (raw_w, _COLOR_EMOJI_NATIVE_SIZE), (255, 255, 255, 0))
|
||||
ImageDraw.Draw(tmp).text((0, 0), run_text, font=color_font, embedded_color=True)
|
||||
scale = target_h / _COLOR_EMOJI_NATIVE_SIZE
|
||||
return tmp.resize((max(1, round(raw_w * scale)), target_h), Image.LANCZOS)
|
||||
except Exception:
|
||||
pass # this deployment's Pillow can't render embedded color bitmaps -- fall back
|
||||
|
||||
mono_font = _mono_emoji_font(target_h)
|
||||
bbox = mono_font.getbbox(run_text)
|
||||
w, h = max(1, bbox[2] - bbox[0]), max(1, bbox[3] - bbox[1])
|
||||
mask = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(mask).text((-bbox[0], -bbox[1]), run_text, fill=255, font=mono_font)
|
||||
glyph = Image.new("RGBA", (w, h), (255, 255, 255, 0))
|
||||
glyph.paste((0, 0, 0, 255), (0, 0), mask)
|
||||
return glyph
|
||||
|
||||
|
||||
# Matches runs of actual emoji base characters (the standard Unicode
|
||||
# emoji blocks -- stable ranges even as new individual emoji get added
|
||||
# within them, so this doesn't need updating as emoji sets grow).
|
||||
_EMOJI_PATTERN = re.compile(
|
||||
"["
|
||||
"\U0001F1E6-\U0001F1FF" # regional indicator symbols (flag emoji)
|
||||
"\U0001F300-\U0001F5FF" # misc symbols & pictographs
|
||||
"\U0001F600-\U0001F64F" # emoticons
|
||||
"\U0001F680-\U0001F6FF" # transport & map symbols
|
||||
"\U0001F900-\U0001F9FF" # supplemental symbols & pictographs
|
||||
"\U0001FA70-\U0001FAFF" # symbols & pictographs extended-A
|
||||
"\U00002600-\U000026FF" # misc symbols (☀☂☕ etc.)
|
||||
"\U00002700-\U000027BF" # dingbats (✂✈✉ etc.)
|
||||
"]+"
|
||||
)
|
||||
_EMOJI_SPLIT_PATTERN = re.compile(f"({_EMOJI_PATTERN.pattern})")
|
||||
# Codepoints with no meaningful standalone glyph once color/ligature
|
||||
# context is dropped: skin-tone modifiers (this is monochrome -- no
|
||||
# color to modify), the variation selector that just requests emoji
|
||||
# presentation, and the zero-width joiner used to fuse multiple emoji
|
||||
# into one combined glyph. That fusion (e.g. the "family" emoji from
|
||||
# four base emoji + 3 ZWJs) needs OpenType ligature substitution
|
||||
# (raqm/harfbuzz), which Pillow only does with a specific, non-default
|
||||
# build -- not something to depend on. Stripping the ZWJ instead means a
|
||||
# ZWJ sequence just draws as its individual base glyphs side by side
|
||||
# (four separate people instead of one family glyph) -- a real fallback,
|
||||
# not a crash or tofu.
|
||||
_EMOJI_MODIFIER_PATTERN = re.compile("[\U0001F3FB-\U0001F3FF\U0000FE0F\U0000200D]")
|
||||
|
||||
|
||||
def _split_emoji_runs(text: str) -> list[tuple[str, bool]]:
|
||||
"""text -> [(run, is_emoji), ...], modifier/joiner codepoints
|
||||
dropped first (see _EMOJI_MODIFIER_PATTERN). Consecutive emoji
|
||||
collapse into one run (_EMOJI_PATTERN's own "+"), consecutive
|
||||
plain-text characters into the other."""
|
||||
cleaned = _EMOJI_MODIFIER_PATTERN.sub("", text)
|
||||
parts = [p for p in _EMOJI_SPLIT_PATTERN.split(cleaned) if p]
|
||||
return [(p, bool(_EMOJI_PATTERN.fullmatch(p))) for p in parts]
|
||||
|
||||
|
||||
def _draw_mixed_line(img: Image.Image, draw: ImageDraw.ImageDraw, xy: tuple[int, int], text: str,
|
||||
text_font: ImageFont.ImageFont, max_width: int, fill: tuple[int, int, int] = FG) -> None:
|
||||
"""Draws `text` left-to-right, switching between text_font (normal
|
||||
characters) and an emoji glyph image (actual emoji runs, per
|
||||
_split_emoji_runs/_emoji_glyph) so emoji visibly render instead of a
|
||||
tofu box. Truncates with "..." once max_width is exceeded -- unlike
|
||||
_truncate_to_width this can't binary-search a single font's metrics
|
||||
across mixed fonts/images, so it works run-by-run instead (and can't
|
||||
partially truncate an emoji run the way it can a text run -- one
|
||||
that doesn't fit just isn't drawn). Fine for the short single-line
|
||||
strings this draws (event/task titles), not meant as a general
|
||||
rich-text layout engine. `fill` only affects text runs -- emoji
|
||||
glyphs are already their own color."""
|
||||
x, y = xy
|
||||
cursor = x
|
||||
# A little taller than text_font's own size so glyphs don't look
|
||||
# cramped next to it; the -2 paste offset below roughly centers that
|
||||
# against the surrounding text's row -- tuned by eye against a real
|
||||
# rendered agenda row, not derived from font metrics.
|
||||
emoji_h = text_font.size + 6
|
||||
for run_text, is_emoji in _split_emoji_runs(text):
|
||||
remaining = max_width - (cursor - x)
|
||||
if remaining <= 0:
|
||||
break
|
||||
if is_emoji:
|
||||
glyph = _emoji_glyph(run_text, emoji_h)
|
||||
if glyph.width <= remaining:
|
||||
img.paste(glyph, (round(cursor), y - 2), glyph)
|
||||
cursor += glyph.width
|
||||
else:
|
||||
break
|
||||
else:
|
||||
run_w = draw.textlength(run_text, font=text_font)
|
||||
if run_w <= remaining:
|
||||
draw_text(img, (round(cursor), y), run_text, text_font, fill)
|
||||
cursor += run_w
|
||||
else:
|
||||
draw_text(img, (round(cursor), y), _truncate_to_width(draw, run_text, text_font, remaining),
|
||||
text_font, fill)
|
||||
break
|
||||
|
||||
|
||||
def _truncate_to_width(draw: ImageDraw.ImageDraw, text: str, font: ImageFont.ImageFont, max_width: int) -> str:
|
||||
"""Pixel-width-aware truncation (unlike device.py's char-count
|
||||
_truncate, tuned for a fixed firmware font at a fixed size) -- this
|
||||
module draws at several different sizes, so truncation has to
|
||||
measure the actual font/size in play."""
|
||||
measure the actual font/size in play. Still uses `draw.textlength`
|
||||
for measurement (identical metrics to draw_text's own bbox), just
|
||||
doesn't paint anything."""
|
||||
if draw.textlength(text, font=font) <= max_width:
|
||||
return text
|
||||
ellipsis = "..."
|
||||
@@ -100,191 +326,556 @@ def _truncate_to_width(draw: ImageDraw.ImageDraw, text: str, font: ImageFont.Ima
|
||||
return text[:lo] + ellipsis if lo else ellipsis
|
||||
|
||||
|
||||
def _build_agenda(events: list[dict], browse_offset: int, orientation: str, tz: ZoneInfo,
|
||||
photo_inlay: Image.Image | None) -> Image.Image:
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
img = Image.new("RGB", (logical_w, logical_h), BG)
|
||||
# --- Size tiers ---------------------------------------------------------
|
||||
#
|
||||
# A calendar widget can now be placed at any grid footprint (see
|
||||
# app/grid.py), not just the full panel -- these three discrete tiers
|
||||
# (chosen by nearest-fit against the target box's pixel area) drive font
|
||||
# sizes/margins instead of continuously scaling a layout that was tuned
|
||||
# by eye for the full ~800x480 panel, which would risk ugly proportions
|
||||
# at odd in-between sizes. Area-based (not width/height-based) so the
|
||||
# same footprint tiers the same regardless of landscape/portrait target
|
||||
# box shape.
|
||||
_TIER_LARGE_AREA = 280_000 # near/at a full 800x480 panel (384,000px^2)
|
||||
_TIER_MEDIUM_AREA = 120_000 # roughly a half-panel split
|
||||
|
||||
text_x0 = MARGIN
|
||||
text_w = logical_w - MARGIN * 2
|
||||
if photo_inlay is not None:
|
||||
# Long axis split: landscape splits left/right, portrait top/bottom.
|
||||
if logical_w >= logical_h:
|
||||
photo_w = logical_w // 2
|
||||
photo = compose_into(photo_inlay, None, photo_w, logical_h, "crop_fill")
|
||||
img.paste(photo, (0, 0))
|
||||
text_x0 = photo_w + MARGIN
|
||||
text_w = logical_w - photo_w - MARGIN * 2
|
||||
else:
|
||||
photo_h = logical_h // 2
|
||||
photo = compose_into(photo_inlay, None, logical_w, photo_h, "crop_fill")
|
||||
img.paste(photo, (0, 0))
|
||||
|
||||
draw = ImageDraw.Draw(img)
|
||||
# Smaller title when the inlay halves the available width -- "Wednesday,
|
||||
# July 22" at full size doesn't fit ~360px, and a *narrower* column is
|
||||
# exactly when a smaller font (rather than truncating to "Wednesday...")
|
||||
# keeps it actually informative.
|
||||
title_font = ImageFont.load_default(size=34 if photo_inlay is None else 24)
|
||||
body_font = ImageFont.load_default(size=22)
|
||||
def _size_tier(target_w: int, target_h: int) -> str:
|
||||
area = target_w * target_h
|
||||
if area >= _TIER_LARGE_AREA:
|
||||
return "large"
|
||||
if area >= _TIER_MEDIUM_AREA:
|
||||
return "medium"
|
||||
return "small"
|
||||
|
||||
text_y0 = MARGIN if photo_inlay is None or logical_w >= logical_h else logical_h // 2 + MARGIN
|
||||
day = datetime.now(tz).date() + timedelta(days=browse_offset)
|
||||
|
||||
def _month_view_fits(target_w: int, target_h: int) -> bool:
|
||||
"""Month view needs real width to keep 7 columns' day numbers and
|
||||
density dots legible -- below the "small" size tier that stops being
|
||||
true, so _build falls back to agenda view instead of drawing an
|
||||
unreadable grid."""
|
||||
return _size_tier(target_w, target_h) != "small"
|
||||
|
||||
|
||||
# --- Weather strip, agenda/today & tomorrow/week views only (never
|
||||
# month -- see _BUILDERS/_build) --------------------------------------
|
||||
|
||||
def _weather_for_day(weather_cities: list[dict] | None, day: date) -> list[dict]:
|
||||
"""[{"label", "code", "high", "low", "category"}, ...] for every
|
||||
configured city that has a cached forecast for this specific date --
|
||||
weather_cities is routers/common.py's get_or_refresh_weather() cache
|
||||
shape, [{"label", "days": {"YYYY-MM-DD": {"code","high","low"}}}]."""
|
||||
if not weather_cities:
|
||||
return []
|
||||
key = day.isoformat()
|
||||
entries = []
|
||||
for city in weather_cities:
|
||||
d = (city.get("days") or {}).get(key)
|
||||
if d is None:
|
||||
continue
|
||||
# Just the city name on-panel ("Portland", not the full
|
||||
# disambiguated "Portland, Oregon, United States") -- that fuller
|
||||
# form matters for telling apart geocoder candidates when adding
|
||||
# a city (see weather.geocode_city), not for a compact display row.
|
||||
entries.append({"label": city["label"].split(",")[0].strip(), "high": d["high"], "low": d["low"],
|
||||
"category": weather_category(d["code"])})
|
||||
return entries
|
||||
|
||||
|
||||
def _draw_agenda_day(img: Image.Image, draw: ImageDraw.ImageDraw, day: date, events: list[dict], tz: ZoneInfo,
|
||||
region: tuple[int, int, int, int], title_font: ImageFont.ImageFont,
|
||||
body_font: ImageFont.ImageFont, owners_seen: list[str], palette_rgb: list | None = None,
|
||||
weather_cities: list[dict] | None = None, weather_font: ImageFont.ImageFont | None = None,
|
||||
weather_units: str = "fahrenheit") -> None:
|
||||
"""Draws one day's header + weather strip (if any) + event rows
|
||||
within `region` (x0, y0, w, h) -- factored out of _build_agenda so
|
||||
the today-and-tomorrow view (_build_today_tomorrow) can stack two of
|
||||
these vertically without duplicating the row-layout/truncation
|
||||
logic. Weather is drawn above the event list -- eating into the same
|
||||
row budget the event count is truncated against, exactly like the
|
||||
header bar above it already does."""
|
||||
x0, y0, w, h = region
|
||||
header_h = title_font.size + 20
|
||||
panel_style.draw_header_bar(draw, (x0, y0, w, header_h), header_h,
|
||||
panel_style.theme_color("calendar", palette_rgb))
|
||||
text_x0 = x0 + MARGIN
|
||||
text_w = w - MARGIN * 2
|
||||
header = day.strftime("%A, %B ") + str(day.day)
|
||||
draw.text((text_x0, text_y0), _truncate_to_width(draw, header, title_font, text_w), fill=FG, font=title_font)
|
||||
y = text_y0 + title_font.size + 12
|
||||
draw.line([(text_x0, y), (text_x0 + text_w, y)], fill=RULE)
|
||||
y += 12
|
||||
draw_text(img, (text_x0, y0 + (header_h - title_font.size) // 2),
|
||||
_truncate_to_width(draw, header, title_font, text_w), title_font, BG)
|
||||
y = y0 + header_h + 12
|
||||
|
||||
weather_entries = _weather_for_day(weather_cities, day)
|
||||
if weather_entries:
|
||||
y += draw_weather_row(img, draw, text_x0, y, text_w, weather_entries,
|
||||
icon_r=title_font.size // 2, font=weather_font or body_font, units=weather_units,
|
||||
palette_rgb=palette_rgb)
|
||||
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
owners_seen: list[str] = []
|
||||
row_h = body_font.size + 14
|
||||
max_rows = max(0, (logical_h - MARGIN - y) // row_h)
|
||||
max_rows = max(0, (y0 + h - MARGIN - y) // row_h)
|
||||
|
||||
if not day_events:
|
||||
draw.text((text_x0, y), "Nothing scheduled", fill=MUTED, font=body_font)
|
||||
draw_text(img, (text_x0, y), "Nothing scheduled", body_font)
|
||||
for i, event in enumerate(day_events):
|
||||
if i >= max_rows:
|
||||
draw.text((text_x0, y), f"+{len(day_events) - max_rows} more", fill=MUTED, font=body_font)
|
||||
draw_text(img, (text_x0, y), f"+{len(day_events) - max_rows} more", body_font)
|
||||
break
|
||||
color = _owner_color(event["owner_display_name"], owners_seen)
|
||||
draw.rectangle([text_x0, y + 3, text_x0 + 6, y + row_h - 8], fill=color)
|
||||
colors = _event_colors(event, owners_seen, palette_rgb)
|
||||
panel_style.draw_color_chip(draw, text_x0, y + 2, text_x0 + 10, y + row_h - 7, colors)
|
||||
time_str = "All day" if event["all_day"] else _fmt_time(_event_start(event, tz))
|
||||
line = f"{time_str} {event['summary']}"
|
||||
draw.text((text_x0 + 16, y), _truncate_to_width(draw, line, body_font, text_w - 16), fill=FG, font=body_font)
|
||||
prefix = f"{time_str} "
|
||||
draw_text(img, (text_x0 + 18, y), prefix, body_font)
|
||||
prefix_w = draw.textlength(prefix, font=body_font)
|
||||
_draw_mixed_line(img, draw, (text_x0 + 18 + prefix_w, y), event["summary"],
|
||||
body_font, text_w - 18 - prefix_w)
|
||||
y += row_h
|
||||
|
||||
|
||||
def _draw_tasks(img: Image.Image, draw: ImageDraw.ImageDraw, region: tuple[int, int, int, int],
|
||||
tasks: list[dict], title_font: ImageFont.ImageFont, body_font: ImageFont.ImageFont,
|
||||
palette_rgb: list | None = None, title: str = "Tasks") -> None:
|
||||
"""A simple checklist filling `region` (x0, y0, w, h) -- a header
|
||||
(`title`, truncated to fit -- TaskWidgetConfig.name or the "Tasks"
|
||||
default; the only widget type with its own on-panel title, since
|
||||
it's the only one where "which list is this" isn't obvious from its
|
||||
content the way a calendar/photo/whiteboard's is), then a color chip
|
||||
(reusing _event_colors/panel_style.draw_color_chip as-is: a task
|
||||
dict's top-level owner_display_name/color_index is exactly
|
||||
_event_colors' single-source fallback shape, since caldav_client.
|
||||
merge_tasks doesn't cross-list-dedup tasks into a "sources" list the
|
||||
way merge_events dedups events) + checkbox glyph + due date (if any)
|
||||
+ summary per task, same header/row-cap/truncation shape as
|
||||
_draw_agenda_day's event list so the standalone tasks widget (see
|
||||
_build_tasks) reads as the same consistent design as everything
|
||||
else on-panel, not a bolted-together look. Reuses _draw_mixed_line
|
||||
so a task summary with emoji in it renders the same way an event
|
||||
title's does.
|
||||
|
||||
Outstanding tasks get an empty checkbox; completed ones (only ever
|
||||
present when TaskWidgetConfig.show_completed is on -- see
|
||||
caldav_client.fetch_tasks' completed_since) get a filled checkbox in
|
||||
this widget's own Green accent (see panel_style.THEME) -- that fill
|
||||
is the "done" signal, no due-date prefix (irrelevant once done) and
|
||||
no separate muted text treatment (see module-level MUTED removal
|
||||
note above _event_colors)."""
|
||||
x0, y0, w, h = region
|
||||
header_h = title_font.size + 20
|
||||
panel_style.draw_header_bar(draw, (x0, y0, w, header_h), header_h,
|
||||
panel_style.theme_color("tasks", palette_rgb))
|
||||
text_x0 = x0 + MARGIN
|
||||
text_w = w - MARGIN * 2
|
||||
draw_text(img, (text_x0, y0 + (header_h - title_font.size) // 2),
|
||||
_truncate_to_width(draw, title or "Tasks", title_font, text_w), title_font, BG)
|
||||
y = y0 + header_h + 12
|
||||
|
||||
row_h = body_font.size + 14
|
||||
max_rows = max(0, (y0 + h - MARGIN - y) // row_h)
|
||||
|
||||
if not tasks:
|
||||
draw_text(img, (text_x0, y), "Nothing outstanding", body_font)
|
||||
return
|
||||
owners_seen: list[str] = []
|
||||
checkbox_fill = panel_style.theme_color("tasks", palette_rgb)
|
||||
for i, task in enumerate(tasks):
|
||||
if i >= max_rows:
|
||||
draw_text(img, (text_x0, y), f"+{len(tasks) - max_rows} more", body_font)
|
||||
break
|
||||
done = task.get("completed_at") is not None
|
||||
colors = _event_colors(task, owners_seen, palette_rgb)
|
||||
panel_style.draw_color_chip(draw, text_x0, y + 2, text_x0 + 10, y + row_h - 7, colors)
|
||||
box = body_font.size - 6
|
||||
box_x = text_x0 + 18
|
||||
box_y = y + (row_h - box) // 2 - 5
|
||||
box_r = min(panel_style.CHIP_RADIUS, box // 2)
|
||||
if done:
|
||||
draw.rounded_rectangle([box_x, box_y, box_x + box, box_y + box], radius=box_r, fill=checkbox_fill)
|
||||
else:
|
||||
draw.rounded_rectangle([box_x, box_y, box_x + box, box_y + box], radius=box_r, outline=FG, width=2)
|
||||
text_x = box_x + box + 10
|
||||
due_str = None if done else _fmt_task_due(task.get("due"))
|
||||
prefix = f"{due_str} " if due_str else ""
|
||||
if prefix:
|
||||
draw_text(img, (text_x, y), prefix, body_font)
|
||||
prefix_w = draw.textlength(prefix, font=body_font) if prefix else 0
|
||||
_draw_mixed_line(img, draw, (round(text_x + prefix_w), y), task["summary"],
|
||||
body_font, text_w - (text_x - text_x0) - prefix_w)
|
||||
y += row_h
|
||||
|
||||
|
||||
# Per-tier (title, body, weather) font sizes -- "Wednesday, July 22" at
|
||||
# full size doesn't fit a narrow column, and a narrower box is exactly
|
||||
# when a smaller font (rather than truncating to "Wednesday...") keeps
|
||||
# the header actually informative.
|
||||
_AGENDA_FONTS = {"large": (34, 22, 20), "medium": (24, 22, 16), "small": (18, 16, 13)}
|
||||
|
||||
|
||||
def _build_agenda(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", font_scale: float = 1.0) -> Image.Image:
|
||||
img, draw, region = panel_style.card_canvas(target_w, target_h)
|
||||
|
||||
title_size, body_size, weather_size = (
|
||||
panel_style.scaled_size(v, font_scale) for v in _AGENDA_FONTS[_size_tier(target_w, target_h)]
|
||||
)
|
||||
title_font = panel_style.font_bold(title_size)
|
||||
body_font = panel_style.font_regular(body_size)
|
||||
weather_font = panel_style.font_regular(weather_size)
|
||||
|
||||
day = datetime.now(tz).date() + timedelta(days=browse_offset)
|
||||
owners_seen: list[str] = []
|
||||
_draw_agenda_day(img, draw, day, events, tz, region, title_font, body_font, owners_seen,
|
||||
palette_rgb, weather_cities, weather_font, weather_units)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def _build_week(events: list[dict], browse_offset: int, orientation: str, tz: ZoneInfo) -> Image.Image:
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
img = Image.new("RGB", (logical_w, logical_h), BG)
|
||||
draw = ImageDraw.Draw(img)
|
||||
_TODAY_TOMORROW_FONTS = {"large": (26, 18, 16), "medium": (20, 15, 13), "small": (15, 12, 10)}
|
||||
|
||||
header_font = ImageFont.load_default(size=18)
|
||||
chip_font = ImageFont.load_default(size=14)
|
||||
|
||||
def _build_today_tomorrow(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
palette_rgb: list | None = None, weather_cities: list[dict] | None = None,
|
||||
weather_units: str = "fahrenheit", font_scale: float = 1.0) -> Image.Image:
|
||||
"""Two _draw_agenda_day sections stacked vertically (below each other
|
||||
rather than side-by-side -- narrower than tall doesn't leave enough
|
||||
width per day for the event-row text at smaller sizes). browse_offset
|
||||
shifts the whole two-day window together, same "days" unit
|
||||
_build_agenda already uses, so NEXT/BACK behaves identically across
|
||||
both views."""
|
||||
img, draw, (cx0, cy0, cw, ch) = panel_style.card_canvas(target_w, target_h)
|
||||
|
||||
title_size, body_size, weather_size = (
|
||||
panel_style.scaled_size(v, font_scale) for v in _TODAY_TOMORROW_FONTS[_size_tier(target_w, target_h)]
|
||||
)
|
||||
title_font = panel_style.font_bold(title_size)
|
||||
body_font = panel_style.font_regular(body_size)
|
||||
weather_font = panel_style.font_regular(weather_size)
|
||||
|
||||
start_day = datetime.now(tz).date() + timedelta(days=browse_offset)
|
||||
section_h = ch // 2
|
||||
owners_seen: list[str] = []
|
||||
for i in range(2):
|
||||
section_y0 = cy0 + i * section_h
|
||||
if i > 0:
|
||||
draw.line([(cx0 + MARGIN, section_y0), (cx0 + cw - MARGIN, section_y0)], fill=RULE)
|
||||
_draw_agenda_day(img, draw, start_day + timedelta(days=i), events, tz,
|
||||
(cx0, section_y0, cw, section_h), title_font, body_font, owners_seen,
|
||||
palette_rgb, weather_cities, weather_font, weather_units)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
# Vertical layout's base (title, body, weather) sizes, before the
|
||||
# per-day-count reduction below -- same three tiers as every other view.
|
||||
_WEEK_VERTICAL_FONTS = {"large": (26, 18, 16), "medium": (20, 15, 13), "small": (16, 12, 10)}
|
||||
# Horizontal layout's (header, chip, weather) sizes.
|
||||
_WEEK_HORIZONTAL_FONTS = {"large": (18, 14, 12), "medium": (14, 12, 10), "small": (11, 10, 8)}
|
||||
|
||||
|
||||
def _build_week(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
week_start: int, palette_rgb: list | None = None,
|
||||
weather_cities: list[dict] | None = None, weather_units: str = "fahrenheit",
|
||||
days: int = 7, layout: str = "horizontal",
|
||||
start_offset: int = 0, font_scale: float = 1.0) -> Image.Image:
|
||||
"""`days` (2-10, see routers/api_widgets.py's clamp) side-by-side
|
||||
columns (layout="horizontal", the original fixed-at-7 behavior
|
||||
generalized) or stacked bands (layout="vertical", reusing
|
||||
_draw_agenda_day the same way _build_today_tomorrow does, just for
|
||||
an arbitrary day count instead of a hardcoded 2).
|
||||
|
||||
At the default 7 days, the view anchors to week_start (a fixed
|
||||
weekday, "start on the most recent Monday") exactly like before --
|
||||
otherwise "start of the week" doesn't mean much for an arbitrary day
|
||||
count, so it instead starts `start_offset` days from today (0 =
|
||||
today, see routers/api_widgets.py's api_widget_config_save)."""
|
||||
img, draw, (cx0, cy0, cw, ch) = panel_style.card_canvas(target_w, target_h)
|
||||
tier = _size_tier(target_w, target_h)
|
||||
|
||||
today = datetime.now(tz).date()
|
||||
week_start = today - timedelta(days=today.weekday()) + timedelta(weeks=browse_offset)
|
||||
col_w = (logical_w - MARGIN * 2) // 7
|
||||
header_h = 44
|
||||
if days == 7:
|
||||
days_since_start = (today.weekday() - week_start) % 7
|
||||
week_first_day = today - timedelta(days=days_since_start) + timedelta(days=days * browse_offset)
|
||||
else:
|
||||
week_first_day = today + timedelta(days=start_offset) + timedelta(days=days * browse_offset)
|
||||
owners_seen: list[str] = []
|
||||
|
||||
for col in range(7):
|
||||
day = week_start + timedelta(days=col)
|
||||
x0 = MARGIN + col * col_w
|
||||
if col > 0:
|
||||
draw.line([(x0, MARGIN), (x0, logical_h - MARGIN)], fill=RULE)
|
||||
label = day.strftime("%a %-d") if day != today else f"* {day.strftime('%a %-d')}"
|
||||
draw.text((x0 + 6, MARGIN), _truncate_to_width(draw, label, header_font, col_w - 10), fill=FG, font=header_font)
|
||||
if layout == "vertical":
|
||||
title_base, body_base, weather_base = _WEEK_VERTICAL_FONTS[tier]
|
||||
title_font = panel_style.font_bold(panel_style.scaled_size(max(14, title_base - days), font_scale))
|
||||
body_font = panel_style.font_regular(panel_style.scaled_size(max(11, body_base - days), font_scale))
|
||||
weather_font = panel_style.font_regular(panel_style.scaled_size(max(9, weather_base - days), font_scale))
|
||||
section_h = ch // days
|
||||
for i in range(days):
|
||||
section_y0 = cy0 + i * section_h
|
||||
if i > 0:
|
||||
draw.line([(cx0 + MARGIN, section_y0), (cx0 + cw - MARGIN, section_y0)], fill=RULE)
|
||||
day = week_first_day + timedelta(days=i)
|
||||
_draw_agenda_day(img, draw, day, events, tz, (cx0, section_y0, cw, section_h),
|
||||
title_font, body_font, owners_seen, palette_rgb,
|
||||
weather_cities, weather_font, weather_units)
|
||||
return img
|
||||
|
||||
y = MARGIN + header_h
|
||||
header_size, chip_size, weather_size = (
|
||||
panel_style.scaled_size(v, font_scale) for v in _WEEK_HORIZONTAL_FONTS[tier]
|
||||
)
|
||||
header_font = panel_style.font_bold(header_size)
|
||||
chip_font = panel_style.font_regular(chip_size)
|
||||
weather_font = panel_style.font_regular(weather_size)
|
||||
col_w = (cw - MARGIN * 2) // days
|
||||
header_h = 44
|
||||
|
||||
for col in range(days):
|
||||
day = week_first_day + timedelta(days=col)
|
||||
x0 = cx0 + MARGIN + col * col_w
|
||||
if col > 0:
|
||||
draw.line([(x0, cy0 + MARGIN), (x0, cy0 + ch - MARGIN)], fill=RULE)
|
||||
label = day.strftime("%a %-d") if day != today else f"* {day.strftime('%a %-d')}"
|
||||
draw_text(img, (x0 + 6, cy0 + MARGIN), _truncate_to_width(draw, label, header_font, col_w - 10), header_font)
|
||||
|
||||
y = cy0 + MARGIN + header_h
|
||||
# Columns are narrow, so only what actually fits gets drawn (see
|
||||
# weather_render.draw_weather_row) -- typically one city, no label
|
||||
# (the column itself makes which day it's for obvious; a city name
|
||||
# wouldn't fit anyway). Never more than that -- this is already
|
||||
# the tight view.
|
||||
weather_entries = _weather_for_day(weather_cities, day)
|
||||
if weather_entries:
|
||||
y += draw_weather_row(img, draw, x0 + 4, y, col_w - 8, weather_entries,
|
||||
icon_r=8, font=weather_font, units=weather_units, show_labels=False,
|
||||
palette_rgb=palette_rgb)
|
||||
row_h = chip_font.size + 10
|
||||
max_rows = max(0, (logical_h - MARGIN - y) // row_h)
|
||||
max_rows = max(0, (cy0 + ch - MARGIN - y) // row_h)
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
for i, event in enumerate(day_events):
|
||||
if i >= max_rows:
|
||||
draw.text((x0 + 6, y), f"+{len(day_events) - max_rows}", fill=MUTED, font=chip_font)
|
||||
draw_text(img, (x0 + 6, y), f"+{len(day_events) - max_rows}", chip_font)
|
||||
break
|
||||
color = _owner_color(event["owner_display_name"], owners_seen)
|
||||
draw.rectangle([x0 + 4, y + 2, x0 + 8, y + row_h - 6], fill=color)
|
||||
text = event["summary"] if event["all_day"] else f"{_fmt_time(_event_start(event, tz))[:-3]} {event['summary']}"
|
||||
draw.text((x0 + 14, y), _truncate_to_width(draw, text, chip_font, col_w - 18), fill=FG, font=chip_font)
|
||||
colors = _event_colors(event, owners_seen, palette_rgb)
|
||||
panel_style.draw_color_chip(draw, x0 + 4, y + 1, x0 + 11, y + row_h - 5, colors, radius=2)
|
||||
if event["all_day"]:
|
||||
_draw_mixed_line(img, draw, (x0 + 16, y), event["summary"], chip_font, col_w - 20)
|
||||
else:
|
||||
prefix = f"{_fmt_time(_event_start(event, tz))[:-3]} "
|
||||
draw_text(img, (x0 + 16, y), prefix, chip_font)
|
||||
prefix_w = draw.textlength(prefix, font=chip_font)
|
||||
_draw_mixed_line(img, draw, (x0 + 16 + prefix_w, y), event["summary"],
|
||||
chip_font, col_w - 20 - prefix_w)
|
||||
y += row_h
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def _build_month(events: list[dict], browse_offset: int, orientation: str, tz: ZoneInfo) -> Image.Image:
|
||||
# Only "large"/"medium" in practice -- _build falls back to agenda view
|
||||
# below the "small" tier (see _month_view_fits) -- but keyed defensively
|
||||
# by tier rather than a bare bool so a future tier addition can't
|
||||
# silently fall through to a KeyError here.
|
||||
_MONTH_FONTS = {"large": (16, 18), "medium": (12, 13), "small": (12, 13)}
|
||||
|
||||
|
||||
def _build_month(events: list[dict], browse_offset: int, target_w: int, target_h: int, tz: ZoneInfo,
|
||||
week_start: int, palette_rgb: list | None = None, font_scale: float = 1.0) -> Image.Image:
|
||||
"""Density dots per day, not literal event text -- real text at
|
||||
typical month-cell size (~100x70px) is close to unreadable on a
|
||||
6-color dithered e-ink panel. Capped at 4 visible dots, "+N" beyond."""
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
img = Image.new("RGB", (logical_w, logical_h), BG)
|
||||
draw = ImageDraw.Draw(img)
|
||||
6-color dithered e-ink panel. Capped at 4 visible dots, "+N" beyond.
|
||||
"Not in this month" day numbers used to be a muted gray -- now
|
||||
de-emphasized by weight instead (Regular vs. Bold), same reasoning
|
||||
as everywhere else this module dropped MUTED -- see module-level
|
||||
comment above MARGIN/BG/FG."""
|
||||
img, draw, (cx0, cy0, cw, ch) = panel_style.card_canvas(target_w, target_h)
|
||||
|
||||
header_font = ImageFont.load_default(size=16)
|
||||
day_font = ImageFont.load_default(size=18)
|
||||
header_size, day_size = (
|
||||
panel_style.scaled_size(v, font_scale) for v in _MONTH_FONTS[_size_tier(target_w, target_h)]
|
||||
)
|
||||
header_font = panel_style.font_bold(header_size)
|
||||
day_font_in_month = panel_style.font_bold(day_size)
|
||||
day_font_out_of_month = panel_style.font_regular(day_size)
|
||||
|
||||
today = datetime.now(tz).date()
|
||||
target_month = _add_months(date(today.year, today.month, 1), browse_offset)
|
||||
weeks = list(calendar_module.Calendar(firstweekday=0).monthdatescalendar(target_month.year, target_month.month))
|
||||
weeks = list(calendar_module.Calendar(firstweekday=week_start).monthdatescalendar(target_month.year, target_month.month))
|
||||
|
||||
col_w = (logical_w - MARGIN * 2) // 7
|
||||
col_w = (cw - MARGIN * 2) // 7
|
||||
header_h = 28
|
||||
grid_top = MARGIN + header_h
|
||||
row_h = (logical_h - MARGIN - grid_top) // len(weeks)
|
||||
grid_top = cy0 + MARGIN + header_h
|
||||
row_h = (cy0 + ch - MARGIN - grid_top) // len(weeks)
|
||||
today_accent = panel_style.theme_color("calendar", palette_rgb)
|
||||
today_badge_r = min(panel_style.CHIP_RADIUS, 9)
|
||||
|
||||
for col, name in enumerate(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]):
|
||||
draw.text((MARGIN + col * col_w + 6, MARGIN), name, fill=MUTED, font=header_font)
|
||||
day_names = WEEKDAY_NAMES[week_start:] + WEEKDAY_NAMES[:week_start]
|
||||
for col, name in enumerate(day_names):
|
||||
draw_text(img, (cx0 + MARGIN + col * col_w + 6, cy0 + MARGIN), name[:3], header_font)
|
||||
|
||||
owners_seen: list[str] = []
|
||||
dot_r = 4
|
||||
dot_r = 6
|
||||
for row, week in enumerate(weeks):
|
||||
for col, day in enumerate(week):
|
||||
x0 = MARGIN + col * col_w
|
||||
x0 = cx0 + MARGIN + col * col_w
|
||||
y0 = grid_top + row * row_h
|
||||
draw.rectangle([x0, y0, x0 + col_w, y0 + row_h], outline=RULE)
|
||||
in_month = day.month == target_month.month
|
||||
color = FG if in_month else MUTED
|
||||
if day == today:
|
||||
draw.rectangle([x0 + 2, y0 + 2, x0 + 24, y0 + 20], outline=FG)
|
||||
draw.text((x0 + 6, y0 + 4), str(day.day), fill=color, font=day_font)
|
||||
# A filled accent badge (this widget's own theme color,
|
||||
# see panel_style.THEME) instead of the old bare outline
|
||||
# -- an actual "today" indicator, not just an outline
|
||||
# easy to miss at ~24px. Sized around the actual digit
|
||||
# bbox (not a fixed pixel box) so a bold 2-digit day
|
||||
# number ("30") fits as comfortably as a single digit
|
||||
# ("3") at every size tier.
|
||||
day_str = str(day.day)
|
||||
text_x, text_y = x0 + 6, y0 + 4
|
||||
dbbox = draw.textbbox((text_x, text_y), day_str, font=day_font_in_month)
|
||||
pad = 3
|
||||
badge_rect = [dbbox[0] - pad, dbbox[1] - pad, dbbox[2] + pad, dbbox[3] + pad]
|
||||
badge_r = min(today_badge_r, (badge_rect[3] - badge_rect[1]) // 2)
|
||||
draw.rounded_rectangle(badge_rect, radius=badge_r, fill=today_accent)
|
||||
draw_text(img, (text_x, text_y), day_str, day_font_in_month, BG)
|
||||
else:
|
||||
day_font = day_font_in_month if in_month else day_font_out_of_month
|
||||
draw_text(img, (x0 + 6, y0 + 4), str(day.day), day_font)
|
||||
|
||||
day_events = _events_on_day(events, day, tz)
|
||||
dot_x = x0 + 8
|
||||
dot_y = y0 + row_h - 14
|
||||
dot_y = y0 + row_h - dot_r * 2 - 6
|
||||
for i, event in enumerate(day_events[:4]):
|
||||
color = _owner_color(event["owner_display_name"], owners_seen)
|
||||
draw.ellipse([dot_x, dot_y, dot_x + dot_r * 2, dot_y + dot_r * 2], fill=color)
|
||||
dot_x += dot_r * 2 + 4
|
||||
# First contributing calendar's color only, even for a
|
||||
# deduplicated shared event -- month view is density
|
||||
# dots, not a place to also show which calendars a
|
||||
# shared event came from (see _event_colors).
|
||||
event_color = _event_colors(event, owners_seen, palette_rgb)[0]
|
||||
draw.ellipse([dot_x, dot_y, dot_x + dot_r * 2, dot_y + dot_r * 2], fill=event_color)
|
||||
dot_x += dot_r * 2 + 5
|
||||
if len(day_events) > 4:
|
||||
draw.text((dot_x, dot_y - 4), f"+{len(day_events) - 4}", fill=MUTED, font=header_font)
|
||||
draw_text(img, (dot_x, dot_y - 2), f"+{len(day_events) - 4}", header_font)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
_BUILDERS = {"agenda": _build_agenda, "week": _build_week, "month": _build_month}
|
||||
_BUILDERS = {"agenda": _build_agenda, "today_tomorrow": _build_today_tomorrow, "week": _build_week,
|
||||
"month": _build_month}
|
||||
|
||||
|
||||
def _build(events: list[dict], view: str, browse_offset: int, orientation: str, timezone: str,
|
||||
photo_inlay: Image.Image | None, fetch_summary: str) -> Image.Image:
|
||||
def _build(events: list[dict], view: str, browse_offset: int, target_w: int, target_h: int, timezone: str,
|
||||
fetch_summary: str, week_start: int, palette_rgb: list | None = None,
|
||||
weather_cities: list[dict] | None = None, weather_units: str = "fahrenheit",
|
||||
week_days: int = 7, week_layout: str = "horizontal",
|
||||
week_start_offset: int = 0, font_scale: float = 1.0) -> Image.Image:
|
||||
tz = ZoneInfo(timezone) if timezone else ZoneInfo("UTC")
|
||||
builder = _BUILDERS.get(view, _build_agenda)
|
||||
if builder is _build_agenda:
|
||||
img = _build_agenda(events, browse_offset, orientation, tz, photo_inlay)
|
||||
effective_view = view
|
||||
if view == "month" and not _month_view_fits(target_w, target_h):
|
||||
effective_view = "agenda"
|
||||
|
||||
if effective_view == "agenda":
|
||||
img = _build_agenda(events, browse_offset, target_w, target_h, tz, palette_rgb,
|
||||
weather_cities, weather_units, font_scale)
|
||||
elif effective_view == "today_tomorrow":
|
||||
img = _build_today_tomorrow(events, browse_offset, target_w, target_h, tz, palette_rgb,
|
||||
weather_cities, weather_units, font_scale)
|
||||
elif effective_view == "week":
|
||||
img = _build_week(events, browse_offset, target_w, target_h, tz, week_start, palette_rgb,
|
||||
weather_cities, weather_units, week_days, week_layout, week_start_offset, font_scale)
|
||||
elif effective_view == "month":
|
||||
# Never given weather -- no room for it at typical month-cell
|
||||
# size, same reasoning that already keeps this view to density
|
||||
# dots instead of literal event text (see _build_month's own
|
||||
# docstring). Colors are still passed through, though -- that's
|
||||
# a different concern (legibility of individual events) than
|
||||
# needing a whole extra strip of content.
|
||||
img = _build_month(events, browse_offset, target_w, target_h, tz, week_start, palette_rgb, font_scale)
|
||||
else:
|
||||
img = builder(events, browse_offset, orientation, tz)
|
||||
img = _build_agenda(events, browse_offset, target_w, target_h, tz, palette_rgb,
|
||||
weather_cities, weather_units, font_scale)
|
||||
|
||||
if fetch_summary:
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = ImageFont.load_default(size=14)
|
||||
logical_w, logical_h = img.size
|
||||
draw.text((MARGIN, logical_h - MARGIN - font.size), fetch_summary, fill=MUTED, font=font)
|
||||
# Drawn as a final overlay onto the already-composited img (not
|
||||
# inside any one _build_* branch above), so it offsets by
|
||||
# panel_style.GUTTER itself to land inside the same visible
|
||||
# margin every builder's own content already respects.
|
||||
font = panel_style.font_regular(14 if _size_tier(target_w, target_h) != "small" else 11)
|
||||
draw_text(img, (panel_style.GUTTER + MARGIN, target_h - panel_style.GUTTER - MARGIN - font.size),
|
||||
fetch_summary, font)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def render_calendar(events: list[dict], view: str, browse_offset: int, orientation: str,
|
||||
palette_rgb: list | None, timezone: str, photo_inlay: Image.Image | None = None,
|
||||
fetch_summary: str = "", manage: dict | None = None) -> bytes:
|
||||
"""Renders one of CALENDAR_VIEWS to the panel's packed format. Always
|
||||
returns exactly EPD_WIDTH*EPD_HEIGHT/2 bytes, same invariant every
|
||||
other renderer honors."""
|
||||
img = _build(events, view, browse_offset, orientation, timezone, photo_inlay, fetch_summary)
|
||||
palette_rgb: list | None, timezone: str,
|
||||
fetch_summary: str = "", manage: dict | None = None, week_start: int = 0,
|
||||
weather_cities: list[dict] | None = None, weather_units: str = "fahrenheit",
|
||||
week_days: int = 7, week_layout: str = "horizontal",
|
||||
week_start_offset: int = 0) -> bytes:
|
||||
"""Renders one of CALENDAR_VIEWS full-panel to the panel's packed
|
||||
format. Always returns exactly EPD_WIDTH*EPD_HEIGHT/2 bytes, same
|
||||
invariant every other renderer honors. weather_cities is
|
||||
routers/common.py's get_or_refresh_weather() cache, or None/[] to
|
||||
omit the weather strip entirely (also always omitted for view ==
|
||||
"month")."""
|
||||
target_w, target_h = logical_render_size(orientation)
|
||||
img = _build(events, view, browse_offset, target_w, target_h, timezone, fetch_summary, week_start,
|
||||
palette_rgb, weather_cities, weather_units, week_days, week_layout, week_start_offset)
|
||||
img = _apply_manage_overlay(img, manage)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
return _transpose_and_pack(quantized, orientation)
|
||||
|
||||
|
||||
def render_calendar_preview_png(events: list[dict], view: str, browse_offset: int, orientation: str,
|
||||
palette_rgb: list | None, timezone: str, photo_inlay: Image.Image | None = None,
|
||||
fetch_summary: str = "", manage: dict | None = None) -> bytes:
|
||||
palette_rgb: list | None, timezone: str,
|
||||
fetch_summary: str = "", manage: dict | None = None, week_start: int = 0,
|
||||
weather_cities: list[dict] | None = None, weather_units: str = "fahrenheit",
|
||||
week_days: int = 7, week_layout: str = "horizontal",
|
||||
week_start_offset: int = 0, font_scale: float = 1.0) -> bytes:
|
||||
"""Same pipeline as render_calendar, but a normal browser-viewable
|
||||
PNG in logical (upright) orientation -- mirrors
|
||||
image_pipeline.render_preview_png's relationship to render_frame."""
|
||||
img = _build(events, view, browse_offset, orientation, timezone, photo_inlay, fetch_summary)
|
||||
target_w, target_h = logical_render_size(orientation)
|
||||
img = _build(events, view, browse_offset, target_w, target_h, timezone, fetch_summary, week_start,
|
||||
palette_rgb, weather_cities, weather_units, week_days, week_layout, week_start_offset, font_scale)
|
||||
img = _apply_manage_overlay(img, manage)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
buf = io.BytesIO()
|
||||
quantized.convert("RGB").save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
# --- Standalone tasks widget (split out of the old calendar-widget-only
|
||||
# week-view task list -- see models.TaskWidgetConfig) -----------------
|
||||
|
||||
_TASKS_FONTS = {"large": (24, 18), "medium": (20, 16), "small": (16, 13)}
|
||||
|
||||
|
||||
def _build_tasks(tasks: list[dict], target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
title: str = "Tasks", font_scale: float = 1.0) -> Image.Image:
|
||||
"""A tasks widget's entire region is the checklist -- unlike the old
|
||||
week-view slot, there's no day columns/header to share space with,
|
||||
so this is just _draw_tasks over the whole box."""
|
||||
img, draw, region = panel_style.card_canvas(target_w, target_h)
|
||||
title_size, body_size = (
|
||||
panel_style.scaled_size(v, font_scale) for v in _TASKS_FONTS[_size_tier(target_w, target_h)]
|
||||
)
|
||||
title_font = panel_style.font_bold(title_size)
|
||||
body_font = panel_style.font_regular(body_size)
|
||||
_draw_tasks(img, draw, region, tasks, title_font, body_font, palette_rgb, title)
|
||||
return img
|
||||
|
||||
|
||||
def render_tasks(tasks: list[dict], orientation: str, palette_rgb: list | None,
|
||||
manage: dict | None = None, title: str = "Tasks") -> bytes:
|
||||
"""Renders the tasks widget full-panel to the panel's packed format.
|
||||
Always returns exactly EPD_WIDTH*EPD_HEIGHT/2 bytes, same invariant
|
||||
every other renderer honors."""
|
||||
target_w, target_h = logical_render_size(orientation)
|
||||
img = _build_tasks(tasks, target_w, target_h, palette_rgb, title)
|
||||
img = _apply_manage_overlay(img, manage)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
return _transpose_and_pack(quantized, orientation)
|
||||
|
||||
|
||||
def render_tasks_preview_png(tasks: list[dict], orientation: str, palette_rgb: list | None,
|
||||
manage: dict | None = None, title: str = "Tasks", font_scale: float = 1.0) -> bytes:
|
||||
"""Same pipeline as render_tasks, but a normal browser-viewable PNG
|
||||
in logical (upright) orientation -- mirrors render_calendar_preview_
|
||||
png's relationship to render_calendar."""
|
||||
target_w, target_h = logical_render_size(orientation)
|
||||
img = _build_tasks(tasks, target_w, target_h, palette_rgb, title, font_scale=font_scale)
|
||||
img = _apply_manage_overlay(img, manage)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
buf = io.BytesIO()
|
||||
|
||||
+31
-1
@@ -16,7 +16,7 @@ from typing import Iterator
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from .models import Frame
|
||||
from .models import WIDGET_CONFIG_MODELS, Frame, Widget
|
||||
|
||||
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:////data/espresso.db")
|
||||
|
||||
@@ -86,3 +86,33 @@ def frame_locked(db: Session, frame_id: int) -> Iterator[Frame]:
|
||||
db.refresh(frame)
|
||||
yield frame
|
||||
db.commit()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def widget_locked(db: Session, frame_id: int, widget_id: int) -> Iterator[tuple[Frame, Widget, object]]:
|
||||
"""Same lock/refresh/commit dance as frame_locked, additionally
|
||||
resolving and refreshing the widget's own per-type config row
|
||||
(PhotoWidgetConfig/CalendarWidgetConfig/WhiteboardWidgetConfig/
|
||||
TaskWidgetConfig, see models.WIDGET_CONFIG_MODELS). Deliberately
|
||||
still locks at *frame* granularity -- the exact same per-frame
|
||||
threading.Lock frame_locked
|
||||
uses, not a separate per-widget lock -- simplest, avoids a new class
|
||||
of multi-lock deadlock bugs, and this project's actual concurrency
|
||||
needs are tiny (a handful of users per household frame).
|
||||
|
||||
threading.Lock is not reentrant: a caller executing several widget
|
||||
actions in one pass (e.g. a button press assigned multiple
|
||||
(widget, action) pairs, see routers/device.py) MUST call this once
|
||||
per action, sequentially, never nested inside an outer
|
||||
frame_locked/widget_locked span for the same frame -- nesting would
|
||||
deadlock instantly, not just misbehave."""
|
||||
with frame_locked(db, frame_id) as frame:
|
||||
widget = db.get(Widget, widget_id)
|
||||
if widget is None or widget.frame_id != frame_id:
|
||||
raise LookupError(f"Widget {widget_id} does not belong to frame {frame_id}")
|
||||
config_model = WIDGET_CONFIG_MODELS[widget.widget_type]
|
||||
config = db.get(config_model, widget_id)
|
||||
if config is None:
|
||||
raise LookupError(f"Widget {widget_id} has no {widget.widget_type} config row")
|
||||
db.refresh(config)
|
||||
yield frame, widget, config
|
||||
|
||||
@@ -25,7 +25,7 @@ MAX_LABELED_FACES = 6
|
||||
|
||||
|
||||
def compute_face_labels(preview_bytes: bytes, faces: list[dict], display_mode: str,
|
||||
orientation: str = "landscape") -> list[dict]:
|
||||
orientation: str = "landscape", region: tuple[int, int, int, int] | None = None) -> list[dict]:
|
||||
"""Returns up to MAX_LABELED_FACES [{"name", "x", "y"}], x/y in
|
||||
logical (pre-rotation) frame space at each named face's bottom-center
|
||||
point -- manage_overlay.compose() draws these directly onto the
|
||||
@@ -38,6 +38,15 @@ def compute_face_labels(preview_bytes: bytes, faces: list[dict], display_mode: s
|
||||
match the settings that were active then -- otherwise the placement
|
||||
computed here won't match what's actually on screen.
|
||||
|
||||
`region` is (x0, y0, w, h): where in the logical canvas the photo
|
||||
actually landed, if not the whole thing -- e.g. a photo widget placed
|
||||
in one corner of the panel rather than full-screen (see
|
||||
routers/common.py's build_manage_content, which passes each photo
|
||||
widget's own placement rect) -- without this a label would be placed
|
||||
as if the photo filled the entire canvas, landing well off where the
|
||||
widget actually is. None (the default) means the photo fills the
|
||||
whole logical canvas.
|
||||
|
||||
The placement math matches render_frame()'s own composition step
|
||||
exactly (see image_pipeline._placement_transform, shared so the two
|
||||
can't drift apart).
|
||||
@@ -46,11 +55,16 @@ def compute_face_labels(preview_bytes: bytes, faces: list[dict], display_mode: s
|
||||
if not named:
|
||||
return []
|
||||
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
if region is None:
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
region_x0, region_y0, target_w, target_h = 0, 0, logical_w, logical_h
|
||||
else:
|
||||
region_x0, region_y0, target_w, target_h = region
|
||||
|
||||
fitted = ImageOps.exif_transpose(Image.open(io.BytesIO(preview_bytes)).convert("RGB"))
|
||||
|
||||
scale_x, scale_y, offset_x, offset_y = _placement_transform(
|
||||
fitted.width, fitted.height, logical_w, logical_h, display_mode, faces
|
||||
fitted.width, fitted.height, target_w, target_h, display_mode, faces
|
||||
)
|
||||
|
||||
labels = []
|
||||
@@ -65,12 +79,16 @@ def compute_face_labels(preview_bytes: bytes, faces: list[dict], display_mode: s
|
||||
center_x = (face["boundingBoxX1"] + face["boundingBoxX2"]) / 2 * img_scale_x
|
||||
bottom_y = face["boundingBoxY2"] * img_scale_y
|
||||
|
||||
frame_x = center_x * scale_x + offset_x
|
||||
frame_y = bottom_y * scale_y + offset_y
|
||||
# Relative to the region's own origin first (matches
|
||||
# _placement_transform's target_w/target_h space), then shifted
|
||||
# into full-canvas coordinates.
|
||||
region_x = center_x * scale_x + offset_x
|
||||
region_y = bottom_y * scale_y + offset_y
|
||||
|
||||
if not (0 <= frame_x <= logical_w and 0 <= frame_y <= logical_h):
|
||||
continue # this face got cropped out of the final frame entirely
|
||||
if not (0 <= region_x <= target_w and 0 <= region_y <= target_h):
|
||||
continue # this face got cropped out of the region entirely
|
||||
|
||||
labels.append({"name": face["person"]["name"], "x": int(frame_x), "y": int(frame_y)})
|
||||
labels.append({"name": face["person"]["name"],
|
||||
"x": int(region_x + region_x0), "y": int(region_y + region_y0)})
|
||||
|
||||
return labels
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright (c) 2010-2013, Anton Koovit ([email protected]), with Reserved Font Name 'Arvo'
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2010 The Crimson Text Project Authors (https://github.com/googlefonts/Crimson)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2010-2020 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2013 Google LLC
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,115 @@
|
||||
"""Frame-wide actions triggered by holding NEXT/BACK past
|
||||
Frame.hold_duration_ms, instead of the per-widget action a short press
|
||||
runs (see models.FrameButtonAction, app/widgets/*.py's ACTIONS). Not
|
||||
scoped to any one widget -- e.g. cycling through the owner's saved
|
||||
layouts -- so this is its own registry rather than living in a widget
|
||||
module.
|
||||
|
||||
Each function's signature is (db, frame) -> None, the frame-level
|
||||
analogue of a widget ACTIONS entry's (db, frame, widget) -> None, and
|
||||
each is responsible for its own locking/commit internally (frame_locked/
|
||||
widget_locked), same convention as app/widgets/*.py. routers/device.py's
|
||||
/frame/global-next and /frame/global-back look up which (if any) of
|
||||
these Frame.next_hold_action/back_hold_action points to and call it,
|
||||
same "unset/unknown -> silent no-op" posture as an unbound short-press
|
||||
button."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import grid
|
||||
from .db import frame_locked
|
||||
from .models import Frame, PhotoWidgetConfig, SavedLayout, Widget
|
||||
from .routers.api_layouts import apply_layout_to_frame
|
||||
from .widgets import WIDGET_TYPES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def cycle_layout(db: Session, frame: Frame) -> None:
|
||||
"""Applies the owner's next saved layout compatible with this
|
||||
frame's current grid size, in a stable order (by id), wrapping back
|
||||
to the first past the last one. A silent no-op if the frame is
|
||||
unclaimed or its owner has no compatible saved layouts -- same
|
||||
posture as every other action here when there's nothing to do."""
|
||||
if frame.owner_user_id is None:
|
||||
return
|
||||
cols, rows = grid.grid_dims(frame.orientation)
|
||||
candidates = db.scalars(
|
||||
select(SavedLayout)
|
||||
.where(SavedLayout.user_id == frame.owner_user_id, SavedLayout.cols == cols, SavedLayout.rows == rows)
|
||||
.order_by(SavedLayout.id)
|
||||
).all()
|
||||
if not candidates:
|
||||
return
|
||||
|
||||
next_layout = candidates[0]
|
||||
if frame.last_cycled_layout_id is not None:
|
||||
for i, layout in enumerate(candidates):
|
||||
if layout.id == frame.last_cycled_layout_id:
|
||||
next_layout = candidates[(i + 1) % len(candidates)]
|
||||
break
|
||||
|
||||
apply_layout_to_frame(db, frame, next_layout)
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
locked.last_cycled_layout_id = next_layout.id
|
||||
|
||||
|
||||
def refresh_all_widgets(db: Session, frame: Frame) -> None:
|
||||
"""Runs every widget's own check_now (calendar/weather/whiteboard),
|
||||
regardless of which button it's normally bound to -- a manual "sync
|
||||
everything now" global action. One widget's failure doesn't block
|
||||
the rest, same posture as routers/device.py's _run_button_actions."""
|
||||
widgets = db.scalars(select(Widget).where(Widget.frame_id == frame.id)).all()
|
||||
for widget in widgets:
|
||||
module = WIDGET_TYPES.get(widget.widget_type)
|
||||
check_now = module.ACTIONS.get("check_now") if module else None
|
||||
if check_now is None:
|
||||
continue
|
||||
try:
|
||||
check_now(db, frame, widget)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"refresh_all_widgets failed for widget %d (frame %d)", widget.id, frame.id
|
||||
)
|
||||
|
||||
|
||||
def toggle_all_photo_locks(db: Session, frame: Frame) -> None:
|
||||
"""Flips PhotoWidgetConfig.locked for every photo widget on the frame
|
||||
at once. Target state is the opposite of "everything's already
|
||||
locked" -- one hold freezes every photo widget unless they're all
|
||||
already frozen, in which case it unfreezes all of them. A no-op if
|
||||
the frame has no photo widgets."""
|
||||
widget_ids = [
|
||||
w.id for w in db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame.id, Widget.widget_type == "photos")
|
||||
)
|
||||
]
|
||||
if not widget_ids:
|
||||
return
|
||||
configs = db.scalars(
|
||||
select(PhotoWidgetConfig).where(PhotoWidgetConfig.widget_id.in_(widget_ids))
|
||||
).all()
|
||||
if not configs:
|
||||
return
|
||||
target = not all(c.locked for c in configs)
|
||||
with frame_locked(db, frame.id):
|
||||
for config in configs:
|
||||
config.locked = target
|
||||
|
||||
|
||||
GLOBAL_ACTIONS = {
|
||||
"cycle_layout": cycle_layout,
|
||||
"refresh_all_widgets": refresh_all_widgets,
|
||||
"toggle_all_photo_locks": toggle_all_photo_locks,
|
||||
}
|
||||
|
||||
GLOBAL_ACTION_LABELS = {
|
||||
"cycle_layout": "Cycle saved layouts",
|
||||
"refresh_all_widgets": "Refresh all widgets now",
|
||||
"toggle_all_photo_locks": "Freeze/unfreeze all photo widgets",
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Snap-to-grid placement math for widgets (see models.Widget) -- pure,
|
||||
no I/O, no ORM.
|
||||
|
||||
The grid is defined relative to the panel's long/short axis, not
|
||||
landscape/portrait specifically, so it stays valid across
|
||||
image_pipeline.logical_render_size(orientation)'s genuine width/height
|
||||
swap for portrait (not just a rotation applied at the very end) --
|
||||
landscape orientations are GRID_LONG columns x GRID_SHORT rows, portrait
|
||||
orientations are GRID_SHORT columns x GRID_LONG rows, same cell size
|
||||
either way. Changing a frame's orientation therefore invalidates any
|
||||
existing widget layout (an 8x5 arrangement isn't valid on a 5x8 grid) --
|
||||
callers are expected to reset to one full-panel widget on an orientation
|
||||
change, not try to remap coordinates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
GRID_LONG = 8
|
||||
GRID_SHORT = 5
|
||||
|
||||
# Per-widget-type minimum grid footprint (cols, rows) -- enforced both in
|
||||
# the placement UI and server-side (routers/api_widgets.py). A calendar
|
||||
# widget crammed into 1x1 would be illegible regardless of size-tier
|
||||
# scaling (see calendar_render.py); whiteboard needs enough room to be
|
||||
# worth looking at; photos can go as small as a single cell; tasks needs
|
||||
# enough width for a due-date prefix plus a couple words of summary
|
||||
# without truncating on every row; weather needs enough room for its
|
||||
# hourly/daily strips to stay legible (its current/multi_city modes
|
||||
# would tolerate smaller, but every mode shares one footprint value).
|
||||
# battery is just an icon + a percent (+ two optional small lines in
|
||||
# "detailed" mode) -- legible even at a single cell, like photos/static.
|
||||
# NOTE: a 1x1 widget-box on a narrow mobile canvas can clip its own
|
||||
# gear/remove buttons behind theme.css's overflow: hidden (their fixed
|
||||
# pixel offsets overflow the box's clipped width) -- a pre-existing
|
||||
# layout gap that already affects photos/static at 1x1 too, not fixed
|
||||
# here; see the finding called out where this was discovered.
|
||||
MIN_FOOTPRINT: dict[str, tuple[int, int]] = {
|
||||
"photos": (1, 1),
|
||||
"calendar": (3, 2),
|
||||
"whiteboard": (2, 2),
|
||||
"tasks": (2, 2),
|
||||
"static": (1, 1),
|
||||
"text": (2, 1),
|
||||
"weather": (2, 2),
|
||||
"battery": (1, 1),
|
||||
}
|
||||
|
||||
Rect = tuple[int, int, int, int] # (x, y, w, h)
|
||||
|
||||
|
||||
def grid_dims(orientation: str) -> tuple[int, int]:
|
||||
"""(cols, rows) for this orientation."""
|
||||
if orientation in ("portrait", "portrait_flipped"):
|
||||
return GRID_SHORT, GRID_LONG
|
||||
return GRID_LONG, GRID_SHORT
|
||||
|
||||
|
||||
def full_panel_rect(orientation: str) -> Rect:
|
||||
"""The single full-panel widget rect for this orientation -- what a
|
||||
frame gets reset to whenever its layout can't carry over (initial
|
||||
migration backfill, an orientation change)."""
|
||||
cols, rows = grid_dims(orientation)
|
||||
return (0, 0, cols, rows)
|
||||
|
||||
|
||||
def in_bounds(orientation: str, rect: Rect) -> bool:
|
||||
cols, rows = grid_dims(orientation)
|
||||
x, y, w, h = rect
|
||||
return x >= 0 and y >= 0 and w > 0 and h > 0 and x + w <= cols and y + h <= rows
|
||||
|
||||
|
||||
def meets_minimum(widget_type: str, rect: Rect) -> bool:
|
||||
min_w, min_h = MIN_FOOTPRINT.get(widget_type, (1, 1))
|
||||
_, _, w, h = rect
|
||||
return w >= min_w and h >= min_h
|
||||
|
||||
|
||||
def overlaps(a: Rect, b: Rect) -> bool:
|
||||
ax, ay, aw, ah = a
|
||||
bx, by, bw, bh = b
|
||||
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
|
||||
|
||||
|
||||
def find_open_rect(orientation: str, existing: list[Rect], w: int, h: int) -> Rect | None:
|
||||
"""First w x h rect that's in-bounds and doesn't overlap any of
|
||||
`existing`, scanning row-major (top-left first) -- used when creating
|
||||
a widget without an explicit placement (see routers/api_widgets.py),
|
||||
so adding one from a type picker doesn't require the caller to find
|
||||
empty space itself first. None if no such rect fits anywhere."""
|
||||
cols, rows = grid_dims(orientation)
|
||||
for y in range(rows - h + 1):
|
||||
for x in range(cols - w + 1):
|
||||
candidate = (x, y, w, h)
|
||||
if not any(overlaps(candidate, other) for other in existing):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def cell_to_pixels(orientation: str, panel_w: int, panel_h: int, rect: Rect) -> tuple[int, int, int, int]:
|
||||
"""Grid rect -> pixel rect in logical (pre-rotation) canvas space --
|
||||
against image_pipeline.logical_render_size(orientation)'s own
|
||||
(panel_w, panel_h), the same space every renderer already composes
|
||||
in before the final orientation transpose."""
|
||||
cols, rows = grid_dims(orientation)
|
||||
cell_w = panel_w / cols
|
||||
cell_h = panel_h / rows
|
||||
x, y, w, h = rect
|
||||
px, py = round(x * cell_w), round(y * cell_h)
|
||||
# Snap the far edge to the next cell boundary rather than compounding
|
||||
# per-cell rounding error across w/h -- keeps adjacent widgets'
|
||||
# shared edge pixel-exact instead of leaving a stray gap/overlap.
|
||||
px2, py2 = round((x + w) * cell_w), round((y + h) * cell_h)
|
||||
return (px, py, px2 - px, py2 - py)
|
||||
@@ -0,0 +1,666 @@
|
||||
"""Experimental "modern" render style, offered as an opt-in alternative
|
||||
to several widget types' hand-drawn PIL primitives: Jinja2 + a
|
||||
persistent headless Chromium browser (Playwright) -- see docs/widgets.md
|
||||
for the design rationale (gradients/shadows/soft shading that PIL can't
|
||||
easily do, at the cost of a real browser-process dependency). Everything
|
||||
in this module is shared infrastructure (the persistent browser, ordered
|
||||
dithering) plus one `build_*` function per widget type that has a
|
||||
modern-style builder -- battery/text/tasks/static image/whiteboard live
|
||||
here directly (mirroring how those widget types are themselves "inlined"
|
||||
in their own widget.py rather than getting a dedicated render module);
|
||||
calendar's (all four view modes, see calendar_html_render.py) is the one
|
||||
exception, kept separate the same reason calendar_render.py itself is
|
||||
its own 800+ line file rather than joining battery/text/tasks inline.
|
||||
Not offered for the photos widget -- a real photograph isn't a
|
||||
synthesized dashboard card, and photos has its own separate palette/
|
||||
dithering concern instead (see widgets/photos.py).
|
||||
|
||||
Two things this module owns that nothing else in the codebase needed
|
||||
before:
|
||||
|
||||
1. A **persistent** background browser process. Widget rendering already
|
||||
happens concurrently across a fresh `ThreadPoolExecutor` per frame
|
||||
request (routers/device.py's _render_widgets) -- Playwright's sync
|
||||
API is thread-affine (an object must be used from the thread that
|
||||
created it), so a single browser object can't be handed across those
|
||||
ad-hoc worker threads, and relaunching a full Chromium process on
|
||||
every widget render would be real, avoidable latency. Fix: one
|
||||
background thread runs its own persistent asyncio event loop hosting
|
||||
one long-lived `Browser`, lazily started on first use (see start()) --
|
||||
not eagerly at server startup, so a deployment that never enables the
|
||||
weather widget's "modern" style never launches Chromium at all and
|
||||
never needs Playwright's browser binaries installed. main.py's
|
||||
lifespan only wires up the *shutdown* half (stop()), so a clean
|
||||
server restart doesn't leave an orphaned Chromium process behind if
|
||||
this was ever actually used. render_html_to_image() is a plain sync
|
||||
function any worker thread can call, bridging in via
|
||||
`asyncio.run_coroutine_threadsafe` (the standard safe cross-thread
|
||||
entry point into a *running* loop on another thread).
|
||||
|
||||
2. **Per-region ordered (Bayer) dithering against the palette**, done
|
||||
here rather than in the shared image_pipeline.py pipeline.
|
||||
render_panel's whole-canvas single Floyd-Steinberg pass exists
|
||||
because Floyd-Steinberg's error diffusion can't be split across
|
||||
independently-quantized regions without a visible seam at the
|
||||
boundary -- but that reasoning doesn't apply to ordered dithering,
|
||||
which has no cross-pixel error term (each pixel's dither decision
|
||||
only depends on its own position + color). So this module dithers its
|
||||
own rendered widget to *already-exact* palette colors before
|
||||
returning it; the later shared Floyd-Steinberg pass sees zero
|
||||
quantization error there and leaves it untouched -- the same
|
||||
"pre-commit to exact palette colors" trick image_pipeline.draw_text
|
||||
and the hand-drawn weather icons already rely on, just reached a
|
||||
different way. Floyd-Steinberg keeps working exactly as before for
|
||||
photos and every other (classic-rendered) widget region.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import threading
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
from PIL import Image
|
||||
|
||||
from . import panel_style, theme_tokens
|
||||
from .image_pipeline import DEFAULT_PALETTE_RGB, hex_to_rgb
|
||||
|
||||
_TEMPLATE_DIR = Path(__file__).resolve().parent / "templates" / "widget_html"
|
||||
_FONT_DIR = Path(__file__).resolve().parent / "fonts"
|
||||
|
||||
_jinja_env = Environment(
|
||||
loader=FileSystemLoader(str(_TEMPLATE_DIR)),
|
||||
autoescape=select_autoescape(["html", "jinja"]),
|
||||
)
|
||||
|
||||
CATEGORY_EMOJI = {
|
||||
"clear": "☀️",
|
||||
"partly_cloudy": "⛅",
|
||||
"cloudy": "☁️",
|
||||
"fog": "\U0001f32b️",
|
||||
"rain": "\U0001f327️",
|
||||
"snow": "❄️",
|
||||
"thunderstorm": "⛈️",
|
||||
}
|
||||
|
||||
# Spelled-out condition word for the "bold minimal" current-mode layout --
|
||||
# classic's build_current never needed one (icon + temp only), but the
|
||||
# redesigned modern layout has room for a secondary line under the temp.
|
||||
CATEGORY_LABEL = {
|
||||
"clear": "Clear",
|
||||
"partly_cloudy": "Partly cloudy",
|
||||
"cloudy": "Cloudy",
|
||||
"fog": "Fog",
|
||||
"rain": "Rain",
|
||||
"snow": "Snow",
|
||||
"thunderstorm": "Thunderstorm",
|
||||
}
|
||||
|
||||
|
||||
def _rgb_to_hex(rgb: tuple[int, int, int]) -> str:
|
||||
return "#%02x%02x%02x" % tuple(rgb)
|
||||
|
||||
|
||||
def _darken_hex(rgb: tuple[int, int, int], factor: float = 0.75) -> str:
|
||||
"""A darker shade of `rgb` for a CSS gradient's second stop -- purely
|
||||
decorative (ordered_dither commits everything to exact palette colors
|
||||
regardless of which literal hex a gradient starts from)."""
|
||||
return _rgb_to_hex(tuple(max(0, round(c * factor)) for c in rgb))
|
||||
|
||||
|
||||
def _clamp(value: float, lo: float, hi: float) -> float:
|
||||
"""Keeps a size/spacing value proportional to widget dimensions
|
||||
(`value` is always some fraction of target_w/target_h) while still
|
||||
guaranteeing a floor (stays legible on a 1-2 grid-cell widget) and a
|
||||
ceiling (stops padding/type from just growing forever on a
|
||||
near-full-panel widget -- see build_current's docstring)."""
|
||||
return max(lo, min(hi, value))
|
||||
|
||||
|
||||
# --- Persistent background browser -------------------------------------
|
||||
|
||||
_loop: asyncio.AbstractEventLoop | None = None
|
||||
_loop_thread: threading.Thread | None = None
|
||||
_browser = None
|
||||
_playwright_cm = None
|
||||
_start_lock = threading.Lock()
|
||||
|
||||
|
||||
async def _launch_browser() -> None:
|
||||
global _browser, _playwright_cm
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
_playwright_cm = async_playwright()
|
||||
playwright = await _playwright_cm.__aenter__()
|
||||
_browser = await playwright.chromium.launch()
|
||||
|
||||
|
||||
async def _close_browser() -> None:
|
||||
global _browser, _playwright_cm
|
||||
if _browser is not None:
|
||||
await _browser.close()
|
||||
_browser = None
|
||||
if _playwright_cm is not None:
|
||||
await _playwright_cm.__aexit__(None, None, None)
|
||||
_playwright_cm = None
|
||||
|
||||
|
||||
def start() -> None:
|
||||
"""Launches the background event loop + persistent Chromium browser,
|
||||
if not already running. Called lazily by render_html_to_image on
|
||||
first use (not from main.py's lifespan -- see module docstring for
|
||||
why this must stay opt-in) -- exposed directly too, for tests that
|
||||
want to control startup explicitly. Idempotent -- a second call
|
||||
while already started is a no-op."""
|
||||
global _loop, _loop_thread
|
||||
if _loop is not None:
|
||||
return
|
||||
ready = threading.Event()
|
||||
|
||||
def _run() -> None:
|
||||
global _loop
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
_loop = loop
|
||||
ready.set()
|
||||
loop.run_forever()
|
||||
|
||||
_loop_thread = threading.Thread(target=_run, daemon=True, name="html-render-loop")
|
||||
_loop_thread.start()
|
||||
ready.wait()
|
||||
asyncio.run_coroutine_threadsafe(_launch_browser(), _loop).result()
|
||||
|
||||
|
||||
def stop() -> None:
|
||||
"""Closes the browser and stops the background loop -- called from
|
||||
main.py's lifespan shutdown so a server restart never leaves an
|
||||
orphaned Chromium process behind. No-op if start() was never called
|
||||
(the common case: most deployments never enable "modern" style)."""
|
||||
global _loop, _loop_thread
|
||||
if _loop is None:
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(_close_browser(), _loop).result()
|
||||
_loop.call_soon_threadsafe(_loop.stop)
|
||||
_loop_thread.join(timeout=5)
|
||||
_loop = None
|
||||
_loop_thread = None
|
||||
|
||||
|
||||
async def _screenshot(html: str, target_w: int, target_h: int) -> bytes:
|
||||
page = await _browser.new_page(viewport={"width": target_w, "height": target_h}, device_scale_factor=1)
|
||||
try:
|
||||
await page.set_content(html, wait_until="networkidle")
|
||||
return await page.screenshot()
|
||||
finally:
|
||||
await page.close()
|
||||
|
||||
|
||||
def render_html_to_image(html: str, target_w: int, target_h: int) -> Image.Image:
|
||||
"""Renders `html` (already sized to target_w x target_h via its own
|
||||
<style>) through the persistent headless Chromium browser and
|
||||
returns an RGB image of exactly that size. Safe to call from any
|
||||
thread -- bridges into the dedicated background asyncio loop via
|
||||
run_coroutine_threadsafe. Lazily calls start() on first use (see its
|
||||
docstring) -- the first "modern" style render on a freshly-started
|
||||
server pays Chromium's launch latency; every render after that reuses
|
||||
the same persistent browser."""
|
||||
if _loop is None:
|
||||
with _start_lock:
|
||||
if _loop is None:
|
||||
start()
|
||||
future = asyncio.run_coroutine_threadsafe(_screenshot(html, target_w, target_h), _loop)
|
||||
png_bytes = future.result()
|
||||
return Image.open(io.BytesIO(png_bytes)).convert("RGB")
|
||||
|
||||
|
||||
# --- Ordered (Bayer 8x8) dithering against an arbitrary palette ---------
|
||||
|
||||
_BAYER8 = (
|
||||
np.array(
|
||||
[
|
||||
[0, 32, 8, 40, 2, 34, 10, 42],
|
||||
[48, 16, 56, 24, 50, 18, 58, 26],
|
||||
[12, 44, 4, 36, 14, 46, 6, 38],
|
||||
[60, 28, 52, 20, 62, 30, 54, 22],
|
||||
[3, 35, 11, 43, 1, 33, 9, 41],
|
||||
[51, 19, 59, 27, 49, 17, 57, 25],
|
||||
[15, 47, 7, 39, 13, 45, 5, 37],
|
||||
[63, 31, 55, 23, 61, 29, 53, 21],
|
||||
],
|
||||
dtype=np.float32,
|
||||
)
|
||||
/ 64.0
|
||||
- 0.5
|
||||
)
|
||||
|
||||
|
||||
def ordered_dither(img: Image.Image, palette_rgb: list | None, amplitude: float = 48.0) -> Image.Image:
|
||||
"""Bayer-ordered dither of `img` against `palette_rgb` (falls back to
|
||||
DEFAULT_PALETTE_RGB) -- every output pixel is one of the palette's
|
||||
exact colors, spatially patterned rather than error-diffused, so it's
|
||||
safe to run per-region before compositing (see module docstring for
|
||||
why that's not true of Floyd-Steinberg). `amplitude` is the Bayer
|
||||
bias's full swing in 0-255 RGB units before nearest-palette-color
|
||||
matching -- 48 was the value this render style was tuned against in
|
||||
the exploratory spike behind this feature; not exposed as a per-frame
|
||||
setting (unlike dither_strength) since there's only one consumer of
|
||||
it today."""
|
||||
palette = np.array(palette_rgb or DEFAULT_PALETTE_RGB, dtype=np.float32)
|
||||
arr = np.asarray(img.convert("RGB"), dtype=np.float32)
|
||||
h, w, _ = arr.shape
|
||||
tile = np.tile(_BAYER8, (h // 8 + 1, w // 8 + 1))[:h, :w]
|
||||
biased = np.clip(arr + tile[:, :, None] * amplitude, 0, 255)
|
||||
diffs = biased[:, :, None, :] - palette[None, None, :, :]
|
||||
dists = np.einsum("hwkc,hwkc->hwk", diffs, diffs)
|
||||
idx = np.argmin(dists, axis=2)
|
||||
return Image.fromarray(palette[idx].astype(np.uint8), "RGB")
|
||||
|
||||
|
||||
def ordered_dither_regions(rendered: Image.Image, palette_rgb: list | None, base_amplitude: float = 48.0,
|
||||
accent_regions: list[tuple[tuple[int, int, int, int], float]] = ()) -> Image.Image:
|
||||
"""Like `ordered_dither`, but lets specific rectangles (e.g. a themed
|
||||
header bar) dither at a higher amplitude than the rest of the widget.
|
||||
A single higher amplitude applied to a whole widget washes out pale
|
||||
content (a weather icon's white cloud body nearly disappeared in
|
||||
testing); dithering the base image at the safe default and only
|
||||
re-dithering an accent rect on top -- pasted back over the base --
|
||||
lets a header carry a rich, arbitrary accent hue (via denser
|
||||
stippling) without touching icon/text legibility elsewhere. Safe to
|
||||
do per-region for the same reason `ordered_dither` is safe per-widget
|
||||
(see its docstring): no cross-pixel error-diffusion term, so each
|
||||
region's result depends only on its own pixels."""
|
||||
base = ordered_dither(rendered, palette_rgb, amplitude=base_amplitude)
|
||||
for (x0, y0, x1, y1), amplitude in accent_regions:
|
||||
crop = rendered.crop((x0, y0, x1, y1))
|
||||
base.paste(ordered_dither(crop, palette_rgb, amplitude=amplitude), (x0, y0))
|
||||
return base
|
||||
|
||||
|
||||
# --- Weather "modern" style ----------------------------------------------
|
||||
|
||||
def _day_label(day_date: date) -> str:
|
||||
delta = (day_date - date.today()).days
|
||||
if delta == 0:
|
||||
return "Today"
|
||||
if delta == 1:
|
||||
return "Tomorrow"
|
||||
return day_date.strftime("%a")
|
||||
|
||||
|
||||
def _short_city(city_label: str) -> str:
|
||||
"""geocode_city (see docs/widgets.md's Weather widget section) hands
|
||||
back a full "City, Region, Country" string -- fine for classic's
|
||||
build_current (just drawn as one line, however wide) but wrong for
|
||||
the bold-minimal layout's small top-row label, where a 1-2 grid-
|
||||
cell widget has no room for the whole thing. Every phone-homescreen
|
||||
weather widget this style is drawing from shows just the city, so
|
||||
that's what this keeps -- CSS `text-overflow: ellipsis` is still in
|
||||
the template as a safety net for a custom single-segment label
|
||||
that's itself too long, not as the primary truncation strategy."""
|
||||
return city_label.split(",")[0].strip()
|
||||
|
||||
|
||||
def build_current(entry: dict | None, target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
units: str = "fahrenheit", city_label: str = "", theme_name: str | None = None) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of weather_render.build_current --
|
||||
same call signature, so app/widgets/weather.py can dispatch to
|
||||
either interchangeably. Returns an already-palette-exact RGB image
|
||||
(see ordered_dither).
|
||||
|
||||
"Bold minimal" layout: the temperature itself is the graphic --
|
||||
city label + icon in a top row, the temp (dominant) and spelled-out
|
||||
condition anchored to the bottom, no card/border/shadow at all. This
|
||||
is a deliberate departure from every other modern-style widget's
|
||||
card-on-white-canvas chrome (see docs/widgets.md) -- there's nothing
|
||||
for a "card" to visually separate from here, so `theme["radius"]`/
|
||||
`theme["shadow"]` have no effect on this template; still theme-aware
|
||||
for font_family only, same as before. No header/accent region either
|
||||
(see ordered_dither_regions' docstring) -- a themed accent has
|
||||
nothing to attach to in a chrome-free layout.
|
||||
|
||||
Every size below is a fraction of `base` (the widget's shorter side),
|
||||
clamped to a floor/ceiling rather than fixed -- so a 1-grid-cell
|
||||
widget doesn't get comically oversized padding relative to its
|
||||
content, and a near-full-panel widget doesn't get comically large
|
||||
padding relative to *its* content either. Floors/ceilings are tuned
|
||||
by eye against real widget sizes, not derived from anything."""
|
||||
img = Image.new("RGB", (target_w, target_h), (255, 255, 255))
|
||||
if not entry:
|
||||
return img
|
||||
|
||||
theme = theme_tokens.resolve_theme(theme_name, "weather", palette_rgb)
|
||||
unit_suffix = "F" if units == "fahrenheit" else "C"
|
||||
base = min(target_w, target_h)
|
||||
pad = _clamp(base * 0.09, 10, 26)
|
||||
icon_size = _clamp(base * 0.20, 22, 60)
|
||||
temp_size = _clamp(base * 0.46, 30, 150)
|
||||
deg_size = _clamp(temp_size * 0.28, 12, 40)
|
||||
cond_size = _clamp(base * 0.075, 11, 20)
|
||||
city_size = _clamp(base * 0.06, 10, 15)
|
||||
template = _jinja_env.get_template("weather_current.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, pad=round(pad),
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
emoji=CATEGORY_EMOJI.get(entry["category"], ""),
|
||||
condition=CATEGORY_LABEL.get(entry["category"], ""),
|
||||
temp=round(entry["temp"]), unit_suffix=unit_suffix, city_label=_short_city(city_label),
|
||||
icon_size=round(icon_size), temp_size=round(temp_size), deg_size=round(deg_size),
|
||||
cond_size=round(cond_size), city_size=round(city_size),
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
return ordered_dither(rendered, palette_rgb)
|
||||
|
||||
|
||||
def build_daily(daily: dict[str, dict], target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
units: str = "fahrenheit", city_label: str = "", theme_name: str | None = None) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of weather_render.build_daily -- same
|
||||
call signature. Returns an already-palette-exact RGB image (see
|
||||
ordered_dither).
|
||||
|
||||
"Bold minimal" layout, matching build_current: no card/border/
|
||||
shadow, a row of day columns each carrying its own high (dominant)
|
||||
/ low (muted) temp the same way build_current makes the current
|
||||
temp dominant. The old full-width gradient banner is gone --
|
||||
city_label, when set, is a slim accent-colored rule (not a block)
|
||||
with the city name understated beneath it, so there's still
|
||||
somewhere for a theme's accent hue to show up (dithered richer via
|
||||
ordered_dither_regions, same mechanism as before) without dragging
|
||||
back the "card with a colored header" chrome this redesign is
|
||||
moving away from. `theme["radius"]`/`theme["shadow"]` are unused
|
||||
here for the same reason as build_current -- no card for them to
|
||||
apply to."""
|
||||
img = Image.new("RGB", (target_w, target_h), (255, 255, 255))
|
||||
days = list(daily.items())
|
||||
if not days:
|
||||
return img
|
||||
|
||||
theme = theme_tokens.resolve_theme(theme_name, "weather", palette_rgb)
|
||||
unit_suffix = "F" if units == "fahrenheit" else "C"
|
||||
base = min(target_w, target_h)
|
||||
pad = round(_clamp(base * 0.08, 10, 22))
|
||||
col_w = max(1, (target_w - pad * 2) // len(days))
|
||||
col_gap = round(_clamp(col_w * 0.12, 4, 16))
|
||||
icon_size = round(_clamp(col_w * 0.30, 16, 32))
|
||||
day_label_size = round(_clamp(col_w * 0.15, 10, 14))
|
||||
high_size = round(_clamp(col_w * 0.32, 16, 32))
|
||||
low_size = round(max(9, high_size * 0.55))
|
||||
city_size = round(_clamp(base * 0.055, 10, 14))
|
||||
accent_h = round(_clamp(base * 0.025, 4, 8))
|
||||
day_entries = [
|
||||
{
|
||||
"label": _day_label(date.fromisoformat(day_str)),
|
||||
"emoji": CATEGORY_EMOJI.get(d["category"], ""),
|
||||
"high": round(d["high"]),
|
||||
"low": round(d["low"]),
|
||||
}
|
||||
for day_str, d in days
|
||||
]
|
||||
template = _jinja_env.get_template("weather_daily.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, pad=pad, col_gap=col_gap,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
city_label=_short_city(city_label), city_size=city_size, accent_h=accent_h,
|
||||
accent_start=theme["accent_hex"], accent_end=theme["accent_hex_dark"],
|
||||
days=day_entries, icon_size=icon_size, day_label_size=day_label_size,
|
||||
high_size=high_size, low_size=low_size, unit_suffix=unit_suffix,
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
if not city_label:
|
||||
return ordered_dither(rendered, palette_rgb)
|
||||
accent_rect = (pad, pad, target_w - pad, pad + accent_h)
|
||||
return ordered_dither_regions(rendered, palette_rgb, accent_regions=[(accent_rect, theme["accent_amplitude"])])
|
||||
|
||||
|
||||
SUPPORTED_MODES = ("current", "daily")
|
||||
|
||||
|
||||
def build(mode: str, data, target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
units: str = "fahrenheit", city_label: str = "", theme_name: str | None = None) -> Image.Image:
|
||||
"""Dispatches to build_current/build_daily -- mirrors weather_render.
|
||||
build()'s signature (minus interval_hours, which no modern-style mode
|
||||
uses) so app/widgets/weather.py and the weather preview endpoint can
|
||||
call either module identically. Only call this for mode in
|
||||
SUPPORTED_MODES -- callers are expected to have already fallen back to
|
||||
weather_render.build() for hourly/multi_city (see weather.py)."""
|
||||
if mode == "current":
|
||||
return build_current(data, target_w, target_h, palette_rgb, units, city_label, theme_name)
|
||||
return build_daily(data, target_w, target_h, palette_rgb, units, city_label, theme_name)
|
||||
|
||||
|
||||
def render_weather_preview_png(mode: str, data, orientation: str, palette_rgb: list | None,
|
||||
units: str = "fahrenheit", city_label: str = "",
|
||||
theme_name: str | None = None) -> bytes:
|
||||
"""Modern-style analogue of weather_render.render_weather_preview_png
|
||||
-- same browser-viewable-PNG convention every other widget's preview
|
||||
endpoint uses. build()'s output is already palette-exact (see
|
||||
ordered_dither), so the final _quantize pass here is a no-op on it,
|
||||
same reasoning as the module docstring's compositing story."""
|
||||
from .image_pipeline import _quantize, _png_bytes, logical_render_size
|
||||
|
||||
target_w, target_h = logical_render_size(orientation)
|
||||
img = build(mode, data, target_w, target_h, palette_rgb, units, city_label, theme_name)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
return _png_bytes(quantized)
|
||||
|
||||
|
||||
# --- Battery "modern" style ------------------------------------------------
|
||||
|
||||
def _battery_sizes(target_w: int, target_h: int, num_lines: int, scale: float) -> dict:
|
||||
base = min(target_w, target_h)
|
||||
icon_h = max(14, int(base * 0.15 * scale))
|
||||
pct_size = max(20, int(base * 0.42 * scale))
|
||||
line_size = max(9, int(base * 0.085 * scale))
|
||||
gap = max(4, int(base * 0.035 * scale))
|
||||
total = icon_h + gap + pct_size + num_lines * (line_size + gap)
|
||||
return {"icon_h": icon_h, "pct_size": pct_size, "line_size": line_size, "gap": gap, "total": total}
|
||||
|
||||
|
||||
def build_battery(percent: int, lines: list[str], target_w: int, target_h: int,
|
||||
palette_rgb: list | None = None, theme_name: str | None = None) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of widgets/battery.py's classic PIL
|
||||
drawing -- same icon+percent+caption-lines shape, `lines` already
|
||||
resolved by the caller (widgets/battery.py's _lines_for(), shared
|
||||
with the classic path so the estimate/age formatting only lives in
|
||||
one place). Returns an already-palette-exact RGB image (see
|
||||
ordered_dither). Theme-aware for font only -- the charge-level
|
||||
fill_color below is a functional status signal (not a style choice)
|
||||
and is never touched by a theme, and there's no header/accent region
|
||||
to dither richer via ordered_dither_regions.
|
||||
|
||||
Bold-minimal: no card (theme["radius"] unused, same carve-out as
|
||||
weather's build_current -- see docs/widgets.md); the percent is the
|
||||
hero value anchored toward the bottom, same treatment build_current
|
||||
gives the temperature, with the icon small and secondary above it
|
||||
instead of both competing at the same size like the old centered
|
||||
layout did.
|
||||
|
||||
Shrinks icon/text sizes together (in 0.05 steps down to 0.3x) until
|
||||
the whole stack actually fits the available height -- the classic
|
||||
PIL path solves the same "icon + percent + 0-2 lines in a fixed box"
|
||||
problem by truncating lines that don't fit; scaling down instead
|
||||
keeps every resolved line visible, which reads better for a widget
|
||||
that only ever has at most 2 short caption lines to begin with."""
|
||||
pad = round(_clamp(min(target_w, target_h) * 0.09, 10, 26))
|
||||
avail_h = target_h - pad * 2
|
||||
num_lines = len(lines)
|
||||
scale = 1.0
|
||||
sizes = _battery_sizes(target_w, target_h, num_lines, scale)
|
||||
while sizes["total"] > avail_h and scale > 0.3:
|
||||
scale -= 0.05
|
||||
sizes = _battery_sizes(target_w, target_h, num_lines, scale)
|
||||
# Extreme case (a 1x1-grid-cell-sized widget in "detailed" mode):
|
||||
# scale bottomed out and it still doesn't fit -- drop the least
|
||||
# important line rather than render overlapping text, same
|
||||
# graceful-degradation idiom the classic PIL path's own
|
||||
# `if y + small_font_size > ...: break` truncation already uses.
|
||||
while sizes["total"] > avail_h and lines:
|
||||
lines = lines[:-1]
|
||||
num_lines = len(lines)
|
||||
sizes = _battery_sizes(target_w, target_h, num_lines, scale)
|
||||
|
||||
theme = theme_tokens.resolve_theme(theme_name, "battery", palette_rgb)
|
||||
fill_color = panel_style.battery_fill_color(percent, palette_rgb)
|
||||
icon_h = sizes["icon_h"]
|
||||
icon_w = int(icon_h * 1.8)
|
||||
stroke = max(2, icon_h // 12)
|
||||
nub_w = max(3, icon_w // 10)
|
||||
template = _jinja_env.get_template("battery.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, pad=pad,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"], percent=percent, lines=lines,
|
||||
icon_w=icon_w, icon_h=icon_h, icon_radius=icon_h // 6, stroke=stroke,
|
||||
fill_pct=max(0, min(100, percent)), fill_radius=max(0, icon_h // 6 - stroke),
|
||||
fill_color=_rgb_to_hex(fill_color), fill_color_dark=_darken_hex(fill_color),
|
||||
nub_w=nub_w, nub_h=icon_h // 2, nub_radius=max(1, nub_w // 3),
|
||||
pct_size=sizes["pct_size"], line_size=sizes["line_size"], line_gap=sizes["gap"],
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
return ordered_dither(rendered, palette_rgb)
|
||||
|
||||
|
||||
# --- Text "modern" style ---------------------------------------------------
|
||||
|
||||
def build_text(cfg, target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
theme_name: str | None = None) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of widgets/text.py's classic PIL
|
||||
drawing. Reuses widgets/text.py's own `_fit()` for the one piece of
|
||||
logic CSS has no native equivalent for (shrink-to-fit sizing) --
|
||||
`_fit` measures against the exact same vendored font files via PIL,
|
||||
so the resolved size is a real fit decision, not a guess -- but lets
|
||||
the browser do its own text wrapping/line-breaking at that size
|
||||
(paragraphs/runs passed through directly as HTML) rather than
|
||||
replicating `_fit`'s own word-wrapped line list; the two wrapping
|
||||
algorithms can disagree on exact break points, an acceptable
|
||||
approximation since this style only needs to look good and fit
|
||||
reasonably, not be pixel-identical to classic. Returns an already-
|
||||
palette-exact RGB image (see ordered_dither).
|
||||
|
||||
theme_name is accepted (every modern-style build_* function takes
|
||||
one, threaded uniformly from frame.theme) but deliberately unused --
|
||||
the text widget's own font_family is a per-widget, user-authored
|
||||
choice (see widgets/text.py's module docstring), same carve-out
|
||||
reasoning as run-level colors; a frame theme overriding it would
|
||||
silently undo an explicit user choice. text.html.jinja also has no
|
||||
card chrome (no radius/shadow) for a theme to touch."""
|
||||
from PIL import ImageDraw
|
||||
|
||||
from . import widgets # local import: heavy-ish, and only "modern" text needs it
|
||||
|
||||
text_widget = widgets.text
|
||||
bg_rgb = (hex_to_rgb(cfg.background_color) if cfg.background_color else None) or (255, 255, 255)
|
||||
family = cfg.font_family if cfg.font_family in text_widget.FONT_FAMILIES else text_widget.DEFAULT_FONT_FAMILY
|
||||
paragraphs = cfg.content or []
|
||||
margin = text_widget.MARGIN
|
||||
max_width = max(10, target_w - 2 * margin)
|
||||
max_height = max(10, target_h - 2 * margin)
|
||||
|
||||
measure_img = Image.new("RGB", (1, 1))
|
||||
draw = ImageDraw.Draw(measure_img)
|
||||
size, _lines = text_widget._fit(draw, paragraphs, family, cfg.font_size, max_width, max_height)
|
||||
|
||||
files = text_widget._FONT_FILES.get(family) or text_widget._FONT_FILES[text_widget.DEFAULT_FONT_FAMILY]
|
||||
align = cfg.align if cfg.align in ("left", "center", "right") else "left"
|
||||
template = _jinja_env.get_template("text.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, margin=margin, bg_color=_rgb_to_hex(bg_rgb),
|
||||
size=size, line_height=text_widget.LINE_HEIGHT_FACTOR, align=align,
|
||||
font_regular=str(_FONT_DIR / files[(False, False)]), font_bold=str(_FONT_DIR / files[(True, False)]),
|
||||
font_italic=str(_FONT_DIR / files[(False, True)]), font_bold_italic=str(_FONT_DIR / files[(True, True)]),
|
||||
paragraphs=paragraphs,
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
return ordered_dither(rendered, palette_rgb)
|
||||
|
||||
|
||||
# --- Tasks "modern" style ---------------------------------------------------
|
||||
|
||||
def build_tasks(tasks: list[dict], target_w: int, target_h: int, palette_rgb: list | None = None,
|
||||
title: str = "Tasks", theme_name: str | None = None, font_scale: float = 1.0) -> Image.Image:
|
||||
"""HTML/CSS-rendered analogue of calendar_render._build_tasks --
|
||||
same header+checklist shape. Reuses calendar_render's own
|
||||
_event_colors/_fmt_task_due (the exact color-dedup/due-date-format
|
||||
logic the classic renderer uses) so a task's color chip/due string
|
||||
matches classic style exactly; only the drawing differs -- and a
|
||||
theme's accent never touches those per-owner chip colors (identity-
|
||||
coding, not style) or the done-checkbox fill (a completion state
|
||||
signal, not a style choice -- it happens to reuse the accent color,
|
||||
but that's incidental, same as before this redesign).
|
||||
|
||||
Bold-minimal: no card (theme["shadow"]/["radius"] unused, same
|
||||
carve-out as calendar's redesigned views -- see docs/widgets.md).
|
||||
The old gradient header banner is now a slim accent rule + plain
|
||||
bold title, matching every calendar view's day-header language --
|
||||
only the rule dithers at the theme's richer accent_amplitude, not
|
||||
the title text sitting on it. Returns an already-palette-exact RGB
|
||||
image (see ordered_dither)."""
|
||||
from .calendar_render import _event_colors, _fmt_task_due
|
||||
|
||||
theme = theme_tokens.resolve_theme(theme_name, "tasks", palette_rgb)
|
||||
base = min(target_w, target_h)
|
||||
accent_h = round(_clamp(base * 0.025, 3, 6))
|
||||
title_size = panel_style.scaled_size(max(14, base // 12), font_scale)
|
||||
body_size = panel_style.scaled_size(max(11, base // 20), font_scale)
|
||||
row_h = body_size + 14
|
||||
box_size = max(10, body_size - 4)
|
||||
header_h = accent_h + 6 + title_size
|
||||
avail_h = target_h - panel_style.GUTTER * 2 - header_h - 8
|
||||
max_rows = max(0, avail_h // row_h)
|
||||
|
||||
owners_seen: list[str] = []
|
||||
rows = []
|
||||
for task in tasks[:max_rows]:
|
||||
colors = _event_colors(task, owners_seen, palette_rgb)
|
||||
done = task.get("completed_at") is not None
|
||||
due = None if done else (_fmt_task_due(task.get("due")) or None)
|
||||
rows.append({
|
||||
"colors": [_rgb_to_hex(c) for c in colors],
|
||||
"done": done,
|
||||
"due": due,
|
||||
"summary": task["summary"],
|
||||
})
|
||||
more_count = max(0, len(tasks) - max_rows)
|
||||
|
||||
template = _jinja_env.get_template("tasks.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=panel_style.GUTTER,
|
||||
font_regular=theme["font_regular"], font_bold=theme["font_bold"],
|
||||
title=title, header_h=header_h, accent_h=accent_h, title_size=title_size,
|
||||
accent_start=theme["accent_hex"],
|
||||
rows=rows, more_count=more_count, row_h=row_h, box_size=box_size, body_size=body_size,
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
gutter = panel_style.GUTTER
|
||||
accent_rect = (gutter, gutter, target_w - gutter, gutter + accent_h)
|
||||
return ordered_dither_regions(rendered, palette_rgb, accent_regions=[(accent_rect, theme["accent_amplitude"])])
|
||||
|
||||
|
||||
# --- Static image / whiteboard "modern" style (shared) ---------------------
|
||||
|
||||
def build_framed_image(composed: Image.Image, target_w: int, target_h: int,
|
||||
palette_rgb: list | None = None, theme_name: str | None = None,
|
||||
widget_kind: str = "static") -> Image.Image:
|
||||
"""Wraps an already-composed image (static_image.py/whiteboard.py's
|
||||
own compose_into() output, exactly target_w x target_h, already
|
||||
cropped/fit per that widget's own display_mode) in a rounded-corner,
|
||||
shadowed card -- the first visual chrome either widget type has ever
|
||||
had (both currently draw with zero chrome of their own). Theme-aware
|
||||
for radius/shadow only -- no text/header content to accent or font.
|
||||
Returns an already-palette-exact RGB image (see ordered_dither)."""
|
||||
import base64
|
||||
|
||||
theme = theme_tokens.resolve_theme(theme_name, widget_kind, palette_rgb)
|
||||
buf = io.BytesIO()
|
||||
composed.convert("RGB").save(buf, format="PNG")
|
||||
image_b64 = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||
|
||||
template = _jinja_env.get_template("framed_image.html.jinja")
|
||||
html = template.render(
|
||||
w=target_w, h=target_h, gutter=panel_style.GUTTER, radius=theme["radius"], shadow=theme["shadow"],
|
||||
image_b64=image_b64,
|
||||
)
|
||||
rendered = render_html_to_image(html, target_w, target_h)
|
||||
return ordered_dither(rendered, palette_rgb)
|
||||
+283
-13
@@ -3,12 +3,134 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import math
|
||||
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageOps
|
||||
|
||||
EPD_WIDTH = 800
|
||||
EPD_HEIGHT = 480
|
||||
|
||||
# PIL's TrueType rendering antialiases by default (graduated gray edge
|
||||
# pixels). Those survive straight into _quantize's Floyd-Steinberg
|
||||
# dithering, which -- confirmed visually -- turns them into scattered
|
||||
# colored speckles along every glyph edge once forced onto the panel's 6
|
||||
# colors, since a mid-gray input has no close palette match and the
|
||||
# diffused error bounces between whichever colors are nearest. Drawing
|
||||
# through a thresholded bilevel mask instead keeps every edge pure
|
||||
# black/white, which _quantize then reproduces exactly (both are already
|
||||
# palette colors, nothing to dither). Shared by every module that draws
|
||||
# text before quantization (this file's render_placeholder,
|
||||
# calendar_render.py, manage_overlay.py).
|
||||
_TEXT_MASK_THRESHOLD = 110
|
||||
|
||||
|
||||
def draw_text(img: Image.Image, xy: tuple[int, int], text: str, font: ImageFont.ImageFont,
|
||||
fill: tuple[int, int, int] = (0, 0, 0)) -> None:
|
||||
bbox = font.getbbox(text)
|
||||
w, h = max(1, bbox[2] - bbox[0]), max(1, bbox[3] - bbox[1])
|
||||
mask = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(mask).text((-bbox[0], -bbox[1]), text, fill=255, font=font)
|
||||
mask = mask.point(lambda p: 255 if p > _TEXT_MASK_THRESHOLD else 0)
|
||||
img.paste(fill, (xy[0] + bbox[0], xy[1] + bbox[1]), mask)
|
||||
|
||||
|
||||
def _dashed_edge(draw: ImageDraw.ImageDraw, x0: float, y0: float, x1: float, y1: float,
|
||||
width: int, color: tuple[int, int, int], dash: float, gap: float) -> None:
|
||||
length = math.hypot(x1 - x0, y1 - y0)
|
||||
if length <= 0:
|
||||
return
|
||||
ux, uy = (x1 - x0) / length, (y1 - y0) / length
|
||||
pos = 0.0
|
||||
while pos < length:
|
||||
end = min(pos + dash, length)
|
||||
draw.line([(x0 + ux * pos, y0 + uy * pos), (x0 + ux * end, y0 + uy * end)], fill=color, width=width)
|
||||
pos += dash + gap
|
||||
|
||||
|
||||
def _dotted_edge(draw: ImageDraw.ImageDraw, x0: float, y0: float, x1: float, y1: float,
|
||||
width: int, color: tuple[int, int, int], spacing: float) -> None:
|
||||
length = math.hypot(x1 - x0, y1 - y0)
|
||||
if length <= 0:
|
||||
return
|
||||
ux, uy = (x1 - x0) / length, (y1 - y0) / length
|
||||
r = max(1, width / 2)
|
||||
pos = 0.0
|
||||
while pos <= length:
|
||||
cx, cy = x0 + ux * pos, y0 + uy * pos
|
||||
draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=color)
|
||||
pos += spacing
|
||||
|
||||
|
||||
def draw_widget_border(img: Image.Image, style: str, thickness: int, color: tuple[int, int, int],
|
||||
radius: int = 0) -> None:
|
||||
"""Draws a border inset within img's own bounds, mutating it in
|
||||
place -- called once per widget's own region (routers/device.py's
|
||||
_render_widgets, and each widget type's own dialog preview) before
|
||||
that region's image is pasted onto the shared canvas, so a border
|
||||
never straddles the boundary between two adjacent widgets. `color`
|
||||
should already be an exact palette RGB (see resolve_border_color) so
|
||||
the stroke quantizes with zero dithering error, same reasoning as
|
||||
the weather/battery icons' exact-panel-ink-RGB fills.
|
||||
|
||||
"solid"/"dashed"/"dotted" are a single thickness-px stroke traced
|
||||
just inside the image's edge; "fancy" is two thinner concentric
|
||||
strokes with a gap between them, picture-frame-mat style. "none" (or
|
||||
a non-positive thickness) draws nothing. `radius` is opt-in and only
|
||||
honored by "solid"/"fancy" (rounded_rectangle instead of rectangle) --
|
||||
"dashed"/"dotted" trace each of the 4 edges as independent straight
|
||||
segments (see _dashed_edge/_dotted_edge) and ignore it, a documented
|
||||
limitation rather than a bug. Defaults to 0 (unchanged sharp-corner
|
||||
behavior) and no call site passes non-zero today -- this ships the
|
||||
capability for a future per-widget "rounded border" setting without
|
||||
changing default behavior anywhere (see tests/test_widget_border.py's
|
||||
exact-corner-pixel assertions)."""
|
||||
if style == "none" or thickness <= 0:
|
||||
return
|
||||
w, h = img.size
|
||||
t = max(1, min(int(thickness), min(w, h) // 2))
|
||||
draw = ImageDraw.Draw(img)
|
||||
r = max(0, min(radius, (w - 1) // 2, (h - 1) // 2))
|
||||
|
||||
if style == "fancy":
|
||||
line_t = max(1, t // 3)
|
||||
gap = max(2, t - 2 * line_t)
|
||||
if r:
|
||||
draw.rounded_rectangle([0, 0, w - 1, h - 1], radius=r, outline=color, width=line_t)
|
||||
else:
|
||||
draw.rectangle([0, 0, w - 1, h - 1], outline=color, width=line_t)
|
||||
inset = line_t + gap
|
||||
if w - 2 * inset > 1 and h - 2 * inset > 1:
|
||||
inner_r = max(0, min(r - inset, (w - 1 - 2 * inset) // 2, (h - 1 - 2 * inset) // 2)) if r else 0
|
||||
if inner_r:
|
||||
draw.rounded_rectangle([inset, inset, w - 1 - inset, h - 1 - inset], radius=inner_r,
|
||||
outline=color, width=line_t)
|
||||
else:
|
||||
draw.rectangle([inset, inset, w - 1 - inset, h - 1 - inset], outline=color, width=line_t)
|
||||
return
|
||||
|
||||
if style == "solid":
|
||||
if r:
|
||||
draw.rounded_rectangle([0, 0, w - 1, h - 1], radius=r, outline=color, width=t)
|
||||
else:
|
||||
draw.rectangle([0, 0, w - 1, h - 1], outline=color, width=t)
|
||||
return
|
||||
|
||||
# dashed/dotted trace the same centered-on-the-edge path solid/
|
||||
# fancy's rectangle outline draws, so all four styles sit at the
|
||||
# same inset regardless of which is chosen.
|
||||
half = t / 2
|
||||
x0, y0, x1, y1 = half, half, w - 1 - half, h - 1 - half
|
||||
edges = [(x0, y0, x1, y0), (x1, y0, x1, y1), (x1, y1, x0, y1), (x0, y1, x0, y0)]
|
||||
if style == "dashed":
|
||||
dash, gap = t * 3, t * 2
|
||||
for ex0, ey0, ex1, ey1 in edges:
|
||||
_dashed_edge(draw, ex0, ey0, ex1, ey1, t, color, dash, gap)
|
||||
elif style == "dotted":
|
||||
spacing = max(t * 2, t + 4)
|
||||
for ex0, ey0, ex1, ey1 in edges:
|
||||
_dotted_edge(draw, ex0, ey0, ex1, ey1, t, color, spacing)
|
||||
|
||||
|
||||
# How each orientation maps the logically-composed image onto the native
|
||||
# 800x480 panel. "portrait"/"portrait_flipped" compose at 480x800 (so the
|
||||
# crop ratio matches how the frame actually hangs) and rotate into native
|
||||
@@ -65,12 +187,48 @@ DEFAULT_PALETTE_RGB = [
|
||||
|
||||
PALETTE_LABELS = ["Black", "White", "Yellow", "Red", "Blue", "Green"]
|
||||
|
||||
# A community-measured alternative starting point for the same 6 slots,
|
||||
# ported (data only, not code) from paperlesspaper/epdoptimize's
|
||||
# src/dither/data/default-palettes.json "spectra6" entry (Apache
|
||||
# License 2.0, https://github.com/paperlesspaper/epdoptimize) -- offered
|
||||
# as a one-click "Load calibrated preset" in the Advanced configuration
|
||||
# UI, not a new default: unlike DEFAULT_PALETTE_RGB above, these are an
|
||||
# actual panel's measured appearance rather than idealized primaries
|
||||
# (real Spectra 6 white/black are notably duller than pure #fff/#000),
|
||||
# but measured from a different unit than any given frame's actual
|
||||
# panel -- panel_style.py's own docstring already notes units vary
|
||||
# enough to be worth calibrating per frame, and this hasn't been
|
||||
# verified against this project's own hardware.
|
||||
CALIBRATED_SPECTRA6_RGB = [
|
||||
(0x1F, 0x22, 0x26), # BLACK
|
||||
(0xB9, 0xC7, 0xC9), # WHITE
|
||||
(0xC1, 0xBB, 0x1E), # YELLOW
|
||||
(0x62, 0x20, 0x1E), # RED
|
||||
(0x23, 0x3F, 0x8E), # BLUE
|
||||
(0x35, 0x56, 0x3A), # GREEN
|
||||
]
|
||||
|
||||
# The panel's actual 4-bit color codes (see firmware/components/epd7in3e),
|
||||
# in the same order as DEFAULT_PALETTE_RGB/PALETTE_LABELS -- fixed by the
|
||||
# hardware protocol, never user-configurable. 0x4 is intentionally unused
|
||||
# upstream.
|
||||
PANEL_CODES = [0x0, 0x1, 0x2, 0x3, 0x5, 0x6]
|
||||
|
||||
# Per-widget optional border (models.Widget.border_style, see
|
||||
# draw_widget_border below). "none" is the default/no-op; the rest are
|
||||
# thickness-px strokes inset within the widget's own region.
|
||||
BORDER_STYLES = ["none", "solid", "dashed", "dotted", "fancy"]
|
||||
BORDER_STYLE_LABELS = {
|
||||
"none": "None",
|
||||
"solid": "Solid",
|
||||
"dashed": "Dashed",
|
||||
"dotted": "Dotted",
|
||||
"fancy": "Fancy (double line)",
|
||||
}
|
||||
MIN_BORDER_THICKNESS = 1
|
||||
MAX_BORDER_THICKNESS = 8
|
||||
DEFAULT_BORDER_THICKNESS = 3
|
||||
|
||||
|
||||
def palette_to_hex(palette_rgb: list) -> list[str]:
|
||||
"""[(0,0,0), ...] -> ["#000000", ...], for pre-filling the Advanced
|
||||
@@ -78,6 +236,21 @@ def palette_to_hex(palette_rgb: list) -> list[str]:
|
||||
return ["#%02x%02x%02x" % tuple(c) for c in palette_rgb]
|
||||
|
||||
|
||||
def resolve_border_color(color_index: int, palette_rgb: list | None) -> tuple[int, int, int]:
|
||||
"""Widget.border_color_index -> an actual RGB tuple, against this
|
||||
frame's tuned palette if it has one (falls back to
|
||||
DEFAULT_PALETTE_RGB) -- so a border always renders as one of the
|
||||
panel's real 6 ink colors and never needs to be dithered, same
|
||||
reasoning as the weather/battery icons' exact-panel-ink-RGB fills
|
||||
(see docs/widgets.md). Out-of-range indexes (a stale value from a
|
||||
frame that used to have more colors, though that never happens
|
||||
today) fall back to Black rather than raising."""
|
||||
palette = palette_rgb or DEFAULT_PALETTE_RGB
|
||||
if 0 <= color_index < len(palette):
|
||||
return tuple(palette[color_index])
|
||||
return tuple(palette[0])
|
||||
|
||||
|
||||
def hex_to_rgb(hex_str: str) -> tuple[int, int, int] | None:
|
||||
""""#1a2b3c" -> (26, 43, 60), or None for anything that isn't exactly
|
||||
a 6-hex-digit color (what <input type="color"> always sends, but a
|
||||
@@ -197,6 +370,13 @@ DISPLAY_MODE_LABELS = {
|
||||
DEFAULT_DISPLAY_MODE = "crop_faces"
|
||||
LETTERBOX_BG = (255, 255, 255)
|
||||
|
||||
# Static-image widget only offers a subset of DISPLAY_MODES -- no face
|
||||
# detection for an uploaded image, so "crop_faces" (which silently falls
|
||||
# back to crop_fill anyway, see compose_into) would just be a confusing
|
||||
# duplicate entry in that dialog's dropdown.
|
||||
STATIC_DISPLAY_MODES = ["crop_fill", "stretch_fill", "letterbox"]
|
||||
DEFAULT_STATIC_DISPLAY_MODE = "crop_fill"
|
||||
|
||||
|
||||
def _placement_transform(
|
||||
img_width: int, img_height: int, target_w: int, target_h: int,
|
||||
@@ -358,6 +538,71 @@ def render_frame(source: Image.Image, faces: list[dict] | None = None,
|
||||
return _transpose_and_pack(quantized, orientation)
|
||||
|
||||
|
||||
def _png_bytes(img: Image.Image) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
img.convert("RGB").save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def render_panel(regions: list[tuple[tuple[int, int, int, int], Image.Image]], orientation: str = "landscape",
|
||||
palette_rgb: list | None = None, color_boost: float = 1.0, contrast_boost: float = 1.0,
|
||||
dither_strength: float = 1.0, manage: dict | None = None, as_png: bool = False,
|
||||
capture_snapshot: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""The widget system's compositor -- generalizes render_frame's tail
|
||||
(paste, enhance once, overlay once, quantize once, pack once) from
|
||||
"compose one photo" to "paste N already-rendered regions, then run
|
||||
the same single shared pipeline over the result." Not a
|
||||
restructuring: the calendar mode's old photo-inlay feature already
|
||||
pasted a second, independently-composed image onto the canvas before
|
||||
`_enhance`/`_quantize` ran exactly once over the whole thing -- this
|
||||
just generalizes that from a fixed 1-2 region split to an arbitrary
|
||||
list.
|
||||
|
||||
Each region is (rect, image): rect is (x, y, w, h) in *logical*
|
||||
(pre-rotation) canvas space -- the same space logical_render_size(
|
||||
orientation) describes, and what app/grid.py's cell_to_pixels()
|
||||
produces -- and image is an already-composed RGB image exactly w x h
|
||||
in size (e.g. from compose_into() for a photo/whiteboard widget, or
|
||||
calendar_render's own builder for a calendar widget). Regions are
|
||||
expected not to overlap (see models.Widget's docstring on why) --
|
||||
this function doesn't enforce that itself, callers/the placement API
|
||||
do, since by the time rendering happens it's too late to do anything
|
||||
but paste in whatever order they're given (later entries would just
|
||||
paint over earlier ones).
|
||||
|
||||
Quantizing/dithering the *whole* composited canvas once, rather than
|
||||
each region separately before pasting, is what keeps a 6-color
|
||||
e-ink panel's dithering pattern consistent across a widget boundary
|
||||
instead of showing a visible seam where two independently-dithered
|
||||
regions meet.
|
||||
|
||||
as_png=True returns a normal browser-viewable PNG in logical (upright)
|
||||
orientation instead of packed native-panel bytes, same convention as
|
||||
render_preview_png -- used for the web UI's live "how it's displaying"
|
||||
thumbnail.
|
||||
|
||||
capture_snapshot=True (only meaningful alongside as_png=False) returns
|
||||
(packed_bytes, png_bytes) instead of just packed_bytes -- both derived
|
||||
from the same already-quantized canvas, so a device-facing render can
|
||||
also persist a browser-viewable copy (see routers/device.py's
|
||||
_record_last_displayed) without re-running composition/quantization a
|
||||
second time."""
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
canvas = Image.new("RGB", (logical_w, logical_h), LETTERBOX_BG)
|
||||
for (x, y, w, h), region_img in regions:
|
||||
canvas.paste(region_img.convert("RGB"), (x, y))
|
||||
|
||||
fitted = _enhance(canvas, color_boost, contrast_boost)
|
||||
fitted = _apply_manage_overlay(fitted, manage)
|
||||
quantized = _quantize(fitted, palette_rgb, dither_strength)
|
||||
if as_png:
|
||||
return _png_bytes(quantized)
|
||||
packed = _transpose_and_pack(quantized, orientation)
|
||||
if capture_snapshot:
|
||||
return packed, _png_bytes(quantized)
|
||||
return packed
|
||||
|
||||
|
||||
def render_preview_png(source: Image.Image, faces: list[dict] | None = None,
|
||||
orientation: str = "landscape", palette_rgb: list | None = None,
|
||||
display_mode: str = DEFAULT_DISPLAY_MODE, color_boost: float = 1.0,
|
||||
@@ -371,14 +616,13 @@ def render_preview_png(source: Image.Image, faces: list[dict] | None = None,
|
||||
fitted = _enhance(_compose(source, faces, orientation, display_mode), color_boost, contrast_boost)
|
||||
fitted = _apply_manage_overlay(fitted, manage)
|
||||
quantized = _quantize(fitted, palette_rgb, dither_strength)
|
||||
buf = io.BytesIO()
|
||||
quantized.convert("RGB").save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
return _png_bytes(quantized)
|
||||
|
||||
|
||||
def render_placeholder(lines: list[str], qr_url: str | None = None,
|
||||
orientation: str = "landscape", palette_rgb: list | None = None,
|
||||
manage: dict | None = None) -> bytes:
|
||||
manage: dict | None = None, as_png: bool = False,
|
||||
capture_snapshot: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""A readable full-panel message (plus an optional QR code) in the
|
||||
same packed format as render_frame -- what /frame/image serves for a
|
||||
frame that isn't claimed or configured yet, so a fresh device shows
|
||||
@@ -386,15 +630,16 @@ def render_placeholder(lines: list[str], qr_url: str | None = None,
|
||||
|
||||
`manage`, same as render_frame's -- lets the manage button still work
|
||||
(at minimum, the scan-to-manage QR) on a frame that isn't configured
|
||||
yet."""
|
||||
from PIL import ImageDraw, ImageFont
|
||||
|
||||
yet. `capture_snapshot`, same as render_panel's -- (packed, png)
|
||||
instead of just packed."""
|
||||
margin = 24
|
||||
logical_w, logical_h = logical_render_size(orientation)
|
||||
img = Image.new("RGB", (logical_w, logical_h), (255, 255, 255))
|
||||
draw = ImageDraw.Draw(img)
|
||||
draw = ImageDraw.Draw(img) # measurement only (textbbox/textlength) -- painting goes through draw_text
|
||||
|
||||
title_font = ImageFont.load_default(size=34)
|
||||
body_font = ImageFont.load_default(size=24)
|
||||
max_text_w = logical_w - margin * 2
|
||||
|
||||
qr_img = None
|
||||
if qr_url:
|
||||
@@ -409,19 +654,39 @@ def render_placeholder(lines: list[str], qr_url: str | None = None,
|
||||
scale = max(1, target // raw.width)
|
||||
qr_img = raw.resize((raw.width * scale, raw.height * scale), Image.NEAREST)
|
||||
|
||||
# Word-wrap each input line to the panel's actual width (portrait is
|
||||
# much narrower than landscape -- a line written assuming ~800px
|
||||
# would otherwise run straight off the edge) before laying anything
|
||||
# out, so wrapped sub-lines count toward the vertical centering below.
|
||||
def wrap(text: str, font) -> list[str]:
|
||||
words = text.split()
|
||||
if not words:
|
||||
return [text]
|
||||
out, current = [], words[0]
|
||||
for word in words[1:]:
|
||||
candidate = f"{current} {word}"
|
||||
if draw.textlength(candidate, font=font) <= max_text_w:
|
||||
current = candidate
|
||||
else:
|
||||
out.append(current)
|
||||
current = word
|
||||
out.append(current)
|
||||
return out
|
||||
|
||||
# Vertical layout: text block, then QR under it, centered as a group.
|
||||
line_heights = []
|
||||
for i, line in enumerate(lines):
|
||||
font = title_font if i == 0 else body_font
|
||||
bbox = draw.textbbox((0, 0), line, font=font)
|
||||
line_heights.append((line, font, bbox[2] - bbox[0], bbox[3] - bbox[1]))
|
||||
for sub_line in wrap(line, font):
|
||||
bbox = draw.textbbox((0, 0), sub_line, font=font)
|
||||
line_heights.append((sub_line, font, bbox[2] - bbox[0], bbox[3] - bbox[1]))
|
||||
gap = 14
|
||||
text_h = sum(h for _, _, _, h in line_heights) + gap * (len(line_heights) - 1 if line_heights else 0)
|
||||
total_h = text_h + (qr_img.height + 28 if qr_img else 0)
|
||||
y = max(20, (logical_h - total_h) // 2)
|
||||
|
||||
for line, font, w, h in line_heights:
|
||||
draw.text(((logical_w - w) // 2, y), line, fill=(0, 0, 0), font=font)
|
||||
draw_text(img, ((logical_w - w) // 2, y), line, font)
|
||||
y += h + gap
|
||||
|
||||
if qr_img:
|
||||
@@ -429,4 +694,9 @@ def render_placeholder(lines: list[str], qr_url: str | None = None,
|
||||
|
||||
img = _apply_manage_overlay(img, manage)
|
||||
quantized = _quantize(img, palette_rgb, dither_strength=1.0)
|
||||
return _transpose_and_pack(quantized, orientation)
|
||||
if as_png:
|
||||
return _png_bytes(quantized)
|
||||
packed = _transpose_and_pack(quantized, orientation)
|
||||
if capture_snapshot:
|
||||
return packed, _png_bytes(quantized)
|
||||
return packed
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Decodes an arbitrary uploaded file (PNG/JPEG/GIF/BMP/WEBP/TIFF/PDF/...)
|
||||
into a plain RGB PIL image, for the static-image widget (see routers/
|
||||
api_widgets.py's api_widget_static_upload, app/widgets/static_image.py).
|
||||
The result is stored (as PNG bytes) rather than the original upload, so
|
||||
render() never needs to re-run PDF/GIF decoding on every panel refresh --
|
||||
this module only runs once, at upload time.
|
||||
|
||||
PDF decoding uses pypdfium2 (Google's PDFium bindings -- BSD-3-Clause/
|
||||
Apache-2.0, no copyleft exposure) rather than a GPL/AGPL alternative
|
||||
like PyMuPDF, per CLAUDE.md's copyleft-dependency convention (a check
|
||||
that only applies to copyleft/unclear licenses -- this one's plainly
|
||||
permissive, so no explicit flag was needed here)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
import pypdfium2 as pdfium
|
||||
from fastapi import HTTPException
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
MAX_UPLOAD_BYTES = 25 * 1024 * 1024 # generous for a single image/PDF page; stops an accidental huge upload
|
||||
# ~144 DPI off a PDF's 72-DPI native unit -- comfortably above the panel's
|
||||
# own 800x480, without ballooning render time/memory on a poster-sized page.
|
||||
PDF_RENDER_SCALE = 2.0
|
||||
|
||||
|
||||
def decode_upload(data: bytes) -> Image.Image:
|
||||
"""Raises HTTPException(400) for anything that isn't a recognizable
|
||||
image or PDF. Detects PDF by magic bytes, not the client-supplied
|
||||
filename/content-type (neither is trustworthy). A PDF renders only
|
||||
its first page -- there's no "which page" concept for a single-image
|
||||
widget."""
|
||||
if len(data) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(400, f"File is too large (max {MAX_UPLOAD_BYTES // (1024 * 1024)}MB)")
|
||||
if data.startswith(b"%PDF-"):
|
||||
return _decode_pdf(data)
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
except UnidentifiedImageError:
|
||||
raise HTTPException(400, "Not a recognizable image or PDF file") from None
|
||||
return img.convert("RGB")
|
||||
|
||||
|
||||
def _decode_pdf(data: bytes) -> Image.Image:
|
||||
try:
|
||||
pdf = pdfium.PdfDocument(data)
|
||||
if len(pdf) == 0:
|
||||
raise HTTPException(400, "PDF has no pages")
|
||||
bitmap = pdf[0].render(scale=PDF_RENDER_SCALE)
|
||||
except pdfium.PdfiumError as e:
|
||||
raise HTTPException(400, f"Could not read PDF: {e}") from e
|
||||
return bitmap.to_pil().convert("RGB")
|
||||
@@ -80,10 +80,10 @@ class ImmichClient:
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def create_share_link(self, asset_id: str, expires_in_s: int) -> str:
|
||||
"""Creates a public, view-only Immich share link for a single
|
||||
asset, expiring expires_in_s seconds from now, and returns its
|
||||
public URL. Used by the manage-button overlay's share QR --
|
||||
def create_share_link(self, asset_ids: list[str], expires_in_s: int) -> str:
|
||||
"""Creates a public, view-only Immich share link covering one or
|
||||
more assets, expiring expires_in_s seconds from now, and returns
|
||||
its public URL. Used by the manage-button overlay's share QR --
|
||||
created lazily (only when someone actually scans it), not when
|
||||
the button's pressed, so the expiry clock starts when it's
|
||||
actually used."""
|
||||
@@ -93,7 +93,7 @@ class ImmichClient:
|
||||
headers=self._headers,
|
||||
json={
|
||||
"type": "INDIVIDUAL",
|
||||
"assetIds": [asset_id],
|
||||
"assetIds": list(asset_ids),
|
||||
"expiresAt": expires_at,
|
||||
"allowUpload": False,
|
||||
"allowDownload": True,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Root-logger configuration: a rotating file handler under the same
|
||||
/data volume as the sqlite DB and legacy config.json, so the admin log
|
||||
viewer has something to read and log content survives container
|
||||
restarts -- a redeploy happens on every push to main touching
|
||||
server/**, which would make an in-memory-only log buffer nearly
|
||||
useless in practice. Before this, the root logger had no handler at
|
||||
all, so every module's logger.info() call (user creation, claims,
|
||||
password resets, ...) was silently dropped rather than merely
|
||||
un-viewable -- this fixes that too, not just adds a viewer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
LOG_PATH = Path(os.environ.get("LOG_PATH", "/data/server.log"))
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
handler = RotatingFileHandler(LOG_PATH, maxBytes=2_000_000, backupCount=3)
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||||
root = logging.getLogger()
|
||||
root.addHandler(handler)
|
||||
root.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
|
||||
|
||||
|
||||
def read_log_tail(lines: int) -> str:
|
||||
if not LOG_PATH.exists():
|
||||
return ""
|
||||
text = LOG_PATH.read_text(errors="replace")
|
||||
return "\n".join(text.splitlines()[-lines:])
|
||||
+64
-19
@@ -4,7 +4,10 @@ for the panel, and serves ESP32 frames ready-to-display images.
|
||||
This module is assembly only -- routes live in app/routers/:
|
||||
device.py the firmware-facing /frame/* protocol (paths frozen)
|
||||
api_frames.py the web UI's JSON API, /api/frames/{id}/...
|
||||
frame_pages.py the per-frame Photos/Configuration/Stats pages
|
||||
api_widgets.py widget CRUD + grid placement, /api/frames/{id}/widgets
|
||||
api_layouts.py named, user-owned saved layouts, /api/layouts,
|
||||
/api/frames/{id}/layouts
|
||||
frame_pages.py the per-frame Photos/Configuration/Layout/Stats pages
|
||||
pages.py setup/login/claim/settings/admin
|
||||
manage.py the limited manage-QR surface (/m/, /api/m/)
|
||||
Storage is SQLite via models.py/db.py; migration.py imports a
|
||||
@@ -13,14 +16,16 @@ pre-database config.json deployment on first boot."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy import select
|
||||
|
||||
from . import migration
|
||||
from . import html_render, logging_setup, migration
|
||||
from .auth import (
|
||||
browser_token_valid,
|
||||
current_user,
|
||||
@@ -30,21 +35,64 @@ from .auth import (
|
||||
)
|
||||
from .db import SessionLocal
|
||||
from .models import Frame
|
||||
from .routers import api_frames, device, frame_pages, manage, pages
|
||||
from .routers import api_frames, api_layouts, api_widgets, device, frame_pages, manage, pages
|
||||
from .routers.common import shell_context
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Before anything else logs: a handler exists to catch it, and it lands in
|
||||
# the same persistent volume the admin log viewer reads from.
|
||||
logging_setup.configure_logging()
|
||||
|
||||
# Schema + legacy-config import, before the first request is served.
|
||||
migration.run_migrations()
|
||||
|
||||
app = FastAPI(title="ESPresso Frame Server")
|
||||
@asynccontextmanager
|
||||
async def _lifespan(app: FastAPI):
|
||||
"""Startup does nothing browser-related -- html_render.start() is
|
||||
lazy (only the weather widget's opt-in "modern" render style ever
|
||||
triggers it, see that module's docstring), so a deployment that
|
||||
never uses it never launches Chromium or needs Playwright's browser
|
||||
binaries installed. Shutdown calls html_render.stop() unconditionally
|
||||
(a no-op if it was never started) so a server restart never leaves
|
||||
an orphaned Chromium process running."""
|
||||
yield
|
||||
html_render.stop()
|
||||
|
||||
|
||||
app = FastAPI(title="ESPresso Frame Server", lifespan=_lifespan)
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def log_device_requests(request: Request, call_next):
|
||||
"""Access log for the firmware-facing /frame/* protocol -- the admin
|
||||
log viewer otherwise only ever shows exceptions (device.py logs
|
||||
those, not successful requests), so a slow-but-200 request or a
|
||||
device hammering a stale/wrong token leaves no trace at all. Logs
|
||||
the device id (query param, not the token -- never log credentials)
|
||||
and wall time, which is exactly what's needed to spot a request that
|
||||
blew past the firmware's fixed HTTP timeout without technically
|
||||
failing server-side."""
|
||||
if not request.url.path.startswith("/frame/"):
|
||||
return await call_next(request)
|
||||
start = time.monotonic()
|
||||
device_id = request.query_params.get("id", "") or "-"
|
||||
response = await call_next(request)
|
||||
elapsed_ms = (time.monotonic() - start) * 1000
|
||||
logger.info(
|
||||
"%s %s id=%s -> %d (%.0fms)",
|
||||
request.method, request.url.path, device_id, response.status_code, elapsed_ms,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
||||
|
||||
app.include_router(device.router)
|
||||
app.include_router(api_frames.router)
|
||||
app.include_router(api_widgets.router)
|
||||
app.include_router(api_layouts.router)
|
||||
app.include_router(frame_pages.router)
|
||||
app.include_router(pages.router)
|
||||
app.include_router(manage.router)
|
||||
@@ -55,26 +103,23 @@ def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def _device_credential_redirect(request: Request, db, allow_legacy: bool) -> str | None:
|
||||
@app.get("/sw.js")
|
||||
def service_worker() -> FileResponse:
|
||||
# Served from / rather than /static/sw.js so its default scope is the
|
||||
# whole app -- a SW can only ever control paths at or below its own URL.
|
||||
return FileResponse("app/static/sw.js", media_type="application/javascript")
|
||||
|
||||
|
||||
def _device_credential_redirect(request: Request, db) -> str | None:
|
||||
"""The on-frame manage QR points at the server root with the device's
|
||||
own credentials (new firmware: ?id=&token=; deployed firmware:
|
||||
?token=<legacy shared token>). Those scans get the frame's limited
|
||||
manage page -- never the full UI, which requires a login.
|
||||
allow_legacy is False before /setup has run: at that point a bare
|
||||
?token= hit is the admin coming through the token prompt to do
|
||||
first-run setup, not a QR scan."""
|
||||
own credentials (?id=&token=). Those scans get the frame's limited
|
||||
manage page -- never the full UI, which requires a login."""
|
||||
device_id = request.query_params.get("id", "").strip().lower()
|
||||
token = request.query_params.get("token", "")
|
||||
if device_id and token:
|
||||
frame = db.scalars(select(Frame).where(Frame.device_id == device_id)).first()
|
||||
if frame is not None and token == frame.device_token:
|
||||
return f"/m/{frame.manage_token}"
|
||||
if allow_legacy and token and management_token() and token == management_token():
|
||||
frame = db.scalars(
|
||||
select(Frame).where(Frame.legacy_token_enabled == True) # noqa: E712
|
||||
).first()
|
||||
if frame is not None:
|
||||
return f"/m/{frame.manage_token}"
|
||||
return None
|
||||
|
||||
|
||||
@@ -85,7 +130,7 @@ def index(request: Request):
|
||||
else is walked through setup/login."""
|
||||
with SessionLocal() as db:
|
||||
have_users = users_exist(db)
|
||||
manage_redirect = _device_credential_redirect(request, db, allow_legacy=have_users)
|
||||
manage_redirect = _device_credential_redirect(request, db)
|
||||
if manage_redirect is not None:
|
||||
return RedirectResponse(manage_redirect, status_code=303)
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ from __future__ import annotations
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from . import panel_style
|
||||
from .image_pipeline import draw_text
|
||||
|
||||
PADDING = 16
|
||||
QR_TEXT_GAP = 8
|
||||
LINE_GAP = 4
|
||||
@@ -25,9 +28,12 @@ BODY_FONT_SIZE = 20
|
||||
|
||||
BATTERY_ICON_W = 40
|
||||
BATTERY_ICON_H = 22
|
||||
BATTERY_ICON_STROKE = 2
|
||||
# Stroke/nub width/height are no longer fixed constants here -- panel_
|
||||
# style.draw_battery_icon derives them from icon_w/icon_h itself (same
|
||||
# formula widgets/battery.py's own icon already used). BATTERY_NUB_W
|
||||
# below is kept only as this box's own outer-width estimate, not fed
|
||||
# into the icon drawing itself.
|
||||
BATTERY_NUB_W = 5
|
||||
BATTERY_NUB_H = 10
|
||||
BATTERY_ICON_TEXT_GAP = 8
|
||||
BATTERY_REGION_GAP = 8 # vertical gap below the manage QR box
|
||||
|
||||
@@ -35,10 +41,6 @@ FACE_LABEL_PADDING = 8
|
||||
FACE_LABEL_GAP = 4 # distance from the face's anchor point to the label box
|
||||
|
||||
|
||||
def _font(size: int) -> ImageFont.ImageFont:
|
||||
return ImageFont.load_default(size=size)
|
||||
|
||||
|
||||
def _qr_image(url: str, target_px: int = QR_TARGET_PX) -> Image.Image:
|
||||
import qrcode
|
||||
|
||||
@@ -50,7 +52,7 @@ def _qr_image(url: str, target_px: int = QR_TARGET_PX) -> Image.Image:
|
||||
return raw.resize((raw.width * scale, raw.height * scale), Image.NEAREST)
|
||||
|
||||
|
||||
def _text_box(draw: ImageDraw.ImageDraw, lines: list[str], font: ImageFont.ImageFont) -> tuple[int, int]:
|
||||
def _text_box(draw: ImageDraw.ImageDraw, lines: list[str], font: ImageFont.FreeTypeFont) -> tuple[int, int]:
|
||||
"""(width, height) of `lines` stacked with LINE_GAP between them, at
|
||||
`font` -- the box _draw_text_box below will need."""
|
||||
w = 0
|
||||
@@ -62,13 +64,13 @@ def _text_box(draw: ImageDraw.ImageDraw, lines: list[str], font: ImageFont.Image
|
||||
return w, h
|
||||
|
||||
|
||||
def _draw_centered_lines(draw: ImageDraw.ImageDraw, lines: list[str], font: ImageFont.ImageFont,
|
||||
def _draw_centered_lines(img: Image.Image, draw: ImageDraw.ImageDraw, lines: list[str], font: ImageFont.FreeTypeFont,
|
||||
center_x: int, top: int) -> None:
|
||||
y = top
|
||||
for line in lines:
|
||||
bbox = draw.textbbox((0, 0), line, font=font)
|
||||
w = bbox[2] - bbox[0]
|
||||
draw.text((center_x - w // 2, y), line, fill=(0, 0, 0), font=font)
|
||||
draw_text(img, (center_x - w // 2, y), line, font)
|
||||
y += (bbox[3] - bbox[1]) + LINE_GAP
|
||||
|
||||
|
||||
@@ -80,7 +82,8 @@ def _draw_qr_box(img: Image.Image, draw: ImageDraw.ImageDraw, url: str, caption:
|
||||
(the battery, below the manage QR) use it instead of recomputing the
|
||||
same geometry a second time."""
|
||||
qr_img = _qr_image(url)
|
||||
text_w, text_h = _text_box(draw, caption, _font(TITLE_FONT_SIZE)) if caption else (0, 0)
|
||||
caption_font = panel_style.font_bold(TITLE_FONT_SIZE)
|
||||
text_w, text_h = _text_box(draw, caption, caption_font) if caption else (0, 0)
|
||||
content_w = max(qr_img.width, text_w)
|
||||
content_h = qr_img.height + (QR_TEXT_GAP + text_h if caption else 0)
|
||||
|
||||
@@ -88,25 +91,27 @@ def _draw_qr_box(img: Image.Image, draw: ImageDraw.ImageDraw, url: str, caption:
|
||||
h = content_h + PADDING * 2
|
||||
x0, y0 = _corner_origin(img.size, (w, h), corner)
|
||||
|
||||
draw.rectangle([x0, y0, x0 + w, y0 + h], fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
draw.rounded_rectangle([x0, y0, x0 + w, y0 + h], radius=panel_style.CHIP_RADIUS,
|
||||
fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
center_x = x0 + w // 2
|
||||
img.paste(qr_img, (center_x - qr_img.width // 2, y0 + PADDING))
|
||||
if caption:
|
||||
_draw_centered_lines(draw, caption, _font(TITLE_FONT_SIZE), center_x, y0 + PADDING + qr_img.height + QR_TEXT_GAP)
|
||||
_draw_centered_lines(img, draw, caption, caption_font, center_x, y0 + PADDING + qr_img.height + QR_TEXT_GAP)
|
||||
return x0, y0, w, h
|
||||
|
||||
|
||||
def _draw_text_box(img: Image.Image, draw: ImageDraw.ImageDraw, lines: list[str], corner: str) -> None:
|
||||
"""White-padded box with centered text lines, placed in one of the
|
||||
panel's four corners."""
|
||||
font = _font(BODY_FONT_SIZE)
|
||||
font = panel_style.font_regular(BODY_FONT_SIZE)
|
||||
text_w, text_h = _text_box(draw, lines, font)
|
||||
w = text_w + PADDING * 2
|
||||
h = text_h + PADDING * 2
|
||||
x0, y0 = _corner_origin(img.size, (w, h), corner)
|
||||
|
||||
draw.rectangle([x0, y0, x0 + w, y0 + h], fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
_draw_centered_lines(draw, lines, font, x0 + w // 2, y0 + PADDING)
|
||||
draw.rounded_rectangle([x0, y0, x0 + w, y0 + h], radius=panel_style.CHIP_RADIUS,
|
||||
fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
_draw_centered_lines(img, draw, lines, font, x0 + w // 2, y0 + PADDING)
|
||||
|
||||
|
||||
def _corner_origin(img_size: tuple[int, int], box_size: tuple[int, int], corner: str) -> tuple[int, int]:
|
||||
@@ -126,8 +131,12 @@ def _draw_battery(img: Image.Image, draw: ImageDraw.ImageDraw, percent: int, anc
|
||||
"""Battery glyph + "NN%" text, right-aligned under the given anchor
|
||||
box (the manage QR box) -- a sensible default position, not a
|
||||
constraint anything else has to route around; move this call site's
|
||||
arguments to place it anywhere else instead."""
|
||||
font = _font(BODY_FONT_SIZE)
|
||||
arguments to place it anywhere else instead. The glyph itself is
|
||||
panel_style.draw_battery_icon -- the one shared implementation
|
||||
replacing what used to be a second, independent copy of widgets/
|
||||
battery.py's own icon-drawing code (same shape, same red/yellow/
|
||||
green thresholds, previously kept in sync by convention only)."""
|
||||
font = panel_style.font_regular(BODY_FONT_SIZE)
|
||||
text = f"{percent}%"
|
||||
icon_total_w = BATTERY_ICON_W + BATTERY_NUB_W
|
||||
text_w = draw.textlength(text, font=font)
|
||||
@@ -139,17 +148,14 @@ def _draw_battery(img: Image.Image, draw: ImageDraw.ImageDraw, percent: int, anc
|
||||
x0 = anchor_x0 + anchor_w - w
|
||||
y0 = anchor_y0 + anchor_h + BATTERY_REGION_GAP
|
||||
|
||||
draw.rectangle([x0, y0, x0 + w, y0 + h], fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
draw.rounded_rectangle([x0, y0, x0 + w, y0 + h], radius=panel_style.CHIP_RADIUS,
|
||||
fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
|
||||
icon_x = x0 + PADDING
|
||||
icon_y = y0 + PADDING + (content_h - BATTERY_ICON_H) // 2
|
||||
draw.rectangle([icon_x, icon_y, icon_x + BATTERY_ICON_W, icon_y + BATTERY_ICON_H], outline=(0, 0, 0),
|
||||
width=BATTERY_ICON_STROKE)
|
||||
nub_y = icon_y + (BATTERY_ICON_H - BATTERY_NUB_H) // 2
|
||||
draw.rectangle([icon_x + BATTERY_ICON_W, nub_y, icon_x + BATTERY_ICON_W + BATTERY_NUB_W, nub_y + BATTERY_NUB_H],
|
||||
fill=(0, 0, 0))
|
||||
draw.text((icon_x + icon_total_w + BATTERY_ICON_TEXT_GAP, y0 + PADDING + (content_h - font.size) // 2),
|
||||
text, fill=(0, 0, 0), font=font)
|
||||
panel_style.draw_battery_icon(draw, icon_x, icon_y, BATTERY_ICON_W, BATTERY_ICON_H, percent)
|
||||
draw_text(img, (icon_x + icon_total_w + BATTERY_ICON_TEXT_GAP, y0 + PADDING + (content_h - font.size) // 2),
|
||||
text, font, panel_style.battery_fill_color(percent))
|
||||
|
||||
|
||||
def _draw_face_label(img: Image.Image, draw: ImageDraw.ImageDraw, name: str, anchor_x: int, anchor_y: int) -> None:
|
||||
@@ -157,7 +163,7 @@ def _draw_face_label(img: Image.Image, draw: ImageDraw.ImageDraw, name: str, anc
|
||||
anchor_y) point, flipped above if there's no room below, clamped to
|
||||
stay fully on-panel -- unlike the four corner boxes (always in-bounds
|
||||
by construction), a face can be anywhere, including near an edge."""
|
||||
font = _font(BODY_FONT_SIZE)
|
||||
font = panel_style.font_regular(BODY_FONT_SIZE)
|
||||
text_w = draw.textlength(name, font=font)
|
||||
bbox = draw.textbbox((0, 0), name, font=font)
|
||||
text_h = bbox[3] - bbox[1]
|
||||
@@ -173,8 +179,9 @@ def _draw_face_label(img: Image.Image, draw: ImageDraw.ImageDraw, name: str, anc
|
||||
x0 = max(0, min(x0, img_w - w))
|
||||
y0 = max(0, min(y0, img_h - h))
|
||||
|
||||
draw.rectangle([x0, y0, x0 + w, y0 + h], fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
draw.text((x0 + FACE_LABEL_PADDING, y0 + FACE_LABEL_PADDING - bbox[1]), name, fill=(0, 0, 0), font=font)
|
||||
draw.rounded_rectangle([x0, y0, x0 + w, y0 + h], radius=panel_style.CHIP_RADIUS,
|
||||
fill=(255, 255, 255), outline=(0, 0, 0))
|
||||
draw_text(img, (x0 + FACE_LABEL_PADDING, y0 + FACE_LABEL_PADDING - bbox[1]), name, font)
|
||||
|
||||
|
||||
def compose(image: Image.Image, management_url: str, battery_percent: int | None = None,
|
||||
|
||||
+1223
-27
File diff suppressed because it is too large
Load Diff
+594
-64
@@ -19,7 +19,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from sqlalchemy import JSON, Boolean, Float, ForeignKey, Index, Integer, String
|
||||
from sqlalchemy import JSON, Boolean, Float, ForeignKey, Index, Integer, LargeBinary, String
|
||||
from sqlalchemy.ext.mutable import MutableList
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
@@ -48,12 +48,45 @@ class User(Base):
|
||||
# email -- see routers/device.py's frame_battery) go here; blank = no
|
||||
# email configured, both features silently no-op for this user.
|
||||
email: Mapped[str] = mapped_column(String, default="")
|
||||
# Personal iCal/CalDAV .ics subscription URL (no OAuth) for calendar
|
||||
# frame mode -- see calendar_feed.py. Setting this alone shows up
|
||||
# nowhere: a linked frame only pulls this user's events in once
|
||||
# they've also opted in on that frame's own Configuration -> Calendar
|
||||
# card (UserFrame.calendar_included below).
|
||||
# Personal ICS subscription URL (no OAuth) for calendar frame mode --
|
||||
# see calendar_feed.py. Setting this alone shows up nowhere: a linked
|
||||
# frame only pulls this user's events in once they've also added it
|
||||
# on that frame's own Calendar tab (FrameCalendar below).
|
||||
calendar_ics_url: Mapped[str] = mapped_column(String, default="")
|
||||
# A CalDAV account (Nextcloud, Fastmail, iCloud, ...) alongside the
|
||||
# plain ICS subscription above -- see caldav_client.py. calendar_url
|
||||
# is the server's CalDAV entry point the user pasted in, not any one
|
||||
# calendar's own URL; the individual calendars it exposes are
|
||||
# discovered and cached below.
|
||||
calendar_caldav_url: Mapped[str] = mapped_column(String, default="")
|
||||
calendar_caldav_username: Mapped[str] = mapped_column(String, default="")
|
||||
calendar_caldav_password: Mapped[str] = mapped_column(String, default="")
|
||||
# [{"href", "display_name"}, ...] from the last successful
|
||||
# caldav_client.discover_calendars() call, refreshed by Settings'
|
||||
# "Discover calendars" button -- NULL until discovery has ever
|
||||
# succeeded. This is what a frame's Calendar tab offers the user to
|
||||
# add, without hitting the CalDAV server on every page load.
|
||||
calendar_caldav_calendars: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
calendar_caldav_checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
# WebDAV credentials for whiteboard frame mode (see webdav_client.py,
|
||||
# whiteboard.py) -- generic WebDAV, not Nextcloud-specific, but
|
||||
# webdav_reuse_caldav_creds is a convenience for the common case
|
||||
# where it IS the same Nextcloud account as calendar_caldav_*: skip
|
||||
# re-entering the same username/password, since Nextcloud's CalDAV
|
||||
# and general-file-WebDAV both sit under the one account. Doesn't
|
||||
# try to be clever and derive the reuse automatically -- an explicit
|
||||
# opt-in, same as everywhere else in this project defaults features
|
||||
# off rather than silently inferring them.
|
||||
webdav_username: Mapped[str] = mapped_column(String, default="")
|
||||
webdav_password: Mapped[str] = mapped_column(String, default="")
|
||||
webdav_reuse_caldav_creds: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# Optional starting folder for the whiteboard dialog's file-picker
|
||||
# (see routers/api_widgets.py's api_widget_whiteboard_browse) --
|
||||
# purely a convenience for browsing to a file rather than typing its
|
||||
# full URL.
|
||||
# Never used for fetching/rendering itself, which always uses the
|
||||
# frame's own saved whiteboard_url regardless of whether this is set.
|
||||
webdav_base_url: Mapped[str] = mapped_column(String, default="")
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
|
||||
__table_args__ = (
|
||||
@@ -84,13 +117,10 @@ class Frame(Base):
|
||||
__tablename__ = "frames"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 12 lowercase hex chars of the device's full STA MAC. NULL only for
|
||||
# the migrated legacy frame until its device first reports an id.
|
||||
# 12 lowercase hex chars of the device's full STA MAC. NULL until its
|
||||
# device first reports an id.
|
||||
device_id: Mapped[str | None] = mapped_column(String, unique=True, nullable=True)
|
||||
name: Mapped[str] = mapped_column(String, default="")
|
||||
# Renderer dispatch seam for future calendar/canva modes -- only
|
||||
# "photos" is registered today (see routers/device.py RENDERERS).
|
||||
mode: Mapped[str] = mapped_column(String, default="photos")
|
||||
# Whose Immich library this frame pulls from; NULL = unclaimed.
|
||||
owner_user_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
@@ -104,11 +134,6 @@ class Frame(Base):
|
||||
# pushing it in /frame/config responses.
|
||||
device_token_ack: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
manage_token: Mapped[str] = mapped_column(String, unique=True)
|
||||
# Migration window: this frame also accepts the legacy shared
|
||||
# MANAGEMENT_TOKEN (and no-id requests resolve to it). Only ever the
|
||||
# migrated frame #1; cleared from /admin once the device is on
|
||||
# per-frame auth.
|
||||
legacy_token_enabled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
claimed_at: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
|
||||
@@ -119,19 +144,13 @@ class Frame(Base):
|
||||
immich_url: Mapped[str] = mapped_column(String, default="")
|
||||
immich_api_key: Mapped[str] = mapped_column(String, default="")
|
||||
|
||||
# -- settings (attribute names match the old FrameConfig fields) --
|
||||
album_id: Mapped[str] = mapped_column(String, default="")
|
||||
order: Mapped[str] = mapped_column("photo_order", String, default="sequential")
|
||||
# -- settings --
|
||||
refresh_interval_s: Mapped[int] = mapped_column(Integer, default=3600)
|
||||
quiet_hours_enabled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
quiet_hours_start: Mapped[str] = mapped_column(String, default="22:00")
|
||||
quiet_hours_end: Mapped[str] = mapped_column(String, default="07:00")
|
||||
timezone: Mapped[str] = mapped_column(String, default="UTC")
|
||||
# How a photo's aspect ratio is reconciled with the panel's -- see
|
||||
# image_pipeline.DISPLAY_MODES.
|
||||
display_mode: Mapped[str] = mapped_column(String, default="crop_faces")
|
||||
orientation: Mapped[str] = mapped_column(String, default="landscape")
|
||||
queue_target_len: Mapped[int] = mapped_column(Integer, default=20)
|
||||
# Advanced configuration: [[r,g,b], ...] x6 (black/white/yellow/red/
|
||||
# blue/green, matching image_pipeline.PANEL_CODES order) overriding
|
||||
# DEFAULT_PALETTE_RGB for this frame's actual panel. NULL = use the
|
||||
@@ -144,39 +163,19 @@ class Frame(Base):
|
||||
# 0.0-1.0, see image_pipeline._quantize -- 1.0 matches this project's
|
||||
# original always-on full-strength Floyd-Steinberg dithering.
|
||||
dither_strength: Mapped[float] = mapped_column(Float, default=1.0)
|
||||
|
||||
# -- calendar mode (see calendar_feed.py, calendar_render.py,
|
||||
# routers/device.py's RENDERERS["calendar"]) --
|
||||
calendar_view: Mapped[str] = mapped_column(String, default="agenda") # "agenda" | "week" | "month"
|
||||
# Agenda view only; reuses this frame's existing photos-mode album/
|
||||
# queue, not a separate photo setup.
|
||||
calendar_photo_inlay: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# How many periods (unit depends on calendar_view: days/weeks/months)
|
||||
# NEXT/BACK have browsed from "today". Reset to 0 by the next normal
|
||||
# (non-button) /frame/image request, and whenever calendar_view
|
||||
# itself changes -- a stale offset means something different in a
|
||||
# different view's units.
|
||||
calendar_browse_offset: Mapped[int] = mapped_column(Integer, default=0)
|
||||
# Throttled merge-fetch cache (see routers/common.py's
|
||||
# get_or_refresh_calendar_events) -- same shape as the
|
||||
# firmware_update_checked_at/firmware_gitea_latest_version pattern
|
||||
# below. One shared cache for every included user's merged events,
|
||||
# not per-user.
|
||||
calendar_checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
calendar_cached_events: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
# "" when the last merge-fetch fully succeeded, else e.g. "1 of 2
|
||||
# calendars unavailable" -- never names which user's feed failed, a
|
||||
# shared household display shouldn't call out a specific person's
|
||||
# outage to everyone who looks at it.
|
||||
calendar_fetch_summary: Mapped[str] = mapped_column(String, default="")
|
||||
|
||||
# -- state --
|
||||
current_asset_id: Mapped[str] = mapped_column(String, default="")
|
||||
current_asset_set_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
queue: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
queue_cursor: Mapped[int] = mapped_column(Integer, default=0)
|
||||
history: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
excluded_asset_ids: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
# Same shape as palette_rgb/dither_strength above, but scoped to only
|
||||
# the photos widget (widgets/photos.py quantizes against these itself,
|
||||
# before returning -- see its own docstring) -- lets a frame tune the
|
||||
# rest of its widgets' palette/dithering (e.g. a "modern" HTML-
|
||||
# rendered dashboard look) independently of what actually looks best
|
||||
# for real photographs. NULL/1.0 = same defaults as the main fields.
|
||||
photo_palette_rgb: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
photo_dither_strength: Mapped[float] = mapped_column(Float, default=1.0)
|
||||
# Curated visual theme for "modern" (HTML/CSS) style widgets -- see
|
||||
# theme_tokens.THEMES. Frame-level (like palette_rgb/dither_strength
|
||||
# above), not per-widget, since a theme is "how this frame looks."
|
||||
# Widgets rendered in classic (PIL) style ignore this entirely.
|
||||
theme: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
# -- telemetry --
|
||||
battery_percent: Mapped[int] = mapped_column(Integer, default=-1)
|
||||
@@ -203,6 +202,33 @@ class Frame(Base):
|
||||
firmware_update_checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
firmware_gitea_latest_version: Mapped[str] = mapped_column(String, default="")
|
||||
|
||||
# -- hold-for-global-action (see app/global_actions.py) -- holding
|
||||
# NEXT/BACK past hold_duration_ms triggers a global action instead of
|
||||
# the per-widget one that a short press runs (models.FrameButtonAction).
|
||||
# Not scoped to any widget, e.g. cycling saved layouts -- hence its
|
||||
# own pair of frame-level columns rather than living in that table.
|
||||
hold_duration_ms: Mapped[int] = mapped_column(Integer, default=3000)
|
||||
next_hold_action: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
|
||||
back_hold_action: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
|
||||
# Where "cycle saved layouts" resumes from -- the last SavedLayout id
|
||||
# it applied, so repeated holds advance through the list instead of
|
||||
# re-applying the same one every time. Deliberately not a real FK:
|
||||
# this is just a resume cursor, not a relationship needing cascade/
|
||||
# referential integrity -- if that layout's since been deleted or
|
||||
# renamed away, global_actions.cycle_layout just doesn't find it and
|
||||
# starts over from the first one, same as an unset value.
|
||||
last_cycled_layout_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
|
||||
# -- "now displaying" (see routers/device.py's _record_last_displayed,
|
||||
# api_frames.py's /now-displaying endpoint) -- exactly what the last
|
||||
# device-facing render (/frame/image, /frame/advance, /frame/back, or
|
||||
# a global hold action) actually sent, as an upright PNG, so the web
|
||||
# UI's header preview can show it frozen alongside a live "up next"
|
||||
# re-render instead of conflating the two. NULL until a real device
|
||||
# has fetched at least once.
|
||||
last_displayed_image: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True, default=None)
|
||||
last_displayed_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
|
||||
# -- stats (flattened from the old nested FrameStats) --
|
||||
stats_first_seen: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
stats_device_wakes: Mapped[int] = mapped_column(Integer, default=0)
|
||||
@@ -231,14 +257,518 @@ class UserFrame(Base):
|
||||
ForeignKey("frames.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
# Explicit per-(user,frame) opt-in for calendar frame mode -- being
|
||||
# linked to a frame does NOT by itself contribute this user's
|
||||
# calendar to it (deliberate choice, not an oversight: each person's
|
||||
# calendar is their own data to share or not, not something a
|
||||
# frame's controller decides on their behalf). Meaningless if the
|
||||
# user has no calendar_ics_url set. See routers/api_frames.py's
|
||||
# api_calendar_included.
|
||||
calendar_included: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class FrameCalendar(Base):
|
||||
"""One calendar included on one frame -- calendar_key is "ics" (the
|
||||
owner's single calendar_ics_url) or "caldav:<href>" (one of the
|
||||
owner's CalDAV collections; href matches an entry in
|
||||
User.calendar_caldav_calendars). Replaces the old single
|
||||
UserFrame.calendar_included boolean now that a CalDAV account can
|
||||
expose more than one calendar.
|
||||
|
||||
A row only ever gets created by its own owner (adding a calendar to
|
||||
a frame is each person's own data-sharing choice, not something a
|
||||
frame's controller decides on their behalf) -- but once it exists,
|
||||
ANY user linked to the frame may flip included back to False, muting
|
||||
a calendar they'd rather not see on a shared display even though
|
||||
they don't own it. Only the owner may flip it back to True. See
|
||||
routers/api_widgets.py's api_widget_calendar_select.
|
||||
|
||||
Keyed by widget_id, not frame_id -- a frame can hold more than one
|
||||
independent calendar widget (see Widget), each with its own included-
|
||||
calendars set; "included on this frame" stopped being unambiguous
|
||||
the moment that became possible (see migration.py's
|
||||
_ensure_frame_calendars_rekeyed, which re-keyed this table)."""
|
||||
|
||||
__tablename__ = "frame_calendars"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
calendar_key: Mapped[str] = mapped_column(String)
|
||||
# Snapshot label for display -- so the list still reads sensibly even
|
||||
# if the owner's CalDAV account later stops offering this calendar.
|
||||
calendar_label: Mapped[str] = mapped_column(String, default="")
|
||||
included: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
# Index into image_pipeline.DEFAULT_PALETTE_RGB/PALETTE_LABELS (2-5:
|
||||
# Yellow/Red/Blue/Green -- 0/1 are reserved, already the page's
|
||||
# text/background) pinning this calendar's events to a specific
|
||||
# panel color rather than calendar_render.py's old owner-name
|
||||
# auto-cycle. NULL keeps the auto-cycle behavior. Only the calendar's
|
||||
# owner may set this -- see routers/api_widgets.py's api_widget_calendar_color.
|
||||
color_index: Mapped[int | None] = mapped_column(Integer, nullable=True, default=None)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_frame_calendars_unique", "widget_id", "user_id", "calendar_key", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class FrameTaskList(Base):
|
||||
"""One CalDAV task list included on one tasks widget -- calendar_key
|
||||
is "caldav:<href>" (an entry in User.calendar_caldav_calendars; no
|
||||
"ics" variant, unlike FrameCalendar -- a plain ICS subscription has
|
||||
no VTODO collection). Same owner-controls-their-own-data shape as
|
||||
FrameCalendar in every other respect: a row is only ever created by
|
||||
its own owner, but any user linked to the frame may flip included
|
||||
back to False, and only the owner may flip it back to True or set
|
||||
color_index. See routers/api_widgets.py's api_widget_task_list_select/
|
||||
api_widget_task_list_color."""
|
||||
|
||||
__tablename__ = "frame_task_lists"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
calendar_key: Mapped[str] = mapped_column(String)
|
||||
calendar_label: Mapped[str] = mapped_column(String, default="")
|
||||
included: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
color_index: Mapped[int | None] = mapped_column(Integer, nullable=True, default=None)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_frame_task_lists_unique", "widget_id", "user_id", "calendar_key", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Widget(Base):
|
||||
"""One placed/sized content item on a frame's panel -- the unit the
|
||||
widget system replaces the old single Frame.mode with (see
|
||||
app/grid.py for the grid this x/y/w/h is measured in, and app/widgets/
|
||||
for the widget_type -> render/action dispatch registry). Widgets never
|
||||
overlap (enforced server-side in routers/api_widgets.py), which is
|
||||
what keeps compositing simple: no z-order, no blending, just N
|
||||
independent regions pasted onto one shared canvas before a single
|
||||
shared dither/quantize pass (see image_pipeline.render_panel).
|
||||
|
||||
widget_type selects which of the three per-type extension tables below
|
||||
(PhotoWidgetConfig/CalendarWidgetConfig/WhiteboardWidgetConfig) holds
|
||||
this widget's actual settings/state -- a 1:1 relational split rather
|
||||
than one wide table with every type's columns, matching how
|
||||
FrameCalendar/BatteryLog are already their own tables in this
|
||||
codebase rather than crammed onto Frame."""
|
||||
|
||||
__tablename__ = "widgets"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
frame_id: Mapped[int] = mapped_column(ForeignKey("frames.id", ondelete="CASCADE"))
|
||||
widget_type: Mapped[str] = mapped_column(String) # "photos" | "calendar" | "whiteboard" | "tasks" | "static" | "text" | "weather" | "battery"
|
||||
x: Mapped[int] = mapped_column(Integer)
|
||||
y: Mapped[int] = mapped_column(Integer)
|
||||
w: Mapped[int] = mapped_column(Integer)
|
||||
h: Mapped[int] = mapped_column(Integer)
|
||||
# Display/tie-break ordering only (e.g. listing widgets in a UI) --
|
||||
# NOT a z-order, since widgets never overlap. Named sort_order, not
|
||||
# order, to sidestep the SQL-keyword dance Frame.order needed
|
||||
# (mapped to a differently-named column) -- nothing outside this
|
||||
# table needs to match a specific attribute name here.
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
# Optional decorative border, drawn once around this widget's own
|
||||
# region (routers/device.py's _render_widgets) regardless of
|
||||
# widget_type -- a Widget-level property, not a per-type config
|
||||
# column, since every widget type can have one. See
|
||||
# image_pipeline.BORDER_STYLES/draw_widget_border. "none" (the
|
||||
# default) draws nothing, so existing widgets don't suddenly grow a
|
||||
# border. border_color_index indexes into the frame's palette_rgb
|
||||
# (0-5, Black/White/Yellow/Red/Blue/Green) rather than storing an
|
||||
# arbitrary hex -- an exact palette color quantizes with zero
|
||||
# dithering error, same reasoning as the weather/battery icons'
|
||||
# exact-panel-ink-RGB fills (see docs/widgets.md).
|
||||
border_style: Mapped[str] = mapped_column(String, default="none")
|
||||
border_thickness: Mapped[int] = mapped_column(Integer, default=3)
|
||||
border_color_index: Mapped[int] = mapped_column(Integer, default=0)
|
||||
# Text-size multiplier for this widget's own body/title text -- another
|
||||
# Widget-level property regardless of widget_type, same reasoning as
|
||||
# border_style above (any widget type with text can use it). One of
|
||||
# panel_style.FONT_SCALE_CHOICES; 1.0 (unchanged size) for every
|
||||
# existing widget until its dialog's "Text size" picker sets it.
|
||||
font_scale: Mapped[float] = mapped_column(Float, default=1.0)
|
||||
|
||||
__table_args__ = (Index("ix_widgets_frame", "frame_id"),)
|
||||
|
||||
|
||||
class PhotoWidgetConfig(Base):
|
||||
"""One photo widget's settings + queue state. Attribute names match
|
||||
Frame's old photo-queue columns exactly (down to `order`'s same
|
||||
photo_order column-name dodge) -- app/photo_queue.py's 5 functions
|
||||
are duck-typed against these exact names (never isinstance-checked
|
||||
against Frame), so they port unchanged onto this table."""
|
||||
|
||||
__tablename__ = "photo_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
album_id: Mapped[str] = mapped_column(String, default="")
|
||||
order: Mapped[str] = mapped_column("photo_order", String, default="sequential")
|
||||
display_mode: Mapped[str] = mapped_column(String, default="crop_faces")
|
||||
queue_target_len: Mapped[int] = mapped_column(Integer, default=20)
|
||||
current_asset_id: Mapped[str] = mapped_column(String, default="")
|
||||
current_asset_set_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
queue: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
queue_cursor: Mapped[int] = mapped_column(Integer, default=0)
|
||||
history: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
excluded_asset_ids: Mapped[list] = mapped_column(MutableList.as_mutable(JSON), default=list)
|
||||
locked: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class CalendarWidgetConfig(Base):
|
||||
"""One calendar widget's settings + cached-fetch state -- the same
|
||||
fields that used to live as calendar_* columns directly on Frame,
|
||||
minus calendar_photo_inlay (dropped: arbitrary widget placement
|
||||
subsumes what a fixed 50/50 inlay split did, so it's not a special
|
||||
case anymore, just place a photo widget alongside) and minus
|
||||
tasks_* (also dropped: split out into its own standalone widget
|
||||
type, see TaskWidgetConfig, so a task list isn't tied to a
|
||||
calendar's week view/footprint anymore). "Included calendars" is
|
||||
its own table (FrameCalendar), widget_id-keyed so each calendar
|
||||
widget on a frame has its own independent set."""
|
||||
|
||||
__tablename__ = "calendar_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
view: Mapped[str] = mapped_column(String, default="agenda")
|
||||
week_start: Mapped[int] = mapped_column(Integer, default=0)
|
||||
browse_offset: Mapped[int] = mapped_column(Integer, default=0)
|
||||
checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
cached_events: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
fetch_summary: Mapped[str] = mapped_column(String, default="")
|
||||
weather_enabled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
weather_units: Mapped[str] = mapped_column(String, default="fahrenheit")
|
||||
weather_cities: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
weather_checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
weather_cached: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
week_days: Mapped[int] = mapped_column(Integer, default=7)
|
||||
week_layout: Mapped[str] = mapped_column(String, default="horizontal")
|
||||
week_start_offset: Mapped[int] = mapped_column(Integer, default=0)
|
||||
# classic (calendar_render.py) vs modern (app/calendar_html_render.py,
|
||||
# agenda mode only so far -- see that module's docstring) -- see
|
||||
# widgets/calendar.py's render().
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
|
||||
class TaskWidgetConfig(Base):
|
||||
"""One tasks widget's settings + cached-fetch state -- split out of
|
||||
CalendarWidgetConfig (which used to carry these as tasks_* columns,
|
||||
a week-view-only task list bolted onto a calendar widget) so a task
|
||||
list can be placed and sized on its own, independent of any
|
||||
calendar's view/footprint. No separate "enabled" flag -- unlike the
|
||||
old bolted-on version, the widget's mere presence on the grid is the
|
||||
on/off switch, same as every other widget type.
|
||||
|
||||
Which task lists feed this widget lives in FrameTaskList, not here
|
||||
-- a widget can merge more than one person's list, mirroring
|
||||
CalendarWidgetConfig/FrameCalendar exactly (this used to be a single
|
||||
user_id/calendar_key pair here, one list only; migration 18 carried
|
||||
each widget's existing single source forward as its first
|
||||
FrameTaskList row when splitting this out)."""
|
||||
|
||||
__tablename__ = "task_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
# Shown on-panel in place of the default "Tasks" header (see
|
||||
# calendar_render._draw_tasks) -- "" keeps the default. The only
|
||||
# widget type with its own on-panel title at all, since it's the
|
||||
# only one where "which list is this" isn't already obvious from
|
||||
# its content the way a calendar/photo/whiteboard's is.
|
||||
name: Mapped[str] = mapped_column(String, default="")
|
||||
checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
# [{"summary", "due", "completed_at" (ISO date/datetime strings or
|
||||
# None), "owner_display_name", "color_index"}, ...] -- the merged
|
||||
# multi-list result, same general shape as CalendarWidgetConfig.
|
||||
# cached_events. See caldav_client.merge_tasks.
|
||||
cached: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
# Also include tasks completed in the last 24h (drawn checked-box +
|
||||
# muted, see calendar_render._draw_tasks) rather than just
|
||||
# outstanding ones -- off by default, same "opt into more" posture
|
||||
# as calendar_weather_enabled.
|
||||
show_completed: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# classic (hand-drawn PIL, calendar_render._build_tasks) vs modern
|
||||
# (app/html_render.py) -- see widgets/tasks.py's render().
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
|
||||
class WhiteboardWidgetConfig(Base):
|
||||
"""One whiteboard widget's source + rendered-PNG cache -- the same
|
||||
fields that used to live as whiteboard_* columns directly on Frame."""
|
||||
|
||||
__tablename__ = "whiteboard_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
url: Mapped[str] = mapped_column(String, default="")
|
||||
checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
cached_image: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True)
|
||||
# classic (no chrome, unchanged) vs modern (app/html_render.py's
|
||||
# rounded-corner shadowed card) -- see widgets/whiteboard.py's
|
||||
# render().
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
|
||||
class WeatherWidgetConfig(Base):
|
||||
"""One weather widget's settings + cached-fetch state. Four display
|
||||
modes (see app/widgets/weather.py): "current" (one city, current
|
||||
temp + icon), "hourly" (one city, a row of ticks across the day),
|
||||
"daily" (one city, a multi-day strip), "multi_city" (several cities'
|
||||
current-day high/low/icon side by side -- the calendar widget's
|
||||
embedded weather strip, lifted out into its own widget type).
|
||||
`provider` selects which of app/weather/'s PROVIDERS actually fetches
|
||||
("open_meteo" | "nws" -- see that package's own module docstring).
|
||||
`cached`'s shape depends on `mode`: {"temp","category"} for current,
|
||||
a list of {"time","temp","category"} for hourly, a
|
||||
{"YYYY-MM-DD": {...}} dict for daily, or a list of
|
||||
{"label","high","low","category"} for multi_city.
|
||||
`render_style` picks which renderer draws the widget: "classic" (the
|
||||
hand-drawn PIL primitives in app/weather_render.py, unchanged
|
||||
default) or "modern" (app/html_render.py's Jinja2/headless-Chromium
|
||||
path, "current"/"daily" modes only for now -- see weather.py's
|
||||
render())."""
|
||||
|
||||
__tablename__ = "weather_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
mode: Mapped[str] = mapped_column(String, default="current") # current | hourly | daily | multi_city
|
||||
provider: Mapped[str] = mapped_column(String, default="open_meteo") # open_meteo | nws
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic") # classic | modern
|
||||
units: Mapped[str] = mapped_column(String, default="fahrenheit") # fahrenheit | celsius
|
||||
# Single-location modes only (current/hourly/daily) -- geocoded once
|
||||
# via weather.geocode_city() when set, same idiom as
|
||||
# CalendarWidgetConfig.weather_cities' per-entry shape.
|
||||
city_label: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
city_latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
city_longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
hourly_interval_hours: Mapped[int] = mapped_column(Integer, default=4)
|
||||
daily_days: Mapped[int] = mapped_column(Integer, default=5)
|
||||
# multi_city mode only -- [{"label", "latitude", "longitude"}, ...],
|
||||
# same shape as CalendarWidgetConfig.weather_cities.
|
||||
cities: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
checked_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
cached: Mapped[dict | list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
|
||||
|
||||
class TextWidgetConfig(Base):
|
||||
"""One text widget's authored content + display settings -- another
|
||||
no-live-upstream type like StaticWidgetConfig, just parsed rich text
|
||||
instead of an uploaded image. content is never raw HTML: the
|
||||
dialog's contenteditable innerHTML is parsed server-side (see
|
||||
app/text_content.py, the sanitization boundary) into this plain
|
||||
run structure at save time, so render() (app/widgets/text.py) never
|
||||
re-parses/sanitizes HTML on every panel refresh, and the dialog never
|
||||
re-injects stored HTML via innerHTML when reopened.
|
||||
|
||||
[[{"text","bold","italic","underline","color","bg"}, ...], ...] --
|
||||
outer list is paragraphs (line breaks), inner list is styled runs
|
||||
within that paragraph. color/bg are "#rrggbb" or null (falls back to
|
||||
black text / no highlight). NULL (not just []) means never
|
||||
configured, matching StaticWidgetConfig.image's None-vs-empty
|
||||
convention for "not configured yet"."""
|
||||
|
||||
__tablename__ = "text_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
content: Mapped[list | None] = mapped_column(JSON, nullable=True, default=None)
|
||||
# Base point size for the whole block -- render() shrinks this down
|
||||
# (never up) to fit the widget's actual box; per-run font size isn't
|
||||
# supported, only the bold/italic/underline/color/bg style flags are
|
||||
# per-run (see app/text_content.py) -- keeps the wrap/shrink-to-fit
|
||||
# layout in app/widgets/text.py to one size per render pass.
|
||||
font_size: Mapped[int] = mapped_column(Integer, default=28)
|
||||
# A key into app/widgets/text.py's FONT_FAMILIES, also whole-widget
|
||||
# not per-run (see font_size above for why).
|
||||
font_family: Mapped[str] = mapped_column(String, default="sans")
|
||||
align: Mapped[str] = mapped_column(String, default="left") # "left" | "center" | "right"
|
||||
background_color: Mapped[str] = mapped_column(String, default="#ffffff")
|
||||
# classic (hand-drawn PIL) vs modern (app/html_render.py) -- see
|
||||
# widgets/text.py's render()/render_preview_png().
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
|
||||
class StaticWidgetConfig(Base):
|
||||
"""One static-image widget's uploaded content + display settings --
|
||||
unlike every other widget type, this one has no live upstream to
|
||||
poll (Immich/CalDAV/WebDAV): the "source" is whatever the user last
|
||||
uploaded (see routers/api_widgets.py's api_widget_static_upload,
|
||||
app/image_upload.py), decoded once at upload time into plain RGB PNG
|
||||
bytes so app/widgets/static_image.py's render() never re-runs
|
||||
PDF/GIF decoding on every panel refresh."""
|
||||
|
||||
__tablename__ = "static_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
image: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True)
|
||||
original_filename: Mapped[str] = mapped_column(String, default="")
|
||||
uploaded_at: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
# Same DISPLAY_MODES vocabulary as PhotoWidgetConfig.display_mode,
|
||||
# minus crop_faces -- no face detection for an uploaded image (see
|
||||
# image_pipeline.STATIC_DISPLAY_MODES).
|
||||
display_mode: Mapped[str] = mapped_column(String, default="crop_fill")
|
||||
# classic (no chrome, unchanged) vs modern (app/html_render.py's
|
||||
# rounded-corner shadowed card) -- see widgets/static_image.py's
|
||||
# render().
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic")
|
||||
|
||||
|
||||
class BatteryWidgetConfig(Base):
|
||||
"""One battery widget's display settings -- another no-live-upstream
|
||||
type like StaticWidgetConfig/TextWidgetConfig, just showing existing
|
||||
frame-level state (Frame.battery_percent/battery_as_of, already set
|
||||
by routers/device.py's frame_battery on every device report) instead
|
||||
of anything the widget itself fetches or the user authors. `mode`
|
||||
"compact" is icon + percent only; "detailed" (default) adds the
|
||||
routers.common.battery_estimate_s time-remaining estimate and the
|
||||
last report's age. `render_style` picks classic (hand-drawn PIL) vs
|
||||
modern (app/html_render.py) -- see widgets/battery.py's render()."""
|
||||
|
||||
__tablename__ = "battery_widget_configs"
|
||||
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"), primary_key=True)
|
||||
mode: Mapped[str] = mapped_column(String, default="detailed") # compact | detailed
|
||||
render_style: Mapped[str] = mapped_column(String, default="classic") # classic | modern
|
||||
|
||||
|
||||
# widget_type -> its per-type extension table, keyed by widget_id. Used
|
||||
# by db.widget_locked() to resolve the right config row without importing
|
||||
# app/widgets/'s heavier render/action registry just for this lookup.
|
||||
WIDGET_CONFIG_MODELS: dict[str, type] = {
|
||||
"photos": PhotoWidgetConfig,
|
||||
"calendar": CalendarWidgetConfig,
|
||||
"whiteboard": WhiteboardWidgetConfig,
|
||||
"tasks": TaskWidgetConfig,
|
||||
"static": StaticWidgetConfig,
|
||||
"battery": BatteryWidgetConfig,
|
||||
"text": TextWidgetConfig,
|
||||
"weather": WeatherWidgetConfig,
|
||||
}
|
||||
|
||||
|
||||
class FrameButtonAction(Base):
|
||||
"""One (widget, action) binding for one of a frame's two physical
|
||||
buttons -- e.g. {button: "next", widget_id: <photo widget>, action:
|
||||
"advance"}. At most one binding per (widget, button) -- edited from
|
||||
that widget's own config dialog (routers/api_widgets.py's
|
||||
api_widget_config_save), prefilled with a sane default at widget
|
||||
creation (app/widgets/default_button_actions). On a press, every
|
||||
widget's row for that (frame, button) runs -- see routers/device.py's
|
||||
frame_advance/frame_back. sort_order is unused (which widget's action
|
||||
runs first never matters: each only touches its own state, and one
|
||||
shared re-render happens after all of them finish) but kept around so
|
||||
dispatch has a stable, deterministic query order."""
|
||||
|
||||
__tablename__ = "frame_button_actions"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
frame_id: Mapped[int] = mapped_column(ForeignKey("frames.id", ondelete="CASCADE"))
|
||||
button: Mapped[str] = mapped_column(String) # "next" | "back"
|
||||
widget_id: Mapped[int] = mapped_column(ForeignKey("widgets.id", ondelete="CASCADE"))
|
||||
action: Mapped[str] = mapped_column(String) # e.g. "advance", "back", "check_now" -- see app/widgets/
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_frame_button_actions_frame_button", "frame_id", "button", "sort_order"),
|
||||
Index("ix_frame_button_actions_widget_button", "widget_id", "button", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class SavedLayout(Base):
|
||||
"""A named snapshot of one frame's widget arrangement (types,
|
||||
placement, per-widget settings, button assignments) -- owned by a
|
||||
*user*, not a frame, so it can be applied to any frame that user
|
||||
controls whose grid matches (see docs/widgets.md's "Saved layouts").
|
||||
cols/rows is the grid.grid_dims(orientation) the snapshot was taken
|
||||
at -- an 8x5 (landscape-class) layout isn't meaningful on a 5x8
|
||||
(portrait-class) frame, same reasoning as grid.py's own orientation-
|
||||
change note.
|
||||
|
||||
Saving again with a name that already exists for this user
|
||||
overwrites that layout's snapshot in place (see routers/
|
||||
api_layouts.py's api_layout_save) rather than erroring or quietly
|
||||
creating a second layout with the same name -- the "named save slot"
|
||||
behavior people expect."""
|
||||
|
||||
__tablename__ = "saved_layouts"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
name: Mapped[str] = mapped_column(String)
|
||||
cols: Mapped[int] = mapped_column(Integer)
|
||||
rows: Mapped[int] = mapped_column(Integer)
|
||||
created_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
updated_at: Mapped[float] = mapped_column(Float, default=time.time)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_saved_layouts_user_name", "user_id", "name", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class SavedLayoutWidget(Base):
|
||||
"""One captured widget's type/placement/settings within a
|
||||
SavedLayout -- the snapshot analogue of Widget plus its per-type
|
||||
config row, minus anything that's runtime/cache state rather than an
|
||||
authored setting (a photo widget's current queue position, a
|
||||
calendar's fetch cache, a whiteboard's rendered-image cache, etc.)
|
||||
-- see api_layouts.LAYOUT_CONFIG_FIELDS for the exact per-type field
|
||||
allowlist. `config` holds every JSON-safe captured setting; `image`
|
||||
is only ever populated for a static-image widget's uploaded bytes
|
||||
(its own BLOB column rather than folding base64 into the JSON, same
|
||||
reasoning as StaticWidgetConfig.image itself)."""
|
||||
|
||||
__tablename__ = "saved_layout_widgets"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
saved_layout_id: Mapped[int] = mapped_column(ForeignKey("saved_layouts.id", ondelete="CASCADE"))
|
||||
widget_type: Mapped[str] = mapped_column(String)
|
||||
x: Mapped[int] = mapped_column(Integer)
|
||||
y: Mapped[int] = mapped_column(Integer)
|
||||
w: Mapped[int] = mapped_column(Integer)
|
||||
h: Mapped[int] = mapped_column(Integer)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
config: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
image: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True)
|
||||
|
||||
__table_args__ = (Index("ix_saved_layout_widgets_layout", "saved_layout_id"),)
|
||||
|
||||
|
||||
class SavedLayoutSource(Base):
|
||||
"""One included calendar/task-list source captured on a calendar or
|
||||
tasks SavedLayoutWidget -- the snapshot analogue of FrameCalendar/
|
||||
FrameTaskList. `kind` ("calendar" | "task") distinguishes which,
|
||||
since both shapes are otherwise identical and sharing one table
|
||||
avoids a near-duplicate SavedLayoutTaskSource table."""
|
||||
|
||||
__tablename__ = "saved_layout_sources"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
saved_layout_widget_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("saved_layout_widgets.id", ondelete="CASCADE")
|
||||
)
|
||||
kind: Mapped[str] = mapped_column(String)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
calendar_key: Mapped[str] = mapped_column(String)
|
||||
calendar_label: Mapped[str] = mapped_column(String, default="")
|
||||
included: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
color_index: Mapped[int | None] = mapped_column(Integer, nullable=True, default=None)
|
||||
|
||||
__table_args__ = (Index("ix_saved_layout_sources_widget", "saved_layout_widget_id"),)
|
||||
|
||||
|
||||
class SavedLayoutButtonAction(Base):
|
||||
"""One (button, action) binding captured for one SavedLayoutWidget --
|
||||
the snapshot analogue of FrameButtonAction. References the captured
|
||||
widget directly rather than a frame_id/widget_id pair (neither
|
||||
exists until the layout is applied) so applying can remap it onto
|
||||
whichever new Widget row that captured widget becomes -- see
|
||||
routers/api_layouts.py's api_layout_apply."""
|
||||
|
||||
__tablename__ = "saved_layout_button_actions"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
saved_layout_widget_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("saved_layout_widgets.id", ondelete="CASCADE")
|
||||
)
|
||||
button: Mapped[str] = mapped_column(String)
|
||||
action: Mapped[str] = mapped_column(String)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
__table_args__ = (Index("ix_saved_layout_button_actions_widget", "saved_layout_widget_id"),)
|
||||
|
||||
|
||||
class PendingClaim(Base):
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Shared visual language for everything drawn onto the e-ink panel
|
||||
(excluding widgets/text.py, which already has its own richer multi-
|
||||
family font picker and is left alone) -- spacing, ink-color resolution,
|
||||
Inter font loading, and the small set of drawing primitives
|
||||
(header bar, color chip, battery icon) more than one render module needs.
|
||||
|
||||
Centralizes what used to be independently redefined per render file
|
||||
(calendar_render.py/weather_render.py each had their own MARGIN/BG/FG/
|
||||
RULE, widgets/battery.py and manage_overlay.py each had their own
|
||||
battery-glyph-drawing code) so the panel reads as one consistent system
|
||||
instead of N separately-styled widgets. Still bound by the same hard
|
||||
constraints as everything else that draws before the single whole-canvas
|
||||
quantize/dither pass (see image_pipeline.py's module docstring/draw_text):
|
||||
every fill here is one of DEFAULT_PALETTE_RGB's 6 exact colors, and text
|
||||
always routes through image_pipeline.draw_text.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from .image_pipeline import DEFAULT_PALETTE_RGB
|
||||
|
||||
# Spacing scale. CONTENT_MARGIN carries over calendar_render.py/
|
||||
# weather_render.py's own long-tuned MARGIN=20 value unchanged (not
|
||||
# re-tuned -- every wrap/truncation-width calc in those modules was
|
||||
# measured against it). GUTTER is new: the inset every widget applies
|
||||
# within its own target_w x target_h box (see card_canvas) to get a
|
||||
# visible seam between adjacent widgets without touching grid.py's
|
||||
# zero-gap cell math.
|
||||
GUTTER = 6
|
||||
CONTENT_MARGIN = 20
|
||||
CARD_RADIUS = 12
|
||||
CHIP_RADIUS = 4
|
||||
|
||||
# models.Widget.font_scale's allowed values -- a per-widget text-size
|
||||
# multiplier (the Layout dialog's "Text size" picker), same "reject
|
||||
# invalid, don't silently coerce" posture as border_style. Deliberately a
|
||||
# small fixed set (a <select>, not a raw slider) rather than an arbitrary
|
||||
# float: every _AGENDA_FONTS/_TASKS_FONTS-style tuple in calendar_render.py
|
||||
# and every proportional size in html_render.py/calendar_html_render.py
|
||||
# derives row heights/max_rows from the same scaled font size, so an
|
||||
# unbounded scale risks a layout that no longer fits its own box.
|
||||
FONT_SCALE_CHOICES = (1.0, 1.25, 1.5)
|
||||
|
||||
|
||||
def scaled_size(value: float, font_scale: float) -> int:
|
||||
"""Applies a widget's font_scale to a text-size value and rounds to
|
||||
an int px, floored at 1 so an extreme scale can never zero out a
|
||||
font. Shared by both the classic (PIL, calendar_render.py) and modern
|
||||
(HTML/CSS, html_render.py/calendar_html_render.py) renderers so "make
|
||||
this widget's text bigger" behaves identically regardless of
|
||||
render_style -- every caller applies this immediately after its own
|
||||
tier lookup/floor calc, so row heights/max_rows computed from the
|
||||
result already account for the bigger text."""
|
||||
return max(1, round(value * font_scale))
|
||||
|
||||
# Index constants into DEFAULT_PALETTE_RGB/a frame's own Frame.
|
||||
# palette_rgb override -- same order as image_pipeline.PALETTE_LABELS.
|
||||
BLACK, WHITE, YELLOW, RED, BLUE, GREEN = range(6)
|
||||
|
||||
# Which accent ink each widget kind's chrome (header bar, task checkbox,
|
||||
# etc.) uses -- one dict, so "what color is a calendar header" has a
|
||||
# single answer instead of being hardcoded separately everywhere a
|
||||
# render module wants it. This is what makes a future global color
|
||||
# theme *possible* without another pass through every render module: a
|
||||
# per-frame override just needs to pick a different THEME mapping (or
|
||||
# remap individual entries) here and resolve through theme_color/ink
|
||||
# below, which already goes through a frame's own tuned Frame.
|
||||
# palette_rgb -- swapping a slot's actual RGB (e.g. a custom "blue")
|
||||
# already re-themes every widget that uses THEME_CALENDAR for its
|
||||
# header, with no other code to touch. Weather deliberately maps to
|
||||
# BLACK, not a color -- see weather_render's header call site -- so its
|
||||
# own hand-drawn, already-colorful icons stay the star.
|
||||
THEME_CALENDAR = BLUE
|
||||
THEME_TASKS = GREEN
|
||||
THEME_WEATHER = BLACK
|
||||
THEME = {"calendar": THEME_CALENDAR, "tasks": THEME_TASKS, "weather": THEME_WEATHER}
|
||||
|
||||
|
||||
def theme_color(widget_kind: str, palette_rgb: list | None = None) -> tuple[int, int, int]:
|
||||
"""THEME[widget_kind] resolved against this frame's actual palette --
|
||||
the one call every render module's header/accent chrome should go
|
||||
through instead of hardcoding a palette index inline."""
|
||||
return ink(palette_rgb, THEME[widget_kind])
|
||||
|
||||
|
||||
def ink(palette_rgb: list | None, index: int) -> tuple[int, int, int]:
|
||||
"""One of this frame's actual panel colors by DEFAULT_PALETTE_RGB
|
||||
index -- generalizes the same resolution idiom weather_render._ink/
|
||||
calendar_render._event_colors already used locally, so a custom
|
||||
palette override (Frame.palette_rgb) still gets its own actual
|
||||
yellow/red/blue/green, and every fill stays an exact, ditherless
|
||||
palette match either way."""
|
||||
return tuple((palette_rgb or DEFAULT_PALETTE_RGB)[index])
|
||||
|
||||
|
||||
_FONT_DIR = Path(__file__).resolve().parent / "fonts"
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def font_bold(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(_FONT_DIR / "Inter-Bold.ttf"), size)
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def font_regular(size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(_FONT_DIR / "Inter-Regular.ttf"), size)
|
||||
|
||||
|
||||
def card_canvas(target_w: int, target_h: int,
|
||||
bg: tuple[int, int, int] = (255, 255, 255)) -> tuple:
|
||||
"""A full target_w x target_h canvas filled with `bg`, plus the
|
||||
GUTTER-inset rect (x0, y0, w, h) every widget should draw its actual
|
||||
chrome/content within -- this is the whole mechanism behind the
|
||||
gutter between widgets (see module docstring): the widget's render()
|
||||
contract (exact target_w x target_h in, same size out, unchanged) is
|
||||
what routers/device.py pastes and what draw_widget_border frames, so
|
||||
a border still frames the widget's true full box; only the widget's
|
||||
own drawing backs off from that box's true edge."""
|
||||
img = Image.new("RGB", (target_w, target_h), bg)
|
||||
draw = ImageDraw.Draw(img)
|
||||
x0, y0 = GUTTER, GUTTER
|
||||
w, h = max(1, target_w - 2 * GUTTER), max(1, target_h - 2 * GUTTER)
|
||||
return img, draw, (x0, y0, w, h)
|
||||
|
||||
|
||||
def _clamped_radius(radius: int, w: int, h: int) -> int:
|
||||
return max(0, min(radius, w // 2, h // 2))
|
||||
|
||||
|
||||
def draw_header_bar(draw: ImageDraw.ImageDraw, rect: tuple[int, int, int, int], height: int,
|
||||
fill: tuple[int, int, int], radius: int = CARD_RADIUS) -> None:
|
||||
"""A widget's title bar: rounded top corners only (corners=(tl, tr,
|
||||
bl, br), the bottom pair left square) so it reads as a card's header
|
||||
fused to the content below it, not a standalone pill floating with a
|
||||
gap above its own body."""
|
||||
x0, y0, w, h = rect
|
||||
r = _clamped_radius(radius, w, height * 2)
|
||||
draw.rounded_rectangle([x0, y0, x0 + w, y0 + height], radius=r, fill=fill,
|
||||
corners=(True, True, False, False))
|
||||
|
||||
|
||||
def draw_color_chip(draw: ImageDraw.ImageDraw, x0: int, y0: int, x1: int, y1: int,
|
||||
colors: list[tuple[int, int, int]], radius: int = CHIP_RADIUS) -> None:
|
||||
"""One rounded chip for a single-source event/task, or that same
|
||||
footprint split into equal-width side-by-side segments -- one per
|
||||
contributing calendar -- for a deduplicated shared event (see
|
||||
calendar_render._event_colors/calendar_feed.merge_events). Splitting
|
||||
rather than e.g. concentric rings keeps every color equally "thick
|
||||
and bold" at a glance, the same design goal a single pinned color
|
||||
already has. Generalizes calendar_render.py's old private
|
||||
_draw_color_bar so the radius comes from one shared constant."""
|
||||
if len(colors) == 1:
|
||||
r = _clamped_radius(radius, x1 - x0, y1 - y0)
|
||||
draw.rounded_rectangle([x0, y0, x1, y1], radius=r, fill=colors[0])
|
||||
return
|
||||
seg_w = (x1 - x0) / len(colors)
|
||||
for i, color in enumerate(colors):
|
||||
seg_x0 = round(x0 + i * seg_w)
|
||||
seg_x1 = round(x0 + (i + 1) * seg_w) - (2 if i < len(colors) - 1 else 0)
|
||||
draw.rectangle([seg_x0, y0, seg_x1, y1], fill=color)
|
||||
|
||||
|
||||
def battery_fill_color(percent: int, palette_rgb: list | None = None) -> tuple[int, int, int]:
|
||||
"""Red/yellow/green by charge level -- the fill itself carries the
|
||||
"how worried should I be" signal, not just the number next to it.
|
||||
Shared threshold logic for widgets/battery.py and manage_overlay.py,
|
||||
which previously each defined the same three-tier thresholds twice."""
|
||||
if percent <= 15:
|
||||
return ink(palette_rgb, RED)
|
||||
if percent <= 40:
|
||||
return ink(palette_rgb, YELLOW)
|
||||
return ink(palette_rgb, GREEN)
|
||||
|
||||
|
||||
def draw_battery_icon(draw: ImageDraw.ImageDraw, x0: int, y0: int, icon_w: int, icon_h: int,
|
||||
percent: int, palette_rgb: list | None = None) -> None:
|
||||
"""A rounded battery glyph -- outline + charge-level fill + terminal
|
||||
nub -- anchored at (x0, y0), the body's own top-left corner (the nub
|
||||
extends past icon_w on the right). The one shared implementation
|
||||
behind what used to be two separate ImageDraw glyphs: widgets/
|
||||
battery.py's own icon+percent widget, and manage_overlay.py's compact
|
||||
battery readout on the "scan to manage" overlay -- same shape, same
|
||||
red/yellow/green thresholds, previously kept in sync by convention
|
||||
rather than by sharing code."""
|
||||
stroke = max(2, icon_h // 12)
|
||||
nub_w = max(3, icon_w // 10)
|
||||
nub_h = icon_h // 2
|
||||
radius = _clamped_radius(icon_h // 6, icon_w, icon_h)
|
||||
|
||||
inner_x0, inner_y0 = x0 + stroke, y0 + stroke
|
||||
inner_x1, inner_y1 = x0 + icon_w - stroke, y0 + icon_h - stroke
|
||||
fill_x1 = inner_x0 + round((inner_x1 - inner_x0) * (max(0, min(100, percent)) / 100))
|
||||
if fill_x1 > inner_x0:
|
||||
fill_radius = _clamped_radius(radius, fill_x1 - inner_x0, inner_y1 - inner_y0)
|
||||
draw.rounded_rectangle([inner_x0, inner_y0, fill_x1, inner_y1], radius=fill_radius,
|
||||
fill=battery_fill_color(percent, palette_rgb))
|
||||
draw.rounded_rectangle([x0, y0, x0 + icon_w, y0 + icon_h], radius=radius, outline=(0, 0, 0), width=stroke)
|
||||
nub_y = y0 + (icon_h - nub_h) // 2
|
||||
nub_radius = _clamped_radius(max(1, nub_w // 3), nub_w, nub_h)
|
||||
draw.rounded_rectangle([x0 + icon_w, nub_y, x0 + icon_w + nub_w, nub_y + nub_h], radius=nub_radius,
|
||||
fill=(0, 0, 0))
|
||||
+36
-15
@@ -85,11 +85,21 @@ def _top_up(cfg: Frame, assets: list[dict]) -> None:
|
||||
cfg.queue_cursor = (cfg.queue_cursor + i + 1) % n
|
||||
|
||||
|
||||
def advance_forced(cfg: Frame, assets: list[dict]) -> None:
|
||||
def advance_forced(cfg: Frame, assets: list[dict], frame: Frame) -> None:
|
||||
"""Unconditionally moves to the next photo, ignoring elapsed time, and
|
||||
resets the interval clock from now. Used by the explicit next-photo
|
||||
action (POST /frame/advance) and by get_current() once the refresh
|
||||
interval has elapsed -- always mutates cfg."""
|
||||
interval has elapsed -- always mutates cfg.
|
||||
|
||||
`frame` is a separate reference to the owning Frame, for fields that
|
||||
stay frame-level rather than moving onto a photo widget's own config
|
||||
(currently just stats_photos_displayed) -- once a photo widget's
|
||||
queue state lives on its own PhotoWidgetConfig row rather than
|
||||
directly on Frame (see models.py), `cfg` and `frame` stop being the
|
||||
same object; every existing caller today still passes the same Frame
|
||||
for both, which is also why this stays a required (not optional)
|
||||
param -- no implicit "guess which Frame owns this" fallback to get
|
||||
wrong later."""
|
||||
if cfg.current_asset_id:
|
||||
# Recorded regardless of *why* this advance happened (a manual
|
||||
# next-press or the timer just elapsing) -- back should be able
|
||||
@@ -105,7 +115,7 @@ def advance_forced(cfg: Frame, assets: list[dict]) -> None:
|
||||
# only asset is already current) -- keep showing what we have.
|
||||
cfg.current_asset_id = assets[0]["id"]
|
||||
cfg.current_asset_set_at = time.time()
|
||||
cfg.stats_photos_displayed += 1
|
||||
frame.stats_photos_displayed += 1
|
||||
# Refill back up to queue_target_len now that current_asset_id has
|
||||
# changed -- otherwise the queue is left one short until the *next*
|
||||
# advance, since the pop above consumes one of the items _top_up just
|
||||
@@ -113,7 +123,7 @@ def advance_forced(cfg: Frame, assets: list[dict]) -> None:
|
||||
_top_up(cfg, assets)
|
||||
|
||||
|
||||
def back_forced(cfg: Frame, assets: list[dict]) -> bool:
|
||||
def back_forced(cfg: Frame, assets: list[dict], frame: Frame) -> bool:
|
||||
"""Unconditionally moves to the previously-current photo, the mirror
|
||||
image of advance_forced() -- pops the most recent entry off history,
|
||||
pushes the photo it's replacing onto the front of queue (so pressing
|
||||
@@ -122,7 +132,7 @@ def back_forced(cfg: Frame, assets: list[dict]) -> bool:
|
||||
since). Returns whether it actually moved -- False (history empty or
|
||||
entirely stale) is a no-op, callers should still just display
|
||||
whatever's current rather than treating it as an error. Used by the
|
||||
back-photo button (POST /frame/back)."""
|
||||
back-photo button (POST /frame/back). See advance_forced() on `frame`."""
|
||||
valid_ids = {a["id"] for a in assets}
|
||||
while cfg.history:
|
||||
previous_id = cfg.history.pop()
|
||||
@@ -132,12 +142,12 @@ def back_forced(cfg: Frame, assets: list[dict]) -> bool:
|
||||
cfg.queue.insert(0, cfg.current_asset_id)
|
||||
cfg.current_asset_id = previous_id
|
||||
cfg.current_asset_set_at = time.time()
|
||||
cfg.stats_photos_displayed += 1
|
||||
frame.stats_photos_displayed += 1
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def remove_from_rotation(cfg: Frame, assets: list[dict], asset_id: str) -> bool:
|
||||
def remove_from_rotation(cfg: Frame, assets: list[dict], asset_id: str, frame: Frame) -> bool:
|
||||
"""Permanently excludes asset_id from this frame's rotation (see the
|
||||
module docstring) -- doesn't touch Immich, just this frame's own
|
||||
selection. Scrubs it out of queue and history too, so it can't
|
||||
@@ -146,10 +156,10 @@ def remove_from_rotation(cfg: Frame, assets: list[dict], asset_id: str) -> bool:
|
||||
*not* through advance_forced(), since that would record the removed
|
||||
photo in history, and going back to a photo you just explicitly
|
||||
removed doesn't make sense. Returns whether the current photo
|
||||
changed as a result."""
|
||||
changed as a result. See advance_forced() on `frame`."""
|
||||
if asset_id not in cfg.excluded_asset_ids:
|
||||
cfg.excluded_asset_ids.append(asset_id)
|
||||
cfg.stats_photos_removed += 1
|
||||
frame.stats_photos_removed += 1
|
||||
cfg.queue = [a for a in cfg.queue if a != asset_id]
|
||||
cfg.history = [a for a in cfg.history if a != asset_id]
|
||||
|
||||
@@ -167,7 +177,7 @@ def remove_from_rotation(cfg: Frame, assets: list[dict], asset_id: str) -> bool:
|
||||
remaining = [a["id"] for a in assets if a["id"] not in excluded_ids]
|
||||
cfg.current_asset_id = remaining[0] if remaining else ""
|
||||
cfg.current_asset_set_at = time.time()
|
||||
cfg.stats_photos_displayed += 1
|
||||
frame.stats_photos_displayed += 1
|
||||
_top_up(cfg, assets)
|
||||
return True
|
||||
|
||||
@@ -180,7 +190,7 @@ def sync_queue_length(cfg: Frame, assets: list[dict]) -> None:
|
||||
_top_up(cfg, assets)
|
||||
|
||||
|
||||
def get_current(cfg: Frame, assets: list[dict], in_quiet_hours: bool = False) -> bool:
|
||||
def get_current(cfg: Frame, assets: list[dict], frame: Frame, in_quiet_hours: bool = False) -> bool:
|
||||
"""Time-based, idempotent path used by GET /frame/image. Advances only
|
||||
if the current photo is unset/invalid or refresh_interval_s has
|
||||
elapsed since it was set. Returns whether it changed anything, so the
|
||||
@@ -190,6 +200,10 @@ def get_current(cfg: Frame, assets: list[dict], in_quiet_hours: bool = False) ->
|
||||
ahead, while a wake that lands after the interval has elapsed still
|
||||
advances exactly once, even after a long time offline.
|
||||
|
||||
refresh_interval_s is read off `frame`, not `cfg` -- it's a device
|
||||
wake-cadence setting shared by the whole panel, not something that
|
||||
becomes per-widget (see advance_forced() on the cfg/frame split).
|
||||
|
||||
in_quiet_hours suppresses *only* the elapsed-time trigger -- an
|
||||
unset/invalid current photo still gets picked regardless, since
|
||||
showing nothing is worse than showing something even at 3am. This
|
||||
@@ -197,12 +211,19 @@ def get_current(cfg: Frame, assets: list[dict], in_quiet_hours: bool = False) ->
|
||||
/api/queue), so without this an open browser tab polling overnight
|
||||
would silently advance the current photo on raw elapsed time alone,
|
||||
even though the device itself is correctly asleep through the
|
||||
window (see main.py's _effective_refresh_interval_s)."""
|
||||
window (see main.py's _effective_refresh_interval_s).
|
||||
|
||||
cfg.locked suppresses the elapsed-time trigger the same way
|
||||
in_quiet_hours does -- a locked widget still needs an initial pick
|
||||
if it somehow has none (an unconfigured widget just locked, or a
|
||||
changed album), but once it has a current photo the whole point of
|
||||
locking is that it stops moving on its own until explicitly
|
||||
unlocked."""
|
||||
valid_ids = {a["id"] for a in assets}
|
||||
needs_pick = not cfg.current_asset_id or cfg.current_asset_id not in valid_ids
|
||||
time_elapsed = (time.time() - cfg.current_asset_set_at) >= cfg.refresh_interval_s
|
||||
stale = needs_pick or (time_elapsed and not in_quiet_hours)
|
||||
time_elapsed = (time.time() - cfg.current_asset_set_at) >= frame.refresh_interval_s
|
||||
stale = needs_pick or (time_elapsed and not in_quiet_hours and not cfg.locked)
|
||||
if not stale:
|
||||
return False
|
||||
advance_forced(cfg, assets)
|
||||
advance_forced(cfg, assets, frame)
|
||||
return True
|
||||
|
||||
@@ -114,6 +114,18 @@ def in_quiet_hours(cfg) -> bool:
|
||||
return in_quiet
|
||||
|
||||
|
||||
def quiet_span_s(cfg) -> int:
|
||||
"""Seconds per day quiet hours keeps the device asleep -- 0 when
|
||||
disabled. Used by common.py's battery-remaining estimate to turn a
|
||||
per-wake battery cost into a wall-clock duration: quiet hours cuts
|
||||
how many wakes happen per day without changing what any one wake
|
||||
costs, so it belongs in the wakes-per-day math, not the per-wake
|
||||
rate itself."""
|
||||
if not cfg.quiet_hours_enabled:
|
||||
return 0
|
||||
return _quiet_hours_span_s(cfg.quiet_hours_start, cfg.quiet_hours_end)
|
||||
|
||||
|
||||
def max_expected_gap_s(cfg) -> int:
|
||||
"""Longest gap between wakes the device might legitimately have --
|
||||
normally just refresh_interval_s, but quiet hours can make the real
|
||||
|
||||
+162
-316
@@ -1,16 +1,17 @@
|
||||
"""The web UI's JSON API, namespaced per frame: /api/frames/{id}/...
|
||||
"""The web UI's JSON API for frame-wide settings: /api/frames/{id}/...
|
||||
Per-widget settings (album, calendar view/inclusion, whiteboard source,
|
||||
etc.) live in api_widgets.py instead, under /api/frames/{id}/widgets/
|
||||
{widget_id}/... -- split out once a frame could hold more than one
|
||||
widget of the same type.
|
||||
|
||||
Auth: session-only (require_frame_view for reads, require_frame_control
|
||||
for mutations -- the "take control" soft lock). The limited manage-QR
|
||||
surface lives separately under /api/m/ (routers/manage.py), and device
|
||||
traffic under /frame/* (routers/device.py).
|
||||
|
||||
Config saves are PARTIAL updates: each page's form posts only its own
|
||||
fields (the old single Settings form split across the Photos and
|
||||
Configuration tabs), so every field is optional and only provided ones
|
||||
are touched. Checkboxes are sent explicitly as "true"/"false" strings by
|
||||
the page JS -- an absent field means "not this form's field", never
|
||||
"unchecked".
|
||||
Config saves are PARTIAL updates: only provided fields are touched.
|
||||
Checkboxes are sent explicitly as "true"/"false" strings by the page JS
|
||||
-- an absent field means "not this form's field", never "unchecked".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,35 +22,18 @@ import time
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import calendar_render, gitea_releases, photo_queue, quiet_hours
|
||||
from .. import gitea_releases, grid, quiet_hours, theme_tokens
|
||||
from ..auth import require_frame_control, require_frame_view, require_user_api
|
||||
from ..db import frame_locked, get_db
|
||||
from ..image_pipeline import (
|
||||
DEFAULT_DISPLAY_MODE,
|
||||
DISPLAY_MODES,
|
||||
PALETTE_LABELS,
|
||||
hex_to_rgb,
|
||||
render_preview_png,
|
||||
)
|
||||
from ..global_actions import GLOBAL_ACTIONS
|
||||
from ..image_pipeline import PALETTE_LABELS, hex_to_rgb
|
||||
from ..firmware import firmware_path, parse_app_version
|
||||
from ..models import BatteryLog, Frame, UserFrame
|
||||
from .common import (
|
||||
FRAME_MODES,
|
||||
OVERDUE_FACTOR,
|
||||
battery_estimate_s,
|
||||
calendar_sources_for_frame,
|
||||
fetch_source_and_faces,
|
||||
get_or_refresh_calendar_events,
|
||||
immich_client_for,
|
||||
immich_creds,
|
||||
list_assets,
|
||||
require_configured,
|
||||
valid_http_url,
|
||||
)
|
||||
from ..models import BatteryLog, Frame, Widget
|
||||
from .common import OVERDUE_FACTOR, battery_estimate_s, immich_client_for, immich_creds, valid_http_url
|
||||
from .device import render_frame_preview_png
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -57,11 +41,40 @@ router = APIRouter()
|
||||
|
||||
MIN_REFRESH_INTERVAL_S = 60
|
||||
MAX_REFRESH_INTERVAL_S = 86400
|
||||
MIN_QUEUE_TARGET_LEN = 5
|
||||
MAX_QUEUE_TARGET_LEN = 5000
|
||||
|
||||
ORIENTATIONS = ("landscape", "portrait", "landscape_flipped", "portrait_flipped")
|
||||
|
||||
# See app/global_actions.py -- how long NEXT/BACK must be held before the
|
||||
# device treats it as a hold instead of a short press.
|
||||
MIN_HOLD_DURATION_MS = 3000
|
||||
MAX_HOLD_DURATION_MS = 10000
|
||||
|
||||
|
||||
def _reset_widget_layout_for_new_orientation(db: Session, frame_id: int, new_orientation: str) -> None:
|
||||
"""A widget's x/y/w/h are grid cells relative to the OLD orientation's
|
||||
cols x rows (see grid.grid_dims) -- landscape and portrait use a
|
||||
transposed grid (8x5 vs 5x8), so an existing placement is often
|
||||
literally out of bounds on the new grid, not just visually wrong.
|
||||
There's no sensible coordinate remap between two differently-shaped
|
||||
grids, so instead: keep whichever widget was first by placement
|
||||
order, resized to fill the new full panel, and delete the rest --
|
||||
cascading to their own config rows and any FrameButtonAction
|
||||
bindings via ondelete="CASCADE" (see models.py). The frontend is
|
||||
expected to confirm this with the user before submitting an
|
||||
orientation change (see frame_config.js) -- this always executes
|
||||
unconditionally once called, same posture as every other
|
||||
confirm-on-the-client / act-unconditionally-on-the-server action in
|
||||
this codebase."""
|
||||
widgets = db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame_id).order_by(Widget.sort_order)
|
||||
).all()
|
||||
if not widgets:
|
||||
return
|
||||
keep, *rest = widgets
|
||||
for widget in rest:
|
||||
db.delete(widget)
|
||||
keep.x, keep.y, keep.w, keep.h = grid.full_panel_rect(new_orientation)
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/albums")
|
||||
def api_albums(frame: Frame = Depends(require_frame_view)):
|
||||
@@ -78,11 +91,7 @@ def api_albums(frame: Frame = Depends(require_frame_view)):
|
||||
@router.post("/api/frames/{frame_id}/config")
|
||||
def api_config_save(
|
||||
name: str | None = Form(None),
|
||||
album_id: str | None = Form(None),
|
||||
order: str | None = Form(None),
|
||||
refresh_interval_s: int | None = Form(None),
|
||||
display_mode: str | None = Form(None),
|
||||
queue_target_len: int | None = Form(None),
|
||||
orientation: str | None = Form(None),
|
||||
quiet_hours_enabled: bool | None = Form(None),
|
||||
quiet_hours_start: str | None = Form(None),
|
||||
@@ -96,37 +105,52 @@ def api_config_save(
|
||||
color_boost: float | None = Form(None),
|
||||
contrast_boost: float | None = Form(None),
|
||||
dither_strength: float | None = Form(None),
|
||||
mode: str | None = Form(None),
|
||||
calendar_view: str | None = Form(None),
|
||||
calendar_photo_inlay: bool | None = Form(None),
|
||||
photo_palette: list[str] | None = Form(None),
|
||||
photo_palette_reset: bool | None = Form(None),
|
||||
photo_dither_strength: float | None = Form(None),
|
||||
theme: str | None = Form(None),
|
||||
hold_duration_ms: int | None = Form(None),
|
||||
next_hold_action: str | None = Form(None),
|
||||
back_hold_action: str | None = Form(None),
|
||||
frame: Frame = Depends(require_frame_control),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Partial update of frame-wide settings only -- per-widget settings
|
||||
(album, calendar view/inclusion, whiteboard source, etc.) live on
|
||||
routers/api_widgets.py's /widgets/{widget_id}/... endpoints instead,
|
||||
since a frame can hold more than one widget of the same type and
|
||||
"the frame's calendar settings" stopped being unambiguous the moment
|
||||
that became possible. `mode` and `calendar_photo_inlay` are no
|
||||
longer accepted here either: mode no longer governs anything (a
|
||||
frame's widgets do), and photo inlay has no widget-system equivalent
|
||||
(place an independent photo widget alongside instead). All three are
|
||||
harmless no-ops if an old cached page still POSTs them -- FastAPI
|
||||
silently ignores form fields with no matching parameter.
|
||||
|
||||
An actual orientation *change* resets the frame's widget layout (see
|
||||
_reset_widget_layout_for_new_orientation) -- widget placement is
|
||||
grid-cell-relative to the panel's long/short axis, which swaps on a
|
||||
landscape<->portrait change, so an old placement is usually not just
|
||||
visually wrong but literally out of bounds on the new grid.
|
||||
|
||||
hold_duration_ms/next_hold_action/back_hold_action configure hold-
|
||||
for-global-action (see app/global_actions.py) -- a frame-wide
|
||||
setting, not per-widget, hence living here rather than on
|
||||
api_widgets.py's per-widget button-actions endpoint. An unrecognized
|
||||
action value clears the binding rather than erroring, same posture
|
||||
as this endpoint's other enum-ish fields (orientation, timezone)."""
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
if name is not None:
|
||||
cfg.name = name.strip()[:64] or cfg.name
|
||||
if album_id is not None and album_id != cfg.album_id:
|
||||
# A newly selected album starts clean -- the old current photo
|
||||
# and queue don't mean anything in the new album's context.
|
||||
cfg.current_asset_id = ""
|
||||
cfg.current_asset_set_at = 0.0
|
||||
cfg.queue = []
|
||||
cfg.queue_cursor = 0
|
||||
cfg.history = []
|
||||
cfg.excluded_asset_ids = []
|
||||
cfg.album_id = album_id
|
||||
if order is not None:
|
||||
cfg.order = order if order in ("sequential", "shuffle") else "sequential"
|
||||
if refresh_interval_s is not None:
|
||||
cfg.refresh_interval_s = max(
|
||||
MIN_REFRESH_INTERVAL_S, min(MAX_REFRESH_INTERVAL_S, refresh_interval_s)
|
||||
)
|
||||
if display_mode is not None:
|
||||
cfg.display_mode = display_mode if display_mode in DISPLAY_MODES else DEFAULT_DISPLAY_MODE
|
||||
if queue_target_len is not None:
|
||||
cfg.queue_target_len = max(MIN_QUEUE_TARGET_LEN, min(MAX_QUEUE_TARGET_LEN, queue_target_len))
|
||||
if orientation is not None:
|
||||
cfg.orientation = orientation if orientation in ORIENTATIONS else "landscape"
|
||||
new_orientation = orientation if orientation in ORIENTATIONS else "landscape"
|
||||
if new_orientation != cfg.orientation:
|
||||
_reset_widget_layout_for_new_orientation(db, cfg.id, new_orientation)
|
||||
cfg.orientation = new_orientation
|
||||
if quiet_hours_enabled is not None:
|
||||
cfg.quiet_hours_enabled = quiet_hours_enabled
|
||||
if quiet_hours_start is not None and quiet_hours.valid_hhmm(quiet_hours_start):
|
||||
@@ -162,19 +186,27 @@ def api_config_save(
|
||||
cfg.contrast_boost = max(0.0, min(2.0, contrast_boost))
|
||||
if dither_strength is not None:
|
||||
cfg.dither_strength = max(0.0, min(1.0, dither_strength))
|
||||
if mode is not None:
|
||||
cfg.mode = mode if mode in FRAME_MODES else "photos"
|
||||
if calendar_view is not None:
|
||||
new_view = calendar_view if calendar_view in calendar_render.CALENDAR_VIEWS else "agenda"
|
||||
if new_view != cfg.calendar_view:
|
||||
# A stale offset means something different in a different
|
||||
# view's units (days vs. weeks vs. months) -- same
|
||||
# reasoning as album_id's reset above.
|
||||
cfg.calendar_browse_offset = 0
|
||||
cfg.calendar_view = new_view
|
||||
if calendar_photo_inlay is not None:
|
||||
cfg.calendar_photo_inlay = calendar_photo_inlay
|
||||
if photo_palette_reset:
|
||||
cfg.photo_palette_rgb = None
|
||||
elif photo_palette is not None:
|
||||
if len(photo_palette) != len(PALETTE_LABELS):
|
||||
raise HTTPException(400, f"Expected {len(PALETTE_LABELS)} palette colors, got {len(photo_palette)}")
|
||||
parsed = [hex_to_rgb(h) for h in photo_palette]
|
||||
if any(rgb is None for rgb in parsed):
|
||||
raise HTTPException(400, "Palette colors must be #rrggbb hex values")
|
||||
cfg.photo_palette_rgb = [list(rgb) for rgb in parsed]
|
||||
if photo_dither_strength is not None:
|
||||
cfg.photo_dither_strength = max(0.0, min(1.0, photo_dither_strength))
|
||||
if theme is not None:
|
||||
cfg.theme = theme if theme in theme_tokens.THEMES else "classic"
|
||||
if hold_duration_ms is not None:
|
||||
cfg.hold_duration_ms = max(MIN_HOLD_DURATION_MS, min(MAX_HOLD_DURATION_MS, hold_duration_ms))
|
||||
if next_hold_action is not None:
|
||||
cfg.next_hold_action = next_hold_action if next_hold_action in GLOBAL_ACTIONS else None
|
||||
if back_hold_action is not None:
|
||||
cfg.back_hold_action = back_hold_action if back_hold_action in GLOBAL_ACTIONS else None
|
||||
cfg.stats_config_saves += 1
|
||||
|
||||
return {"status": "saved"}
|
||||
|
||||
|
||||
@@ -207,65 +239,82 @@ def api_stats(frame: Frame = Depends(require_frame_view)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/queue")
|
||||
def api_queue(
|
||||
@router.get("/api/frames/{frame_id}/status")
|
||||
def api_status(
|
||||
request: Request, frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)
|
||||
):
|
||||
"""Device liveness + control-lock info -- frame-level facts (battery,
|
||||
last-seen, firmware, who has control), not tied to any particular
|
||||
widget. Powers static/device_status_bar.js, shown on every per-frame
|
||||
page regardless of which widgets that frame has. Used to piggyback on
|
||||
the photo queue endpoint (back when a frame had at most one widget,
|
||||
always photos-shaped); split out once that stopped being true, so the
|
||||
status bar isn't blank on a frame with no photo widget."""
|
||||
user = require_user_api(request, db)
|
||||
require_configured(frame)
|
||||
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
photo_queue.get_current(cfg, assets, in_quiet_hours=quiet_hours.in_quiet_hours(cfg))
|
||||
photo_queue.sync_queue_length(cfg, assets)
|
||||
snapshot = {
|
||||
"current_asset_id": cfg.current_asset_id,
|
||||
"queue": list(cfg.queue),
|
||||
"last_seen": cfg.last_seen,
|
||||
"overdue_gap": quiet_hours.max_expected_gap_s(cfg) * OVERDUE_FACTOR,
|
||||
"firmware_version": cfg.device_firmware_version,
|
||||
"firmware_available": cfg.firmware_available_version,
|
||||
"battery_percent": cfg.battery_percent,
|
||||
"battery_as_of": cfg.battery_as_of,
|
||||
"battery_estimate_s": battery_estimate_s(cfg),
|
||||
"controller_id": cfg.controlled_by_user_id,
|
||||
"controller": (
|
||||
(cfg.controlled_by.display_name or cfg.controlled_by.username)
|
||||
if cfg.controlled_by
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
def entry(asset_id: str) -> dict:
|
||||
return {"id": asset_id, "thumbnail_url": f"/api/frames/{frame.id}/thumbnail/{asset_id}"}
|
||||
|
||||
now = time.time()
|
||||
overdue_gap = quiet_hours.max_expected_gap_s(frame) * OVERDUE_FACTOR
|
||||
return {
|
||||
"current": entry(snapshot["current_asset_id"]) if snapshot["current_asset_id"] else None,
|
||||
"upcoming": [entry(asset_id) for asset_id in snapshot["queue"]],
|
||||
"control": {
|
||||
"controller": snapshot["controller"],
|
||||
"you": snapshot["controller_id"] == user.id,
|
||||
"controller": (frame.controlled_by.display_name or frame.controlled_by.username) if frame.controlled_by else None,
|
||||
"you": frame.controlled_by_user_id == user.id,
|
||||
},
|
||||
"device": {
|
||||
"last_seen": snapshot["last_seen"] or None,
|
||||
"overdue": bool(
|
||||
snapshot["last_seen"] and now - snapshot["last_seen"] > snapshot["overdue_gap"]
|
||||
"last_seen": frame.last_seen or None,
|
||||
"overdue": bool(frame.last_seen and now - frame.last_seen > overdue_gap),
|
||||
# When the device is next expected to check in, per the same
|
||||
# sleep duration frame_config() actually hands it (see
|
||||
# device.py's /frame/config) -- not the raw overdue_gap above,
|
||||
# which is deliberately generous (OVERDUE_FACTOR) to avoid
|
||||
# false alarms during quiet hours rather than a best guess.
|
||||
"expected_next_checkin": (
|
||||
frame.last_seen + quiet_hours.effective_refresh_interval_s(frame) if frame.last_seen else None
|
||||
),
|
||||
"firmware_version": snapshot["firmware_version"] or None,
|
||||
"firmware_available": snapshot["firmware_available"] or None,
|
||||
"firmware_version": frame.device_firmware_version or None,
|
||||
"firmware_available": frame.firmware_available_version or None,
|
||||
"battery": (
|
||||
{"percent": snapshot["battery_percent"], "as_of": snapshot["battery_as_of"]}
|
||||
if snapshot["battery_percent"] >= 0
|
||||
else None
|
||||
{"percent": frame.battery_percent, "as_of": frame.battery_as_of}
|
||||
if frame.battery_percent >= 0 else None
|
||||
),
|
||||
"battery_estimate_s": snapshot["battery_estimate_s"],
|
||||
"battery_estimate_s": battery_estimate_s(frame, db),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/preview")
|
||||
def api_frame_preview(
|
||||
request: Request, frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)
|
||||
):
|
||||
"""A small PNG of exactly what the frame is currently displaying --
|
||||
the same widget compositor /frame/image uses (see routers/device.py's
|
||||
render_frame_preview_png), just handed back upright and unpacked for
|
||||
the dashboard header's live thumbnail instead of the device's packed
|
||||
native format. Not cached: cheap enough for an on-demand header image,
|
||||
and each widget's own render is already idempotent between a device's
|
||||
real wakes (see photo_queue.get_current, calendar widget's browse
|
||||
reset), so an extra read here doesn't skip or duplicate anything."""
|
||||
png = render_frame_preview_png(db, frame, request)
|
||||
return Response(content=png, media_type="image/png")
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/now-displaying")
|
||||
def api_frame_now_displaying(frame: Frame = Depends(require_frame_view)):
|
||||
"""Exactly what was last actually sent to this frame's device (see
|
||||
routers/device.py's _record_last_displayed) -- the frozen "now
|
||||
displaying" half of the header preview pair, as opposed to /preview's
|
||||
always-live "up next" re-render. 404 (not a placeholder image) until
|
||||
the device has fetched at least once, so the web UI can show its own
|
||||
empty state instead of a broken image. X-Displayed-At carries the
|
||||
capture time (unix seconds) for a "N ago" label -- a header, not the
|
||||
body, since the body is the raw PNG bytes."""
|
||||
if frame.last_displayed_image is None:
|
||||
raise HTTPException(404, "This frame hasn't displayed anything yet")
|
||||
return Response(
|
||||
content=frame.last_displayed_image,
|
||||
media_type="image/png",
|
||||
headers={"X-Displayed-At": str(frame.last_displayed_at)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/battery-log")
|
||||
def api_battery_log(frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)):
|
||||
rows = db.execute(
|
||||
@@ -276,210 +325,6 @@ def api_battery_log(frame: Frame = Depends(require_frame_view), db: Session = De
|
||||
return {"log": [[ts, percent] for ts, percent in rows]}
|
||||
|
||||
|
||||
class QueueReorderRequest(BaseModel):
|
||||
queue: list[str]
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/queue/reorder")
|
||||
def api_queue_reorder(
|
||||
body: QueueReorderRequest,
|
||||
frame: Frame = Depends(require_frame_control),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Applies the client's requested order, tolerating drift between the
|
||||
browser's last-fetched snapshot and the server's current queue (e.g.
|
||||
a top-up/trim landed in between) instead of hard-rejecting: any ID
|
||||
the client sent that's no longer actually queued is dropped, and any
|
||||
ID the server has that the client didn't know about is appended
|
||||
rather than lost."""
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
current_set = set(cfg.queue)
|
||||
reordered = [asset_id for asset_id in body.queue if asset_id in current_set]
|
||||
reordered += [asset_id for asset_id in cfg.queue if asset_id not in set(reordered)]
|
||||
cfg.queue = reordered
|
||||
return {"status": "saved"}
|
||||
|
||||
|
||||
class QueuePromoteRequest(BaseModel):
|
||||
asset_id: str
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/queue/promote")
|
||||
def api_queue_promote(
|
||||
body: QueuePromoteRequest,
|
||||
frame: Frame = Depends(require_frame_control),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Moves a single photo to the front of the queue -- "Show next".
|
||||
Unlike reorder, doesn't depend on the client knowing the queue's
|
||||
exact current order, so it can't fail from staleness."""
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
if body.asset_id not in cfg.queue:
|
||||
raise HTTPException(400, "That photo is no longer in the upcoming queue")
|
||||
cfg.queue = [body.asset_id] + [asset_id for asset_id in cfg.queue if asset_id != body.asset_id]
|
||||
return {"status": "saved"}
|
||||
|
||||
|
||||
class QueueRemoveRequest(BaseModel):
|
||||
asset_id: str
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/queue/remove")
|
||||
def api_queue_remove(
|
||||
body: QueueRemoveRequest,
|
||||
frame: Frame = Depends(require_frame_control),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Permanently removes a photo from this frame's rotation. Does NOT
|
||||
touch Immich or the album itself; see photo_queue.remove_from_rotation()."""
|
||||
require_configured(frame)
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
photo_queue.remove_from_rotation(cfg, assets, body.asset_id)
|
||||
return {"status": "removed"}
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/thumbnail/{asset_id}")
|
||||
def api_thumbnail(asset_id: str, frame: Frame = Depends(require_frame_view)):
|
||||
"""Scoped to what this frame is actually showing/queuing -- a user
|
||||
merely linked to view this frame shouldn't be able to pull thumbnails
|
||||
for arbitrary asset ids in the owner's Immich library, only the
|
||||
frame's own curated album. Same rule device.frame_share and
|
||||
manage.manage_thumbnail already enforce."""
|
||||
require_configured(frame)
|
||||
if asset_id != frame.current_asset_id and asset_id not in frame.queue:
|
||||
raise HTTPException(404, "Not on this frame")
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
content, content_type = client.download_asset_thumbnail(asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(502, f"Could not download thumbnail from Immich: {e}") from e
|
||||
return Response(content=content, media_type=content_type)
|
||||
|
||||
|
||||
def _current_asset_id(frame: Frame, db: Session) -> str:
|
||||
"""Same idempotent get_current() dance /api/frames/{id}/queue uses --
|
||||
picks a current photo if none is set yet, otherwise just reads it,
|
||||
never advances early."""
|
||||
require_configured(frame)
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
with frame_locked(db, frame.id) as cfg:
|
||||
photo_queue.get_current(cfg, assets, in_quiet_hours=quiet_hours.in_quiet_hours(cfg))
|
||||
asset_id = cfg.current_asset_id
|
||||
if not asset_id:
|
||||
raise HTTPException(404, "No current photo")
|
||||
return asset_id
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/preview/original")
|
||||
def api_preview_original(frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)):
|
||||
"""The Immich preview image behind the currently-displayed photo,
|
||||
unprocessed -- the "now displaying" side of the Configuration tab's
|
||||
before/after comparison."""
|
||||
asset_id = _current_asset_id(frame, db)
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
jpeg_bytes = client.download_asset_preview(asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(502, f"Could not download asset from Immich: {e}") from e
|
||||
return Response(content=jpeg_bytes, media_type="image/jpeg")
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/preview/rendered")
|
||||
def api_preview_rendered(frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)):
|
||||
"""The same photo run through this frame's actual saved rendering
|
||||
pipeline (display mode, palette, color/contrast/dithering) and
|
||||
exported as a PNG -- the "how it will look on the frame" side of the
|
||||
comparison. Not a live preview of unsaved slider values; reflects
|
||||
whatever's currently saved."""
|
||||
asset_id = _current_asset_id(frame, db)
|
||||
client = immich_client_for(frame)
|
||||
source, faces = fetch_source_and_faces(client, frame, asset_id)
|
||||
png = render_preview_png(
|
||||
source, faces=faces, orientation=frame.orientation, palette_rgb=frame.palette_rgb,
|
||||
display_mode=frame.display_mode, color_boost=frame.color_boost,
|
||||
contrast_boost=frame.contrast_boost, dither_strength=frame.dither_strength,
|
||||
)
|
||||
return Response(content=png, media_type="image/png")
|
||||
|
||||
|
||||
class CalendarIncludedRequest(BaseModel):
|
||||
included: bool
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/calendar-included")
|
||||
def api_calendar_included(
|
||||
body: CalendarIncludedRequest,
|
||||
request: Request,
|
||||
frame: Frame = Depends(require_frame_view), # view access only -- NOT require_frame_control
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""A user's own opt-in into this frame's merged calendar (see
|
||||
UserFrame.calendar_included). Deliberately not require_frame_control:
|
||||
this is the toggling user's own data-sharing preference about their
|
||||
own calendar, not a frame setting its controller manages on someone
|
||||
else's behalf -- there's no target user_id in the request body by
|
||||
design, it always toggles the calling session's own row."""
|
||||
user = require_user_api(request, db)
|
||||
row = db.get(UserFrame, (user.id, frame.id))
|
||||
if row is None:
|
||||
raise HTTPException(404, "Not linked to this frame")
|
||||
row.calendar_included = body.included
|
||||
# Force this frame's merged cache to pick up the change promptly
|
||||
# rather than waiting out the throttle.
|
||||
frame.calendar_checked_at = 0.0
|
||||
db.commit()
|
||||
return {"status": "saved", "included": row.calendar_included}
|
||||
|
||||
|
||||
def _calendar_photo_inlay(frame: Frame, db: Session):
|
||||
"""The agenda view's optional photo-inlay source image, or None if
|
||||
inlay is off, not agenda view, or the frame's photos-mode album isn't
|
||||
configured. Shared shape between the live render (routers/device.py's
|
||||
_render_calendar_mode) and this preview endpoint; small enough that
|
||||
duplicating rather than factoring out is fine, since the two call
|
||||
sites differ slightly in error handling."""
|
||||
if not (frame.calendar_view == "agenda" and frame.calendar_photo_inlay):
|
||||
return None
|
||||
url, key = immich_creds(frame)
|
||||
if not (url and key and frame.album_id):
|
||||
return None
|
||||
try:
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
photo_queue.get_current(locked, assets, in_quiet_hours=quiet_hours.in_quiet_hours(locked))
|
||||
asset_id = locked.current_asset_id
|
||||
if not asset_id:
|
||||
return None
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
return Image.open(io.BytesIO(client.download_asset_preview(asset_id)))
|
||||
except HTTPException:
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/preview/calendar")
|
||||
def api_preview_calendar(frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)):
|
||||
"""The same merged, cached event set a live device render would use
|
||||
-- not a live preview of an unsaved calendar_view choice, same
|
||||
"reflects what's currently saved" convention as preview/rendered."""
|
||||
if not calendar_sources_for_frame(db, frame):
|
||||
raise HTTPException(400, "No calendars included on this frame yet")
|
||||
events, summary = get_or_refresh_calendar_events(db, frame)
|
||||
photo_inlay = _calendar_photo_inlay(frame, db)
|
||||
view = frame.calendar_view if frame.calendar_view in calendar_render.CALENDAR_VIEWS else "agenda"
|
||||
png = calendar_render.render_calendar_preview_png(
|
||||
events, view=view, browse_offset=frame.calendar_browse_offset, orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb, timezone=frame.timezone, photo_inlay=photo_inlay, fetch_summary=summary,
|
||||
)
|
||||
return Response(content=png, media_type="image/png")
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/firmware")
|
||||
def api_firmware_upload(
|
||||
@@ -583,6 +428,7 @@ def api_firmware_check(
|
||||
"board": frame.device_board_variant or None,
|
||||
"latest_version": frame.firmware_gitea_latest_version or None,
|
||||
"staged_version": frame.firmware_available_version or None,
|
||||
"running_version": frame.device_firmware_version or None,
|
||||
"update_available": update_available,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""Saved layouts: a named snapshot of one frame's widget arrangement
|
||||
(types, placement, per-widget settings, button assignments) that a user
|
||||
can capture and later apply to any frame they control whose grid matches
|
||||
-- see models.SavedLayout and docs/widgets.md's "Saved layouts" section.
|
||||
|
||||
Layouts are owned by a *user*, not a frame (SavedLayout.user_id), so
|
||||
every endpoint here except save/apply/list (which need a frame_id to act
|
||||
on) is frame-agnostic -- /api/layouts/{id} rather than /api/frames/{fid}/
|
||||
layouts/{id}, gated purely on "is this your own saved layout" rather than
|
||||
frame view/control.
|
||||
|
||||
Save/apply DO live under /api/frames/{frame_id}/... (require_frame_
|
||||
control) since they read/replace one specific frame's actual widgets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import grid
|
||||
from ..auth import require_frame_control, require_frame_view, require_user_api
|
||||
from ..db import frame_locked, get_db
|
||||
from ..models import (
|
||||
Frame,
|
||||
FrameButtonAction,
|
||||
FrameCalendar,
|
||||
FrameTaskList,
|
||||
SavedLayout,
|
||||
SavedLayoutButtonAction,
|
||||
SavedLayoutSource,
|
||||
SavedLayoutWidget,
|
||||
User,
|
||||
WIDGET_CONFIG_MODELS,
|
||||
Widget,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_LAYOUT_NAME_LEN = 60
|
||||
|
||||
# Per-widget-type allowlist of config columns that are an actual authored
|
||||
# *setting* (captured/restored by a saved layout) as opposed to runtime/
|
||||
# cache state (a photo widget's current queue position, a calendar's
|
||||
# fetch cache, a whiteboard's rendered-image cache, ...) which a layout
|
||||
# deliberately leaves out -- applying a layout should feel like a fresh
|
||||
# widget of that type with these settings pre-filled, not a resurrection
|
||||
# of stale queue/cache state from whenever it was saved. "static"
|
||||
# excludes `image` on purpose -- that BLOB lives on SavedLayoutWidget.image
|
||||
# instead (see its own model docstring).
|
||||
LAYOUT_CONFIG_FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"photos": ("album_id", "order", "display_mode", "queue_target_len"),
|
||||
"calendar": (
|
||||
"view", "week_start", "weather_enabled", "weather_units", "weather_cities",
|
||||
"week_days", "week_layout", "week_start_offset", "render_style",
|
||||
),
|
||||
"tasks": ("name", "show_completed", "render_style"),
|
||||
"static": ("display_mode", "original_filename", "render_style"),
|
||||
"text": ("content", "font_size", "font_family", "align", "background_color", "render_style"),
|
||||
"whiteboard": ("user_id", "url", "render_style"),
|
||||
"battery": ("mode", "render_style"),
|
||||
"weather": (
|
||||
"mode", "provider", "units", "city_label", "city_latitude", "city_longitude",
|
||||
"hourly_interval_hours", "daily_days", "cities", "render_style",
|
||||
),
|
||||
}
|
||||
|
||||
# widget_type -> (FrameCalendar|FrameTaskList model, SavedLayoutSource.kind)
|
||||
SOURCE_MODELS: dict[str, tuple[type, str]] = {
|
||||
"calendar": (FrameCalendar, "calendar"),
|
||||
"tasks": (FrameTaskList, "task"),
|
||||
}
|
||||
|
||||
|
||||
def _layout_summary(db: Session, layout: SavedLayout, frame: Frame | None = None) -> dict:
|
||||
widget_count = db.scalar(
|
||||
select(func.count()).select_from(SavedLayoutWidget).where(SavedLayoutWidget.saved_layout_id == layout.id)
|
||||
)
|
||||
result = {
|
||||
"id": layout.id,
|
||||
"name": layout.name,
|
||||
"cols": layout.cols,
|
||||
"rows": layout.rows,
|
||||
"widget_count": widget_count or 0,
|
||||
"created_at": layout.created_at,
|
||||
"updated_at": layout.updated_at,
|
||||
}
|
||||
if frame is not None:
|
||||
cols, rows = grid.grid_dims(frame.orientation)
|
||||
result["compatible"] = (layout.cols, layout.rows) == (cols, rows)
|
||||
return result
|
||||
|
||||
|
||||
def _user_owned_layout(db: Session, layout_id: int, user: User) -> SavedLayout:
|
||||
layout = db.get(SavedLayout, layout_id)
|
||||
if layout is None or layout.user_id != user.id:
|
||||
raise HTTPException(404, "No such saved layout")
|
||||
return layout
|
||||
|
||||
|
||||
@router.get("/api/frames/{frame_id}/layouts")
|
||||
def api_layouts_list(request: Request, frame: Frame = Depends(require_frame_view), db: Session = Depends(get_db)):
|
||||
"""Every saved layout owned by the calling user (saved layouts are
|
||||
global to a user, not scoped to this or any other frame) -- includes
|
||||
a `compatible` flag per layout for whether it can actually be applied
|
||||
to *this* frame's current grid, so the UI can offer incompatible ones
|
||||
greyed-out with a reason rather than hiding them outright."""
|
||||
user = require_user_api(request, db)
|
||||
layouts = db.scalars(
|
||||
select(SavedLayout).where(SavedLayout.user_id == user.id).order_by(SavedLayout.name)
|
||||
).all()
|
||||
return {"layouts": [_layout_summary(db, layout, frame) for layout in layouts]}
|
||||
|
||||
|
||||
class LayoutSaveRequest(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
def _snapshot_widget_config(widget: Widget, config) -> dict:
|
||||
fields = LAYOUT_CONFIG_FIELDS.get(widget.widget_type, ())
|
||||
return {field: getattr(config, field) for field in fields}
|
||||
|
||||
|
||||
def _snapshot_sources(db: Session, widget_id: int, model: type) -> list[dict]:
|
||||
rows = db.scalars(select(model).where(model.widget_id == widget_id)).all()
|
||||
return [
|
||||
{
|
||||
"user_id": row.user_id, "calendar_key": row.calendar_key, "calendar_label": row.calendar_label,
|
||||
"included": row.included, "color_index": row.color_index,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/layouts")
|
||||
def api_layout_save(
|
||||
body: LayoutSaveRequest, request: Request,
|
||||
frame: Frame = Depends(require_frame_control), db: Session = Depends(get_db),
|
||||
):
|
||||
"""Snapshots this frame's current widgets (placement + settings,
|
||||
see LAYOUT_CONFIG_FIELDS), their calendar/task sources, and their
|
||||
button-action bindings into a named layout owned by the calling
|
||||
user. Saving again with a name this user already has overwrites that
|
||||
layout's snapshot in place (see models.SavedLayout's docstring)
|
||||
rather than erroring or creating a duplicate."""
|
||||
user = require_user_api(request, db)
|
||||
name = body.name.strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name is required")
|
||||
if len(name) > MAX_LAYOUT_NAME_LEN:
|
||||
raise HTTPException(400, f"Name must be {MAX_LAYOUT_NAME_LEN} characters or fewer")
|
||||
|
||||
cols, rows = grid.grid_dims(frame.orientation)
|
||||
widgets = db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame.id).order_by(Widget.sort_order)
|
||||
).all()
|
||||
|
||||
now = time.time()
|
||||
existing = db.execute(
|
||||
select(SavedLayout).where(SavedLayout.user_id == user.id, SavedLayout.name == name)
|
||||
).scalar_one_or_none()
|
||||
if existing is not None:
|
||||
layout = existing
|
||||
layout.cols, layout.rows, layout.updated_at = cols, rows, now
|
||||
db.execute(delete(SavedLayoutWidget).where(SavedLayoutWidget.saved_layout_id == layout.id))
|
||||
db.flush()
|
||||
else:
|
||||
layout = SavedLayout(user_id=user.id, name=name, cols=cols, rows=rows, created_at=now, updated_at=now)
|
||||
db.add(layout)
|
||||
db.flush()
|
||||
|
||||
snapshot_id_by_widget_id: dict[int, int] = {}
|
||||
for widget in widgets:
|
||||
config = db.get(WIDGET_CONFIG_MODELS[widget.widget_type], widget.id)
|
||||
snapshot = SavedLayoutWidget(
|
||||
saved_layout_id=layout.id, widget_type=widget.widget_type,
|
||||
x=widget.x, y=widget.y, w=widget.w, h=widget.h, sort_order=widget.sort_order,
|
||||
config=_snapshot_widget_config(widget, config),
|
||||
image=config.image if widget.widget_type == "static" else None,
|
||||
)
|
||||
db.add(snapshot)
|
||||
db.flush()
|
||||
snapshot_id_by_widget_id[widget.id] = snapshot.id
|
||||
|
||||
source_model = SOURCE_MODELS.get(widget.widget_type)
|
||||
if source_model is not None:
|
||||
model, kind = source_model
|
||||
for source in _snapshot_sources(db, widget.id, model):
|
||||
db.add(SavedLayoutSource(saved_layout_widget_id=snapshot.id, kind=kind, **source))
|
||||
|
||||
actions = db.scalars(select(FrameButtonAction).where(FrameButtonAction.frame_id == frame.id)).all()
|
||||
for action in actions:
|
||||
snapshot_id = snapshot_id_by_widget_id.get(action.widget_id)
|
||||
if snapshot_id is None:
|
||||
continue
|
||||
db.add(SavedLayoutButtonAction(
|
||||
saved_layout_widget_id=snapshot_id, button=action.button, action=action.action,
|
||||
sort_order=action.sort_order,
|
||||
))
|
||||
|
||||
db.commit()
|
||||
return _layout_summary(db, layout, frame)
|
||||
|
||||
|
||||
class LayoutRenameRequest(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
@router.patch("/api/layouts/{layout_id}")
|
||||
def api_layout_rename(layout_id: int, body: LayoutRenameRequest, request: Request, db: Session = Depends(get_db)):
|
||||
user = require_user_api(request, db)
|
||||
layout = _user_owned_layout(db, layout_id, user)
|
||||
name = body.name.strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name is required")
|
||||
if len(name) > MAX_LAYOUT_NAME_LEN:
|
||||
raise HTTPException(400, f"Name must be {MAX_LAYOUT_NAME_LEN} characters or fewer")
|
||||
conflict = db.execute(
|
||||
select(SavedLayout).where(
|
||||
SavedLayout.user_id == user.id, SavedLayout.name == name, SavedLayout.id != layout.id
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if conflict is not None:
|
||||
raise HTTPException(400, "You already have a saved layout with that name")
|
||||
layout.name = name
|
||||
layout.updated_at = time.time()
|
||||
db.commit()
|
||||
return _layout_summary(db, layout)
|
||||
|
||||
|
||||
@router.delete("/api/layouts/{layout_id}")
|
||||
def api_layout_delete(layout_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
user = require_user_api(request, db)
|
||||
layout = _user_owned_layout(db, layout_id, user)
|
||||
db.delete(layout)
|
||||
db.commit()
|
||||
return {"status": "deleted"}
|
||||
|
||||
|
||||
def apply_layout_to_frame(db: Session, frame: Frame, layout: SavedLayout) -> int:
|
||||
"""Replaces frame's entire widget arrangement with layout's snapshot
|
||||
-- every current widget (and its own config/sources/button actions,
|
||||
all ondelete="CASCADE") is deleted first, same "act unconditionally
|
||||
on the server, confirm on the client" posture as
|
||||
api_widgets.api_widgets_clear. A source whose owning user account
|
||||
(or a whiteboard's user_id) no longer exists is silently dropped
|
||||
rather than left dangling -- config is JSON, not FK-checked, so
|
||||
nothing enforces that at the storage layer. Shared by api_layout_apply
|
||||
(explicit user action) and global_actions.cycle_layout (a hold-
|
||||
triggered global action, see app/global_actions.py) -- caller is
|
||||
responsible for checking the grid-size match first. Returns the
|
||||
number of widgets applied."""
|
||||
snapshots = db.scalars(
|
||||
select(SavedLayoutWidget)
|
||||
.where(SavedLayoutWidget.saved_layout_id == layout.id)
|
||||
.order_by(SavedLayoutWidget.sort_order)
|
||||
).all()
|
||||
|
||||
with frame_locked(db, frame.id):
|
||||
for widget in db.scalars(select(Widget).where(Widget.frame_id == frame.id)).all():
|
||||
db.delete(widget)
|
||||
db.flush()
|
||||
|
||||
new_widget_id_by_snapshot_id: dict[int, int] = {}
|
||||
for snapshot in snapshots:
|
||||
widget = Widget(
|
||||
frame_id=frame.id, widget_type=snapshot.widget_type,
|
||||
x=snapshot.x, y=snapshot.y, w=snapshot.w, h=snapshot.h,
|
||||
sort_order=snapshot.sort_order, created_at=time.time(),
|
||||
)
|
||||
db.add(widget)
|
||||
db.flush()
|
||||
new_widget_id_by_snapshot_id[snapshot.id] = widget.id
|
||||
|
||||
config = WIDGET_CONFIG_MODELS[snapshot.widget_type](widget_id=widget.id)
|
||||
for field, value in snapshot.config.items():
|
||||
if field == "user_id" and value is not None and db.get(User, value) is None:
|
||||
value = None # that WebDAV account no longer exists
|
||||
setattr(config, field, value)
|
||||
if snapshot.widget_type == "static" and snapshot.image is not None:
|
||||
config.image = snapshot.image
|
||||
config.uploaded_at = time.time()
|
||||
db.add(config)
|
||||
|
||||
source_model = SOURCE_MODELS.get(snapshot.widget_type)
|
||||
if source_model is not None:
|
||||
model, kind = source_model
|
||||
sources = db.scalars(
|
||||
select(SavedLayoutSource).where(
|
||||
SavedLayoutSource.saved_layout_widget_id == snapshot.id, SavedLayoutSource.kind == kind
|
||||
)
|
||||
).all()
|
||||
for source in sources:
|
||||
if db.get(User, source.user_id) is None:
|
||||
continue # that account no longer exists
|
||||
db.add(model(
|
||||
widget_id=widget.id, user_id=source.user_id, calendar_key=source.calendar_key,
|
||||
calendar_label=source.calendar_label, included=source.included,
|
||||
color_index=source.color_index,
|
||||
))
|
||||
|
||||
for snapshot in snapshots:
|
||||
actions = db.scalars(
|
||||
select(SavedLayoutButtonAction)
|
||||
.where(SavedLayoutButtonAction.saved_layout_widget_id == snapshot.id)
|
||||
.order_by(SavedLayoutButtonAction.sort_order)
|
||||
).all()
|
||||
for action in actions:
|
||||
db.add(FrameButtonAction(
|
||||
frame_id=frame.id, button=action.button,
|
||||
widget_id=new_widget_id_by_snapshot_id[snapshot.id], action=action.action,
|
||||
sort_order=action.sort_order, created_at=time.time(),
|
||||
))
|
||||
db.commit()
|
||||
return len(snapshots)
|
||||
|
||||
|
||||
@router.post("/api/frames/{frame_id}/layouts/{layout_id}/apply")
|
||||
def api_layout_apply(
|
||||
layout_id: int, request: Request,
|
||||
frame: Frame = Depends(require_frame_control), db: Session = Depends(get_db),
|
||||
):
|
||||
"""Replaces this frame's entire widget arrangement with a saved
|
||||
layout's -- see apply_layout_to_frame above for what that actually
|
||||
does."""
|
||||
user = require_user_api(request, db)
|
||||
layout = _user_owned_layout(db, layout_id, user)
|
||||
cols, rows = grid.grid_dims(frame.orientation)
|
||||
if (layout.cols, layout.rows) != (cols, rows):
|
||||
raise HTTPException(400, "This layout was saved for a different frame size/orientation")
|
||||
|
||||
widget_count = apply_layout_to_frame(db, frame, layout)
|
||||
return {"status": "applied", "widget_count": widget_count}
|
||||
File diff suppressed because it is too large
Load Diff
+565
-104
@@ -5,8 +5,9 @@ from __future__ import annotations
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import statistics
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
@@ -15,15 +16,28 @@ from PIL import Image
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import calendar_feed, quiet_hours
|
||||
from ..db import frame_locked
|
||||
from ..image_pipeline import render_frame
|
||||
from .. import caldav_client, calendar_feed, grid, quiet_hours, weather, whiteboard
|
||||
from ..db import widget_locked
|
||||
from ..image_pipeline import logical_render_size
|
||||
from ..immich_client import ImmichClient
|
||||
from ..models import Frame, User, UserFrame
|
||||
from ..models import (
|
||||
BatteryLog,
|
||||
CalendarWidgetConfig,
|
||||
Frame,
|
||||
FrameButtonAction,
|
||||
FrameCalendar,
|
||||
FrameTaskList,
|
||||
PhotoWidgetConfig,
|
||||
TaskWidgetConfig,
|
||||
User,
|
||||
Widget,
|
||||
WeatherWidgetConfig,
|
||||
WhiteboardWidgetConfig,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FRAME_MODES = ("photos", "calendar")
|
||||
FRAME_MODES = ("photos", "calendar", "whiteboard")
|
||||
|
||||
# Battery-history / estimate tuning (see /frame/battery and battery_estimate_s).
|
||||
BATTERY_HISTORY_MAX = 500 # ~20 days at hourly reports
|
||||
@@ -38,8 +52,19 @@ RECHARGE_JUMP_PCT = 5 # a report this much above the recent baseline = battery
|
||||
# still needs to clear all of them, while a single stray low one doesn't
|
||||
# get to set the bar.
|
||||
RECHARGE_LOOKBACK = 3
|
||||
MIN_ESTIMATE_SPAN_S = 2 * 3600 # need at least this much observed time...
|
||||
MIN_ESTIMATE_DROP_PCT = 2 # ...and this much observed drop before estimating
|
||||
BATTERY_ESTIMATE_SAMPLE_COUNT = 100 # most recent battery_log rows considered
|
||||
MIN_ESTIMATE_SAMPLES = 5 # discharge steps needed before trusting the average
|
||||
# Modified z-score cutoff (Iglewicz & Hoaglin's standard figure) for
|
||||
# _reject_outlier_drops -- see that function's docstring for why a
|
||||
# single noisy reading needs rejecting at the per-wake-drop level, not
|
||||
# just at the recharge-detection level.
|
||||
OUTLIER_MODIFIED_Z_THRESHOLD = 3.5
|
||||
# Readings considered on each side of a given reading when
|
||||
# _smooth_percents looks for local outliers. Needs to be at least half
|
||||
# the length of the longest bad-reading burst a noisy divider produces
|
||||
# (observed up to ~4 consecutive corrupted reports on one frame) so the
|
||||
# good neighbors still outnumber the bad ones in the window.
|
||||
BATTERY_SMOOTHING_WINDOW = 4
|
||||
|
||||
# "Overdue" threshold multiplier: the device should check in roughly every
|
||||
# refresh_interval_s; give it half again as long before flagging it.
|
||||
@@ -67,17 +92,9 @@ def immich_client_for(frame: Frame) -> ImmichClient:
|
||||
return ImmichClient(url, key)
|
||||
|
||||
|
||||
def require_configured(frame: Frame) -> None:
|
||||
url, key = immich_creds(frame)
|
||||
if not url or not key:
|
||||
raise HTTPException(400, "Immich URL/API key not configured yet")
|
||||
if not frame.album_id:
|
||||
raise HTTPException(400, "No album configured yet")
|
||||
|
||||
|
||||
def list_assets(client: ImmichClient, frame: Frame) -> list[dict]:
|
||||
def list_assets(client: ImmichClient, album_id: str) -> list[dict]:
|
||||
try:
|
||||
assets = client.list_album_assets(frame.album_id)
|
||||
assets = client.list_album_assets(album_id)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(502, f"Could not reach Immich: {e}") from e
|
||||
if not assets:
|
||||
@@ -85,18 +102,22 @@ def list_assets(client: ImmichClient, frame: Frame) -> list[dict]:
|
||||
return assets
|
||||
|
||||
|
||||
def fetch_source_and_faces(client: ImmichClient, frame: Frame, asset_id: str) -> tuple[Image.Image, list[dict] | None]:
|
||||
def fetch_source_and_faces(
|
||||
client: ImmichClient, display_mode: str, asset_id: str
|
||||
) -> tuple[Image.Image, list[dict] | None]:
|
||||
"""The shared first half of rendering: download the Immich preview
|
||||
and (only if display_mode needs it) its detected faces. Used by both
|
||||
render_asset (device-facing) and the web UI's rendered-preview
|
||||
endpoint (routers/api_frames.py) so they can't drift apart."""
|
||||
and (only if display_mode needs it) its detected faces. Used by the
|
||||
web UI's rendered-preview endpoint (routers/api_widgets.py's
|
||||
api_widget_preview_rendered). Takes display_mode directly (a photos
|
||||
widget's own setting, see PhotoWidgetConfig) rather than a whole
|
||||
Frame -- this function only ever needed that one attribute off it."""
|
||||
try:
|
||||
jpeg_bytes = client.download_asset_preview(asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(502, f"Could not download asset from Immich: {e}") from e
|
||||
|
||||
faces = None
|
||||
if frame.display_mode == "crop_faces":
|
||||
if display_mode == "crop_faces":
|
||||
try:
|
||||
faces = client.get_asset_faces(asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
@@ -107,30 +128,173 @@ def fetch_source_and_faces(client: ImmichClient, frame: Frame, asset_id: str) ->
|
||||
return Image.open(io.BytesIO(jpeg_bytes)), faces
|
||||
|
||||
|
||||
def render_asset(client: ImmichClient, frame: Frame, asset_id: str, manage: dict | None = None) -> bytes:
|
||||
source, faces = fetch_source_and_faces(client, frame, asset_id)
|
||||
return render_frame(source, faces=faces, orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb, display_mode=frame.display_mode,
|
||||
color_boost=frame.color_boost, contrast_boost=frame.contrast_boost,
|
||||
dither_strength=frame.dither_strength, manage=manage)
|
||||
def _avg_wake_interval_s(frame: Frame) -> float:
|
||||
"""Average wall-clock seconds between wakes: refresh_interval_s
|
||||
scaled up for however much of each day quiet hours removes from the
|
||||
wake schedule entirely -- fewer wakes/day, not a cheaper wake. This
|
||||
is what lets battery_estimate_s convert a per-wake drop rate into a
|
||||
remaining-time estimate that reacts to both settings immediately,
|
||||
rather than only after enough new history accumulates under them."""
|
||||
active_day_s = max(1, 86400 - quiet_hours.quiet_span_s(frame))
|
||||
interval_s = max(1, frame.refresh_interval_s)
|
||||
wakes_per_day = max(1, active_day_s // interval_s)
|
||||
return 86400 / wakes_per_day
|
||||
|
||||
|
||||
def battery_estimate_s(frame: Frame) -> int | None:
|
||||
"""Linear remaining-time estimate from the current discharge cycle's
|
||||
observed rate, or None when there's not enough signal to be honest
|
||||
about (too little time observed, or too little drop -- a flat line
|
||||
extrapolates to garbage)."""
|
||||
hist = frame.battery_history
|
||||
if len(hist) < 2:
|
||||
def _reject_outlier_drops(steps: list[tuple[int, float]]) -> list[tuple[int, float]]:
|
||||
"""Drops (weight, drop_pct) pairs whose drop is a wild outlier
|
||||
relative to the rest of the recent steps. A single noisy ADC/
|
||||
regulator glitch (see firmware/main/battery.c) corrupts one of the
|
||||
two steps around it, whichever way it reads: a glitch that dips low
|
||||
then recovers makes the step INTO it a spurious huge drop (the step
|
||||
back out is an increase, already excluded above as a "recharge");
|
||||
one that spikes high then settles makes the step OUT OF it the
|
||||
spurious one instead (the step into it is the excluded "recharge").
|
||||
Either way, one bad reading survives the recharge filter looking
|
||||
like an ordinary, legitimately huge drop and swings the whole
|
||||
remaining-time estimate on its own.
|
||||
|
||||
Uses a MAD-based modified z-score (robust to a small number of
|
||||
extreme values in a way a plain mean/stdev z-score isn't -- a single
|
||||
huge outlier inflates the stdev itself, which just hides the outlier
|
||||
from a stdev-based test) rather than a fixed percent-point cutoff, so
|
||||
it adapts to how noisy a given frame's own sensor actually is
|
||||
instead of guessing one global threshold for every install."""
|
||||
drops = [drop for _, drop in steps]
|
||||
median = statistics.median(drops)
|
||||
abs_devs = [abs(d - median) for d in drops]
|
||||
mad = statistics.median(abs_devs)
|
||||
if mad == 0:
|
||||
# The standard median-based MAD degenerates to exactly 0 as soon
|
||||
# as more than half the steps share the median exactly -- and
|
||||
# real battery data is small integer percents, so "most wakes
|
||||
# cost exactly 1%" ties are the norm, not an edge case. That's
|
||||
# precisely the shape a single spliced-in glitch among a steady
|
||||
# discharge rate has (18 steps at "1", one at "26"), so treating
|
||||
# MAD==0 as "no spread, nothing to reject" would let exactly the
|
||||
# outlier this function exists for sail straight through. Fall
|
||||
# back to mean absolute deviation instead, which only reaches 0
|
||||
# when every single step is identical.
|
||||
mad = statistics.mean(abs_devs)
|
||||
if mad == 0:
|
||||
return steps # every step really is identical -- nothing to reject
|
||||
kept = [
|
||||
(weight, drop) for weight, drop in steps
|
||||
if abs(0.6745 * (drop - median) / mad) <= OUTLIER_MODIFIED_Z_THRESHOLD
|
||||
]
|
||||
return kept or steps # never filter down to nothing
|
||||
|
||||
|
||||
def _smooth_percents(percents: list[int]) -> list[float]:
|
||||
"""Replaces any reading that's a wild outlier against its own local
|
||||
neighborhood with that neighborhood's median, before per-wake drop
|
||||
steps are ever built from the series.
|
||||
|
||||
_reject_outlier_drops (above) only catches a bad reading by how much
|
||||
it distorts the *steps* immediately on either side of it -- which is
|
||||
exactly what one isolated glitch does, but a 1M-ohm divider (see
|
||||
firmware/main/battery.c) doesn't always misfire in isolation: several
|
||||
consecutive reports can drift or glitch together (a multi-minute
|
||||
crawl from 68 up into the high 70s with nothing charging, or a run of
|
||||
several ~40 reports spliced into an otherwise flat ~53 run). A step
|
||||
computed *between* two bad readings in the same burst looks like an
|
||||
ordinary small change, not an outlier, so it sails through
|
||||
_reject_outlier_drops untouched.
|
||||
|
||||
A Hampel identifier catches that instead: each reading is compared to
|
||||
the median of its own local window (not the whole series), using the
|
||||
same MAD-based modified z-score as _reject_outlier_drops so this
|
||||
adapts to how noisy a given frame's sensor actually is rather than a
|
||||
fixed percent-point cutoff. A window of BATTERY_SMOOTHING_WINDOW
|
||||
reports on each side tolerates a bad burst up to that long while
|
||||
still being outvoted by the surrounding good readings."""
|
||||
n = len(percents)
|
||||
smoothed = list(percents)
|
||||
for i in range(n):
|
||||
lo = max(0, i - BATTERY_SMOOTHING_WINDOW)
|
||||
hi = min(n, i + BATTERY_SMOOTHING_WINDOW + 1)
|
||||
neighborhood = percents[lo:hi]
|
||||
median = statistics.median(neighborhood)
|
||||
abs_devs = [abs(v - median) for v in neighborhood]
|
||||
# Unlike _reject_outlier_drops, no mean-of-abs-devs fallback here:
|
||||
# a burst can be a big enough share of this small a window that
|
||||
# the mean itself gets dragged up by the very values being
|
||||
# tested, hiding them. A flat 1-percentage-point floor -- this
|
||||
# project's smallest real unit of noise -- keeps the test from
|
||||
# dividing by zero without being skewed by the burst it's
|
||||
# checking.
|
||||
mad = statistics.median(abs_devs) or 1
|
||||
if abs(0.6745 * (percents[i] - median) / mad) > OUTLIER_MODIFIED_Z_THRESHOLD:
|
||||
smoothed[i] = median
|
||||
return smoothed
|
||||
|
||||
|
||||
def battery_estimate_s(frame: Frame, db: Session) -> int | None:
|
||||
"""Remaining-time estimate from a recency-weighted average of the
|
||||
*per-wake* percent drop, over the last BATTERY_ESTIMATE_SAMPLE_COUNT
|
||||
rows of the permanent battery_log table -- not just the current
|
||||
discharge cycle's battery_history, which resets to empty on every
|
||||
recharge and so often doesn't hold enough signal on its own even
|
||||
though the frame has plenty of history overall.
|
||||
|
||||
Consecutive reports are assumed to be consecutive wakes (firmware
|
||||
reports battery on every wake while on battery), so each step's
|
||||
(prev_percent - next_percent) is that wake's cost. Raw percents go
|
||||
through _smooth_percents first, which corrects readings (including
|
||||
short bursts of them) that are wild outliers against their own local
|
||||
neighborhood -- see that function's docstring for why that catches
|
||||
noise shapes _reject_outlier_drops can't. A step where percent went
|
||||
*up* is a recharge, not negative drain, and is skipped entirely
|
||||
rather than folded in as a weird outlier; a flat step (0% change)
|
||||
still counts as a real, cheap wake -- excluding those would
|
||||
systematically overstate the per-wake cost by only counting the
|
||||
wakes that happened to tick the percentage down. The remaining steps
|
||||
then get one more pass, _reject_outlier_drops, to catch whatever
|
||||
single-noisy-reading shape survives smoothing (see that function's
|
||||
docstring). Steps are weighted linearly by recency (step i of n gets
|
||||
weight i, 1-indexed) so a recent change in usage pattern shows up
|
||||
quickly instead of being washed out by a long flat history.
|
||||
|
||||
The resulting %/wake rate is then converted to wall-clock time using
|
||||
the frame's *current* refresh_interval_s and quiet-hours settings
|
||||
(see _avg_wake_interval_s), not whatever cadence produced the
|
||||
historical data -- so halving refresh_interval_s roughly halves the
|
||||
estimate immediately (not exactly halves: quiet hours removes a
|
||||
fixed wake-free window from every day regardless of interval, which
|
||||
is the "other things going on" that keeps the scaling sublinear)."""
|
||||
if frame.battery_percent < 0:
|
||||
return None
|
||||
first_ts, first_pct = hist[0]
|
||||
last_ts, last_pct = hist[-1]
|
||||
span = last_ts - first_ts
|
||||
drop = first_pct - last_pct
|
||||
if span < MIN_ESTIMATE_SPAN_S or drop < MIN_ESTIMATE_DROP_PCT:
|
||||
rows = db.execute(
|
||||
select(BatteryLog.percent)
|
||||
.where(BatteryLog.frame_id == frame.id)
|
||||
.order_by(BatteryLog.ts.desc())
|
||||
.limit(BATTERY_ESTIMATE_SAMPLE_COUNT)
|
||||
).scalars().all()
|
||||
if len(rows) < MIN_ESTIMATE_SAMPLES + 1:
|
||||
return None
|
||||
rate = drop / span # percent per second
|
||||
return int(last_pct / rate)
|
||||
percents = list(reversed(rows)) # chronological order
|
||||
percents = _smooth_percents(percents)
|
||||
|
||||
steps: list[tuple[int, float]] = [] # (recency_weight, drop_pct)
|
||||
for i in range(1, len(percents)):
|
||||
prev_pct, next_pct = percents[i - 1], percents[i]
|
||||
if next_pct > prev_pct:
|
||||
continue # recharge (or a swap) -- not a discharge sample
|
||||
steps.append((i, prev_pct - next_pct)) # later steps (larger i) weigh more
|
||||
|
||||
if len(steps) < MIN_ESTIMATE_SAMPLES:
|
||||
return None
|
||||
steps = _reject_outlier_drops(steps)
|
||||
|
||||
weight_total = sum(weight for weight, _ in steps)
|
||||
if weight_total <= 0:
|
||||
return None
|
||||
avg_drop_per_wake = sum(weight * drop for weight, drop in steps) / weight_total
|
||||
if avg_drop_per_wake <= 0:
|
||||
return None # flat -- no honest rate to extrapolate
|
||||
|
||||
remaining_wakes = frame.battery_percent / avg_drop_per_wake
|
||||
return int(remaining_wakes * _avg_wake_interval_s(frame))
|
||||
|
||||
|
||||
def shell_context(request, db: Session, user, active_frame: Frame | None = None,
|
||||
@@ -241,16 +405,63 @@ def _format_taken_at(exif: dict) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _manage_content_asset_id(frame: Frame) -> str | None:
|
||||
"""Whether frame.current_asset_id refers to a photo actually visible
|
||||
right now, for whichever mode is active -- always true in photos
|
||||
mode; only true in calendar mode when the agenda view's photo inlay
|
||||
is on (otherwise current_asset_id could be stale, left over from
|
||||
whenever photos mode last ran, and showing its location/date/share
|
||||
info on a manage overlay over a view with no visible photo at all
|
||||
would be actively misleading, not just unhelpful)."""
|
||||
relevant = frame.mode != "calendar" or (frame.calendar_view == "agenda" and frame.calendar_photo_inlay)
|
||||
return frame.current_asset_id if relevant and frame.current_asset_id else None
|
||||
def widget_of_type(db: Session, frame: Frame, widget_type: str) -> Widget | None:
|
||||
"""The frame's first widget of this type, by placement order. Until
|
||||
the placement UI (a later phase) ships, every frame has at most one
|
||||
widget per type -- the auto-migrated default -- so callers needing
|
||||
"the photo widget" / "the calendar widget" / "the whiteboard widget"
|
||||
for what's still effectively a single-widget-per-type frame use this
|
||||
rather than querying Widget directly. None if the frame has no widget
|
||||
of this type."""
|
||||
return db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame.id, Widget.widget_type == widget_type)
|
||||
.order_by(Widget.sort_order)
|
||||
).first()
|
||||
|
||||
|
||||
def photo_widget_config_or_404(db: Session, frame: Frame) -> tuple[Widget, PhotoWidgetConfig]:
|
||||
"""The frame's photo widget + its config, or a 400 if Immich creds or
|
||||
an album aren't set up yet. Immich creds are frame/owner-level, but
|
||||
album_id lives on PhotoWidgetConfig. Shared by api_frames.py and
|
||||
manage.py, whose photo-related endpoints both need exactly this."""
|
||||
url, key = immich_creds(frame)
|
||||
if not url or not key:
|
||||
raise HTTPException(400, "Immich URL/API key not configured yet")
|
||||
widget = widget_of_type(db, frame, "photos")
|
||||
cfg = db.get(PhotoWidgetConfig, widget.id) if widget else None
|
||||
if widget is None or not cfg.album_id:
|
||||
raise HTTPException(400, "No album configured yet")
|
||||
return widget, cfg
|
||||
|
||||
|
||||
def photo_widgets_for_frame(db: Session, frame: Frame) -> list[Widget]:
|
||||
return db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame.id, Widget.widget_type == "photos")
|
||||
.order_by(Widget.sort_order)
|
||||
).all()
|
||||
|
||||
|
||||
def _primary_photo_widget(db: Session, frame: Frame, photo_widgets: list[Widget]) -> Widget | None:
|
||||
"""The one photo widget the manage overlay's location/date/share-link
|
||||
boxes show info for -- unlike face labels (which generalize to every
|
||||
photo widget on screen, see build_manage_content), there's only one
|
||||
of each of these fixed panel corners to go around, so with more than
|
||||
one photo widget some single one has to be picked. Resolution rule:
|
||||
whichever photo widget the NEXT button's first assigned action
|
||||
targets, falling back to the first photo widget by placement order
|
||||
if none is button-assigned."""
|
||||
if not photo_widgets:
|
||||
return None
|
||||
next_actions = db.scalars(
|
||||
select(FrameButtonAction)
|
||||
.where(FrameButtonAction.frame_id == frame.id, FrameButtonAction.button == "next")
|
||||
.order_by(FrameButtonAction.sort_order)
|
||||
).all()
|
||||
photo_widget_ids = {w.id for w in photo_widgets}
|
||||
for action in next_actions:
|
||||
if action.widget_id in photo_widget_ids:
|
||||
return next(w for w in photo_widgets if w.id == action.widget_id)
|
||||
return photo_widgets[0]
|
||||
|
||||
|
||||
def build_manage_content(db: Session, frame: Frame, request) -> dict:
|
||||
@@ -259,82 +470,332 @@ def build_manage_content(db: Session, frame: Frame, request) -> dict:
|
||||
/frame/face-labels, both removed -- see the module docstring in
|
||||
manage_overlay.py) are now just internal calls made here, once,
|
||||
server-side, since compositing itself also moved server-side.
|
||||
management_url and battery_percent always apply; location/date/
|
||||
share-URL/face-labels only when there's a real current photo (see
|
||||
_manage_content_asset_id) -- absent otherwise, which
|
||||
manage_overlay.compose() already treats as "skip that region",
|
||||
exactly the graceful-degradation behavior the old firmware-fetched
|
||||
version had."""
|
||||
management_url and battery_percent always apply. location/date/
|
||||
share-URL come from one "primary" photo widget (see
|
||||
_primary_photo_widget -- there's only one of each of those fixed
|
||||
panel corners, so with more than one photo widget on screen some
|
||||
single one has to be picked); face labels generalize more simply,
|
||||
since manage_overlay.compose() already takes a flat list and draws
|
||||
each one independently -- every photo widget's own named faces get
|
||||
concatenated in, each positioned within that widget's own region
|
||||
(see face_labels.compute_face_labels' region param) rather than as
|
||||
if a photo filled the whole panel."""
|
||||
base = str(request.base_url).rstrip("/")
|
||||
content: dict = {
|
||||
"management_url": f"{base}/m/{frame.manage_token}",
|
||||
"battery_percent": frame.battery_percent,
|
||||
}
|
||||
|
||||
asset_id = _manage_content_asset_id(frame)
|
||||
if not asset_id:
|
||||
photo_widgets = photo_widgets_for_frame(db, frame)
|
||||
if not photo_widgets:
|
||||
return content
|
||||
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
asset = client.get_asset(asset_id)
|
||||
faces = client.get_asset_faces(asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
logger.warning("Could not fetch manage-overlay photo info for asset %s: %s", asset_id, e)
|
||||
return content
|
||||
|
||||
exif = asset.get("exifInfo") or {}
|
||||
content["location_lines"] = _format_location(exif)
|
||||
content["taken_at"] = _format_taken_at(exif)
|
||||
content["share_url"] = f"{base}/frame/share/{asset_id}"
|
||||
|
||||
if any((face.get("person") or {}).get("name") for face in faces):
|
||||
primary = _primary_photo_widget(db, frame, photo_widgets)
|
||||
primary_cfg = db.get(PhotoWidgetConfig, primary.id) if primary else None
|
||||
if primary_cfg and primary_cfg.current_asset_id:
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
preview_bytes = client.download_asset_preview(asset_id)
|
||||
from ..face_labels import compute_face_labels
|
||||
|
||||
content["face_labels"] = compute_face_labels(preview_bytes, faces, frame.display_mode, frame.orientation)
|
||||
asset = client.get_asset(primary_cfg.current_asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
logger.warning("Could not download asset %s for face-label mapping: %s", asset_id, e)
|
||||
logger.warning(
|
||||
"Could not fetch manage-overlay photo info for asset %s: %s", primary_cfg.current_asset_id, e
|
||||
)
|
||||
else:
|
||||
exif = asset.get("exifInfo") or {}
|
||||
content["location_lines"] = _format_location(exif)
|
||||
content["taken_at"] = _format_taken_at(exif)
|
||||
|
||||
# Unlike location/date-taken (a single fixed corner, so tied to the
|
||||
# one "primary" widget above), the share link covers every photo
|
||||
# widget's current photo (see manage.manage_share) -- so it only
|
||||
# needs *some* photo widget to have a current photo, not specifically
|
||||
# the primary one, and doesn't depend on the EXIF fetch above
|
||||
# succeeding.
|
||||
if any(db.get(PhotoWidgetConfig, w.id).current_asset_id for w in photo_widgets):
|
||||
content["share_url"] = f"{base}/frame/share/{frame.manage_token}"
|
||||
|
||||
panel_w, panel_h = logical_render_size(frame.orientation)
|
||||
face_labels: list[dict] = []
|
||||
for widget in photo_widgets:
|
||||
cfg = db.get(PhotoWidgetConfig, widget.id)
|
||||
if not cfg.current_asset_id:
|
||||
continue
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
preview_bytes = client.download_asset_preview(cfg.current_asset_id)
|
||||
faces = client.get_asset_faces(cfg.current_asset_id)
|
||||
except httpx.HTTPError as e:
|
||||
logger.warning("Could not fetch manage-overlay face info for asset %s: %s", cfg.current_asset_id, e)
|
||||
continue
|
||||
if not any((face.get("person") or {}).get("name") for face in faces):
|
||||
continue # no Immich-identified person on this widget's current photo -- nothing to label
|
||||
|
||||
from ..face_labels import compute_face_labels
|
||||
|
||||
region = grid.cell_to_pixels(frame.orientation, panel_w, panel_h, (widget.x, widget.y, widget.w, widget.h))
|
||||
face_labels.extend(compute_face_labels(preview_bytes, faces, cfg.display_mode, frame.orientation,
|
||||
region=region))
|
||||
|
||||
if face_labels:
|
||||
content["face_labels"] = face_labels
|
||||
return content
|
||||
|
||||
|
||||
def calendar_sources_for_frame(db: Session, frame: Frame) -> list[tuple[str, str]]:
|
||||
"""Every user linked to this frame with BOTH a calendar URL set AND
|
||||
explicit per-frame opt-in (UserFrame.calendar_included) -- the exact
|
||||
set calendar_feed.merge_events needs. [(display_name-or-username,
|
||||
ics_url), ...]."""
|
||||
def calendar_sources_for_widget(db: Session, widget: Widget) -> list[calendar_feed.CalendarSource]:
|
||||
"""Every calendar included on this calendar widget (FrameCalendar.
|
||||
included) -- the exact set calendar_feed.merge_events needs. A
|
||||
calendar_key of "ics" resolves against its owner's calendar_ics_url;
|
||||
"caldav:<href>" resolves against the href itself, authenticated with
|
||||
the owner's CalDAV account credentials (see caldav_client.py)."""
|
||||
rows = db.execute(
|
||||
select(User)
|
||||
.join(UserFrame, UserFrame.user_id == User.id)
|
||||
.where(UserFrame.frame_id == frame.id, UserFrame.calendar_included == True, # noqa: E712
|
||||
User.calendar_ics_url != "")
|
||||
).scalars().all()
|
||||
return [(u.display_name or u.username, u.calendar_ics_url) for u in rows]
|
||||
select(FrameCalendar, User)
|
||||
.join(User, User.id == FrameCalendar.user_id)
|
||||
.where(FrameCalendar.widget_id == widget.id, FrameCalendar.included == True) # noqa: E712
|
||||
).all()
|
||||
sources = []
|
||||
for fc, u in rows:
|
||||
name = u.display_name or u.username
|
||||
if fc.calendar_key == "ics":
|
||||
if u.calendar_ics_url:
|
||||
sources.append(calendar_feed.CalendarSource(
|
||||
name, "ics", u.calendar_ics_url, color_index=fc.color_index
|
||||
))
|
||||
elif fc.calendar_key.startswith("caldav:") and u.calendar_caldav_username:
|
||||
href = fc.calendar_key[len("caldav:"):]
|
||||
sources.append(calendar_feed.CalendarSource(
|
||||
name, "caldav", href, u.calendar_caldav_username, u.calendar_caldav_password,
|
||||
color_index=fc.color_index,
|
||||
))
|
||||
return sources
|
||||
|
||||
|
||||
def get_or_refresh_calendar_events(db: Session, frame: Frame) -> tuple[list[dict], str]:
|
||||
def get_or_refresh_calendar_events_for_widget(db: Session, frame: Frame, widget: Widget) -> tuple[list[dict], str]:
|
||||
"""Frame-level throttled merge-fetch (calendar_feed.CHECK_INTERVAL_S)
|
||||
-- same shape as the Gitea release-check throttle in api_frames.py's
|
||||
api_firmware_check. One shared cache for the whole merged result
|
||||
(every included user's events together), not per-user -- ICS feeds
|
||||
are small and this refetches at most every ~20 minutes regardless of
|
||||
how many are included, so per-user cache columns would add
|
||||
bookkeeping for a marginal benefit."""
|
||||
api_firmware_check -- reading/writing CalendarWidgetConfig (see
|
||||
app/widgets/calendar.py, which this backs). One shared cache for the
|
||||
whole merged result (every included user's events together), not
|
||||
per-user -- ICS feeds are small and this refetches at most every ~20
|
||||
minutes regardless of how many are included, so per-user cache
|
||||
columns would add bookkeeping for a marginal benefit."""
|
||||
cfg = db.get(CalendarWidgetConfig, widget.id)
|
||||
now = time.time()
|
||||
if frame.calendar_cached_events is not None and now - frame.calendar_checked_at < calendar_feed.CHECK_INTERVAL_S:
|
||||
return frame.calendar_cached_events, frame.calendar_fetch_summary
|
||||
if cfg.cached_events is not None and now - cfg.checked_at < calendar_feed.CHECK_INTERVAL_S:
|
||||
return cfg.cached_events, cfg.fetch_summary
|
||||
|
||||
sources = calendar_sources_for_frame(db, frame)
|
||||
sources = calendar_sources_for_widget(db, widget)
|
||||
today = quiet_hours.local_date(frame)
|
||||
events, summary = calendar_feed.merge_events(
|
||||
sources,
|
||||
today - timedelta(days=calendar_feed.EXPAND_WINDOW_PAST_DAYS),
|
||||
today + timedelta(days=calendar_feed.EXPAND_WINDOW_FUTURE_DAYS),
|
||||
)
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
locked.calendar_cached_events = events
|
||||
locked.calendar_fetch_summary = summary
|
||||
locked.calendar_checked_at = now
|
||||
with widget_locked(db, frame.id, widget.id) as (_, _, locked_cfg):
|
||||
locked_cfg.cached_events = events
|
||||
locked_cfg.fetch_summary = summary
|
||||
locked_cfg.checked_at = now
|
||||
return events, summary
|
||||
|
||||
|
||||
def get_or_refresh_weather_for_widget(db: Session, frame: Frame, widget: Widget) -> list[dict]:
|
||||
"""Throttled per-city forecast cache (weather.CHECK_INTERVAL_S, much
|
||||
longer than calendar_feed's -- weather doesn't need to be that
|
||||
fresh), reading/writing CalendarWidgetConfig (see
|
||||
app/widgets/calendar.py). [] if weather's off or no cities are
|
||||
configured. A city whose refetch fails keeps its last-known days
|
||||
rather than going blank for one bad cycle -- calendar_render.py
|
||||
would otherwise show a real city as having no forecast at all just
|
||||
because one refresh hit a network hiccup."""
|
||||
cfg = db.get(CalendarWidgetConfig, widget.id)
|
||||
if not cfg.weather_enabled or not cfg.weather_cities:
|
||||
return []
|
||||
now = time.time()
|
||||
if cfg.weather_cached is not None and now - cfg.weather_checked_at < weather.CHECK_INTERVAL_S:
|
||||
return cfg.weather_cached
|
||||
|
||||
previous_days = {c["label"]: c.get("days", {}) for c in (cfg.weather_cached or [])}
|
||||
result = []
|
||||
for city in cfg.weather_cities:
|
||||
try:
|
||||
days = weather.fetch_daily_forecast(city["latitude"], city["longitude"], cfg.weather_units)
|
||||
except weather.WeatherFetchError as e:
|
||||
logger.warning("Could not refresh weather for %s: %s", city["label"], e)
|
||||
days = previous_days.get(city["label"], {})
|
||||
result.append({"label": city["label"], "days": days})
|
||||
|
||||
with widget_locked(db, frame.id, widget.id) as (_, _, locked_cfg):
|
||||
locked_cfg.weather_cached = result
|
||||
locked_cfg.weather_checked_at = now
|
||||
return result
|
||||
|
||||
|
||||
HOURLY_FETCH_HOURS = 48 # 2 days -- comfortably covers every hourly_interval_hours option (3/4/6/12) at any widget width
|
||||
|
||||
|
||||
def get_or_refresh_weather_widget_data(db: Session, frame: Frame, widget: Widget, force: bool = False):
|
||||
"""Throttled fetch cache (weather.CHECK_INTERVAL_S) for the standalone
|
||||
weather widget (see app/widgets/weather.py) -- reads/writes
|
||||
WeatherWidgetConfig. What gets fetched depends on cfg.mode: current/
|
||||
hourly/daily need a single configured location (city_latitude/
|
||||
city_longitude); multi_city needs cfg.cities. None if not configured
|
||||
yet, so render() falls back to a placeholder -- same convention as
|
||||
get_or_refresh_whiteboard_for_widget. force=True (the "Refresh now"
|
||||
button) bypasses the throttle entirely.
|
||||
|
||||
A single-location mode's fetch failure keeps the last-known cached
|
||||
value (same reasoning as get_or_refresh_whiteboard_for_widget); a
|
||||
multi_city fetch fails per-city (like get_or_refresh_weather_for_
|
||||
widget's calendar-strip counterpart) so one broken city doesn't blank
|
||||
the others."""
|
||||
cfg = db.get(WeatherWidgetConfig, widget.id)
|
||||
if cfg.mode == "multi_city":
|
||||
if not cfg.cities:
|
||||
return None
|
||||
elif cfg.city_latitude is None or cfg.city_longitude is None:
|
||||
return None
|
||||
|
||||
now = time.time()
|
||||
if not force and cfg.cached is not None and now - cfg.checked_at < weather.CHECK_INTERVAL_S:
|
||||
return cfg.cached
|
||||
|
||||
if cfg.mode == "multi_city":
|
||||
previous = {c["label"]: c for c in (cfg.cached or [])}
|
||||
result = []
|
||||
for city in cfg.cities:
|
||||
try:
|
||||
today = weather.fetch_daily(cfg.provider, city["latitude"], city["longitude"], cfg.units, 1)
|
||||
d = next(iter(today.values())) if today else previous.get(city["label"], {})
|
||||
except weather.WeatherFetchError as e:
|
||||
logger.warning("Could not refresh weather for %s: %s", city["label"], e)
|
||||
d = previous.get(city["label"], {})
|
||||
result.append({
|
||||
"label": city["label"], "high": d.get("high"), "low": d.get("low"),
|
||||
"category": d.get("category", "cloudy"),
|
||||
})
|
||||
else:
|
||||
try:
|
||||
if cfg.mode == "current":
|
||||
result = weather.fetch_current(cfg.provider, cfg.city_latitude, cfg.city_longitude, cfg.units)
|
||||
elif cfg.mode == "hourly":
|
||||
result = weather.fetch_hourly(cfg.provider, cfg.city_latitude, cfg.city_longitude, cfg.units,
|
||||
hours=HOURLY_FETCH_HOURS)
|
||||
else: # "daily"
|
||||
result = weather.fetch_daily(cfg.provider, cfg.city_latitude, cfg.city_longitude, cfg.units,
|
||||
cfg.daily_days)
|
||||
except weather.WeatherFetchError as e:
|
||||
logger.warning("Could not refresh weather widget %d: %s", widget.id, e)
|
||||
return cfg.cached
|
||||
|
||||
with widget_locked(db, frame.id, widget.id) as (_, _, locked_cfg):
|
||||
locked_cfg.cached = result
|
||||
locked_cfg.checked_at = now
|
||||
return result
|
||||
|
||||
|
||||
TASKS_COMPLETED_WINDOW_HOURS = 24 # how far back TaskWidgetConfig.show_completed looks
|
||||
|
||||
|
||||
def task_sources_for_widget(db: Session, widget: Widget) -> list[caldav_client.TaskSource]:
|
||||
"""Every task list included on this tasks widget (FrameTaskList.
|
||||
included) -- the exact set caldav_client.merge_tasks needs. CalDAV
|
||||
only (calendar_key is always "caldav:<href>" -- no "ics" variant, a
|
||||
plain ICS subscription has no VTODO collection), resolved against
|
||||
the owning user's CalDAV account credentials."""
|
||||
rows = db.execute(
|
||||
select(FrameTaskList, User)
|
||||
.join(User, User.id == FrameTaskList.user_id)
|
||||
.where(FrameTaskList.widget_id == widget.id, FrameTaskList.included == True) # noqa: E712
|
||||
).all()
|
||||
sources = []
|
||||
for ftl, u in rows:
|
||||
if not ftl.calendar_key.startswith("caldav:") or not u.calendar_caldav_username:
|
||||
continue
|
||||
href = ftl.calendar_key[len("caldav:"):]
|
||||
sources.append(caldav_client.TaskSource(
|
||||
u.display_name or u.username, href, u.calendar_caldav_username, u.calendar_caldav_password,
|
||||
color_index=ftl.color_index,
|
||||
))
|
||||
return sources
|
||||
|
||||
|
||||
def get_or_refresh_tasks_for_widget(db: Session, frame: Frame, widget: Widget) -> list[dict]:
|
||||
"""Throttled multi-list merge-fetch cache (calendar_feed.
|
||||
CHECK_INTERVAL_S, same cadence as event merging), reading/writing
|
||||
TaskWidgetConfig (see app/widgets/tasks.py). [] if no list is
|
||||
included yet. Same posture as get_or_refresh_calendar_events_for_
|
||||
widget (which this otherwise mirrors closely), not weather's own
|
||||
per-city stale-cache fallback: a broken list just contributes
|
||||
nothing to this cycle's merge (logged in fetch_summary) rather than
|
||||
silently keeping its last-known tasks around."""
|
||||
cfg = db.get(TaskWidgetConfig, widget.id)
|
||||
now = time.time()
|
||||
if cfg.cached is not None and now - cfg.checked_at < calendar_feed.CHECK_INTERVAL_S:
|
||||
return cfg.cached
|
||||
|
||||
sources = task_sources_for_widget(db, widget)
|
||||
if not sources:
|
||||
return []
|
||||
completed_since = datetime.now(timezone.utc) - timedelta(hours=TASKS_COMPLETED_WINDOW_HOURS) \
|
||||
if cfg.show_completed else None
|
||||
tasks, summary = caldav_client.merge_tasks(sources, completed_since=completed_since)
|
||||
if summary:
|
||||
logger.warning("Could not refresh tasks for widget %d: %s", widget.id, summary)
|
||||
|
||||
with widget_locked(db, frame.id, widget.id) as (_, _, locked_cfg):
|
||||
locked_cfg.cached = tasks
|
||||
locked_cfg.checked_at = now
|
||||
return tasks
|
||||
|
||||
|
||||
def webdav_creds_for(user: User) -> tuple[str, str] | None:
|
||||
"""(username, password) for `user`'s WebDAV access -- their own
|
||||
dedicated webdav_username/password, or (if they opted in)
|
||||
calendar_caldav_username/password reused from their CalDAV account
|
||||
(see models.py's User docstring on webdav_reuse_caldav_creds). None
|
||||
if neither is actually set up."""
|
||||
if user.webdav_reuse_caldav_creds:
|
||||
if user.calendar_caldav_username:
|
||||
return user.calendar_caldav_username, user.calendar_caldav_password
|
||||
return None
|
||||
if user.webdav_username:
|
||||
return user.webdav_username, user.webdav_password
|
||||
return None
|
||||
|
||||
|
||||
def get_or_refresh_whiteboard_for_widget(
|
||||
db: Session, frame: Frame, widget: Widget, force: bool = False
|
||||
) -> bytes | None:
|
||||
"""Throttled render cache (calendar_feed.CHECK_INTERVAL_S), reading/
|
||||
writing WhiteboardWidgetConfig (see app/widgets/whiteboard.py) --
|
||||
None if no whiteboard source is configured, credentials are missing
|
||||
(e.g. the owning user unlinked their WebDAV/CalDAV account), or the
|
||||
most recent fetch/render failed and nothing was ever cached yet. A
|
||||
failure after a previous success keeps showing the last good render
|
||||
rather than going blank for one bad refresh cycle, same reasoning as
|
||||
get_or_refresh_weather_for_widget/get_or_refresh_tasks_for_widget.
|
||||
force=True (the web UI's "Refresh now" button) skips the throttle
|
||||
entirely -- unlike a device's normal wake, a person clicking a
|
||||
button means do it right now, not eventually once the cache goes
|
||||
stale."""
|
||||
cfg = db.get(WhiteboardWidgetConfig, widget.id)
|
||||
if not cfg.url or not cfg.user_id:
|
||||
return None
|
||||
now = time.time()
|
||||
if not force and cfg.cached_image is not None and now - cfg.checked_at < calendar_feed.CHECK_INTERVAL_S:
|
||||
return cfg.cached_image
|
||||
|
||||
user = db.get(User, cfg.user_id)
|
||||
creds = webdav_creds_for(user) if user else None
|
||||
if creds is None:
|
||||
return cfg.cached_image
|
||||
|
||||
try:
|
||||
png = whiteboard.fetch_and_render(cfg.url, creds[0], creds[1])
|
||||
except whiteboard.WhiteboardRenderError as e:
|
||||
logger.warning("Could not refresh whiteboard for widget %d: %s", widget.id, e)
|
||||
return cfg.cached_image
|
||||
|
||||
with widget_locked(db, frame.id, widget.id) as (_, _, locked_cfg):
|
||||
locked_cfg.cached_image = png
|
||||
locked_cfg.checked_at = now
|
||||
return png
|
||||
|
||||
+264
-179
@@ -14,32 +14,28 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, RedirectResponse, Response
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import calendar_render, mail, photo_queue, quiet_hours
|
||||
from .. import grid, mail, quiet_hours
|
||||
from ..auth import get_server_settings, require_device
|
||||
from ..db import frame_locked, get_db
|
||||
from ..db import SessionLocal, frame_locked, get_db
|
||||
from ..firmware import firmware_path
|
||||
from ..image_pipeline import render_placeholder
|
||||
from ..models import BatteryLog, Frame
|
||||
from ..global_actions import GLOBAL_ACTIONS
|
||||
from ..image_pipeline import draw_widget_border, logical_render_size, render_panel, render_placeholder, resolve_border_color
|
||||
from ..models import BatteryLog, Frame, FrameButtonAction, Widget
|
||||
from ..widgets import WIDGET_TYPES
|
||||
from .common import (
|
||||
BATTERY_HISTORY_MAX,
|
||||
BATTERY_LOG_MAX,
|
||||
RECHARGE_JUMP_PCT,
|
||||
RECHARGE_LOOKBACK,
|
||||
build_manage_content,
|
||||
get_or_refresh_calendar_events,
|
||||
immich_client_for,
|
||||
immich_creds,
|
||||
list_assets,
|
||||
render_asset,
|
||||
require_configured,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -47,12 +43,13 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _setup_placeholder(frame: Frame, request: Request, manage: dict | None = None) -> bytes:
|
||||
"""What an unclaimed or not-yet-configured frame displays instead of a
|
||||
photo -- instructions with a QR, rendered at 200 so the device treats
|
||||
it as a perfectly normal image and never error-loops. The URLs are
|
||||
built from the request's own base URL: whatever address the device
|
||||
reached us at is by definition an address that works on this
|
||||
def _setup_placeholder(frame: Frame, request: Request, manage: dict | None = None,
|
||||
as_png: bool = False, capture_snapshot: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""What an unclaimed or widget-less frame displays instead of real
|
||||
content -- instructions with a QR, rendered at 200 so the device
|
||||
treats it as a perfectly normal image and never error-loops. The
|
||||
URLs are built from the request's own base URL: whatever address the
|
||||
device reached us at is by definition an address that works on this
|
||||
network."""
|
||||
base = str(request.base_url).rstrip("/")
|
||||
if frame.owner_user_id is None and frame.device_id:
|
||||
@@ -63,6 +60,8 @@ def _setup_placeholder(frame: Frame, request: Request, manage: dict | None = Non
|
||||
orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb,
|
||||
manage=manage,
|
||||
as_png=as_png,
|
||||
capture_snapshot=capture_snapshot,
|
||||
)
|
||||
if frame.owner_user_id is None:
|
||||
return render_placeholder(
|
||||
@@ -70,137 +69,186 @@ def _setup_placeholder(frame: Frame, request: Request, manage: dict | None = Non
|
||||
orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb,
|
||||
manage=manage,
|
||||
as_png=as_png,
|
||||
capture_snapshot=capture_snapshot,
|
||||
)
|
||||
return render_placeholder(
|
||||
["Almost there!", "Pick an album for this frame:", base],
|
||||
["Almost there!", "Add a widget for this frame at", base],
|
||||
qr_url=base,
|
||||
orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb,
|
||||
manage=manage,
|
||||
as_png=as_png,
|
||||
capture_snapshot=capture_snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _frame_configured(frame: Frame) -> bool:
|
||||
url, key = immich_creds(frame)
|
||||
return bool(url and key and frame.album_id)
|
||||
|
||||
|
||||
# --- photos mode ---
|
||||
|
||||
def _render_photos_mode(db: Session, frame: Frame, request: Request, manage: dict | None,
|
||||
is_normal_wake: bool) -> bytes:
|
||||
if not _frame_configured(frame):
|
||||
return _setup_placeholder(frame, request, manage=manage)
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
photo_queue.get_current(locked, assets, in_quiet_hours=quiet_hours.in_quiet_hours(locked))
|
||||
asset_id = locked.current_asset_id
|
||||
|
||||
return render_asset(client, frame, asset_id, manage=manage)
|
||||
|
||||
|
||||
def _advance_photos_mode(db: Session, frame: Frame, manage: dict | None) -> bytes:
|
||||
require_configured(frame)
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
photo_queue.advance_forced(locked, assets)
|
||||
asset_id = locked.current_asset_id
|
||||
|
||||
return render_asset(client, frame, asset_id, manage=manage)
|
||||
|
||||
|
||||
def _back_photos_mode(db: Session, frame: Frame, manage: dict | None) -> bytes:
|
||||
require_configured(frame)
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
photo_queue.back_forced(locked, assets)
|
||||
asset_id = locked.current_asset_id
|
||||
|
||||
return render_asset(client, frame, asset_id, manage=manage)
|
||||
|
||||
|
||||
# --- calendar mode ---
|
||||
|
||||
def _render_calendar_mode(db: Session, frame: Frame, request: Request, manage: dict | None,
|
||||
is_normal_wake: bool) -> bytes:
|
||||
from .common import calendar_sources_for_frame
|
||||
|
||||
if not calendar_sources_for_frame(db, frame):
|
||||
return render_placeholder(
|
||||
["This frame's calendar isn't set up yet",
|
||||
"Add a calendar in Settings, then include it on",
|
||||
"this frame's Configuration -> Calendar card."],
|
||||
orientation=frame.orientation, palette_rgb=frame.palette_rgb, manage=manage,
|
||||
def _render_one_widget(frame_id: int, widget_id: int, orientation: str, panel_w: int, panel_h: int,
|
||||
cell: tuple[int, int, int, int], is_normal_wake: bool,
|
||||
) -> tuple[tuple[int, int, int, int], object] | None:
|
||||
"""Renders exactly one widget on its own DB session, so several of
|
||||
these can run concurrently in a thread pool -- see app/db.py's
|
||||
module docstring: handlers already run multi-threaded (sync
|
||||
handlers in FastAPI's threadpool, one process), and frame_locked/
|
||||
widget_locked's per-frame threading.Lock is what makes that safe,
|
||||
not anything about which Session object is in play. A SQLAlchemy
|
||||
Session itself is never safe to share across threads, so each
|
||||
concurrent render gets a fresh one rather than reusing the
|
||||
request's. Most of a widget's render time is spent waiting on an
|
||||
external call (Immich, a weather provider, CalDAV) with the DB
|
||||
untouched, which is exactly the time this buys back."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
frame = db.get(Frame, frame_id)
|
||||
widget = db.get(Widget, widget_id)
|
||||
if widget is None:
|
||||
return None # deleted between the listing query and this fetch -- skip it, not a 500
|
||||
module = WIDGET_TYPES.get(widget.widget_type)
|
||||
if module is None:
|
||||
return None # unrecognized widget_type -- shouldn't happen, skip defensively rather than 500
|
||||
px, py, pw, ph = grid.cell_to_pixels(orientation, panel_w, panel_h, cell)
|
||||
img = module.render(db, frame, widget, pw, ph, is_normal_wake=is_normal_wake)
|
||||
draw_widget_border(
|
||||
img, widget.border_style, widget.border_thickness,
|
||||
resolve_border_color(widget.border_color_index, frame.palette_rgb),
|
||||
)
|
||||
return (px, py, pw, ph), img
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
if is_normal_wake and locked.calendar_browse_offset != 0:
|
||||
locked.calendar_browse_offset = 0
|
||||
browse_offset = locked.calendar_browse_offset
|
||||
view = locked.calendar_view if locked.calendar_view in calendar_render.CALENDAR_VIEWS else "agenda"
|
||||
inlay_wanted = locked.calendar_photo_inlay and view == "agenda"
|
||||
|
||||
events, summary = get_or_refresh_calendar_events(db, frame)
|
||||
def _render_widgets(db: Session, frame: Frame, manage: dict | None, is_normal_wake: bool,
|
||||
as_png: bool = False, capture_snapshot: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""The widget-system compositor: renders every widget on this frame
|
||||
into its own region (see app/grid.py for grid-cell -> pixel math),
|
||||
draws that widget's own optional border directly onto its region
|
||||
(models.Widget.border_style, a shared per-widget property no
|
||||
widget_type module needs to know about) and hands the results to
|
||||
image_pipeline.render_panel for the single shared paste/enhance/
|
||||
overlay/quantize/pack pass. Replaces the old per-mode RENDERERS
|
||||
dict -- a frame can now show several widgets at once instead of
|
||||
exactly one mode owning the whole panel.
|
||||
|
||||
photo_inlay = None
|
||||
if inlay_wanted and _frame_configured(frame):
|
||||
try:
|
||||
client = immich_client_for(frame)
|
||||
assets = list_assets(client, frame)
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
photo_queue.get_current(locked, assets, in_quiet_hours=quiet_hours.in_quiet_hours(locked))
|
||||
asset_id = locked.current_asset_id
|
||||
if asset_id:
|
||||
jpeg_bytes = client.download_asset_preview(asset_id)
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
photo_inlay = Image.open(io.BytesIO(jpeg_bytes))
|
||||
except HTTPException:
|
||||
pass # inlay is nice-to-have -- an Immich hiccup shouldn't blank the whole agenda
|
||||
|
||||
return calendar_render.render_calendar(
|
||||
events, view=view, browse_offset=browse_offset, orientation=frame.orientation,
|
||||
palette_rgb=frame.palette_rgb, timezone=frame.timezone,
|
||||
photo_inlay=photo_inlay, fetch_summary=summary, manage=manage,
|
||||
Widgets render concurrently (_render_one_widget, each on its own DB
|
||||
session) rather than one at a time -- a layout with several
|
||||
network-backed widgets (photos, weather, calendar) previously paid
|
||||
their fetch latency serially, which could push a single /frame/*
|
||||
response past the firmware's fixed HTTP timeout and show a
|
||||
misleading "server failed" status screen even though the server
|
||||
was simply still working. Futures are submitted in sort_order and
|
||||
collected in that same order (not completion order) -- overlapping
|
||||
widgets must still paint in the original z-order."""
|
||||
all_widgets = db.scalars(
|
||||
select(Widget).where(Widget.frame_id == frame.id).order_by(Widget.sort_order)
|
||||
).all()
|
||||
panel_w, panel_h = logical_render_size(frame.orientation)
|
||||
regions = []
|
||||
if all_widgets:
|
||||
with ThreadPoolExecutor(max_workers=min(len(all_widgets), 8)) as pool:
|
||||
futures = [
|
||||
pool.submit(
|
||||
_render_one_widget, frame.id, widget.id, frame.orientation, panel_w, panel_h,
|
||||
(widget.x, widget.y, widget.w, widget.h), is_normal_wake,
|
||||
)
|
||||
for widget in all_widgets
|
||||
]
|
||||
for future in futures:
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
regions.append(result)
|
||||
return render_panel(
|
||||
regions, orientation=frame.orientation, palette_rgb=frame.palette_rgb,
|
||||
color_boost=frame.color_boost, contrast_boost=frame.contrast_boost,
|
||||
dither_strength=frame.dither_strength, manage=manage, as_png=as_png,
|
||||
capture_snapshot=capture_snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _advance_calendar_mode(db: Session, frame: Frame, manage: dict | None) -> bytes:
|
||||
"""NEXT in calendar mode: moves the displayed period forward one step
|
||||
(day for agenda, week for week view, month for month view) from
|
||||
wherever it currently is -- not from "today" -- so repeated presses
|
||||
walk further forward. See Frame.calendar_browse_offset."""
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
locked.calendar_browse_offset += 1
|
||||
return _render_calendar_mode(db, frame, request=None, manage=manage, is_normal_wake=False)
|
||||
def _render_frame_content(db: Session, frame: Frame, request: Request | None, manage: dict | None,
|
||||
is_normal_wake: bool, as_png: bool = False,
|
||||
capture_snapshot: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""The top-level "what does this frame show right now" entry point.
|
||||
An unclaimed frame or one with no widgets yet gets the setup
|
||||
placeholder (needs `request` for its QR URLs -- only available on the
|
||||
normal-wake path where a real request is on hand, never on an
|
||||
advance/back button press); otherwise every widget on it gets
|
||||
composited via _render_widgets. Individual widgets that are
|
||||
themselves unconfigured show their own small placeholder within
|
||||
their own region (see app/widgets/*.py) rather than blanking the
|
||||
whole panel -- a partially-set-up multi-widget frame still shows
|
||||
whatever IS configured."""
|
||||
has_widgets = frame.owner_user_id is not None and (
|
||||
db.scalars(select(Widget.id).where(Widget.frame_id == frame.id).limit(1)).first() is not None
|
||||
)
|
||||
if not has_widgets:
|
||||
if request is None:
|
||||
return render_placeholder(
|
||||
["Almost there!"], orientation=frame.orientation, palette_rgb=frame.palette_rgb,
|
||||
manage=manage, as_png=as_png, capture_snapshot=capture_snapshot,
|
||||
)
|
||||
return _setup_placeholder(frame, request, manage=manage, as_png=as_png, capture_snapshot=capture_snapshot)
|
||||
|
||||
return _render_widgets(db, frame, manage, is_normal_wake, as_png=as_png, capture_snapshot=capture_snapshot)
|
||||
|
||||
|
||||
def _back_calendar_mode(db: Session, frame: Frame, manage: dict | None) -> bytes:
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
locked.calendar_browse_offset -= 1
|
||||
return _render_calendar_mode(db, frame, request=None, manage=manage, is_normal_wake=False)
|
||||
def render_frame_preview_png(db: Session, frame: Frame, request: Request) -> bytes:
|
||||
"""The web UI's live "how it's displaying" thumbnail (see
|
||||
routers/api_frames.py's /preview endpoint) -- same compositor
|
||||
/frame/image uses, just handed back as a small upright PNG instead of
|
||||
packed native-panel bytes. Exported from here (rather than
|
||||
duplicated) since this module already owns the full widget-
|
||||
compositing pipeline; nothing about the /frame/* paths themselves
|
||||
changes."""
|
||||
return _render_frame_content(db, frame, request, manage=None, is_normal_wake=True, as_png=True)
|
||||
|
||||
|
||||
RENDERERS = {
|
||||
"photos": _render_photos_mode,
|
||||
"calendar": _render_calendar_mode,
|
||||
}
|
||||
ADVANCE_RENDERERS = {
|
||||
"photos": _advance_photos_mode,
|
||||
"calendar": _advance_calendar_mode,
|
||||
}
|
||||
BACK_RENDERERS = {
|
||||
"photos": _back_photos_mode,
|
||||
"calendar": _back_calendar_mode,
|
||||
}
|
||||
def _run_button_actions(db: Session, frame: Frame, button: str) -> None:
|
||||
"""Executes every (widget, action) binding assigned to this physical
|
||||
button, in order -- see models.FrameButtonAction and the button-
|
||||
assignment UI (a later phase). Each action runs to completion (its
|
||||
own widget_locked span) before the next one starts -- never nested,
|
||||
since db.widget_locked's underlying lock isn't reentrant (see its own
|
||||
docstring) -- a button assigned several actions would deadlock
|
||||
instantly if this looped any other way. One action failing
|
||||
unexpectedly doesn't block the others, or the eventual re-render,
|
||||
from happening -- the user pressed a physical button and expects
|
||||
*something* to happen even if one of several assigned widgets is
|
||||
having a bad moment."""
|
||||
actions = db.scalars(
|
||||
select(FrameButtonAction)
|
||||
.where(FrameButtonAction.frame_id == frame.id, FrameButtonAction.button == button)
|
||||
.order_by(FrameButtonAction.sort_order)
|
||||
).all()
|
||||
for action_row in actions:
|
||||
widget = db.get(Widget, action_row.widget_id)
|
||||
if widget is None:
|
||||
continue
|
||||
module = WIDGET_TYPES.get(widget.widget_type)
|
||||
action_fn = module.ACTIONS.get(action_row.action) if module else None
|
||||
if action_fn is None:
|
||||
continue
|
||||
try:
|
||||
action_fn(db, frame, widget)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Button action %r failed for widget %d (frame %d)", action_row.action, widget.id, frame.id
|
||||
)
|
||||
|
||||
|
||||
def _run_global_action(db: Session, frame: Frame, button: str) -> None:
|
||||
"""The hold-triggered counterpart to _run_button_actions -- runs
|
||||
whichever entry in app/global_actions.GLOBAL_ACTIONS this button's
|
||||
Frame.next_hold_action/back_hold_action points to, if any (unset or
|
||||
unrecognized is a silent no-op, same posture as an unbound short-
|
||||
press button). See routers/device.py's frame_global_next/back."""
|
||||
action = frame.next_hold_action if button == "next" else frame.back_hold_action
|
||||
action_fn = GLOBAL_ACTIONS.get(action) if action else None
|
||||
if action_fn is None:
|
||||
return
|
||||
try:
|
||||
action_fn(db, frame)
|
||||
except Exception:
|
||||
logger.exception("Global hold action %r failed for frame %d", action, frame.id)
|
||||
|
||||
|
||||
@router.get("/frame/config")
|
||||
@@ -228,12 +276,16 @@ def frame_config(request: Request, frame: Frame = Depends(require_device), db: S
|
||||
response = {
|
||||
"refresh_interval_s": quiet_hours.effective_refresh_interval_s(locked),
|
||||
"firmware_version": locked.firmware_available_version or None,
|
||||
# Additive key -- old firmware's hand-rolled parser only ever
|
||||
# extracts the keys it knows about, so this is safe for
|
||||
# firmware that predates hold-for-global-action (see
|
||||
# firmware/main/next_button.c, app/global_actions.py).
|
||||
"hold_duration_ms": locked.hold_duration_ms,
|
||||
}
|
||||
# Per-frame token push: only once the device has introduced itself
|
||||
# by id (so the response to pure-legacy firmware stays byte-
|
||||
# compatible with its 256-byte parse buffer), and only until the
|
||||
# device has authenticated with the token once (device_token_ack).
|
||||
if locked.device_id is not None and not locked.device_token_ack:
|
||||
# Per-frame token push: only until the device has authenticated
|
||||
# with it once (device_token_ack) -- no reason to keep sending it
|
||||
# on every wake once the device has it.
|
||||
if not locked.device_token_ack:
|
||||
response["device_token"] = locked.device_token
|
||||
return response
|
||||
|
||||
@@ -242,46 +294,103 @@ def _manage_flag(request: Request) -> bool:
|
||||
return request.query_params.get("manage") == "1"
|
||||
|
||||
|
||||
def _record_last_displayed(db: Session, frame: Frame, png_snapshot: bytes) -> None:
|
||||
"""Persists exactly what a device-facing render just sent (upright
|
||||
PNG, manage overlay included if present -- whatever's actually on the
|
||||
panel) as this frame's "now displaying" snapshot, the frozen half of
|
||||
the web UI's header preview pair (see api_frames.py's /now-displaying
|
||||
endpoint and its always-live "up next" counterpart, /preview)."""
|
||||
with frame_locked(db, frame.id) as locked:
|
||||
locked.last_displayed_image = png_snapshot
|
||||
locked.last_displayed_at = time.time()
|
||||
|
||||
|
||||
@router.get("/frame/image")
|
||||
def frame_image(
|
||||
request: Request, frame: Frame = Depends(require_device), db: Session = Depends(get_db)
|
||||
):
|
||||
"""Returns the frame's current image. For photos mode: idempotent --
|
||||
only actually advances to the next photo once refresh_interval_s has
|
||||
elapsed since the current one was set (see app/photo_queue.py) --
|
||||
safe to call as often as the device wants, including after an
|
||||
unplanned reboot, without skipping ahead in the album. An unclaimed/
|
||||
unconfigured frame gets a rendered instruction placeholder (200, not
|
||||
an error) so a fresh device never error-loops.
|
||||
"""Returns the frame's current image -- every widget on the frame
|
||||
composited into one panel (see _render_widgets). Each widget's own
|
||||
render is idempotent in whatever way makes sense for its type (e.g.
|
||||
a photo widget only actually advances once its own refresh interval
|
||||
has elapsed, see app/photo_queue.py) -- safe to call as often as the
|
||||
device wants, including after an unplanned reboot, without skipping
|
||||
ahead. An unclaimed frame or one with no widgets yet gets a rendered
|
||||
instruction placeholder (200, not an error) so a fresh device never
|
||||
error-loops.
|
||||
|
||||
?manage=1 (the manage button) composites the manage overlay onto
|
||||
whatever this would have returned anyway -- see build_manage_content.
|
||||
For calendar mode, this is also the "normal wake" that resets
|
||||
calendar_browse_offset back to 0 (see _render_calendar_mode)."""
|
||||
renderer = RENDERERS.get(frame.mode, _render_photos_mode)
|
||||
This is also the "normal wake" that resets any calendar widget's
|
||||
browse position back to today (see app/widgets/calendar.py).
|
||||
|
||||
Also records what's returned as this frame's "now displaying"
|
||||
snapshot (see _record_last_displayed) -- every other device-facing
|
||||
render endpoint below does the same."""
|
||||
manage = build_manage_content(db, frame, request) if _manage_flag(request) else None
|
||||
content = renderer(db, frame, request, manage, True)
|
||||
content, snapshot = _render_frame_content(db, frame, request, manage, is_normal_wake=True, capture_snapshot=True)
|
||||
_record_last_displayed(db, frame, snapshot)
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/frame/advance")
|
||||
def frame_advance(request: Request, frame: Frame = Depends(require_device), db: Session = Depends(get_db)):
|
||||
"""Forces an immediate move forward -- the next photo in photos mode,
|
||||
or the next day/week/month in calendar mode -- ignoring
|
||||
refresh_interval_s. Used by the device's next-photo button."""
|
||||
handler = ADVANCE_RENDERERS.get(frame.mode, _advance_photos_mode)
|
||||
"""Forces an immediate move forward on whatever widget(s) the NEXT
|
||||
button is assigned to (see models.FrameButtonAction) -- e.g. the next
|
||||
photo for a photo widget, or the next day/week/month for a calendar
|
||||
widget -- then re-renders and returns the whole panel. Used by the
|
||||
device's next-photo button."""
|
||||
_run_button_actions(db, frame, "next")
|
||||
manage = build_manage_content(db, frame, request) if _manage_flag(request) else None
|
||||
return Response(content=handler(db, frame, manage), media_type="application/octet-stream")
|
||||
content, snapshot = _render_frame_content(
|
||||
db, frame, request=None, manage=manage, is_normal_wake=False, capture_snapshot=True
|
||||
)
|
||||
_record_last_displayed(db, frame, snapshot)
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/frame/back")
|
||||
def frame_back(request: Request, frame: Frame = Depends(require_device), db: Session = Depends(get_db)):
|
||||
"""The mirror of /frame/advance -- back a photo in photos mode, back
|
||||
a period in calendar mode. A no-op (still 200, unchanged) if there's
|
||||
nothing to go back to. Used by the device's back-photo button."""
|
||||
handler = BACK_RENDERERS.get(frame.mode, _back_photos_mode)
|
||||
"""The mirror of /frame/advance, for whatever widget(s) the BACK
|
||||
button is assigned to. A no-op (still 200, unchanged) for any widget
|
||||
with nothing to go back to. Used by the device's back-photo button."""
|
||||
_run_button_actions(db, frame, "back")
|
||||
manage = build_manage_content(db, frame, request) if _manage_flag(request) else None
|
||||
return Response(content=handler(db, frame, manage), media_type="application/octet-stream")
|
||||
content, snapshot = _render_frame_content(
|
||||
db, frame, request=None, manage=manage, is_normal_wake=False, capture_snapshot=True
|
||||
)
|
||||
_record_last_displayed(db, frame, snapshot)
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/frame/global-next")
|
||||
def frame_global_next(request: Request, frame: Frame = Depends(require_device), db: Session = Depends(get_db)):
|
||||
"""Fires when the device detects NEXT held past Frame.hold_duration_ms
|
||||
instead of a short press -- runs Frame.next_hold_action (see
|
||||
app/global_actions.GLOBAL_ACTIONS) if one is set, then re-renders and
|
||||
returns the whole panel same as /frame/advance. A separate endpoint
|
||||
from /frame/advance (not a query flag on it) so the frozen short-press
|
||||
path's behavior never has to account for the long-press case -- see
|
||||
firmware/main/next_button.c for the short/long split."""
|
||||
_run_global_action(db, frame, "next")
|
||||
manage = build_manage_content(db, frame, request) if _manage_flag(request) else None
|
||||
content, snapshot = _render_frame_content(
|
||||
db, frame, request=None, manage=manage, is_normal_wake=False, capture_snapshot=True
|
||||
)
|
||||
_record_last_displayed(db, frame, snapshot)
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/frame/global-back")
|
||||
def frame_global_back(request: Request, frame: Frame = Depends(require_device), db: Session = Depends(get_db)):
|
||||
"""The mirror of /frame/global-next, for a held BACK button."""
|
||||
_run_global_action(db, frame, "back")
|
||||
manage = build_manage_content(db, frame, request) if _manage_flag(request) else None
|
||||
content, snapshot = _render_frame_content(
|
||||
db, frame, request=None, manage=manage, is_normal_wake=False, capture_snapshot=True
|
||||
)
|
||||
_record_last_displayed(db, frame, snapshot)
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
class BatteryReport(BaseModel):
|
||||
@@ -373,27 +482,3 @@ def frame_firmware(frame: Frame = Depends(require_device)):
|
||||
if not path.exists():
|
||||
raise HTTPException(404, "No firmware uploaded")
|
||||
return FileResponse(path, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.get("/frame/share/{asset_id}")
|
||||
def frame_share(asset_id: str, frame: Frame = Depends(require_device)):
|
||||
"""Creates a 30-minute public Immich share link for asset_id and
|
||||
redirects to it -- what the manage overlay's bottom-left QR code
|
||||
points to. The link is created lazily, when this actually gets hit
|
||||
(i.e. when someone scans it), not when the manage button was
|
||||
pressed, so the 30-minute window starts when it's actually used.
|
||||
Also scoped to the photo currently showing or queued on THIS frame --
|
||||
not any arbitrary Immich asset id -- as a second layer even a leaked
|
||||
token wouldn't bypass."""
|
||||
require_configured(frame)
|
||||
|
||||
if asset_id != frame.current_asset_id and asset_id not in frame.queue:
|
||||
raise HTTPException(404, "That photo isn't currently showing or queued on this frame")
|
||||
|
||||
client = immich_client_for(frame)
|
||||
try:
|
||||
share_url = client.create_share_link(asset_id, expires_in_s=1800)
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(502, f"Could not create share link: {e}") from e
|
||||
|
||||
return RedirectResponse(share_url)
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
"""The per-frame HTML pages: Photos (/frames/{id}), Configuration, and
|
||||
Stats tabs, all inside the sidebar app shell. Data loading happens
|
||||
client-side against /api/frames/{id}/... (routers/api_frames.py); these
|
||||
routes just authorize and render the scaffold."""
|
||||
"""The per-frame HTML pages: Layout (/frames/{id}, the widget placement
|
||||
canvas), Configuration, and Stats, all inside the sidebar app shell.
|
||||
Each widget's own settings (album, calendar view/inclusion, whiteboard
|
||||
source, etc.) no longer have their own tab/page -- they're a dialog
|
||||
opened from a gear icon on the widget's box in the Layout canvas (see
|
||||
static/frame_layout.js), whose content this module also serves (the
|
||||
/widgets/{widget_id}/dialog route) as a small HTML fragment, not a full
|
||||
page. Data loading otherwise happens client-side against
|
||||
/api/frames/{id}/... (routers/api_frames.py, routers/api_widgets.py);
|
||||
these routes just authorize and render the scaffold."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,18 +17,44 @@ from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import panel_style, theme_tokens, weather
|
||||
from ..auth import can_view_frame, current_user
|
||||
from ..calendar_render import CALENDAR_VIEW_LABELS
|
||||
from ..db import get_db
|
||||
from ..global_actions import GLOBAL_ACTION_LABELS
|
||||
from ..image_pipeline import (
|
||||
BORDER_STYLES,
|
||||
BORDER_STYLE_LABELS,
|
||||
CALIBRATED_SPECTRA6_RGB,
|
||||
DEFAULT_PALETTE_RGB,
|
||||
DISPLAY_MODE_LABELS,
|
||||
MAX_BORDER_THICKNESS,
|
||||
MIN_BORDER_THICKNESS,
|
||||
PALETTE_LABELS,
|
||||
STATIC_DISPLAY_MODES,
|
||||
palette_to_hex,
|
||||
)
|
||||
from ..models import Frame, User, UserFrame
|
||||
from ..models import (
|
||||
BatteryWidgetConfig,
|
||||
CalendarWidgetConfig,
|
||||
Frame,
|
||||
FrameButtonAction,
|
||||
FrameCalendar,
|
||||
FrameTaskList,
|
||||
PhotoWidgetConfig,
|
||||
StaticWidgetConfig,
|
||||
TaskWidgetConfig,
|
||||
TextWidgetConfig,
|
||||
User,
|
||||
UserFrame,
|
||||
WeatherWidgetConfig,
|
||||
WhiteboardWidgetConfig,
|
||||
Widget,
|
||||
)
|
||||
from ..quiet_hours import ALL_TIMEZONES
|
||||
from .common import shell_context
|
||||
from ..widgets import WIDGET_TYPES
|
||||
from ..widgets import text as text_widget
|
||||
from .common import shell_context, widget_of_type
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
@@ -41,43 +73,266 @@ def _frame_page(request: Request, db: Session, frame_id: int, template: str, tab
|
||||
|
||||
|
||||
@router.get("/frames/{frame_id}", response_class=HTMLResponse)
|
||||
def frame_photos_page(frame_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
return _frame_page(request, db, frame_id, "frame_photos.html", "photos")
|
||||
|
||||
|
||||
def _calendar_users_for_frame(db: Session, frame_id: int) -> list[dict]:
|
||||
"""Every user linked to this frame, their calendar opt-in state, and
|
||||
whether they even have a calendar URL set -- what the Configuration
|
||||
tab's "Included calendars" list needs. Whether a given row is *this*
|
||||
viewer's own (and therefore editable) is decided in the template,
|
||||
using the `user` shell_context already provides."""
|
||||
rows = db.execute(
|
||||
select(User, UserFrame.calendar_included)
|
||||
.join(UserFrame, UserFrame.user_id == User.id)
|
||||
.where(UserFrame.frame_id == frame_id)
|
||||
.order_by(User.username)
|
||||
).all()
|
||||
return [
|
||||
{"user_id": u.id, "display_name": u.display_name or u.username,
|
||||
"has_url": bool(u.calendar_ics_url), "included": included}
|
||||
for u, included in rows
|
||||
]
|
||||
def frame_layout_page(frame_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
return _frame_page(request, db, frame_id, "frame_layout.html", "layout")
|
||||
|
||||
|
||||
@router.get("/frames/{frame_id}/config", response_class=HTMLResponse)
|
||||
def frame_config_page(frame_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
frame = db.get(Frame, frame_id)
|
||||
photo_widget_id = None
|
||||
if frame is not None:
|
||||
photo_widget = widget_of_type(db, frame, "photos")
|
||||
if photo_widget is not None:
|
||||
photo_widget_id = photo_widget.id
|
||||
return _frame_page(
|
||||
request, db, frame_id, "frame_config.html", "config",
|
||||
timezones=ALL_TIMEZONES,
|
||||
palette_labels=PALETTE_LABELS,
|
||||
default_palette_rgb=DEFAULT_PALETTE_RGB,
|
||||
calibrated_spectra6_hex=palette_to_hex(CALIBRATED_SPECTRA6_RGB),
|
||||
palette_to_hex=palette_to_hex,
|
||||
display_mode_labels=DISPLAY_MODE_LABELS,
|
||||
calendar_views=CALENDAR_VIEW_LABELS,
|
||||
calendar_users=_calendar_users_for_frame(db, frame_id),
|
||||
photo_widget_id=photo_widget_id,
|
||||
global_action_labels=GLOBAL_ACTION_LABELS,
|
||||
themes=theme_tokens.THEMES,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/frames/{frame_id}/stats", response_class=HTMLResponse)
|
||||
def frame_stats_page(frame_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
return _frame_page(request, db, frame_id, "frame_stats.html", "stats")
|
||||
return _frame_page(request, db, frame_id, "frame_stats.html", "stats")
|
||||
|
||||
|
||||
# --- Per-widget config dialog content -------------------------------------
|
||||
|
||||
def _user_available_calendars(user: User) -> list[dict]:
|
||||
"""This user's full set of calendars available to add to any widget:
|
||||
the single ICS subscription (if set) plus every CalDAV calendar last
|
||||
discovered from Settings' "Discover calendars" button. Doesn't hit
|
||||
the network -- reads the cached list a user refreshes themselves."""
|
||||
calendars = []
|
||||
if user.calendar_ics_url:
|
||||
calendars.append({"key": "ics", "label": "My calendar (ICS)"})
|
||||
for c in (user.calendar_caldav_calendars or []):
|
||||
calendars.append({"key": f"caldav:{c['href']}", "label": c.get("display_name") or "Calendar"})
|
||||
return calendars
|
||||
|
||||
|
||||
def _calendar_users_for_widget(db: Session, frame_id: int, widget_id: int, viewer_id: int | None) -> list[dict]:
|
||||
"""Per-linked-user calendar list for the calendar dialog's "Included
|
||||
calendars" section. The viewer's own row lists EVERY calendar they
|
||||
have available, each with a full add/remove toggle; every other
|
||||
linked user's row lists ONLY the calendars they've already included
|
||||
(mute-only for the viewer -- see api_widgets.py's
|
||||
api_widget_calendar_select: only a calendar's owner may turn it on,
|
||||
but anyone linked to the frame may turn one off)."""
|
||||
users = db.execute(
|
||||
select(User).join(UserFrame, UserFrame.user_id == User.id)
|
||||
.where(UserFrame.frame_id == frame_id).order_by(User.username)
|
||||
).scalars().all()
|
||||
included_by_user: dict[int, list[FrameCalendar]] = {}
|
||||
for fc in db.execute(select(FrameCalendar).where(FrameCalendar.widget_id == widget_id)).scalars().all():
|
||||
included_by_user.setdefault(fc.user_id, []).append(fc)
|
||||
|
||||
result = []
|
||||
for u in users:
|
||||
is_self = u.id == viewer_id
|
||||
if is_self:
|
||||
own_rows = {fc.calendar_key: fc for fc in included_by_user.get(u.id, [])}
|
||||
calendars = [
|
||||
{**c, "included": own_rows[c["key"]].included if c["key"] in own_rows else False,
|
||||
"color_index": own_rows[c["key"]].color_index if c["key"] in own_rows else None}
|
||||
for c in _user_available_calendars(u)
|
||||
]
|
||||
else:
|
||||
calendars = [
|
||||
{"key": fc.calendar_key, "label": fc.calendar_label, "included": True}
|
||||
for fc in included_by_user.get(u.id, []) if fc.included
|
||||
]
|
||||
result.append({
|
||||
"user_id": u.id, "display_name": u.display_name or u.username,
|
||||
"is_self": is_self, "calendars": calendars,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _task_users_for_widget(db: Session, frame_id: int, widget_id: int, viewer_id: int | None) -> list[dict]:
|
||||
"""Per-linked-user task-list list for the tasks dialog's "Included
|
||||
task lists" section -- same shape as _calendar_users_for_widget,
|
||||
restricted to CalDAV calendars only (no "ics" option: a plain ICS
|
||||
subscription has no VTODO collection to speak of, see
|
||||
caldav_client.fetch_tasks)."""
|
||||
users = db.execute(
|
||||
select(User).join(UserFrame, UserFrame.user_id == User.id)
|
||||
.where(UserFrame.frame_id == frame_id).order_by(User.username)
|
||||
).scalars().all()
|
||||
included_by_user: dict[int, list[FrameTaskList]] = {}
|
||||
for ftl in db.execute(select(FrameTaskList).where(FrameTaskList.widget_id == widget_id)).scalars().all():
|
||||
included_by_user.setdefault(ftl.user_id, []).append(ftl)
|
||||
|
||||
result = []
|
||||
for u in users:
|
||||
is_self = u.id == viewer_id
|
||||
available = [c for c in _user_available_calendars(u) if c["key"].startswith("caldav:")]
|
||||
if is_self:
|
||||
own_rows = {ftl.calendar_key: ftl for ftl in included_by_user.get(u.id, [])}
|
||||
task_lists = [
|
||||
{**c, "included": own_rows[c["key"]].included if c["key"] in own_rows else False,
|
||||
"color_index": own_rows[c["key"]].color_index if c["key"] in own_rows else None}
|
||||
for c in available
|
||||
]
|
||||
else:
|
||||
task_lists = [
|
||||
{"key": ftl.calendar_key, "label": ftl.calendar_label, "included": True}
|
||||
for ftl in included_by_user.get(u.id, []) if ftl.included
|
||||
]
|
||||
result.append({
|
||||
"user_id": u.id, "display_name": u.display_name or u.username,
|
||||
"is_self": is_self, "task_lists": task_lists,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _whiteboard_source_info(db: Session, whiteboard_cfg: WhiteboardWidgetConfig) -> dict | None:
|
||||
"""Whose account this widget currently fetches with, for showing
|
||||
"using <name>'s account" to everyone linked, not just whoever set
|
||||
it. None if no source is configured."""
|
||||
if not whiteboard_cfg.user_id or not whiteboard_cfg.url:
|
||||
return None
|
||||
user = db.get(User, whiteboard_cfg.user_id)
|
||||
if user is None:
|
||||
return None
|
||||
return {"user_id": user.id, "display_name": user.display_name or user.username, "url": whiteboard_cfg.url}
|
||||
|
||||
|
||||
WEEK_START_LABELS = {0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday",
|
||||
4: "Friday", 5: "Saturday", 6: "Sunday"}
|
||||
|
||||
|
||||
@router.get("/frames/{frame_id}/widgets/{widget_id}/dialog", response_class=HTMLResponse)
|
||||
def widget_dialog(frame_id: int, widget_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
"""The gear-icon dialog's content, dispatched by widget_type -- a
|
||||
small HTML fragment (no app_base shell/tabs), fetched and injected
|
||||
into a <dialog> by static/frame_layout.js. Not itself a page a user
|
||||
would navigate to directly."""
|
||||
user = current_user(request, db)
|
||||
if user is None:
|
||||
raise HTTPException(401, "Not logged in")
|
||||
frame = db.get(Frame, frame_id)
|
||||
if frame is None or not can_view_frame(db, user, frame):
|
||||
raise HTTPException(404, "No such frame")
|
||||
widget = db.get(Widget, widget_id)
|
||||
if widget is None or widget.frame_id != frame.id:
|
||||
raise HTTPException(404, "No such widget")
|
||||
|
||||
# Every dialog includes the shared "Border" card (_widget_border_fields.html,
|
||||
# models.Widget.border_style/border_thickness/border_color_index) --
|
||||
# a Widget-level property, not a per-type config field, so this
|
||||
# context is the same regardless of widget_type.
|
||||
border_ctx = {
|
||||
"border_styles": BORDER_STYLES,
|
||||
"border_style_labels": BORDER_STYLE_LABELS,
|
||||
"border_color_labels": PALETTE_LABELS,
|
||||
"default_palette_rgb": DEFAULT_PALETTE_RGB,
|
||||
"palette_to_hex": palette_to_hex,
|
||||
"min_border_thickness": MIN_BORDER_THICKNESS,
|
||||
"max_border_thickness": MAX_BORDER_THICKNESS,
|
||||
}
|
||||
|
||||
# Every dialog also includes the shared "Button actions" card
|
||||
# (_widget_button_fields.html) if this widget type supports any --
|
||||
# empty for tasks/static/text/battery, so the card renders nothing
|
||||
# for those. Bindings, not the type's own config, so this lives in
|
||||
# FrameButtonAction (see models.py), same reasoning as border_ctx
|
||||
# above for why it's a separate card/endpoint from the type-specific
|
||||
# form.
|
||||
bindings = {
|
||||
row.button: row.action
|
||||
for row in db.scalars(
|
||||
select(FrameButtonAction).where(FrameButtonAction.widget_id == widget.id)
|
||||
)
|
||||
}
|
||||
button_ctx = {
|
||||
"button_action_labels": WIDGET_TYPES[widget.widget_type].ACTION_LABELS,
|
||||
"next_button_action": bindings.get("next", ""),
|
||||
"back_button_action": bindings.get("back", ""),
|
||||
}
|
||||
|
||||
# The shared "Text size" card (_widget_font_scale_fields.html,
|
||||
# models.Widget.font_scale) -- only included on the dialogs whose
|
||||
# on-panel content is mostly body text (calendar/tasks; the other
|
||||
# types are either image-only or, for text, already have their own
|
||||
# richer per-widget font_size control -- see TextWidgetConfig).
|
||||
font_scale_labels = {1.0: "Normal", 1.25: "Large", 1.5: "X-Large"}
|
||||
font_scale_ctx = {
|
||||
"font_scale_choices": [(v, font_scale_labels[v]) for v in panel_style.FONT_SCALE_CHOICES],
|
||||
}
|
||||
|
||||
if widget.widget_type == "photos":
|
||||
photo_cfg = db.get(PhotoWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_photos.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "photo_cfg": photo_cfg,
|
||||
"display_mode_labels": DISPLAY_MODE_LABELS, **border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "calendar":
|
||||
calendar_cfg = db.get(CalendarWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_calendar.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "calendar_cfg": calendar_cfg, "user": user,
|
||||
"calendar_views": CALENDAR_VIEW_LABELS,
|
||||
"calendar_users": _calendar_users_for_widget(db, frame.id, widget.id, user.id),
|
||||
"week_start_labels": WEEK_START_LABELS,
|
||||
"calendar_color_labels": PALETTE_LABELS,
|
||||
**border_ctx, **button_ctx, **font_scale_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "tasks":
|
||||
task_cfg = db.get(TaskWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_tasks.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "task_cfg": task_cfg, "user": user,
|
||||
"task_users": _task_users_for_widget(db, frame.id, widget.id, user.id),
|
||||
"task_color_labels": PALETTE_LABELS,
|
||||
**border_ctx, **button_ctx, **font_scale_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "static":
|
||||
static_cfg = db.get(StaticWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_static.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "static_cfg": static_cfg,
|
||||
"display_mode_labels": {k: v for k, v in DISPLAY_MODE_LABELS.items() if k in STATIC_DISPLAY_MODES},
|
||||
**border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "text":
|
||||
text_cfg = db.get(TextWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_text.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "text_cfg": text_cfg,
|
||||
"text_font_families": text_widget.FONT_FAMILIES, **border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "whiteboard":
|
||||
whiteboard_cfg = db.get(WhiteboardWidgetConfig, widget.id)
|
||||
viewer_has_webdav_creds = bool(
|
||||
user.webdav_username or (user.webdav_reuse_caldav_creds and user.calendar_caldav_username)
|
||||
)
|
||||
return templates.TemplateResponse("_widget_dialog_whiteboard.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "user": user,
|
||||
"whiteboard_cfg": whiteboard_cfg,
|
||||
"whiteboard_source": _whiteboard_source_info(db, whiteboard_cfg),
|
||||
"viewer_has_webdav_creds": viewer_has_webdav_creds, **border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "weather":
|
||||
weather_cfg = db.get(WeatherWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_weather.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "weather_cfg": weather_cfg,
|
||||
"weather_provider_labels": weather.PROVIDER_LABELS, **border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
if widget.widget_type == "battery":
|
||||
battery_cfg = db.get(BatteryWidgetConfig, widget.id)
|
||||
return templates.TemplateResponse("_widget_dialog_battery.html", {
|
||||
"request": request, "frame": frame, "widget": widget, "battery_cfg": battery_cfg, **border_ctx, **button_ctx,
|
||||
})
|
||||
|
||||
raise HTTPException(400, f"Unknown widget type: {widget.widget_type}")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user