diff --git a/docs/README.md b/docs/README.md index e711f94..0f1e988 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,7 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory | | `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media///` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) | -| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | +| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`, and its picture (6R.13): `fit` (keep a slide's shape with bands / stretch) and `area_*` (px cut off each edge, set by Screens → Calibrate the picture; `signage.calibrate` to that screen while calibrating; the TV reports its window with `POST /api/signage/screen/viewport`); playlists and library slides have a shape (`orientation` + `aspect` "21:9", `shapeOf()` in `@xenia/signage`); `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) | | `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) | | `local_backend/routers/floor_plans.py`, `services/floor_live.py`, `packages/floorplan`, manager `src/pages/floor/` | The table map (6.8, D-31): `floor_plans` / `floor_items` (0035) and the tables' `plan_id`, `floor_x/y` (centre), `width`, `height`, `rotation`, `shape`. Set-up `/api/floor-plans` (`catalog.tables.manage`; `PUT /{id}/layout` saves tables + items whole) sends `floor_plans.changed`; `GET /api/floor-plans/live` (any signed-in person, the waiter app's zone rule) gives each table's state, guests (`customer_count`), waiters and time. `@xenia/floorplan`: `FloorView` (inline styles on tokens, so the waiter app can use it), `Floor` / `Item` / `TableShape`, `geometry.js` (grid snap = positions and sizes in whole cells; `@xenia/floorplan/geometry` for node tests). Dockerfiles copy its package.json | diff --git a/local_backend/migrations/versions/0045_signage_shapes.py b/local_backend/migrations/versions/0045_signage_shapes.py new file mode 100644 index 0000000..411a0e6 --- /dev/null +++ b/local_backend/migrations/versions/0045_signage_shapes.py @@ -0,0 +1,28 @@ +"""Signage slide shapes (6R.13, owner 2026-11-22): a playlist or a library slide may be built for a +custom shape ("21:9", "16:10", …) besides landscape / portrait. NULL = its orientation's 16:9 / 9:16. + +Revision ID: 0045_signage_shapes +Revises: 0044_signage_saved_slides +Create Date: 2026-11-22 10:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0045_signage_shapes' +down_revision = '0044_signage_saved_slides' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('signage_playlists') as b: + b.add_column(sa.Column('aspect', sa.String(), nullable=True)) + with op.batch_alter_table('signage_saved_slides') as b: + b.add_column(sa.Column('aspect', sa.String(), nullable=True)) + + +def downgrade() -> None: + with op.batch_alter_table('signage_saved_slides') as b: + b.drop_column('aspect') + with op.batch_alter_table('signage_playlists') as b: + b.drop_column('aspect') diff --git a/local_backend/models/signage.py b/local_backend/models/signage.py index 950c6e4..1e53481 100644 --- a/local_backend/models/signage.py +++ b/local_backend/models/signage.py @@ -23,6 +23,7 @@ class SignagePlaylist(Base): id = Column(Integer, primary_key=True, index=True) name = Column(String, nullable=False) orientation = Column(String, nullable=False, default="landscape") # landscape | portrait + aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16 transition = Column(String, nullable=False, default="fade") # the slides' default created_at = Column(UTCDateTime, default=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) @@ -91,6 +92,7 @@ class SignageSavedSlide(Base): name = Column(String, nullable=False) description = Column(String, nullable=True) orientation = Column(String, nullable=False, default="landscape") # landscape | portrait + aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16 kind = Column(String, nullable=False) # menu | image | video | text | blank duration_s = Column(Integer, nullable=False, default=10) transition = Column(String, nullable=True) diff --git a/local_backend/modules/signage/manifest.py b/local_backend/modules/signage/manifest.py index 7169930..cfc927b 100644 --- a/local_backend/modules/signage/manifest.py +++ b/local_backend/modules/signage/manifest.py @@ -31,5 +31,12 @@ MODULE = Module( ConfigField('slide', 'ref', default=None, choices_from='signage_slides'), ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), + # its picture (6R.13): a slide of another shape keeps its shape (bands) or fills the picture; + # px cut off each edge of the TV's window (set by Signage > Screens > Calibrate) + ConfigField('fit', 'enum', default='keep', choices=('keep', 'stretch'), group='picture'), + ConfigField('area_left', 'int', default=0, min=0, max=4000, group='picture'), + ConfigField('area_top', 'int', default=0, min=0, max=4000, group='picture'), + ConfigField('area_right', 'int', default=0, min=0, max=4000, group='picture'), + ConfigField('area_bottom', 'int', default=0, min=0, max=4000, group='picture'), )), ) diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index f760f70..d3b835b 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -18,11 +18,14 @@ Manager side (signage.manage): PUT /api/signage/library/{id} change it (a screen showing it is told) DELETE /api/signage/library/{id} screens that had it as their default show nothing POST /api/signage/library/{id}/duplicate a copy - GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation - PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation} + GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation, + picture area (insets), fit, the window size it reported + PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation, area_*, fit} + POST /api/signage/screens/{id}/calibrate {on} the TV outlines its picture area (6R.13) The screen (a paired device running `signage`, no sign-in): GET /api/signage/screen its playlist resolved for playing + POST /api/signage/screen/viewport {width, height, ratio} its window (for calibrating) Any change sends `signage.changed` only to the screens playing that playlist (a screen's own settings: `device.updated` plus `signage.changed` to it). A slide's content is typed per kind @@ -51,10 +54,16 @@ KEY = "signage.manage" MESSAGE = "signage.message" MAX_WIDGETS = "signage.max_widgets" # widgets a slide may hold (owner review 6: Performance; 10 recommended) MAX_WIDGETS_CAP = 50 # never more, whatever the setting +AREA_MAX = 4000 # px a screen's picture area may cut off one edge (6R.13) +AREA_KEYS = ("area_left", "area_top", "area_right", "area_bottom") +CALIBRATE_S = 15 * 60 # a calibration nobody ends stops by itself +_viewports: dict = {} # device id → {width, height, ratio} (what the TV reported; memory only) +_calibrating: dict = {} # device id → when calibration started (monotonic) HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" # #rrggbb, or #rrggbbaa (see-through, 2026-11-21) TIME = r"^([01]\d|2[0-3]):[0-5]\d$" DATE = r"^\d{4}-\d{2}-\d{2}$" Orientation = Literal["landscape", "portrait"] +ASPECT = r"^\d{1,2}:\d{1,2}$" # a custom shape "21:9" (6R.13), from 1:4 to 4:1 Transition = Literal["none", "fade", "slide", "zoom"] Font = Literal["sans", "serif", "rounded", "condensed", "display"] @@ -353,13 +362,55 @@ Kind = Literal["menu", "image", "video", "text", "blank"] # ── requests ─────────────────────────────────────────────────────────────────── -class PlaylistBody(BaseModel): +def _aspect(v): + """A custom shape "W:H" (6R.13): None / "" = none; between 1:4 and 4:1.""" + import re as _re + v = (v or "").strip() or None + if v is None: + return None + if not _re.match(ASPECT, v): + raise ValueError("a shape is written W:H, e.g. 21:9") + w, h = (int(x) for x in v.split(":")) + if not w or not h or w / h > 4 or h / w > 4: + raise ValueError("a shape between 1:4 and 4:1") + return v + + +class _Shaped(BaseModel): + aspect: Optional[str] = None # a custom shape "21:9"; None / "" = landscape / portrait + + @field_validator("aspect") + @classmethod + def _shape(cls, v): + return _aspect(v) + + +def set_shape(obj, body) -> None: + """A playlist's / library slide's shape from a body: `aspect` sets orientation too (wide or tall; + "16:9" / "9:16" are plain landscape / portrait); `orientation` alone drops a custom shape.""" + sent = body.model_fields_set + if "aspect" in sent: + a = body.aspect + if a is None: + obj.aspect = None + if body.orientation is not None: + obj.orientation = body.orientation + return + w, h = (int(x) for x in a.split(":")) + obj.orientation = "landscape" if w >= h else "portrait" + obj.aspect = None if a in ("16:9", "9:16") else a + elif body.orientation is not None: + obj.orientation = body.orientation + obj.aspect = None + + +class PlaylistBody(_Shaped): name: str = Field(min_length=1, max_length=80) orientation: Orientation = "landscape" transition: Transition = "fade" -class PlaylistUpdate(BaseModel): +class PlaylistUpdate(_Shaped): name: Optional[str] = Field(default=None, min_length=1, max_length=80) orientation: Optional[Orientation] = None transition: Optional[Transition] = None @@ -438,6 +489,12 @@ class SavedSlideBody(SlideFields): kind: Optional[Kind] = None description: Optional[str] = Field(default=None, max_length=300) orientation: Optional[Orientation] = None + aspect: Optional[str] = None # a custom shape (6R.13) + + @field_validator("aspect") + @classmethod + def _shape(cls, v): + return _aspect(v) class ScreenBody(BaseModel): @@ -445,6 +502,22 @@ class ScreenBody(BaseModel): slide_id: Optional[int] = None # … or a library slide (one or the other) orientation: Optional[Orientation] = None rotation: Optional[Literal[0, 90, 180, 270]] = None + # its picture area (6R.13): px cut off each edge of the TV's window; how a slide of another shape fits + area_left: Optional[int] = Field(default=None, ge=0, le=AREA_MAX) + area_top: Optional[int] = Field(default=None, ge=0, le=AREA_MAX) + area_right: Optional[int] = Field(default=None, ge=0, le=AREA_MAX) + area_bottom: Optional[int] = Field(default=None, ge=0, le=AREA_MAX) + fit: Optional[Literal["keep", "stretch"]] = None + + +class CalibrateBody(BaseModel): + on: bool + + +class ViewportBody(BaseModel): + width: int = Field(ge=1, le=20000) + height: int = Field(ge=1, le=20000) + ratio: float = Field(default=1, gt=0, le=10) # device pixels per CSS px # ── helpers ──────────────────────────────────────────────────────────────────── @@ -670,7 +743,7 @@ def _slide_out(s: SignageSlide) -> dict: def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict: playing = set(_screens_playing(db, p.id)) - out = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, + out = {"id": p.id, "name": p.name, "orientation": p.orientation, "aspect": p.aspect, "transition": p.transition, "slide_count": len(p.slides), "screens": [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in playing]} if slides: from services.signage_menu import resolve @@ -761,6 +834,7 @@ def list_playlists(db: Session = Depends(get_db), user=Depends(require(KEY))): @router.post("/playlists", status_code=201) def create_playlist(body: PlaylistBody, db: Session = Depends(get_db), user=Depends(require(KEY))): p = SignagePlaylist(name=body.name.strip(), orientation=body.orientation, transition=body.transition) + set_shape(p, body) db.add(p) db.commit() db.refresh(p) @@ -777,8 +851,7 @@ def update_playlist(playlist_id: int, body: PlaylistUpdate, db: Session = Depend p = _playlist(db, playlist_id) if body.name is not None: p.name = body.name.strip() - if body.orientation is not None: - p.orientation = body.orientation + set_shape(p, body) if body.transition is not None: p.transition = body.transition db.commit() @@ -804,7 +877,7 @@ def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depend @router.post("/playlists/{playlist_id}/duplicate", status_code=201) def duplicate_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): p = _playlist(db, playlist_id) - copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, transition=p.transition) + copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, aspect=p.aspect, transition=p.transition) db.add(copy) db.flush() for s in p.slides: @@ -904,7 +977,7 @@ def _saved(db, sid: int) -> SignageSavedSlide: def _saved_out(s: SignageSavedSlide, db=None) -> dict: - out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "kind": s.kind, + out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "aspect": s.aspect, "kind": s.kind, "duration_s": s.duration_s, "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled), "days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to, "content": s.content or {}} @@ -957,6 +1030,7 @@ def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depen name = _saved_name(body) s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True, video_to_end=body.kind == "video", content=_content(db, body.kind, None)) + set_shape(s, body) _apply(db, s, body) s.name = name s.description = (body.description or "").strip() or None @@ -984,8 +1058,7 @@ def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_ s.name = name if "description" in body.model_fields_set: s.description = (body.description or "").strip() or None - if body.orientation is not None: - s.orientation = body.orientation + set_shape(s, body) db.commit() db.refresh(s) _tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)) @@ -1008,7 +1081,7 @@ def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(requ @router.post("/library/{slide_id}/duplicate", status_code=201) def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): s = _saved(db, slide_id) - copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, kind=s.kind, + copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, aspect=s.aspect, kind=s.kind, duration_s=s.duration_s, transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled, days=s.days, time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to, content=json.loads(json.dumps(s.content or {}))) @@ -1039,7 +1112,30 @@ def _screen_out(db, d) -> dict: return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None, "slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None, "orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now, - "orientation_mismatch": any(o != cfg["orientation"] for o in shapes)} + "orientation_mismatch": any(o != cfg["orientation"] for o in shapes), + **_picture(d, cfg), "viewport": _viewports.get(d.id)} + + +def _area(cfg: dict) -> dict: + return {k[5:]: int(cfg.get(k) or 0) for k in AREA_KEYS} + + +def calibrating(device_id: int) -> bool: + import time + at = _calibrating.get(device_id) + if at is not None and time.monotonic() - at > CALIBRATE_S: + _calibrating.pop(device_id, None) + return False + return at is not None + + +def _picture(d, cfg: dict) -> dict: + """A screen's picture (6R.13): the insets of its area, how a slide of another shape fits, calibrating now.""" + return {"area": _area(cfg), "fit": cfg.get("fit") or "keep", "calibrating": calibrating(d.id)} + + +def _tell_calibration(d, cfg: dict) -> None: + broadcast_sync("signage.calibrate", {"on": calibrating(d.id), "area": _area(cfg)}, device_ids=[d.id]) @router.get("/screens") @@ -1064,11 +1160,36 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db cfg["playlist"] = None d.config = validate(for_app("signage"), cfg, db) db.commit() + if calibrating(d.id): + _tell_calibration(d, _screen_config(d)) # the TV moves its outline at once broadcast_sync("device.updated", {}, device_ids=[d.id]) _tell([d.id]) return _screen_out(db, d) +def _a_screen(db, device_id: int): + from models.device import Device + d = db.get(Device, device_id) + if d is None or d.app_key != "signage" or d.revoked_at is not None: + raise XeniaError("signage.not_a_screen", device_id=device_id) + return d + + +@router.post("/screens/{device_id}/calibrate") +def calibrate_screen(device_id: int, body: CalibrateBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + """Calibrating a screen's picture (6R.13): on, the TV outlines its picture area with arrows + pointing out and its size, and follows every change of the insets at once; off (the manager's + dialog closes, or after 15 min) it plays again.""" + import time + d = _a_screen(db, device_id) + if body.on: + _calibrating[d.id] = time.monotonic() + else: + _calibrating.pop(d.id, None) + _tell_calibration(d, _screen_config(d)) + return _screen_out(db, d) + + # ── the screen itself ────────────────────────────────────────────────────────── def _resolved(db, p: SignagePlaylist) -> dict: @@ -1085,7 +1206,7 @@ def _resolved(db, p: SignagePlaylist) -> dict: for w in s["content"].get("widgets") or []: if w["kind"] == "qr": w["link"] = _qr_link(w) - return {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides, + return {"id": p.id, "name": p.name, "orientation": p.orientation, "aspect": p.aspect, "transition": p.transition, "slides": slides, "media": _media_map(db, [i for s in slides for i in media_ids(s["content"])] + more)} @@ -1101,7 +1222,7 @@ def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict: if w["kind"] == "qr": w["link"] = _qr_link(w) slides = [one] if s.enabled else [] - return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides, + return {"id": slide_key(s.id), "name": s.name, "orientation": s.orientation, "aspect": s.aspect, "transition": "fade", "slides": slides, "media": _media_map(db, media_ids(one["content"]) + more)} @@ -1143,7 +1264,7 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage")) schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key} else: playlist = fallback - out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]}, + out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"], **_picture(dev, cfg)}, "playlist": playlist, "schedule": schedule, "playlists": playlists, # for the widgets (5.4c): weather None = hide it (no internet, no place, too old) "venue": _venue(db)} @@ -1151,6 +1272,14 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage")) return out +@router.post("/screen/viewport") +def screen_viewport(body: ViewportBody, dev=Depends(require_device("signage"))): + """The TV's window size (6R.13), sent when it starts and when it changes: the calibration + dialog's presets fit a shape into it. Kept in memory only (the TV sends it again after a restart).""" + _viewports[dev.id] = {"width": body.width, "height": body.height, "ratio": round(body.ratio, 3)} + return {"ok": True} + + # ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ───── def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict: diff --git a/local_backend/tests/test_signage.py b/local_backend/tests/test_signage.py index 857e2d8..0dce70f 100644 --- a/local_backend/tests/test_signage.py +++ b/local_backend/tests/test_signage.py @@ -56,7 +56,8 @@ def test_a_screen_plays_its_playlist_in_order(client, owner_h, screens, sent): assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"] assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40 - assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0} + assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0, + "area": {"left": 0, "top": 0, "right": 0, "bottom": 0}, "fit": "keep", "calibrating": False} assert len(got["version"]) == 16 diff --git a/local_backend/tests/test_signage_shapes.py b/local_backend/tests/test_signage_shapes.py new file mode 100644 index 0000000..1bd9948 --- /dev/null +++ b/local_backend/tests/test_signage_shapes.py @@ -0,0 +1,69 @@ +"""Slide shapes and a screen's picture (6R.13, owner 2026-11-22): custom shapes for playlists and +library slides, a screen's picture area (insets) and fit, calibrating told to that screen only, +the window size a screen reports.""" +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers) + + +def test_custom_shapes_for_playlists_and_library_slides(client, owner_h): + p = playlist(client, owner_h, aspect="21:9") + assert (p["orientation"], p["aspect"]) == ("landscape", "21:9") + r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "10:16"}) + assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", "10:16") + # the plain shapes are landscape / portrait; picking one drops a custom shape + r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "16:9"}) + assert (r.json()["orientation"], r.json()["aspect"]) == ("landscape", None) + client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "32:9"}) + r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"orientation": "portrait"}) + assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None) + for bad in ("21x9", "9:1", "0:5"): + assert client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": bad}).status_code == 422 + dup = client.post(f"/api/signage/playlists/{p['id']}/duplicate", headers=owner_h).json() + assert dup["orientation"] == "portrait" + s = client.post("/api/signage/library", headers=owner_h, json={"name": "Wide", "kind": "text", "aspect": "16:10"}).json() + assert (s["orientation"], s["aspect"]) == ("landscape", "16:10") + r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"aspect": None, "orientation": "portrait"}) + assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None) + + +def test_a_screens_picture_area_and_calibration(client, owner_h, screens, sent): + tv, other = screens[1], screens[2] + p = playlist(client, owner_h, aspect="21:9") + slide(client, owner_h, p["id"], "text", content={"title": "Wide"}) + client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]}) + got = client.get("/api/signage/screen", headers=tv["h"]).json() + assert got["playlist"]["aspect"] == "21:9" and got["screen"]["fit"] == "keep" and got["screen"]["calibrating"] is False + # the TV reports its window; the manager sees it + assert client.post("/api/signage/screen/viewport", headers=tv["h"], json={"width": 2560, "height": 1080, "ratio": 1}).status_code == 200 + one = next(s for s in client.get("/api/signage/screens", headers=owner_h).json() if s["id"] == tv["id"]) + assert one["viewport"] == {"width": 2560, "height": 1080, "ratio": 1.0} and one["area"] == {"left": 0, "top": 0, "right": 0, "bottom": 0} + # calibrating: only that TV hears it, with its area; every change of the insets follows at once + sent.clear() + r = client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True}) + assert r.json()["calibrating"] is True and sent == [("signage.calibrate", [tv["id"]])] + sent.clear() + r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 320, "area_right": 320, "fit": "stretch"}) + assert r.json()["area"] == {"left": 320, "top": 0, "right": 320, "bottom": 0} and r.json()["fit"] == "stretch" + assert sent[0] == ("signage.calibrate", [tv["id"]]) and ("signage.changed", [tv["id"]]) in sent + scr = client.get("/api/signage/screen", headers=tv["h"]).json()["screen"] + assert scr["area"]["left"] == 320 and scr["calibrating"] is True + sent.clear() + client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": False}) + assert sent == [("signage.calibrate", [tv["id"]])] + sent.clear() + client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_top": 5}) + assert ("signage.calibrate", [tv["id"]]) not in sent + # limits; not a screen + assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 5000}).status_code == 422 + assert err(client.post("/api/signage/screens/99999/calibrate", headers=owner_h, json={"on": True})) == "signage.not_a_screen" + # a screen can't calibrate itself or report for another + assert client.post(f"/api/signage/screens/{other['id']}/calibrate", headers=tv["h"], json={"on": True}).status_code in (401, 403) + + +def test_calibration_ends_by_itself(client, owner_h, screens, monkeypatch): + import routers.signage as sg + tv = screens[1] + client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True}) + assert sg.calibrating(tv["id"]) is True + sg._calibrating[tv["id"]] -= sg.CALIBRATE_S + 1 + assert client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]["calibrating"] is False diff --git a/manager_dashboard/src/pages/signage/AddSlideDialog.jsx b/manager_dashboard/src/pages/signage/AddSlideDialog.jsx index ea346c1..cf1773d 100644 --- a/manager_dashboard/src/pages/signage/AddSlideDialog.jsx +++ b/manager_dashboard/src/pages/signage/AddSlideDialog.jsx @@ -5,6 +5,7 @@ import { Film, ImageIcon, LayoutDashboard, LayoutList, Square, Type } from 'lucide-react' import { useTranslation } from '@xenia/i18n' import { Button, Dialog, Spinner } from '@xenia/ui' +import { shapeRatio } from '@xenia/signage' import { BLANK_WITH_WIDGETS, mediaLookup, slideFromSaved, slideFromTemplate, TEMPLATES } from './signageLogic' import SlidePreview from './SlidePreview' @@ -28,7 +29,7 @@ function Heading({ children, hint }) { export default function AddSlideDialog({ onClose, onPick, orientation = 'landscape', venue, library = null, libraryMedia = {}, title }) { const { t } = useTranslation('manager') - const tall = orientation === 'portrait' + const tall = shapeRatio(orientation) < 1 return ( {t('fees.cancel')}}> diff --git a/manager_dashboard/src/pages/signage/CalibrateDialog.jsx b/manager_dashboard/src/pages/signage/CalibrateDialog.jsx new file mode 100644 index 0000000..c6ec00e --- /dev/null +++ b/manager_dashboard/src/pages/signage/CalibrateDialog.jsx @@ -0,0 +1,113 @@ +// Calibrating a screen's picture (6R.13, owner 2026-11-22). While this is open the TV outlines its +// picture area with four arrows pointing out and shows its size; each edge moves in or out here +// pixel by pixel (or in steps of 10 / 50 px), or a preset sets the largest box of a common shape in +// the middle of the TV's window (it reports its size). Every change reaches the TV at once; closing +// ends the calibration (the TV also stops by itself after 15 min). +import { useCallback, useEffect, useRef, useState } from 'react' +import toast from 'react-hot-toast' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, NumberInput, Segmented } from '@xenia/ui' +import { pictureArea, presetInsets, shapeName } from '@xenia/signage' +import * as api from './signageApi' +import { ShapeMark } from './ShapeField' + +const EDGES = ['top', 'right', 'bottom', 'left'] +const PRESETS = ['full', '16:9', '16:10', '21:9', '32:9', '4:3', '9:16'] +const SAVE_MS = 200 + +export default function CalibrateDialog({ screen, onClose, onSaved }) { + const { t } = useTranslation('manager') + const [area, setArea] = useState(screen.area || { left: 0, top: 0, right: 0, bottom: 0 }) + const [viewport, setViewport] = useState(screen.viewport || null) + const [step, setStep] = useState(1) + const timer = useRef(null) + const latest = useRef(area) + + // on while open; off when closed + useEffect(() => { + api.calibrateScreen(screen.id, true).catch(err => toast.error(errorMessage(err, t))) + return () => { api.calibrateScreen(screen.id, false).catch(() => {}) } + }, [screen.id]) // eslint-disable-line react-hooks/exhaustive-deps + // the TV's window size (it reports it when it starts and when it changes) + useEffect(() => { + const id = setInterval(() => { + api.listScreens().then(list => setViewport(list.find(s => s.id === screen.id)?.viewport || null)).catch(() => {}) + }, 2000) + return () => clearInterval(id) + }, [screen.id]) + + const send = useCallback(() => { + const a = latest.current + api.updateScreen(screen.id, { area_left: a.left, area_top: a.top, area_right: a.right, area_bottom: a.bottom }) + .then(onSaved).catch(err => toast.error(errorMessage(err, t))) + }, [screen.id, onSaved, t]) + const change = next => { + latest.current = next + setArea(next) + clearTimeout(timer.current) + timer.current = setTimeout(send, SAVE_MS) + } + useEffect(() => () => clearTimeout(timer.current), []) + const win = viewport ? { w: viewport.width, h: viewport.height } : null + const pic = win ? pictureArea(win, area) : null + const setEdge = (edge, v) => change({ ...area, [edge]: Math.max(0, Math.min(4000, v ?? 0)) }) + + // the diagram: the TV's window and the picture inside it, to scale + const W = 320 + const H = win ? Math.round(W * win.h / win.w) : 180 + const k = win ? W / win.w : 0 + const edge = e => ( + + setEdge(e, v)} data-testid={`signage-calibrate-${e}`} /> + + ) + return ( + + + + }> +
+

+ {win ? t('signage.calibrate.window', { w: win.w, h: win.h, shape: shapeName(win.w, win.h) }) : t('signage.calibrate.waiting')} +

+
+ {t('signage.calibrate.presets')} +
+ {PRESETS.map(p => ( + + ))} +
+
+
+ {t('signage.calibrate.step')} + ({ value: n, label: `${n} px` }))} data-testid="signage-calibrate-step" /> +
+
+ {edge('top')} +
+ {edge('left')} + + {edge('right')} +
+ {edge('bottom')} +
+

+ {pic ? t('signage.calibrate.picture', { w: Math.round(pic.width), h: Math.round(pic.height), shape: shapeName(pic.width, pic.height) }) : ''} +

+ {EDGES.some(e => area[e] > 0) &&

{t('signage.calibrate.outside')}

} +
+
+ ) +} diff --git a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx index a32f4b1..c927b47 100644 --- a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx +++ b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx @@ -12,6 +12,7 @@ import toast from 'react-hot-toast' import { AlertTriangle, ArrowLeft, ArrowRight, BookmarkPlus, Copy, ImageIcon, Plus, Trash2 } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useTranslation } from '@xenia/i18n' +import { shapeOf, shapeRatio } from '@xenia/signage' import { Button, Dialog, Dropdown, Field, IconButton, Input, Spinner, Textarea, useConfirm } from '@xenia/ui' import * as api from './signageApi' import { mediaEntry, mediaLookup, misfits, moved, secondsMissing, slideBody, totalSeconds, TRANSITIONS, windowParts } from './signageLogic' @@ -19,6 +20,7 @@ import { playSeconds } from './timing' import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' import SlideEditor, { SlideBasics } from './SlideEditor' import SlidePreview from './SlidePreview' +import ShapeField from './ShapeField' import { useSlidePreview, useWidgetEditor } from './useSlideDraft' /** The preview as big as its box allows (the box is as tall as the basics beside it). */ @@ -32,7 +34,7 @@ export function FitPreview({ orientation, children }) { ro.observe(el) return () => ro.disconnect() }, []) - const ratio = orientation === 'portrait' ? 9 / 16 : 16 / 9 + const ratio = shapeRatio(orientation) const width = Math.max(0, Math.min(size.w, size.h * ratio)) return (
@@ -77,8 +79,8 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { const saved = pl?.slides.find(s => s.id === selected) const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved]) - const bad = useMemo(() => misfits(pl?.slides, media, pl?.orientation), [pl, media]) - const draftBad = useMemo(() => (draft ? misfits([draft], media, pl?.orientation)[draft.id] || [] : []), [draft, media, pl]) + const bad = useMemo(() => misfits(pl?.slides, media, shapeOf(pl)), [pl, media]) + const draftBad = useMemo(() => (draft ? misfits([draft], media, shapeOf(pl))[draft.id] || [] : []), [draft, media, pl]) if (!pl) return
const run = async (fn, done, select) => { @@ -135,7 +137,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { const made = await run(() => api.addSlide(pl.id, body), t('signage.added')) if (made) await load(made.id) } - const total = totalSeconds(pl.slides, media, s => playSeconds(s, pl.orientation)) + const shape = shapeOf(pl) + const tall = shapeRatio(shape) < 1 + const total = totalSeconds(pl.slides, media, s => playSeconds(s, shape)) const marker = i => drag && drag.at === i && drag.at !== drag.from && drag.at !== drag.from + 1 return ( @@ -146,10 +150,7 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { onBlur={() => name.trim() && name.trim() !== pl.name && savePlaylist({ name: name.trim() })} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} /> - - savePlaylist({ orientation: v })} data-testid="signage-orientation" - options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} /> - + savePlaylist({ transition: v })} options={TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} /> @@ -179,8 +180,8 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { {marker(i) && } {marker(i + 1) && i === pl.slides.length - 1 && }
-
- +
+
@@ -191,7 +192,7 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { {bad[s.id] && } - {s.kind === 'video' && s.video_to_end ? t('signage.toTheEnd') : t('signage.seconds', { count: playSeconds(s, pl.orientation) })} + {s.kind === 'video' && s.video_to_end ? t('signage.toTheEnd') : t('signage.seconds', { count: playSeconds(s, shape) })} {!s.enabled && <> · {t('signage.off')}} {parts.map(p => · {p.key === 'days' ? p.params.days.map(d => t(`signage.weekdays.${d}`)).join(' ') : t(`signage.window.${p.key}`, p.params)})} @@ -219,9 +220,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { {/* the picked slide: its basics beside its preview (one height), then what it shows */} {draft ? <>
- - - + + +
@@ -239,9 +240,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { :

{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}

} {adding !== null && ( - setAdding(null)} onPick={addSlide} orientation={pl.orientation} venue={venue} library={adding} libraryMedia={libMedia} /> + setAdding(null)} onPick={addSlide} orientation={shape} venue={venue} library={adding} libraryMedia={libMedia} /> )} - {keeping && draft && setKeeping(false)} />} + {keeping && draft && setKeeping(false)} />} {confirmDialog} {confirmDelete && ( @@ -265,7 +266,7 @@ function DropLine({ side }) { } /** Keep the slide (as it is now, saved or not) in the Slides library, with a name and a description. */ -function KeepDialog({ draft, orientation, onClose }) { +function KeepDialog({ draft, shape, onClose }) { const { t } = useTranslation('manager') const [name, setName] = useState(draft.name || '') const [description, setDescription] = useState('') @@ -273,7 +274,7 @@ function KeepDialog({ draft, orientation, onClose }) { const keep = async () => { setBusy(true) try { - await api.createSaved({ ...slideBody(draft), kind: draft.kind, name: name.trim(), description: description.trim() || null, orientation }) + await api.createSaved({ ...slideBody(draft), kind: draft.kind, name: name.trim(), description: description.trim() || null, ...shape }) toast.success(t('signage.library.kept')) onClose() } catch (err) { toast.error(errorMessage(err, t)) } diff --git a/manager_dashboard/src/pages/signage/ScreensTab.jsx b/manager_dashboard/src/pages/signage/ScreensTab.jsx index 94b9992..49f4486 100644 --- a/manager_dashboard/src/pages/signage/ScreensTab.jsx +++ b/manager_dashboard/src/pages/signage/ScreensTab.jsx @@ -2,14 +2,17 @@ // playlist, or one slide from the Slides library shown alone), its shape and how its picture is // turned, and what plays on it now. A schedule line for a screen // (Schedules) wins over its default while it matches. A warning when a playlist it may play was -// made for the other shape. New TVs are paired in Devices. +// made for the other shape. New TVs are paired in Devices. 6R.13: how slides of another shape fit +// (keep their shape with bands, or stretch) and Calibrate the picture (CalibrateDialog). import { useCallback, useEffect, useState } from 'react' import toast from 'react-hot-toast' import { Link } from 'react-router-dom' -import { AlertTriangle, CalendarClock, Monitor, Smartphone } from 'lucide-react' +import { AlertTriangle, CalendarClock, Monitor, Scan, Smartphone } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useTranslation } from '@xenia/i18n' -import { Dropdown, EmptyState, Field, Spinner } from '@xenia/ui' +import { Button, Dropdown, EmptyState, Field, Spinner } from '@xenia/ui' +import { pictureArea, shapeName } from '@xenia/signage' +import CalibrateDialog from './CalibrateDialog' import { DeviceSupport } from '../platform/DeviceSupport' import * as api from './signageApi' @@ -18,6 +21,7 @@ export default function ScreensTab() { const [screens, setScreens] = useState(null) const [playlists, setPlaylists] = useState([]) const [slides, setSlides] = useState([]) + const [calibrating, setCalibrating] = useState(null) // the screen whose picture is being calibrated const load = useCallback(async () => { try { const [s, p, l] = await Promise.all([api.listScreens(), api.listPlaylists(), api.listSaved().catch(() => ({ slides: [] }))]) @@ -25,6 +29,7 @@ export default function ScreensTab() { } catch (err) { toast.error(errorMessage(err, t)) } }, [t]) useEffect(() => { load() }, [load]) + const replace = useCallback(s => setScreens(list => list.map(x => (x.id === s.id ? s : x))), []) const save = async (id, body) => { try { const s = await api.updateScreen(id, body); setScreens(list => list.map(x => (x.id === id ? s : x))); toast.success(t('settings.saved')) } catch (err) { toast.error(errorMessage(err, t)) } @@ -61,7 +66,7 @@ export default function ScreensTab() { {s.now?.scheduled &&