diff --git a/toaster-oven/AGENTS.md b/toaster-oven/AGENTS.md index eb6a7ca..7cf9a9b 100644 --- a/toaster-oven/AGENTS.md +++ b/toaster-oven/AGENTS.md @@ -45,6 +45,10 @@ src/ expressions.ts Expression type, defaults, naming/validation helpers expression-editor.ts Selected expression + undo/redo stacks (module state, survives tab switches) pin-usage.ts Detects digital pins assigned twice + import/ + read-config.ts Config.h -> state. A list of readers per setting, newest format first + read-faces.ts Protogen_Faces.h -> expressions. Adds back missing required expressions + import-files.ts Detects each file's type, applies it in place, builds the import summary faces/ faces.ts Parses the presets from assets/Protogen_Faces.h. mirror(), expressionToPanels() parse-faces.ts Regex parser for `struct FaceExpression Face_X = {...}` blocks @@ -84,6 +88,8 @@ src/ - `required-expressions.ts` - the copy at `src/assets/Protogen_Faces.h` +**Keep old downloads importable.** Users import files they downloaded earlier, possibly from an older version of the site. When the generated format changes, add a reader for the new format at the front of that setting's list in `import/read-config.ts` and keep the old ones. Bump `FORMAT_VERSION` in `config-download.ts`. Settings no reader finds fall back to their defaults and are listed in the import summary. + **Default panel layout differs on purpose.** The app starts with the first preset in `FACE_LAYOUT_PRESETS` (14 panels, one connection). `../ToasterOS/Config.h` keeps the two-connection layout, which is the `14-two` preset. Don't change either to match the other. To check a generator, render the defaults and diff the output against the firmware file. Expect the panel layout to differ unless you pick the `14-two` preset first. `vite`'s `createServer` + `ssrLoadModule` can load the TS modules from a Node script. @@ -91,7 +97,8 @@ To check a generator, render the defaults and diff the output against the firmwa ## State and downloads - All state is in memory. **Nothing persists across a refresh yet.** Saving is planned as "projects" (multiple saved configurations to switch between). Keep state serialisable: plain objects, number bitmaps, and numeric ids on expressions. -- `config-download.ts` regenerates both files reactively and compares each with its text at the last download, starting from the defaults. The download buttons, nav dot and sticky reminder all use `changedDownloads` / `hasChanged(kind)`. +- `config-download.ts` regenerates both files reactively and compares each with its text at the last download, starting from the defaults. The download buttons, nav dot and sticky reminder all use `changedDownloads` / `hasChanged(kind)`. A clean import counts as a download (`markDownloaded`). +- The Configure views hold references to `appStore.faceConfig`, `featureConfig` and `expressions`. Update them in place (assign properties, `splice`), never replace the objects. - Undo/redo covers LED edits and adding or removing a blink, not renames or removals. ## Design conventions diff --git a/toaster-oven/src/components/ImportFilesButton.vue b/toaster-oven/src/components/ImportFilesButton.vue new file mode 100644 index 0000000..bf925c3 --- /dev/null +++ b/toaster-oven/src/components/ImportFilesButton.vue @@ -0,0 +1,45 @@ + + + diff --git a/toaster-oven/src/state/config-download.ts b/toaster-oven/src/state/config-download.ts index cd96c96..1d4943f 100644 --- a/toaster-oven/src/state/config-download.ts +++ b/toaster-oven/src/state/config-download.ts @@ -14,6 +14,9 @@ export const DOWNLOADS: Record step(undoStack, redoStack) export const redo = () => step(redoStack, undoStack) + +/** Start fresh after the expressions are replaced, e.g. by an import */ +export function resetEditor() { + selectedExpressionId.value = appStore.expressions[0]!.id + undoStack.value = [] + redoStack.value = [] +} diff --git a/toaster-oven/src/state/import/import-files.ts b/toaster-oven/src/state/import/import-files.ts new file mode 100644 index 0000000..2e01270 --- /dev/null +++ b/toaster-oven/src/state/import/import-files.ts @@ -0,0 +1,99 @@ +import { appStore } from '../app-state' +import { hasChanged, markDownloaded, type DownloadKind } from '../config-download' +import { resetEditor } from '../expression-editor' +import { readConfig } from './read-config' +import { readFaces } from './read-faces' + +// Imports Config.h and/or Protogen_Faces.h files downloaded from Toaster Oven earlier. +// Each file replaces its part of the app state. + +export interface ImportSummary { + /** Names of the files that were imported */ + imported: string[] + /** Things the user should know, e.g. settings that fell back to defaults */ + notes: string[] + errors: string[] +} + +/** Works out which file this is from its contents, as it may have been renamed */ +export function detectKind(text: string): DownloadKind | null { + if (text.includes('ProtoConfigStruct') || text.includes('FaceConfig::FaceConfig')) { + return 'config' + } + if (text.includes('struct FaceExpression Face_')) return 'expressions' + return null +} + +type Read = + | { kind: 'config'; name: string; result: ReturnType } + | { kind: 'expressions'; name: string; result: ReturnType } + +function read(kind: DownloadKind, name: string, text: string): Read { + return kind === 'config' + ? { kind, name, result: readConfig(text) } + : { kind, name, result: readFaces(text) } +} + +function defaultedNote(fileName: string, labels: string[]): string { + if (labels.length === 1) { + return `1 setting wasn't in ${fileName}, so it uses the default: ${labels[0]}` + } + return `${labels.length} settings weren't in ${fileName}, so they use defaults: ${labels.join(', ')}` +} + +/** + * Reads the files and applies them. `confirmReplace` is asked first if an import would + * replace changes that haven't been downloaded; returning false cancels the whole import. + */ +export function importFiles( + files: { name: string; text: string }[], + confirmReplace: () => boolean, +): ImportSummary { + const errors: string[] = [] + const reads = new Map() + + for (const { name, text } of files) { + const kind = detectKind(text) + if (!kind) { + errors.push(`Couldn't find a config or expressions in ${name}.`) + continue + } + try { + reads.set(kind, read(kind, name, text)) // A later file of the same kind wins + } catch (e) { + errors.push(`Couldn't read ${name}: ${e instanceof Error ? e.message : String(e)}`) + } + } + + if ([...reads.keys()].some((kind) => hasChanged(kind)) && !confirmReplace()) { + return { imported: [], notes: [], errors: [] } + } + + const imported: string[] = [] + const notes: string[] = [] + + for (const r of reads.values()) { + imported.push(r.name) + let upToDate: boolean + + // Update in place: the Configure views hold references to these objects + if (r.kind === 'config') { + appStore.faceConfig.connections = r.result.faceConfig.connections + Object.assign(appStore.featureConfig, r.result.featureConfig) + if (r.result.defaulted.length) notes.push(defaultedNote(r.name, r.result.defaulted)) + upToDate = r.result.defaulted.length === 0 + } else { + appStore.expressions.splice(0, appStore.expressions.length, ...r.result.expressions) + resetEditor() + if (r.result.added.length) { + notes.push(`Added missing expressions the firmware needs: ${r.result.added.join(', ')}`) + } + upToDate = r.result.added.length === 0 + } + + // The user already has this file, unless something had to be filled in + if (upToDate) markDownloaded(r.kind) + } + + return { imported, notes, errors } +} diff --git a/toaster-oven/src/state/import/read-config.ts b/toaster-oven/src/state/import/read-config.ts new file mode 100644 index 0000000..681da0b --- /dev/null +++ b/toaster-oven/src/state/import/read-config.ts @@ -0,0 +1,170 @@ +import { defaultFaceConfig, defaultFeatureConfig } from '../config-defaults' +import { + EMPTY_PANEL, + PANEL_TYPES, + type FaceConfig, + type FaceLEDConnection, + type FeatureConfig, + type PanelConfig, +} from '../config-types' + +// Reads a Config.h that Toaster Oven downloaded earlier, possibly from an older version. +// +// Each setting has a list of readers, newest format first. When the generated format +// changes, add a reader for the new format at the front and keep the old ones, so older +// downloads still import. Settings that no reader finds fall back to the default. + +type Reader = (text: string) => T | undefined +type Parser = (value: string) => T | undefined + +const number: Parser = (v) => { + const n = Number(v) + return v !== '' && Number.isFinite(n) ? n : undefined +} + +const int: Parser = (v) => (/^-?\d+$/.test(v) ? Number(v) : undefined) + +const bool: Parser = (v) => { + if (v === 'true' || v === '1') return true + if (v === 'false' || v === '0') return false + return undefined +} + +/** `.Name = value,` inside a struct initialiser */ +function structField(name: string, parse: Parser): Reader { + const pattern = new RegExp(`\\.${name}\\s*=\\s*([^,\\s}]+)`) + return (text) => { + const match = pattern.exec(text) + return match ? parse(match[1]!) : undefined + } +} + +/** `#define NAME value` */ +function define(name: string, parse: Parser): Reader { + const pattern = new RegExp(`^[ \\t]*#define[ \\t]+${name}[ \\t]+(\\S+)`, 'm') + return (text) => { + const match = pattern.exec(text) + return match ? parse(match[1]!) : undefined + } +} + +interface Setting { + key: K + /** Shown in the import summary when the setting falls back to its default */ + label: string + readers: Reader[] +} + +function setting( + key: K, + label: string, + readers: Reader[], +): Setting { + return { key, label, readers } +} + +const SETTINGS = [ + setting('pinLeftLEDStripData', 'Left strip data pin', [define('PIN_LEFT_LEDSTRIP_DATA', int)]), + setting('pinRightLEDStripData', 'Right strip data pin', [define('PIN_RIGHT_LEDSTRIP_DATA', int)]), + setting('ledStripNumLEDs', 'LEDs per strip', [define('LEDSTRIP_NUM_LEDS', int)]), + setting('pinRemoteControlOutput', 'Output LED pin', [define('PIN_REMOTECONTROL_OUTPUT', int)]), + setting('rapidPanelAutoRecovery', 'Rapid panel auto-recovery', [ + define('RAPID_PANEL_AUTORECOVERY', bool), + ]), + setting('brightness', 'Brightness', [structField('Brightness', number)]), + setting('debugMode', 'Debug mode', [structField('DebugMode', int)]), + setting('enableBoopSensor', 'Boop sensor', [structField('EnableBoopSensor', bool)]), + setting('pinAnalogBoopSensor', 'Boop sensor analog pin', [ + structField('PinAnalogBoopSensor', int), + ]), + setting('numBoopsToActivateGame', 'Boops to activate game', [ + structField('NumBoopsToActivateGame', int), + ]), + setting('enableSideLEDs', 'Side LED strips', [structField('EnableSideLEDs', bool)]), + setting('enableRemoteControl', 'Remote control', [structField('EnableRemoteControl', bool)]), + setting('pinRemoteButtonA', 'Remote button A pin', [structField('PinRemoteButtonA', int)]), + setting('pinRemoteButtonB', 'Remote button B pin', [structField('PinRemoteButtonB', int)]), + setting('pinRemoteButtonC', 'Remote button C pin', [structField('PinRemoteButtonC', int)]), + setting('pinRemoteButtonD', 'Remote button D pin', [structField('PinRemoteButtonD', int)]), + setting('enableRemoteControlOutputLEDs', 'Remote control output LEDs', [ + structField('EnableRemoteControlOutputLEDs', bool), + ]), +] + +// Fails the build if a FeatureConfig setting has no readers, so it can't be silently defaulted +type SettingsWithoutReaders = Exclude +const everySettingHasReaders: [SettingsWithoutReaders] extends [never] + ? true + : SettingsWithoutReaders = true +void everySettingHasReaders + +const PANEL_LAYOUT_LABEL = 'Panel layout' + +function readPanelType(value: string): number | undefined { + if (/^-?\d+$/.test(value)) { + const id = Number(value) + return id === EMPTY_PANEL || PANEL_TYPES.some((p) => p.id === id) ? id : undefined + } + return PANEL_TYPES.find((p) => p.define === value)?.id +} + +/** The panel connections in `FaceConfig::FaceConfig() { ... }`, or undefined if unreadable */ +function readConnections(text: string): FaceLEDConnection[] | undefined { + const start = text.indexOf('FaceConfig::FaceConfig') + if (start === -1) return undefined + + // Each connection starts at its .PIN_DataIn and runs until the next one + const blocks = text + .slice(start) + .split(/(?=\.PIN_DataIn\s*=)/) + .slice(1) + if (blocks.length === 0) return undefined + + const connections: FaceLEDConnection[] = [] + for (const block of blocks) { + const pinDataIn = structField('PIN_DataIn', int)(block) + const pinCS = structField('PIN_CS', int)(block) + const pinCLK = structField('PIN_CLK', int)(block) + if (pinDataIn === undefined || pinCS === undefined || pinCLK === undefined) return undefined + + const panels: PanelConfig[] = [] + for (const m of block.matchAll( + /\{\s*\.PanelType\s*=\s*([\w-]+)\s*,\s*\.UpsideDown\s*=\s*(\w+)\s*,?\s*\}/g, + )) { + const panelType = readPanelType(m[1]!) + const upsideDown = bool(m[2]!) + if (panelType === undefined || upsideDown === undefined) return undefined + panels.push({ panelType, upsideDown }) + } + connections.push({ pinDataIn, pinCS, pinCLK, panels }) + } + return connections +} + +export function readConfig(text: string): { + faceConfig: FaceConfig + featureConfig: FeatureConfig + defaulted: string[] +} { + const featureConfig = defaultFeatureConfig() + const defaulted: string[] = [] + + for (const { key, label, readers } of SETTINGS) { + let value: FeatureConfig[typeof key] | undefined + for (const read of readers) { + value = read(text) + if (value !== undefined) break + } + if (value === undefined) defaulted.push(label) + else (featureConfig as Record)[key] = value + } + + const connections = readConnections(text) + if (!connections) defaulted.push(PANEL_LAYOUT_LABEL) + + return { + faceConfig: connections ? { connections } : defaultFaceConfig(), + featureConfig, + defaulted, + } +} diff --git a/toaster-oven/src/state/import/read-faces.ts b/toaster-oven/src/state/import/read-faces.ts new file mode 100644 index 0000000..43c8350 --- /dev/null +++ b/toaster-oven/src/state/import/read-faces.ts @@ -0,0 +1,25 @@ +import { defaultExpression } from '@/faces/faces' +import { parseExpressions } from '@/faces/parse-faces' +import { REQUIRED_EXPRESSIONS } from '@/faces/required-expressions' +import { createExpression, displayName, type Expression } from '../expressions' + +// Reads a Protogen_Faces.h that Toaster Oven downloaded earlier. +// Expressions the firmware needs but the file doesn't have are added back from the defaults, +// so the generated file still compiles. + +export function readFaces(text: string): { expressions: Expression[]; added: string[] } { + const parsed = parseExpressions(text) + if (parsed.length === 0) throw new Error('No expressions found') + + const expressions = parsed.map((e) => createExpression(e.name, e)) + const names = new Set(parsed.map((e) => e.name)) + const added: string[] = [] + + for (const name of Object.keys(REQUIRED_EXPRESSIONS)) { + if (names.has(name)) continue + expressions.push(createExpression(name, defaultExpression(name))) + added.push(displayName(name)) + } + + return { expressions, added } +} diff --git a/toaster-oven/src/views/ConfigureView.vue b/toaster-oven/src/views/ConfigureView.vue index 770873d..451632a 100644 --- a/toaster-oven/src/views/ConfigureView.vue +++ b/toaster-oven/src/views/ConfigureView.vue @@ -3,12 +3,14 @@ import { computed, ref, watch } from 'vue' import { RouterLink, RouterView, useRoute } from 'vue-router' import PageHeading from '@/components/PageHeading.vue' import DownloadConfigButton from '@/components/DownloadConfigButton.vue' +import ImportFilesButton from '@/components/ImportFilesButton.vue' import { DOWNLOADS, changedDownloads, downloadFile, hasUndownloadedChanges, } from '@/state/config-download' +import type { ImportSummary } from '@/state/import/import-files' const tabs = [ { to: '/configure/panels', label: 'Panel layout' }, @@ -29,6 +31,29 @@ const reminderHidden = ref(false) watch(hasUndownloadedChanges, (changed) => { if (!changed) reminderHidden.value = false }) + +// What the last import did, until dismissed +const importSummary = ref<(ImportSummary & { at: Date }) | null>(null) + +function onImported(summary: ImportSummary) { + importSummary.value = { ...summary, at: new Date() } +} + +/** e.g. "24 Nov, 14:03:12", so an old summary is easy to tell apart from a new one */ +const importedAt = computed(() => + importSummary.value?.at.toLocaleString(undefined, { + day: 'numeric', + month: 'short', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }), +) +const importNeedsAttention = computed( + () => + !!importSummary.value && + (importSummary.value.notes.length > 0 || importSummary.value.errors.length > 0), +)