diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 6bc5889..521b59c 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -6026,3 +6026,59 @@ button.tile:hover {
.asm-load .hint {
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;
+}
diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue
index 31e79a6..d570d1a 100644
--- a/app/components/editor/Canvas.vue
+++ b/app/components/editor/Canvas.vue
@@ -11,6 +11,7 @@ import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { latchLayout, latchSeam } from '~/lib/logic/latch'
import { probeAt } from '~/lib/logic/probes'
+import { keyCode } from '~/lib/logic/devices'
import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move'
import { wirePath, type HopSpan } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
@@ -711,6 +712,8 @@ function onPointerDown(e: PointerEvent) {
}
if (e.button !== 0) return
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 end = link?.queue[link.at]
@@ -835,7 +838,7 @@ function onPointerDown(e: PointerEvent) {
at: [0, 0],
moved: false,
node,
- toggle: (node.kind === 'input' || !!row) && !multi,
+ toggle: (node.kind === 'input' || node.kind === 'keyboard' || !!row) && !multi,
row,
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.commit(false)
} 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)
break
case 'wire': {
@@ -1286,6 +1290,15 @@ function onKey(e: KeyboardEvent) {
}
// Paused: the pause menu has the keys.
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 key = e.key.toLowerCase()
if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
diff --git a/app/components/editor/NodeView.vue b/app/components/editor/NodeView.vue
index fe2ed29..f1b94b0 100644
--- a/app/components/editor/NodeView.vue
+++ b/app/components/editor/NodeView.vue
@@ -3,6 +3,7 @@ import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
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 { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices'
import type { CircuitNode } from '~/lib/logic/types'
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). */
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')) : ''))
+// 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 hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0))
const segments = computed(() => sevenSegment(hexValue.value))
@@ -401,6 +421,30 @@ const title = computed(() => {
{{ node.conn && !connType ? 'type missing' : 'no lines' }}
+
+
+
+
+ {{ line }}
+
+ {{ p.label }}
+ {{ node.label }}
+
+
+
+
+
+
+
+
+ {{ kbTyping ? 'typing' : 'click, type' }}
+ {{ kbQueue }}
+ {{ kbCount }}
+ {{ p.label }}
+ {{ p.label }}
+ {{ node.label }}
+
+
diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts
index 3401ef7..0f7ca4c 100644
--- a/app/composables/useEditor.ts
+++ b/app/composables/useEditor.ts
@@ -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 { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
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 { 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'
@@ -421,6 +422,19 @@ function create() {
const circuitStats = ref({ nands: 0, sequential: false, delay: 0 })
const pressed = new Set()
+ // 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())
+ const keyQueues = shallowRef(new Map())
+ /** Goes up when a screen or a queue changes. */
+ const devVersion = ref(0)
+ /** The keyboard the keys you type go into. */
+ const typingInto = ref(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()
+
function rebuild() {
const d = def.value
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)
+ // 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
sim.value = s
simRoot = key
@@ -543,6 +564,83 @@ function create() {
}
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 ────────────────────────────────────────────────
/** The analyzer panel is open. */
const analyzerOpen = ref(false)
@@ -630,6 +728,7 @@ function create() {
acc[i]! -= half
s.run(BUDGET)
sample(true)
+ devices()
if (s.toggleClock(i) && i === counted) rises++
}
if (acc[i]! > half) acc[i] = 0
@@ -638,6 +737,7 @@ function create() {
const end = performance.now() + 10
while (performance.now() < end) {
if (!s.run(BUDGET)) break
+ devices()
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'
if (s.changes !== lastChanges) {
lastChanges = s.changes
- if (settled) sample()
+ if (settled) {
+ sample()
+ devices()
+ }
tick.value++
}
}
@@ -669,13 +772,16 @@ function create() {
s.run(BUDGET)
}
sample(true)
+ devices()
s.setClock(1)
s.run(BUDGET)
cycles.value++
sample(true)
+ devices()
s.setClock(0)
s.run(BUDGET)
sample(true)
+ devices()
tick.value++
}
@@ -2901,6 +3007,14 @@ function create() {
setRowsType,
setScreen,
setRgb,
+ screens,
+ keyQueues,
+ devVersion,
+ typingInto,
+ typeInto,
+ typeKey,
+ clearScreen,
+ clearKeys,
asmDoc,
saveAsm,
loadProgram,
diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts
index a1ad8ee..71166da 100644
--- a/app/composables/useMenu.ts
+++ b/app/composables/useMenu.ts
@@ -147,6 +147,11 @@ export function useMenu() {
{ 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 (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) {
const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in'
diff --git a/app/composables/useParts.ts b/app/composables/useParts.ts
index d1a97a1..152e08e 100644
--- a/app/composables/useParts.ts
+++ b/app/composables/useParts.ts
@@ -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: '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: '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' },
],
},
@@ -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: '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: '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' },
],
},
diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts
index 271c18e..1f192e9 100644
--- a/app/lib/logic/compile.ts
+++ b/app/lib/logic/compile.ts
@@ -3,6 +3,7 @@
// 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 { DATA_KEYS } from './devices'
import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0
@@ -53,6 +54,10 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return ['a']
case 'hex':
return ['b0', 'b1', 'b2', 'b3']
+ case 'terminal':
+ return [...DATA_KEYS, 'wr', 'clr']
+ case 'keyboard':
+ return ['next']
case 'outpanel':
return (node.rows ?? []).map(r => r.id)
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)] : []
case 'hex':
return ['q0', 'q1', 'q2', 'q3']
+ case 'keyboard':
+ return [...DATA_KEYS, 'rdy']
case 'panel':
case 'outpanel':
return (node.rows ?? []).map(r => r.id)
@@ -247,6 +254,10 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
case 'button':
if (!inNets) sources.set(n.id, q)
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':
union(q, HIGH)
break
diff --git a/app/lib/logic/devices.ts b/app/lib/logic/devices.ts
new file mode 100644
index 0000000..25578f6
--- /dev/null
+++ b/app/lib/logic/devices.ts
@@ -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 = {
+ ...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))
diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts
index e65a777..c9d3471 100644
--- a/app/lib/logic/geometry.ts
+++ b/app/lib/logic/geometry.ts
@@ -2,6 +2,7 @@
// (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 { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
export const GRID = 16
@@ -720,6 +721,18 @@ const PIXEL_RGB_SHAPE: Shape = {
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. */
export function panelOffsets(rows: PanelRow[]): number[] {
const out: number[] = []
@@ -816,6 +829,10 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
return cableShape(node)
case 'pixel':
return node.rgb ? PIXEL_RGB_SHAPE : PIXEL_SHAPE
+ case 'terminal':
+ return TERMINAL_SHAPE
+ case 'keyboard':
+ return KEYBOARD_SHAPE
case 'outpanel':
return outPanelShape(node)
case 'tag':
diff --git a/app/lib/logic/labels.ts b/app/lib/logic/labels.ts
index fd32990..d361486 100644
--- a/app/lib/logic/labels.ts
+++ b/app/lib/logic/labels.ts
@@ -3,6 +3,7 @@
// name of the component pin it is wired to.
import { chipPins, splitLines, type DefLookup } from './geometry'
+import { DEVICE_PIN_NAMES } from './devices'
import type { CircuitNode, ComponentDef, NodeKind } from './types'
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).
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
const def = get(node.chip)
// A line of a port split on the box: port.line, named after the line.
diff --git a/app/lib/logic/progress.ts b/app/lib/logic/progress.ts
index 2958b28..7e10eb8 100644
--- a/app/lib/logic/progress.ts
+++ b/app/lib/logic/progress.ts
@@ -28,6 +28,8 @@ export const KIND_NAMES: Partial> = {
portout: 'Connector out',
tag: 'Send signal',
ref: 'Use signal',
+ terminal: 'Terminal',
+ keyboard: 'Keyboard',
}
/** Challenges each one builds on. */
@@ -59,6 +61,8 @@ export const KIND_UNLOCK: Partial> = {
outpanel: 'and',
hex: 'dec2',
pixel: 'dec2',
+ terminal: 'dec2',
+ keyboard: 'dec2',
bundle: 'add2',
split: 'add2',
portin: 'add2',
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index 386888c..ffa4300 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -22,6 +22,8 @@ export type BuiltinKind =
| 'portout' // the same, where a cable goes out
| '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
+ | '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'
diff --git a/tests/devices.test.ts b/tests/devices.test.ts
new file mode 100644
index 0000000..5c34fc8
--- /dev/null
+++ b/tests/devices.test.ts
@@ -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
+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)
+ })
+})