Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion toaster-oven/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -84,14 +88,17 @@ 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.

## 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
Expand Down
45 changes: 45 additions & 0 deletions toaster-oven/src/components/ImportFilesButton.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ref } from 'vue'
import { importFiles, type ImportSummary } from '@/state/import/import-files'

const emit = defineEmits<{ imported: [summary: ImportSummary] }>()

const input = ref<HTMLInputElement>()

async function onChange() {
const picked = [...(input.value?.files ?? [])]
// Clear it so picking the same file again still triggers a change
if (input.value) input.value.value = ''
if (!picked.length) return

const files = await Promise.all(picked.map(async (f) => ({ name: f.name, text: await f.text() })))
const summary = importFiles(files, () =>
confirm("Importing will replace changes you haven't downloaded. Continue?"),
)
if (summary.imported.length || summary.errors.length) emit('imported', summary)
}
</script>

<template>
<button
type="button"
class="btn btn-secondary px-5 py-2.5 text-base"
title="Import Config.h or Protogen_Faces.h you downloaded before"
@click="input?.click()"
>
<!-- Upload icon -->
<svg class="size-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path
d="M9.25 13.25a.75.75 0 0 0 1.5 0V4.636l2.955 3.129a.75.75 0 0 0 1.09-1.03l-4.25-4.5a.75.75 0 0 0-1.09 0l-4.25 4.5a.75.75 0 1 0 1.09 1.03L9.25 4.636v8.614Z"
/>
<path
d="M3.5 12.75a.75.75 0 0 0-1.5 0v2.5A2.75 2.75 0 0 0 4.75 18h10.5A2.75 2.75 0 0 0 18 15.25v-2.5a.75.75 0 0 0-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5Z"
/>
</svg>
<span class="flex flex-col items-start leading-tight">
<span>Import</span>
<span class="text-xs font-normal opacity-75">.h files</span>
</span>
</button>
<input ref="input" type="file" accept=".h" multiple class="hidden" @change="onChange" />
</template>
12 changes: 11 additions & 1 deletion toaster-oven/src/state/config-download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export const DOWNLOADS: Record<DownloadKind, { fileName: string; label: string }

const KINDS = Object.keys(DOWNLOADS) as DownloadKind[]

/** Written into downloaded files. Bump it when the generated format changes */
const FORMAT_VERSION = 1

function generateFiles(
face: typeof appStore.faceConfig,
features: typeof appStore.featureConfig,
Expand Down Expand Up @@ -61,7 +64,14 @@ function formatTimestamp(date: Date): string {
export function downloadFile(kind: DownloadKind) {
const contents = currentFiles.value[kind]
// The timestamp is only added to the downloaded file, so it doesn't count as a change
const stamped = `// Generated by Toaster Oven on ${formatTimestamp(new Date())}\n\n${contents}`
const stamped =
`// Generated by Toaster Oven on ${formatTimestamp(new Date())}\n` +
`// Toaster Oven format: ${FORMAT_VERSION}\n\n${contents}`
downloadBlob(DOWNLOADS[kind].fileName, new Blob([stamped], { type: 'text/plain' }))
lastDownloaded.value = { ...lastDownloaded.value, [kind]: contents }
}

/** Treat the current state as already downloaded, e.g. after importing that same file */
export function markDownloaded(kind: DownloadKind) {
lastDownloaded.value = { ...lastDownloaded.value, [kind]: currentFiles.value[kind] }
}
7 changes: 7 additions & 0 deletions toaster-oven/src/state/expression-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,10 @@ function step(from: typeof undoStack, to: typeof undoStack) {

export const undo = () => 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 = []
}
99 changes: 99 additions & 0 deletions toaster-oven/src/state/import/import-files.ts
Original file line number Diff line number Diff line change
@@ -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<typeof readConfig> }
| { kind: 'expressions'; name: string; result: ReturnType<typeof readFaces> }

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<DownloadKind, Read>()

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 }
}
170 changes: 170 additions & 0 deletions toaster-oven/src/state/import/read-config.ts
Original file line number Diff line number Diff line change
@@ -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<T> = (text: string) => T | undefined
type Parser<T> = (value: string) => T | undefined

const number: Parser<number> = (v) => {
const n = Number(v)
return v !== '' && Number.isFinite(n) ? n : undefined
}

const int: Parser<number> = (v) => (/^-?\d+$/.test(v) ? Number(v) : undefined)

const bool: Parser<boolean> = (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<T>(name: string, parse: Parser<T>): Reader<T> {
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<T>(name: string, parse: Parser<T>): Reader<T> {
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<K extends keyof FeatureConfig> {
key: K
/** Shown in the import summary when the setting falls back to its default */
label: string
readers: Reader<FeatureConfig[K]>[]
}

function setting<K extends keyof FeatureConfig>(
key: K,
label: string,
readers: Reader<FeatureConfig[K]>[],
): Setting<K> {
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<keyof FeatureConfig, (typeof SETTINGS)[number]['key']>
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<typeof key, typeof value>)[key] = value
}

const connections = readConnections(text)
if (!connections) defaulted.push(PANEL_LAYOUT_LABEL)

return {
faceConfig: connections ? { connections } : defaultFaceConfig(),
featureConfig,
defaulted,
}
}
Loading
Loading