riskAcceptedSet(v)} />
@@ -206,6 +206,10 @@
flex: none;
}
}
+ .rollback {
+ display: block;
+ margin-top: 0.5rem;
+ }
.accept {
display: flex;
align-items: center;
diff --git a/src/lib/modules/device/i18n.ts b/src/lib/modules/device/i18n.ts
index 02e1ea0..0275f2e 100644
--- a/src/lib/modules/device/i18n.ts
+++ b/src/lib/modules/device/i18n.ts
@@ -73,6 +73,8 @@ export const t = dict(
fileMeta: (kb: string, time: string) => `${kb} KB, modified ${time}`,
firmwareRisk:
"A firmware image can brick the watch. Battery at 50% or more, on the charger, tab open until it's done.",
+ rollbackRisk:
+ "Before installing stock or older firmware, switch to a built-in face and delete Watch 3 Pro faces with animated or data widgets from the watch: older firmware can restart in a loop on them.",
acceptRisk: "I accept the risk",
installingOnWatch: "Installing on the watch",
isOnWatch: (name: string) => `${name} is on the watch.`,
@@ -196,6 +198,8 @@ export const t = dict(
fileMeta: (kb: string, time: string) => `${kb} КБ, изменён в ${time}`,
firmwareRisk:
"Образ прошивки может превратить часы в кирпич. Заряд от 50%, часы на зарядке, вкладка открыта до конца установки.",
+ rollbackRisk:
+ "Перед установкой стоковой или более старой прошивки включите встроенный циферблат и удалите с часов циферблаты Watch 3 Pro с анимацией и виджетами данных: на старой прошивке часы могут зациклиться на перезагрузке.",
acceptRisk: "Я принимаю риск",
installingOnWatch: "Установка на часы",
isOnWatch: (name: string) => `«${name}» уже на часах.`,
@@ -317,6 +321,8 @@ export const t = dict(
fileMeta: (kb: string, time: string) => `${kb} КБ, змінено о ${time}`,
firmwareRisk:
"Образ прошивки може перетворити годинник на цеглину. Заряд від 50%, годинник на зарядці, вкладка відкрита до кінця встановлення.",
+ rollbackRisk:
+ "Перед встановленням стокової або старішої прошивки увімкніть вбудований циферблат і видаліть з годинника циферблати Watch 3 Pro з анімацією та віджетами даних: на старій прошивці годинник може циклічно перезавантажуватися.",
acceptRisk: "Я приймаю ризик",
installingOnWatch: "Встановлення на годинник",
isOnWatch: (name: string) => `«${name}» уже на годиннику.`,
@@ -438,6 +444,8 @@ export const t = dict(
fileMeta: (kb: string, time: string) => `${kb} KB, modificado a las ${time}`,
firmwareRisk:
"Una imagen de firmware puede dejar el reloj inservible. Batería al 50 % o más, en el cargador y la pestaña abierta hasta que termine.",
+ rollbackRisk:
+ "Antes de instalar firmware original o anterior, cambia a una esfera integrada y borra del reloj las esferas del Watch 3 Pro con animaciones o widgets de datos: con un firmware anterior el reloj puede reiniciarse en bucle.",
acceptRisk: "Acepto el riesgo",
installingOnWatch: "Instalando en el reloj",
isOnWatch: (name: string) => `${name} ya está en el reloj.`,
@@ -558,6 +566,8 @@ export const t = dict(
fileMeta: (kb: string, time: string) => `${kb} KB, ${time} पर बदली गई`,
firmwareRisk:
"फ़र्मवेयर इमेज घड़ी को हमेशा के लिए खराब (ब्रिक) कर सकती है। बैटरी 50% या ज़्यादा हो, घड़ी चार्जर पर हो, और काम पूरा होने तक टैब खुला रहे।",
+ rollbackRisk:
+ "स्टॉक या पुराना फ़र्मवेयर इंस्टॉल करने से पहले कोई बिल्ट-इन फ़ेस चुनें और Watch 3 Pro के एनिमेशन या डेटा विजेट वाले फ़ेस घड़ी से हटा दें: पुराने फ़र्मवेयर पर घड़ी बार-बार रीस्टार्ट हो सकती है।",
acceptRisk: "जोखिम मुझे मंज़ूर है",
installingOnWatch: "घड़ी पर इंस्टॉल हो रहा है",
isOnWatch: (name: string) => `${name} घड़ी पर है।`,
diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts
index 28a3dbd..429d6f9 100644
--- a/src/lib/modules/device/messages.ts
+++ b/src/lib/modules/device/messages.ts
@@ -1,5 +1,5 @@
// What the watch connection says — BLE statuses and the errors of ble.ts, ota-image.ts, wp2.ts
-// and the flash checks in editor/core/format/bin.ts — in the UI language.
+// and the flash checks in editor/core/format (bin.ts, compat.ts) — in the UI language.
//
// Those files keep writing English: the log (Copy log) and analytics (reasonOf) read it, and the
// protocol code shouldn't know about languages. The text is translated where it reaches a store
@@ -70,6 +70,14 @@ const en = {
bigImage: (w: string, h: string) =>
`This face has a ${w}×${h} px image, larger than factory faces use. The watch may run out of memory loading it and restart in a loop, and there is no confirmed way out of that loop yet.`,
// firmware update
+ widgetUnknown: (type: string) =>
+ `this face has a widget of type ${type}, which no supported watch knows — it can restart a watch in a loop. Nothing was sent to the watch.`,
+ widgetUnsupported: (type: string) =>
+ `this face has a Watch 3 Pro widget (type ${type}) that this watch's firmware can't draw — the watch would restart in a loop. Nothing was sent to the watch.`,
+ a8Untested:
+ "this face has A8 images (cf 14), which haven't been tested on a Watch Pro 2. Open it in the editor, use Export for Watch Pro 2 and install the exported file. Nothing was sent to the watch.",
+ etc2OverTested: (need: string, max: string) =>
+ `this face's ETC2 images need ${need} MB unpacked on a Watch Pro 2, over the ${max} MB tested there — the watch could restart in a loop. Nothing was sent to the watch.`,
noOtaChannel: "the watch didn't offer its firmware-update channel — reconnect and retry",
refusedUpdate: (d: string) => `the watch refused the update (${d})`,
refusedStart: (d: string) => `the watch refused to start (${d})`,
@@ -175,6 +183,14 @@ export const bt = dict(en, {
`${aod ? "экрану always-on" : "основному экрану"} нужно ${need} МБ памяти часов, а Watch 3 Pro вмещает ${max} МБ — часы зациклятся на перезагрузке. Используйте меньше полноэкранных изображений или уменьшите их.`,
bigImage: (w, h) =>
`В циферблате есть изображение ${w}×${h} px — больше, чем в заводских. Часам может не хватить памяти, и они зациклятся на перезагрузке, а проверенного способа выйти из этого цикла пока нет.`,
+ widgetUnknown: (type) =>
+ `в этом циферблате виджет типа ${type}, его не знают ни одни поддерживаемые часы — от него часы могут зациклиться на перезагрузке. На часы ничего не отправлено.`,
+ widgetUnsupported: (type) =>
+ `в этом циферблате виджет Watch 3 Pro (тип ${type}), который прошивка этих часов не умеет рисовать — часы зациклятся на перезагрузке. На часы ничего не отправлено.`,
+ a8Untested:
+ "в этом циферблате изображения A8 (cf 14), их работа на Watch Pro 2 не проверена. Откройте его в редакторе, выберите «Экспорт для Watch Pro 2» и установите полученный файл. На часы ничего не отправлено.",
+ etc2OverTested: (need, max) =>
+ `изображениям ETC2 этого циферблата на Watch Pro 2 нужно ${need} МБ после распаковки, а проверено только до ${max} МБ — часы могут зациклиться на перезагрузке. На часы ничего не отправлено.`,
noOtaChannel: "часы не открыли канал обновления прошивки — переподключитесь и повторите",
refusedUpdate: (d) => `часы отклонили обновление (${d})`,
refusedStart: (d) => `часы отказались начать (${d})`,
@@ -276,6 +292,14 @@ export const bt = dict(en, {
`${aod ? "екрану always-on" : "основному екрану"} потрібно ${need} МБ пам'яті годинника, а Watch 3 Pro вміщує ${max} МБ — годинник циклічно перезавантажуватиметься. Використайте менше повноекранних зображень або зменште їх.`,
bigImage: (w, h) =>
`У циферблаті є зображення ${w}×${h} px — більше, ніж у заводських. Годиннику може забракнути пам'яті, і він циклічно перезавантажуватиметься, а перевіреного способу вийти з цього циклу поки немає.`,
+ widgetUnknown: (type) =>
+ `у цьому циферблаті віджет типу ${type}, його не знає жоден підтримуваний годинник — через нього годинник може циклічно перезавантажуватися. На годинник нічого не надіслано.`,
+ widgetUnsupported: (type) =>
+ `у цьому циферблаті віджет Watch 3 Pro (тип ${type}), який прошивка цього годинника не вміє малювати — годинник циклічно перезавантажуватиметься. На годинник нічого не надіслано.`,
+ a8Untested:
+ "у цьому циферблаті зображення A8 (cf 14), їхню роботу на Watch Pro 2 не перевірено. Відкрийте його в редакторі, виберіть «Експорт для Watch Pro 2» і встановіть отриманий файл. На годинник нічого не надіслано.",
+ etc2OverTested: (need, max) =>
+ `зображенням ETC2 цього циферблата на Watch Pro 2 потрібно ${need} МБ після розпакування, а перевірено лише до ${max} МБ — годинник може циклічно перезавантажуватися. На годинник нічого не надіслано.`,
noOtaChannel: "годинник не відкрив канал оновлення прошивки — під'єднайтеся знову й повторіть",
refusedUpdate: (d) => `годинник відхилив оновлення (${d})`,
refusedStart: (d) => `годинник відмовився почати (${d})`,
@@ -377,6 +401,14 @@ export const bt = dict(en, {
`la pantalla ${aod ? "siempre activa" : "principal"} necesita ${need} MB de memoria del reloj, más de los ${max} MB que caben en un Watch 3 Pro — se reiniciaría en bucle. Usa menos imágenes a pantalla completa o hazlas más pequeñas.`,
bigImage: (w, h) =>
`Esta esfera tiene una imagen de ${w}×${h} px, mayor que las de las esferas de fábrica. El reloj puede quedarse sin memoria al cargarla y reiniciarse en bucle, y aún no hay una forma confirmada de salir de ese bucle.`,
+ widgetUnknown: (type) =>
+ `esta esfera tiene un widget de tipo ${type} que ningún reloj compatible conoce — puede dejar el reloj reiniciándose en bucle. No se envió nada al reloj.`,
+ widgetUnsupported: (type) =>
+ `esta esfera tiene un widget del Watch 3 Pro (tipo ${type}) que el firmware de este reloj no sabe dibujar — el reloj se reiniciaría en bucle. No se envió nada al reloj.`,
+ a8Untested:
+ "esta esfera tiene imágenes A8 (cf 14), que no se han probado en un Watch Pro 2. Ábrela en el editor, usa «Exportar para Watch Pro 2» e instala el archivo exportado. No se envió nada al reloj.",
+ etc2OverTested: (need, max) =>
+ `las imágenes ETC2 de esta esfera necesitan ${need} MB descomprimidas en un Watch Pro 2, más de los ${max} MB probados — el reloj podría reiniciarse en bucle. No se envió nada al reloj.`,
noOtaChannel:
"el reloj no ofreció su canal de actualización de firmware — reconecta y reintenta",
refusedUpdate: (d) => `el reloj rechazó la actualización (${d})`,
@@ -480,6 +512,14 @@ export const bt = dict(en, {
`${aod ? "ऑलवेज़-ऑन" : "मुख्य"} स्क्रीन को घड़ी की ${need} MB मेमोरी चाहिए, जबकि Watch 3 Pro में ${max} MB ही आती है — घड़ी बार-बार रीस्टार्ट होगी। कम या छोटी फ़ुल-स्क्रीन इमेज इस्तेमाल करें।`,
bigImage: (w, h) =>
`इस फ़ेस में ${w}×${h} px की इमेज है, जो फ़ैक्टरी फ़ेस से बड़ी है। घड़ी की मेमोरी खत्म हो सकती है और वह बार-बार रीस्टार्ट हो सकती है, और इस लूप से निकलने का कोई पक्का तरीका अभी नहीं है।`,
+ widgetUnknown: (type) =>
+ `इस फ़ेस में टाइप ${type} का विजेट है, जिसे कोई समर्थित घड़ी नहीं पहचानती — इससे घड़ी बार-बार रीस्टार्ट हो सकती है। घड़ी पर कुछ नहीं भेजा गया।`,
+ widgetUnsupported: (type) =>
+ `इस फ़ेस में Watch 3 Pro का विजेट (टाइप ${type}) है, जिसे इस घड़ी का फ़र्मवेयर नहीं दिखा सकता — घड़ी बार-बार रीस्टार्ट होती रहेगी। घड़ी पर कुछ नहीं भेजा गया।`,
+ a8Untested:
+ "इस फ़ेस में A8 इमेज (cf 14) हैं, जिन्हें Watch Pro 2 पर जाँचा नहीं गया है। इसे एडिटर में खोलें, “Watch Pro 2 के लिए एक्सपोर्ट” चुनें और एक्सपोर्ट की गई फ़ाइल इंस्टॉल करें। घड़ी पर कुछ नहीं भेजा गया।",
+ etc2OverTested: (need, max) =>
+ `इस फ़ेस की ETC2 इमेज को Watch Pro 2 पर अनपैक होकर ${need} MB चाहिए, जो वहाँ जाँची गई ${max} MB सीमा से ज़्यादा है — घड़ी बार-बार रीस्टार्ट हो सकती है। घड़ी पर कुछ नहीं भेजा गया।`,
noOtaChannel: "घड़ी ने फ़र्मवेयर अपडेट चैनल नहीं खोला — फिर से कनेक्ट करके कोशिश करें",
refusedUpdate: (d) => `घड़ी ने अपडेट अस्वीकार किया (${d})`,
refusedStart: (d) => `घड़ी ने शुरू करने से मना किया (${d})`,
@@ -589,6 +629,13 @@ const RULES: Rule[] = [
/^the (.+?) screen needs ([\d.]+) MB of the watch's memory, over the ([\d.]+) MB/,
(w, m) => w.screenOverBudget(m[1] === "always-on", m[2], m[3]),
],
+ [/^this face has a widget of type (\d+), /, (w, m) => w.widgetUnknown(m[1])],
+ [/^this face has a Watch 3 Pro widget \(type (\d+)\)/, (w, m) => w.widgetUnsupported(m[1])],
+ lit("a8Untested"),
+ [
+ /^this face's ETC2 images need ([\d.]+) MB unpacked on a Watch Pro 2, over the ([\d.]+) MB/,
+ (w, m) => w.etc2OverTested(m[1], m[2]),
+ ],
lit("noOtaChannel"),
[/^the watch refused the update \((.+)\)$/, (w, m) => w.refusedUpdate(m[1])],
[/^the watch refused to start \((.+)\)$/, (w, m) => w.refusedStart(m[1])],
diff --git a/src/lib/modules/device/model/ble.model.ts b/src/lib/modules/device/model/ble.model.ts
index 3c5723a..f93762a 100644
--- a/src/lib/modules/device/model/ble.model.ts
+++ b/src/lib/modules/device/model/ble.model.ts
@@ -14,6 +14,7 @@ import type { Wp2State } from "../lib/wp2";
import { rememberDial, unclaimDial } from "../lib/catalog-names";
import {
assertFlashable,
+ assertWatchCompat,
fitForWatchOffThread,
flashWarning,
} from "$lib/modules/editor/core/format";
@@ -127,6 +128,7 @@ const flashFx = createEffect(async ({ bin: file, preview, key, slot, confirmed }
const { bin, compressed } = await fitForWatchOffThread(file, device);
assertFlashable(bin, device);
+ await assertWatchCompat(bin, device, async () => (await watch!.readWp2())?.stub.version ?? null);
const warning = confirmed ? null : flashWarning(bin);
if (warning) throw new NeedsConfirmError(warning);
diff --git a/src/lib/modules/editor/components/SimPanel.svelte b/src/lib/modules/editor/components/SimPanel.svelte
index 21e9a69..4818ea3 100644
--- a/src/lib/modules/editor/components/SimPanel.svelte
+++ b/src/lib/modules/editor/components/SimPanel.svelte
@@ -1,6 +1,7 @@
+{#if proc}
+
+ {#if proc.type === PANELS && proc.panel >= 1 && proc.panel <= 4}
+
+ {$t.panel}
+ ({ value: String(n), label: $t.panels[n] }))}
+ onChange={(v) => panelSet({ id: layer.id, panel: Number(v) })}
+ />
+
+ {:else if proc.type === PANELS && proc.panel === 0}
+
{$t.weatherPanel}
+ {/if}
+
+ {proc.type === RINGS ? $t.ringsWidget : $t.procWidget(proc.type)}
+
+
+{/if}
{#if meta}
@@ -733,20 +757,31 @@
- {#if showMem && screenMem}
-
- {$t.memory(mb(screenMem.bytes), mb(SCREEN_BUDGET))}{screenMem.fit === "compressed"
- ? ` — ${$t.memoryCompressed}`
- : screenMem.fit === "too-heavy"
- ? ` — ${$t.memoryTooHeavy}`
- : ""}
-
- {/if}
+
+ {#if $support}
+
+ {$t.support[$support]}
+
+ {/if}
+ {#if showMem && screenMem}
+
+ {$t.memory(mb(screenMem.bytes), mb(SCREEN_BUDGET))}{screenMem.fit === "compressed"
+ ? ` — ${$t.memoryCompressed}`
+ : screenMem.fit === "too-heavy"
+ ? ` — ${$t.memoryTooHeavy}`
+ : ""}
+
+ {/if}
+
{#if perf && $doc}
0 && fps < 50}>
{fps} fps · {drawMs} ms draw
@@ -1200,12 +1235,25 @@
}
}
- /* the open screen's share of a Watch 3 Pro's memory, over the canvas's top edge */
- .memory {
+ /* where the face can go and the open screen's share of a Watch 3 Pro's memory, stacked over
+ the canvas's top edge */
+ .notes {
position: absolute;
top: 0.5rem;
inset-inline-end: 0.5rem;
z-index: 2;
+ display: flex;
+ max-width: calc(100% - 1rem);
+ flex-direction: column;
+ align-items: flex-end;
+ gap: 0.25rem;
+ }
+ @media (max-width: 767px) {
+ .notes {
+ top: 3.5rem; /* under the floating Main/AOD switch */
+ }
+ }
+ .memory {
margin: 0;
padding: 0.125rem 0.5rem;
border-radius: calc(var(--border-radius) - 0.25rem);
diff --git a/src/lib/modules/editor/shared/drag.ts b/src/lib/modules/editor/shared/drag.ts
index eae1b4a..9dd17da 100644
--- a/src/lib/modules/editor/shared/drag.ts
+++ b/src/lib/modules/editor/shared/drag.ts
@@ -2,6 +2,7 @@
// does to a layer's box. Nothing here imports Svelte or the model — the page reads the pointer,
// calls these, and fires the model event the result names.
import { framesOf, type Doc, type Layer, type NodeId } from "../core/document/doc";
+import { procOf, RINGS } from "../core/document/proc";
import type { LayerHit, Point, Size } from "../core/render/canvas";
import type { ResizePreview } from "../core/render/render";
import {
@@ -59,7 +60,7 @@ export type ResizeRequest =
| { to: "image"; p: { layer: NodeId; w: number; h: number; at?: Point } };
export function dragItem(l: Layer): DragItem | null {
- if (l.locked) return null;
+ if (l.locked || procOf(l)?.type === RINGS) return null;
if (l.kind === "group") return { layer: l, x0: l.frame.x, y0: l.frame.y };
return l.kind === "raw" ? null : { layer: l, x0: l.x, y0: l.y };
}
diff --git a/src/lib/modules/store/i18n.ts b/src/lib/modules/store/i18n.ts
index b9ce60b..aa17644 100644
--- a/src/lib/modules/store/i18n.ts
+++ b/src/lib/modules/store/i18n.ts
@@ -81,6 +81,8 @@ export const t = dict(
`The connected watch is “${name}”, and this firmware is for the ${device}. It can't be installed on this watch from here — download only.`,
unnamed: "unnamed",
ownRisk: "You install it at your own risk. FMC takes no responsibility for your watch.",
+ rollbackRisk:
+ "Before installing stock or older firmware, switch to a built-in face and delete Watch 3 Pro faces with animated or data widgets from the watch: older firmware can restart in a loop on them.",
acceptRisk: "I accept the risk",
downloading: "Downloading",
keepTabOpen: "Keep this tab open and the watch close.",
@@ -221,6 +223,8 @@ export const t = dict(
unnamed: "без имени",
ownRisk:
"Вы устанавливаете её на свой страх и риск. FMC не несёт ответственности за ваши часы.",
+ rollbackRisk:
+ "Перед установкой стоковой или более старой прошивки включите встроенный циферблат и удалите с часов циферблаты Watch 3 Pro с анимацией и виджетами данных: на старой прошивке часы могут зациклиться на перезагрузке.",
acceptRisk: "Я принимаю риск",
downloading: "Загрузка",
keepTabOpen: "Не закрывайте вкладку и держите часы рядом.",
@@ -357,6 +361,8 @@ export const t = dict(
`Під'єднано годинник «${name}», а ця прошивка для ${device}. Звідси її на цей годинник не встановити — лише завантажити.`,
unnamed: "без назви",
ownRisk: "Ви встановлюєте її на власний ризик. FMC не несе відповідальності за ваш годинник.",
+ rollbackRisk:
+ "Перед встановленням стокової або старішої прошивки увімкніть вбудований циферблат і видаліть з годинника циферблати Watch 3 Pro з анімацією та віджетами даних: на старій прошивці годинник може циклічно перезавантажуватися.",
acceptRisk: "Я приймаю ризик",
downloading: "Завантаження",
keepTabOpen: "Не закривайте вкладку й тримайте годинник поруч.",
@@ -493,6 +499,8 @@ export const t = dict(
`El reloj conectado es “${name}” y este firmware es para el ${device}. No se puede instalar en este reloj desde aquí, solo descargar.`,
unnamed: "sin nombre",
ownRisk: "Lo instalas bajo tu propio riesgo. FMC no se hace responsable de tu reloj.",
+ rollbackRisk:
+ "Antes de instalar firmware original o anterior, cambia a una esfera integrada y borra del reloj las esferas del Watch 3 Pro con animaciones o widgets de datos: con un firmware anterior el reloj puede reiniciarse en bucle.",
acceptRisk: "Acepto el riesgo",
downloading: "Descargando",
keepTabOpen: "Mantén esta pestaña abierta y el reloj cerca.",
@@ -627,6 +635,8 @@ export const t = dict(
`कनेक्टेड घड़ी “${name}” है, और यह फ़र्मवेयर ${device} के लिए है। इसे यहां से इस घड़ी पर इंस्टॉल नहीं किया जा सकता — सिर्फ़ डाउनलोड।`,
unnamed: "बिना नाम",
ownRisk: "आप इसे अपने जोखिम पर इंस्टॉल करते हैं। आपकी घड़ी की कोई ज़िम्मेदारी FMC की नहीं है।",
+ rollbackRisk:
+ "स्टॉक या पुराना फ़र्मवेयर इंस्टॉल करने से पहले कोई बिल्ट-इन फ़ेस चुनें और Watch 3 Pro के एनिमेशन या डेटा विजेट वाले फ़ेस घड़ी से हटा दें: पुराने फ़र्मवेयर पर घड़ी बार-बार रीस्टार्ट हो सकती है।",
acceptRisk: "मैं जोखिम स्वीकार करता/करती हूं",
downloading: "डाउनलोड हो रहा है",
keepTabOpen: "यह टैब खुला रखें और घड़ी पास रखें।",
diff --git a/src/lib/modules/store/pages/firmware.svelte b/src/lib/modules/store/pages/firmware.svelte
index 0b6a1fd..583ebe1 100644
--- a/src/lib/modules/store/pages/firmware.svelte
+++ b/src/lib/modules/store/pages/firmware.svelte
@@ -149,6 +149,8 @@
{$t.ownRisk}
+
+ {#if ota && !loader}{$t.rollbackRisk} {/if}
@@ -385,6 +387,10 @@
}
/* which watch is the one thing on this plate to read first */
}
+ .rollback {
+ display: block;
+ margin-top: 0.5rem;
+ }
.accept {
display: flex;
align-items: center;
diff --git a/tests/ble-messages.test.ts b/tests/ble-messages.test.ts
index dfe8aa1..403afc9 100644
--- a/tests/ble-messages.test.ts
+++ b/tests/ble-messages.test.ts
@@ -9,6 +9,7 @@ import ble from "$lib/modules/device/lib/ble.ts?raw";
import ota from "$lib/modules/device/lib/ota-image.ts?raw";
import wp2 from "$lib/modules/device/lib/wp2.ts?raw";
import bin from "$lib/modules/editor/core/format/bin.ts?raw";
+import compat from "$lib/modules/editor/core/format/compat.ts?raw";
// protocol internals nobody acts on: shown as they are, inside a translated "decode: …"
const TECHNICAL =
@@ -31,7 +32,10 @@ test("every status and error from the watch libraries has a translation", () =>
i18nModel.localePicked("ru");
const w = bt.getState();
const said = [
- ...sentences(ble + ota + wp2, new RegExp(String.raw`(?:status|Error)\(\s*` + LIT, "g")),
+ ...sentences(
+ ble + ota + wp2 + compat,
+ new RegExp(String.raw`(?:status|Error)\(\s*` + LIT, "g"),
+ ),
...sentences(
bin.slice(bin.indexOf("export function assertFlashable")),
new RegExp(String.raw`(?:Error\(|\?)\s*` + LIT, "g"),
diff --git a/tests/editor-pro2-export.browser.test.ts b/tests/editor-pro2-export.browser.test.ts
new file mode 100644
index 0000000..4ba02e2
--- /dev/null
+++ b/tests/editor-pro2-export.browser.test.ts
@@ -0,0 +1,60 @@
+// Export for Watch Pro 2 through the model: what actually gets downloaded.
+import { afterEach, expect, test, vi } from "vitest";
+import { editorModel } from "$lib/modules/editor/model";
+import { parseBin } from "$lib/modules/editor/core/format";
+import { assertWatchCompat, procWidgets } from "$lib/modules/editor/core/format/compat";
+import { faceBin, imageNode, procNode, squares } from "./proc-face";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+async function exported(bin: Uint8Array) {
+ const files: Blob[] = [];
+ const names: string[] = [];
+
+ vi.spyOn(URL, "createObjectURL").mockImplementation((b) => {
+ files.push(b as Blob);
+ return "blob:export";
+ });
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(
+ function (this: HTMLAnchorElement) {
+ names.push(this.download);
+ },
+ );
+ editorModel.errored("");
+ editorModel.loadRequested({ buf: bin, label: "export" });
+ await vi.waitFor(() => {
+ expect(editorModel.$loading.getState()).toBe(false);
+ expect(editorModel.$fileLabel.getState()).toBe("export");
+ });
+ editorModel.exportPro2();
+ await vi.waitFor(() => expect(files.length + editorModel.$err.getState().length).toBeTruthy(), {
+ timeout: 8000,
+ });
+ return { files, names, err: editorModel.$err.getState() };
+}
+
+test("a copy a stock Watch Pro 2 takes", async () => {
+ const src = faceBin(
+ [imageNode([0]), imageNode([1, 2], 0x99), procNode({ type: 4 })],
+ [...squares(1, 28), ...squares(2, 14)],
+ );
+ const { files, names, err } = await exported(src);
+
+ expect(err).toBe("");
+ expect(names).toEqual(["Synthetic-watch-pro-2.bin"]);
+ const out = new Uint8Array(await files[0].arrayBuffer());
+
+ expect(new Set(parseBin(out).resources.map((r) => r.cf))).not.toContain(28);
+ expect(new Set(parseBin(out).resources.map((r) => r.cf))).not.toContain(14);
+ expect(procWidgets(out)).toEqual([{ type: 4, hasImages: false }]);
+ await expect(assertWatchCompat(out, "watch_pro_2", async () => null)).resolves.toBeUndefined();
+});
+
+test("a face that would boot-loop it downloads nothing", async () => {
+ const { files, err } = await exported(faceBin([procNode({ type: 5, images: [0] })], squares(1)));
+
+ expect(files).toEqual([]);
+ expect(err).toMatch(/Watch 3 Pro only/);
+});
diff --git a/tests/editor-proc.browser.test.ts b/tests/editor-proc.browser.test.ts
new file mode 100644
index 0000000..5eb752d
--- /dev/null
+++ b/tests/editor-proc.browser.test.ts
@@ -0,0 +1,84 @@
+// Editing a procedural widget through the model and the inspector.
+import { describe, expect, test, vi } from "vitest";
+import { render } from "vitest-browser-svelte";
+import PropsPanel from "$lib/modules/editor/components/PropsPanel.svelte";
+import { editorModel } from "$lib/modules/editor/model";
+import { procOf } from "$lib/modules/editor/core/document/proc";
+import { framesOf, type Doc } from "$lib/modules/editor/core/document/doc";
+import { faceBin, procNode, squares, type Proc } from "./proc-face";
+
+const doc = () => editorModel.$doc.getState() as Doc;
+const first = () => doc().screens[0].layers[0];
+
+async function open(p: Proc, cf = 5) {
+ const bin = faceBin([procNode(p)], squares(p.images?.length ?? 0, cf, 8, 8));
+
+ editorModel.loadRequested({ buf: bin, label: "proc" });
+ await vi.waitFor(() => {
+ expect(editorModel.$loading.getState()).toBe(false);
+ expect(procOf(first())?.type).toBe(p.type);
+ });
+ editorModel.select(first().id);
+}
+const thirteen = Array.from({ length: 13 }, (_, i) => i);
+
+test("a panel change is one undoable edit", async () => {
+ await open({ type: 6, sub: 1, images: thirteen });
+ editorModel.panelSet({ id: first().id, panel: 4 });
+ expect(procOf(first())?.panel).toBe(4);
+ editorModel.undo();
+ expect(procOf(first())?.panel).toBe(1);
+});
+
+test("a resize leaves the widget's images alone", async () => {
+ await open({ type: 6, sub: 1, images: thirteen });
+ const before = doc();
+
+ editorModel.resizeImageRequested({ layer: first().id, w: 32, h: 32 });
+ editorModel.rotateImageRequested({ layer: first().id, deg: 90 });
+ await new Promise((r) => setTimeout(r, 300));
+ expect(doc()).toBe(before);
+});
+
+// Briqbot's frames are JPEG (cf 1): the bytes of a picked PNG are not one
+test("a PNG dropped on a JPEG frame is stored as a JPEG", async () => {
+ await open({ type: 7, images: [0] });
+ const id = framesOf(first())[0];
+ const c = new OffscreenCanvas(8, 8);
+
+ c.getContext("2d")!.fillRect(0, 0, 8, 8);
+ const jpeg = new Uint8Array(await (await c.convertToBlob({ type: "image/jpeg" })).arrayBuffer());
+
+ editorModel.committed({
+ edit: (d) => ({
+ ...d,
+ images: new Map(d.images).set(id, { ...d.images.get(id)!, cf: 1, data: jpeg }),
+ }),
+ });
+ const png = new File([await c.convertToBlob({ type: "image/png" })], "frame.png", {
+ type: "image/png",
+ });
+
+ editorModel.replaceImageRequested({ id, file: png });
+ await vi.waitFor(() => expect(doc().images.get(id)!.data).not.toBe(jpeg), { timeout: 5000 });
+ expect(Array.from(doc().images.get(id)!.data.subarray(0, 2))).toEqual([0xff, 0xd8]);
+});
+
+describe("the inspector", () => {
+ test("says which watch a widget is for and offers the panel", async () => {
+ await open({ type: 6, sub: 1, images: thirteen });
+ const screen = await render(PropsPanel);
+
+ await expect.element(screen.getByText(/Watch 3 Pro widget/)).toBeInTheDocument();
+ await expect.element(screen.getByText("Heart rate").first()).toBeInTheDocument();
+ expect(screen.container.textContent).not.toMatch(/regenerate from a font|none — static/i);
+ });
+
+ test("a ring widget has no position fields", async () => {
+ await open({ type: 4 });
+ const screen = await render(PropsPanel);
+
+ await expect.element(screen.getByText(/follows the finger/)).toBeInTheDocument();
+ expect(screen.container.querySelectorAll('input[type="number"]')).toHaveLength(0);
+ });
+});
diff --git a/tests/face-compat.test.ts b/tests/face-compat.test.ts
new file mode 100644
index 0000000..d97c758
--- /dev/null
+++ b/tests/face-compat.test.ts
@@ -0,0 +1,238 @@
+// Which Watch 3 Pro widgets may go to which watch and firmware (core/format/compat.ts). Every
+// refusal here was a boot loop in the cmf-watch-utils emulator, or falls in the same table bug.
+import { readdirSync, readFileSync } from "node:fs";
+import { describe, expect, test } from "vitest";
+import { buildBin, parseBin, TAG } from "$lib/modules/editor/core/format";
+import {
+ assertWatchCompat,
+ PRO2_FACES_STUB,
+ procWidgets,
+} from "$lib/modules/editor/core/format/compat";
+import { faceBin, imageNode, procNode, squares, type Proc } from "./proc-face";
+
+const P2 = "watch_pro_2";
+const P3 = "watch_3_pro";
+const face = (p: Proc) => faceBin([procNode(p)], p.images ? squares(p.images.length) : []);
+const noStub = async () => null;
+const stub = (n: number | null) => async () => n;
+const check = (bin: Uint8Array, device: string | null, version: number | null = null, min = 10) =>
+ assertWatchCompat(bin, device, stub(version), min);
+
+describe("what the firmware would read", () => {
+ test("type and whether the image lookup finds a list", () => {
+ expect(procWidgets(face({ type: 6, images: [0] }))).toEqual([{ type: 6, hasImages: true }]);
+ expect(procWidgets(face({ type: 4 }))).toEqual([{ type: 4, hasImages: false }]);
+ });
+
+ // the parser reads the list at a fixed offset, past the end of a short struct
+ test("a short struct with a condition after it has a list, as far as the watch is concerned", () => {
+ const bin = face({ type: 4, tail: "", conditions: "010b02630000" });
+
+ expect(procWidgets(bin)).toEqual([{ type: 4, hasImages: true }]);
+ });
+
+ test("the type is two bytes", () => {
+ expect(procWidgets(face({ type: 0xffff }))[0].type).toBe(0xffff);
+ expect(procWidgets(face({ type: 0x0104 }))[0].type).toBe(0x0104);
+ });
+
+ // parseBin takes some of these payloads for a subtree; the check must not depend on it
+ test.each([2, 3, 6, 9, 24, 25, 27])("a %i-byte payload is still seen", (len) => {
+ expect(procWidgets(face({ type: 8, len }))[0].type).toBe(8);
+ });
+
+ test("inside groups, however deep", () => {
+ const group = (child: ReturnType) => ({
+ tag: TAG.group,
+ subs: [{ tag: TAG.frame, hex: "00000000d201d20100" }, child],
+ });
+ const bin = faceBin([group(group(procNode({ type: 6, images: [0] })))], squares(1));
+
+ expect(procWidgets(bin)).toEqual([{ type: 6, hasImages: true }]);
+ });
+
+ test("no widget, nothing to report", () => {
+ expect(procWidgets(faceBin([imageNode([0])], squares(1)))).toEqual([]);
+ });
+
+ test("a screen that doesn't walk is unreadable, not safe", () => {
+ const bin = face({ type: 6 }).slice();
+
+ bin[36 + 3 + 3 + 1] = 0xff; // the first layer's length now runs past its screen
+ bin[36 + 3 + 3 + 2] = 0xff;
+ expect(() => procWidgets(bin)).toThrow(/can't read this file/);
+ });
+});
+
+describe("Watch Pro 2 on stock or older patched firmware", () => {
+ test.each([0, 1, 2, 3])("type %i is its own", async (type) => {
+ await expect(check(face({ type, images: [0] }), P2)).resolves.toBeUndefined();
+ });
+
+ test("type 4 without images is dropped by the watch, so it goes", async () => {
+ await expect(check(face({ type: 4 }), P2)).resolves.toBeUndefined();
+ });
+
+ test("type 4 with images is refused", async () => {
+ await expect(check(face({ type: 4, images: [0] }), P2)).rejects.toThrow(/widget \(type 4\)/);
+ });
+
+ test("type 4 with a short struct is refused", async () => {
+ const bin = face({ type: 4, tail: "", conditions: "010b02630000" });
+
+ await expect(check(bin, P2)).rejects.toThrow(/widget \(type 4\)/);
+ });
+
+ test.each([5, 6, 7])("type %i is refused, images or not", async (type) => {
+ await expect(check(face({ type, images: [0] }), P2)).rejects.toThrow(/restart in a loop/);
+ await expect(check(face({ type }), P2)).rejects.toThrow(/restart in a loop/);
+ });
+
+ test.each([1, 8, 9])("stub %i is not enough", async (version) => {
+ await expect(check(face({ type: 6, images: [0] }), P2, version)).rejects.toThrow(/type 6/);
+ });
+});
+
+describe("Watch Pro 2 with a stub that draws them", () => {
+ test.each([4, 5, 6, 7])("type %i goes to stub 10", async (type) => {
+ await expect(check(face({ type, images: [0] }), P2, 10)).resolves.toBeUndefined();
+ });
+
+ test("until that stub ships nobody is asked and the widgets are refused", async () => {
+ expect(PRO2_FACES_STUB).toBeNull();
+ let asked = false;
+ const read = async () => {
+ asked = true;
+ return 99;
+ };
+
+ await expect(assertWatchCompat(face({ type: 6 }), P2, read)).rejects.toThrow(/type 6/);
+ expect(asked).toBe(false);
+ });
+
+ test("a watch that doesn't answer counts as stock", async () => {
+ const silent = async () => {
+ throw new Error("timeout waiting for stubInfoRep");
+ };
+
+ await expect(assertWatchCompat(face({ type: 5 }), P2, silent, 10)).rejects.toThrow(/type 5/);
+ });
+
+ test("the stub is asked only for a face that needs it", async () => {
+ let asked = 0;
+ const read = async () => {
+ asked++;
+ return 10;
+ };
+
+ await assertWatchCompat(face({ type: 2 }), P2, read, 10);
+ await assertWatchCompat(face({ type: 4 }), P2, read, 10);
+ await assertWatchCompat(face({ type: 6 }), P3, read, 10);
+ expect(asked).toBe(0);
+ await assertWatchCompat(face({ type: 6 }), P2, read, 10);
+ expect(asked).toBe(1);
+ });
+});
+
+describe("Watch 3 Pro", () => {
+ test.each([0, 1, 2, 3, 4, 5, 6, 7])("type %i is in its table", async (type) => {
+ await expect(check(face({ type }), P3)).resolves.toBeUndefined();
+ });
+});
+
+describe("a watch with no known model", () => {
+ test("gets types 0..3 and nothing newer", async () => {
+ await expect(check(face({ type: 3 }), null)).resolves.toBeUndefined();
+ await expect(check(face({ type: 4 }), null)).rejects.toThrow(/type 4/);
+ await expect(check(face({ type: 6 }), null, 10)).rejects.toThrow(/type 6/);
+ });
+});
+
+describe.each([8, 12, 0xff, 0x100, 0xffff])("type %i", (type) => {
+ test.each([P2, P3, null])("goes to no watch (%s)", async (device) => {
+ await expect(check(face({ type }), device, 10)).rejects.toThrow(/no supported watch/);
+ });
+});
+
+// A stub that decodes cf 28 unpacks it to cf 5, three bytes a pixel; FMC's budget counts one.
+describe("ETC2 on a Watch Pro 2", () => {
+ const etc2 = (n: number) =>
+ faceBin(
+ Array.from({ length: n }, (_, i) => imageNode([i])),
+ // only the header's size counts: nothing here decodes the payload
+ squares(n, 28).map((r) => ({ ...r, w: 464, h: 464 })),
+ );
+
+ test("is counted unpacked", async () => {
+ await expect(assertWatchCompat(etc2(3), P2, noStub)).resolves.toBeUndefined(); // 1.94 MB
+ await expect(assertWatchCompat(etc2(4), P2, noStub)).rejects.toThrow(/2\.6 MB unpacked/);
+ });
+
+ test("also when it isn't the largest frame of its run as stored", async () => {
+ const big = squares(4, 28).map((r) => ({ ...r, w: 464, h: 464 }));
+ // cf 5 at 280x280 outweighs cf 28 at 464x464 until the latter is unpacked
+ const small = squares(4, 5).map((r) => ({ ...r, w: 280, h: 280 }));
+ const bin = faceBin(
+ [0, 2, 4, 6].map((i) => imageNode([i, i + 1])),
+ big.flatMap((r, i) => [r, small[i]]),
+ );
+
+ await expect(assertWatchCompat(bin, P2, noStub)).rejects.toThrow(/2\.6 MB unpacked/);
+ });
+
+ test("and left to the budget on a Watch 3 Pro", async () => {
+ await expect(assertWatchCompat(etc2(4), P3, noStub)).resolves.toBeUndefined();
+ });
+});
+
+// Nobody has seen what a Watch Pro 2 does with an A8 image, and the emulator stops on them.
+describe("A8 (cf 14) on a Watch Pro 2", () => {
+ const a8 = () => faceBin([imageNode([0])], squares(1, 14));
+
+ test("is refused, with the way out", async () => {
+ await expect(assertWatchCompat(a8(), P2, noStub)).rejects.toThrow(
+ /A8 images \(cf 14\).*Export for Watch Pro 2/,
+ );
+ });
+
+ test("whatever the stub: none of them converts A8", async () => {
+ await expect(check(a8(), P2, 10)).rejects.toThrow(/A8 images/);
+ });
+
+ test("also as a frame that isn't the run's largest", async () => {
+ const bin = faceBin([imageNode([0, 1])], [...squares(1, 5, 8, 8), ...squares(1, 14)]);
+
+ await expect(assertWatchCompat(bin, P2, noStub)).rejects.toThrow(/A8 images/);
+ });
+
+ test("the thumbnail counts: the face picker draws it on the same watch", async () => {
+ const face = parseBin(faceBin([imageNode([0])], squares(1)));
+
+ face.resources[face.resources.length - 1] = squares(1, 14, 8, 8)[0];
+ await expect(assertWatchCompat(buildBin(face), P2, noStub)).rejects.toThrow(/A8 images/);
+ });
+
+ test("a Watch 3 Pro takes them", async () => {
+ await expect(assertWatchCompat(a8(), P3, noStub)).resolves.toBeUndefined();
+ });
+
+ test("a boot loop is named before a format", async () => {
+ const bin = faceBin([procNode({ type: 6, images: [0] })], squares(1, 14));
+
+ await expect(assertWatchCompat(bin, P2, noStub)).rejects.toThrow(/type 6/);
+ });
+});
+
+// the repo's factory faces: the check must not refuse a watch its own faces
+const fixtures = new URL("./__fixtures__/", import.meta.url);
+
+test.each(readdirSync(fixtures).filter((f) => f.endsWith(".bin")))(
+ "%s still goes to the watch it was made for",
+ async (name) => {
+ const bin = new Uint8Array(readFileSync(new URL(name, fixtures)));
+
+ await expect(
+ assertWatchCompat(bin, name.startsWith("Pro3__") ? P3 : P2, noStub),
+ ).resolves.toBeUndefined();
+ },
+);
diff --git a/tests/firmware-rollback.browser.test.ts b/tests/firmware-rollback.browser.test.ts
new file mode 100644
index 0000000..9112314
--- /dev/null
+++ b/tests/firmware-rollback.browser.test.ts
@@ -0,0 +1,45 @@
+// Going back to a firmware without the Watch 3 Pro widgets can strand a face that needs them in
+// a boot loop, and the install gate can't see that coming: both ways to flash an image say so.
+import { expect, test } from "vitest";
+import { render } from "vitest-browser-svelte";
+import type { RecordModel } from "pocketbase";
+import DevSheet from "$lib/modules/device/components/dev-sheet.svelte";
+import { devModel } from "$lib/modules/device/model";
+import * as storeApi from "$lib/modules/store/model/store.api";
+import { FirmwarePage } from "$lib/modules/store/pages";
+
+const rec = (id: string, extra: object) =>
+ ({ id, name: id, image: `${id}.bin`, ...extra }) as unknown as RecordModel;
+const stock = rec("stock", { kind: "stock", device: "watch_pro_2" });
+const loader = rec("loader", { kind: "loader", device: "watch_pro_2" });
+const WARNING = /Before installing stock or older firmware, switch to a built-in face/;
+
+storeApi.loadFirmwaresFx.use(() => [stock, loader]);
+storeApi.loadFirmwareFx.use((id) => [stock, loader].find((r) => r.id === id)!);
+
+test("a firmware page warns before a rollback", async () => {
+ const screen = await render(FirmwarePage, { id: "stock" });
+
+ await expect.element(screen.getByText(WARNING)).toBeInTheDocument();
+});
+
+test("the App Loader isn't firmware: no such warning", async () => {
+ const screen = await render(FirmwarePage, { id: "loader" });
+
+ await expect.element(screen.getByRole("heading", { name: "loader" })).toBeInTheDocument();
+ expect(screen.container.textContent).not.toMatch(WARNING);
+});
+
+test("the Developer panel warns over a local image", async () => {
+ (devModel.$build as unknown as { setState(v: devModel.LocalBuild): void }).setState({
+ name: "local.bin",
+ size: 1024,
+ modified: 0,
+ kind: "firmware",
+ what: "firmware 1.0 for board jx402_01_3089c",
+ });
+ devModel.panelOpened();
+ const screen = await render(DevSheet);
+
+ await expect.element(screen.getByText(WARNING)).toBeInTheDocument();
+});
diff --git a/tests/flash-compat.browser.test.ts b/tests/flash-compat.browser.test.ts
new file mode 100644
index 0000000..5ff0331
--- /dev/null
+++ b/tests/flash-compat.browser.test.ts
@@ -0,0 +1,60 @@
+// The editor's and the store's installs both end in ble.model's flash: a face with a widget that
+// would boot-loop the connected watch never reaches the upload. Transport stubbed out.
+import { beforeAll, beforeEach, expect, test, vi } from "vitest";
+import { bleModel } from "$lib/modules/device/model";
+import { faceBin, imageNode, procNode, squares } from "./proc-face";
+
+const sent = vi.hoisted(() => ({ uploads: [] as Uint8Array[], asked: 0 }));
+
+vi.mock("$lib/modules/device/lib/ble", async (importOriginal) => {
+ class Watch {
+ serial = null;
+ name = "CMF Watch Pro 2-1A2B";
+ onDials = () => {};
+ async connect() {
+ return { name: this.name, battery: null, firmware: null, serial: null };
+ }
+ async readWp2() {
+ sent.asked++;
+ return null;
+ }
+ async uploadWatchface(bin: Uint8Array) {
+ sent.uploads.push(bin);
+ return { id: 1, name: "synthetic" };
+ }
+ mergeDials() {}
+ }
+
+ return { ...(await importOriginal()), Watch };
+});
+
+beforeAll(async () => {
+ bleModel.connectRequested();
+ await vi.waitFor(() => expect(bleModel.$bleInfo.getState()).not.toBeNull());
+});
+beforeEach(() => {
+ sent.uploads.length = 0;
+ sent.asked = 0; // a connection asks once by itself, for the Developer panel
+});
+
+test("a Watch Pro 2 is never sent a widget its firmware falls over", async () => {
+ bleModel.flashRequested({ bin: faceBin([procNode({ type: 6, images: [0] })], squares(1)) });
+ await vi.waitFor(() => expect(bleModel.$bleStatus.getState()).toMatch(/widget \(type 6\)/), {
+ timeout: 5000,
+ });
+ expect(sent.uploads).toEqual([]);
+ expect(sent.asked).toBe(0); // no stub release draws these yet, so there is nothing to ask
+});
+
+test("an A8 face is refused with a pointer to the export", async () => {
+ bleModel.flashRequested({ bin: faceBin([imageNode([0])], squares(1, 14)) });
+ await vi.waitFor(() => expect(bleModel.$bleStatus.getState()).toMatch(/A8 images/), {
+ timeout: 5000,
+ });
+ expect(sent.uploads).toEqual([]);
+});
+
+test("and still gets the one it drops safely", async () => {
+ bleModel.flashRequested({ bin: faceBin([procNode({ type: 4 })]) });
+ await vi.waitFor(() => expect(sent.uploads).toHaveLength(1), { timeout: 5000 });
+});
diff --git a/tests/pro2-export.test.ts b/tests/pro2-export.test.ts
new file mode 100644
index 0000000..21151fa
--- /dev/null
+++ b/tests/pro2-export.test.ts
@@ -0,0 +1,157 @@
+// The converted copy of a Watch 3 Pro face for a Watch Pro 2 (core/document/pro2.ts).
+import { describe, expect, test } from "vitest";
+import {
+ buildBin,
+ decodePixels,
+ encodePixels,
+ parseBin,
+ screenBytes,
+ TAG,
+} from "$lib/modules/editor/core/format";
+import type { FaceNode } from "$lib/modules/editor/core/format/raw";
+import { PRO2_TESTED_BYTES } from "$lib/modules/editor/core/format/compat";
+import { fromLegacy, toLegacy, type Doc } from "$lib/modules/editor/core/document/doc";
+import { forPro2, pro2Problem } from "$lib/modules/editor/core/document/pro2";
+import { faceBin, imageNode, metaHex, procNode, squares } from "./proc-face";
+
+const open = (bin: Uint8Array) => fromLegacy(parseBin(bin)).doc;
+const convert = (bin: Uint8Array, theme = 0) =>
+ parseBin(buildBin(toLegacy(forPro2(open(bin), theme))));
+const firstStruct = (nodes: FaceNode[]) =>
+ nodes.find((n) => n.tag === TAG.image)!.subs!.find((n) => n.tag === TAG.struct)!;
+
+/** A 4x4 block of one colour survives ETC2 closely enough to compare after RGB565. */
+function solid(cf: number, rgba: number[]) {
+ const px = new Uint8ClampedArray(64);
+
+ for (let o = 0; o < 64; o += 4) px.set(rgba, o);
+ return encodePixels(px, 4, 4, cf);
+}
+
+describe("formats", () => {
+ test("cf 28 becomes cf 5 with the pixels it decodes to", () => {
+ const etc2 = solid(28, [200, 40, 90, 128]);
+ const out = convert(faceBin([imageNode([0])], [etc2]));
+ const r = out.resources[firstStruct(out.screens[0].subs!).images![0]];
+ const expected = encodePixels(decodePixels(etc2)!, 4, 4, 5);
+
+ expect(r.cf).toBe(5);
+ expect(decodePixels(r)).toEqual(decodePixels(expected));
+ });
+
+ test("cf 14 becomes white with the mask as alpha", () => {
+ const out = convert(faceBin([imageNode([0])], [solid(14, [0, 0, 0, 77])]));
+ const r = out.resources[firstStruct(out.screens[0].subs!).images![0]];
+
+ expect(r.cf).toBe(5);
+ expect(Array.from(decodePixels(r)!.slice(0, 4))).toEqual([255, 255, 255, 77]);
+ });
+
+ test("the thumbnail too, and nothing else", () => {
+ const face = parseBin(
+ faceBin([imageNode([0]), imageNode([1])], [...squares(1, 4), ...squares(1, 13)]),
+ );
+ const preview = face.screens[0].subs!.find((n) => n.tag === TAG.preview)!.subs![0].images![0];
+
+ face.resources[preview] = solid(28, [10, 20, 30, 255]);
+ const bin = buildBin(face);
+
+ expect(convert(bin).resources.map((r) => r.cf)).toEqual([4, 13, 5]);
+ });
+
+ test("the document it was made from is untouched", () => {
+ const doc: Doc = open(faceBin([imageNode([0])], [solid(28, [1, 2, 3, 255])]));
+ const before = [...doc.images.values()];
+
+ forPro2(doc, 0);
+ expect([...doc.images.values()]).toEqual(before);
+ });
+});
+
+describe("the colour theme's source", () => {
+ test.each([
+ [0, 0],
+ [2, 2],
+ [4, 1], // past the run: the watch wraps
+ ])("theme %i keeps frame %i alone", (theme, frame) => {
+ const src = squares(3);
+ const out = convert(faceBin([imageNode([0, 1, 2], 0x99, 4)], src), theme);
+ const st = firstStruct(out.screens[0].subs!);
+
+ expect(st.images).toHaveLength(1);
+ expect(out.resources[st.images![0]].data).toEqual(src[frame].data);
+ expect(out.resources).toHaveLength(2); // that frame and the thumbnail
+ expect(st.meta).toBe(metaHex(4, 4, 0, 4)); // the source goes, the tint flag stays
+ });
+
+ test("a condition on it can't be pinned", () => {
+ const node = imageNode([0]);
+
+ node.subs!.push({ tag: TAG.bind, hex: "019901020000" });
+ const doc = open(faceBin([node], squares(1)));
+
+ expect(pro2Problem(doc)).toEqual({ reason: "theme" });
+ });
+
+ test("a number printing it can't be either", () => {
+ const node: FaceNode = {
+ tag: TAG.number,
+ subs: [
+ {
+ tag: TAG.struct,
+ x: 0,
+ y: 0,
+ meta: metaHex(4, 4, 0x99),
+ refType: 0x61,
+ images: Array.from({ length: 10 }, (_, i) => i),
+ },
+ { tag: TAG.fmt, hex: "01" },
+ ],
+ };
+
+ expect(pro2Problem(open(faceBin([node], squares(10))))).toEqual({ reason: "theme" });
+ });
+});
+
+describe("what isn't exported", () => {
+ test.each([5, 6, 7])("type %i", (type) => {
+ const doc = open(faceBin([procNode({ type, images: [0] })], squares(1, 28)));
+
+ expect(pro2Problem(doc)).toEqual({ reason: "pro3Only" });
+ });
+
+ test("type 8", () => {
+ expect(pro2Problem(open(faceBin([procNode({ type: 8 })])))).toEqual({ reason: "none" });
+ });
+
+ test("type 4 without images converts", () => {
+ expect(pro2Problem(open(faceBin([procNode({ type: 4 })])))).toBeNull();
+ });
+
+ // the header alone decides what a screen weighs
+ test("a screen past the bytes tested on a Pro 2", () => {
+ const four = squares(4, 28).map((r) => ({ ...r, w: 464, h: 464 }));
+ const doc = open(
+ faceBin(
+ [0, 1, 2, 3].map((i) => imageNode([i])),
+ four,
+ ),
+ );
+
+ expect(pro2Problem(doc)).toEqual({ reason: "tooHeavy", bytes: 4 * 464 * 464 * 3 });
+ });
+
+ test("the largest screen it lets through stays in them after converting", () => {
+ const small = squares(3, 28, 64, 64);
+ const bin = faceBin(
+ [0, 1, 2].map((i) => imageNode([i])),
+ small,
+ );
+
+ expect(pro2Problem(open(bin))).toBeNull();
+ const out = convert(bin);
+
+ expect(screenBytes(out.screens[0], out.resources)).toBe(3 * 64 * 64 * 3);
+ expect(3 * 64 * 64 * 3).toBeLessThanOrEqual(PRO2_TESTED_BYTES);
+ });
+});
diff --git a/tests/proc-edit.test.ts b/tests/proc-edit.test.ts
new file mode 100644
index 0000000..b3763b5
--- /dev/null
+++ b/tests/proc-edit.test.ts
@@ -0,0 +1,142 @@
+// What may be edited on a procedural widget, and where the resulting face can go.
+import { describe, expect, test } from "vitest";
+import { buildBin, hex, parseBin, TAG } from "$lib/modules/editor/core/format";
+import { procWidgets } from "$lib/modules/editor/core/format/compat";
+import { fromLegacy, toLegacy, type Layer } from "$lib/modules/editor/core/document/doc";
+import { patchLayer, withPanel } from "$lib/modules/editor/core/document/edits";
+import { procOf } from "$lib/modules/editor/core/document/proc";
+import { watchSupport } from "$lib/modules/editor/core/document/support";
+import { resizable, rotatable } from "$lib/modules/editor/core/render/overlay";
+import { dragItem } from "$lib/modules/editor/shared/drag";
+import { faceBin, imageNode, procNode, squares, type Proc } from "./proc-face";
+
+function open(p: Proc) {
+ const { doc } = fromLegacy(parseBin(faceBin([procNode(p)], squares(p.images?.length ?? 0))));
+ const layer = doc.screens[0].layers.find((l) => procOf(l))!;
+
+ return { doc, layer, id: layer.id };
+}
+const thirteen = Array.from({ length: 13 }, (_, i) => i);
+const patch = (p: object) => p as Partial;
+
+describe("position", () => {
+ test.each([5, 6, 7])("type %i moves", (type) => {
+ const { doc, id } = open({ type, images: [0] });
+ const moved = patchLayer(doc, id, patch({ x: 10, y: 20 })).screens[0].layers[0];
+
+ expect(moved).toMatchObject({ x: 10, y: 20 });
+ });
+
+ // the watch tests the finger against the screen's centre, so a moved ring lights off its art
+ test("type 4 stays put, from every way in", () => {
+ const { doc, id, layer } = open({ type: 4 });
+
+ expect(patchLayer(doc, id, patch({ x: 10, y: 20 }))).toBe(doc);
+ expect(dragItem(layer)).toBeNull();
+ });
+});
+
+describe("images", () => {
+ test("the count is the widget's own: a shorter run is rejected", () => {
+ const { doc, id, layer } = open({ type: 6, sub: 1, images: thirteen });
+ const frames = "frames" in layer ? layer.frames!.slice(1) : [];
+
+ expect(patchLayer(doc, id, patch({ frames }))).toBe(doc);
+ });
+
+ test("the same count in another order is fine", () => {
+ const { doc, id, layer } = open({ type: 6, sub: 1, images: thirteen });
+ const frames = "frames" in layer ? [...layer.frames!].reverse() : [];
+
+ expect(patchLayer(doc, id, patch({ frames })).screens[0].layers[0]).toMatchObject({ frames });
+ });
+
+ // positions are fixed by the firmware, so scaled glyphs would pile up
+ test("no resize or rotate handles", () => {
+ const { layer } = open({ type: 6, sub: 1, images: thirteen });
+
+ expect([resizable(layer), rotatable(layer)]).toEqual([false, false]);
+ });
+});
+
+describe("panel", () => {
+ test.each([1, 2, 3, 4])("heart rate can become panel %i", (panel) => {
+ const { doc, id } = open({ type: 6, sub: 1, images: thirteen });
+ const next = withPanel(doc, id, panel);
+
+ expect(procOf(next.screens[0].layers[0])).toEqual({ type: 6, panel });
+ });
+
+ test("and only that byte of the file changes", () => {
+ const { doc, id } = open({ type: 6, sub: 1, images: thirteen });
+ const expected = faceBin([procNode({ type: 6, sub: 3, images: thirteen })], squares(13));
+
+ expect(hex(buildBin(toLegacy(withPanel(doc, id, 3))))).toBe(hex(expected));
+ });
+
+ test("weather has 88 images, the others 13: no switching to it or from it", () => {
+ const low = open({ type: 6, sub: 1, images: thirteen });
+ const top = open({ type: 6, sub: 0, images: thirteen });
+
+ expect(withPanel(low.doc, low.id, 0)).toBe(low.doc);
+ expect(withPanel(low.doc, low.id, 5)).toBe(low.doc);
+ expect(withPanel(top.doc, top.id, 2)).toBe(top.doc);
+ });
+
+ test("other types have no panel", () => {
+ const { doc, id } = open({ type: 7, images: [0] });
+
+ expect(withPanel(doc, id, 2)).toBe(doc);
+ });
+});
+
+describe("where the face can go", () => {
+ const support = (bin: Uint8Array) => watchSupport(fromLegacy(parseBin(bin)).doc);
+
+ test("an ordinary face needs no note", () => {
+ expect(support(faceBin([imageNode([0])], squares(1)))).toBeNull();
+ });
+
+ test.each([5, 6, 7])("type %i is the Watch 3 Pro's alone", (type) => {
+ expect(support(faceBin([procNode({ type, images: [0] })], squares(1)))).toBe("pro3Only");
+ });
+
+ test("type 4 without images: a Pro 2 drops it", () => {
+ expect(support(faceBin([procNode({ type: 4 })]))).toBe("pro2Drops");
+ });
+
+ test("a short struct with a condition is the 3 Pro's alone, as at install", () => {
+ const bin = faceBin([procNode({ type: 4, tail: "", conditions: "010b02630000" })]);
+
+ expect(procWidgets(bin)[0].hasImages).toBe(true);
+ expect(support(bin)).toBe("pro3Only");
+ });
+
+ test("type 8 is nobody's", () => {
+ expect(support(faceBin([procNode({ type: 8 })]))).toBe("none");
+ });
+
+ test.each([14, 28])("cf %i needs converting for a Pro 2", (cf) => {
+ expect(support(faceBin([imageNode([0])], squares(1, cf)))).toBe("pro2Converts");
+ });
+
+ test("so does a layer picked by the colour theme", () => {
+ expect(support(faceBin([imageNode([0, 1], 0x99)], squares(2)))).toBe("pro2Converts");
+ });
+
+ // the install refuses it, so the note has to offer the export that gets past that
+ test("an A8 thumbnail alone needs converting", () => {
+ const face = parseBin(faceBin([imageNode([0])], squares(1)));
+
+ face.resources[face.resources.length - 1] = squares(1, 14, 8, 8)[0];
+ expect(support(buildBin(face))).toBe("pro2Converts");
+ });
+
+ test("an ETC2 thumbnail alone asks for nothing", () => {
+ const face = parseBin(faceBin([imageNode([0])], squares(1)));
+ const preview = face.screens[0].subs!.find((n) => n.tag === TAG.preview)!.subs![0].images![0];
+
+ face.resources[preview] = squares(1, 28, 8, 8)[0];
+ expect(support(buildBin(face))).toBeNull();
+ });
+});
diff --git a/tests/proc-face.ts b/tests/proc-face.ts
new file mode 100644
index 0000000..59f6a89
--- /dev/null
+++ b/tests/proc-face.ts
@@ -0,0 +1,99 @@
+// Synthetic Watch 3 Pro faces for the tests: no vendor art, every image is made here.
+import { buildBin, encodePixels, hex, TAG, type Resource } from "$lib/modules/editor/core/format";
+import type { FaceNode } from "$lib/modules/editor/core/format/raw";
+
+/** A 14-byte widget meta: size, flags and data source. */
+export function metaHex(w = 466, h = 466, source = 0, flags = 0): string {
+ const m = new Uint8Array(14);
+
+ m[0] = w;
+ m[1] = w >> 8;
+ m[2] = h;
+ m[3] = h >> 8;
+ m[7] = flags;
+ m[9] = source;
+ return hex(m);
+}
+
+/** Opaque squares, each its own grey, so a drawn index can be told from its neighbour. */
+export const squares = (n: number, cf = 5, w = 4, h = 4): Resource[] =>
+ Array.from({ length: n }, (_, i) => {
+ const px = new Uint8ClampedArray(w * h * 4);
+
+ for (let o = 0; o < px.length; o += 4) px.set([(i * 3) % 256, 128, 64, 255], o);
+ return encodePixels(px, w, h, cf);
+ });
+
+export interface Proc {
+ type: number;
+ sub?: number;
+ /** 0x5c payload length. */
+ len?: number;
+ images?: number[];
+ /** What follows the meta of a struct with no images; "" is the short struct. */
+ tail?: string;
+ conditions?: string;
+}
+
+/** A 0x82 widget with its 0x5c body. */
+export function procNode({
+ type,
+ sub = 0,
+ len = 25,
+ images,
+ tail = "0000",
+ conditions,
+}: Proc): FaceNode {
+ const body = new Uint8Array(len);
+
+ body[0] = type;
+ body[1] = type >> 8;
+ if (len > 0x14) body[0x14] = sub;
+ const st: FaceNode = { tag: TAG.struct, x: 0, y: 0, meta: metaHex() };
+
+ if (images?.length) {
+ st.refType = 0x61;
+ st.images = images;
+ } else if (tail) st.tail = tail;
+
+ return {
+ tag: 0x82,
+ subs: [
+ st,
+ ...(conditions ? [{ tag: TAG.bind, hex: conditions }] : []),
+ { tag: 0x5c, hex: hex(body) },
+ ],
+ };
+}
+
+export const imageNode = (images: number[], source = 0, flags = 0): FaceNode => ({
+ tag: TAG.image,
+ subs: [
+ { tag: TAG.struct, x: 0, y: 0, meta: metaHex(4, 4, source, flags), refType: 0x61, images },
+ ],
+});
+
+/** A main screen holding `layers`, with the preview every flashable face carries. */
+export function faceBin(
+ layers: FaceNode[],
+ resources: Resource[] = [],
+ { title = true, header = "Synthetic" } = {},
+): Uint8Array {
+ // resource indices in `layers` count from the caller's list: the preview goes last
+ const preview: FaceNode = {
+ tag: TAG.preview,
+ subs: [{ tag: 0x08, prefix: "0000000000", refType: 0x01, images: [resources.length] }],
+ };
+
+ return buildBin({
+ name: header,
+ screens: [
+ {
+ tag: TAG.main,
+ subs: [...(title ? [{ tag: TAG.name, text: header }] : []), ...layers, preview],
+ },
+ ],
+ // the size of a real thumbnail: a smaller one loses a panel's thin glyphs
+ resources: [...resources, ...squares(1, 4, 270, 270)],
+ });
+}
diff --git a/tests/proc-widgets.test.ts b/tests/proc-widgets.test.ts
new file mode 100644
index 0000000..846f375
--- /dev/null
+++ b/tests/proc-widgets.test.ts
@@ -0,0 +1,194 @@
+// The drawing logic of the procedural widgets. The numbers are the ones cmf-watch-sdk's
+// fw/wp2-core/src/wfproc.rs is tested with (MIT, Copyright (c) 2026 Egor Kolesnikov): the stub
+// and the editor have to put the same image at the same pixel.
+import { describe, expect, test } from "vitest";
+import {
+ calories,
+ frameAt,
+ GREY,
+ heart,
+ hourLabel,
+ nextClip,
+ ringAt,
+ ringBand,
+ sleep,
+ spo2,
+ STAGES,
+ stress,
+ weather,
+ WHITE,
+ type Forecast,
+ type Item,
+} from "$lib/modules/editor/core/render/proc-scene";
+
+const images = (s: Item[]) => s.flatMap((i) => ("img" in i ? [[i.img, i.x, i.y]] : []));
+const rects = (s: Item[]) => s.flatMap((i) => ("w" in i ? [[i.x, i.y, i.w, i.h, i.color]] : []));
+const C24 = { hour: 8, twelve: false };
+const day = (n: number, at: Record) =>
+ Array.from({ length: 24 }, (_, h) => at[h] ?? Array(n).fill(0));
+
+describe("weather", () => {
+ const forecast: Forecast[] = [
+ { temp: 20, code: 2 },
+ { temp: -3, code: 3 },
+ { temp: -2, code: 4 },
+ { temp: -1, code: 5 },
+ ];
+
+ test("columns, 24h", () => {
+ const got = images(weather(forecast, C24));
+
+ // "now", icon, two digits, degree
+ expect(got.slice(0, 5)).toEqual([
+ [0x27, 94, 51],
+ [2, 104, 91],
+ [0x1b + 2, 105, 148],
+ [0x1b, 119, 148],
+ [0x25, 133, 148],
+ ]);
+ // 9:00, icon, minus, 3, degree
+ expect(got.slice(5, 10)).toEqual([
+ [0x40 + 9, 181, 51],
+ [3, 181, 91],
+ [0x26, 182, 148],
+ [0x1b + 3, 196, 148],
+ [0x25, 210, 148],
+ ]);
+ expect(got).toHaveLength(20);
+ });
+
+ test("hour labels, 12h", () => {
+ for (let h = 0; h < 24; h++)
+ expect(hourLabel(h, true)).toEqual([0x28 + h, [0, 10, 11, 12, 22, 23].includes(h) ? 0 : 7]);
+ expect(hourLabel(13, false)).toEqual([0x40 + 13, 17]);
+ });
+
+ // the 3 Pro centres "--" as one digit, seen in its frame
+ test("without data", () => {
+ expect(images(weather([null, null, null, null], C24)).slice(1, 5)).toEqual([
+ [0, 104, 91],
+ [0x26, 112, 148],
+ [0x26, 126, 148],
+ [0x25, 140, 148],
+ ]);
+ });
+
+ test("a code past the face's 27 icons doesn't show a digit", () => {
+ expect(images(weather([{ temp: 5, code: 0x40 }], C24))[1][0]).toBe(1);
+ });
+
+ test.each([-2147483648, -1000, -5, 0, 999, 100000, 2147483647])("%i fits the column", (temp) => {
+ for (const [img] of images(weather(Array(4).fill({ temp, code: 1 }), C24))) {
+ expect(img).toBeGreaterThanOrEqual(0);
+ expect(img).toBeLessThan(88);
+ }
+ });
+});
+
+describe("heart rate", () => {
+ test("bars span min to max", () => {
+ const s = heart(day(4, { 0: [100, 80, 120, 70], 8: [150, 150, 0, 0] }), 150, 50, C24);
+
+ expect(images(s)).toEqual([[10, 80, 295]]);
+ expect(rects(s)).toEqual([
+ [90, 321, 8, 40, GREY],
+ [186, 297, 8, 2, WHITE],
+ ]);
+ });
+
+ test("one value, and none", () => {
+ const none = heart(day(4, {}), 0, 0, { hour: 8, twelve: true });
+
+ expect(images(none)).toEqual([[11, 80, 295]]);
+ expect(rects(none)).toEqual([]);
+ expect(rects(heart(day(4, { 0: [70, 70, 0, 0] }), 70, 70, C24))).toEqual([
+ [90, 297, 8, 5, GREY],
+ ]);
+ });
+});
+
+test("SpO2 under 90 is a stub on the axis", () => {
+ expect(rects(spo2(day(2, { 0: [99, 91], 2: [89, 85] }), C24))).toEqual([
+ [90, 297, 8, 46, GREY],
+ [114, 371, 8, 5, GREY],
+ ]);
+});
+
+test("stress bars", () => {
+ expect(rects(stress(day(2, { 0: [100, 50], 1: [1, 1] }), C24))).toEqual([
+ [90, 297, 8, 40, GREY],
+ [102, 374, 8, 2, GREY],
+ ]);
+});
+
+describe("sleep", () => {
+ test("stages and times", () => {
+ const s = sleep({
+ start: 23 * 3600 + 30 * 60,
+ end: 25 * 3600 + 30 * 60,
+ stages: [
+ { kind: 1, seconds: 3600 },
+ { kind: 3, seconds: 3600 },
+ ],
+ });
+
+ expect(rects(s)).toEqual([
+ [91, 316, 140, 17, STAGES[1]],
+ [233, 350, 140, 17, STAGES[3]],
+ ]);
+ expect(images(s).map(([img]) => img)).toEqual([2, 3, 3, 0, 0, 1, 3, 0]);
+ expect([images(s)[0][1], images(s)[0][2], images(s)[7][1]]).toEqual([91, 378, 361]);
+ });
+
+ test("without data: eight dashes", () => {
+ const s = sleep(null);
+
+ expect(rects(s)).toEqual([]);
+ expect(images(s).map(([img]) => img)).toEqual(Array(8).fill(12));
+ });
+
+ test("more stages than the panel has room for are not drawn", () => {
+ const stages = Array(51).fill({ kind: 1, seconds: 60 });
+
+ expect(rects(sleep({ start: 0, end: 3060, stages }))).toEqual([]);
+ });
+});
+
+test("calories percent", () => {
+ const full = [
+ [0, 275, 332, 3350],
+ [0, 259, 338, 3440],
+ [1, 242, 341, 3530],
+ ];
+ const glyphs = (goal: number, burned: number) =>
+ calories(goal, burned).flatMap((i) => ("img" in i ? [[i.img, i.x, i.y, i.angle]] : []));
+
+ expect(glyphs(500, 0)).toEqual([[0, 275, 332, 3350]]);
+ expect(glyphs(500, 210)).toEqual([
+ [2, 275, 332, 3350],
+ [4, 259, 338, 3440],
+ ]);
+ expect(glyphs(500, 500)).toEqual(full);
+ expect(glyphs(500, 4294967295)).toEqual(full);
+ // the 3 Pro shows 100 without a goal
+ expect(glyphs(0, 7)).toEqual(full);
+});
+
+test("rings under a touch", () => {
+ // 14 rings 16 px apart, each takes 4 px more on both sides
+ expect(ringAt(233, 233)).toBeNull();
+ expect(ringAt(233 + 17, 233)).toBe(0);
+ expect(ringAt(233, 233 - 29)).toBe(0);
+ expect(ringAt(233, 233 + 30)).toBeNull();
+ expect(ringAt(233 + 225, 233)).toBe(13);
+ expect(ringAt(233 + 238, 233)).toBeNull();
+ expect(ringBand(0)).toEqual({ at: 208, size: 50, color: 0xfce1 });
+ expect(ringBand(13)).toEqual({ at: 0, size: 466, color: 0x0c3f });
+});
+
+test("robot clips play once and hold their last frame; a tap starts the next", () => {
+ expect([0, 33, 39 * 33, 1e6].map((ms) => frameAt(0, ms))).toEqual([0, 1, 39, 39]);
+ expect([0, 49 * 33, 1e6].map((ms) => frameAt(1, ms))).toEqual([40, 89, 89]);
+ expect([0, 1e6].map((ms) => frameAt(2, ms))).toEqual([90, 158]);
+ expect([0, 1, 2, 9].map(nextClip)).toEqual([1, 2, 0, 0]);
+});
diff --git a/tests/render-proc.browser.test.ts b/tests/render-proc.browser.test.ts
new file mode 100644
index 0000000..9ab5907
--- /dev/null
+++ b/tests/render-proc.browser.test.ts
@@ -0,0 +1,197 @@
+// The procedural widgets on the canvas: panels at their places, nothing in the corner where
+// their first image used to land, and what a click does in the preview.
+import { describe, expect, test, vi } from "vitest";
+import { parseBin } from "$lib/modules/editor/core/format";
+import { fromLegacy } from "$lib/modules/editor/core/document/doc";
+import {
+ collectIdsDoc,
+ defaultSim,
+ idValue,
+ previewSim,
+ timeParts,
+ type Sim,
+} from "$lib/modules/editor/core/document/sources";
+import { decodeAssets, regenPreviewAssets } from "$lib/modules/editor/core/render/pixels";
+import { renderDoc } from "$lib/modules/editor/core/render/render";
+import { editorModel } from "$lib/modules/editor/model";
+import { faceBin, imageNode, procNode, squares, type Proc } from "./proc-face";
+
+const SIM: Sim = { ...defaultSim(), live: false, time: new Date(2026, 0, 8, 10, 9).getTime() };
+
+async function draw(proc: Proc, count: number, sim: Partial = {}) {
+ const images = Array.from({ length: count }, (_, i) => i);
+ const { doc } = fromLegacy(parseBin(faceBin([procNode({ ...proc, images })], squares(count))));
+ const cache = await decodeAssets(doc.images);
+ const c = document.createElement("canvas");
+
+ c.width = c.height = 466;
+ const ctx = c.getContext("2d")!;
+ const store = { assets: doc.images, cache };
+ const hits = renderDoc(ctx, doc, store, "main", { ...SIM, ...sim });
+ const red = (x: number, y: number) => {
+ const [r, , , a] = ctx.getImageData(x, y, 1, 1).data;
+
+ return a ? r : null;
+ };
+
+ return { red, hits, doc, store };
+}
+/** What a square of `squares()` reads back as after RGB565. */
+const redOf = (img: number) => Math.floor(((((img * 3) % 256) >> 3) * 255) / 31);
+
+describe("DataPulse's panels", () => {
+ test("weather: the 'now' label in its column, none in the corner", async () => {
+ const { red, hits } = await draw({ type: 6, sub: 0 }, 88);
+
+ expect(red(1, 1)).toBeNull();
+ expect(red(95, 52)).toBe(redOf(0x27));
+ expect(hits).toHaveLength(1);
+ expect([hits[0].x, hits[0].y]).toEqual([94, 51]);
+ expect(hits[0].w).toBeLessThan(340);
+ });
+
+ test.each([1, 2, 3])("panel %i: the axis and bars over it", async (sub) => {
+ const { red, hits } = await draw({ type: 6, sub }, 13);
+
+ expect(red(1, 1)).toBeNull();
+ expect(red(81, 296)).toBe(redOf(10));
+ expect(hits[0].h).toBeGreaterThan(20);
+ });
+
+ test("sleep: the start time's first digit", async () => {
+ const { red } = await draw({ type: 6, sub: 4 }, 13, { sleep: 480 }); // 23:00 to 07:00
+
+ expect(red(92, 379)).toBe(redOf(2));
+ });
+
+ // DataPulse's lower panels each sit in a group, which centres a child at x 0 by its size:
+ // that size is the widget's own box, not the ink in it
+ test("inside a full-screen group it stays where the watch puts it", async () => {
+ const images = Array.from({ length: 13 }, (_, i) => i);
+ const group = {
+ tag: 0x68,
+ subs: [{ tag: 0x48, hex: "00000000d201d20100" }, procNode({ type: 6, sub: 1, images })],
+ };
+ const { doc } = fromLegacy(parseBin(faceBin([group], squares(13))));
+ const cache = await decodeAssets(doc.images);
+ const ctx = new OffscreenCanvas(466, 466).getContext("2d")!;
+ const hits = renderDoc(ctx, doc, { assets: doc.images, cache }, "main", SIM);
+
+ expect(hits[0].x).toBe(80);
+ });
+
+ test("the thumbnail baked on save has the panel", async () => {
+ const { doc, store } = await draw({ type: 6, sub: 0 }, 88);
+ const [baked] = [...(await regenPreviewAssets(doc, store, previewSim(SIM))).values()];
+ const k = baked.asset.w / 466;
+ const c = new OffscreenCanvas(baked.asset.w, baked.asset.h);
+ const ctx = c.getContext("2d")!;
+
+ ctx.drawImage(baked.bitmap, 0, 0);
+ // the weather's rows, well away from the corner
+ const d = ctx.getImageData(80 * k, 45 * k, 310 * k, 120 * k).data;
+
+ expect(d.some((v, i) => i % 4 === 1 && v > 0)).toBe(true);
+ });
+});
+
+test("Luminous Beam: the percent along the dial, not in the corner", async () => {
+ const { red, hits } = await draw({ type: 7 }, 10, { calories: 210, calGoal: 500 });
+
+ expect(red(1, 1)).toBeNull();
+ expect(red(277, 334)).toBe(redOf(2));
+ expect(red(261, 340)).toBe(redOf(4));
+ expect(hits).toHaveLength(1);
+});
+
+describe("Rainbow Lollipop", () => {
+ const ringTop = 233 - 23;
+
+ test("draws nothing until it is touched", async () => {
+ expect((await draw({ type: 4 }, 0)).red(233, ringTop)).toBeNull();
+ });
+
+ test("lights the ring under the finger", async () => {
+ const { red, hits } = await draw({ type: 4 }, 0, { touch: { x: 250, y: 233 } });
+
+ expect(red(233, ringTop)).toBeGreaterThan(200);
+ expect(red(233, 233)).toBeNull();
+ expect(hits).toEqual([]); // a full-screen box would swallow every click
+ });
+});
+
+describe("Briqbot", () => {
+ test("rests on the end of its first clip", async () => {
+ expect((await draw({ type: 5 }, 159)).red(1, 1)).toBe(redOf(39));
+ });
+
+ test("plays the clip a tap started", async () => {
+ const now = Date.now();
+
+ expect((await draw({ type: 5 }, 159, { clip: 1, clipAt: now })).red(1, 1)).toBeLessThanOrEqual(
+ redOf(45),
+ );
+ expect((await draw({ type: 5 }, 159, { clip: 1, clipAt: now - 60_000 })).red(1, 1)).toBe(
+ redOf(89),
+ );
+ });
+});
+
+test("the simulator offers what a widget reads", () => {
+ const ids = (p: Proc) =>
+ collectIdsDoc(fromLegacy(parseBin(faceBin([procNode(p)]))).doc).map(({ id }) => id);
+
+ expect(ids({ type: 6, sub: 0 })).toEqual([0x5f]);
+ expect(ids({ type: 6, sub: 1 })).toEqual([0x1a]);
+ expect(ids({ type: 6, sub: 2 })).toEqual([0x1b]);
+ expect(ids({ type: 6, sub: 3 })).toEqual([0x8c]);
+ expect(ids({ type: 6, sub: 4 })).toEqual([0x46]);
+ expect(ids({ type: 7 })).toEqual([0x1c]);
+});
+
+test("source 0x99 is the colour theme", () => {
+ expect(idValue(0x99, { ...SIM, theme: 3 }, timeParts(SIM))).toBe(3);
+});
+
+// 3 Pro's getter reads the night's minutes as they are (0x101D2CD2)
+test("source 0x93 is the minutes of last night's sleep", () => {
+ expect(idValue(0x93, { ...SIM, sleep: 7 * 60 + 36 }, timeParts(SIM))).toBe(36);
+});
+
+test("a published preview carries no touch and no clip", () => {
+ const p = previewSim({ ...SIM, touch: { x: 1, y: 2 }, clip: 2, clipAt: 5 });
+
+ expect([p.touch, p.clip, p.clipAt]).toEqual([null, 0, null]);
+});
+
+describe("clicking the preview", () => {
+ const open = async (bin: Uint8Array) => {
+ editorModel.loadRequested({ buf: bin, label: "proc" });
+ await vi.waitFor(() => expect(editorModel.$loading.getState()).toBe(false));
+ };
+
+ test("press and release light and clear a ring", async () => {
+ await open(faceBin([procNode({ type: 4 })]));
+ editorModel.watchPressed({ x: 250, y: 233 });
+ expect(editorModel.$sim.getState().touch).toEqual({ x: 250, y: 233 });
+ editorModel.watchReleased();
+ expect(editorModel.$sim.getState().touch).toBeNull();
+ });
+
+ test("a tap starts the next clip", async () => {
+ await open(faceBin([procNode({ type: 5, images: [0] })], squares(1)));
+ editorModel.watchTapped(1000);
+ expect(editorModel.$sim.getState()).toMatchObject({ clip: 1, clipAt: 1000 });
+ editorModel.watchTapped(2000);
+ expect(editorModel.$sim.getState()).toMatchObject({ clip: 2, clipAt: 2000 });
+ });
+
+ test("a face without such widgets leaves the simulator alone", async () => {
+ await open(faceBin([imageNode([0])], squares(1)));
+ const before = editorModel.$sim.getState();
+
+ editorModel.watchPressed({ x: 1, y: 2 });
+ editorModel.watchTapped(3000);
+ expect(editorModel.$sim.getState()).toBe(before);
+ });
+});
diff --git a/tests/wp3-corpus.test.ts b/tests/wp3-corpus.test.ts
new file mode 100644
index 0000000..6c38606
--- /dev/null
+++ b/tests/wp3-corpus.test.ts
@@ -0,0 +1,43 @@
+// The whole chain over local face files, which are the vendor's and never committed.
+//
+// FMC_WP3_FACES=~/Downloads/wp3-faces-for-wp2/wp3-original Watch 3 Pro originals
+// FMC_WP2_FACES=/path/to/stock/watchfaces/files Watch Pro 2 stock faces
+// npx vitest run --project unit wp3-corpus
+import { readdirSync, readFileSync } from "node:fs";
+import { describe, expect, test } from "vitest";
+import { assertFlashable, buildBin, hex, parseBin } from "$lib/modules/editor/core/format";
+import { assertWatchCompat } from "$lib/modules/editor/core/format/compat";
+import { fromLegacy, toLegacy } from "$lib/modules/editor/core/document/doc";
+
+const corpus = (dir: string | undefined) =>
+ dir
+ ? readdirSync(dir)
+ .filter((f) => f.endsWith(".bin"))
+ .sort()
+ .map((name): [string, Uint8Array] => [name, new Uint8Array(readFileSync(`${dir}/${name}`))])
+ : [];
+
+describe.each([
+ ["watch_3_pro", process.env.FMC_WP3_FACES],
+ ["watch_pro_2", process.env.FMC_WP2_FACES],
+] as const)("local faces for %s", (device, dir) => {
+ test.skipIf(!dir)("open and save byte for byte", () => {
+ const files = corpus(dir);
+ const broken = files.filter(
+ ([, bin]) => hex(buildBin(toLegacy(fromLegacy(parseBin(bin)).doc))) !== hex(bin),
+ );
+
+ expect(files.length).toBeGreaterThan(0);
+ expect(broken.map(([name]) => name)).toEqual([]);
+ });
+
+ test.skipIf(!dir)("still install on the watch they were made for", async () => {
+ for (const [name, bin] of corpus(dir)) {
+ expect(() => assertFlashable(bin, device), name).not.toThrow();
+ await expect(
+ assertWatchCompat(bin, device, async () => null),
+ name,
+ ).resolves.toBeUndefined();
+ }
+ });
+});
diff --git a/tests/wp3-roundtrip.test.ts b/tests/wp3-roundtrip.test.ts
new file mode 100644
index 0000000..cfbe376
--- /dev/null
+++ b/tests/wp3-roundtrip.test.ts
@@ -0,0 +1,71 @@
+// Opening and saving a Watch 3 Pro face loses nothing. Synthetic shapes here; the owner's files
+// in tests/wp3-corpus.test.ts.
+import { expect, test } from "vitest";
+import { buildBin, hex, parseBin, TAG } from "$lib/modules/editor/core/format";
+import { fromLegacy, toLegacy } from "$lib/modules/editor/core/document/doc";
+import { withName } from "$lib/modules/editor/core/document/factory";
+import type { FaceNode } from "$lib/modules/editor/core/format/raw";
+import { faceBin, metaHex, procNode, squares } from "./proc-face";
+
+const saved = (bin: Uint8Array) => buildBin(toLegacy(fromLegacy(parseBin(bin)).doc));
+
+// a payload of zeroes reads as a run of empty tags: 0x5c with 24 of them was dropped on save
+test.each([3, 6, 9, 24, 25, 27])("a 0x5c of %i bytes survives saving", (len) => {
+ const bin = faceBin([procNode({ type: 6, len, images: [0] })], squares(1));
+
+ expect(hex(saved(bin))).toBe(hex(bin));
+});
+
+test.each([
+ [0x83, 0x5d],
+ [0x84, 0x5e],
+ [0x89, 0x63],
+])("widget tag %i keeps a body (%i) that reads as tags", (tag, body) => {
+ const node: FaceNode = {
+ tag,
+ subs: [
+ { tag: TAG.struct, x: 1, y: 2, meta: metaHex(), tail: "0000" },
+ { tag: body, hex: "010000000000" },
+ ],
+ };
+ const bin = faceBin([node]);
+
+ expect(hex(saved(bin))).toBe(hex(bin));
+});
+
+// two stock faces (Sun Circle, SlopeTime) have no 0x86 title and used to gain one
+test("a face with no title node doesn't gain one", () => {
+ const bin = faceBin([procNode({ type: 4 })], [], { title: false });
+
+ expect(hex(saved(bin))).toBe(hex(bin));
+});
+
+test("until it is renamed", () => {
+ const { doc } = fromLegacy(parseBin(faceBin([procNode({ type: 4 })], [], { title: false })));
+ const title = toLegacy(withName(doc, "Renamed")).screens[0].subs?.find(
+ (n) => n.tag === TAG.name,
+ )?.text;
+
+ expect(title).toBe("Renamed");
+});
+
+test("a face built here, not read from a file, still gets its title", () => {
+ const { doc } = fromLegacy({
+ name: "Imported",
+ screens: [{ tag: TAG.main, subs: [] }],
+ resources: [],
+ });
+
+ expect(toLegacy(doc).screens[0].subs?.[0]).toEqual({ tag: TAG.name, text: "Imported" });
+});
+
+test("an importer's face, which carries a header, gets its title too", () => {
+ const { doc } = fromLegacy({
+ name: "Imported",
+ nameRaw: "496d706f7274656400000000000000" + "0a",
+ screens: [{ tag: TAG.main, subs: [] }],
+ resources: [],
+ });
+
+ expect(toLegacy(doc).screens[0].subs?.[0]).toEqual({ tag: TAG.name, text: "Imported" });
+});