TEN CUMULATIVE BUILD STAGES
Build a native Morphic Todo app
Create a useful task manager with native controls, stable selection, validation and confirmed save/reload behavior.
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 a checkpoint, then run its launcher
Build a working native Squeak 6.1 Todo application one capability at a time. Each of these ten cumulative source checkpoints installs the methods introduced so far. The final app can add, edit, delete, complete, filter, save, and reload tasks. Every stage was filed into a fresh copy of the Squeak 6.1 release image and opened successfully.
- Know how to evaluate a Workspace expression and file in a .st file
- Recognize keyword messages, Symbols, blocks, Arrays, and OrderedCollections
- Use a disposable image or save your image before installing tutorial classes
- Download a checkpoint or the final MorphicTodo.st source. In Squeak File List, select it and choose file in.
- Open a Workspace and evaluate MorphicTodo open. To retain a handle, evaluate app := MorphicTodo open.
- The complete application opens empty. Tutorial captures use their own demonstration records; the app does not preload, save, or reload data automatically.
- Install checkpoints in ascending order. Every checkpoint contains all methods needed to that point, so you can start with any stage in a fresh image.
Download the complete workshop
Complete app source · SUnit test source
MorphicTodo openA checkpoint is a complete chunk-format file-in, not one method to paste into a Browser. Close an earlier window before installing the next checkpoint. The model class is reused, so moving backward requires a fresh learning image.
01 · Start with a model and a native window
Create an object that owns the data and a SystemWindow that displays it.
A Morphic application is a conversation between objects. The model owns meaning; Morphs handle drawing and input. Keeping them separate lets us test the same task actions without a screen.
- File in the stage-01 checkpoint from the File List. The source first declares MorphicTodo as a subclass of Model, with instance variables for the task collection, selection, title field, and widgets.
- initialize sends super initialize before setting an empty OrderedCollection, the first task ID, no selected ID, an empty title, and the #all filter. savedTasks is an empty structural snapshot used by the finished application.
- createWindow answers SystemWindow new model: self. The model link lets the window later ask okToClose. open builds once, opens in the current world, and sets a usable 780 by 540 extent.
- Evaluate MorphicTodo open in a Workspace. The class-side open creates a fresh model; the instance-side open returns that model, which is handy for inspection.
initialize
super initialize.
tasks := OrderedCollection new.
nextId := 1.
selectedId := nil.
draft := ''.
filter := #all.
status := 'Ready'.
savedTasks := #().createWindow
window := SystemWindow new model: self.
window setLabel: 'Morphic Todo - build a real application'.
^ windowopen
window ifNotNil: [window comeToFront. ^ self].
self buildWindow.
window openInWorld; extent: 780@540.
^ selfopen
^ self new openUse File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: A genuine empty Squeak SystemWindow. The application already has a model, even though it has no controls.

Try it yourself
- Open two applications. Add behavior later to one and observe that their instance variables are separate.
- Inspect the returned object. tasks is empty; nextId is 1; window is a SystemWindow.
Watch for
- Model is not a widget. Do not send addMorph: to it; send that to the window.
- super initialize preserves superclass setup. Omitting it can create subtle behavior problems in other model subclasses.
02 · Connect an editable title field
Put a native text widget on screen and connect it to model selectors.
PluggableTextMorph does not know what a task is. It asks draftText for text and sends acceptDraft: when text is accepted. That selector-based connection is the central pattern behind pluggable Morphic widgets.
- Create the static instruction label with StringMorph contents:. Add it with a fractional frame so the layout follows the window size.
- Create PluggableTextMorph on: self text: #draftText accept: #acceptDraft:. The hash marks make literal Symbols; the widget uses them as message selectors.
- Set acceptOnCR: true, wrapFlag: false, and plainTextOnly: true. Return accepts the field; it does not add a task. The later Add button performs that separate action.
- Implement currentDraft to read input text asString when the widget exists. This avoids the common bug where clicking Add immediately after typing uses the previously accepted text.
- Use setDraft: when the application changes the field. It stores the value, broadcasts changed: #draftText, and clears the widget’s unaccepted-edit marker.
draftText
^ draftcurrentDraft
"Buttons read live text, even before the editor has accepted it."
^ input ifNil: [draft] ifNotNil: [input text asString]acceptDraft: aText
draft := aText asString copy.
^ truesetDraft: aString
draft := aString copy.
self changed: #draftText.
input ifNotNil: [input hasUnacceptedEdits: false].buildInput
| label |
label := StringMorph contents: 'Task title (select a row to edit it):'.
window addMorph: label frame: (0.025@0.02 corner: 0.975@0.07).
input := PluggableTextMorph on: self text: #draftText accept: #acceptDraft:.
input acceptOnCR: true; wrapFlag: false; plainTextOnly: true.
window addMorph: input frame: (0.025@0.075 corner: 0.975@0.17).Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: A labeled, editable title field above an otherwise empty window.

Try it yourself
- Type a title and inspect draftText before accepting; compare it with currentDraft.
- Press Return and compare again. The model field now matches, but no task exists yet.
Watch for
- Do not read only the accepted model string from a toolbar action. A mouse click can arrive before the editor accepts its text.
- changed: tells dependents to ask the model again; it does not write anything to disk.
03 · Show a selectable task list
Bind a native list to derived labels and translate row indices into stable task IDs.
A filtered row number is a position in the current view, not a permanent identity. Storing a stable ID prevents edits and deletions from touching the wrong task after filtering.
- Represent each task as a three-element Array: {id. title. completed}. The collection preserves insertion order; IDs preserve identity.
- visibleTasks derives the current view from tasks and filter. No filtering mutates the underlying collection.
- taskLabels maps visible records to strings with [ ] or [x]. Those display strings are derived data, never the saved source of truth.
- Build PluggableListMorph on: self list: #taskLabels selected: #selection changeSelected: #selection:. The native list reads its items, reads the current row index, and sends a new index when clicked.
- selection: validates its argument and looks up the selected visible record. It stores the record ID and fills the title editor. selection performs the reverse lookup, answering 0 when the ID is not visible.
- refresh broadcasts #taskLabels and #selection after changes so the list can rebuild its rows and selection.
visibleTasks
^ tasks select: [:task |
filter = #all or: [filter = #active
ifTrue: [task third not]
ifFalse: [task third]]]taskLabels
^ self visibleTasks collect: [:task |
(task third ifTrue: ['[x] '] ifFalse: ['[ ] ']), task second]selection
"The widget speaks row indices; the model stores a stable task ID."
^ self visibleTasks findFirst: [:task | task first = selectedId]selection: anIndex
| visible task |
visible := self visibleTasks.
(anIndex isInteger and: [anIndex between: 1 and: visible size]) ifFalse: [
selectedId := nil.
self setDraft: ''.
self refresh.
^ self].
task := visible at: anIndex.
selectedId := task first.
self setDraft: task second.
self refresh.selectedTask
^ tasks detect: [:task | task first = selectedId] ifNone: [nil]buildList
list := PluggableListMorph on: self
list: #taskLabels selected: #selection changeSelected: #selection:.
window addMorph: list frame: (0.025@0.365 corner: 0.975@0.815).Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: A real PluggableListMorph occupies the main content area. It starts empty.

Try it yourself
- Inspect app taskLabels in an empty model; it answers an empty collection.
- Evaluate app selection: 99. The selection remains empty and no exception is raised. Real task creation arrives in the next checkpoint.
Watch for
- Squeak list positions begin at 1; 0 means no selection.
- Never use the visible row index directly against tasks. In Active, row 1 might actually be the second or fifth stored task.
04 · Add tasks and validate the live input
Turn an input string into a valid record with a unique ID.
Validation belongs at the model boundary, where both UI actions and scripted callers use it. An empty or malformed title should explain the problem without changing tasks, IDs, or selection.
- Create a SimpleButtonMorph with label:, target: self, and actionSelector: #addTask. A click sends addTask to the model.
- validatedTitle: trims the input, rejects an empty title, enforces a maximum of 160 characters, and disallows newlines and control characters. The limit is measured in Squeak characters, not bytes.
- addTask reads currentDraft, validates it inside an Error handler, and returns false with a useful status message if validation fails.
- Only after validation does it append {nextId. title. false}, increment the ID, clear selection and draft, and refresh. The sample is limited to 1000 tasks and bounded positive IDs.
- Add a status StringMorph. report: changes that text through refresh; validation failures use inline feedback instead of modal dialogs.
validatedTitle: aString
| title |
aString isString ifFalse: [self error: 'Enter a text title'].
title := aString withBlanksTrimmed.
title isEmpty ifTrue: [self error: 'Enter a task title first'].
title size > 160 ifTrue: [self error: 'Use 160 characters or fewer'].
(title anySatisfy: [:character | | code |
code := character asUnicode.
code < 32 or: [code = 127 or: [code = 8232 or: [code = 8233
or: [code between: 55296 and: 57343]]]]])
ifTrue: [self error: 'Use a single line without control characters'].
^ titlebuttonLabel: aString action: aSelector
^ SimpleButtonMorph new
label: aString; target: self; actionSelector: aSelector;
extent: 108@29; yourselfbuildActions: specifications
| bar x |
bar := Morph new color: (Color r: 0.91 g: 0.93 b: 0.96).
x := 7.
specifications do: [:spec | | button |
button := self buttonLabel: spec first action: spec second.
bar addMorph: button.
button position: x@5.
x := x + 117].
window addMorph: bar frame: (0.025@0.195 corner: 0.975@0.275).addTask
| title |
[title := self validatedTitle: self currentDraft]
on: Error do: [:error | ^ self report: error messageText].
nextId > 1000000000 ifTrue: [^ self report: 'No task IDs remain in this sample'].
tasks size >= 1000 ifTrue: [^ self report: 'The sample supports at most 1000 tasks'].
tasks add: {nextId. title. false}.
nextId := nextId + 1.
selectedId := nil.
self setDraft: ''.
status := 'Added: ', title.
self refresh.
^ truereport: aString
status := aString.
self refresh.
^ falseUse File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: Two example tasks in the native list, an Add task button, and a status message explaining the last action.

Try it yourself
- Type “ Buy milk ” and click Add task without pressing Return. One task appears as “Buy milk”.
- Click Add task again. No second task appears, because the field was cleared.
- Try an empty title, whitespace only, a pasted newline, and 161 characters. Each is rejected and the list remains intact.
Watch for
- Return accepts text but does not add it. Keep field acceptance and application actions distinct.
- Duplicate titles are allowed. Identity comes from IDs, so two “Call Alex” tasks can still be edited independently.
05 · Edit exactly the selected task
Load a selected task into the field and commit an edited title back to that record.
Add and Update mean different things. Keeping separate actions makes the model transition explicit and makes failures predictable.
- Add an Update selected button that targets #updateTask.
- updateTask asks selectedTask for the record with the stored selected ID. With no selection it reports the missing step and returns false.
- Validate currentDraft before changing the record. A failed edit preserves the original title.
- Replace only element 2, the title. Preserve the ID and completion flag. Keep the row selected and synchronize the title field after success.
updateTask
| task title |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to update'].
[title := self validatedTitle: self currentDraft]
on: Error do: [:error | ^ self report: error messageText].
task at: 2 put: title.
self setDraft: title.
status := 'Updated selected task'.
self refresh.
^ trueselectedTask
^ tasks detect: [:task | task first = selectedId] ifNone: [nil]currentDraft
"Buttons read live text, even before the editor has accepted it."
^ input ifNil: [draft] ifNotNil: [input text asString]Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: The selected row and editor both show the revised title.

Try it yourself
- Add “First” and “Second”. Select “Second”, edit the field, and click Update selected. Only that task changes.
- Clear the selected title and try Update selected. The old task remains.
- Click Update selected twice after a valid edit. There is still one task with that ID.
Watch for
- Typing alone changes the field, not the stored task. Click Update selected to commit.
- Selecting a different row loads that row’s title and replaces any unapplied field text. Apply an edit before changing selection.
06 · Complete and reopen tasks
Toggle completion while keeping selection valid when a row disappears from a filter.
A task’s state affects whether it belongs in the current view. Updating the data and repairing selection must be one coherent action.
- Add the Done / reopen button wired to #toggleComplete.
- Find the selected record by ID. Guard the no-selection case before changing anything.
- Replace the completion Boolean with its negation. Derive the status and [x] marker from the resulting state.
- Check self selection after the change. In the finished Active or Completed view the selected record may disappear; clear selectedId and the draft if the row is no longer visible.
- Refresh the list and selection together.
toggleComplete
| task |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to complete or reopen'].
task at: 3 put: task third not.
status := task third ifTrue: ['Marked complete'] ifFalse: ['Reopened task'].
"Changing completion may remove this row from the active filter."
self selection = 0 ifTrue: [selectedId := nil. self setDraft: ''].
self refresh.
^ trueselection
"The widget speaks row indices; the model stores a stable task ID."
^ self visibleTasks findFirst: [:task | task first = selectedId]taskLabels
^ self visibleTasks collect: [:task |
(task third ifTrue: ['[x] '] ifFalse: ['[ ] ']), task second]Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: One completed task and one active task with native selected-row highlighting.

Try it yourself
- Select a task and click Done / reopen. The label changes from [ ] to [x].
- Click again in All. The same task reopens.
- Later, repeat under Active. Completing the row removes it from that view and clears selection.
Watch for
- A toggle is intentionally reversible. Two clicks in All return a task to its original state.
- In Active or Completed, the first click may remove selection. A second click then reports that selection is required instead of targeting another row.
07 · Delete without stale selection
Remove one selected record and make a repeated delete harmless.
After deleting a row, a stale index can point at its neighbor. Clearing identity and editor state avoids accidental cascading deletions.
- Add Delete selected and point it at #deleteTask.
- Resolve the record through selectedTask. If nothing is selected, report the missing selection.
- Remove the exact record object from tasks. Then clear selectedId and the input field.
- Refresh so the view and selection match the new model. This educational app has no undo, so the button label names the exact scope: selected task.
deleteTask
| task |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to delete'].
tasks remove: task.
selectedId := nil.
self setDraft: ''.
status := 'Deleted selected task'.
self refresh.
^ trueUse File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: Only the retained task remains; the title field and list selection are empty.

Try it yourself
- Add two different tasks, select the second, and delete it. The first remains.
- Click Delete selected again. Nothing else is removed.
- After adding filters, delete visible row 1 in Active and verify that completed tasks remain untouched.
Watch for
- Deletion is an in-memory edit until Save sample is confirmed. Reload sample can restore the last saved task list.
- This small application does not provide an undo stack. Build one as an extension once the model transitions are clear.
08 · Filter the view without changing the data
Switch among All, Active, and Completed while preserving the underlying task collection.
A filter is a query over data. It must not silently delete records or redefine what a row number means.
- Add All, Active, and Completed buttons, each delegating to filter:.
- Accept only #all, #active, and #completed. Unknown filters report an error while retaining current state.
- A different filter clears selection and the draft, sets a readable status, and refreshes. Clicking the already active filter is a no-op, preserving selection.
- Use visibleTasks for labels and selection mapping. Keep all save and load operations based on tasks, so a filtered save still stores every task.
- Add a small Filter: label so the current mode remains visible independently of which rows happen to be present.
filter: aSymbol
(#(all active completed) includes: aSymbol)
ifFalse: [^ self report: 'Unknown filter'].
filter = aSymbol ifTrue: [^ true].
filter := aSymbol.
selectedId := nil.
self setDraft: ''.
status := 'Showing ', filter asString, ' tasks'.
self refresh.
^ trueshowAll
^ self filter: #allshowActive
^ self filter: #activeshowCompleted
^ self filter: #completedvisibleTasks
^ tasks select: [:task |
filter = #all or: [filter = #active
ifTrue: [task third not]
ifFalse: [task third]]]buildFilters
| bar x |
bar := Morph new color: (Color r: 0.96 g: 0.96 b: 0.96).
x := 7.
#(('All' showAll) ('Active' showActive) ('Completed' showCompleted)) do: [:spec |
| button |
button := self buttonLabel: spec first action: spec second.
bar addMorph: button.
button position: x@4.
x := x + 117].
filterMorph := StringMorph contents: 'Filter: ', filter asString.
bar addMorph: filterMorph.
filterMorph position: 375@10.
window addMorph: bar frame: (0.025@0.285 corner: 0.975@0.355).Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: Active shows only unfinished records and the filter label reads active.

Try it yourself
- Complete the first of two tasks, then choose Active. Only the second appears.
- Select Active row 1 and edit it. Return to All: the completed first task is unchanged.
- Choose Completed, reopen its task, and observe an empty view with cleared selection.
Watch for
- Changing filters intentionally clears unapplied title text. Add or update before switching views.
- An empty filtered list can coexist with many stored tasks. The final summary distinguishes total and visible counts.
09 · Save and reload an explicit JSON sample
Persist the task list as validated data, with confirmations, staged writes, and failure-safe state transitions.
Persistence introduces a boundary between an object graph and external bytes. Keep that boundary narrow: a known sample path, a data-only parser, complete validation, and a commit only after success.
- Add Save sample... and Reload sample... buttons. samplePath names MorphicTodo-sample.json beside the running image. The buttons show the full path and require confirmation; no tutorial checkpoint writes on file-in.
- dataJSON produces an object with version: 1 and tasks: an array of three-element records. View state, widget objects, and an unapplied title field are not serialized.
- parseTasks: uses Json with ctorMap: nil and Dictionary output. No Compiler evaluation or object constructor map is used for imported content. Validate the root, version, task count, record width, unique positive IDs, trimmed valid titles, and real Boolean flags.
- A small MorphicTodoJSONReader subclass rejects literal control characters in every JSON string, including keys and ignored fields, and decodes Unicode escape code units and surrogate pairs. Escaped controls remain valid JSON; task-title validation separately rejects them. This keeps supplementary characters valid without changing the image-wide Json class.
- readTextFrom: rejects files larger than 1 MiB and decodes strict UTF-8. It closes the stream with ensure: even if reading fails.
- writeText:to: encodes UTF-8, writes a sibling temporary file, closes and rereads it to verify the bytes, moves an existing destination to a unique backup, then installs the new file. On failure it attempts restoration and reports where an original backup survives.
- saveTo: advances the saved snapshot only after a successful write. loadFrom: parses and validates into a local collection first, then replaces tasks, resets selection/filter/draft, advances nextId, and records the loaded snapshot. Errors keep the current tasks.
samplePath
"One explicit sample file beside the running image; no path from imported data."
^ FileDirectory default fullNameFor: 'MorphicTodo-sample.json'dataJSON
| document |
document := Dictionary new.
document at: 'version' put: 1; at: 'tasks' put: tasks asArray.
^ Json render: documentparseTasks: aString
"Json is a data parser. No Compiler evaluation, constructors or object deserialization."
| document records ids result |
document := (MorphicTodoJSONReader new ctorMap: nil; dictionaryClass: Dictionary; yourself)
readFromString: aString withBlanksTrimmed.
(document isKindOf: Dictionary) ifFalse: [self error: 'Expected a JSON object'].
(document at: 'version' ifAbsent: [nil]) = 1
ifFalse: [self error: 'Unsupported sample format version'].
records := document at: 'tasks' ifAbsent: [self error: 'Missing tasks array'].
(records isArray and: [records size <= 1000])
ifFalse: [self error: 'Expected at most 1000 task records'].
ids := Set new.
result := OrderedCollection new.
records do: [:record | | id title done |
(record isArray and: [record size = 3])
ifFalse: [self error: 'Each task needs an ID, title and completion flag'].
id := record first.
(id isInteger and: [id between: 1 and: 1000000000])
ifFalse: [self error: 'Invalid task ID'].
(ids includes: id) ifTrue: [self error: 'Duplicate task ID'].
ids add: id.
title := self validatedTitle: record second.
title = record second ifFalse: [self error: 'Stored titles must be trimmed'].
done := record third.
(done == true or: [done == false])
ifFalse: [self error: 'Completion must be true or false'].
result add: {id. title. done}].
^ resultsaveSample
self confirmSave == true ifFalse: [^ self report: 'Save canceled'].
^ self saveTo: self samplePathreloadSample
self confirmReload == true ifFalse: [^ self report: 'Reload canceled'].
^ self loadFrom: self samplePathsaveTo: aPath
| json |
json := self dataJSON.
[self writeText: json to: aPath]
on: Error do: [:error | ^ self report: 'Save failed: ', error messageText].
savedTasks := self tasks asArray.
status := 'Saved task list (the title field is not saved until Add or Update)'.
self refresh.
^ trueloadFrom: aPath
| imported |
[imported := self parseTasks: (self readTextFrom: aPath)]
on: Error do: [:error | ^ self report: 'Reload failed: ', error messageText].
"Commit only after the entire file has passed validation."
tasks := imported.
nextId := (tasks inject: 0 into: [:maximum :task | maximum max: task first]) + 1.
selectedId := nil.
filter := #all.
self setDraft: ''.
savedTasks := self tasks asArray.
status := 'Reloaded sample; showing all tasks'.
self refresh.
^ truewriteText: 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, '.todo-tmp-'.
backup := self unusedNameIn: directory basedOn: leaf, '.todo-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 sample'].
(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 | ]].
^ trueUse File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: A successful sample save reports success. The screenshot driver writes only its own tutorial sample file, with no unrelated filesystem changes.

Try it yourself
- Add two tasks, complete one, and confirm Save sample. Inspect the JSON file with an ordinary text editor.
- Add a temporary task, confirm Reload sample, and verify the saved two-task state returns in All.
- Cancel each confirmation and verify that nothing is written or replaced.
- Using a disposable sample only, make the JSON malformed, then reload. The app reports the error and preserves the current list.
Watch for
- Save stores the task list, not a title that has only been typed. Click Add or Update selected before saving it.
- Staged replacement reduces common failure damage, but is not an atomic or power-loss-safe transaction and does not detect concurrent external edits. A backup may remain if cleanup fails.
- The complete file is held in memory. This is a bounded single-user sample, not a database or concurrent sync engine.
10 · Finish the application with status and close guards
Make unsaved model changes and unapplied text visible, and protect them at window close.
An application is more than its happy path. The user needs to know what is stored, what is merely typed, and whether closing will discard work.
- isDirty compares current task records with a deep copy of the last successfully saved or loaded records. Comparing structured data avoids depending on JSON dictionary-key ordering.
- hasPendingDraft compares the live field with a selected stored title before checking for blank input. Clearing a selected title, including replacing it with spaces, is an unapplied edit and still needs a close confirmation. With no selection, a blank field is not a pending new title.
- Add the summary with total, completed, and visible counts, saved/unsaved state, and an unapplied-title indicator. Prefix the title with * while the task list is dirty.
- Connect editTextSelector: to noteDraftEdited:, so text edits refresh the status without resetting the editor buffer.
- SystemWindow consults okToClose. A dirty list or pending title triggers confirmClose; Cancel leaves the actual native window open. A clean window closes immediately.
- windowIsClosing preserves the current field in the model and releases widget references. Reopening the same model builds fresh widgets around retained in-memory data. A brand-new MorphicTodo has its own empty collection.
- File in MorphicTodoTests.st and run MorphicTodoTest suite run. The suite covers the model actions, native widgets, confirmations, malformed data, file failures, and round trips.
isDirty
^ tasks asArray ~= savedTaskshasPendingDraft
| selected live |
live := self currentDraft.
selected := self selectedTask.
selected ifNotNil: [^ live ~= selected second].
^ live withBlanksTrimmed notEmptysummaryText
| complete |
complete := tasks count: [:task | task third].
^ tasks size printString, ' tasks / ', complete printString,
' complete / ', self visibleTasks size printString, ' visible',
(self isDirty ifTrue: [' / unsaved changes'] ifFalse: [' / saved']),
(self hasPendingDraft ifTrue: [' / unapplied title'] ifFalse: [''])refresh
self changed: #taskLabels; changed: #selection.
statusMorph ifNotNil: [statusMorph contents: status].
filterMorph ifNotNil: [filterMorph contents: 'Filter: ', filter asString].
summaryMorph ifNotNil: [summaryMorph contents: self summaryText].
window ifNotNil: [window setLabel:
(self isDirty ifTrue: ['* '] ifFalse: ['']), 'Morphic Todo'].okToClose
(self isDirty or: [self hasPendingDraft]) ifFalse: [^ true].
^ self confirmClose == truewindowIsClosing
draft := self currentDraft copy.
window := nil.
input := nil.
list := nil.
statusMorph := nil.
filterMorph := nil.
summaryMorph := nil.
super windowIsClosing.Use File List > file in on this checkpoint, then evaluate MorphicTodo open in a Workspace. Close any previous demo window first. Move forward through checkpoints; to move backward, use a fresh image because file-in does not remove later methods.
MorphicTodo openExpected: The finished native Todo app shows task counts, completion, filtering, explicit sample persistence, and meaningful unsaved-state feedback.

Try it yourself
- Type an unapplied title and close the window. Cancel; both window and text remain.
- Save the task list, then type a new title without adding it. The list is saved, but closing still warns about the unapplied title.
- Save a task, select it, clear its title, and close the window. The unapplied-title indicator remains and Cancel keeps the window open.
- Resize the window and run the SUnit suite. The same model actions work without relying on mouse coordinates.
Watch for
- Saving a Squeak image and saving the Todo JSON sample are different operations. This tutorial’s Save sample button writes only the JSON task list.
- Confirming close allows the window to disappear. The object may remain in memory if you kept a reference; do not treat that as durable storage.
Use the finished application
These GIFs show real Squeak windows after repeatable scripted editor/model actions. They demonstrate the native states and behavior; they are not a recording of a person clicking. The persistence harness confirms only its own generated sample files.

- Ready to add a task
- The native text editor contains an unaccepted title
- Add reads the live buffer and creates a task
- Selecting a row loads its title
- Change the title in the live editor
- Update selected commits the edit to the same task

- Three tasks in All
- Select the first task
- Complete toggles its state
- Active shows only unfinished tasks and clears selection
- Visible row 2 is selected by its stable task ID
- Delete removes only that selected active task
- All shows the completed task and remaining active task

- Two tasks ready to save
- Save sample writes the explicit sample path; harness supplies confirmation
- Add another unsaved task
- Change to Active before reloading
- Reload validates the complete file then replaces the list; harness supplies confirmation

- Empty title is rejected without creating a task
- Whitespace-only title is also rejected
- A valid title succeeds
- A repeated click cannot add an empty second task
- Update without a selection explains what is missing
Persistence, validation and boundaries
- Task titles are one line, trimmed, and at most 160 Squeak characters
- At most 1000 tasks and a 1 MiB input file
- Fixed sample-file UI with explicit create/replace and reload confirmations
- No arbitrary code evaluation for persisted data
- No undo stack, sync, concurrency control, or atomic/power-loss-safe saves
The list stores plain task data in validated JSON. It does not evaluate data as Smalltalk source. Selection is attached to a stable task ID, so filtered row numbers cannot silently target a different task. Save and Reload ask before touching the sample file or replacing unsaved state.
Saving stages a complete file and retains backup recovery during replacement. This teaching app does not provide concurrent editing locks or crash-atomic storage. Read the source and use tutorial-owned files.
MorphicTodoTest suite runAll 66 native SUnit tests passed. Native SUnit results and reproducible test instructions are included in the workshop download. Checkpoints were also opened independently in fresh images.
Read the complete application source
"Morphic Todo tutorial. File in, then evaluate MorphicTodo open. Squeak 6.1."
Model subclass: #MorphicTodo
instanceVariableNames: 'tasks nextId selectedId draft filter status savedTasks window input list statusMorph filterMorph summaryMorph'
classVariableNames: '' poolDictionaries: '' category: 'Morphic-Todo-Tutorial'!
"A narrowly scoped JSON reader with strict string controls and Unicode escapes."
Json subclass: #MorphicTodoJSONReader
instanceVariableNames: '' classVariableNames: '' poolDictionaries: ''
category: 'Morphic-Todo-Tutorial'!
!MorphicTodoJSONReader methodsFor: 'string parsing'!
readString
"JSON forbids literal U+0000 through U+001F in every string, including keys
and ignored properties. Escaped controls remain valid JSON data."
self resetStringBufferStream.
[
currentCharacter := stream next ifNil: [self incomplete: 'Unexpected end of string'].
currentCharacter == $" ifTrue: [
currentCharacter := stream next.
^ stringBufferStream contents].
currentCharacter == $\
ifTrue: [
stringBufferStream nextPut: (self interpretStringEscape:
(stream next ifNil: [self incomplete: 'Unexpected end of string']))]
ifFalse: [
currentCharacter asUnicode < 32
ifTrue: [self invalid: 'Unescaped control character in JSON string'].
stringBufferStream nextPut: currentCharacter]
] repeat
! !
!MorphicTodoJSONReader methodsFor: 'unicode escapes'!
readHexCodeUnit
| code character digit |
code := 0.
1 to: 4 do: [:ignored |
character := stream next ifNil: [self incomplete: 'Truncated Unicode escape'].
digit := character digitValue.
(digit between: 0 and: 15) ifFalse: [self invalid: 'Invalid Unicode hex digit'].
code := code * 16 + digit].
^ code
! !
!MorphicTodoJSONReader methodsFor: 'unicode escapes'!
unescapeUnicode
| high low |
high := self readHexCodeUnit.
(high between: 16rD800 and: 16rDFFF) ifFalse: [^ Unicode value: high].
high > 16rDBFF ifTrue: [self invalid: 'High surrogate expected'].
(stream next = $\ and: [stream next = $u])
ifFalse: [self invalid: 'Escaped low surrogate expected'].
low := self readHexCodeUnit.
(low between: 16rDC00 and: 16rDFFF)
ifFalse: [self invalid: 'Low surrogate expected'].
^ Unicode value: 16r10000 + ((high - 16rD800) bitShift: 10) + (low - 16rDC00)
! !
!MorphicTodo methodsFor: 'initialization'!
initialize
super initialize.
tasks := OrderedCollection new.
nextId := 1.
selectedId := nil.
draft := ''.
filter := #all.
status := 'Ready'.
savedTasks := #().
! !
!MorphicTodo methodsFor: 'accessing'!
window
^ window
! !
!MorphicTodo methodsFor: 'accessing'!
tasks
"Return copies: callers cannot mutate our records accidentally."
^ tasks collect: [:task | {task first. task second copy. task third}]
! !
!MorphicTodo methodsFor: 'accessing'!
taskCount
^ tasks size
! !
!MorphicTodo methodsFor: 'opening'!
open
window ifNotNil: [window comeToFront. ^ self].
self buildWindow.
window openInWorld; extent: 780@540.
^ self
! !
!MorphicTodo class methodsFor: 'opening'!
open
^ self new open
! !
!MorphicTodo methodsFor: 'building'!
createWindow
window := SystemWindow new model: self.
window setLabel: 'Morphic Todo - build a real application'.
^ window
! !
!MorphicTodo methodsFor: 'building'!
buildWindow
self createWindow.
self buildInput.
self buildList.
self buildActions: #(('Add task' addTask) ('Update selected' updateTask) ('Done / reopen' toggleComplete) ('Delete selected' deleteTask)).
self buildStatus.
self buildFilters.
self buildPersistence.
input editTextSelector: #noteDraftEdited:.
self buildSummary.
^ window
! !
!MorphicTodo methodsFor: 'accessing'!
draftText
^ draft
! !
!MorphicTodo methodsFor: 'accessing'!
currentDraft
"Buttons read live text, even before the editor has accepted it."
^ input ifNil: [draft] ifNotNil: [input text asString]
! !
!MorphicTodo methodsFor: 'accessing'!
input
^ input
! !
!MorphicTodo methodsFor: 'editing'!
acceptDraft: aText
draft := aText asString copy.
^ true
! !
!MorphicTodo methodsFor: 'editing'!
setDraft: aString
draft := aString copy.
self changed: #draftText.
input ifNotNil: [input hasUnacceptedEdits: false].
! !
!MorphicTodo methodsFor: 'building'!
buildInput
| label |
label := StringMorph contents: 'Task title (select a row to edit it):'.
window addMorph: label frame: (0.025@0.02 corner: 0.975@0.07).
input := PluggableTextMorph on: self text: #draftText accept: #acceptDraft:.
input acceptOnCR: true; wrapFlag: false; plainTextOnly: true.
window addMorph: input frame: (0.025@0.075 corner: 0.975@0.17).
! !
!MorphicTodo methodsFor: 'accessing'!
visibleTasks
^ tasks select: [:task |
filter = #all or: [filter = #active
ifTrue: [task third not]
ifFalse: [task third]]]
! !
!MorphicTodo methodsFor: 'accessing'!
taskLabels
^ self visibleTasks collect: [:task |
(task third ifTrue: ['[x] '] ifFalse: ['[ ] ']), task second]
! !
!MorphicTodo methodsFor: 'accessing'!
selection
"The widget speaks row indices; the model stores a stable task ID."
^ self visibleTasks findFirst: [:task | task first = selectedId]
! !
!MorphicTodo methodsFor: 'accessing'!
selection: anIndex
| visible task |
visible := self visibleTasks.
(anIndex isInteger and: [anIndex between: 1 and: visible size]) ifFalse: [
selectedId := nil.
self setDraft: ''.
self refresh.
^ self].
task := visible at: anIndex.
selectedId := task first.
self setDraft: task second.
self refresh.
! !
!MorphicTodo methodsFor: 'accessing'!
selectedTask
^ tasks detect: [:task | task first = selectedId] ifNone: [nil]
! !
!MorphicTodo methodsFor: 'updating'!
refresh
self changed: #taskLabels; changed: #selection.
statusMorph ifNotNil: [statusMorph contents: status].
filterMorph ifNotNil: [filterMorph contents: 'Filter: ', filter asString].
summaryMorph ifNotNil: [summaryMorph contents: self summaryText].
window ifNotNil: [window setLabel:
(self isDirty ifTrue: ['* '] ifFalse: ['']), 'Morphic Todo'].
! !
!MorphicTodo methodsFor: 'building'!
buildList
list := PluggableListMorph on: self
list: #taskLabels selected: #selection changeSelected: #selection:.
window addMorph: list frame: (0.025@0.365 corner: 0.975@0.815).
! !
!MorphicTodo methodsFor: 'validation'!
validatedTitle: aString
| title |
aString isString ifFalse: [self error: 'Enter a text title'].
title := aString withBlanksTrimmed.
title isEmpty ifTrue: [self error: 'Enter a task title first'].
title size > 160 ifTrue: [self error: 'Use 160 characters or fewer'].
(title anySatisfy: [:character | | code |
code := character asUnicode.
code < 32 or: [code = 127 or: [code = 8232 or: [code = 8233
or: [code between: 55296 and: 57343]]]]])
ifTrue: [self error: 'Use a single line without control characters'].
^ title
! !
!MorphicTodo methodsFor: 'updating'!
report: aString
status := aString.
self refresh.
^ false
! !
!MorphicTodo methodsFor: 'actions'!
addTask
| title |
[title := self validatedTitle: self currentDraft]
on: Error do: [:error | ^ self report: error messageText].
nextId > 1000000000 ifTrue: [^ self report: 'No task IDs remain in this sample'].
tasks size >= 1000 ifTrue: [^ self report: 'The sample supports at most 1000 tasks'].
tasks add: {nextId. title. false}.
nextId := nextId + 1.
selectedId := nil.
self setDraft: ''.
status := 'Added: ', title.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'building'!
buttonLabel: aString action: aSelector
^ SimpleButtonMorph new
label: aString; target: self; actionSelector: aSelector;
extent: 108@29; yourself
! !
!MorphicTodo methodsFor: 'building'!
buildActions: specifications
| bar x |
bar := Morph new color: (Color r: 0.91 g: 0.93 b: 0.96).
x := 7.
specifications do: [:spec | | button |
button := self buttonLabel: spec first action: spec second.
bar addMorph: button.
button position: x@5.
x := x + 117].
window addMorph: bar frame: (0.025@0.195 corner: 0.975@0.275).
! !
!MorphicTodo methodsFor: 'building'!
buildStatus
statusMorph := StringMorph contents: status.
window addMorph: statusMorph frame: (0.025@0.845 corner: 0.975@0.89).
! !
!MorphicTodo methodsFor: 'accessing'!
status
^ status
! !
!MorphicTodo methodsFor: 'actions'!
updateTask
| task title |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to update'].
[title := self validatedTitle: self currentDraft]
on: Error do: [:error | ^ self report: error messageText].
task at: 2 put: title.
self setDraft: title.
status := 'Updated selected task'.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'actions'!
toggleComplete
| task |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to complete or reopen'].
task at: 3 put: task third not.
status := task third ifTrue: ['Marked complete'] ifFalse: ['Reopened task'].
"Changing completion may remove this row from the active filter."
self selection = 0 ifTrue: [selectedId := nil. self setDraft: ''].
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'actions'!
deleteTask
| task |
task := self selectedTask.
task ifNil: [^ self report: 'Select a task to delete'].
tasks remove: task.
selectedId := nil.
self setDraft: ''.
status := 'Deleted selected task'.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'actions'!
showAll
^ self filter: #all
! !
!MorphicTodo methodsFor: 'actions'!
showActive
^ self filter: #active
! !
!MorphicTodo methodsFor: 'actions'!
showCompleted
^ self filter: #completed
! !
!MorphicTodo methodsFor: 'accessing'!
filter
^ filter
! !
!MorphicTodo methodsFor: 'actions'!
filter: aSymbol
(#(all active completed) includes: aSymbol)
ifFalse: [^ self report: 'Unknown filter'].
filter = aSymbol ifTrue: [^ true].
filter := aSymbol.
selectedId := nil.
self setDraft: ''.
status := 'Showing ', filter asString, ' tasks'.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'building'!
buildFilters
| bar x |
bar := Morph new color: (Color r: 0.96 g: 0.96 b: 0.96).
x := 7.
#(('All' showAll) ('Active' showActive) ('Completed' showCompleted)) do: [:spec |
| button |
button := self buttonLabel: spec first action: spec second.
bar addMorph: button.
button position: x@4.
x := x + 117].
filterMorph := StringMorph contents: 'Filter: ', filter asString.
bar addMorph: filterMorph.
filterMorph position: 375@10.
window addMorph: bar frame: (0.025@0.285 corner: 0.975@0.355).
! !
!MorphicTodo methodsFor: 'persistence'!
samplePath
"One explicit sample file beside the running image; no path from imported data."
^ FileDirectory default fullNameFor: 'MorphicTodo-sample.json'
! !
!MorphicTodo methodsFor: 'persistence'!
dataJSON
| document |
document := Dictionary new.
document at: 'version' put: 1; at: 'tasks' put: tasks asArray.
^ Json render: document
! !
!MorphicTodo methodsFor: 'persistence'!
parseTasks: aString
"Json is a data parser. No Compiler evaluation, constructors or object deserialization."
| document records ids result |
document := (MorphicTodoJSONReader new ctorMap: nil; dictionaryClass: Dictionary; yourself)
readFromString: aString withBlanksTrimmed.
(document isKindOf: Dictionary) ifFalse: [self error: 'Expected a JSON object'].
(document at: 'version' ifAbsent: [nil]) = 1
ifFalse: [self error: 'Unsupported sample format version'].
records := document at: 'tasks' ifAbsent: [self error: 'Missing tasks array'].
(records isArray and: [records size <= 1000])
ifFalse: [self error: 'Expected at most 1000 task records'].
ids := Set new.
result := OrderedCollection new.
records do: [:record | | id title done |
(record isArray and: [record size = 3])
ifFalse: [self error: 'Each task needs an ID, title and completion flag'].
id := record first.
(id isInteger and: [id between: 1 and: 1000000000])
ifFalse: [self error: 'Invalid task ID'].
(ids includes: id) ifTrue: [self error: 'Duplicate task ID'].
ids add: id.
title := self validatedTitle: record second.
title = record second ifFalse: [self error: 'Stored titles must be trimmed'].
done := record third.
(done == true or: [done == false])
ifFalse: [self error: 'Completion must be true or false'].
result add: {id. title. done}].
^ result
! !
!MorphicTodo methodsFor: 'dialogs'!
confirmSave
^ UIManager default confirm:
'Write this sample file? Existing sample contents will be replaced.',
String cr, self samplePath
! !
!MorphicTodo methodsFor: 'dialogs'!
confirmReload
^ UIManager default confirm:
'Replace the current task list and draft with the saved sample?',
String cr, self samplePath
! !
!MorphicTodo methodsFor: 'actions'!
saveSample
self confirmSave == true ifFalse: [^ self report: 'Save canceled'].
^ self saveTo: self samplePath
! !
!MorphicTodo methodsFor: 'actions'!
reloadSample
self confirmReload == true ifFalse: [^ self report: 'Reload canceled'].
^ self loadFrom: self samplePath
! !
!MorphicTodo methodsFor: 'persistence'!
saveTo: aPath
| json |
json := self dataJSON.
[self writeText: json to: aPath]
on: Error do: [:error | ^ self report: 'Save failed: ', error messageText].
savedTasks := self tasks asArray.
status := 'Saved task list (the title field is not saved until Add or Update)'.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'persistence'!
loadFrom: aPath
| imported |
[imported := self parseTasks: (self readTextFrom: aPath)]
on: Error do: [:error | ^ self report: 'Reload failed: ', error messageText].
"Commit only after the entire file has passed validation."
tasks := imported.
nextId := (tasks inject: 0 into: [:maximum :task | maximum max: task first]) + 1.
selectedId := nil.
filter := #all.
self setDraft: ''.
savedTasks := self tasks asArray.
status := 'Reloaded sample; showing all tasks'.
self refresh.
^ true
! !
!MorphicTodo methodsFor: 'building'!
buildPersistence
| save reload |
save := self buttonLabel: 'Save sample...' action: #saveSample.
reload := self buttonLabel: 'Reload sample...' action: #reloadSample.
window addMorph: save frame: (0.025@0.905 corner: 0.245@0.975).
window addMorph: reload frame: (0.26@0.905 corner: 0.49@0.975).
! !
!MorphicTodo 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, '.todo-tmp-'.
backup := self unusedNameIn: directory basedOn: leaf, '.todo-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 sample'].
(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
! !
!MorphicTodo 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']
! !
!MorphicTodo 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
! !
!MorphicTodo methodsFor: 'files'!
readTextFrom: aPath
| stream bytes |
stream := FileStream readOnlyFileNamed: aPath.
stream ifNil: [self error: 'The file could not be opened'].
[stream binary.
stream size > 1048576 ifTrue: [self error: 'Sample file exceeds 1 MiB'].
bytes := stream upToEnd] ensure: [stream close].
^ (self decodeUTF8Bytes: bytes) withSqueakLineEndings
! !
!MorphicTodo 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)]]]
! !
!MorphicTodo 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 sample 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)]]]]]
! !
!MorphicTodo methodsFor: 'accessing'!
hasPendingDraft
| selected live |
live := self currentDraft.
selected := self selectedTask.
selected ifNotNil: [^ live ~= selected second].
^ live withBlanksTrimmed notEmpty
! !
!MorphicTodo methodsFor: 'accessing'!
isDirty
^ tasks asArray ~= savedTasks
! !
!MorphicTodo methodsFor: 'accessing'!
summaryText
| complete |
complete := tasks count: [:task | task third].
^ tasks size printString, ' tasks / ', complete printString,
' complete / ', self visibleTasks size printString, ' visible',
(self isDirty ifTrue: [' / unsaved changes'] ifFalse: [' / saved']),
(self hasPendingDraft ifTrue: [' / unapplied title'] ifFalse: [''])
! !
!MorphicTodo methodsFor: 'building'!
buildSummary
summaryMorph := StringMorph contents: self summaryText.
window addMorph: summaryMorph frame: (0.025@0.82 corner: 0.975@0.85).
! !
!MorphicTodo methodsFor: 'editing'!
noteDraftEdited: aText
self refresh.
! !
!MorphicTodo methodsFor: 'closing'!
confirmClose
^ UIManager default confirm:
'Close and discard unsaved tasks or the unapplied title? Use Save sample first to keep tasks.'
! !
!MorphicTodo methodsFor: 'closing'!
okToClose
(self isDirty or: [self hasPendingDraft]) ifFalse: [^ true].
^ self confirmClose == true
! !
!MorphicTodo methodsFor: 'closing'!
windowIsClosing
draft := self currentDraft copy.
window := nil.
input := nil.
list := nil.
statusMorph := nil.
filterMorph := nil.
summaryMorph := nil.
super windowIsClosing.
! !
Keep building
- Add an undo stack by recording the previous structured task snapshot for each action
- Introduce a TodoItem class once you understand the current three-element records
- Persist a due date with a new schema version and migration tests
- Add keyboard shortcuts through documented Morphic event handling
- Create a separate reusable persistence object and inject it into the model
Next: debug a deliberately broken application →
Review control wiring · Compare document-state handling · Official Squeak documentation
Put it into practice.
Try an exercise before revealing its hints and tested solution.