Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Capstone: a Cross-Platform Notepad

The other capstones run in a terminal. This one has windows. tpad is a plain-text editor in the shape of the Notepad that comes with an operating system: a menu bar, a page of text, a status bar, the usual keys, and a question before it throws away unsaved work.

It is built on tkControls, the vendor package of controls that draw into SDL3 windows, and one source builds and runs on Windows, Linux and macOS. Much of it is about text files rather than windows, and most of what is interesting about the windows is the short list of things that differ from one system to the next: a file dialog that does not stop your code, a text control that counts in bytes, a command key that is not always Ctrl, and a Quit that arrives from the system and never touches your window. It joins:

  • modules and a package (Chapter 15), with the part that needs no window kept apart from the part that does;
  • procedure pointers and lambdas (Chapters 7 and 21), which is how every control reports back;
  • new and delete for state that lives as long as a window (Chapter 11);
  • files, text encodings and atomic writes through std/fs (Chapters 9 and 25);
  • text as units and as bytes (Chapter 9);
  • a C library's callback, and the thread it may arrive on (Chapters 23 and 30);
  • conditional compilation by platform (Chapter 16);
  • tiko build, and what a program built on shared libraries takes with it (Chapter 31).

tpad on tkControls, a short file open, in the dark theme.

The specification

tpad [file]
tpad --selftest
tpad --shot out.bmp [file]
  • One window: a menu bar, the text, a vertical scroll bar beside it, and a status bar.
  • It runs on Windows, Linux and macOS, from one source with no per-platform files.
  • File: New (Ctrl+N), Open (Ctrl+O), Save (Ctrl+S), Save As (Ctrl+Shift+S), Exit. Edit: Undo, Cut, Copy, Paste and Select All, on their usual keys; Find (Ctrl+F) and Find Next (F3).
  • The command key is Cmd on macOS and Ctrl elsewhere, for tpad's own keys and the text box's, and the menus say which.
  • Text is UTF-8. A file keeps the line ending it was written with, CR LF or LF, and its byte-order mark if it had one, when it is saved. A file with no line break is saved with CR LF. A file that is not UTF-8 opens with U+FFFD in place of what could not be read, and tpad says so. Selection, Find and the line and column are right after accented letters and other characters that are not ASCII.
  • The status bar shows the caret's line and column, the line ending, and the encoding.
  • The title bar shows the file's name, with a * in front while there are unsaved changes.
  • Before anything throws away unsaved text — New, Open, closing the window, or the system's own Quit, such as Cmd+Q on a Mac or a logout — tpad asks: Save, Don't Save, or Cancel.
  • Find ignores case unless asked not to, and wraps around from the end to the top.
  • --selftest drives the window with nobody at it, prints what happened, and exits.
  • --shot renders the window once and saves it as a picture, so that two systems can be compared.

The layout

ch36/
    tiko.toml               the package, and the target tpad
    textfile/textfile.tiko  the document: load, save, find, line and column
    filetest.tiko           textfile on its own, on every target
    offsets/offsets.tiko    UTF-8 bytes and ustring units
    offsettest.tiko         offsets on its own, on every target
    pad/pad.tiko            the window: controls, menus, commands
    tpad.tiko               the program, and its self-test

The rule is the one from Chapter 33: the part that does not need a window does not import one. Everything tpad knows about text files is in textfile, which imports std/fs and std/strings and nothing from tkControls, and offsets imports nothing at all. Each is tested by a program that prints. pad is the window, and tpad.tiko starts it.

# tpad on tkControls: `tiko build tpad` writes out/debug/tpad
[package]
name = "tpad"

[target.tpad]
main = "tpad.tiko"

That is the whole manifest, and nothing in it names a platform.

The document

#module "textfile"
#import "std/fs"
#import "std/strings"
'' Nothing here knows about windows: this module is tested on its
'' own, on every target, by a program that prints.
public enum LineEnding
    CrLf
    Lf
end enum

'' A text file as the editor sees it. Inside, every line break is one
'' LF, counted as one character, as the editor control counts it too.
public type Document
    as ustring path             '' "" until the first Save As
    as ustring text
    as LineEnding ending = LineEnding.CrLf
    as boolean hasBom           '' the file began with a byte-order mark
    as boolean lossy            '' some bytes were not UTF-8
end type

A Document is what was read from the file, and what is needed to write it back the same way: its path, its text, its line ending, and whether it began with a byte-order mark. lossy records that some of its bytes could not be read. (The module is textfile and not document because a module may not export a name it shares, in any case, with its own: TKO0870: public 'document' has the same name as its module 'document'.)

The comment on text is the most important line in the module. Inside a Document, a line break is one character, LF. Files do not agree on that, so the module converts at the edge. ToLf makes it true of any text, whatever its line breaks:

'' CR LF and a lone CR both become LF.
public function ToLf( byref s as const ustring ) as ustring
    return strings.Replace( strings.Replace( s, !"\r\n", !"\n" ), _
                            !"\r", !"\n" )
end function

A multiline tkTextBox keeps its text the same way: it turns a CR LF that is set or pasted into LF. A line break is one in the document and one in the box, so lines and line breaks agree between the two. Other characters are a different story, and a later section is about it.

Loading

'' Did the file start with a byte-order mark? Only its first three
'' bytes are read.
private function StartsWithBom( byref p as const ustring ) as boolean
    dim as fs.File f
    if f.OpenRead( p ).IsOk( ) = false then return false
    dim as ubyte b( 0 to 2 )
    var got = f.Read( @b( 0 ), 3 )
    if got.IsOk( ) = false then return false
    dim as longint n = got.Value( )
    if n >= 3 andalso b( 0 ) = &hEF andalso b( 1 ) = &hBB andalso _
       b( 2 ) = &hBF then return true
    return n >= 2 andalso b( 0 ) = &hFF andalso b( 1 ) = &hFE
end function

'' Reads a file into doc. Returns "" or what went wrong; on failure doc
'' is left as it was.
public function Load( byref p as const ustring, _
                      byref doc as Document ) as ustring
    var r = fs.ReadAllText( p )
    if r.IsOk( ) = false then return r.Failure( ).Message( )

    dim as Document d
    d.path = p
    dim as ustring raw = r.Value( )
    '' The first line break says how the file writes them.
    dim as int32 lf = instr( raw, !"\n" ), cr = instr( raw, !"\r" )
    if lf > 0 andalso cr <> lf - 1 then d.ending = LineEnding.Lf
    d.text = ToLf( raw )
    d.hasBom = StartsWithBom( p )
    d.lossy = instr( d.text, wchr( &hFFFD ) ) > 0
    doc = d
    return ""
end function

fs.ReadAllText does most of the work, and two things it does decide the rest of the function:

  • It removes a byte-order mark, UTF-8's or UTF-16's, and decodes what follows. That is what a program reading text wants, but an editor must write the mark back, so StartsWithBom opens the file and reads its first three bytes itself.
  • It replaces bytes that are not UTF-8 with U+FFFD, the replacement character, on every target. A file in an old 8-bit encoding opens, but its accented letters are gone from the text, and saving writes the replacement characters. Load records that in lossy, and the window warns before anyone edits the file.

The line ending is the file's first one: an LF with a CR before it means CR LF. A file that mixes the two is saved with the first kind throughout. Load fills a local Document and copies it to doc only when everything has worked, so a failed open leaves the document that was there.

Pitfall

fs.ReadAllBytes has a three-argument form, and it is not "read the first n bytes". The third argument is a limit: a file larger than it is refused with an error, and nothing is read.

fs.ReadAllBytes( p, head, 3 )    '' fails on any file over 3 bytes

The first draft of StartsWithBom was that line. It compiled, every file was "too large", the function returned false, and the byte-order mark was quietly dropped on every save. filetest caught it: its first file has a mark. Read a prefix with a File and Read, as the listing does.

Saving

'' Writes doc.text to doc.path in the file's own line ending. The old
'' file is replaced only once the new one is complete on disk.
public function Save( byref doc as Document ) as ustring
    dim as ustring s = doc.text
    if doc.ending = LineEnding.CrLf then
        s = strings.Replace( s, !"\n", !"\r\n" )
    end if
    if doc.hasBom then s = wchr( &hFEFF ) & s
    var r = fs.WriteAtomic( doc.path, s )
    if r.IsOk( ) = false then return r.Failure( ).Message( )
    return ""
end function

Save undoes what Load did: LF back to CR LF if that is how the file was written, and the mark back on the front. The mark is the character U+FEFF, which UTF-8 writes as the three bytes EF BB BF. fs.WriteAtomic writes a temporary file beside the real one and renames it into place only when the write is complete (Chapter 25), so a full disk or a crash in the middle of a save leaves the old file whole, never half of the new one.

Names, finding, line and column

'' The file's name without its folder, or "Untitled".
public function DisplayName( byref doc as Document ) as ustring
    if len( doc.path ) = 0 then return "Untitled"
    dim as int32 i = len( doc.path )
    do until i = 0
        dim as ustring c = mid( doc.path, i, 1 )
        if c = "\" orelse c = "/" then exit do
        i -= 1
    loop
    return mid( doc.path, i + 1 )
end function

'' The title bar: "*notes.txt - tpad" while there are unsaved changes.
public function Caption( byref doc as Document, _
                         byval modified as boolean ) as ustring
    return iif( modified, "*", "" ) & DisplayName( doc ) & " - tpad"
end function
'' The offset of the next match at or after start, wrapping around to
'' the top; -1 when there is none. Offsets count from 0, as the editor
'' control's do.
public function FindNext( byref text as const ustring, _
                          byref needle as const ustring, _
                          byval start as int32, _
                          byval matchCase as boolean ) as int32
    if len( needle ) = 0 then return -1
    dim as ustring hay = text, pin = needle
    if matchCase = false then
        hay = lcase( hay )
        pin = lcase( pin )
    end if
    dim as int32 at = instr( start + 1, hay, pin )
    if at = 0 then at = instr( hay, pin )
    return at - 1
end function

FindNext takes and returns offsets counted from 0, as a selection is, and converts at its edges: instr counts from 1. It searches from start to the end, then from the top, so a search always wraps around once. Without match case, it lowers the case of both strings and searches the copies; that keeps the offsets right, because lcase changes no string's length.

'' The 1-based line and column of an offset, for the status bar.
public sub LineColumn( byref text as const ustring, _
                       byval offset as int32, _
                       byref ln as int32, byref col as int32 )
    ln = 1
    dim as int32 lineStart = 1, at = instr( text, !"\n" )
    do until at = 0 orelse at > offset
        ln += 1
        lineStart = at + 1
        at = instr( at + 1, text, !"\n" )
    loop
    col = offset + 2 - lineStart
end sub

Testing it on every target

'' The textfile module on its own, with no window: load, find, the
'' status-bar numbers, and a save that keeps the file's own format.
#import "./textfile"
#import "std/fs"
#import "std/containers"

'' Writes exact bytes, so the test does not depend on how this source
'' file's own line endings were checked out.
sub WriteBytes( byref p as ustring, bytes( ) as ubyte )
    dim as containers.Array( of ubyte ) buf
    for each b in bytes
        buf.Push( b )
    next
    fs.WriteAllBytes( p, buf )
end sub

function HexOf( byref p as ustring ) as ustring
    dim as containers.Array( of ubyte ) buf
    fs.ReadAllBytes( p, buf )
    dim as ustring s
    for each b in buf
        s &= hex( b, 2 ) & " "
    next
    return rtrim( s )
end function

print "== a Windows file with a byte-order mark"
'' BOM, "Hi", CR LF, "hi there"
dim as ubyte win( ... ) = { &hEF, &hBB, &hBF, 72, 105, 13, 10, _
                            104, 105, 32, 116, 104, 101, 114, 101 }
WriteBytes( "win.tmp", win( ) )
dim as textfile.Document doc
print "load: ["; textfile.Load( "win.tmp", doc ); "]"
print "crlf: "; cbool( doc.ending = textfile.LineEnding.CrLf ); _
      ", bom: "; doc.hasBom; ", lossy: "; doc.lossy
print "length: "; len( doc.text ); ", title: "; _
      textfile.Caption( doc, false )

print "== finding"
dim as int32 at = textfile.FindNext( doc.text, "hi", 0, false )
print "'hi' from 0, any case:  "; at
at = textfile.FindNext( doc.text, "hi", at + 1, false )
print "next one:               "; at
at = textfile.FindNext( doc.text, "hi", at + 1, false )
print "next wraps to the top:  "; at
print "'hi' from 0, exact case:"; _
      textfile.FindNext( doc.text, "hi", 0, true )
print "'bye':                  "; _
      textfile.FindNext( doc.text, "bye", 0, false )

print "== line and column"
dim as int32 ln, col
dim as int32 offsets( ... ) = { 0, 2, 3, 11 }
for each offset as int32 in offsets
    textfile.LineColumn( doc.text, offset, ln, col )
    print "offset"; offset; " -> Ln"; ln; ", Col"; col
next

print "== save keeps the BOM and CR LF"
doc.text &= !"\nthird"
doc.path = "copy.tmp"
print "save: ["; textfile.Save( doc ); "] "; _
      textfile.Caption( doc, true )
print HexOf( "copy.tmp" )

print "== a Linux file that is not UTF-8"
'' "caf", the Latin-1 byte for e-acute, LF
dim as ubyte latin( ... ) = { 99, 97, 102, &hE9, 10 }
WriteBytes( "latin.tmp", latin( ) )
print "load: ["; textfile.Load( "latin.tmp", doc ); "]"
print "lf: "; cbool( doc.ending = textfile.LineEnding.Lf ); _
      ", bom: "; doc.hasBom; ", lossy: "; doc.lossy
print "last character: U+"; hex( asc( doc.text, 4 ), 4 )

print "== a file that is not there"
dim as ustring e = textfile.Load( "missing.tmp", doc )
print "refused: "; cbool( len( e ) > 0 ); ", doc kept: "; _
      textfile.DisplayName( doc )
== a Windows file with a byte-order mark
load: []
crlf: true, bom: true, lossy: false
length:  11, title: win.tmp - tpad
== finding
'hi' from 0, any case:   0
next one:                3
next wraps to the top:   0
'hi' from 0, exact case: 3
'bye':                  -1
== line and column
offset 0 -> Ln 1, Col 1
offset 2 -> Ln 1, Col 3
offset 3 -> Ln 2, Col 1
offset 11 -> Ln 2, Col 9
== save keeps the BOM and CR LF
save: [] *copy.tmp - tpad
EF BB BF 48 69 0D 0A 68 69 20 74 68 65 72 65 0D 0A 74 68 69 72 64
== a Linux file that is not UTF-8
load: []
lf: true, bom: false, lossy: true
last character: U+FFFD
== a file that is not there
refused: true, doc kept: latin.tmp

The test writes its files byte by byte, so that what it reads does not depend on how this source file's own line endings were checked out. The Windows file keeps its mark and its CR LF through a load, an edit and a save. The Latin-1 file opens with LF, as lossy, with U+FFFD where the e-acute was. A file that is not there is refused, and doc still holds the file before it.

What a window is made of

#module "pad"
#import "../textfile"
#import "../offsets"
#import "vendor/tkControls/tkApp"
#import "vendor/tkControls/tkMenuBar"
#import "vendor/tkControls/tkPopupMenu"
#import "vendor/tkControls/tkTextBox"
#import "vendor/tkControls/tkVScrollBar"
#import "vendor/tkControls/tkStatusBar"
#import "vendor/tkControls/tkMessageBox"
#import "vendor/tkControls/tkButton"
#import "vendor/tkControls/tkCheckBox"

using tkApp
using tkHost
using tkPaint
using tkTheme
using tkMenuBar
using tkPopupMenu
using tkTextBox
using tkVScrollBar
using tkStatusBar
using tkMessageBox
using tkButton
using tkCheckBox

Each control is a module of its own, and a program imports the ones it uses. using makes their names bare, so a call is tkTextBox_SetText, as the package's documentation writes it, rather than tkTextBox.tkTextBox_SetText. tkApp is the application: it starts SDL, owns the windows and runs the event loop, and it brings tkHost and tkTheme, the layers under every control, with it.

A tkControls window is one SDL window, and everything in it is a TK_WIDGET: a record in a tree that the library draws and sends events to. A TK_FORM is the window itself. It reports what happens to it through procedure pointers set by tkForm_OnSize, tkForm_OnClose and the rest, each of which receives the form first. There is no handle to look up a control by, so the program keeps a pointer to each control it talks to:

'' Every command the menus and the keyboard can give.
public enum Cmd
    CmdNew = 1000
    CmdOpen
    CmdSave
    CmdSaveAs
    CmdExit
    CmdUndo
    CmdCut
    CmdCopy
    CmdPaste
    CmdSelectAll
    CmdFind
    CmdFindNext
end enum

'' The two things a person answers: a question in a message box, and
'' a file name in a file dialog. Each is reached through a pointer, so
'' a test can answer in the person's place.
public type AskProc as function( byval f as TK_FORM ptr, _
    byref text as ustring, byval buttons as long ) as long
public type PickProc as function( byval f as TK_FORM ptr, _
    byval saving as boolean, byref suggest as ustring ) as ustring

'' One open file and its window. The form's Tag points here.
public type Editor
    as TK_FORM ptr form
    as TK_WIDGET ptr bar, text, scroll, status
    as textfile.Document doc
    as ustring findWhat
    as boolean matchCase
    as boolean picking          '' a file dialog is waiting

    as AskProc ask
    as PickProc pick
end type

'' The Find box's controls. Its form's Tag points here.
type FindBox
    as Editor ptr ed
    as TK_WIDGET ptr what, matchCase, ok, cancel
end type

public declare sub Execute( byval ed as Editor ptr, byval id as long )
public declare sub ShowTitle( byval ed as Editor ptr )
public declare sub ShowStatus( byval ed as Editor ptr )

'' A control's callback receives only the control: its form's Tag is
'' the Editor.
function EditorOf( byval w as TK_WIDGET ptr ) as Editor ptr
    return tkForm_FromWidget( w )->Tag
end function

Editor is everything tpad keeps about one window, and the form holds a pointer to it in its Tag. That is the answer to a question every callback raises. A control's callback receives the control and nothing else; tkForm_FromWidget finds the form that control is on, and the form's Tag finds the Editor. EditorOf does both. So no part of the program needs a dim shared variable, and a second tpad window would be a second Editor with nothing shared.

Cmd names every command once. A menu item, a key and the self-test all end up passing one of these numbers to the same procedure. picking is the subject of a later section.

The last two fields are the subject of another. ask and pick are the two places a person answers tpad: a question in a message box, and a file name in a file dialog. Both are procedure pointers, and Create points them at the real thing. The message box is one call:

'' The real answers come from a person.
function AskPerson( byval f as TK_FORM ptr, byref text as ustring, _
                    byval buttons as long ) as long
    return tkMessageBox_Show( tkForm_Widget( f ), text, "tpad", _
        iif( buttons = MBX_BTN_OK, MBX_ICON_INFO, MBX_ICON_QUESTION ), _
        buttons )
end function

tkMessageBox_Show puts up a themed message box and waits for an answer. Its button sets are named presets; MBX_BTN_SAVE_DONTSAVE_CANCEL returns MBX_IDYES, MBX_IDNO or MBX_IDCANCEL, because a save question is a yes-no-cancel question with better captions.

A dialog that does not stop your code

The file dialog is the other thing a person answers, and it does not work the way the message box does. SDL3's file dialogs return at once and answer later, through a callback, because on some systems a dialog cannot be run any other way. Worse for a program that wants to read an answer, the callback may run on another thread.

tpad's commands want a function that returns a path, so PickFile builds one:

'' What the dialog's callback leaves for the code waiting on it.
type PickWait
    as SDL_AtomicInt answered
    as zstring ptr path         '' SDL's copy of the answer, or null
end type

'' May run on another thread, so it touches nothing but C memory.
sub PickAnswered( byval userdata as any ptr, _
                  byval filelist as const zstring const ptr ptr, _
                  byval filter as long )
    dim as PickWait ptr w = userdata
    if filelist <> 0 then
        if filelist[0] <> 0 then w->path = SDL_strdup( filelist[0] )
    end if
    SDL_SetAtomicInt( @w->answered, 1 )
end sub

'' Shows the system's file dialog and returns the path, or "".
function PickFile( byval f as TK_FORM ptr, byval saving as boolean, _
                   byref suggest as ustring ) as ustring
    dim as SDL_DialogFileFilter filters( 0 to 1 )
    filters( 0 ).name = @"Text files" : filters( 0 ).pattern = @"txt"
    filters( 1 ).name = @"All files" : filters( 1 ).pattern = @"*"
    dim as string where = suggest
    dim as PickWait w
    dim as SDL_Window ptr win = tkForm_Host( f )->win
    if saving then
        SDL_ShowSaveFileDialog( @PickAnswered, @w, win, @filters( 0 ), _
            2, iif( len( where ), strptr( where ), 0 ) )
    else
        SDL_ShowOpenFileDialog( @PickAnswered, @w, win, @filters( 0 ), _
            2, 0, false )
    end if
    do until SDL_GetAtomicInt( @w.answered ) = 1
        tkApp_Pump( )
        SDL_Delay( 10 )
    loop
    dim as ustring picked
    if w.path <> 0 then
        picked = *w.path
        SDL_free( w.path )
    end if
    return picked
end function

'' Every question for a path comes through here. The event loop runs
'' while the dialog is up, so nothing else may start until it answers.
function PickPath( byval ed as Editor ptr, byval saving as boolean, _
                   byref suggest as ustring ) as ustring
    ed->picking = true
    dim as ustring p = ed->pick( ed->form, saving, suggest )
    ed->picking = false
    return p
end function

It starts the dialog, then turns the event loop by hand until the answer arrives, so the window keeps painting and SDL keeps delivering events.

Everything the callback does is chosen for the thread it may be on. It is handed @w, so it needs no global. It copies the path with SDL_strdup, which is C memory and owes nothing to tiko's string runtime, and it signals with an atomic integer (Chapter 23). Only back on the waiting thread does the copy become a ustring. The order matters: path is written first, and the atomic's write is what tells the waiting thread that it is safe to read.

If the system has no dialog to show, SDL calls back with no list at all, and PickFile returns "", as if the person had cancelled. On Linux the dialog comes from the desktop's portal or from zenity, so a stripped-down machine can reach that path.

Pitfall

A dialog that returns at once leaves the event loop running, and a running event loop will deliver anything. If the window is not blocked for you, the person can choose File > Exit while the dialog is open. MayDiscard finds nothing unsaved, the form is destroyed, its OnDestroy deletes the Editor, and when the dialog does answer, the code waiting for it carries on with a pointer to memory that has been freed.

Whether a system blocks the parent window is the system's decision, so PickPath does not depend on it. It sets picking; Execute starts nothing while it is set, and the form's close handler refuses. The self-test tries it, with a scripted person who closes the window from inside the dialog:

== File > Exit while the file dialog is open
  window closed: false

With the close handler's one line removed, that line reads true.

The text, and the callback that runs afterwards

'' Queued from the message callback: by the time it runs, the text box
'' has acted on the key or the click and the caret has moved.
sub CaretMoved( byval payload as any ptr )
    ShowStatus( payload )
end sub

sub BuildText( byval f as TK_FORM ptr, byval ed as Editor ptr )
    ed->text = tkTextBox_Create( tkForm_Widget( f ), 101, true )
    tkTextBox_SetFont( ed->text, tkForm_Font( f, TKFONT_MONO ) )
    tkTextBox_SetLimitText( ed->text, &h7FFFFFFE )
    tkTextBox_SetMargins( ed->text, tkForm_Scale( f, 6 ), _
                          tkForm_Scale( f, 6 ) )

    '' The person typed, cut, pasted or undid something.
    tkTextBox_SetChangeCallback( ed->text, _
        sub( byval h as TK_WIDGET ptr )
            ShowTitle( EditorOf( h ) )
            ShowStatus( EditorOf( h ) )
        end sub )

    '' The caret may be about to move: look once the control has acted.
    tkTextBox_SetMessageCallback( ed->text, _
        function( byval m as TKTEXTBOX_MESSAGEINFO ptr ) as boolean
            select case m->msg
            case TKM_KEYDOWN, TKM_KEYUP, TKM_LBUTTONDOWN, TKM_LBUTTONUP
                tkApp_RunOnUI( @CaretMoved, EditorOf( m->hTextBox ) )
            end select
            return false
        end function )

    '' The box and its scroll bar report to each other.
    ed->scroll = tkVScrollBar_Create( tkForm_Widget( f ), 102 )
    tkTextBox_SetScrollChangedCallback( ed->text, _
        sub( byval h as TK_WIDGET ptr )
            dim as integer total, page, top
            tkTextBox_GetVScrollInfo( h, total, page, top )
            tkVScrollBar_SetRange( EditorOf( h )->scroll, total, _
                                   page, top )
        end sub )
    tkVScrollBar_SetScrollCallback( ed->scroll, _
        sub( byval h as TK_WIDGET ptr, byval newPos as integer )
            tkTextBox_ScrollToLine( EditorOf( h )->text, newPos )
        end sub )
end sub

The third argument to tkTextBox_Create makes a multiline box: Enter starts a new line, and long lines wrap. tkForm_Font( f, TKFONT_MONO ) is the form's monospaced font, which the package ships, and the text limit is raised from the control's default to nearly 2^31 bytes.

Four callbacks, each a lambda, connect the box to the rest of the window:

  • The change callback fires when the person changes the text: typing, cutting, pasting, undoing. It never fires for tkTextBox_SetText. Every tkControls setter is silent in the same way, so a program can set a control's value inside its own handler without being called back in the middle of it. tpad relies on that when it loads a file.
  • The message callback sees the box's keyboard and mouse events before the box acts on them. A key that moves the caret has not moved it yet, so reading the caret position here gives the old one. Instead the callback hands CaretMoved to tkApp_RunOnUI, which queues it to run when the current event has been handled, by which time the caret is where the key put it. false lets the box handle the event as usual.
  • The scroll callbacks connect the box to a tkVScrollBar. The box reports its line count, page size and top line whenever they may have changed, and the scroll bar reports a new position when it is dragged.

The status bar

sub BuildStatus( byval f as TK_FORM ptr, byval ed as Editor ptr )
    ed->status = tkStatusBar_Create( tkForm_Widget( f ), 103 )
    tkStatusBar_AddPanel( ed->status, "" )      '' Ln, Col: springs
    tkStatusBar_AddPanel( ed->status, "" )      '' line ending
    tkStatusBar_AddPanel( ed->status, "" )      '' encoding
    tkStatusBar_SetExpandPanel( ed->status, 0 )
end sub

A tkStatusBar lays out and draws its own panels, and SetExpandPanel makes the first one take the space left over. Setting a panel's text is all there is to do.

Two ways of counting

'' The editor's text, with one LF per line break, as textfile wants.
function TextOf( byval ed as Editor ptr ) as ustring
    return textfile.ToLf( tkTextBox_GetText( ed->text ) )
end function

public sub ShowTitle( byval ed as Editor ptr )
    dim as string title = textfile.Caption( ed->doc, _
        tkTextBox_GetModify( ed->text ) )
    SDL_SetWindowTitle( tkForm_Host( ed->form )->win, strptr( title ) )
end sub

public sub ShowStatus( byval ed as Editor ptr )
    dim as integer first, last
    tkTextBox_GetSel( ed->text, first, last )
    dim as ustring body = TextOf( ed )
    dim as int32 ln, col
    textfile.LineColumn( body, offsets.UnitsIn( body, last ), ln, col )
    tkStatusBar_SetText( ed->status, 0, "Ln " & ln & ", Col " & col )
    tkStatusBar_SetText( ed->status, 1, _
        iif( ed->doc.ending = textfile.LineEnding.CrLf, _
             "Windows (CRLF)", "Unix (LF)" ) )
    tkStatusBar_SetText( ed->status, 2, _
        iif( ed->doc.hasBom, "UTF-8 with BOM", "UTF-8" ) )
end sub

TextOf is the one place pad reads the control's text, and it passes it through ToLf, so that textfile's rule holds whatever the control does. ShowTitle reads the box's modified flag, which the control sets on every edit the person makes and pad clears after a load or a save, and hands SDL the caption as UTF-8: title is a string, and assigning a ustring to it stores the text's UTF-8 bytes. ShowStatus takes the end of the selection as the caret and lets textfile count lines, after one conversion, which is the subject of this section.

A tkTextBox holds its text in UTF-8 and its offsets count bytes. A ustring counts UTF-16 units (Chapter 9), and so do len, instr and everything in textfile. While every character before the offset is ASCII, the two numbers are equal. The first character that is not, and they are not:

#module "offsets"
'' Two ways of counting the same position in a text. A ustring counts
'' UTF-16 units; a tkTextBox counts UTF-8 bytes. They agree only while
'' everything before the position is ASCII.
''
'' A string assigned from a ustring holds its UTF-8 bytes, and a ustring
'' assigned from a string decodes them, so each conversion is a prefix
'' turned into the other form and measured.

'' How many ustring units the first `count` UTF-8 bytes of text make.
public function UnitsIn( byref text as const ustring, _
                         byval count as int32 ) as int32
    dim as string utf8 = text
    dim as ustring head = left( utf8, count )
    return len( head )
end function

'' How many UTF-8 bytes the first `count` ustring units of text make.
public function BytesIn( byref text as const ustring, _
                         byval count as int32 ) as int32
    dim as string head = left( text, count )
    return len( head )
end function

The two functions do the conversion by letting tiko do it: take the prefix in one form, turn it into the other, measure. They need no window, so they get a module and a test of their own:

'' The two counts of a position, with no window. U+00E9 is two bytes
'' and one unit; U+1F600 is four bytes and two units.
#import "./offsets"

dim as ustring ascii = "plain text"
dim as ustring accent = "caf" & wchr( &hE9 ) & " au lait"
dim as ustring emoji = wchr( &h1F600 ) & " smile"

print "== ASCII: the two counts agree"
print "byte 5 is unit"; offsets.UnitsIn( ascii, 5 )
print "unit 5 is byte"; offsets.BytesIn( ascii, 5 )

print "== 'au' in cafe-acute au lait"
dim as int32 at = instr( accent, "au" ) - 1
print "unit offset:"; at
print "byte offset:"; offsets.BytesIn( accent, at )
print "and back:   "; offsets.UnitsIn( accent, _
                          offsets.BytesIn( accent, at ) )

print "== 'smile' after U+1F600"
at = instr( emoji, "smile" ) - 1
print "unit offset:"; at
print "byte offset:"; offsets.BytesIn( emoji, at )
print "and back:   "; offsets.UnitsIn( emoji, _
                          offsets.BytesIn( emoji, at ) )

print "== the edges"
print "offset 0:   "; offsets.BytesIn( accent, 0 ); _
      offsets.UnitsIn( accent, 0 )
dim as int32 units = len( accent )
dim as int32 count = offsets.BytesIn( accent, units )
print "the end:    "; count; offsets.UnitsIn( accent, count )
== ASCII: the two counts agree
byte 5 is unit 5
unit 5 is byte 5
== 'au' in cafe-acute au lait
unit offset: 5
byte offset: 6
and back:    5
== 'smile' after U+1F600
unit offset: 3
byte offset: 5
and back:    3
== the edges
offset 0:    0 0
the end:     13 12

An e-acute is one unit and two bytes. U+1F600 is two units and four bytes. Both directions land on a boundary between characters, and the box snaps an offset to one in any case.

Pitfall

Nothing about this mistake is visible with ASCII text, and every test written in English passes. Take out the three conversions in pad, and open a file whose first line is café au lait and whose second is naïve lait. Find Next for lait selects:

== text that is not ASCII, Find Next for "lait", twice
  selected:  lai
  status: Ln 1, Col 13 | Unix (LF) | UTF-8
  selected: e la
  status: Ln 2, Col 11 | Unix (LF) | UTF-8

The search worked and the selection is wrong, by one byte for each character before it that took two. The status bar is right, for the wrong reason: the position it measured was the one the selection had been given. A file that is only slightly non-English looks fine until someone uses Find.

Line breaks are the same mistake in another unit, and textfile already answers them the same way. Each control and each file counts in its own way, so give the program one way, and convert where the two meet.

Layout, menus, keys

sub Main_OnSize( byval f as TK_FORM ptr, byval cx as long, _
                 byval cy as long )
    dim as Editor ptr ed = f->Tag
    dim as long barH = tkForm_Scale( f, 30 )
    dim as long statusH = tkForm_Scale( f, 26 )
    dim as long sbW = tkForm_Scale( f, 14 )
    dim as long textH = cy - barH - statusH
    tkWidget_SetPos( ed->bar, 0, 0, cx, barH )
    tkWidget_SetPos( ed->text, 0, barH, cx - sbW, textH )
    tkWidget_SetPos( ed->scroll, cx - sbW, barH, sbW, textH )
    tkWidget_SetPos( ed->status, 0, cy - statusH, cx, statusH )
end sub

Controls start with no size, and nothing is on screen until the form's size handler places each one. The handler runs whenever the window's size changes. Every literal is passed through tkForm_Scale, which turns device-independent units into pixels at the window's scale: thirty units is thirty pixels on an ordinary display and sixty on one at 200%.

function AddMenu( byval f as TK_FORM ptr, byval bar as TK_WIDGET ptr, _
                  byref title as ustring ) as TK_MENU ptr
    dim as long i = tkMenuBar_AddItem( bar, title, 0 )
    dim as TK_MENU ptr m = tkPopupMenu_Create( tkForm_Host( f ) )
    tkMenuBar_SetDropDown( bar, i, m )
    return m
end function

'' The command key, as the menus spell it: Cmd on macOS, Ctrl
'' elsewhere. TK_KMOD_PRIMARY is the same key as a modifier mask.
#if defined( TIKO_OS_MACOS )
const PrimaryKey = "Cmd+"
#else
const PrimaryKey = "Ctrl+"
#endif

function FormKey( byval f as TK_FORM ptr, byval key as long, _
                  byval mods as long ) as boolean
    dim as boolean primary = (mods and TK_KMOD_PRIMARY) <> 0
    dim as boolean shift = (mods and SDL_KMOD_SHIFT) <> 0
    dim as long id = 0
    if primary then
        select case key
        case SDLK_N : id = CmdNew
        case SDLK_O : id = CmdOpen
        case SDLK_S : id = iif( shift, CmdSaveAs, CmdSave )
        case SDLK_F : id = CmdFind
        end select
    elseif key = SDLK_F3 then
        id = CmdFindNext
    end if
    if id = 0 then return false
    Execute( f->Tag, id )
    return true
end function

sub BuildMenus( byval f as TK_FORM ptr, byval ed as Editor ptr )
    dim as TK_WIDGET ptr bar = _
        tkMenuBar_Create( tkForm_Widget( f ), 100 )
    ed->bar = bar
    tkMenuBar_SetCommandCallback( bar, _
        sub( byval h as TK_WIDGET ptr, byval id as long )
            Execute( EditorOf( h ), id )
        end sub )
    dim as TK_MENU ptr m = AddMenu( f, bar, "File" )
    dim as ustring k = PrimaryKey
    tkPopupMenu_AddItem( m, CmdNew, "New", k & "N" )
    tkPopupMenu_AddItem( m, CmdOpen, "Open...", k & "O" )
    tkPopupMenu_AddItem( m, CmdSave, "Save", k & "S" )
    tkPopupMenu_AddItem( m, CmdSaveAs, "Save As...", k & "Shift+S" )
    tkPopupMenu_AddSeparator( m )
    tkPopupMenu_AddItem( m, CmdExit, "Exit" )
    m = AddMenu( f, bar, "Edit" )
    tkPopupMenu_AddItem( m, CmdUndo, "Undo", k & "Z" )
    tkPopupMenu_AddSeparator( m )
    tkPopupMenu_AddItem( m, CmdCut, "Cut", k & "X" )
    tkPopupMenu_AddItem( m, CmdCopy, "Copy", k & "C" )
    tkPopupMenu_AddItem( m, CmdPaste, "Paste", k & "V" )
    tkPopupMenu_AddItem( m, CmdSelectAll, "Select All", k & "A" )
    tkPopupMenu_AddSeparator( m )
    tkPopupMenu_AddItem( m, CmdFind, "Find...", k & "F" )
    tkPopupMenu_AddItem( m, CmdFindNext, "Find Next", "F3" )
    tkForm_OnKeyDown( f, @FormKey )
end sub

A tkMenuBar holds the titles; each title drops down a tkPopupMenu. The text after an item, such as k & "N", is only shown. The menu bar's command callback hands the item's Cmd to Execute.

What makes a key work is FormKey. The text box handles the primary key with Z, X, C, V and A itself and leaves every other key unclaimed, and an unclaimed key reaches the form's OnKeyDown. Returning true says that it was used.

The primary key is the one thing in tpad that is written differently for one system. TK_KMOD_PRIMARY, from tkHost, is the Cmd key on macOS and Ctrl elsewhere, and the text box tests it too, so tpad writes that name once. Only the menu's label needs the platform spelled out, so that is the only #if in the program (Chapter 16).

Commands

'' The one place a command is carried out, wherever it came from.
public sub Execute( byval ed as Editor ptr, byval id as long )
    if ed->picking then exit sub
    select case id
    case CmdNew
        if MayDiscard( ed ) then
            dim as textfile.Document blank
            ShowDocument( ed, blank )
        end if
    case CmdOpen
        if MayDiscard( ed ) then
            dim as ustring p = PickPath( ed, false, "" )
            if len( p ) then OpenPath( ed, p )
        end if
    case CmdSave
        SaveDocument( ed, false )
    case CmdSaveAs
        SaveDocument( ed, true )
    case CmdExit
        tkForm_Close( ed->form )
    case CmdUndo
        tkTextBox_Undo( ed->text )
    case CmdCut
        tkTextBox_Cut( ed->text )
    case CmdCopy
        tkTextBox_Copy( ed->text )
    case CmdPaste
        tkTextBox_Paste( ed->text )
    case CmdSelectAll
        tkTextBox_SelectAll( ed->text )
    case CmdFind
        AskWhatToFind( ed )
    case CmdFindNext
        if len( ed->findWhat ) then
            FindAgain( ed )
        else
            AskWhatToFind( ed )
        end if
    end select
end sub

One procedure carries out every command, whether it came from a menu, a key or the self-test. The menus and the keys say which command; Execute says what it does. Adding a command means adding a Cmd, an item, perhaps a key, and a case. Its first line is the dialog's rule: while a file dialog is waiting, no command starts.

Files, and the question before discarding

'' Puts doc in the window, replacing what was there.
sub ShowDocument( byval ed as Editor ptr, _
                  byref doc as textfile.Document )
    ed->doc = doc
    tkTextBox_SetText( ed->text, doc.text )
    tkTextBox_SetModify( ed->text, false )
    tkTextBox_SetSel( ed->text, 0, 0 )
    ShowTitle( ed )
    ShowStatus( ed )
end sub

'' Opens path; says why not if it cannot.
public function OpenPath( byval ed as Editor ptr, _
                          byref path as ustring ) as boolean
    dim as textfile.Document doc
    dim as ustring e = textfile.Load( path, doc )
    if len( e ) then
        ed->ask( ed->form, e, MBX_BTN_OK )
        return false
    end if
    ShowDocument( ed, doc )
    if doc.lossy then
        ed->ask( ed->form, textfile.DisplayName( doc ) & _
            " is not UTF-8. Characters that could not be read show" & _
            " as U+FFFD, and saving writes them that way.", MBX_BTN_OK )
    end if
    return true
end function

'' Saves, asking for a name when there is none (or when asked to).
function SaveDocument( byval ed as Editor ptr, _
                       byval newName as boolean ) as boolean
    if newName orelse len( ed->doc.path ) = 0 then
        dim as ustring p = PickPath( ed, true, _
                                     textfile.DisplayName( ed->doc ) )
        if len( p ) = 0 then return false
        ed->doc.path = p
    end if
    ed->doc.text = TextOf( ed )
    dim as ustring e = textfile.Save( ed->doc )
    if len( e ) then
        ed->ask( ed->form, e, MBX_BTN_OK )
        return false
    end if
    tkTextBox_SetModify( ed->text, false )
    ShowTitle( ed )
    return true
end function

'' True when it is all right to throw the text away: it is saved,
'' the person saved it now, or said not to.
function MayDiscard( byval ed as Editor ptr ) as boolean
    if tkTextBox_GetModify( ed->text ) = false then return true
    select case ed->ask( ed->form, "Do you want to save changes to " & _
                         textfile.DisplayName( ed->doc ) & "?", _
                         MBX_BTN_SAVE_DONTSAVE_CANCEL )
    case MBX_IDYES
        return SaveDocument( ed, false )
    case MBX_IDNO
        return true
    end select
    return false
end function

ShowDocument puts a document in the window. tkTextBox_SetText is silent, as a setter should be, and the modified flag is cleared after it.

MayDiscard is the specification's question, in one place. New and Open call it before they replace the text, and the form's close handler calls it before the window goes. Save in the answer saves, and continues only if the save worked: a save that is cancelled at the file dialog, or fails, keeps the window and its text.

SaveDocument reads the text out of the control into the document, saves, and clears the modified flag only after textfile.Save reports success. An error from either module comes back as text, and goes to the person as a message box with an OK button.

Find

sub FindAgain( byval ed as Editor ptr )
    if len( ed->findWhat ) = 0 then exit sub
    dim as integer first, last
    tkTextBox_GetSel( ed->text, first, last )
    dim as ustring body = TextOf( ed )
    dim as int32 at = textfile.FindNext( body, ed->findWhat, _
        offsets.UnitsIn( body, last ), ed->matchCase )
    if at < 0 then
        ed->ask( ed->form, "Cannot find """ & ed->findWhat & """", _
                 MBX_BTN_OK )
        exit sub
    end if
    '' SetSel scrolls the caret into view itself.
    tkTextBox_SetSel( ed->text, offsets.BytesIn( body, at ), _
        offsets.BytesIn( body, at + len( ed->findWhat ) ) )
    ShowStatus( ed )
end sub

'' The Find box: a modal form that only collects the search.
sub FindBox_OnSize( byval f as TK_FORM ptr, byval cx as long, _
                    byval cy as long )
    dim as FindBox ptr box = f->Tag
    dim as long pad = tkForm_Scale( f, 12 ), bw, bh
    tkButton_GetIdealSize( box->ok, bw, bh )
    dim as long w = cx - 3 * pad - bw
    tkWidget_SetPos( box->what, pad, pad, w, bh )
    tkWidget_SetPos( box->matchCase, pad, 2 * pad + bh, w, bh )
    tkWidget_SetPos( box->ok, cx - pad - bw, pad, bw, bh )
    tkWidget_SetPos( box->cancel, cx - pad - bw, 2 * pad + bh, bw, bh )
end sub

sub FindBox_Accept( byval box as FindBox ptr )
    box->ed->findWhat = tkTextBox_GetText( box->what )
    box->ed->matchCase = tkCheckBox_GetChecked( box->matchCase )
    tkForm_EndModal( tkForm_FromWidget( box->what ), TKAPP_IDOK )
end sub

sub AskWhatToFind( byval ed as Editor ptr )
    dim as TK_FORM ptr f = tkApp_NewForm( "Find", 420, 112, ed->form )
    dim as FindBox box
    box.ed = ed
    f->Tag = @box
    box.what = tkTextBox_Create( tkForm_Widget( f ), 104 )
    tkTextBox_SetText( box.what, ed->findWhat )
    tkTextBox_SetSelectOnFocus( box.what, true )
    tkTextBox_SetEnterPressedCallback( box.what, _
        sub( byval h as TK_WIDGET ptr )
            FindBox_Accept( tkForm_FromWidget( h )->Tag )
        end sub )
    box.matchCase = tkCheckBox_Create( tkForm_Widget( f ), 105 )
    tkCheckBox_SetText( box.matchCase, "Match case" )
    tkCheckBox_SetChecked( box.matchCase, ed->matchCase )
    box.ok = tkButton_Create( tkForm_Widget( f ), TKAPP_IDOK )
    tkButton_SetText( box.ok, "Find Next" )
    tkButton_SetClickCallback( box.ok, _
        sub( byval h as TK_WIDGET ptr, byval id as long )
            FindBox_Accept( tkForm_FromWidget( h )->Tag )
        end sub )
    box.cancel = tkButton_Create( tkForm_Widget( f ), TKAPP_IDCANCEL )
    tkButton_SetText( box.cancel, "Cancel" )
    tkButton_SetClickCallback( box.cancel, _
        sub( byval h as TK_WIDGET ptr, byval id as long )
            tkForm_EndModal( tkForm_FromWidget( h ), TKAPP_IDCANCEL )
        end sub )
    tkForm_OnSize( f, @FindBox_OnSize )
    '' Esc ends a modal form with IDCANCEL by itself.
    if tkForm_ShowModal( f ) = TKAPP_IDOK then FindAgain( ed )
end sub

The Find box is a modal form. tkForm_ShowModal runs the event loop until the box ends it, and returns the code passed to tkForm_EndModal; because it returns only once the box is closed, the FindBox can live on the stack of AskWhatToFind. Enter in the search box is Find Next, through the box's Enter callback, and Esc ends a modal form with TKAPP_IDCANCEL without being asked.

The box only collects what to look for, into the Editor its Tag points at. FindAgain does the searching, so F3 can repeat a search without the box. It converts twice: the selection's end into units for textfile, and the match back into bytes for the box. tkTextBox_SetSel scrolls the caret into view itself, so there is nothing after it.

A Quit that is not a close

The close button goes through OnClose. The system's own Quit does not. SDL gives every Mac application a menu with Quit on it, and Cmd+Q reaches the program as SDL_EVENT_QUIT, an event that belongs to no window. A logout can arrive the same way. tkControls responds by marking every window closed, and the program ends with the question never asked.

'' The event hook is handed only the event, so the one window it
'' protects is kept where the hook can reach it.
function MainEditor( byval ed as Editor ptr = 0 ) as Editor ptr
    static as Editor ptr kept
    if ed <> 0 then kept = ed
    return kept
end function

'' The system asking the whole program to quit (Cmd+Q, logging out)
'' becomes an ordinary close, which asks first.
function QuitHook( byval e as SDL_Event ptr ) as boolean
    if e->type <> SDL_EVENT_QUIT then return false
    tkForm_Close( MainEditor( )->form )
    return true
end function

tkHost_AddEventHook is called for every event before the library looks at it, and a hook that returns true has dealt with it. QuitHook turns the system's Quit into an ordinary close of the main window, which runs OnClose, which asks. An event hook is handed the event and nothing else, so MainEditor keeps a pointer in a static for it. It is the one piece of state in the program that is not in the Editor, and it is there because the C-shaped callback left no place for it.

Pitfall

The window's close button is an event for the window, and it is the one you remember to handle. With the hook removed, the self-test's Quit closes the window with unsaved text in it and no question: the two lines asked: and answered: vanish, and window closed: reads true. On Windows nothing a person ordinarily does produces this event, which is why a program developed there does not find out.

Creating it all

'' Builds the main window, with an empty, untitled document.
public function Create( byval forcedScale as single = 0 ) as Editor ptr
    dim as Editor ptr ed = new Editor
    ed->ask = @AskPerson
    ed->pick = @PickFile
    dim as TK_FORM ptr f = tkApp_NewForm( "tpad", 720, 480, 0, _
                                          forcedScale )
    ed->form = f
    f->Tag = ed

    BuildMenus( f, ed )
    BuildText( f, ed )
    BuildStatus( f, ed )

    tkForm_OnSize( f, @Main_OnSize )
    '' Asked before the window closes, however it is closed.
    tkForm_OnClose( f, _
        function( byval f as TK_FORM ptr ) as boolean
            dim as Editor ptr ed = f->Tag
            if ed->picking then return false
            return MayDiscard( ed )
        end function )
    tkForm_OnDestroy( f, _
        sub( byval f as TK_FORM ptr )
            tkHost_RemoveEventHook( @QuitHook )
            delete cast( Editor ptr, f->Tag )
            f->Tag = 0
        end sub )
    MainEditor( ed )
    tkHost_AddEventHook( @QuitHook )

    ShowTitle( ed )
    ShowStatus( ed )
    return ed
end function

Create allocates the Editor with new, because it must outlive the call: it lives exactly as long as the window, and the form's destroy handler deletes it, after taking the Quit hook away. The close handler is the specification's question again; returning false from it cancels the close, so Cancel keeps the window open, and so does a file dialog that has not answered.

Nothing here handles a change of scale. When the window moves to a display at another scale, tkControls re-sizes the fonts each control was given and hands out no others, so the text box keeps its monospaced font. That is the library's behaviour rather than tpad's, and it could change, so the self-test checks it. forcedScale pins a scale instead of the display's.

The program

#cmdline "-s gui"
#import "std/fs"
#import "std/strings"
#import "./pad"
#import "vendor/tkControls/tkApp"
#import "vendor/tkControls/tkTextBox"
#import "vendor/tkControls/tkStatusBar"
#import "vendor/tkControls/tkMessageBox"

using tkApp
using tkHost
using tkTextBox
using tkStatusBar
using tkMessageBox

'' tpad [file]                 run it
'' tpad --selftest             drive the real window, print what it saw
'' tpad --shot out.bmp [file]  render once, dark theme, and save it
dim as string first = command( 1 )
dim as boolean testing = (first = "--selftest")
dim as boolean shooting = (first = "--shot")

dim as TKAPP_OPTIONS opts
if testing orelse shooting then opts.ThemeMode = TKAPP_THEME_DARK
if tkApp_Init( opts ) = false then
    print "tkApp_Init: " & *SDL_GetError( )
    end 1
end if

'' 0 means the display's own scale. A test pins it, so that its layout
'' is the same on every machine.
dim as single uiScale = val( environ( "TPAD_SCALE" ) )
if testing then uiScale = 1.0
if shooting then uiScale = 1.75
dim as pad.Editor ptr ed = pad.Create( uiScale )

if testing then
    dim as long result = SelfTest( ed )
    tkApp_Shutdown( )
    end result
end if
if shooting then
    if len( command( 3 ) ) then pad.OpenPath( ed, command( 3 ) )
    TakeShot( ed, command( 2 ) )
    tkApp_Shutdown( )
    end 0
end if

if len( first ) then pad.OpenPath( ed, first )
end tkApp_Run( ed->form )

#cmdline "-s gui" builds for the GUI subsystem on Windows (Chapter 31), so starting tpad from Explorer opens no console window; the other two systems make no such distinction. tkApp_Run shows the form and runs the event loop until it closes, and its result is the program's exit code. A file named on the command line is opened before the loop starts; if it cannot be, the person is told and gets an empty window. Under --selftest and --shot the loop never runs.

Testing a window with nobody at it

The harness that checks this book's listings runs every program and compares its output with what the book prints. A window waits for a person. So tpad takes --selftest, which drives the real window — the real controls, the real callbacks, the real Execute — and prints what it saw.

The only things it cannot drive are the two that wait for a person: the message box and the file dialog. That is why they are behind ask and pick. The test points them at a script:

'' The person, scripted: what the test answers to each question.
function ScriptedAsk( byval f as TK_FORM ptr, byref text as ustring, _
                      byval buttons as long ) as long
    static as long replies( ... ) = { MBX_IDCANCEL, MBX_IDNO, _
                                      MBX_IDCANCEL, MBX_IDNO }
    static as int32 n
    print "  asked: "; text
    if buttons = MBX_BTN_OK then return MBX_IDOK
    n += 1
    print "  answered: "; iif( replies( n - 1 ) = MBX_IDNO, _
                               "Don't Save", "Cancel" )
    return replies( n - 1 )
end function

function ScriptedPick( byval f as TK_FORM ptr, _
                       byval saving as boolean, _
                       byref suggest as ustring ) as ustring
    print "  picked: lf.tmp"
    return "lf.tmp"
end function

'' A person who tries to close the window while the dialog is up.
function ImpatientPick( byval f as TK_FORM ptr, _
                        byval saving as boolean, _
                        byref suggest as ustring ) as ustring
    pad.Execute( f->Tag, pad.CmdExit )
    tkForm_Close( f )
    print "  window closed: "; cbool( tkForm_Host( f )->bQuit )
    return ""
end function
'' Lets queued events arrive, as the loop would.
sub Pump( )
    tkApp_Pump( )
end sub

'' Keeps the loop turning for a while.
sub PumpFor( byval ms as uint64 )
    dim as uint64 start = SDL_GetTicks( )
    do until SDL_GetTicks( ) - start >= ms
        Pump( )
        SDL_Delay( 10 )
    loop
end sub

'' A key, delivered where the keyboard would deliver it.
sub Press( byval ed as pad.Editor ptr, byval key as long )
    dim as SDL_Event e
    e.type = SDL_EVENT_KEY_DOWN
    e.key.windowID = tkForm_Host( ed->form )->winId
    e.key.key = key
    e.key.down = true
    SDL_PushEvent( @e )
    Pump( )
end sub

'' Typed text, as the system hands it over after the keys: UTF-8. The
'' event points at this string, so it has to outlive the event.
sub TypeText( byval ed as pad.Editor ptr, byref s as ustring )
    static as string typed
    typed = s
    dim as SDL_Event e
    e.type = SDL_EVENT_TEXT_INPUT
    e.text.windowID = tkForm_Host( ed->form )->winId
    e.text.text = strptr( typed )
    SDL_PushEvent( @e )
    Pump( )
end sub

sub Report( byval ed as pad.Editor ptr )
    dim as ustring title = _
        *SDL_GetWindowTitle( tkForm_Host( ed->form )->win )
    print "  title:  "; title
    print "  status: "; tkStatusBar_GetText( ed->status, 0 ); " | "; _
          tkStatusBar_GetText( ed->status, 1 ); " | "; _
          tkStatusBar_GetText( ed->status, 2 )
end sub

The test pushes SDL events onto the queue, where the system would put them, so a key takes the same path a real one does, through the message callback and the change callback. Three things follow from that:

  • Pump after every event. SDL_PushEvent only queues it, and the self-test runs before tkApp_Run, so there is no event loop delivering it.
  • Size the window, then wait. A system applies a new window size when it gets to it, and a key sent to a text box with no size moves nothing. PumpFor gives it time, and the layout is checked by comparing edges, which are the same at any scale, rather than pixel counts, which are not.
  • An event's text has to outlive the event. SDL_EVENT_TEXT_INPUT points at its string, so TypeText keeps it in a static.
function SelfTest( byval ed as pad.Editor ptr ) as long
    ed->ask = @ScriptedAsk
    ed->pick = @ScriptedPick
    fs.WriteAllText( "lf.tmp", !"one\ntwo\nthree\n" )
    dim as TK_HOST ptr h = tkForm_Host( ed->form )
    tkForm_Show( ed->form )
    Pump( )

    print "== a new window"
    Report( ed )
    print "== the layout, at 600 x 400"
    SDL_SetWindowSize( h->win, 600, 400 )
    PumpFor( 300 )
    print "  text meets the scroll bar: "; _
          cbool( ed->text->x + ed->text->cw = ed->scroll->x )
    print "  text meets the status bar: "; _
          cbool( ed->text->y + ed->text->ch = ed->status->y )
    print "  status bar is as wide as the window: "; _
          cbool( ed->status->cw = h->root->cw )

    print "== File > Open"
    pad.Execute( ed, pad.CmdOpen )
    Report( ed )
    print "== Down, Down, End, and type ""!"""
    tkHost_SetFocus( h, ed->text )
    Press( ed, SDLK_DOWN )
    Press( ed, SDLK_DOWN )
    Press( ed, SDLK_END )
    TypeText( ed, "!" )
    Report( ed )

    print "== Find Next, for ""T"", twice"
    ed->findWhat = "T"
    pad.Execute( ed, pad.CmdFindNext )
    Report( ed )
    pad.Execute( ed, pad.CmdFindNext )
    Report( ed )
    print "== Find Next, for ""four"""
    ed->findWhat = "four"
    pad.Execute( ed, pad.CmdFindNext )

    print "== File > Save"
    pad.Execute( ed, pad.CmdSave )
    Report( ed )
    dim as ustring saved = fs.ReadAllText( "lf.tmp" ).Value( )
    print "  on disk: "; strings.Escape( saved )

    print "== type, then File > New, twice"
    TypeText( ed, "?" )
    pad.Execute( ed, pad.CmdNew )
    Report( ed )
    pad.Execute( ed, pad.CmdNew )
    Report( ed )

    print "== moved to a monitor at twice the DPI"
    h->fScaleForced = 2 * h->fScale
    dim as SDL_Event e
    e.type = SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED
    e.window.windowID = h->winId
    SDL_PushEvent( @e )
    Pump( )
    print "  the text is still monospaced: "; _
          cbool( tkTextBox_GetFont( ed->text ) = _
                 tkForm_Font( ed->form, TKFONT_MONO ) )

    print "== text that is not ASCII, Find Next for ""lait"", twice"
    fs.WriteAllText( "lf.tmp", "caf" & wchr( &hE9 ) & !" au lait\n" & _
                     "na" & wchr( &hEF ) & "ve lait" )
    pad.Execute( ed, pad.CmdOpen )
    ed->findWhat = "lait"
    pad.Execute( ed, pad.CmdFindNext )
    print "  selected: "; tkTextBox_GetSelText( ed->text )
    Report( ed )
    pad.Execute( ed, pad.CmdFindNext )
    print "  selected: "; tkTextBox_GetSelText( ed->text )
    Report( ed )

    print "== File > Exit while the file dialog is open"
    ed->pick = @ImpatientPick
    pad.Execute( ed, pad.CmdOpen )
    ed->pick = @ScriptedPick

    print "== type, then the system asks the program to quit"
    TypeText( ed, "x" )
    e.type = SDL_EVENT_QUIT
    SDL_PushEvent( @e )
    Pump( )
    print "  window closed: "; cbool( h->bQuit )

    print "== type, then close the window"
    TypeText( ed, "x" )
    tkForm_Close( ed->form )
    print "  window closed: "; cbool( h->bQuit )
    fs.RemoveFile( "lf.tmp" )
    return 0
end function
== a new window
  title:  Untitled - tpad
  status: Ln 1, Col 1 | Windows (CRLF) | UTF-8
== the layout, at 600 x 400
  text meets the scroll bar: true
  text meets the status bar: true
  status bar is as wide as the window: true
== File > Open
  picked: lf.tmp
  title:  lf.tmp - tpad
  status: Ln 1, Col 1 | Unix (LF) | UTF-8
== Down, Down, End, and type "!"
  title:  *lf.tmp - tpad
  status: Ln 3, Col 7 | Unix (LF) | UTF-8
== Find Next, for "T", twice
  title:  *lf.tmp - tpad
  status: Ln 2, Col 2 | Unix (LF) | UTF-8
  title:  *lf.tmp - tpad
  status: Ln 3, Col 2 | Unix (LF) | UTF-8
== Find Next, for "four"
  asked: Cannot find "four"
== File > Save
  title:  lf.tmp - tpad
  status: Ln 3, Col 2 | Unix (LF) | UTF-8
  on disk: one\ntwo\nthree!\n
== type, then File > New, twice
  asked: Do you want to save changes to lf.tmp?
  answered: Cancel
  title:  *lf.tmp - tpad
  status: Ln 3, Col 2 | Unix (LF) | UTF-8
  asked: Do you want to save changes to lf.tmp?
  answered: Don't Save
  title:  Untitled - tpad
  status: Ln 1, Col 1 | Windows (CRLF) | UTF-8
== moved to a monitor at twice the DPI
  the text is still monospaced: true
== text that is not ASCII, Find Next for "lait", twice
  picked: lf.tmp
  selected: lait
  title:  lf.tmp - tpad
  status: Ln 1, Col 13 | Unix (LF) | UTF-8
  selected: lait
  title:  lf.tmp - tpad
  status: Ln 2, Col 11 | Unix (LF) | UTF-8
== File > Exit while the file dialog is open
  window closed: false
== type, then the system asks the program to quit
  asked: Do you want to save changes to lf.tmp?
  answered: Cancel
  window closed: false
== type, then close the window
  asked: Do you want to save changes to lf.tmp?
  answered: Don't Save
  window closed: true

Read in order, the output is the specification at work: a file opened, edited, searched and saved in its own line ending, the question before New answered Cancel and then Don't Save, a change of scale, text that is not ASCII, the dialog, the system's Quit, and the close.

The book's harness compares that output with what the program prints on all three systems, and there is one .out file for all of them. On Linux it also holds under both SDL video drivers, X11 and Wayland. One script and one expected output, run everywhere, is what shows that tpad is one program and not three that happen to look alike.

What the self-test cannot see

Report reads each panel's text back with tkStatusBar_GetText. A status bar that held the right text and drew none of it would pass. A test that reads the model does not see pixels. --shot is for that:

'' Renders the window once and saves what it drew.
sub TakeShot( byval ed as pad.Editor ptr, byref file as ustring )
    tkForm_Show( ed->form )
    PumpFor( 300 )
    dim as TK_HOST ptr h = tkForm_Host( ed->form )
    tkHost_Render( h )
    tkHost_RenderTo( h, false )
    dim as SDL_Surface ptr s = SDL_RenderReadPixels( h->renderer, 0 )
    dim as string path = file
    if s then
        SDL_SaveBMP( s, strptr( path ) )
        SDL_DestroySurface( s )
    end if
end sub

It runs at a fixed scale, in the dark theme, and saves a bitmap; the picture at the top of the chapter is one. Reading the pixels back needs the second argument of tkHost_RenderTo to be false, because on Metal the back buffer is black once it has been presented. With the same scale on two systems you can compare the files, and what remains is small: mostly a level or two of anti-aliasing, from one platform's build of SDL3_ttf to another's.

The real file dialogs and the real message box are the other thing the test does not reach. They are behind pick and ask because they wait for a person, and that person has to try them once on each system.

Running it

From the chapter's directory:

tiko build tpad
out/debug/tpad notes.txt

On Windows the program is out/debug/tpad.exe. tiko build tpad builds the target tpad with the debug profile into out/debug; tiko run -- notes.txt builds and starts it in one step. The first build compiles the tkControls modules the program imports; later builds compile only what changed.

Shipping

tiko build tpad --profile release writes an optimised program, and the build copies what it needs beside it. What that is differs by system:

The programBeside itThe folder
Windows337,920 bytesthe fonts, SDL3.dll, SDL3_ttf.dll, SDL3_image.dll10.3 MB
Linux348,888 bytesthe fonts5.0 MB
macOS361,480 bytesthe fonts5.0 MB

On Windows the folder is the installation: the toolchain ships the three SDL libraries and copies them. The fonts are Inter, Cascadia Mono and Fluent UI System Icons, with their licences, and they are why the program looks the same everywhere.

On Linux and macOS the program links the system's SDL3 and needs it on the machine that runs it. On a Mac that is brew install sdl3 sdl3_ttf sdl3_image. On Linux it is the distribution's SDL3 packages, and where a distribution has none yet, examples/tkControls/tools/build-linux-libs.sh, which comes with the toolchain, builds them. Tell the link where they are with tiko build tpad --options "-p /path/to/libs", and the program with LD_LIBRARY_PATH or an installed copy.

What it costs

  • What you ship. The program is about a third of a megabyte, and it brings 10 MB of libraries and fonts on Windows and needs SDL3 installed elsewhere. Portability is paid for in what you ship.
  • Every caret move reads the whole text, and converts it. ShowStatus copies the text out of the control, converts its line breaks, counts bytes into units and counts lines up to the caret. Measured on a 1 MB file in a release build on Windows, that takes about 10 ms, of which under 2 ms is tkTextBox_GetText. A notes file costs nothing; a large log would make the caret lag.
  • The controls are drawn, not provided. A tkTextBox looks and behaves the same on every system, which is the reason for using it, and for the same reason it is nothing the system recognises. There is no accessibility interface, so a screen reader sees an empty window. The menu bar is in the window, on a Mac too, not in the Mac's menu bar at the top of the screen.
  • The column counts UTF-16 units. A character outside the Basic Multilingual Plane, such as U+1F600, moves the column by two. Exercise 1 fixes it.
  • A new document is saved with CR LF on every system, and the status bar says so honestly. A file that was read keeps its own ending. Exercise 2 fixes it.
  • The text always wraps. A multiline tkTextBox wraps long lines and has no horizontal scroll bar, so Notepad's Word Wrap switch would have nothing to switch.
  • The whole file is in memory, twice while it is saved: once in the control and once in the document being written.
  • Text that is not UTF-8 is not preserved. tpad warns, and saving writes U+FFFD where the unreadable bytes were. Keeping them would mean reading the file in its own encoding, which needs the encoding to be known or guessed.
  • A self-test is code in the shipped program. It is a few dozen lines that do nothing unless asked, and the price buys a window that is checked on every build, on every system.

Summary

  • Keep the part of a program that needs no window in a module that imports none. textfile and offsets are tested by programs that print; only pad needs a window.
  • Give text one line-break convention inside the program — one LF, counted as one character — and convert at the edges: ToLf on the way in from the file and from the control, the file's own ending on the way out.
  • fs.ReadAllText removes a byte-order mark and replaces bytes that are not UTF-8 with U+FFFD. An editor that must write a file back the same way reads the mark itself. fs.ReadAllBytes's third argument is a size limit, not a prefix length.
  • Save with fs.WriteAtomic, so a failed save leaves the old file whole.
  • tkControls puts a tree of TK_WIDGETs in one SDL window. Keep a pointer to each control you talk to, keep per-window state in a newed type that the form's Tag points at, and reach it from any control's callback through tkForm_FromWidget.
  • tkControls setters are silent: only a person's actions call back. Read the caret after a key by queueing the read with tkApp_RunOnUI.
  • SDL3's file dialogs return at once and answer through a callback that may run on another thread. Wait for the answer by turning the event loop, and have the callback touch nothing but C memory and an atomic.
  • While a loop turns under a dialog, anything can be delivered. Refuse new commands and the close until the dialog answers, or an Editor can be freed underneath the code waiting on it.
  • tkTextBox offsets are UTF-8 bytes and a ustring counts UTF-16 units. They agree for ASCII and nowhere else. Convert at the edge, in one place, and test with text that is not English.
  • Route menus, keys and tests to one Execute. TK_KMOD_PRIMARY is Cmd on macOS and Ctrl elsewhere; only the menu's label needs #if.
  • Ask the person in one place, before anything is thrown away, and wire the close handler to it. A system's Quit is SDL_EVENT_QUIT, an event that belongs to no window: turn it into a close with an event hook, or it skips the question.
  • Put the person behind procedure pointers, and a test can drive the real window: push SDL events, pump after each, wait after resizing, and print what changed. One self-test and one expected output, run on every system, show that the program is one program. --shot covers the pixels.
  • A program built on SDL3 ships its libraries and fonts on Windows, and asks for SDL3 on Linux and macOS.

Exercises

  1. Make the status bar's column count characters, so that U+1F600 counts as one. A ustring holds such a character as two units, and the second is a low surrogate. {solution="ex36-01"}
  2. Make a new document use the line ending of the system it was started on, through a NewDocument function and #if, while a file that was read keeps its own. {solution="ex36-02"}
  3. Add Find Previous (Shift+F3) to textfile and to the Edit menu: the last match that ends at or before the start of the selection, wrapping around to the bottom. Mind which count each side uses. {solution="ex36-03"}
  4. Add Replace (Ctrl+H): a modal box with Find what, Replace with, Replace and Replace All. Do the replacing in textfile, so that it can be tested on every target.
  5. On macOS, make File > Exit read Quit, with Cmd+Q as its key, while Windows and Linux keep Exit.
  6. Open a file dropped on the window. Add an event hook for SDL_EVENT_DROP_FILE, whose data field is the path in UTF-8, and call MayDiscard first.
  7. Remember the window's size between runs, in a file under the folder SDL_GetPrefPath returns, and check that the same code finds the right place on all three systems.