// 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))