browser

clock-repl.xyw

clock-repl.xyw
calendarsave
.include "lib/macros.xyw"

; Clock REPL - demonstrates simultaneous keypress + timer handling.
; The prompt shows a live clock [HH:MM:SS] that updates every second
; while accepting keyboard input. Type a line and press Enter to echo it.

; Main program: show initial prompt, register both handlers, halt
print-prompt JSRw
setup-handlers JSRw
HLT

.include "lib/putd.xyw"
.include "lib/puts.xyw"

; Register keypress and timer handlers, start 1-second timer
; ->
.label setup-handlers
  on-keypress terminal.on_keypress STW
  on-timer clock.on_timer STW
  $0100 clock.timer STW
  RTS

; Timer handler: redraw the prompt line with updated clock
; ->
.label on-timer
  redraw-line JSRw
  $0100 clock.timer STW
  RTS

; Keypress handler
; ->
.label on-keypress
  terminal.input LDB
  ; Enter
  DUP $0D EQU on-enter JCNw
  DUP $0A EQU on-enter JCNw
  ; Backspace (DEL or BS)
  DUP $7F EQU on-backspace JCNw
  DUP $08 EQU on-backspace JCNw
  ; Ignore non-printable
  DUP $20 LTH on-ignore JCNw
  ; Ignore if buffer full (48 chars)
  buf-len LDBw $30 EQU on-ignore JCNw
  ; Store char in buffer at buf[len]
  DUP
  buf-len LDBw $00 SWP buf ADDw STBw
  ; Increment length
  buf-len LDBw INC buf-len STBw
  ; Echo the character
  PUTC
  RTS

; b ->
.label on-ignore
  POP RTS

; Enter: echo back the line
; b ->
.label on-enter
  POP
  NL
  echo-prefix puts JSRw
  print-buffer JSRw
  NL
  ; Clear buffer
  $00 buf-len STBw
  ; Show fresh prompt
  print-prompt JSRw
  RTS

; Backspace: remove last character
; b ->
.label on-backspace
  POP
  buf-len LDBw $00 EQU on-backspace.done JCNw
  buf-len LDBw DEC buf-len STBw
  $08 PUTC $20 PUTC $08 PUTC
  .label on-backspace.done
    RTS

; Print the clock prompt: [HH:MM:SS] > 
; ->
.label print-prompt
  $5B PUTC
  clock.hour LDB ZEROPADx JSRw
  $3A PUTC
  clock.minute LDB ZEROPADx JSRw
  $3A PUTC
  clock.second LDB ZEROPADx JSRw
  $5D PUTC SP $3E PUTC SP
  RTS

; Redraw current line in-place: CR + prompt + buffer + clear-to-EOL
; ->
.label redraw-line
  $0D PUTC
  print-prompt JSRw
  print-buffer JSRw
  ; ANSI escape: ESC[K (clear to end of line)
  $1B PUTC $5B PUTC $4B PUTC
  RTS

; Print buffer contents (buf[0..len-1])
; ->
.label print-buffer
  buf POPxw
  buf-len LDBw POPy
  .label print-buffer.loop
    PSHy $00 EQU print-buffer.done JCNw
    LDBxw PUTC
    INCxw DECy
    print-buffer.loop JMPw
  .label print-buffer.done
    RTS

; Print 8-bit value with leading zero if < 10
; b ->
.label ZEROPADx
  POPx PSHx $0A LTH zeropad.zero JCNw
  .label zeropad.digit
    PSHx putd JSRw
    RTS
  .label zeropad.zero
    $30 PUTC
    zeropad.digit JMPw

; --- Data ---

.label echo-prefix
  .string ";< "

.label buf-len
  .byte $00

.label buf
  .byte $00 $00 $00 $00 $00 $00 $00 $00
  .byte $00 $00 $00 $00 $00 $00 $00 $00
  .byte $00 $00 $00 $00 $00 $00 $00 $00
  .byte $00 $00 $00 $00 $00 $00 $00 $00
  .byte $00 $00 $00 $00 $00 $00 $00 $00
  .byte $00 $00 $00 $00 $00 $00 $00 $00