A terminal and keyboard parts: text out on a rising WR (CLR clears), keys typed in waiting on D0-D7 with RDY, NEXT takes one

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 13:05:57 +01:00
parent 52aea3fe96
commit 2be845030e
13 changed files with 469 additions and 2 deletions

View File

@ -6026,3 +6026,59 @@ button.tile:hover {
.asm-load .hint { .asm-load .hint {
margin: 0; margin: 0;
} }
/* Terminal and keyboard */
.node .term-screen {
fill: #050807;
stroke: #1f2a24;
}
.node .term-text {
fill: #6ff0a0;
font-family: var(--font-mono);
font-size: 11px;
white-space: pre;
pointer-events: none;
}
.node .term-cursor {
fill: #6ff0a0;
opacity: 0.7;
animation: term-blink 1s steps(1) infinite;
pointer-events: none;
}
@keyframes term-blink {
50% {
opacity: 0;
}
}
.node .kb-body.typing {
stroke: var(--accent);
stroke-width: 2;
}
.node .kb-keys rect {
fill: #232c38;
stroke: #3b4554;
stroke-width: 1;
}
.node .kb-state {
fill: var(--muted);
font-size: 9px;
pointer-events: none;
}
.node .kb-body.typing ~ .kb-state {
fill: var(--accent);
}
.node .kb-queue {
fill: var(--text);
font-family: var(--font-mono);
font-size: 11px;
white-space: pre;
pointer-events: none;
}

View File

@ -11,6 +11,7 @@ import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { latchLayout, latchSeam } from '~/lib/logic/latch' import { latchLayout, latchSeam } from '~/lib/logic/latch'
import { probeAt } from '~/lib/logic/probes' import { probeAt } from '~/lib/logic/probes'
import { keyCode } from '~/lib/logic/devices'
import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move' import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move'
import { wirePath, type HopSpan } from '~/lib/draw' import { wirePath, type HopSpan } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet' import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
@ -711,6 +712,8 @@ function onPointerDown(e: PointerEvent) {
} }
if (e.button !== 0) return if (e.button !== 0) return
root.value!.setPointerCapture(e.pointerId) root.value!.setPointerCapture(e.pointerId)
// A click anywhere but the keyboard being typed into stops the typing.
if (ed.typingInto.value && (e.target as Element).closest?.('[data-node]')?.getAttribute('data-node') !== ed.typingInto.value) ed.typeInto(null)
const link = ed.linking.value const link = ed.linking.value
const end = link?.queue[link.at] const end = link?.queue[link.at]
@ -835,7 +838,7 @@ function onPointerDown(e: PointerEvent) {
at: [0, 0], at: [0, 0],
moved: false, moved: false,
node, node,
toggle: (node.kind === 'input' || !!row) && !multi, toggle: (node.kind === 'input' || node.kind === 'keyboard' || !!row) && !multi,
row, row,
grabbed: selected.value.has(id) ? ed.selection.value.length : 1, grabbed: selected.value.has(id) ? ed.selection.value.length : 1,
} }
@ -1170,6 +1173,7 @@ function onPointerUp(e: PointerEvent) {
ed.unplugMoved(new Set(d.orig.nodes.keys())) ed.unplugMoved(new Set(d.orig.nodes.keys()))
ed.commit(false) ed.commit(false)
} else if (d.toggle && d.row) ed.toggleRow(d.node, d.row) } else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
else if (d.toggle && d.node.kind === 'keyboard') ed.typeInto(d.node.id)
else if (d.toggle) ed.toggleInput(d.node) else if (d.toggle) ed.toggleInput(d.node)
break break
case 'wire': { case 'wire': {
@ -1286,6 +1290,15 @@ function onKey(e: KeyboardEvent) {
} }
// Paused: the pause menu has the keys. // Paused: the pause menu has the keys.
if (ed.paused.value) return if (ed.paused.value) return
// Typing into a keyboard: the keys go there (Esc stops).
if (ed.typingInto.value) {
if (e.key === 'Escape') return ed.typeInto(null)
const code = keyCode(e)
if (code !== null) {
e.preventDefault()
return ed.typeKey(code)
}
}
const mod = e.ctrlKey || e.metaKey const mod = e.ctrlKey || e.metaKey
const key = e.key.toLowerCase() const key = e.key.toLowerCase()
if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) { if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {

View File

@ -3,6 +3,7 @@ import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables' import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide' import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry' import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry'
import { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices'
import type { CircuitNode } from '~/lib/logic/types' import type { CircuitNode } from '~/lib/logic/types'
const props = defineProps<{ const props = defineProps<{
@ -171,6 +172,25 @@ const faceHex = (inner: string) => sevenSegment([0, 1, 2, 3].reduce((n, i) => n
/** The colour of an RGB pixel inside this chip ('' while off). */ /** The colour of an RGB pixel inside this chip ('' while off). */
const facePx = (inner: string) => rgbHex(fv(inner, 'r'), fv(inner, 'g'), fv(inner, 'b')) const facePx = (inner: string) => rgbHex(fv(inner, 'r'), fv(inner, 'g'), fv(inner, 'b'))
const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : '')) const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : ''))
// Terminal and keyboard: what the store keeps for this part.
const TERM_CHAR = 6.6
const termLines = computed(() => {
if (props.node.kind !== 'terminal' || props.ghost) return []
void ed.devVersion.value
return (ed.screens.value.get(props.node.id) ?? ['']).slice(-TERMINAL_LINES)
})
const termCursor = computed(() => {
const lines = termLines.value.length ? termLines.value : ['']
return { x: Math.min(TERMINAL_COLS - 1, lines[lines.length - 1]!.length), y: lines.length - 1 }
})
const kbTyping = computed(() => ed.typingInto.value === props.node.id)
const kbWaiting = computed(() => {
if (props.node.kind !== 'keyboard' || props.ghost) return []
void ed.devVersion.value
return [...(ed.keyQueues.value.get(props.node.id) ?? [])]
})
const kbQueue = computed(() => kbWaiting.value.slice(0, 6).map(keyLabel).join(''))
const kbCount = computed(() => (kbWaiting.value.length ? `${kbWaiting.value.length} waiting` : ''))
const FACE_SCALE = 0.6 const FACE_SCALE = 0.6
const hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0)) const hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0))
const segments = computed(() => sevenSegment(hexValue.value)) const segments = computed(() => sevenSegment(hexValue.value))
@ -401,6 +421,30 @@ const title = computed(() => {
<text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text> <text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text>
</template> </template>
<!-- Terminal: a text screen the circuit writes to -->
<template v-else-if="node.kind === 'terminal'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body display" />
<rect :x="1.9 * G" :y="b.y * G + 3" :width="(b.w - 2.2) * G" :height="b.h * G - 6" rx="2" class="term-screen" />
<text v-for="(line, i) in termLines" :key="i" :x="2.1 * G" :y="i * G + 4" class="term-text">{{ line }}</text>
<rect :x="2.1 * G + termCursor.x * TERM_CHAR" :y="termCursor.y * G - 5" :width="TERM_CHAR" height="10" class="term-cursor" />
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
</template>
<!-- Keyboard: the keys you type, one at a time -->
<template v-else-if="node.kind === 'keyboard'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body kb-body" :class="{ typing: kbTyping }" />
<g :transform="`translate(${1.85 * G} ${0.4 * G})`" class="kb-keys">
<rect v-for="k in 9" :key="k" :x="((k - 1) % 3) * 0.75 * G" :y="Math.floor((k - 1) / 3) * 0.75 * G" :width="0.6 * G" :height="0.6 * G" rx="1.5" />
</g>
<text :x="2.9 * G" :y="3.4 * G" text-anchor="middle" class="kb-state">{{ kbTyping ? 'typing' : 'click, type' }}</text>
<text :x="2.9 * G" :y="4.6 * G" text-anchor="middle" class="kb-queue">{{ kbQueue }}</text>
<text :x="2.9 * G" :y="5.6 * G" text-anchor="middle" class="pin-label tiny">{{ kbCount }}</text>
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 4" :y="p.dy * G + 3" text-anchor="end" class="pin-label tiny">{{ p.label }}</text>
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
</template>
<!-- Pixel: one square of a screen --> <!-- Pixel: one square of a screen -->
<template v-else-if="node.kind === 'pixel'"> <template v-else-if="node.kind === 'pixel'">
<template v-if="node.rgb"> <template v-if="node.rgb">

View File

@ -26,6 +26,7 @@ import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide' import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { probeValue } from '~/lib/logic/probes' import { probeValue } from '~/lib/logic/probes'
import { bitsCode, codeBits, DATA_KEYS, KEY_QUEUE, putChar } from '~/lib/logic/devices'
import { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm' import { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library' import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
@ -421,6 +422,19 @@ function create() {
const circuitStats = ref<Stats>({ nands: 0, sequential: false, delay: 0 }) const circuitStats = ref<Stats>({ nands: 0, sequential: false, delay: 0 })
const pressed = new Set<string>() const pressed = new Set<string>()
// Terminals and keyboards (see "Text in and out" below).
/** What each terminal shows and the keys waiting in each keyboard, by part id; not saved. */
const screens = shallowRef(new Map<string, string[]>())
const keyQueues = shallowRef(new Map<string, number[]>())
/** Goes up when a screen or a queue changes. */
const devVersion = ref(0)
/** The keyboard the keys you type go into. */
const typingInto = ref<string | null>(null)
let devTerms: string[] = []
let devKbs: string[] = []
/** Each strobe pin's level when last looked at, to act on a rise. */
const levels = new Map<string, number>()
function rebuild() { function rebuild() {
const d = def.value const d = def.value
const nl = compile(getDef.value, d.id) const nl = compile(getDef.value, d.id)
@ -440,7 +454,14 @@ function create() {
} }
} }
} }
devTerms = d.nodes.filter(n => n.kind === 'terminal').map(n => n.id)
devKbs = d.nodes.filter(n => n.kind === 'keyboard').map(n => n.id)
if (!devKbs.includes(typingInto.value ?? '')) typingInto.value = null
for (const id of devKbs) feedKeyboard(id, s)
s.run(BUDGET) s.run(BUDGET)
// Where the strobes start: only a rise from here on acts.
for (const id of devTerms) for (const pin of ['wr', 'clr']) levels.set(`${id}:${pin}`, s.pin(id, pin))
for (const id of devKbs) levels.set(`${id}:next`, s.pin(id, 'next'))
if (simRoot !== key) cycles.value = 0 if (simRoot !== key) cycles.value = 0
sim.value = s sim.value = s
simRoot = key simRoot = key
@ -543,6 +564,83 @@ function create() {
} }
let raf = 0 let raf = 0
// ── Text in and out ───────────────────────────────────────────────
function rose(id: string, pin: string, v: number) {
const k = `${id}:${pin}`
const before = levels.get(k) ?? v
levels.set(k, v)
return v === 1 && before === 0
}
/** A keyboard's outputs: the first waiting key on D0–D7, RDY while there is one. */
function feedKeyboard(id: string, s = sim.value) {
if (!s) return
const q = keyQueues.value.get(id) ?? []
const bits = codeBits(q[0] ?? 0)
DATA_KEYS.forEach((k, i) => s.setSource(`${id}:${k}`, bits[i] === 1))
s.setSource(`${id}:rdy`, q.length > 0)
}
/** Acts on the strobes of terminals and keyboards; called whenever the circuit has settled. */
function devices() {
const s = sim.value
if (!s || (!devTerms.length && !devKbs.length)) return
let changed = false
for (const id of devTerms) {
if (rose(id, 'clr', s.pin(id, 'clr'))) {
screens.value.set(id, [''])
changed = true
}
if (rose(id, 'wr', s.pin(id, 'wr'))) {
screens.value.set(id, putChar(screens.value.get(id) ?? [], bitsCode(DATA_KEYS.map(k => s.pin(id, k)))))
changed = true
}
}
for (const id of devKbs) {
if (rose(id, 'next', s.pin(id, 'next'))) {
const q = keyQueues.value.get(id)
if (q?.length) {
q.shift()
feedKeyboard(id, s)
changed = true
}
}
}
if (changed) devVersion.value++
}
/** Starts (or stops) typing into a keyboard. */
function typeInto(id: string | null) {
typingInto.value = id && typingInto.value !== id ? id : null
}
/** A key typed into the keyboard being typed into. */
function typeKey(code: number) {
const id = typingInto.value
if (!id) return
const q = keyQueues.value.get(id) ?? []
if (q.length >= KEY_QUEUE) {
play('error')
return notify(`The keyboard holds ${KEY_QUEUE} keys: let the circuit take some (NEXT)`, 'error')
}
q.push(code)
keyQueues.value.set(id, q)
feedKeyboard(id)
devVersion.value++
}
function clearScreen(id: string) {
screens.value.set(id, [''])
devVersion.value++
}
function clearKeys(id: string) {
keyQueues.value.set(id, [])
feedKeyboard(id)
devVersion.value++
}
// ── Logic analyzer ──────────────────────────────────────────────── // ── Logic analyzer ────────────────────────────────────────────────
/** The analyzer panel is open. */ /** The analyzer panel is open. */
const analyzerOpen = ref(false) const analyzerOpen = ref(false)
@ -630,6 +728,7 @@ function create() {
acc[i]! -= half acc[i]! -= half
s.run(BUDGET) s.run(BUDGET)
sample(true) sample(true)
devices()
if (s.toggleClock(i) && i === counted) rises++ if (s.toggleClock(i) && i === counted) rises++
} }
if (acc[i]! > half) acc[i] = 0 if (acc[i]! > half) acc[i] = 0
@ -638,6 +737,7 @@ function create() {
const end = performance.now() + 10 const end = performance.now() + 10
while (performance.now() < end) { while (performance.now() < end) {
if (!s.run(BUDGET)) break if (!s.run(BUDGET)) break
devices()
for (const i of fastest) if (s.toggleClock(i) && i === counted) rises++ for (const i of fastest) if (s.toggleClock(i) && i === counted) rises++
} }
} }
@ -649,7 +749,10 @@ function create() {
status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy' status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy'
if (s.changes !== lastChanges) { if (s.changes !== lastChanges) {
lastChanges = s.changes lastChanges = s.changes
if (settled) sample() if (settled) {
sample()
devices()
}
tick.value++ tick.value++
} }
} }
@ -669,13 +772,16 @@ function create() {
s.run(BUDGET) s.run(BUDGET)
} }
sample(true) sample(true)
devices()
s.setClock(1) s.setClock(1)
s.run(BUDGET) s.run(BUDGET)
cycles.value++ cycles.value++
sample(true) sample(true)
devices()
s.setClock(0) s.setClock(0)
s.run(BUDGET) s.run(BUDGET)
sample(true) sample(true)
devices()
tick.value++ tick.value++
} }
@ -2901,6 +3007,14 @@ function create() {
setRowsType, setRowsType,
setScreen, setScreen,
setRgb, setRgb,
screens,
keyQueues,
devVersion,
typingInto,
typeInto,
typeKey,
clearScreen,
clearKeys,
asmDoc, asmDoc,
saveAsm, saveAsm,
loadProgram, loadProgram,

View File

@ -147,6 +147,11 @@ export function useMenu() {
{ label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) }, { label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) },
) )
} }
if (n.kind === 'terminal') out.push({ label: 'Clear the screen', icon: 'lucide:eraser', run: () => ed.clearScreen(n.id) })
if (n.kind === 'keyboard') {
out.push({ label: ed.typingInto.value === n.id ? 'Stop typing' : 'Type into it', icon: 'lucide:keyboard', keys: 'Click', run: () => ed.typeInto(n.id) })
if (ed.keyQueues.value.get(n.id)?.length) out.push({ label: 'Forget the waiting keys', icon: 'lucide:eraser', run: () => ed.clearKeys(n.id) })
}
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) }) if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) { if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) {
const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in' const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in'

View File

@ -31,6 +31,7 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.', aka: 'oscillator tick' }, { kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.', aka: 'oscillator tick' },
{ kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour.', aka: 'switches buttons' }, { kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour.', aka: 'switches buttons' },
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.', aka: 'vcc high one supply' }, { kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.', aka: 'vcc high one supply' },
{ kind: 'keyboard', name: 'Keyboard', icon: 'lucide:keyboard', hint: 'Click it, then type: the first key waiting is on D0–D7 (its code), RDY is 1 while one waits, a rising NEXT takes it.', aka: 'text input ascii typing keys' },
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.', aka: 'gnd low zero' }, { kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.', aka: 'gnd low zero' },
], ],
}, },
@ -41,6 +42,7 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.', aka: 'led light' }, { kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.', aka: 'led light' },
{ kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of named lamps. Inside a component its rows are output pins.', aka: 'lamps leds' }, { kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of named lamps. Inside a component its rows are output pins.', aka: 'lamps leds' },
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F, and passes them on.', aka: 'seven segment 7seg digit' }, { kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F, and passes them on.', aka: 'seven segment 7seg digit' },
{ kind: 'terminal', name: 'Terminal', icon: 'lucide:square-terminal', hint: 'A text screen: a rising WR writes the character whose code is on D0–D7 (10 starts a new line, 8 goes back); a rising CLR clears it.', aka: 'text output ascii console screen print' },
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1, or in colour with red, green and blue inputs. Pixels inside a component show on its box as screens.', aka: 'screen lcd rgb colour color monitor' }, { kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1, or in colour with red, green and blue inputs. Pixels inside a component show on its box as screens.', aka: 'screen lcd rgb colour color monitor' },
], ],
}, },

View File

@ -3,6 +3,7 @@
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH. // merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
import { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry' import { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
import { DATA_KEYS } from './devices'
import type { CircuitNode, ComponentDef, Wire } from './types' import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0 export const LOW = 0
@ -53,6 +54,10 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return ['a'] return ['a']
case 'hex': case 'hex':
return ['b0', 'b1', 'b2', 'b3'] return ['b0', 'b1', 'b2', 'b3']
case 'terminal':
return [...DATA_KEYS, 'wr', 'clr']
case 'keyboard':
return ['next']
case 'outpanel': case 'outpanel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
case 'bundle': case 'bundle':
@ -91,6 +96,8 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out'), ...lineKeys(node, pins, get, false)] : [] return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out'), ...lineKeys(node, pins, get, false)] : []
case 'hex': case 'hex':
return ['q0', 'q1', 'q2', 'q3'] return ['q0', 'q1', 'q2', 'q3']
case 'keyboard':
return [...DATA_KEYS, 'rdy']
case 'panel': case 'panel':
case 'outpanel': case 'outpanel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
@ -247,6 +254,10 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
case 'button': case 'button':
if (!inNets) sources.set(n.id, q) if (!inNets) sources.set(n.id, q)
break break
case 'keyboard':
// The keys typed, in the open circuit; inside a component it is all 0.
if (!inNets) for (const k of outputKeys(n)) sources.set(`${n.id}:${k}`, outNet.get(`${n.id}:${k}`)!)
break
case 'high': case 'high':
union(q, HIGH) union(q, HIGH)
break break

71
app/lib/logic/devices.ts Normal file
View File

@ -0,0 +1,71 @@
// Text in and out: a terminal shows the characters a circuit writes, a
// keyboard hands it the keys you type. Both act on the rising edge of a pin
// (WR, CLR, NEXT), the way a real chip latches on a strobe, and only in the
// circuit you have open (inside a component they do nothing).
/** Data pins, bit 0 first: one character code, 8 bits. */
export const DATA_KEYS = ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7']
export const TERMINAL_COLS = 32
export const TERMINAL_LINES = 10
/** Lines a terminal keeps (what scrolled out of view is gone after these). */
const KEEP = 200
/** Keys a keyboard holds before it drops new ones. */
export const KEY_QUEUE = 64
export const DEVICE_PIN_NAMES: Record<string, string> = {
...Object.fromEntries(DATA_KEYS.map((k, i) => [k, `D${i}`])),
wr: 'WR',
clr: 'CLR',
next: 'NEXT',
rdy: 'RDY',
}
/**
* A terminal's text after one more character: printable codes from 32 (in
* Latin-1), 10 a new line, 13 back to the line's start, 8 one back, 9 to the
* next multiple of 4, 12 a clear screen; other control codes do nothing.
* Lines wrap at the terminal's width.
*/
export function putChar(lines: string[], code: number, cols = TERMINAL_COLS): string[] {
const out = lines.length ? [...lines] : ['']
const last = () => out[out.length - 1]!
const set = (s: string) => (out[out.length - 1] = s)
if (code === 12) return ['']
if (code === 10) out.push('')
else if (code === 13) set('')
else if (code === 8) set(last().slice(0, -1))
else if (code === 9) {
const n = 4 - (last().length % 4)
for (let i = 0; i < n; i++) {
if (last().length >= cols) out.push('')
set(last() + ' ')
}
} else if (code >= 32 && code !== 127 && code < 256) {
if (last().length >= cols) out.push('')
set(last() + String.fromCharCode(code))
}
return out.length > KEEP ? out.slice(out.length - KEEP) : out
}
/** The code a key press types, or null for keys that type nothing. */
export function keyCode(e: { key: string; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean }): number | null {
if (e.metaKey || e.altKey) return null
if (e.ctrlKey) return e.key.length === 1 && /[a-z]/i.test(e.key) ? e.key.toUpperCase().charCodeAt(0) - 64 : null
if (e.key === 'Enter') return 10
if (e.key === 'Backspace') return 8
if (e.key === 'Tab') return 9
if (e.key === 'Delete') return 127
if (e.key.length !== 1) return null
const c = e.key.charCodeAt(0)
return c < 256 ? c : null
}
/** A key's code as data bits. */
export const codeBits = (code: number) => DATA_KEYS.map((_, i) => (code >> i) & 1)
/** Data bits as a code. */
export const bitsCode = (bits: number[]) => bits.reduce((v, b, i) => v + (b ? 1 << i : 0), 0)
/** How a key waiting in a keyboard shows. */
export const keyLabel = (code: number) => (code === 10 ? '⏎' : code === 8 ? '⌫' : code === 9 ? '⇥' : code === 32 ? '␣' : code < 32 || code === 127 ? '·' : String.fromCharCode(code))

View File

@ -2,6 +2,7 @@
// (x, y). Pins always sit on whole grid points so straight wires line up. // (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types' import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
export const GRID = 16 export const GRID = 16
@ -720,6 +721,18 @@ const PIXEL_RGB_SHAPE: Shape = {
outputs: [], outputs: [],
} }
const TERMINAL_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 15, h: 10 },
inputs: [...DATA_KEYS, 'wr', 'clr'].map((key, i) => ({ key, label: DEVICE_PIN_NAMES[key]!, dx: 0, dy: i })),
outputs: [],
}
const KEYBOARD_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 7, h: 9 },
inputs: [{ key: 'next', label: 'NEXT', dx: 0, dy: 8 }],
outputs: [...DATA_KEYS, 'rdy'].map((key, i) => ({ key, label: DEVICE_PIN_NAMES[key]!, dx: 7, dy: i })),
}
/** Grid offset of every panel row below the first one. */ /** Grid offset of every panel row below the first one. */
export function panelOffsets(rows: PanelRow[]): number[] { export function panelOffsets(rows: PanelRow[]): number[] {
const out: number[] = [] const out: number[] = []
@ -816,6 +829,10 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
return cableShape(node) return cableShape(node)
case 'pixel': case 'pixel':
return node.rgb ? PIXEL_RGB_SHAPE : PIXEL_SHAPE return node.rgb ? PIXEL_RGB_SHAPE : PIXEL_SHAPE
case 'terminal':
return TERMINAL_SHAPE
case 'keyboard':
return KEYBOARD_SHAPE
case 'outpanel': case 'outpanel':
return outPanelShape(node) return outPanelShape(node)
case 'tag': case 'tag':

View File

@ -3,6 +3,7 @@
// name of the component pin it is wired to. // name of the component pin it is wired to.
import { chipPins, splitLines, type DefLookup } from './geometry' import { chipPins, splitLines, type DefLookup } from './geometry'
import { DEVICE_PIN_NAMES } from './devices'
import type { CircuitNode, ComponentDef, NodeKind } from './types' import type { CircuitNode, ComponentDef, NodeKind } from './types'
const SERIES = /^(.*?)(\d+)$/ const SERIES = /^(.*?)(\d+)$/
@ -82,6 +83,7 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
} }
// A wire of a cable carries the name of its signal (the cable pin itself has none). // A wire of a cable carries the name of its signal (the cable pin itself has none).
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
if (node.kind === 'terminal' || node.kind === 'keyboard') return DEVICE_PIN_NAMES[pin]
if (node.kind !== 'chip' || !node.chip) return undefined if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip) const def = get(node.chip)
// A line of a port split on the box: port.line, named after the line. // A line of a port split on the box: port.line, named after the line.

View File

@ -28,6 +28,8 @@ export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
portout: 'Connector out', portout: 'Connector out',
tag: 'Send signal', tag: 'Send signal',
ref: 'Use signal', ref: 'Use signal',
terminal: 'Terminal',
keyboard: 'Keyboard',
} }
/** Challenges each one builds on. */ /** Challenges each one builds on. */
@ -59,6 +61,8 @@ export const KIND_UNLOCK: Partial<Record<NodeKind, string>> = {
outpanel: 'and', outpanel: 'and',
hex: 'dec2', hex: 'dec2',
pixel: 'dec2', pixel: 'dec2',
terminal: 'dec2',
keyboard: 'dec2',
bundle: 'add2', bundle: 'add2',
split: 'add2', split: 'add2',
portin: 'add2', portin: 'add2',

View File

@ -22,6 +22,8 @@ export type BuiltinKind =
| 'portout' // the same, where a cable goes out | 'portout' // the same, where a cable goes out
| 'tag' // gives the signal wired into it a name (its label) | 'tag' // gives the signal wired into it a name (its label)
| 'ref' // carries the signal of the tag with the same name in this circuit, without a wire | 'ref' // carries the signal of the tag with the same name in this circuit, without a wire
| 'terminal' // a text screen: writes the character on D0–D7 at a rising WR, clears at a rising CLR
| 'keyboard' // the keys you type: the first waiting one on D0–D7, RDY while one waits, a rising NEXT takes it
export type NodeKind = BuiltinKind | 'chip' export type NodeKind = BuiltinKind | 'chip'

126
tests/devices.test.ts Normal file
View File

@ -0,0 +1,126 @@
// The terminal and the keyboard: the text a terminal keeps, the codes keys
// type, and both running in the real editor, a button strobing them.
import * as vue from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { DATA_KEYS, keyCode, putChar } from '../app/lib/logic/devices'
import { createProject, lookup } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
import { saveProject, setCurrentId } from '../app/lib/logic/storage'
import type { ComponentDef, Project } from '../app/lib/logic/types'
const type = (s: string, cols = 32) => [...s].reduce((lines, c) => putChar(lines, c.charCodeAt(0), cols), [''])
describe('terminal text', () => {
it('prints, breaks lines, goes back, clears', () => {
expect(type('Hi\nyou')).toEqual(['Hi', 'you'])
expect(type('abc\b\bX')).toEqual(['aX'])
expect(type('abcdef', 4)).toEqual(['abcd', 'ef'])
expect(type('a\tb')).toEqual(['a b'])
expect(type('one\rtwo')).toEqual(['two'])
expect(type('junk\fok')).toEqual(['ok'])
expect(type('\x01\x07x')).toEqual(['x'])
expect(putChar(['é'], 0xe9)).toEqual(['éé'])
})
it('keys type their codes', () => {
expect(keyCode({ key: 'a' })).toBe(97)
expect(keyCode({ key: 'Enter' })).toBe(10)
expect(keyCode({ key: 'Backspace' })).toBe(8)
expect(keyCode({ key: 'c', ctrlKey: true })).toBe(3)
expect(keyCode({ key: 'ArrowUp' })).toBeNull()
expect(keyCode({ key: '😀' })).toBeNull()
})
})
/** A keyboard wired straight to a terminal; button W writes the waiting key and takes it, C clears. */
function echoProject(): Project {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'echo',
name: 'Echo',
symbol: 'box',
nodes: [
{ id: 'kb', kind: 'keyboard', x: 0, y: 0 },
{ id: 'tm', kind: 'terminal', x: 12, y: 0 },
{ id: 'w', kind: 'button', x: 0, y: 14, label: 'W' },
{ id: 'c', kind: 'button', x: 0, y: 16, label: 'C' },
],
wires: [
...DATA_KEYS.map(k => ({ id: `d-${k}`, from: { node: 'kb', pin: k }, to: { node: 'tm', pin: k } })),
{ id: 'wr', from: { node: 'w', pin: 'q' }, to: { node: 'tm', pin: 'wr' } },
{ id: 'nx', from: { node: 'w', pin: 'q' }, to: { node: 'kb', pin: 'next' } },
{ id: 'cl', from: { node: 'c', pin: 'q' }, to: { node: 'tm', pin: 'clr' } },
],
}
p.components.push(def)
p.openId = def.id
return p
}
let store: Map<string, string>
beforeEach(() => {
store = new Map()
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
})
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
async function openEditor(p: Project) {
saveProject({ id: 'p1', name: p.name, updated: Date.now() }, p)
setCurrentId('p1')
const on = () => {}
vi.stubGlobal('window', { addEventListener: on })
vi.stubGlobal('document', { addEventListener: on, visibilityState: 'visible' })
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
vi.stubGlobal('history', { state: null, replaceState() {} })
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch', 'nextTick'] as const) vi.stubGlobal(k, vue[k])
vi.resetModules()
const { useEditor } = await import('../app/composables/useEditor')
return useEditor()
}
describe('keyboard and terminal in the editor', () => {
it('a rising WR writes the waiting key; NEXT takes it; CLR clears', async () => {
const ed = await openEditor(echoProject())
vi.advanceTimersByTime(100)
const click = (label: string) => {
const n = ed.def.value.nodes.find(x => x.label === label)!
ed.press(n, true)
ed.step()
ed.press(n, false)
ed.step()
}
ed.typeInto('kb')
for (const c of 'Hi!') ed.typeKey(c.charCodeAt(0))
ed.typeKey(10)
ed.typeKey('o'.charCodeAt(0))
ed.sim.value!.run()
expect(ed.val('kb', 'rdy')).toBe(1)
for (let i = 0; i < 5; i++) click('W')
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
expect(ed.keyQueues.value.get('kb')).toEqual([])
expect(ed.val('kb', 'rdy')).toBe(0)
// Nothing waiting: a strobe writes code 0, which shows nothing.
click('W')
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
click('C')
expect(ed.screens.value.get('tm')).toEqual([''])
})
it('inside a component a keyboard gives 0 and a terminal does nothing', () => {
const p = echoProject()
p.components.push({ id: 'outer', name: 'Outer', symbol: 'box', nodes: [{ id: 'e', kind: 'chip', chip: 'echo', x: 0, y: 0 }], wires: [] })
const s = new Simulator(compile(lookup(p), 'outer'))
s.run()
expect(s.nl.sources.size).toBe(0)
})
})