s LearnSqueak.com

PRACTICAL SQUEAK WORKSHOP

Menus, dialogs & keyboard shortcuts

One command receiver, native popups, explicit cancellation and focused events.

8 construction stagesTested source & checkpointsNative screenshots & demos
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.

Before you start

Build a small fictional document workbench and learn how native Morphic interactions fit together. Eight checkpoints cover buttons, a context menu, Yes/No confirmation, the real file chooser, and keyboard focus. The screenshots follow an executed sequence: add from the toolbar, add from the menu, decline a removal, accept another removal, choose a fixture file, and add via a focused keyboard event. Individual checkpoints start from three rows, so their counts may differ from later sequence screenshots.

Classes and objects · Using Squeak’s tools

  • Download LearnSqueakCommands.st and file it in with Squeak File List → fileIn. It installs LSCommandWorkbench; it does not open a dialog.
  • Open a Workspace and Do it on LSCommandWorkbench open. This returns the app morph. Close a demo with its halo’s delete handle or send delete to a Workspace variable holding the app.
  • Each numbered checkpoint is self-contained and opens its stage automatically. Checkpoints 4 and 6 intentionally display modal dialogs; answer or cancel the dialog to continue. Close the old demo before opening another.
  • The file-choice example creates two fictional .txt files under LearnSqueak-Dialog-Fixtures in the image’s working directory. It never deletes files and only displays the selected name. The verification suite selects only those tutorial fixtures.

01 · Build a small command receiver

The workbench owns an OrderedCollection of fictional document names, a selected index, and a status string. A zero index means no selection. The rows are native SimpleButtonMorph instances whose action sends selectIndex:. refresh rebuilds the short row list and highlights the selected document. The example intentionally caps the list at five rows so every state remains visible; a production app would usually use a scrolling list.

Where to run this

File List → fileIn commands-stage-01.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: LSCommandWorkbench openStage: 1.

Construction code · follow the run instructions above
initialize
    super initialize.
    documents := OrderedCollection with: 'Morphic ideas' with: 'Layout notes' with: 'Tiny experiments'.
    selectedIndex := 1.
    serial := 0.
    status := 'Ready - select a document'.
    stage := 0.
    self extent: 740@440; color: (Color r: 0.95 g: 0.97 b: 0.99);
        borderWidth: 2; borderColor: (Color r: 0.24 g: 0.37 b: 0.53)
Expected result

A native Morphic panel containing three fictional rows. Click another row to update the selected label.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Build a small command receiver in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. The checkpoint is rendered directly by the native image.

02 · Wire a button to one method

The New draft button has target: self and actionSelector: #newDocument. The method performs the model update once, selects the new row, and refreshes the view. This keeps application behavior separate from the widget that requested it. Repeated New commands stop at five rows with a status message instead of drawing rows outside the panel.

Where to run this

File List → fileIn commands-stage-02.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: LSCommandWorkbench openStage: 2.

Construction code · follow the run instructions above
newDocument
    documents size >= 5 ifTrue: [status := 'Five rows fit this small demo. Remove a row first.'. self refresh. ^ false].
    serial := serial + 1.
    documents add: 'Draft ', serial printString.
    selectedIndex := documents size.
    status := 'Created draft ', serial printString.
    self refresh.
    ^ true
Expected result

New draft adds Draft 1 and highlights it. The same command will later be reused by the menu and keyboard.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Wire a button to one method in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. The checkpoint is rendered directly by the native image.

03 · Create a native context menu

MenuMorph stores a receiver and a selector for each item. defaultTarget: self saves repeating the same receiver. addLine separates related command groups. showCommandMenu sends popUpInWorld to this menu, and mouseDown: also opens it for a yellow-button event on empty workbench space. The Menu button is a discoverable alternative to a platform-dependent mouse gesture.

Where to run this

File List → fileIn commands-stage-03.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: (LSCommandWorkbench openStage: 3) showCommandMenu.

Construction code · follow the run instructions above
commandMenu
    | menu |
    menu := MenuMorph new defaultTarget: self.
    menu addTitle: 'Document commands'.
    menu add: 'New draft (Cmd/Ctrl+N)' action: #newDocument.
    menu add: 'Remove selected...' action: #removeDocument.
    menu addLine.
    menu add: 'Open tutorial file...' action: #chooseFile.
    menu add: 'Focus keyboard commands' action: #focusForCommands.
    ^ menu
Expected result

A native popup with New, Remove, Open file and Focus commands. Choosing New invokes exactly the same newDocument method as the toolbar.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Create a native context menu in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. The real MenuMorph is open after the toolbar added a draft.

04 · Ask before changing the selection

Guard the no-selection case before displaying anything. UIManager default confirm: opens Squeak’s actual modal Yes/No question and returns an answer. A modal call pauses this command while Morphic continues processing the dialog. The answer then goes to a separate method that owns the mutation. This small separation lets you test the state change without inventing a second behavior.

Where to run this

File List → fileIn commands-stage-04.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. This checkpoint opens a modal dialog; answer it to finish the file-in. If the final source is already loaded, use Workspace → Do it on: (LSCommandWorkbench openStage: 4) removeDocument.

Construction code · follow the run instructions above
removeDocument
    self selectedDocument ifNil: [status := 'Select a document first'. self refresh. ^ false].
    ^ self removeSelectionConfirmed: (UIManager default confirm: 'Remove the selected tutorial row?')
Expected result

The real Please Confirm dialog appears above the workbench. Yes removes one in-memory row. The example never deletes a disk file.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Ask before changing the selection in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. The actual UIManager confirmation; the capture script positions it centrally before answering No.

05 · Treat cancellation as ordinary control flow

Only the Boolean true authorizes the removal. false, nil and unexpected answers return false with an unchanged collection. The command also checks selection again at the point of mutation. After a removal it selects a valid neighbor; after removing the last row it stores zero. These branches prevent out-of-bounds indexing and keep the empty state usable.

Where to run this

File List → fileIn commands-stage-05.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: (LSCommandWorkbench openStage: 5) removeSelectionConfirmed: false.

Construction code · follow the run instructions above
removeSelectionConfirmed: anAnswer
    anAnswer == true ifFalse: [status := 'Cancelled - documents unchanged'. self refresh. ^ false].
    self selectedDocument ifNil: [status := 'Select a document first'. self refresh. ^ false].
    documents removeAt: selectedIndex.
    selectedIndex := documents isEmpty ifTrue: [0] ifFalse: [selectedIndex min: documents size].
    status := 'Removed one row (no file was deleted)'.
    self refresh.
    ^ true
Expected result

Choose No and the status says Cancelled. All documents and the selected index remain intact.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Treat cancellation as ordinary control flow in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. After a real No response, the collection is unchanged.

06 · Open Squeak’s actual file chooser

chooseFileFrom:matching:label: starts the native chooser in a known directory and filters for *.txt. prepareFixtures creates only two fictional files in LearnSqueak-Dialog-Fixtures beside the image, and preserves either file if it already exists. The directory is a starting location, not a security sandbox: the native chooser can navigate elsewhere. For this lesson choose only the supplied fixtures.

Where to run this

File List → fileIn commands-stage-06.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. This checkpoint opens a modal dialog; answer it to finish the file-in. If the final source is already loaded, use Workspace → Do it on: (LSCommandWorkbench openStage: 6) chooseFile.

Construction code · follow the run instructions above
chooseFile
    | path |
    path := UIManager default chooseFileFrom: self prepareFixtures matching: '*.txt' label: 'Choose a tutorial file'.
    ^ self acceptChosenPath: path
Expected result

The native Choose File dialog lists Layout-notes.txt and Morphic-notes.txt. Select one and Accept, or Cancel without changing the model.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Open Squeak’s actual file chooser in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. The real FileChooserDialog over tutorial-owned fixtures; the capture script selects a row and positions the dialog.

07 · Validate the returned path

A file chooser returns a filename or nil; it does not make that filename permanently valid. Test the answer’s type, reject an empty string, and check that the file still exists. Only after those checks should a command proceed. This tutorial displays the chosen filename without loading its contents, so file selection can be studied independently of text decoding and editing.

Where to run this

File List → fileIn commands-stage-07.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: | app | app := LSCommandWorkbench openStage: 7. app acceptChosenPath: (app prepareFixtures fullNameFor: 'Morphic-notes.txt').

Construction code · follow the run instructions above
acceptChosenPath: path
    "The chooser returns a path or nil. Validate before touching the model."
    (path isString and: [path notEmpty]) ifFalse: [status := 'File choice cancelled'. self refresh. ^ false].
    (FileDirectory default fileExists: path) ifFalse: [status := 'That file no longer exists'. self refresh. ^ false].
    status := 'Chosen: ', (FileDirectory localNameFor: path).
    self refresh.
    ^ true
Expected result

Accepting Morphic-notes.txt updates the status. Cancel and a vanished file produce clear status messages and leave the document rows unchanged.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Validate the returned path in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. After accepting the existing fictional text file.

08 · Give shortcuts an explicit focus owner

Morphic sends keyboard events through a HandMorph to its keyboardFocus. Clicking Focus keys, or empty workbench space, makes this panel the receiver. handlesKeyboard: accepts only Escape and the New combination; keyStroke: dispatches New and marks it handled. Escape releases focus, and delete releases focus before removing the morph. Both commandKeyPressed and controlKeyPressed are checked. Their physical keys depend on the VM and host OS; the toolbar and menu remain available when a host reserves a shortcut.

Where to run this

File List → fileIn commands-stage-08.st. The checkpoint installs the definitions and runs the stage action. The displayed method code belongs in the Browser on LSCommandWorkbench’s instance side. If the final source is already loaded, use Workspace → Do it on: (LSCommandWorkbench openStage: 8) focusForCommands.

Construction code · follow the run instructions above
keyStroke: event
    stage < 8 ifTrue: [^ self].
    event keyCharacter = Character escape ifTrue: [
        event hand releaseKeyboardFocus: self.
        status := 'Keyboard focus released'. self refresh.
        event wasHandled: true. ^ self].
    ((event commandKeyPressed or: [event controlKeyPressed]) and: [event keyCharacter asLowercase = $n]) ifTrue: [
        self newDocument. event wasHandled: true]
Expected result

Focus the workbench, then try your platform’s command/control modifier with N. A new draft appears. Escape releases focus. Typing in a different focused morph does not invoke this workbench.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Give shortcuts an explicit focus owner in native Squeak 6.1
Native Squeak 6.1 capture of executed Morphic code. After HandMorph dispatches a scripted control-modified key event to the focused panel.

Watch the workflow

The demonstrations below use the real Squeak image. Each caption explains the recorded interaction. Animations stay paused until you choose Play demo.

NATIVE SQUEAK CAPTURE
Menus, dialogs & keyboard shortcuts demonstration
Native scripted sequence: toolbar New, native menu New, focused keyboard New, then Escape. Each frame comes from the actual isolated Morphic world. This is an action-driven animation, not a human mouse recording.
NATIVE SQUEAK CAPTURE
Menus, dialogs & keyboard shortcuts demonstration
Native scripted sequence: real confirmation No, confirmation Yes, real file chooser selection, then file Cancel. The script answers the dialogs through their native APIs and captures the resulting states.

Practice with tested solutions

1. Exercise the no-selection guard

A destructive command must handle an empty selection before indexing the collection or opening a dialog.

Show a tested solution

Workspace → Print it after filing in LearnSqueakCommands.st. No dialog should open.

Exercise solution
| app answer |
app := LSCommandWorkbench open.
app selectIndex: 0.
answer := {app removeDocument. app documents size. app selectedIndex}.
app delete.
answer
Expected

#(false 3 0)

2. Inspect the shared command route

Ask the real first menu item who receives its action and which selector it sends. This proves that the menu reuses application behavior.

Show a tested solution

Workspace → Print it. This constructs a menu without popping it up.

Exercise solution
| app menu answer |
app := LSCommandWorkbench open.
menu := app commandMenu.
answer := {menu items first target == app. menu items first selector}.
app delete.
answer
Expected

#(true #newDocument)

3. Test a cancelled file choice

A nil filename is the ordinary Cancel result. Verify that applying it returns false and preserves every row.

Show a tested solution

Workspace → Print it. This tests the result handler without opening a file dialog.

Exercise solution
| app before answer |
app := LSCommandWorkbench open.
before := app documents.
answer := {app acceptChosenPath: nil. app documents = before. app status}.
app delete.
answer
Expected

#(false true 'File choice cancelled')

When something looks wrong

The shortcut does nothing

Click Focus keys or empty panel space first. Squeak only sends the event to the current focus owner. Try the command or control modifier supported by your VM/host; use the New button if the OS reserves that key.

Right-click does not open this menu

The example handles Squeak’s yellow-button event, whose physical mouse mapping varies. Use the Menu button; this calls the same menu method.

New stops adding rows

The teaching panel deliberately limits itself to five visible rows. Remove a row, or extend it with a scrolling list as a next project.

The chooser shows folders outside the fixture directory

Its initial directory is a starting point, not a sandbox. Choose the provided fictional .txt files for this lesson.

A file-in appears to wait

Stages 4 and 6 intentionally open modal dialogs. Answer the confirmation or Accept/Cancel the file choice. Other checkpoints complete immediately.

Verification, cleanup and next steps

51 native checks passed, plus all eight fresh-image checkpoints and the three exact published exercises.

  • Native toolbar and MenuItemMorph dispatch to the same receiver
  • Real UIManager confirmation Yes and No
  • Native FileChooserDialog selects an existing fixture and cancels
  • Nil, empty and missing path handling
  • No selection, empty collection and row-limit recovery
  • Control and command modifier events dispatched via HandMorph
  • Other focus prevents workbench shortcuts; Escape and delete release focus

Close the tutorial windows when finished. Save the source separately from the image if you want to recreate the application in a clean image.

  • Squeak 6.1 build 23976 source verification — MorphicUIManager>>confirm: and chooseFileFrom:matching:label:, FileChooserDialog class>>openOn:pattern:label:, FileAbstractSelectionDialog selection/accept/cancel methods, MenuItemMorph>>invokeWithEvent:, HandMorph>>sendKeyboardEvent: and newKeyboardFocus:, KeyboardEvent modifier queries.

Explore more working examples · Return to the learning path