s LearnSqueak.com

A COMPLETE SMALL APPLICATION

Build a notepad.
Keep your edits.

Create a native multiline text editor with New, Open, Save, Save As, and a working unsaved-changes guard.

Build it one control and one responsibility at a time. Then use it to write real text files. The screenshots and recordings come from Squeak; the website does not run the editor.

10 build-and-use checkpointsNative screenshots3 recorded workflowsCancelable file actions
Try the finished example

Run in the SqueakJS playground

The separate playground loads the real Smalltalk image on demand. This lesson keeps its native setup instructions; browser compatibility notes appear beside each demo.

Install once, then build in checkpoints

This tutorial creates MorphicNotepad, a Model subclass, using native Squeak controls. It was tested in Squeak 6.1, 64-bit, build 23976. No extra package is required.

Download the complete Notepad source. Open the native File List, select this .st file, and choose fileIn. It is a Smalltalk chunk-format file, not one Workspace expression. Use a learning image and check that the tutorial class names are unused; filing in again replaces their methods.

After source file-in · Workspace Do it
MorphicNotepad open

To run a checkpoint below, open Tools → Workspace, paste its complete block, select all of it, and choose do it (usually Ctrl+D / Cmd+D). Checkpoints 1–4 construct the visible controls progressively; checkpoints 5–10 exercise the completed application and explain each behavior. Every checkpoint starts a fresh window. Close the previous one before running the next; temporary variables do not carry between evaluations.

Three different kinds of state: the live editor buffer can differ from accepted model text, and both can differ from the last file saved on disk. The application checks the live buffer before leaving a document. Use its Save toolbar button to write a file. In this native text widget, Ctrl/Cmd-S accepts text; acceptance alone is not a disk save. Normal Return inserts a newline; keypad Enter can accept the editor text.

Build 01 · A native window

Start a fresh Model and SystemWindow. The model owns the window reference; the window owns the native title bar, close button and resizing handles. Extent is set after openInWorld because Squeak can restore a remembered size when opening.

Installed method · initialize
initialize
    super initialize.
    documentText := ''.
    savedText := ''.
    fileName := nil.
    statusMessage := 'Ready'.
Installed method · createWindow
createWindow
    window := SystemWindow new model: self.
    window setLabel: self windowTitle.
    ^ window
Complete runnable checkpoint 1
Checkpoint 1 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad win |
pad := MorphicNotepad new.
win := pad createWindow.
win openInWorld.
win extent: 760@490.
pad

Download checkpoint 1 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 1: A native window
A native window in the actual Squeak image.

Try it: Drag the title bar, resize the window, then close this empty checkpoint.

Build 02 · A multiline editor

Add only the editor to the new window. PluggableTextMorph asks #text for accepted model content and sends #acceptText: when native acceptance occurs. acceptOnCR: false keeps normal Return available for multiline text; plainTextOnly: true makes this a text-file editor.

Installed method · createEditor
createEditor
    editor := PluggableTextMorph on: self text: #text accept: #acceptText:.
    editor acceptOnCR: false; plainTextOnly: true; editTextSelector: #noteTextEdited:.
    ^ editor
Installed method · text
text
    "The accepted model text. The editor may contain newer, unaccepted text."
    ^ documentText
Installed method · acceptText:
acceptText: aText
    "Accepting an edit changes the model; it does not write a file."
    documentText := aText asString copy.
    self refreshChrome.
    ^ true
Complete runnable checkpoint 2
Checkpoint 2 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad win edit |
pad := MorphicNotepad new.
win := pad createWindow.
edit := pad createEditor.
win addMorph: edit frame: (0@0 corner: 1@1).
win openInWorld.
win extent: 760@490.
pad

Download checkpoint 2 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 2: A multiline editor
A multiline editor in the actual Squeak image.

Try it: Click the editor and type two lines with Return between them. This checkpoint has no toolbar yet; discard its draft when closing if you are only experimenting.

Build 03 · Read the live buffer

The scripted draft is deliberately unaccepted. #text still returns the accepted model string, while #currentText reads editor text asString. #isDirty compares that live text with savedText. The edit callback updates the title without sending changed: #text, which would reset the editor.

Installed method · currentText
currentText
    "Always read the live buffer before Save, New, Open or Close."
    ^ editor ifNil: [documentText] ifNotNil: [editor text asString]
Installed method · isDirty
isDirty
    ^ self currentText ~= savedText
Installed method · noteTextEdited:
noteTextEdited: aText
    "Called by PluggableTextMorph on edits. Do not reset its text here."
    statusMessage := 'Editing'.
    self refreshChrome
Installed method · acceptText:
acceptText: aText
    "Accepting an edit changes the model; it does not write a file."
    documentText := aText asString copy.
    self refreshChrome.
    ^ true
Complete runnable checkpoint 3
Checkpoint 3 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad win edit |
pad := MorphicNotepad new.
win := pad createWindow.
edit := pad createEditor.
win addMorph: edit frame: (0@0 corner: 1@1).
win openInWorld.
win extent: 760@490.
edit setText: ('This text is in the live editor.', String cr,
    'It has not been accepted or saved.') asText.
edit hasUnacceptedEdits: true.
edit textEdited: edit text.
pad

Download checkpoint 3 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 3: Read the live buffer
Read the live buffer in the actual Squeak image.

Try it: Select and print pad currentText only if you kept a named reference; otherwise inspect the returned model. Closing now must ask Save, Discard or Cancel even though the model text has not been accepted.

Build 04 · Add four action buttons

The toolbar builds four SimpleButtonMorphs. Each button has this model as its target and an action selector: #newDocument, #openDocument, #saveDocument or #saveDocumentAs. LayoutFrame fractions follow resizing; the fixed 42-pixel offset reserves the toolbar height. These buttons already call the installed complete application methods.

Installed method · buildToolbar
buildToolbar
    | bar x |
    bar := Morph new color: (Color r: 0.91 g: 0.93 b: 0.96).
    x := 8.
    #(('New' newDocument) ('Open...' openDocument) ('Save' saveDocument)
        ('Save As...' saveDocumentAs)) do: [:spec | | button |
        button := SimpleButtonMorph new target: self; actionSelector: spec second;
            label: spec first; extent: 104@28.
        bar addMorph: button.
        button position: x@7.
        x := x + 112].
    ^ bar
Installed method · createEditor
createEditor
    editor := PluggableTextMorph on: self text: #text accept: #acceptText:.
    editor acceptOnCR: false; plainTextOnly: true; editTextSelector: #noteTextEdited:.
    ^ editor
Installed method · buildWindow
buildWindow
    | toolbar |
    self createWindow.
    toolbar := self buildToolbar.
    window addMorph: toolbar fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 0;
        bottomOffset: 42).
    self createEditor.
    window addMorph: editor fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 1;
        topOffset: 42; bottomOffset: -50).
    statusMorph := StringMorph contents: self statusText.
    pathMorph := StringMorph contents: 'No file yet'.
    window addMorph: statusMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -46; bottomOffset: -25).
    window addMorph: pathMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -24; bottomOffset: -3).
    self refreshChrome.
    ^ window
Complete runnable checkpoint 4
Checkpoint 4 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad win edit toolbar |
pad := MorphicNotepad new.
win := pad createWindow.
toolbar := pad buildToolbar.
win addMorph: toolbar fullFrame: (LayoutFrame new
    leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 0;
    bottomOffset: 42).
edit := pad createEditor.
win addMorph: edit fullFrame: (LayoutFrame new
    leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 1;
    topOffset: 42).
win openInWorld.
win extent: 760@490.
pad

Download checkpoint 4 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 4: Add four action buttons
Add four action buttons in the actual Squeak image.

Try it: Resize the window and check that the editor fills the remaining space. The file buttons are functional; use only a disposable file while learning.

Build 05 · Show filename and dirty status

The complete #buildWindow adds the toolbar, editor, status and path. A leading asterisk and Modified reflect comparison with savedText. Unmodified means the content matches the snapshot; an empty Untitled document can be unmodified without having any file on disk.

Installed method · buildWindow
buildWindow
    | toolbar |
    self createWindow.
    toolbar := self buildToolbar.
    window addMorph: toolbar fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 0;
        bottomOffset: 42).
    self createEditor.
    window addMorph: editor fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 1;
        topOffset: 42; bottomOffset: -50).
    statusMorph := StringMorph contents: self statusText.
    pathMorph := StringMorph contents: 'No file yet'.
    window addMorph: statusMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -46; bottomOffset: -25).
    window addMorph: pathMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -24; bottomOffset: -3).
    self refreshChrome.
    ^ window
Installed method · refreshChrome
refreshChrome
    window ifNotNil: [window setLabel: self windowTitle].
    statusMorph ifNotNil: [statusMorph contents: self statusText].
    pathMorph ifNotNil: [pathMorph contents: (fileName ifNil: ['No file yet'] ifNotNil: [fileName])]
Installed method · windowTitle
windowTitle
    ^ (self isDirty ifTrue: ['* '] ifFalse: ['']), self displayName, ' - Morphic Notepad'
Installed method · statusText
statusText
    ^ statusMessage, '  |  ', (self isDirty ifTrue: ['Modified'] ifFalse: ['Unmodified']),
        '  |  ', self currentText size printString, ' characters'
Installed method · displayName
displayName
    ^ fileName ifNil: ['Untitled'] ifNotNil: [FileDirectory localNameFor: fileName]
Complete runnable checkpoint 5
Checkpoint 5 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad editor setText: ('A document has three useful states:', String cr,
    'the live buffer, accepted text, and the saved snapshot.') asText.
pad editor hasUnacceptedEdits: true.
pad editor textEdited: pad editor text.
pad

Download checkpoint 5 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 5: Show filename and dirty status
Show filename and dirty status in the actual Squeak image.

Try it: Type more text. The title and character count change while the path remains No file yet. Accepting text in Squeak does not save it to disk.

Build 06 · Guard New with Save / Discard / Cancel

This checkpoint starts with a clean New and then creates an unaccepted draft. #newDocument asks #canLeaveDocument before resetting any text. Save continues only when #saveDocument returns true. Discard permits the action. Cancel, dialog dismissal, canceled Save As and failed saves return false.

Installed method · newDocument
newDocument
    self canLeaveDocument ifFalse: [^ false].
    statusMessage := 'New document'.
    self replaceDocumentWith: '' named: nil.
    ^ true
Installed method · canLeaveDocument
canLeaveDocument
    | answer |
    self isDirty ifFalse: [^ true].
    answer := self askUnsavedChanges.
    answer = #discard ifTrue: [^ true].
    answer = #save ifTrue: [^ self saveDocument].
    "Cancel, nil, and every unexpected answer are conservative."
    ^ false
Installed method · askUnsavedChanges
askUnsavedChanges
    ^ UIManager default
        chooseOptionFrom: #('Save' 'Discard' 'Cancel')
        values: #(save discard cancel)
        title: 'Save changes to ', self displayName, '?'
Installed method · replaceDocumentWith:named:
replaceDocumentWith: aString named: aPath
    "Only call after a successful load, New, or Save."
    documentText := aString copy.
    savedText := aString copy.
    fileName := aPath.
    self changed: #text.
    self refreshChrome
Complete runnable checkpoint 6
Checkpoint 6 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad newDocument.
pad editor setText: ('Keep this unsaved draft.', String cr,
    'Click New, then choose Cancel to keep working.') asText.
pad editor hasUnacceptedEdits: true.
pad editor textEdited: pad editor text.
pad

Download checkpoint 6 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 6: Guard New with Save / Discard / Cancel
Guard New with Save / Discard / Cancel in the actual Squeak image.
NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
New asks about the unsaved draft before discarding it.
New asks about the unsaved draft before discarding it. This is an additional real usage capture, after interacting with the completed app.

Try it: Click New and choose Cancel. The draft must stay visible. Click New again and choose Discard to obtain a clean Untitled document.

Build 07 · Open a UTF-8 document

Open requests a full file path using the current UIManager. Canceling that path changes nothing. With a path selected, the unsaved guard runs before the read; this avoids stale contents when Save writes the very file being opened. The document is replaced only after a successful strict UTF-8 read. CR, LF and CRLF become Squeak editor line endings.

Installed method · openDocument
openDocument
    | path contents |
    path := self requestPathFor: 'Open'.
    (self validPathAnswer: path) ifFalse: [^ false].
    self canLeaveDocument ifFalse: [^ false].
    "Keep the old document until the read succeeds. Read after a possible Save,
    because the selected path can be the same file we just saved."
    [contents := self readTextFrom: path] on: Error do: [:error |
        self reportError: 'Open failed: ', error messageText. ^ false].
    statusMessage := 'Opened'.
    self replaceDocumentWith: contents named: (FileDirectory default fullNameFor: path).
    ^ true
Installed method · requestPathFor:
requestPathFor: anAction
    "Native UIManager request. An empty answer, nil, or Cancel changes nothing."
    ^ UIManager default
        request: anAction, ' - enter a full file path'
        initialAnswer: (fileName ifNil: [FileDirectory default fullNameFor: 'notes.txt'])
        onCancelReturn: nil
Installed method · readTextFrom:
readTextFrom: aPath
    | stream bytes |
    stream := FileStream readOnlyFileNamed: aPath.
    stream ifNil: [self error: 'The file could not be opened'].
    [stream binary. bytes := stream upToEnd] ensure: [stream close].
    ^ (self decodeUTF8Bytes: bytes) withSqueakLineEndings
Installed method · decodeUTF8Bytes:
decodeUTF8Bytes: bytes
    "Reject noncanonical UTF-8, surrogate code points and values above U+10FFFF.
    Squeak 6.1's native decoder is permissive and removes interior U+FEFF."
    | index size |
    index := 1.
    size := bytes size.
    ^ String streamContents: [:out |
        [index <= size] whileTrue: [| first code extra minimum continuation start |
            start := index.
            first := bytes at: index.
            index := index + 1.
            first < 128
                ifTrue: [code := first. extra := 0. minimum := 0]
                ifFalse: [
                    (first between: 194 and: 223)
                        ifTrue: [code := first bitAnd: 31. extra := 1. minimum := 128]
                        ifFalse: [
                            (first between: 224 and: 239)
                                ifTrue: [code := first bitAnd: 15. extra := 2. minimum := 2048]
                                ifFalse: [
                                    (first between: 240 and: 244)
                                        ifTrue: [code := first bitAnd: 7. extra := 3. minimum := 65536]
                                        ifFalse: [self error: 'Invalid UTF-8 at byte ', start printString]]]].
            index + extra - 1 > size ifTrue: [
                self error: 'Truncated UTF-8 at byte ', start printString].
            1 to: extra do: [:ignored |
                continuation := bytes at: index.
                (continuation between: 128 and: 191) ifFalse: [
                    self error: 'Invalid UTF-8 continuation at byte ', index printString].
                code := (code bitShift: 6) + (continuation bitAnd: 63).
                index := index + 1].
            (code < minimum or: [code > 1114111 or: [code between: 55296 and: 57343]])
                ifTrue: [self error: 'Invalid Unicode scalar at byte ', start printString].
            (start = 1 and: [code = 65279]) ifFalse: [out nextPut: (Unicode value: code)]]]
Installed method · replaceDocumentWith:named:
replaceDocumentWith: aString named: aPath
    "Only call after a successful load, New, or Save."
    documentText := aString copy.
    savedText := aString copy.
    fileName := aPath.
    self changed: #text.
    self refreshChrome
Complete runnable checkpoint 7
Checkpoint 7 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad

Download checkpoint 7 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 7: Open a UTF-8 document
Open a UTF-8 document in the actual Squeak image.
NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
The actual Open path dialog. This recording uses a tutorial-owned sample file.
The actual Open path dialog. This recording uses a tutorial-owned sample file. This is an additional real usage capture, after interacting with the completed app.

Try it: Use Open... on a disposable UTF-8 text file. Try a nonexistent path too: the error is reported and the current buffer is preserved.

Build 08 · Save and Save As safely

Save uses the current filename, or delegates to Save As when Untitled. Save As asks before replacing an existing destination. Saving snapshots the live buffer, encodes valid Unicode as UTF-8 with LF, writes and verifies a sibling temporary file, preserves the previous file as a backup, and installs the staged file. Dirty state clears only after success. This is a recovery-oriented tutorial implementation, without atomicity or concurrent-edit guarantees.

Installed method · saveDocument
saveDocument
    fileName ifNil: [^ self saveDocumentAs].
    ^ self saveTo: fileName
Installed method · saveDocumentAs
saveDocumentAs
    | path |
    path := self requestPathFor: 'Save As'.
    (self validPathAnswer: path) ifFalse: [^ false].
    path := FileDirectory default fullNameFor: path.
    ((FileDirectory default fileExists: path) and: [(self confirmOverwrite: path) ~= true])
        ifTrue: [^ false].
    ^ self saveTo: path
Installed method · saveTo:
saveTo: aPath
    | contents |
    contents := self currentText copy.
    [self writeText: contents to: aPath] on: Error do: [:error |
        self reportError: 'Save failed: ', error messageText. ^ false].
    documentText := contents copy.
    savedText := contents copy.
    fileName := aPath.
    editor ifNotNil: [editor hasUnacceptedEdits: false].
    statusMessage := 'Saved'.
    self refreshChrome.
    ^ true
Installed method · writeText:to:
writeText: aString to: aPath
    "Stage a complete UTF-8 file before replacing the destination.
    A backup is retained until installation succeeds; no atomicity is promised."
    | directory leaf temporary backup stream hadOriginal installed bytes staged |
    directory := FileDirectory on: (FileDirectory dirPathFor: aPath).
    leaf := FileDirectory localNameFor: aPath.
    leaf isEmpty ifTrue: [self error: 'A file name is required'].
    (directory directoryExists: leaf) ifTrue: [self error: 'The path names a directory'].
    bytes := self encodedTextBytes: aString.
    temporary := self unusedNameIn: directory basedOn: leaf, '.notepad-tmp-'.
    backup := self unusedNameIn: directory basedOn: leaf, '.notepad-backup-'.
    hadOriginal := false.
    installed := false.
    [
        stream := FileStream newFileNamed: (directory fullNameFor: temporary).
        stream ifNil: [self error: 'The temporary file could not be created'].
        [stream binary; nextPutAll: bytes; flush] ensure: [stream close].
        stream := FileStream readOnlyFileNamed: (directory fullNameFor: temporary).
        stream ifNil: [self error: 'The temporary file could not be verified'].
        [stream binary. staged := stream contents] ensure: [stream close].
        staged = bytes ifFalse: [self error: 'The staged file did not match the document'].
        (directory fileExists: leaf) ifTrue: [
            self rename: leaf to: backup in: directory.
            hadOriginal := true].
        self rename: temporary to: leaf in: directory.
        installed := true
    ] on: Error do: [:error |
        (hadOriginal and: [(directory fileExists: leaf) not]) ifTrue: [
            [self rename: backup to: leaf in: directory] on: Error do: [:rollbackError |
                self error: error messageText, '. Original file is preserved at ',
                    (directory fullNameFor: backup), '. Restore failed: ', rollbackError messageText]].
        (directory fileExists: temporary) ifTrue: [
            [directory deleteFileNamed: temporary] on: Error do: [:ignored | ]].
        (hadOriginal and: [directory fileExists: backup]) ifTrue: [
            self error: error messageText, '. Original file is preserved at ',
                (directory fullNameFor: backup)].
        error pass].
    (installed and: [hadOriginal]) ifTrue: [
        "A harmless leftover backup must not turn a successful save into failure."
        [directory deleteFileNamed: backup] on: Error do: [:ignored | ]].
    ^ true
Installed method · rename:to:in:
rename: oldName to: newName in: aDirectory
    "Do not allow FileDirectory to open an implicit overwrite dialog."
    ((aDirectory fileExists: newName) or: [aDirectory directoryExists: newName])
        ifTrue: [self error: 'The destination changed while saving'].
    [aDirectory rename: oldName toBe: newName]
        on: ReplaceExistingFileException do: [:error |
            self error: 'The destination changed while saving'].
    ((aDirectory fileExists: oldName) not and: [aDirectory fileExists: newName])
        ifFalse: [self error: 'The file rename did not complete']
Installed method · encodedTextBytes:
encodedTextBytes: aString
    "Encode Unicode scalars as UTF-8 without a BOM, using LF line endings."
    | normalized |
    normalized := aString withLineEndings: String lf.
    ^ ByteArray streamContents: [:out |
        normalized do: [:character | | code |
            code := character asUnicode.
            (code isNil or: [code < 0 or: [code > 1114111 or: [code between: 55296 and: 57343]]])
                ifTrue: [self error: 'The document contains an invalid Unicode scalar'].
            code < 128
                ifTrue: [out nextPut: code]
                ifFalse: [
                    code < 2048
                        ifTrue: [
                            out nextPut: 192 + (code bitShift: -6);
                                nextPut: 128 + (code bitAnd: 63)]
                        ifFalse: [
                            code < 65536
                                ifTrue: [
                                    out nextPut: 224 + (code bitShift: -12);
                                        nextPut: 128 + ((code bitShift: -6) bitAnd: 63);
                                        nextPut: 128 + (code bitAnd: 63)]
                                ifFalse: [
                                    out nextPut: 240 + (code bitShift: -18);
                                        nextPut: 128 + ((code bitShift: -12) bitAnd: 63);
                                        nextPut: 128 + ((code bitShift: -6) bitAnd: 63);
                                        nextPut: 128 + (code bitAnd: 63)]]]]]
Complete runnable checkpoint 8
Checkpoint 8 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad editor setText: ('Morphic Notepad', String cr,
    'This file was written by a Smalltalk model.', String cr,
    'Save As asks before replacing an existing file.') asText.
pad editor hasUnacceptedEdits: true.
pad editor textEdited: pad editor text.
pad

Download checkpoint 8 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 8: Save and Save As safely
Save and Save As safely in the actual Squeak image.
NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
The actual Save As path dialog before the first file is written.
The actual Save As path dialog before the first file is written. This is an additional real usage capture, after interacting with the completed app.

Try it: Click Save As... and choose a new disposable filename. Edit and click Save. Try Save As to that existing path and decline replacement; the draft and file should remain unchanged.

Build 09 · Guard the title-bar close button

Squeak 6.1 routes its title-bar close control through SystemWindow>>delete, which asks model okToClose. The model delegates to #canLeaveDocument, so unaccepted edits are protected on native close too. #windowIsClosing clears references only after a successful close.

Installed method · okToClose
okToClose
    "SystemWindow>>delete asks this before closing, including the title-bar X."
    ^ self canLeaveDocument
Installed method · canLeaveDocument
canLeaveDocument
    | answer |
    self isDirty ifFalse: [^ true].
    answer := self askUnsavedChanges.
    answer = #discard ifTrue: [^ true].
    answer = #save ifTrue: [^ self saveDocument].
    "Cancel, nil, and every unexpected answer are conservative."
    ^ false
Installed method · windowIsClosing
windowIsClosing
    "SystemWindow sends this only after the close guard succeeds."
    documentText := self currentText copy.
    window := nil.
    editor := nil.
    statusMorph := nil.
    pathMorph := nil.
    super windowIsClosing
Complete runnable checkpoint 9
Checkpoint 9 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad editor setText: ('The close button uses the same guard.', String cr,
    'Click the red X and choose Cancel.') asText.
pad editor hasUnacceptedEdits: true.
pad editor textEdited: pad editor text.
pad

Download checkpoint 9 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 9: Guard the title-bar close button
Guard the title-bar close button in the actual Squeak image.
NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
The actual title-bar close guard. Cancel leaves the modified document open.
The actual title-bar close guard. Cancel leaves the modified document open. This is an additional real usage capture, after interacting with the completed app.

Try it: Click the red X and choose Cancel: the window and draft remain. Try again with Discard, or Save to a disposable path, to close.

Build 10 · Complete Notepad workflow

All parts work together in one native window: a model, an editable Morph, direct action buttons, path/status feedback, real file I/O and one consistent transition guard. The setup inserts a demonstration draft programmatically; it does not record typing or create a file. Run the SUnit suite separately to inspect the tested behavior.

Installed method · class>>open
open
    ^ self new open
Installed method · open
open
    window ifNotNil: [window comeToFront. ^ self].
    self buildWindow.
    window openInWorld.
    window extent: 760@490.
    ^ self
Installed method · buildWindow
buildWindow
    | toolbar |
    self createWindow.
    toolbar := self buildToolbar.
    window addMorph: toolbar fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 0;
        bottomOffset: 42).
    self createEditor.
    window addMorph: editor fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 1;
        topOffset: 42; bottomOffset: -50).
    statusMorph := StringMorph contents: self statusText.
    pathMorph := StringMorph contents: 'No file yet'.
    window addMorph: statusMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -46; bottomOffset: -25).
    window addMorph: pathMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -24; bottomOffset: -3).
    self refreshChrome.
    ^ window
Installed method · currentText
currentText
    "Always read the live buffer before Save, New, Open or Close."
    ^ editor ifNil: [documentText] ifNotNil: [editor text asString]
Installed method · canLeaveDocument
canLeaveDocument
    | answer |
    self isDirty ifFalse: [^ true].
    answer := self askUnsavedChanges.
    answer = #discard ifTrue: [^ true].
    answer = #save ifTrue: [^ self saveDocument].
    "Cancel, nil, and every unexpected answer are conservative."
    ^ false
Installed method · saveTo:
saveTo: aPath
    | contents |
    contents := self currentText copy.
    [self writeText: contents to: aPath] on: Error do: [:error |
        self reportError: 'Save failed: ', error messageText. ^ false].
    documentText := contents copy.
    savedText := contents copy.
    fileName := aPath.
    editor ifNotNil: [editor hasUnacceptedEdits: false].
    statusMessage := 'Saved'.
    self refreshChrome.
    ^ true
Complete runnable checkpoint 10
Checkpoint 10 · Workspace Do it
"Requires MorphicNotepad.st to be filed in once. Run the whole block in a Workspace."
| pad |
pad := MorphicNotepad open.
pad editor setText: ('A small, complete Morphic application', String cr, String cr,
    '1. Edit this multiline document.', String cr,
    '2. Save As to a new disposable text file.', String cr,
    '3. Edit again and test New / Cancel.', String cr,
    '4. Open the saved file.', String cr,
    '5. Close using the native title bar.') asText.
pad editor hasUnacceptedEdits: true.
pad editor textEdited: pad editor text.
pad

Download checkpoint 10 .st

NATIVE SQUEAK CAPTURECONSTRUCTION CHECKPOINT
Morphic Notepad construction step 10: Complete Notepad workflow
Complete Notepad workflow in the actual Squeak image.

Try it: Complete the five steps with a generated sample file. Normal Return inserts a line; use the app buttons for disk operations because native text acceptance is a separate action.

Use it: write, save, open, and cancel

Open the finished app with MorphicNotepad open. Type two or three lines. The title acquires an asterisk and the status reports a modification, including edits that have not been accepted into the model.

  1. Click Save As… and enter a new full path in a folder you created for these examples. Cancel leaves your document unchanged.
  2. After a successful save, the filename appears and the modified marker clears.
  3. Make another edit, then use Save. This writes the live buffer to the current file.
  4. Use Open… to load a valid UTF-8 text file. If the current document is modified, choose Save, Discard, or Cancel.
  5. Test New and the window’s red close control with unsaved edits. Cancel must leave the window and text intact.
NATIVE SQUEAK CAPTURERECORDED WORKFLOW
Real typing and saving in the native Morphic Notepad
Actual mouse and keyboard workflow in Squeak: create multiline text and save it to a tutorial-owned sample file.
NATIVE SQUEAK CAPTURERECORDED WORKFLOW
Native unsaved-changes dialog and cancellation workflow
Actual Squeak workflow: edit a document, cancel leaving it, then discard the temporary draft and reopen the saved sample.
NATIVE SQUEAK CAPTURERECORDED WORKFLOW
The native close confirmation with Save Discard and Cancel
Actual title-bar close action, followed by Cancel. The unsaved text stays in the open editor.

These recordings show real mouse and keyboard actions in Squeak. Playback is accelerated and the final frames are held briefly. Play is opt-in; Stop restores the still image.

Understand the buffer, model and file

currentText reads the live widget buffer. text is the accepted model value. savedText is the snapshot associated with the last successful load or save. Dirty state compares the live buffer to that snapshot; accepting text must not erase the need to save.

Read the live editor buffer
currentText
    "Always read the live buffer before Save, New, Open or Close."
    ^ editor ifNil: [documentText] ifNotNil: [editor text asString]
Compare against the saved snapshot
isDirty
    ^ self currentText ~= savedText

The edit callback refreshes the title and status without replacing the editor text on every keystroke. Replacing the buffer while someone is typing can disturb their selection and cursor. Document replacement after New or Open is a separate operation.

Edit notification, not a file write
noteTextEdited: aText
    "Called by PluggableTextMorph on edits. Do not reset its text here."
    statusMessage := 'Editing'.
    self refreshChrome

File handling and failure behavior

The toolbar is the application’s file interface. Save As asks before replacing an existing destination. A canceled path or overwrite question stops the action. A failed save keeps the live text and modified state; New, Open or Close cannot proceed through a failed Save choice.

Saving writes a complete temporary sibling file before replacing the destination. The old file is kept as a backup during replacement. Error paths attempt restoration and preserve recovery information if restoration fails. This teaching implementation does not lock out other editors or promise crash-atomic replacement.

Files use UTF-8. The reader validates byte sequences before decoding. A leading UTF-8 BOM is removed, an interior U+FEFF is preserved, and CR/LF/CRLF line endings normalize to the editor’s CR. Saving writes UTF-8 without an added BOM and uses LF line endings. This is a small plain-text editor; it does not infer encodings, preserve rich-text formatting, or provide a large-file editing engine.

One shared Save / Discard / Cancel guard
canLeaveDocument
    | answer |
    self isDirty ifFalse: [^ true].
    answer := self askUnsavedChanges.
    answer = #discard ifTrue: [^ true].
    answer = #save ifTrue: [^ self saveDocument].
    "Cancel, nil, and every unexpected answer are conservative."
    ^ false
Native title-bar close hook
okToClose
    "SystemWindow>>delete asks this before closing, including the title-bar X."
    ^ self canLeaveDocument

Tests, source, and cleanup

The main suite passed 29 SUnit tests. An independent native review passed 42 further safety and UTF-8 assertions. File checks used generated sample files only, and the recordings separately exercised actual typing, Save As, Open, New cancellation and title-bar close cancellation. The tests cover live unaccepted edits, accepted-but-unsaved text, cancellation, overwrite rejection, failed save/open, same-file Open after Save, staged replacement and restoration, UTF-8 handling, and the actual SystemWindow close path.

Download the test classes, file them in after the application source, and run MorphicNotepadTest suite run with Print it, or find MorphicNotepadTest in Squeak’s Test Runner. The test source creates its own tutorial fixtures; read its setup before running it in an image containing important work.

Read the complete application source
Complete Smalltalk file-in source · use File List fileIn
"Morphic Notepad. Tested with Squeak 6.1. File in once, then evaluate MorphicNotepad open."

Model subclass: #MorphicNotepad
    instanceVariableNames: 'documentText savedText fileName window editor statusMorph pathMorph statusMessage'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'Morphic-Notepad-Tutorial'!

!MorphicNotepad methodsFor: 'initialization'!
initialize
    super initialize.
    documentText := ''.
    savedText := ''.
    fileName := nil.
    statusMessage := 'Ready'.
! !

!MorphicNotepad methodsFor: 'accessing'!
text
    "The accepted model text. The editor may contain newer, unaccepted text."
    ^ documentText
! !

!MorphicNotepad methodsFor: 'accessing'!
currentText
    "Always read the live buffer before Save, New, Open or Close."
    ^ editor ifNil: [documentText] ifNotNil: [editor text asString]
! !

!MorphicNotepad methodsFor: 'accessing'!
isDirty
    ^ self currentText ~= savedText
! !

!MorphicNotepad methodsFor: 'accessing'!
fileName
    ^ fileName
! !

!MorphicNotepad methodsFor: 'accessing'!
window
    ^ window
! !

!MorphicNotepad methodsFor: 'accessing'!
editor
    ^ editor
! !

!MorphicNotepad methodsFor: 'accessing'!
statusMessage
    ^ statusMessage
! !

!MorphicNotepad methodsFor: 'accessing'!
displayName
    ^ fileName ifNil: ['Untitled'] ifNotNil: [FileDirectory localNameFor: fileName]
! !

!MorphicNotepad methodsFor: 'accessing'!
windowTitle
    ^ (self isDirty ifTrue: ['* '] ifFalse: ['']), self displayName, ' - Morphic Notepad'
! !

!MorphicNotepad methodsFor: 'accessing'!
statusText
    ^ statusMessage, '  |  ', (self isDirty ifTrue: ['Modified'] ifFalse: ['Unmodified']),
        '  |  ', self currentText size printString, ' characters'
! !

!MorphicNotepad methodsFor: 'editing'!
acceptText: aText
    "Accepting an edit changes the model; it does not write a file."
    documentText := aText asString copy.
    self refreshChrome.
    ^ true
! !

!MorphicNotepad methodsFor: 'editing'!
noteTextEdited: aText
    "Called by PluggableTextMorph on edits. Do not reset its text here."
    statusMessage := 'Editing'.
    self refreshChrome
! !

!MorphicNotepad methodsFor: 'editing'!
replaceDocumentWith: aString named: aPath
    "Only call after a successful load, New, or Save."
    documentText := aString copy.
    savedText := aString copy.
    fileName := aPath.
    self changed: #text.
    self refreshChrome
! !

!MorphicNotepad methodsFor: 'editing'!
refreshChrome
    window ifNotNil: [window setLabel: self windowTitle].
    statusMorph ifNotNil: [statusMorph contents: self statusText].
    pathMorph ifNotNil: [pathMorph contents: (fileName ifNil: ['No file yet'] ifNotNil: [fileName])]
! !

!MorphicNotepad methodsFor: 'building'!
open
    window ifNotNil: [window comeToFront. ^ self].
    self buildWindow.
    window openInWorld.
    window extent: 760@490.
    ^ self
! !

!MorphicNotepad methodsFor: 'building'!
buildWindow
    | toolbar |
    self createWindow.
    toolbar := self buildToolbar.
    window addMorph: toolbar fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 0;
        bottomOffset: 42).
    self createEditor.
    window addMorph: editor fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 0; rightFraction: 1; bottomFraction: 1;
        topOffset: 42; bottomOffset: -50).
    statusMorph := StringMorph contents: self statusText.
    pathMorph := StringMorph contents: 'No file yet'.
    window addMorph: statusMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -46; bottomOffset: -25).
    window addMorph: pathMorph fullFrame: (LayoutFrame new
        leftFraction: 0; topFraction: 1; rightFraction: 1; bottomFraction: 1;
        leftOffset: 10; topOffset: -24; bottomOffset: -3).
    self refreshChrome.
    ^ window
! !

!MorphicNotepad methodsFor: 'building'!
createWindow
    window := SystemWindow new model: self.
    window setLabel: self windowTitle.
    ^ window
! !

!MorphicNotepad methodsFor: 'building'!
createEditor
    editor := PluggableTextMorph on: self text: #text accept: #acceptText:.
    editor acceptOnCR: false; plainTextOnly: true; editTextSelector: #noteTextEdited:.
    ^ editor
! !

!MorphicNotepad methodsFor: 'building'!
buildToolbar
    | bar x |
    bar := Morph new color: (Color r: 0.91 g: 0.93 b: 0.96).
    x := 8.
    #(('New' newDocument) ('Open...' openDocument) ('Save' saveDocument)
        ('Save As...' saveDocumentAs)) do: [:spec | | button |
        button := SimpleButtonMorph new target: self; actionSelector: spec second;
            label: spec first; extent: 104@28.
        bar addMorph: button.
        button position: x@7.
        x := x + 112].
    ^ bar
! !

!MorphicNotepad methodsFor: 'dialogs'!
requestPathFor: anAction
    "Native UIManager request. An empty answer, nil, or Cancel changes nothing."
    ^ UIManager default
        request: anAction, ' - enter a full file path'
        initialAnswer: (fileName ifNil: [FileDirectory default fullNameFor: 'notes.txt'])
        onCancelReturn: nil
! !

!MorphicNotepad methodsFor: 'dialogs'!
askUnsavedChanges
    ^ UIManager default
        chooseOptionFrom: #('Save' 'Discard' 'Cancel')
        values: #(save discard cancel)
        title: 'Save changes to ', self displayName, '?'
! !

!MorphicNotepad methodsFor: 'dialogs'!
confirmOverwrite: aPath
    ^ UIManager default confirm: 'Replace the existing file?', String cr, aPath
! !

!MorphicNotepad methodsFor: 'dialogs'!
reportError: aString
    statusMessage := aString.
    self refreshChrome.
    UIManager default inform: aString
! !

!MorphicNotepad methodsFor: 'dialogs'!
validPathAnswer: anAnswer
    ^ anAnswer isString and: [anAnswer withBlanksTrimmed notEmpty]
! !

!MorphicNotepad methodsFor: 'actions'!
canLeaveDocument
    | answer |
    self isDirty ifFalse: [^ true].
    answer := self askUnsavedChanges.
    answer = #discard ifTrue: [^ true].
    answer = #save ifTrue: [^ self saveDocument].
    "Cancel, nil, and every unexpected answer are conservative."
    ^ false
! !

!MorphicNotepad methodsFor: 'actions'!
newDocument
    self canLeaveDocument ifFalse: [^ false].
    statusMessage := 'New document'.
    self replaceDocumentWith: '' named: nil.
    ^ true
! !

!MorphicNotepad methodsFor: 'actions'!
openDocument
    | path contents |
    path := self requestPathFor: 'Open'.
    (self validPathAnswer: path) ifFalse: [^ false].
    self canLeaveDocument ifFalse: [^ false].
    "Keep the old document until the read succeeds. Read after a possible Save,
    because the selected path can be the same file we just saved."
    [contents := self readTextFrom: path] on: Error do: [:error |
        self reportError: 'Open failed: ', error messageText. ^ false].
    statusMessage := 'Opened'.
    self replaceDocumentWith: contents named: (FileDirectory default fullNameFor: path).
    ^ true
! !

!MorphicNotepad methodsFor: 'actions'!
saveDocument
    fileName ifNil: [^ self saveDocumentAs].
    ^ self saveTo: fileName
! !

!MorphicNotepad methodsFor: 'actions'!
saveDocumentAs
    | path |
    path := self requestPathFor: 'Save As'.
    (self validPathAnswer: path) ifFalse: [^ false].
    path := FileDirectory default fullNameFor: path.
    ((FileDirectory default fileExists: path) and: [(self confirmOverwrite: path) ~= true])
        ifTrue: [^ false].
    ^ self saveTo: path
! !

!MorphicNotepad methodsFor: 'actions'!
saveTo: aPath
    | contents |
    contents := self currentText copy.
    [self writeText: contents to: aPath] on: Error do: [:error |
        self reportError: 'Save failed: ', error messageText. ^ false].
    documentText := contents copy.
    savedText := contents copy.
    fileName := aPath.
    editor ifNotNil: [editor hasUnacceptedEdits: false].
    statusMessage := 'Saved'.
    self refreshChrome.
    ^ true
! !

!MorphicNotepad methodsFor: 'files'!
writeText: aString to: aPath
    "Stage a complete UTF-8 file before replacing the destination.
    A backup is retained until installation succeeds; no atomicity is promised."
    | directory leaf temporary backup stream hadOriginal installed bytes staged |
    directory := FileDirectory on: (FileDirectory dirPathFor: aPath).
    leaf := FileDirectory localNameFor: aPath.
    leaf isEmpty ifTrue: [self error: 'A file name is required'].
    (directory directoryExists: leaf) ifTrue: [self error: 'The path names a directory'].
    bytes := self encodedTextBytes: aString.
    temporary := self unusedNameIn: directory basedOn: leaf, '.notepad-tmp-'.
    backup := self unusedNameIn: directory basedOn: leaf, '.notepad-backup-'.
    hadOriginal := false.
    installed := false.
    [
        stream := FileStream newFileNamed: (directory fullNameFor: temporary).
        stream ifNil: [self error: 'The temporary file could not be created'].
        [stream binary; nextPutAll: bytes; flush] ensure: [stream close].
        stream := FileStream readOnlyFileNamed: (directory fullNameFor: temporary).
        stream ifNil: [self error: 'The temporary file could not be verified'].
        [stream binary. staged := stream contents] ensure: [stream close].
        staged = bytes ifFalse: [self error: 'The staged file did not match the document'].
        (directory fileExists: leaf) ifTrue: [
            self rename: leaf to: backup in: directory.
            hadOriginal := true].
        self rename: temporary to: leaf in: directory.
        installed := true
    ] on: Error do: [:error |
        (hadOriginal and: [(directory fileExists: leaf) not]) ifTrue: [
            [self rename: backup to: leaf in: directory] on: Error do: [:rollbackError |
                self error: error messageText, '. Original file is preserved at ',
                    (directory fullNameFor: backup), '. Restore failed: ', rollbackError messageText]].
        (directory fileExists: temporary) ifTrue: [
            [directory deleteFileNamed: temporary] on: Error do: [:ignored | ]].
        (hadOriginal and: [directory fileExists: backup]) ifTrue: [
            self error: error messageText, '. Original file is preserved at ',
                (directory fullNameFor: backup)].
        error pass].
    (installed and: [hadOriginal]) ifTrue: [
        "A harmless leftover backup must not turn a successful save into failure."
        [directory deleteFileNamed: backup] on: Error do: [:ignored | ]].
    ^ true
! !

!MorphicNotepad methodsFor: 'files'!
rename: oldName to: newName in: aDirectory
    "Do not allow FileDirectory to open an implicit overwrite dialog."
    ((aDirectory fileExists: newName) or: [aDirectory directoryExists: newName])
        ifTrue: [self error: 'The destination changed while saving'].
    [aDirectory rename: oldName toBe: newName]
        on: ReplaceExistingFileException do: [:error |
            self error: 'The destination changed while saving'].
    ((aDirectory fileExists: oldName) not and: [aDirectory fileExists: newName])
        ifFalse: [self error: 'The file rename did not complete']
! !

!MorphicNotepad methodsFor: 'files'!
unusedNameIn: aDirectory basedOn: prefix
    | candidate number |
    number := 1.
    [candidate := prefix, number printString.
     (aDirectory fileExists: candidate) or: [aDirectory directoryExists: candidate]]
        whileTrue: [number := number + 1].
    ^ candidate
! !

!MorphicNotepad methodsFor: 'closing'!
okToClose
    "SystemWindow>>delete asks this before closing, including the title-bar X."
    ^ self canLeaveDocument
! !

!MorphicNotepad methodsFor: 'closing'!
windowIsClosing
    "SystemWindow sends this only after the close guard succeeds."
    documentText := self currentText copy.
    window := nil.
    editor := nil.
    statusMorph := nil.
    pathMorph := nil.
    super windowIsClosing
! !

!MorphicNotepad class methodsFor: 'opening'!
open
    ^ self new open
! !

"Strict UTF-8 helpers. Read CR, LF and CRLF as Squeak CR; write LF.
A leading UTF-8 BOM is treated as a signature. Interior U+FEFF is preserved."!

!MorphicNotepad methodsFor: 'files'!
readTextFrom: aPath
    | stream bytes |
    stream := FileStream readOnlyFileNamed: aPath.
    stream ifNil: [self error: 'The file could not be opened'].
    [stream binary. bytes := stream upToEnd] ensure: [stream close].
    ^ (self decodeUTF8Bytes: bytes) withSqueakLineEndings
! !

!MorphicNotepad methodsFor: 'files'!
decodeUTF8Bytes: bytes
    "Reject noncanonical UTF-8, surrogate code points and values above U+10FFFF.
    Squeak 6.1's native decoder is permissive and removes interior U+FEFF."
    | index size |
    index := 1.
    size := bytes size.
    ^ String streamContents: [:out |
        [index <= size] whileTrue: [| first code extra minimum continuation start |
            start := index.
            first := bytes at: index.
            index := index + 1.
            first < 128
                ifTrue: [code := first. extra := 0. minimum := 0]
                ifFalse: [
                    (first between: 194 and: 223)
                        ifTrue: [code := first bitAnd: 31. extra := 1. minimum := 128]
                        ifFalse: [
                            (first between: 224 and: 239)
                                ifTrue: [code := first bitAnd: 15. extra := 2. minimum := 2048]
                                ifFalse: [
                                    (first between: 240 and: 244)
                                        ifTrue: [code := first bitAnd: 7. extra := 3. minimum := 65536]
                                        ifFalse: [self error: 'Invalid UTF-8 at byte ', start printString]]]].
            index + extra - 1 > size ifTrue: [
                self error: 'Truncated UTF-8 at byte ', start printString].
            1 to: extra do: [:ignored |
                continuation := bytes at: index.
                (continuation between: 128 and: 191) ifFalse: [
                    self error: 'Invalid UTF-8 continuation at byte ', index printString].
                code := (code bitShift: 6) + (continuation bitAnd: 63).
                index := index + 1].
            (code < minimum or: [code > 1114111 or: [code between: 55296 and: 57343]])
                ifTrue: [self error: 'Invalid Unicode scalar at byte ', start printString].
            (start = 1 and: [code = 65279]) ifFalse: [out nextPut: (Unicode value: code)]]]
! !

!MorphicNotepad methodsFor: 'files'!
encodedTextBytes: aString
    "Encode Unicode scalars as UTF-8 without a BOM, using LF line endings."
    | normalized |
    normalized := aString withLineEndings: String lf.
    ^ ByteArray streamContents: [:out |
        normalized do: [:character | | code |
            code := character asUnicode.
            (code isNil or: [code < 0 or: [code > 1114111 or: [code between: 55296 and: 57343]]])
                ifTrue: [self error: 'The document contains an invalid Unicode scalar'].
            code < 128
                ifTrue: [out nextPut: code]
                ifFalse: [
                    code < 2048
                        ifTrue: [
                            out nextPut: 192 + (code bitShift: -6);
                                nextPut: 128 + (code bitAnd: 63)]
                        ifFalse: [
                            code < 65536
                                ifTrue: [
                                    out nextPut: 224 + (code bitShift: -12);
                                        nextPut: 128 + ((code bitShift: -6) bitAnd: 63);
                                        nextPut: 128 + (code bitAnd: 63)]
                                ifFalse: [
                                    out nextPut: 240 + (code bitShift: -18);
                                        nextPut: 128 + ((code bitShift: -12) bitAnd: 63);
                                        nextPut: 128 + ((code bitShift: -6) bitAnd: 63);
                                        nextPut: 128 + (code bitAnd: 63)]]]]]
! !

Close each tutorial window using its red close control. Save writes your note as a text file. Saving the Squeak image is a separate operation that retains classes and running objects. Keep the .st source if you want to recreate this app in another image.

Review native controls and events · Review the System Browser and development tools · Official Squeak documentation