
\ -----------------------------------------------------------------------------
\  Text mode with character buffer
\ -----------------------------------------------------------------------------

$60000000 constant characters
$60001000 constant glyphs

: font! ( x addr -- ) glyphs     + c! ;
: font@ ( addr -- x ) glyphs     + c@ ;

: char! ( x addr -- ) characters + c! ;
: char@ ( addr -- x ) characters + c@ ;

\ -----------------------------------------------------------------------------
\   Character handling for text mode
\ -----------------------------------------------------------------------------

100 constant xres
 37 constant yres

0 variable xpos
0 variable ypos

0 variable textmarker

: highlight ( -- )  $80 textmarker ! ;
: normal    ( -- )    0 textmarker ! ;

0 variable captionchars

: caption ( -- ) \ Fix caption lines when scrolling
  ypos @ xres * xpos @ + captionchars !
;

: nocaption ( -- ) 0 captionchars ! ; \ Remove caption protection

: page ( -- ) \ Clear display
  xres yres * captionchars @ do 32 i char! loop
  captionchars @ xres /mod ypos ! xpos !
;

: clrscr ( -- ) page ; \ Just an intuitive alias for page

: addline ( -- )
  ypos @ yres 1- < if
    1 ypos +!
  else
    captionchars @ xres +  characters +
    captionchars @         characters +
    xres yres * captionchars @ - xres -
    move

    xres yres 1- * characters + xres 32 fill
  then
  0 xpos !
;

: addchar ( c -- )
  textmarker @ or
  xpos @ xres 1- > if addline 0 xpos ! then
  ypos @ xres * xpos @ + char!
  1 xpos +!
;

: stepback ( -- )
  xpos @
  if
    -1 xpos +!
  else
    ypos @ if -1 ypos +! xres 1- xpos ! then
  then
;

: hdmi-emit ( c -- )
  case
    10 of addline  endof \ Line Feed
     8 of stepback endof \ Backspace
    dup $C0 and $80 <>
    if dup 127 umin addchar then \ Display block glyph for UTF-8 chars.
  endcase
;
