SmalltalkThe Interactive Programming Environment Adele Goldberg Xerox Palo Alto Research Center
A Addison-Wesley Publishing Company Reading, Massachusetts · Menlo Park, California London · Amsterdam · Don Mills, Ontario · Sydney
This book is in the Addison-Wesley series in Computer Science MICHAEL A. HARRISON CONSULTING EDITOR
Library of Congress Cataloging in Publication Data Goldberg, Adele. Smalltalk-80. Includes indexes. 1. Smalltalk-80 (Computer system) I. Title. II. Title: Smalltalk-eighty. QA76.8.S635G6381984 001.64 83-11856 ISBN 0-201-11372-4
Copyright © 1984 by Xerox Corporation. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. Published simultaneously in Canada. ISBN 0-201-11372-4 EFGHU-HA-89
Preface
The user interface to the Smalltalk-80 system is a multipurpose interface, designed to facilitate text and graphics creation and manipulation, program development, and information storage and retrieval. You, as the user create, manipulate, save, or retrieve, either a visual form or specific information within such a form. You interact with the system on a bitmapped display screen, using a typewriter keyboard and a pointing device. The Smalltalk-80 system includes utilities typical of a computer's operating system: compiler, debugger, text editor. These are brought together on the display screen in the form of a collection of rectangular areas or views of information. One rectangular area might view the text of a program under development. Changing the text is accomplished by pointing to the parts to be changed, and typing new text or issuing an editing command such as delete. When the text is considered correct, an accept or compile command is issued. If any syntactic errors are detected, they will be indicated in the text in the window so that they can be corrected right away. Once all syntactic errors are corrected, the text is compiled into object code and linked into the system, as the system is running. The new code can then be tested by typing an appropriate expression, selecting it, and issuing an evaluate command. This process is immediate; no exchange of editing, compiling, filing, or executing "modes" is required. Part One of this book is an introduction to the user interface to the Smalltalk-80 system. Part Two is an explanation of the support provided for finding information about objects that exist in the Smalltalk-80
IV
Preface
system. Part Three is an illustrated description of how to explore the class descriptions available in the system, and of how to use the editors for implementing new class descriptions. Part Four presents the support available for finding and correcting errors, while Part Five introduces access to external files and system housekeeping support such as crash recovery and change management. Parts One through Five explain how to manipulate the components of the user interface. They are written to encourage specific practice and exploration; each section includes suggested exercises. A brief introduction to the Smalltalk-80 language is also provided in order to explain the ways in which the interface components provide access to the language components. If you have access to a Smalltalk-80 system, you will need to read the book only once, after which you can rely on the on-line aids provided by the interactive system. The on-line aids consist of a menu-oriented interface to remind you of available functionality, comments for each class and method, an "explain" capability that can identify the tokens in a method, and a spelling corrector. This book is not intended as an introduction to programming in the Smalltalk-80 language. If an indepth understanding of the language is desired, you should use this book in conjunction with Smalltalk-80: The Language and its Implementation, by Adele Goldberg and David Robson (Addison-Wesley, Reading, Mass., 1983), which includes reference material for the system classes. Because of the detailed scenarios and figures, this book can be used independent of a running system to learn about the components of the user interface, and about the process of working with a graphicaloriented, interactive system development environment.
About the Described System
The system described in this book was released for general licensing in May, 1983, by the Xerox Corporation as the "Smalltalk-80 System Version 2." Version 1 was a preliminary version of the system that was originally released to several companies participating in a review of the formal specification of the Smalltalk-80 virtual machine, and provided by Xerox Electo-Optical Systems (now Xerox Special Information Systems, Pasadena, Calif.) in 1981-1982 as one of their software offerings on the Xerox 1100 Scientific Information Processor. Version 2 added functionality to the system, notably the spelling correction used in compiling and debugging methods; special browser queries about instance
Preface
and class variables, class references, and class hierarchies; and special inspectors. As a language, the Smalltalk-80 system Version 2 includes support for multiple inheritance and multiple language compilers. Some of the examples provided in this book use system user interface components from Version 2 that do not exist in the Smalltalk-80 System Version 1. The larger examples of Smalltalk-80 definitions given in this book are provided to Xerox customers or system licensees as part of the files on their disk or magnetic tape. This includes the protocol and project browsers described in Chapter 15, the model for financial histories developed in Chapters 17, 18, and 19, and methods for viewing and interacting with financial histories listed in Appendix 1. Glenn Krasner and Evelyn Van Orden have been the main motivators and supporters in getting the system releases and examples completed for this kind of distribution.
Acknowledgments
As the Smalltalk-80 system evolved and was tested by nonXerox commerical organizations and universities, this book evolved from a user manual to a general description of the programming environment. The choice of content and organization benefited from review by many people. Norman Meyrowitz of Brown University was especially instrumental in pointing out omissions of detail. I wish also to thank Susanne Bodker, Glenn Krasner, Michael Madsen, Paul McCullough, Michael Rutenberg, Rachel Rutherford, and Evelyn Van Orden, (all of the Xerox Corporation); David Casseres (Apple Computer), Pavel Curtis (Cornell University), Steve Draper (University of California, San Diego), and Trygve Reenskaug (Central Institute for Industrial Design, Oslo, Norway). The Smalltalk-80 System is the result of research and development of the Software Concepts Group of the Xerox Palo Alto Research Center. As the group manager, I took responsibility for documenting the system. It is not possible to identify the individual contributions made by each member of the group in the creation of the complete system. However, I would like to point to several aspects of the system documented in this book, and acknowledge several contributors: the system browser was first introduced by Larry Tesler and then enriched by Dan Ingalls, the debugger was introduced by Dan, the change manager by Peter Deutsch, the version handler by Steve Putz, the special inspectors and the file list view by Glenn Krasner, and the form and bit editors by Bob Flegal and Diana Merry. The first version of spelling correction was implemented by Steve and then incorporated into the system com-
γι
Preface piler by Dan. Ted Kaehler created the explanation utility on a suggestion by Ellis Cohen of Brandeis University. In addition, the example of a protocol browser given in Chapter 15 was suggested by Dave Wallace from the University of California, Berkeley, and that of the combinations of elements of a collection by Steve Putz. Many new ideas and bug fixes came from our colleagues at the Xerox Special Information Systems, including Evelyn Van Orden, who maintains the customer release version of the system (a system that includes network communication facilities), Rae Conrad, Bob Lansford, and Michael Malcolm (whose clever scrolling additions to the text editor are included in Version 2). Glenn Krasner, Dave Robson, and Steve Putz helped me complete Version 2 of the Smalltalk-80 system, create the images of the display screen for the book figures, and produce the magnetic tapes for the typesetter. As in the other books in the Smalltalk-80 series, the original text for this book was supplied to the publisher on magnetic tape that included formatting codes identifying the various types of textual entity in the manuscript. The software for the conversion from the Xerox internal formats to that of the typesetter was written by Dave Robson. The timely manner in which the production process was handled was due both to Dave's software and personal support, and to the efforts of Eileen Colahan of the International Computaprint Corporation and Fran Fulton, the production editor. The original syntax diagrams shown in Chapter 5 were prepared by Janet Moreland. All the figures that represent the Smalltalk-80 display screen graphics and the chapter opening artwork were created by me using the Smalltalk-80 system. They were printed on the Platemaker system developed by Gary Starkweather and the Imaging Sciences Laboratory of PARC. I would like to thank Gary, Eric Larson, and Julian Orr for making the Platemaker available. Registered trademarks mentioned in this book are Lisa, (Apple Computer Inc.); VAX 11/780 and VAXstation (Digital Equipment Corp.); and Smalltalk-80 (Xerox Corp.). Adele Goldberg Palo Alto, California October 1983
Contents
PART ONE
The General System Interface 1 Introduction to the Book and the System 1.1 Appearance of the Hardware System 1.2 Getting Started 1.3 Try It, Just to See 1.4 Stopping a Work Session 1.5 Summary of Terminology 2 Basic User Interface Components 2.1 Display Screen Visual Cues 2.2 Designating Rectangular Areas on the Display Screen 2.3 Menus 2.4 The System Menu 2.5 Standard System Views 2.6 Summary of Terminology 3 How to Use the Text Editor 3.1 Text Selection 3.2 Inserting Text
1 3 6 14 15 22 26 29 30 34 35 41 46 49 51 52 57 VII
VIM
Contents
PART TWO
3.3 Issuing an Editing Command 3.4 The System Transcript 3.5 Summary of Terminology 4 How to Use Projects 5 Fundamentals of the Smalltalk-80 Language 5.1 Objects, Messages, and Methods 5.2 Expression Syntax
57 65 65 67 75 76 80
5.3 System Components 5.4 Overview of the Programming Process 5.5 Summary of Terminology: General Concepts 5.6 Summary of Terminology: Syntax 6 How to Evaluate Expressions 6.1 The do it Command 6.2 The print it Command 6.3 The System Workspace 6.4 Examples 6.5 Summary of Terminology 7 How to Make Pictures 7.1 Making Pictures with the Form Editor 7.2 Making Pictures with the Bit Editor 7.3 Making Pictures with Expression Evaluation 7.4 Summary of Terminology
95 99 102 103 105 106 110 111 112 116 119 120 133 136 139
How to Find Information in the System 8 Finding Out About Instances 8.1 The Structure of an Inspector 8.2 Changing the Values of Variables 8.3 Sending Messages to an Object 8.4 Special Kinds of Inspectors 8.5 Finding Out About a Running Process 9 Finding Out About System Classes 9.1 The Structure of a System Browser 9.2 Messages to a Class versus Messages to an Instance
141 143 144 147 154 156 159 161 163 168
[Χ
Contents
9.3 Browser Menu Commands 9.4 Browsing a Subset of the System 10 Finding Out About Messages and Methods 10.1 Which Methods Send a Particular Message? 10.2 Which Classes Implement a Particular Message?
ART THREE
172 187 195 196 199
10.3 Which Messages are Sent in a Particular Method?
201
10.4 Which Methods Reference a Particular Variable or Literal?
206
How to Modify Existing Classes and Create New Classes
215
11 Modifying Existing Class Descriptions 11.1 Modifying Existing Methods
217 218
11.2 Modifying Protocols
224
11.3 Adding New Methods 11.4 Modifying Class Comments
233 249
12 Modifying Existing Class Definitions
251
12.1 Name of Superclass
252
12.2 Name of Class 12.3 Instance Variable Declarations
254 260
12.4 Class Variable Declarations 12.5 Pooled Dictionary Declarations
266 267
12.6 Class Category
268
13 Creating a New Class Description 13.1 Define a New Class
273 274
13.2 Define the Class Protocol
278
13.3 Define the Instance Protocol
284
14 Improving Performance 15 Examples of Creating or Changing Browsers 15.1 A Protocol Browser 15.2 A Project Browser
295 299 300 322
15.3 Modify Class Project
339
15.4 Change the System Menu
346
Contents
PART FOUR
How to Find and Correct Errors 16 Spelling Correction
353
17 Syntax Errors
363
17.1 Variable Name or Message Selector Errors
364
17.2 Poorly-Formed Statements or Methods
369
18 Notification of an Execution Interrupt
375
18.1 Incorrect Message Selector
376
18.2 Other Runtime Errors
383
19 Examining and Debugging Execution State
385
19.1 The Activation Stack
386
19.2 The Structure of a Debugger
388
19.3 The Context of a Message Receiver
394
19.4 The Context of an Interrupted Method
395
19.5 Evaluation Within the Context of an Interrupt
396
20 Kinds of Execution Interrupts
401
20.1 Breakpoints
402
20.2 User Interrupts
409
20.3 Running Out of Space
409
20.4 Recursion in the System Error Handler
411
21 Single-stepping Through an Execution
PART FIVE
351
External Files 22 The File System 22.1 Writing Code onto a File
415
429 431 432
22.2 Accessing the Contents of a File
436
22.3 Retrieving the Contents of a File
450
22.4 Getting Started Revisited
457
23 System Backup, Crash Recovery, and Cleanup
459
23.1 Saving Your System State
460
23.2 The System Change Set
462
23.3 The System Audit Trail
467
23.4 Creating a "Clean" System
477
23.5 Version Management
480
X[
Contents
Appendixes 1 Financial History Views and Controllers 2 Smalltalk-80 Software Development Do's and Don'ts Indexes System Workspace Index Menu Command Index Subject Index
485 499 503 510 512
PART
ONE
The General System Interface
The Smalltalk-80 system consists of an object-oriented programming language and an integrated collection of tools for interacting with components of that language. In the Smalltalk-80 language, the fundamental way to indicate that something should happen is by sending a message to an object. An object is a representation of information consisting of private memory, and a set of operations to manipulate information stored in the private memory or to carry out some actions relative to that information. Sending a message is the Smalltalk-80 way of asking the object to carry out one of its operations. All information in the Smalltalk-80 system is represented as an object. Each object knows the messages it can understand. Associated with each such message is a method that describes how the object should respond to the message. The user interface to the Smalltalk-80 system can be viewed as a graphical way in which to identify objects and to choose messages to send to objects. When an object is sent a message, the appropriate method is invoked and some action is taken. The purpose of this book is to describe the varied ways in which objects and messages can be identified and methods invoked; its purpose is also to describe some useful ways in which information about objects can be retrieved. This book is written in a tutorial or "try and see" style. Each section describes the functionality of a part of the user interface and then encourages you to employ that functionality. Although this book does not substitute for a detailed exposition about the language, an overview is provided and a summary of the language syntax is included. The overview is sufficient information so that you can understand the chapters on evaluating expressions, on accessing objects already in the programming system, and on creating new objects.
The tutorials are presented in an order designed first to give you practice in controlling the hardware devices that support interaction with the graphical elements of the display screen, and in reading and responding to the visual cues. Visual cues include differently-shaped cursors, highlighted text, flashing rectangular areas of the screen, and prompters and confirmers. Next, the basic editing functions are introduced: creating rectangular areas on the screen, called views, in which to access information; and invoking menus in which to choose commands to send to objects, editing text, and editing pictures. Special views called projects allow you to manage several separate screens of information. Each project or screenful maintains its own history list of the views you have created and of the changes you have made to the system. After a description of how to create and edit projects, you are introduced to the Smalltalk-80 language, and how to evaluate expressions.
1 Introduction to the Book and the System
1.1 Appearance of the Hardware System Appearance of the Display Screen Pointing Device "Buttons" 1.2 Getting Started System Files 1.3 Try It, Just to See 1.4 Stopping a Work Session Saving Information 1.5 Summary of Terminology
Introduction to the Book and the System The Smalltalk-80 system runs on a microcomputer that includes a highresolution bitmapped display screen, a typewriter keyboard, and a pointing device. The display is used to present graphical and textual views of information to the user. The keyboard is used to present textual information to the system. The pointing device is used to select information on the display screen. The pointing device controls the movement of a cursor on the screen; the cursor shows the location currently being selected. The pointing device can be, for example, a mouse, a graphics tablet, or function keys on a keyboard. There are a variety of hardware configurations on which the Smalltalk-80 system runs. These configurations might have different resolutions for their display screens, different layouts of keys on their keyboards, and different types of pointing devices. Photographs of several Smalltalk-80 systems are shown in Figure 1.1. Several sections of this book depend on the particular hardware configuration that you, the user, have available. These are Sections 1.1 and 1.2, on the hardware system and on how to get started, and the chapters of Part Five on the use of an external file system. Much of the interface to external files is the same for all hardware configurations, but the particulars of naming files and creating system back ups may differ. For a description of the hardware devices you have available, the initial start up sequence you must follow, and the file-naming and back-up conventions you should use, you must obtain information specific to your system that is not provided in this book. Throughout the book, an indented paragraph of small print is used to provide information at a level of detail that may be of interest to yoii if you want to know a bit more about the structure of the Smalltalk-80 system. For example, the names of classes that support a user interface component may be given, along with messages that implement a particular user interface function.
You can skip over these comments without losing information needed to interact with the system. Also, alternate designs are given in small print as suggested exercises that you might try if you are proficient with the language and the programming environment.
Figure 1.1 Top: Tektronix Magnolia, experimental workstation (photo by Edward L. Reuss, courtesy of Tektronix Inc.), Apple Lisa, experimental software (photo courtesy of Apple Computer Inc.); middle: Hewlett-Packard Laboratories, development station (photo by Rich Marconi, courtesy of Hewlett-Packard), Digital Equipment Corp.,VAX-ll/780 with VAXstation display (photo by Charles W. Gamage Jr., courtesy of Digital Equipment Corp.); bottom: Xerox Dorado and Xerox implementation on the SUN Microsystems Inc. workstation (photos by Κ. Ο. Beckman and Wes Dorman, courtesy of Xerox Corp.).
Introduction to the Book and the System
Introduction to the Book and the System
1.1 Appearance of the Hardware System
The significant parts of the hardware on which the Smalltalk-80 system runs are identified in Figure 1.2: the keyboard, the display screen, and a pointing device. These are the parts that play a significant role in the user interface of the system. In Figure 1.2, keys that play a specific role in the Smalltalk-80 text editor are labeled. Henceforth, the names of the keys as indicated in the following keyboard map are used, rather than the key-cap label. To use the system, you must determine the correct mapping for the hardware system you have available. Also in Figure 1.2, the coordinates of the corners of the display screen are marked. Notice that position 0, 0 is at the upper left corner of the screen, and that the y-coordinate increases as you move down the screen. 1024.0
Display Screen
Τ 2 l 3 I 4 [ 5 Τ 6 ] Γ] β | 9 I ° I TAB I
CTRL I
Figure 1.2
| Q | W | E | R | T | Y |
Pointing Device
]
RETURN
| Z | X | C | V | B 1 N 1 M | , | | / | SHIFT
Space Bar
ΐ ^F
U
1 A | S | D | F | G | H | J | K | L | |
SHIFT
I ° Ι
Keyboard
1
I
1.1 Appearance of the Hardware System
" Appearance of the Display Screen
key names
key cap label
backspace carriage return control delete escape line feed space bar
BS RETURN CTRL DEL ESC LF no label (bottom row, large single key)
The display screen has a light gray background. White rectangular areas containing text and/or pictures are placed against this background. Each of these areas is called a view. The content of a view is the text and/or picture within its rectangular border that you can examine, create, store, and retrieve. A sample image of a Smalltalk-80 display is shown in Figure 1.3. Most of the views on the Smalltalk-80 display screen are standard system views, meaning they provide some standard functions. In particular, you can • visually identify a standard system view by a label • change the screen location of a standard system view • change its size • replace it with an area containing only the label • remove it from the screen In Figure 1.4, there are several standard views. Each has a label in the upper left corner. Some, such as the two views in the center of the figure, consist only of a label. These are referred to as collapsed views. The views in the figure are in different locations and have different sizes. The view at the top of the figure consists of five parts or subviews. The content of a subview might depend on the content of one or more of the other subviews. When you are working on several different tasks, the tasks can be presented in a variety of ways: with each in a different view, with some or all in the same view, or with some tasks, such as background processes, in no view at all. Views are known to a special system object called a control manager. This manager's job is to let you move the cursor within the border of a view, and to interact with either the view itself or with the information inside it.
8 Introduction to the Book and the System Form Edit or I
!
fl
File List| +
'Γί a 11 e y Fo rm - c 1 a. s s - fro m G a. 11 e y -. s t, La s t Pa. re η t - S c r e e η 0 u t - c h a. n g e s. s t. PressOut.st, ScreenOut.st.
1 II' 1
/
,st
\
Μ \
'Fro m 8 m a 111 a. 1 k - 8 0 ο f 18 A p ri I 19 8 3 [ V 3 1 ] ο η 2 5 April 1 9 8 3 3:04:56 pm PDT ( M o n d a y ) ' ! IFile D i r e c t o r y class met hods For: ' u t i l i t i e s ' !
m
mP -
m
-JIB
fife; ffl
Β• 9
files Μ a. t c h i η g: file D e s i g η a. t ο r " A n s w e r a c o l l e c t i o n of t h e names of files t h a t match the string, file Designator, Ε χ a rn pie: File D i re c t ο ry files Μ a t c h ing: • System>*,errors' " | dir pattern | dir ·*- self directory From Name: fileDesignator setFileNarne: [ i p a t t e r n ] . tdir files Matching: pattern!
S y s t e m W ο rl· .s ρ a c e Ό y s t e m Τ r a n s c r ί ρ 11
S m a l l t a l k - 8 0 of April 1 , 1 9 8 3 Copyright ( c ) 1 9 8 3 Xerox Corp. All rights r e s e r v e d . C r e a t e File System Source Files «- A r r a y n e w : 2, Source Files a t : 1 p u t : (File S t r e a m ο 1 d Fi 1 e Ν a m e d: ' S m a 111 a 1l·180, s ο υ re e s').
Figure 1.3
_9 1.1 Appearance of the Hardware System
System Browsgr Fraction N u m e r i c - M a g n i t u d Integer Large Negative I nte mathematical func Collect ions-Abst r= La rcj e Po s i t i ν e I n t e g I test i η g
Collect ion s-Unordi: C ο 11 e c t i ο η s - S e q u θ message selector and arqun Point + "comment stating purpo Smalllnteqer + | temporary variab statements
+ aNumber "Answer the sum of the receiver and a Number," self s u b c I a s s R e s ρ ο η s i b hit y
b y 51 e m W ο rl· s ρ a c e Smalltalk-80 of April 1, 1983 Copyright (c) 1 9 8 1 , 1982, 1983 Xerox Corp, All rights reserved,
Create File System Source Files *• Array new: 2, Source Files at: 1 put: (FileStream oldFileNamed: 'SmalltalRSO. sources'), SourceFiles at: 2 put: (FileStream oldFileNamed: 'SmalltalkSO.changes'). (SourceFiles at: 1) readonly, Figure 1.4
10 Introduction to the Book and the System
Svstem Browser Numeric-Magnitu< Numeric-Numbers Collections-Abstr Collect ion s-Unord ' I: o 11 e c t i ο η 5 - S e q υ s
Collections-Text cIass
bitmapped display screen, a typewriter Rev board, and a pointing device, The display is used to present graphical and textual views of information to the user, The keyboard is used to present textual information to the system, The pointing device is used to select information on the display screen, The pointing device controls the movement of a cursor on the screen.; the cursor shows the location currently being selected, The pointing device can be, for example, a mouse, a graphics tablet, or function Revs on a keyboard.
System Worl· span Create File Syste Source Files *• Arr Source Files at: 1 oldFileNamed: 'Sma.lltalR8O.sour SourceFiles at: 2 oldFileNamed: 'Srnalltall· 80.change.
Figure 1.5
There are a. variety of hardware configurations on which the Small talk- 80 system runs, These configurations might have different resolutions for their display screens, different layouts of keys on their keyboard, and different types of pointing devices, Photographs of several SrnalltalR-SO systems are shown in Figure 1,0, Several sections of this book depend on the
π 1.1 Appearance of the Hardware System Available screen space has been optimized by allowing the views to overlap, partially or wholly. The active view (the view in which you are currently working) is automatically moved to the top of any stack of overlapping views. Since a view often contains more information than can be displayed at any given time within its boundaries, an additional scroll bar area is associated with each view, where appropriate. A scroll bar presents a method by which you can specify the part of the available information that you want displayed. In Figure 1.5, a view of textual information is the active view, the one labeled Workspace. Its scroll bar area is shown at its left side. The fact that the gray area of the scroll bar fills only part of the scroll bar height indicates that you see only part of the information that can be accessed using this view.
Pointing Device "Buttons"
Figure 1.6
A likeness of a pointing device used by the Smalltalk-80 system developed at the Xerox Palo Alto Research Center is shown in Figure 1.6. It is called a mouse. The cursor on the display screen is moved by moving the mouse over a flat surface. The mouse has buttons on it which are used to make different kinds of selections. Some hardware configurations for the Smalltalk-80 system have buttons on the pointing device that can be used to select display positions or to request the display of a particular menu. Other configurations use keyboard function keys for the same purpose. Each configuration shares an identical collection of techniques for accessing objects and messages, and an identical collection of tools for manipulating objects. For example, each system shares a common editor for creating and modifying text or pictures. The Xerox mouse has three buttons on it. These buttons are identified in Figure 1.6 as red button, yellow button, and blue button.
red yellow button button
blue button
12 Introduction to t h e Book and t h e System The names are for historical, not visual reasons. Some of the original Xerox mice had colored buttons.
Throughout the standard Smalltalk-80 system, • red button is used to SELECT information • yellow button is used to get a menu for EDITING the CONTENTS of a view • blue button is used to get a menu for EDITING the VIEW itself In referring to the use of the buttons, we will use the following terminology: press
push and hold the button down
release
remove finger from button, letting the button up
click
press button, then release it, without moving the cursor
double click
click two times in succession, without moving the cursor
Some people refer to selection using a click as bugging. Their expressions take the form of "bug that command" or "bug outside the view."
Note carefully that we distinguish between pressing the button down without releasing (press), and pushing the button down and releasing (click). Note also that a selected item is highlighted, typically by complementing it. To complement text, black characters on a white background are changed to white characters on a black background. For many operations, pressing the button down is a separate action from releasing the button. Pressing down the yellow or blue button, for example, causes a list of items to appear on the screen; releasing the button chooses the selected item. This list of items is referred to as a menu. While the button is down, the system provides feedback about what can occur. For example, a menu item may be highlighted to indicate that it will be the one chosen if the button is released. This gives you a chance to confirm visually that it is the desired item, or to move the cursor to a different item and to see it selected (highlighted) before you release the button. Releasing the button chooses the item. The distinction between pressing and releasing a button is a significant one to learn in order to be able to interact with the Smalltalk-80 system. Most actions occur as a result of releasing a button. There are only two places in the system where the action is invoked when the button is pressed down: in controlling the scroll bar, and in selecting text. In Figure 1.7, notice the image of the pointing device at the lower left side. The image consists of a rectangle with three subareas; one of the three subareas is filled with black, the others are white. Each area denotes one of the buttons you can press. In the picture, the image indi-
. 13 1.1 Appearance of the Hardware System
This is some text that has been typed into a work: a g a ι η undo
This is some text thi waaym been typed into a ρaste do it workspace, print it
Figure 1.7
a.ccQpt This is some text that ]cancel been typed into a workspace.
010
cates that the yellow button is currently being pressed, causing a menu to appear and an item in the menu to be highlighted. This image is used throughout this book in order to illustrate pressing a button, even though the three buttons on the hardware system you are using may not be grouped or packaged on a single rectangular-shaped device. The four possible button images that may appear at the lower left side of a figure are shown in Figure 1.8. Each button image represents a press of one or no button. When we wish to denote "clicking" a button, two button images will be displayed at the lower left side of the screen image. The first button image designates the button to press, and the second indicates that a release should follow. Figure 1.9 shows the three possible images for button clicks.
000 100 010 001 Figure 1.8
denotes no button pressed
denotes red button pressed
denotes yellow button pressed
100 010 001 000 000 000 click red button Figure 1.9
click yellow button
click blue button
denotes blue button pressed
14 Introduction to the Book and the System
1.2 Getting Started
In order to get your Smalltalk-80 system started, there should be a separate document for you to consult that describes your particular hardware system and file-naming conventions. It will identify the files you need, the procedure for turning the power on, and the commands or buttons to push in order to install the Smalltalk-80 system. On most of the Xerox systems, for example, there is a small button located at the back of the keyboard that you push (called the "boot" button). A herald will appear announcing the Xerox Executive. If the Xerox Executive is installed with the proper files, you can then type @st80.cm
and then press the "carriage return" key. After a few moments, an image of the Smalltalk-80 programming interface should appear on the display screen.
System Files
Although different implementations may have different start up procedures, and perhaps require different sets of system files, the basic Xerox Smalltalk-80 system requires four significant files. ST80< Version >.im
This is the Smalltalk-80 system image. It contains the compiled form of each method, as well as the initial bitmap that appears on the screen when the system is installed, and all the other system objects.
ST80 < Version > .sources
This file contains the text for each method in the system. The compiled form of each method includes an index into this file so that the text can be retrieved upon user request. In the Xerox systems, when a network-based file server is available, this "sources" file resides on the file server and is shared by all Smalltalk-80 users.
ST80 < Version > .changes
Initially this is an empty file. When the user interacts with the Smalltalk-80 system, each action that involves evaluating an expression is stored in this file. If the system crashes, it is possible to recover your work by evaluating the expressions stored in this file. See Part Five for more details.
ST80< Version >.run
This is the "run file" or virtual machine emulator for the Smalltalk-80 language. The system is invoked by executing this file with the name of the image file as its single argument. The file ST80.cm is a "command" file; it is an indirect way of naming the two files.
15 1.3 Try
It, Just to
See
Wherever we have written < Version > in naming a file, we mean that the file name actually contains a date indicating a particular system release. Typically the date should be the same for all the files. In the Xerox systems, capitalization in file names is not meaningful.
1.3 Try It, Just to See
The next chapters present details about the basic user interface components, the text editor, and how to evaluate Smalltalk-80 expressions. Before reading these chapters you might wish to try the system, just to see what you can do. This section illustrates an example interaction you can try in order to get an early introduction. You already know that the display screen has a light gray background and that there may be one or more rectangular areas containing text. Move the cursor so that it is not inside any rectangular area, that is, move it so that it is over the light gray background. Press the yellow button; do not release the button. A menu appears (Figure 1.10a).
iiiiiiii S y s t e m T r a n s c r i p t j |M Π=Μ ΠΜ Μ Μ Μ ΠWm Μ=^=Μ i=S y s t e m W ο r k s ρ a c e |ϊΗΜ!ΗΠΠΠΠΗΜΐ:ΠΠΠΠΠί!ΠΠΙΠΠΝΜΠΜΠΠπΠ!ΠΟΗΠΠΠ
:
:·:·:: ::::::::::::::i^i^i^i^i^:::::::::::::::::::::-:::;::i::::r:!:::::::!:::::::;::::
ijiiiij Workspace
| i Smalltalk-80 of April 1, 1983 iiiiiiii Copyright (c) 1983 Xerox Corp. iiiiiii All rights reserved,
m iiiiiii iiiiiii
iiiiiijii Create File System
iiiiii
ijiiijiii SourceFiles *• A r r a y n e w : 2.
jjjjiij
:::;::;;: bourceFiles a t 1 put: (Filebtrearn :j;j:;; Ι;:;:;!:; ο 1d Fi 1 e Ν a. in e ό \ ' I a s 11 a. s ΐ ρ a. r
;iiiiij This is some text that has been typed into a iiiiiii workspace.
iiijii iiii
!;!;!;; m\
:;::!:; This is 5ΟΓ e text tnat ηas ο i e n t y p e d i n t o a i;i; ml iiiiiii workspace, iiiii; Μ
!|l||li
iiiiiij This is some text that has been iiiiiii typed into a workspace.
Figure 1.10a
0101
r e s t o r e display e x i t project
MMM W&M
project file list
· iiiiiiiiiiiiii! iiiiiliiiiij
browser
ιϋϋϋϋίιϋϋ
i;| iiiiiii system transcript iiiiiiiiiiiiiii ui iiiiiii system workspace iiiiiiiiiiiiiii iiiiiii iiiiiii
s a v e
quit
iiiiiiiiiiiiiii iiiiiiiiiiiiiii
w 16 Introduction to the Book and the System
Move the cursor up and down, noticing that different menu items are highlighted. Move the cursor so that the item workspace is highlighted. Release the yellow button. The cursor changes shape (Figure 1.10b). Move the cursor anywhere towards the center of the screen and press the red button. You have selected the upper left corner of a rectangular area. The cursor changes shape again (Figure 1.10c). Move the cursor around to select the lower right corner of the area. Release the red button. You have now created a small workspace on the screen (Figure l.lOd).
jiililii S y s t e m Transcript|||ΗΠ!ϊΐ!Η!Η|!:ΠΗΙ|!!!Η |!i|i:!i System Workspace! yMiii; Srnalltalk-80 of April 1, 1983 iiiiiiii! Copyright (c) 1983 Xerox Corp, n i UHU
A
" f i g h t s reserved.
jiiiijiij Create File System ι!:!!!;!! SourceFiles *• Array new: 2. liiijiili SourceFiles at: 1 put: (FileStream W ο r k s ρ a c e |ΠΗΠίΗΗίΗϊ;ΗΠΠΗΗ=Η!ΗΗΗ;ΗΠΗΠΗ=ίΗΝ;! ijijliili oldFileNamed: 'lastlastparent.source;'). This is some text that has been typed into a workspace. This is some text that has been typed into a workspace.
This is some text that has been typed into a workspace.
Figure 1.10b
000
r
_π
1.3 Try
It, Just to
S y s t e m "Transcript|Πϋϋϋϋ1ΙϋΠίΗΗϋ J!ijjj|jjj|j|j; System Workspace 1 1 1 Srnalltalk-80 of April 1, 1983 |j|!|j|!|j|i;! C o p y r i g h t (c) 1983 Xerox Corp, |;|!|li|!i!j|i All rights reserved,
ΙΙϋϋΐϋ Create File System
W o r k s p a c e |ΐΠΙΜΜϋϊΙΗΗΜΐϊΠΠΜΜΗΜ!ΜΠϊΜΜΐϋϋΠ
!;!|!;!;!;!|!:! S o u r c e F i l e s *• A r r a y n e w : 2, ijiiijiiijijlji S o u r c e F i l e s a t : 1 p u t ; ( F i l e S t r e a m ijiiijijijijij: oldFile N a m e d : ' l a s t l a s t p a r e η t,s n u r c e s ' ) ,
This is some text that has been typed into a workspace. This is some text that has been typed into a workspace,
Figure 1.10c
J
This is some text that has been typed into a workspace.
100
System Transcript
S y s t e rn W ο rl· s ρ ace
Srnalltalk-80 of April 1, 1983 C ο ρ y ri q h t (c ) 19 8 3 - e ro • C ο rp, All rights reserved,
W ο rl· s ρ β c e I This is some t workspace. This is some t w o r t space,
Figure l.lOd
TOO
This is some text that has been typed into a workspace.
y new: y, ut: (FileStream β s t ρ a re η t, s ο υ re e s'),
See
18 Introduction to the Book and the System Make certain the cursor is inside the workspace. Type 3+4 and then press the "escape" key. The three characters, 3, -f, and 4 should be highlighted (Figure 1.11a). If not, place the cursor just before the character 3, press the red button, move the cursor past the character 4, and then release the red button. The characters should be highlighted. Note that they make up a Smalltalk-80 expression.
cript[ System Transcr
iystem Wort space Smalltalk-80 of April 1, 1983 C ο ρ y ri q h t (c ) 19 8 3 :'. e ro · C ο rp. All right5 reserved,
Worl· spa e e l
y new: 2. ut: (FileStream a s t ρ a re η t. s ο υ re e s').
This is some ti workspace. Τ hi 5 if. some t worl· spece
This is some text that has been typed into a workspace.
Figure 1.11a
000 Be sure that the cursor is still inside the workspace. Press the yellow button so that another menu appears (Figure 1.11b). Move the cursor so that the item print it in the menu is highlighted (Figure 1.11c). Now release the yellow button. Notice that the expression has been evaluated and the result printed in the workspace. The result 7 is highlighted (Figure 1.1 Id).
19 1.3 Try It, Just to See
Systern Τranscrip11
System Workspace Srnalltalk-80 of April 1, 1983 C ο ρ y right (c) 19 8 3 X e r ο χ C ο r ρ. All rights reserved.
y new: 'd. ut: (FileStream a s t ρ a rent, s ο u re e s').
Worl· s ρ a e e l This is some ti workspace. This is some t worf.spa.ee,
Figure 1.11b
Bio
This is some text that has been typed into a workspace.
System Tra η script. I
S y s t e m Worl· space I
Srnalltalk-80 of April 1, 1983 C ο ρ ν ri q h t f c ) 19 8 3 '•'• e ro • C ο rρ, All rights reserved.
a ga ιη υηdo W ο r\ s ρ a c e I This is some ti workspace. This is some t worl· space.
Figure 1.11c
Bio
This is some text that has been typed into a workspace.
,• new: 2, ut: (FileS t re am a st pa rent, source;
20 Introduction to bhe Book and the System
b ν ."tern Tra Ί;Ι; ri
by i t e m V'.i'nrf ι p a c e Srnalltalk-80 of April 1, 1983 'Jinpynqht (.: I ^ o o :*ro. .jorp. All nqhtj r e ; e r v e d .
^
Workspace g 3+ 4 ^ ,. ne·//: 2. Jt
Workspace ||||!
ι1 File s t r e a m
a ; t p a rent ;ourc e ; ).
This is some ti workspace. Τ h i ; Ί ; ;orne t υ Γ Γ·._· ρ -r·. L y,
This is some t e x t that has been typed into a i•vorkspace.
Figure 1.1 Id
000 Press the blue button so that another menu appears (Figure 1.12a). Move the cursor so that the item close is highlighted (Figure 1.12b). Release the blue button. A special menu called a confirmer appears. You have requested closing a workspace, but the contents have not been saved. This is acceptable to you. Notice that as you move the cursor around, the shape of the cursor changes. When the cursor is over the part labeled yes, it is shaped as a hand with a thumb pointing up; when the cursor is over the part labeled no, it is shaped as a hand with a thumb pointing down. If you move the cursor outside the confirmer, it will "flash" or "blink" to indicate that you must answer the confirmer's question before proceeding. Move the cursor over the part of the confirmer that is labeled yes. Press the red button (Figure 1.12c). The item labeled yes is framed by a gray box as a way to indicate it is selected. Release the red button. The workspace will disappear. If you were able to follow the example, you successfully created a new view on the screen, used the text editor, evaluated an expression, and closed the view.
21
1.3 Try It, Just to See System Workspace Iji
S y 51 e m Τ ra η s c ri ρ t
Srnalltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp. All rights reserved.
y η e w: ϋ. ut: (FileStream a s t ρ a re η t. s ο u re e s'),
Worl· space I This is some text tl workspace. This is some text t workspace.
Figure 1.12a
Bui
This is some text that has been typed into a workspace.
System Workspace!!
S y s t e rn Τ ra n s c ri ρ t
Smalltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp. All rights reserved. 3+4
Workspace This is some text tl workspace.
under move frame [collapse]
This is some text t workspace.
This is some text that has been typed into a workspace. Figure 1.12b
y new: 2. ut: (FileStream a s t ρ a re η t, s ο υ re e s').
22 Introduction to the Book and the System
System Workspacel
SystQm Transcript!
Smalltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp. All rights reserved, 3+ 4
Wort-spacel This is some text tl workspace.
y new: 2. ut: fFileStream Contents have not been saved, Are you jurces'). certain that you want to close?
This is some text t '/vorl· space
Figure 1.12c
100
This is some text that has been typed into a workspace.
1.4 Stopping a Work Session
When you are ready to stop using the system, you choose a menu command quit. Move the cursor so that it is over the light gray background. Press the yellow button to obtain the menu and move the cursor so that the item quit is highlighted (Figure 1.13a). Release the button.
System Transcriptl;|
S y s t e rn W ο rks ρ a c e l
Srnalltalk-80 of April 1, 1983 restore display exit project project file list browser w ο rks ρ a c e system transcript s y s t e m w ο rks ρ a c ei save
Figure 1.13a
010
Copyright (c) 1983 Xerox Corp, All rights reserved, Create File System SourceFiles *• Array new: 2, SourceFiles a t : 1 put: (FileStream ο I d Fi I e Ν a m e d: 'la s 11 a s t ρ a re η t, s ο u re e s').
23 1.4 Stopping a Work Session
Another menu appears (Figure 1.13b), giving you three command choices.
3ystem Τranscrip11
System Workspace Smalltalk-80 of April 1, 1983 C ο ρ y ri q h t f c) 19 8 3 : '• e ro • C ο rp. All rights reserved. Create File System
iiijjil
Source Files *- A r r a y new; 2. i;i:ij; SourceFiles a t : 1 put: (FileStream jiijjii ο 1 d Fi 1 e Ν a m e d: Ί a stlastpa rent,sources'), ijiiiii
Figure 1.13b
000
;;;i::i!|:;;ilj;|ii;i;:|;;;;:ij;ji:i; bave, then iiiiliiiiiiiiiiiiiiiiiiiiiiUiiiiiii! Q u i t , w i t h o u t
;ί&;:ί;ί£ί;ϋ!:!ϋ:ί;ί;ίίί;;ί;;ί;
Continue
quit savirq
^
iiiiiiiiiilliiliiiiliiiii Save, then quit
Creates a snapshot as described later in this section, and then takes you out of the system.
Quit, without saving
Takes you out of the Smalltalk-80 system. (Each implementation of the system will differ as to what happens next. In the Xerox systems, you are returned to the Xerox Executive. You then type quit followed by a "carriage return" to blacken the screen.)
Continue
Erases the menu and continues your use of the system.
Choose one of these commands by moving the cursor over the menu, press the red button, move the cursor until the item you prefer is highlighted (Figure 1.13c), and then release the button.
S y s t e m T r a n sscript |
S y s t e m Wort s p a c e l
Smalltalk-80 of April 1, 1983 C ο ρ y ri q h t (c ) 19 8 3 " e ro • C ο rp. All rights reserved.
Create File System SourceFiles A r r a y new: ^ . SourceFiles a t 1 put: (FileStream old File Named: I a s 11 a s t ρ a re η t, s ο υ re e s'),
Figure 1.13c
100
24 Introduction to the Book and the System Clicking the red button outside the boundaries of the menu will also erase the menu and allow you to continue your use of the system.
Saving Information
There are times when you will save the current state of your work using a command in the user interface to create a snapshot. What you save is a version of the system image, that is, the compiled methods (the system ones and any you may have added to the system), all other system objects, and a representation of your current display screen. This saved image is referred to as a snapshot, and is stored on a file named snapshot.im If you create a snapshot and then quit, you can use the saved version of the system, rather than the original image, by executing the run file with the name snapshot.im as its single argument. Most Xerox systems include a command file for this purpose, so that you simply type ©snap.cm and then press the "carriage return" key. Sometimes more than one user will share a computer and its disk space. Each may wish to maintain their own snapshot. Some care must be taken to manage this situation by maintaining both the "snapshot" file and "changes" file (backing up on a separate disk or changing the name on the current disk). Both files must be maintained in a coordinated way because the snapshot refers to source code written on the changes file. When you restart a snapshot, you must also be sure to use the same run file and the same sources file that were used when the snapshot was created. See Chapter 23 for more details about the coordination requirements. Π Create a Snapshot Try to create a snapshot. There are two ways. Follow the instructions for stopping your work session given earlier and choose the menu item Save, then quit. Alternatively, choose the item save. That is, move the cursor over the light gray background, press the yellow button to obtain the menu, and move the cursor so that the item save is highlighted, as shown in Figure 1.14a. Release the button. A view called a prompter appears (Figure 1.14b). The name of the current snapshot image file shows in the prompter. Let's assume that you wish to use this same name. With the cursor inside the lower half of the prompter, press the yellow button and move the cursor so that the item accept is highlighted (Figure 1.14c). Release the button to choose the displayed name as the name of the snapshot. As an alternative to choosing the command accept to complete your response, you can type the "carriage return" key.
1.4 Stopping a Work Session
System Transcript}!!!
restore display exit project project file list browser workspace system transcript [system works ρ a c el
Srnalltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp. All rights reserved. Create File System SourceFiles <- Array new: 2. SourceFiles at: 1 put: (FileStream oldFileNamed: 'lastlastparent.sources'
Figure 1.14a
a y s t e m W ο rks ρ a c e Srnalltalk-80 of April 1, 1983 Copyright (c) 1983 Xero • Corp All rights reserved.
Create File System SourceFiles <- Array new: 2. Enter name for irnaqe file:
is at: 1 put: (FileStream π e d: Ί a. s 11 a s t ρ a re η t. s ο υ re e s' ι
Figure 1.14b
Sy31em Workspace I Srnalltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp. All rights reserved. Create File System again undo SourceFiles *• Array new: 2. copy • ^ s at: 1 put: (FileStream Enter η am cut i.ge file: paste ned: 'last last parent, sources'1!.
Figure 1.14c
26 Introduction to the Book and the System
The system now takes control to create the file. The cursor changes first to a slanted arrow with a star attached, meaning execution is taking place. It then changes to an hourglass shape, meaning "wait." If you make a snapshot prior to quitting, then you will be taken out of the Smalltalk-80 system once the snapshot file is created. Otherwise, the cursor shape changes back to the normal slanted arrow shape and you can continue working. In some of the Xerox systems, the screen turns to white while the snapshot file is being created. This is done to improve the speed with which the disk interactions are carried out.
When the prompter appears, you can choose to change the name of the file into which the image is copied. Simply edit the bottom text subview of the prompter before you choose the yellow button command accept (see Chapter 3 on how to use the text editor). The system will copy the existing changes file into a file whose name is the one you typed followed by a period and then the characters changes; the image file name is the name you typed followed by a period and then the characters im. You must respond to the prompter. If you move the cursor outside the prompter boundaries, the prompter will "flash" or "blink" to indicate that a response is required. If you have changed your mind and do not want to create a snapshot, then delete all the text from the prompter response area and choose the yellow button command accept. The prompter will disappear and you can continue using the system.
1.5 Summary of Terminology
button red button yellow button blue button button action press release click double click
Button on a pointing device, or function key on a keyboard, that is used to request some action. Used to select information. (Left button in all illustrations.) Used to get a menu for editing the contents of a view. (Middle button in all illustrations.) Used to get a menu for editing the view itself. (Right button in all illustrations.) The physical use of a button. Push and hold the button down. Remove finger from button, letting the button up. Press the button, then release it, without moving the cursor. Click two times in succession, without moving the cursor.
27 1.5 S u m m a r y of T e r m i n o l o g y
confirmer
A "binary-choice" kind of menu, that is, a menu with two items from which to choose.
control manager
A system object that maintains a list of screen views; it lets you point to a view and interact with either the view itself or with information inside the view.
cursor
A locator of information on the display screen, presented as a small graphical image, superimposed on the screen and controlled by a pointing device.
file
Refers to a sequence of characters on an external storage device, such as a disk.
changes file
Initially an empty file; when the user interacts with the Smalltalk-80 system, each action that involves evaluating an expression is stored in this file.
image file
A file that contains the compiled form of each method and the initial bitmap that appears on the screen when the system is installed.
sources file
A file that contains the source text for each method in the system.
menu
A list or collection of selectable items; choosing an item from a menu invokes some action.
message method
A request for an object to carry out one of its operations. A procedure describing how to perform one of an object's operations.
mouse
A pointing device that the user manipulates in order to move the cursor.
object
A component of the Smalltalk-80 system represented by some private memory and a set of operations.
prompter
A "fill-in-the-blank" kind of menu in which you must type your choice.
scroll bar
A menu associated with a screen view; you use a scroll bar to specify which part of the available information you want displayed in the view.
snapshot
A file in which you save the current state of your Smalltalk-80 system image.
subview system image
A view contained as a subpart of another view.
view
A set of compiled methods and global variables, and the initial display screen to be shown when the system is first installed. A rectangular area on the display screen in which to access information.
28 Introduction to the Book and the System
active view collapsed view standard system view
The view in which you are currently working. A standard system view that displays only its label part, but can be selected and expanded to show the entire view. A view that provides standard interface functions for manipulating itself, for example, for moving, framing, collapsing, and closing.
2 Basic User Interface Components
2.1 Display Screen Visual Cues Cursors Highlighting Flashing Screen Areas 2.2 Designating Rectangular Areas on the Display Screen 2.3 Menus Scroll Bars Confirmers Prompters 2.4 The System Menu 2.5 Standard System Views Standard Blue Button Menu 2.6 Summary of Terminology
30 Basic User Interface Components In the Smalltalk-80 programming environment, a bitmapped display screen is used to present to the user graphical and textual views of the information about objects. Menus and views are the primary ways in which objects are visually presented. A cursor is used to select items in menus or in parts of a view.
2.1 Display Screen Visual Cues
Cursors
A cursor takes on different shapes in order to provide visual feedback about where you are pointing and what system activities you are currently doing. Highlighting is used to indicate menu, view, and text selections. Flashing screen areas draw your attention to attempts to initiate inappropriate actions. There is only one active cursor and it is controlled by the pointing device. In the following table, each cursor is listed with its name, its visual form, and its typical use in the system. The cursor takes on different shapes when it is used in editors for text, pictorial images (Form Editor), and magnified images (Bit Editor); in controlling the views on the screen; and in interacting with the external file system. name normal
image
use
The cursor looks like this most of the time. The point of cursor selection is at the upper left corner, at the tip of the arrowhead. Wait. The system is executing some time-consuming expression. During this time, you cannot do anything else.
execute
origin
Γ
Indicates that you should designate the top left corner of a rectangular area by moving the cursor to where you want, and then pressing, but not releasing, the red button.
corner
J
Indicates that you should designate the bottom right corner of a rectangular area by keeping the red button depressed while you move the cursor to where you want the corner to be, then releasing the button.
31 2.1 Display Screen Visual Cues read
Wait. Information is being read from an external file.
write
Wait. Information is being written on an external file.
crossHair
In the Bit Editor, indicates the location of the bit at which editing will occur.
down (previous information)
In a scroll bar, indicates scrolling the text to see the preceding text.
up (next information)
In a scroll bar, indicates scrolling the text to see the succeeding text.
marker (jump)
In a scroll bar, indicates the proportional location to which you want to jump.
wait
Wait. The system is carrying out some file operation that is time consuming.
thumbs up
Answer yes in the confirmer.
thumbs down
Answer no in the confirmer.
The Form Editor prefers to let the cursor take on arbitrary shapes that depict the current painting tool. To do this, the cursor is made blank, and the editor itself provides an image of the painting tool at the location of the cursor. The confirmer uses the cursor in the shape of a hand with either thumb up or thumb down, depending on which item is selected. Some versions of the system include storage reclamation in the form of a compactor; when compaction is taking place, an animated image of a cartoon character appears. Class Cursor is defined in the Smalltalk-80 system as the representation of cursor forms. Cursor knows about several cursor forms that are predefined in the system and used in the interface. With the exception of the last two Cursors, the name of the cursor given in the preceding table is also the name of the unary message that should be sent to Cursor in order to gain access to the instance, for example, Cursor normal. Since a cursor is a kind of Form, it can be edited by sending it the message edit or bitEdit. See Chapter 7 "How to Make Pictures" to learn how to use the editors (the Form Editor and the Bit Editor) that you access in response to these messages. Sending the message show to an instance of class Cursor sets the form of the visible cursor to be that of the instance. For example, sending the object, Cursor normal, the message show, makes the visible cursor look like a slanted arrow (as explained in Chapter 6, sending such a message directly involves typing the expression Cursor
32 Basic User Interface Components normal show in a workspace, selecting it using the red button, then choosing the yellow button command do it. The expression Cursor normal returns an instance of class Cursor; all instances of Cursor respond to the message show.) You can create cursors, instances of class Cursor, and use them as visual cues in your applications systems.
Highlighting
In using the Smalltalk-80 system, you will select various views or parts of views. For example, you will often select a sequence of characters using the text editor. When you do so, the system will highlight the sequence to indicate which one will be affected by the next editing command. Similarly, when you press a button to obtain a menu to choose one of its items, the system will highlight an item to indicate the current selection; the current selection is the one you choose by releasing the button. And when you select any standard system view, the system will highlight its label (located just above the view's top left corner) to indicate that it is the active view. When you invoke a menu, the current selection is the item that you chose the last time you obtained this menu.
To highlight a selection, the system complements it. In complementing, the black bits on the screen are turned to white, and white bits to black. In particular, black text on a white background is turned to white text on a black background. All views except the single active one are "inactive." Selections in inactive views are generally not shown. Selections in menus that are textual lists are still shown, but their visual emphasis is "toned down" a little—the background of the selection is changed from black to a gray tone. As a design decision, standard system views allow for only one active view. Using the multitasking capabilities of the Smalltalk-80 system, you can create multiple simultaneous activities, including "active" views that operate in tandem with system views.
Figure 2.1 shows examples of highlighted text within a sequence of characters (in the active standard system view labeled System Workspace), several lists of items with highlighted selections (in the inactive standard system view labeled System Browser), an inactive standard system view (labeled Project), and an inactive standard system view labeled System Transcript. Menu items that appear in inactive standard system views are highlighted using a gray background.
33 2.1 Display Screen Visual Cues
Change Management and Crash recovery "Create a blank view for change recovery,'
Project I This project gives access to several e-arnples of Browser;
"Create a view for change recovery from a given file' L· C h a n g e Li s t V i e w open Ο π: (C h a n g e Li s t new recoverFile: (FileStrearn oldFileNarned: 'fileName')). "After a crash, crea.te a view to brows* changes sine* tne lest snapshot:'
S ν stem Browser 'JFiFilllnThsBIa nl· Oc Interface- Browser instance creation e · ample 1 Interface- •Inspectc FilllnTheBlankCont e · arnpleG Interface- •Debuggs FilllnTheBlankView Interface- File Mod Interface- Transcr instance liiiiii example 2 "Example waits for you to click red button somewhere on the screen, The view will show where you point, Terminate by choosing menu command accept or typing carriage return," FilllnTheBlank request: 'Type a. name for recalling a source Form," display At: Sensor wait But ton Figure 2.1
34 Basic User Interface Components
Flashing Screen Areas
A flashing area refers to an area of the display screen rapidly alternating its black and white bits so as to draw your attention to it. This is used in the programming interface to indicate that what you are trying to do is currently disallowed or not appropriate. Flashing will occur, for example, if you attempt to invoke a menu where no such menu is available, or if you do not complete a response to a confirmer or a prompter.
2.2 Designating Rectangular Areas on the Display Screen
Several interactions in the Smalltalk-80 system expect you to designate (to show location and size of) a rectangular area of the display screen. When this happens, the system will jog your memory by changing the cursor shape to look like the top left corner of a rectangle. A possible screen image is shown in Figure 2.2a.
Figure 2.2a After you have moved the cursor to where you want the top left corner of the rectangular area to be, press and hold down the red button. In response, the cursor will change shape again, this time to look like the bottom right corner of a rectangle. Where the corner first appears will delimit the minimum-sized rectangle for that particular kind of view. The cursor is shown on the screen in Figure 2.2b. While still holding down the red button, move the cursor around. You will see that, as the cursor moves, a flashing image of the rectangular area changes correspondingly on the screen. The area shown always maintains any minimum size that may have been assigned by the constraints of the view that will fill the area. When you are satisfied that the selected area is the size you want it to be, release the red button. A possible resulting workspace is shown in Figure 2.2c.
35 2.3 Menus
Figure 2.2b
A
Figure 2.2c
000
2.3 Menus
A menu on the display screen is similar to one in a restaurant: it shows you the available items from which to choose. An item in a menu represents a message. The item workspace in one of the menus you used in Chapter 1, for example, represents a message that creates a new view in which text can be created and edited. In the Smalltalk-80 interface, menus are displayed as lists of words or of phrases. Menus come in several varieties, including fixed and pop-up. Examples of fixed menus were shown in the view labeled System Browser in Figure 2.1.
36 Basic User Interface Components • To make a selection in a fixed menu, place the cursor over the desired item and press the red button; this will highlight the item. • When you release the button, the system will carry out the action corresponding to the highlighted item, leaving the selection highlighted until you select a new item. • To deselect the current selection without choosing another item, simply choose the same item again (that is, move the cursor over the item and click the red button). To allow best utilization of space on the display screen, many menus in the Smalltalk-80 system have been designed to be pop-up menus. Fixed menus are already on the screen; pop-up menus appear when you press the appropriate button. The menu displays itself directly beneath the cursor. To see a pop-up menu, move the cursor into the background area of the display screen, outside the boundaries of any view. Press and hold down the yellow button. A pop-up menu will appear. (If you tried the various examples in Chapter 1, you have already seen several pop-up menus.) In order to make a choice, continue to hold down the button, move the cursor around until the desired item is highlighted, and release the button. When you release the button, the menu will disappear. In order to make no choice, continue to hold down the button, move the cursor outside the menu area until no item is highlighted, and release the button. Another variety of menu is one that appears in response to some user action. This kind of menu remains on the screen until you either choose an item using the red button, or until you click with the red button at a location outside the menu area. One example is a confirmer. This is a menu with a noneditable text subview that describes a binary choice, and two items: yes and no. If you create a workspace, type some text, and then try to close the workspace, a confirmer will appear to verify that you want to delete unsaved information. Recall that this example was presented to you in Chapter 1. Another example is the menu that appears when you decide to stop your work session. As described in Chapter 1, when you choose to stop a work session, a menu appears from which you can choose to create a snapshot, quit immediately, or change your mind. A particular kind of fixed or pop-up menu is called a list menu. List menus appear as a sequence of lines, each one containing a menu item. For aesthetic purposes, and to help identify groups of items, lines of text in a list menu may be separated by a drawn line. Fixed list menus are used for choosing class names and messages in a system browser, for choosing class message pairs in a message-set browser or a debugger, and for choosing variable names in an inspector. (The differ-
37 2.3 Menus
ent browsers, debuggers, and inspectors, will be described in detail in subsequent sections.) List menus appear in standard system views in response to your pressing the yellow or blue button. If you press the yellow button while the cursor is in the background gray area, the list menu we refer to as the System Menu will appear (see Section 2.4). You can create different standard system views by selecting items from the System Menu. If a menu flashes when you try to make a selection, it has become locked. The system will lock a menu when you have not yet completed the activity associated with your current selection. This flashing is used as one of the ways to indicate that you have been editing text, but have not yet issued the command cancel or accept. (The use of a confirmer is another way the system indicates that text has not been saved.) The locked menu will become unlocked as soon as you properly complete the associated activity. Most of the subviews of the system browsers, which are the views for accessing class descriptions, fall into the category of lockable menus. Whenever the user interface directions say that you should choose an item from a pop-up menu, the directions will state which button to press (yellow or blue) and which command to choose. Selection in fixed menus is done using a red button.
Scroll Bars
A view on the screen may not be large enough to display all the information appropriate to that view. Additional user interface control is given to such views in order to assist you in exploring all the information. Especially in views of textual information, this control is provided in the form of a scroll bar. Assume you wish to examine a large document of information, and that you have created a view on the screen for this purpose. The view is likely to be too small to display all of the document. So a rectangular area known as a view for often called a window) is defined by mapping from the area allotted on the display screen to a corresponding-sized area of the document. The mapping determines how much document information can actually be displayed in the screen view. The purpose of a scroll bar is to change the area of the document that can be seen in the view. A scroll bar is a rectangular area, displayed adjacent to the left side of the view it controls. The scroll bar appears in the active view only when the cursor is actually inside the view. If you move the cursor outside the view (without pressing a button), the scroll bar will disappear. It will appear as soon as you move the cursor back inside the viewing area. Thus the scroll bar is a useful visual cue that the view will notice your typing or button pressing. Scroll bars appear only in those views for which scrolling is appropriate, typically in any view in which text can be edited or in list menus.
38 Basic User Interface Components
The length of the scroll bar area is meant to represent the length of the entire document that can be examined. Inside the area is another rectangular area filled with a light gray tone. The length of this gray area represents the height of the window onto the document (as illustrated in Figure 2.3). The gray area is located within the scroll bar at a point relative to the location of the window: if the gray area begins at the top of the scroll bar, then the window is at the beginning of the document. If the gray area fills the entire scroll bar, then you can assume that all of the document is currently displayed (see Figure 2.4). This is the document with text in it. This is the beginning of the document,
This is the part of the document that is displayed,
This is the part of the document that is displayed, This is the end.
Figure 2.3
Figure 2.4
window at the bottom of document
window at the top of document
window shows entire document
39 2.3 Menus
You can change which part of the document is displayed by moving the window through the document. This action is called scrolling. It is done in one of three ways. scroll next
1 scroll previous
1 jump
The line of text nearest the cursor is moved to the top of the view. Move the cursor into the scroll bar area, in the right one-third of the rectangle and outside of the gray area. The cursor shape becomes that of an up arrow. Click the red button. Scrolling occurs.
The line of text at the top of the view moves to become the line nearest to the cursor. Move the cursor into the scroll bar area, in the left one-third of the rectangle and outside of the gray area. The cursor shape becomes that of a down arrow. Click the red button. Scrolling occurs.
Displays a view of the document beginning with a location in the document relative to the gray area in the scroll bar. Move the cursor into the scroll bar area, in the middle onethird of the rectangle and outside of the gray area. The cursor shape becomes that of a right arrow. Press the red button and hold. The gray area moves to the cursor location and then tracks the cursor until the red button is released. The displayed document jumps to the appropriate location. While the red button remains pressed, a lighter gray image is left in the scroll bar area to indicate the previous position of the gray area.
In an earlier design of the scroll bar, jumping was done by moving the cursor into the gray area. The cursor shape changed to a small dot. While the red button was pressed, you moved the gray area to the desired location. This design was abandoned because users found it difficult, if not impossible, to grab the gray bar when it was very small. Another design that has been used in an application was to di-
40 Basic User Interface Components vide the scroll bar into three parts horizontally, rather than vertically. When the cursor was in the small top part, the resulting action was to scroll next; when the cursor was in the small bottom part, the resulting action was to scroll previous. As programming exercises, you might like to experiment in creating different types of scroll bars.
Π Practicing To start learning how to use the Smalltalk-80 system, try using the System Menu. Get the menu by first moving the cursor into the light gray background area, then pressing and holding down the yellow button. This will cause a pop-up menu to appear. As long as you keep the button down, you can move the cursor around in the menu, deciding between various selections. You don't actually choose the highlighted item until you release the button, so be sure you have selected the item you want before you release the button. If you decide you don't want to make any choice, simply move the cursor out of the menu area completely (so no item is highlighted) and release the button. The menu will disappear. Practice getting the System Menu and moving around in it. Become comfortable using the System Menu without making any selections, so that it becomes a habit to move the cursor outside the menu when you are undecided. Read the subsequent sections to find out what choosing each of the System Menu items will do. A confirmer is a "binary choice" menu. That is, a confirmer is a menu with two items in it, where each choice represents opposing points of view. A confirmer consists of three parts, the top part is a statement or question; the other two parts are possible opinions about the statement or answers to the question. An example is shown in Figure 2.5. It is a confirmer that appears when you choose the yellow button command close in a workspace, after you have typed some text without accepting it. Choose one of the answers, yes or no, by placing the cursor over the answer and clicking the red button.
Confirmers
T h i o ίο 5ΟΠΊΘ tQ • ΐ ^ ContQnts have riot been saved. Are you certain that you want to close? yes
Figure 2.5
000
^
no
41 2.4 The System Menu
A prompter is a "fill-in the blank" menu. That is, a prompter is a menu in which you must type your choice. It consists of two parts: the top part is a statement or question, and the bottom part is a workspace in which you type. Two kinds of prompters are available in the system, as shown in Figure 2.6. One has a label and acts like a standard system view, with both yellow and blue button menus accessible. This kind of prompter is called a scheduled prompter. The other kind of prompter is unscheduled. It preempts activity and requires you to give a response. You press the "carriage return" key to indicate that your answer is completed. To give no response, type only the "carriage return" key. Unscheduled views like this prompter do not have a title label.
Prompters
Type a. response Type the name of the file,
1
chapter 1, text
i
'•IS
Type a. n am Θ for recalling a. source Form. A
Figure 2.6
2.4 The System Menu
As noted earlier, the menu obtained by moving the cursor into the light gray background area and then pressing the yellow button is called the System Menu. It is shown in Figure 2.7. Each item or command in the System Menu is described briefly.
42 Basic User Interface Components
restore display e.-.it project project file list browser workspace system transcript s y s t e m w ο rks ρ a c e save quit
Figure 2.7
010 restore display
Redraws the display, getting rid of anything which is not known to the control manager. Often the display screen gets cluttered with the side effects of drawing or the results of erroneous actions. Whenever things look especially bad, you can redraw the views by choosing this command. Another effect of restoring the display is to reset the cursor to the slanted arrow (normal) cursor.
exit project
It is possible to create several different collections of views of information, each one called a project. Each project takes up an entire display screen for the presentation of its views. A project is accessed by creating a project view and then choosing the yellow button menu command enter. Once inside a project, it is possible to return to the project from which it was entered by choosing this command. At the topmost project, this command is equivalent to restore display. See Chapter 4 "How to Use Projects" for a more detailed description.
project
Creates a new project view. You are asked to designate a rectangular area in which the project view is to be displayed.
file list
Short files can be read, edited, updated, and evaluated, using a view that is created by choosing this command. You are asked to designate a rectangular area in which a file list view is to be displayed. See Chapter 22 "The File System" for a description of this view.
browser
A browser is a special view that allows you to access hierarchically-organized information. Choosing this command opens a system browser that allows you to traverse infor-
43 2.4 The System Menu mation about the Smalltalk-80 system itself. You are asked to designate a rectangular area in which the browser view is to be displayed. See Chapter 9 "Finding Out About System Classes" for a description of this view of system information.
workspace
Creates a blank area in which to edit text. You are asked to designate a rectangular area in which the workspace is to be displayed. See Chapter 3 "How to Use the Text Editor" for a description of how to use this view.
System Transcript
Most display screens in a Smalltalk-80 system have a special view known as a System Transcript. Because messages sent to the object Transcript affect this view, methods can contain expressions that print information in the System Transcript in order to create a form of user feedback. A view of the System Transcript is created by choosing this command. You are asked to designate a rectangular area in which the transcript view is to be displayed. See Section 3.4 "The System Transcript" for a description of this view.
system workspace
A special workspace is available that contains many useful message expressions that you can edit and evaluate, notably expressions about accessing files, querying the system, and recovering from a crash. You are asked to designate a rectangular area in which this special workspace is to be displayed.
save
Periodically you might decide that you have done a lot of work that you want to save. One way to save your work is to create a complete image of the system (see Section 1.4). A new system image is created in an external file whenever you choose this command.
quit
When you are done working, choose this command (see Section 1.4 "Stopping a Work Session").
Q Keep Practicing Several exercises are provided here so that you can practice with menus, scrolling, and creating workspaces. Exercise 1: In the System Menu, choose workspace (Figure 2.8a). Designate a rectangular area in order to specify the location and size of a workspace (an example workspace is shown in Figure 2.8b). Do this several times so that there are three or four workspaces on the screen, some overlapping others (as shown in Figure 2.8c). The last workspace that you created is the active one. Notice that the label of this workspace is highlighted and that a scroll bar appears at its left side.
44 Basic User Interface Components υ:::;:;:::::::;:;:·:::::;:::·:::·:::::·:::::::!:::·;·;
restore display exit project proiect file" list browser
::·::::::::::::::::ί::::::::::;:::::;:::::::::::::::; :;:;:;:;:;:;i;;f:;:;:;:>::::f:;:;:::::;:;:::;:;:;:-:
system transcr^jit s y s t e rn w ο rks ρ a. c e save quit ·ΐ!:!:!:;ΐ;:·:;:!ϋ!::;ϋ:;ϋ:!:;ϋ:·:;:!:;ϋϋ:::;::;;ϋ:;ϋ:;ϋ;::;!;:;:·:::!:;:;:·!·:ΐ:;ϋϋϋ:!:;ϋ:·!·:!:ϋ;:·ϋ;ϋ::;:;:ϋϋ::::::
•.::•:•·.'•:.::•:':::.•/••.'•:•:•:••.'•:•:'••.••:•:'•·.:•.••.':••.:•. : : ; : ; : ; : ; : ; : ; : ; : : : ; : ; : ; : : : ; : : : ) : : : ; : : : ; : : : ; : ; : : : ; : ; : •
• : • • . - • . ' • • . • • . ' • • . * - • . • •.·::·.:-.;ι.:ι.:·.:-.:-.:ι.:'.:·.:ι.:;:·.::·:-::::
: :
:
:
:
:
: ;
:
: :
: ::::: " ::::::· :ί::>:: ::;::·: : ;·::::: :': : :
Figure 2.8a
Figure 2.8b
Figure 2.8c
010
•
: : : : : : : : :
:
:
:
:
:
; : :
:
:
:
:
:
:
:
: : :
:
:
:
:
:
:
:
: : :
:
:
;
:
:
:
:
: : :
:
:
;
:
:
:
:
:
::::::::!:;::::·:•;:;:·:;•::;:::;:;·;:;;;:!:;•;:;:;:;:;:
Γ" 45 2.4 The System Menu
Move the cursor outside the active view and into the gray background area. Click the red button. Notice, as shown in Figure 2.8d, that the workspace is no longer active, in particular, that its label is no longer highlighted. We refer to this action as deselecting a view. Typically, however, you do not explicitly deselect a view. Rather, the deselection takes place automatically when you select another view.
Workspace Ιϋϋϋϋ Worf space]
Figure 2.8d
iilliiiliiil WorRspaLceΙιίΗϋΙϋΙϋΗϊΐΒΠΗΪΠϊΗΠΗιΗΜΜϋΗΗίΜΜΝΪ Workspace
100 Suppose no view is active (which would be true if you click the red button in the gray background area outside of all the views). Move the cursor into a workspace. Without your pressing a button, this workspace will become the active view. When all the views are inactive, whichever one you place the cursor into next becomes the active one. Place the cursor in one of the other workspaces and click the red button. We refer to this action as selecting a view. A view can be deselected as described, or as a result of a message sent by selecting a menu item, or as a result of evaluating an expression. You can deselect a view by moving the cursor outside it, into the gray area or into another view, and then clicking the red button. Actually, you can press the yellow or blue button as well, which, in addition to deselecting the active view and selecting a new view if the cursor is inside one, may cause a menu to appear.
Exercise 2: To practice scrolling, choose the command System Workspace from the System Menu, or, if you have a workspace labeled System Workspace already open, select it. The System Workspace should have a lot of text in it. Try scrolling using it. Learn how to control the positioning of the cursor by watching for the change in cursor shape. Make the workspace larger by choosing the command frame from the blue button menu. You will be asked to designate a rectangular area. Notice the change in the scroll bar.
46 Basic User Interface Components
Exercise 3: Make an existing or new workspace active. Type a lot of keys on the keyboard and notice that the characters are displayed in the workspace; do not worry about typing correctly or meaningfully. Notice that the scroll bar does not change while you are typing. The scroll bar only changes (is updated) when you make a new selection, or you move the cursor into the scroll bar area or out of the view boundaries and back in again. Do not worry about editing the text just now. Deferred update of the scroll bar can be changed so that the update occurs while you are typing. Once you acquire Smalltalk-80 programming expertise, you might try to make this change to text views.
Move the cursor outside the workspace without pressing a button. Type some keys. The characters do not show up in the workspace; they do not show up anywhere. Move the cursor back into the workspace and notice that the characters now appear. The cursor must be inside the active (text) view when you are typing keys on the keyboard in order to see the corresponding characters displayed immediately in the view. Select a different workspace. Again, type some keys on the keyboard. Press the yellow button and notice the menu that appears. Release the button without choosing any command. Select another workspace. Obtain the yellow button menu; notice that it contains the same items in both workspaces.
2.5 Standard System Views
There are a number of kinds of views that can appear on the display screen of the Smalltalk-80 system. Most of these are standard system views, meaning, among other things, that they are seen as rectangular areas with labels above the top left corner. They become active when you place the cursor inside their bounded area and click the red button. Each standard system view provides a general interface accessed through a pop-up menu. Standard system views can be moved, stretched, and removed from the screen; other abilities depend on the particular kind of view. Abilities shared by all views are presented in the blue button menu; abilities of a particular kind of view are presented in the yellow button menu. Access to the currently scheduled standard system views is maintained by a system component called the control manager. The references to views are stored in the control manager in a seemingly arbitrary order; ordering occurs as a by-product of the order in which the views are created and the order in which they become active. This ordering affects the way you can select views under one another.
47 2.5 Standard S y s t e m Views This control manager is referenced by the system variable ScheduledControllers. This name reflects the fact that the control manager consists of references to kinds of Controllers that provide interfaces to Views. The active view is always the first element of ScheduledControllers.
When you press the blue button while the cursor is inside a standard system view, the pop-up menu shown in Figure 2.9 appears. Each of these menu items represents a message to the view. They are
Standard Blue Button Menu
under rn ο ν Q frame collapse close
Figure 2.9
\
001 under
Since standard system views can overlap, this menu item is a request to give control to (to make active) the view located underneath the currently active view and underneath the cursor location. A view can be overlapping several views—the one that appears on top when you choose under depends on the ordering of the references in the control manager; under might have to be chosen several times in order to locate the desired view. Also, a view might be underneath the currently active one and not underneath the cursor, in which case it will not be selected.
move
The view disappears with only its label remaining, and the cursor changes to the shape of the origin cursor. Move the cursor around. The label of the view tracks the cursor. When you press the red button, the view reappears so that the label is at the last location to which you moved it.
When you move a view, space that is simply gray area appears in its place. The standard system does not try to keep a clean, refreshed display, since it assumes you can clean up by choosing the command restore display from the System Menu. Solutions to fix this problem of redisplaying hidden parts of overlapped views exist, but were not included in the standard Smalltalk-80 system. frame
The view disappears and the cursor changes to the shape of the origin cursor. You then designate a new rectangular area in which the view should reappear.
48 Basic User Interface Components Collapse
The view disappears with only its label remaining, and the origin cursor appears. Move the cursor around. The label of the view tracks the cursor. When you press red button, the label portion only of the view reappears on the screen at the last location to which you moved it. This considerably smaller area can be enlarged to show the full view by selecting it and choosing the blue button menu command frame.
Close
The view disappears. Unless you have a reference to it, that is, it is referenced by some other object, it can not be made to reappear.
If the task in the view is not complete (typically completion is indicated by choosing the yellow button command accept), an attempt to close the view results in another view. This is a confirmer. The cursor moves automatically into the confirmer's area, and the confirmer becomes the active view. The message in the confirmer is a warning that a task or information will be lost by closing the view. If the view has several subviews, a gray box is drawn around any information that will be lost. An example is that a part of a system browser was changed but not saved before the close command was chosen. The gray box surrounds the lower part of the browser, and a confirmer appears. Choose yes to indicate that close is really intended; choose no to continue using the original view. If you close a view, it is irrecoverably gone. You can only recover it if you have made a snapshot and start over using the saved image, or if you have stored a reference to it. You can think of other messages to the view itself to put in the blue button menu. In some of the Xerox Smalltalk-80 systems, the message edit is available. When you choose edit, you can move the borders of the subviews (either up and down for horizontal lines, or left and right for vertical lines) in order to modify the layout of subviews within the view.
Q More Practicing Select different workspaces. Try the various blue button commands such as under, move, and frame. Try the command collapse and then frame again. Collapsed views save space on the screen yet allow direct access to the task represented in the view—simply select the view and choose the blue button command frame. Try to close a workspace in which you have typed some characters. A confirmer view appears. Choose yes. The confirmer disappears and then the workspace disappears. Again try to close a workspace in which you have typed characters. Before doing so, choose the yellow button command accept. Now try to close the workspace. No confirmer appears; the workspace disappears. Because you issued the command accept, the system believes you have "saved" your work.
49 2.6 Summary of Terminology
2.6 — Summary of Terminology
Bit Editor
A set of operations used to modify pictorial images that are presented in a magnified format (8 times original size).
browser
A view that allows you to access hierarchically organized and indexable information.
confirmer
A "binary-choice" menu, that is, a menu with two items from which to choose.
cursor
An image on the display screen that is used to select information such as text, menu items, or parts of a view.
file list flashing area
A view that provides access to short files of text.
Form Editor menu fixed
A set of operations used to modify pictorial images.
Rapidly alternating the black and white bits of an area of the display screen (black to white, white to black). A list or collection of selectable items. A menu, typically associated with a view, that remains displayed on the screen as long as the view is displayed.
list
A menu appears on the screen as a sequence of lines, each containing an item; it can be of the fixed or pop-up variety.
locked
A menu that is in a state such that you are not allowed to change the current selection.
pop-up
A menu that appears when you press a button, and disappears when you release the button.
system
A pop-up list menu that is obtained by pressing the yellow button while the cursor is located over the gray background area.
project
A collection of views of information that takes up an entire display screen for the presentation of its views.
prompter
A "fill-in-the-blank" menu, in which you must type your choice.
system transcript
A workspace. Text in a transcript can be edited as in any workspace. In addition, text can be printed in a transcript as the result of expression evaluations.
system workspace
A workspace that contains many useful message expressions that you can edit and evaluate, notably expressions about accessing files, querying the system, and recovering from a crash.
3 How to Use the Text Editor
3.1 Text Selection Extending Text Selection Beyond the Visible Text Selecting Text with the Escape Key 3.2 Inserting Text 3.3 Issuing an Editing Command Moving and Copying Text Searching for Text Issuing Editing Commands Using Keys and the "Control" Key Inserting Delimiters About a Selection 3.4 The System Transcript 3.5 Summary of Terminology
52 How to Use the Text Editor
The same text editor is used everywhere in the Smalltalk-80 system views. Learning how to use the text editor involves learning how to: • make a text selection • issue an editing command using a menu or the keyboard Note that this is a text editor for a single paragraph of text, not for a large document. Paragraphs have extensive format and style knowledge; however, the generally-used text editor is a simple one that does not provide a menu-based interface for changing the format nor the style. More sophisticated document-creation systems can be created that provide function-key or menu-based access to these aspects of a paragraph.
3.1 Text Selection
Text is selected using the pointing device and the red button. Text editing can be carried out in those system views in which the information is textual. Examples are a workspace, a transcript, a project, a file list, and the parts of browsers that provide editing areas for Smalltalk-80 methods. Select a view that contains text, such as a workspace. A small caret (an inverted "v") appears near the point you selected in order to make the view active. If there is no text in the view, then the caret will appear in the top left corner. Figure 3.1a shows a workspace containing text. The caret appears at the end of the first sentence. Type some text. Move the cursor somewhere else in the view, either at one of the characters or between characters or at the end of the passage of text. Click the red button. The caret appears at the cursor location or at the gap just before the character. Notice that you are asked to point at a character or between characters, not under a character. Move the cursor to one end of the passage of text and press the red button (as shown in Figure 3.1b). Hold it down while moving the cursor to the other end of the passage (Figure 3.1c). The text that is traversed is highlighted. This activity is called draw through. It is not necessary to traverse intermediate characters en route to the destination (that is, when drawing through several lines). When the cursor reaches the other end of the passage, release the button (Figure 3.Id). The selected passage remains highlighted. The highlighted text is called the text
selection. Pointing to a place in the text and clicking the red button creates a zero-width selection. The method of clicking once between characters is the one to use if you want to insert text. The method of drawing through a passage of text is the one to use if you want to replace, copy, delete, or change the font or emphasis (bold or italic face) of the text.
53 3.1 Text Selection
ίοϋο
This is a workspace t h a t Γ ο η t a i η • s ο rn e t e • t
This is a. workspace that *o η t a i η s s ο rn e t e χ t,
The t e >: t ο a n be e rn ρ h a size d in bold, italic, underlined, or m i χ t u re s s υ c h a s bold and under Mined The text can be in different fonts, emphasised in bold, italics, or underlined. The text can be in different fonts, emphasized in bold, italics, or underlined.
The t e χ ΐ c a π be emρha s i ζed in bold, it-ilk, underlined, or mixture; such as bold and underlilned The text can be in different fonts, emphasised in bold, italics, or underlined, The text can be in different fonts, emphasized in l)old, ;'ta Ii.;•s, οr underlined,
100 Figure 3.1b
Figure 3.1a
Mi
100
The t e >• t c a n b e e rn ρ h a s i ζ e d in bold, it a M.;, underlined, or rn i ••· t u re." :• u c h a s bold and underlilned. The text can be in different fonts, emphasize':! in bold, italics, or underlined. The text can be in different fonts, emphasized in hold, italics, or underlined.
000
The text can be emphasized ii in bold, italic, underlined, or ii mixtures such as bold and ii underlilned. \i The text can be in | different fonts, |i emphasized in bold, |j italics, or underlined. !; The text caii be in different ii fonts, emphasized in bold, ij italics, or underlined, ii
Figure 3.Id
Figure 3.1c
Clicking the button twice with the cursor in the same location selects different passages, depending on the cursor location.
To select
Double click
a whole word
Within a word, or just before or just after the word if the word is not just inside a delimiter (as demonstrated in Figure 3.2a, first click, and Figure 3.2b, second click).
54 How to Use the Text Editor
I 1
I 100 000
1
This is a workspace t h a t c o n t a i n ; s o m e i e ·:ΐ.
ii ii
The te
ii ii ii i
The text can be in different font·;., emphasized in bold, italics, iM underlined.
ii i ii ii
The· text can be in different fonts, emphasized in bold, itoiicj, or underlined.
ii ii ϋ
The
a delimited text
underlined,
or
a ; bold a n d
underlilned.
100 000
The text can be in different font·;., emphasized in bold, it a lies, or underlined.
The tj?;.;t can be in different fontj., emphasued in ftold, :'tο!ics, οr underlined.
Just after the left member of a pair of delimiters or just before the right member (the delimiters themselves are not selected); recognized delimiters are parentheses, square brackets, angle brackets, braces ("curly brackets"), single quotes, and double quotes (see Figures 3.3a and 3.4a, first clicks, and Figures 3.3b and 3.4b, second clicks).
This is a w o r k s p a c e t h a t c o n t a i n ; some t e c t delimited
Τ hi 5 ι; a workspace that contains some text delimited b> ιparentheses) [square brackets]
Figure 3.3a
italic,
m i :•: t υ r e s s u c h
Figure 3.2b
Figure 3.2a
100 000
t e •• t c a n b e e rn ρ hi a ; i ; e d
in b o l d ,
angle brackets:· 'single quote' "double quote"
100
oon
Figure 3.3b
55 3.1 Text Selection
This is a. workspace that contains some text delimited by...
s is a workspace that contain; some text delimited by...
(parentheses) [square brackets]
100 000 Figure 3.4a
i 1
Figure 3.5a
"double quote"
Figure 3.4b At the beginning or the end of everything in the view (as demonstrated in Figure 3.5a, first click, and Figure 3.5b, second click, and Figure 3.5c, scrolling to see the rest of the text).
all text in the view
100 000
'jingle quote'
This is a w o r k s p a c e t h a t C o n t a i n s some t e x t delimited
ii i;
by...
ii
(parentheses)
ii
[square brackets]
ii
;i
'single quote'
;i
"double quote"
ii
:
•00 : 0001 Figure 3.5b
56 How to Use the Text Editor
11Ε
I Figure 3.5c
III
single quote' double, quote" Thir t e · t c ϋ η bs e m ρ h.? ;.: Ί e d η bold, i'olici, underlined, or ni · t u r e i ;uch β; bold and jnderlined . ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ J
mm
a line of text
(If the line is delimited by carriage returns) at the beginning of a line (just after a carriage return), or at the end of a line (just before a carriage return).
Double clicking provides a faster way to make a text selection. Because double clicking will always select the designated text, it makes it possible to select text that is not visible on the screen.
Extending Text Selection Beyond the Visible Text
Suppose you wish to select text that is not visible on the screen, but that the text is not delimited in such a way that double clicking will support selection. Try the following technique. Move the cursor to either end of the passage of text that you want to select. Press the red button. Hold the red button down while moving the cursor to the other end of the passage. So far, this is the usual way to select visible text. But the other end of the passage is not visible. You have to move the cursor outside the boundaries of the text view (either above or below the view). As long as you hold down the red button, the text in the view will be scrolled (to the previous text or to the next text), and the text that becomes visible will be selected. Keep holding down the red button until you see the end of the passage. Don't worry about scrolling past the end, because you can always move the cursor back into the view. When you move the cursor back into the view, the scrolling stops. You can then position the cursor at the desired end of the passage and release the red button. The distance that you move the cursor outside the view affects the speed at which the text scrolling takes place. The further outside the view you move the cursor, the faster the scrolling.
57 3.3 Issuing an Editing Command
Selecting Text with the Escape Key
The "escape" key on the keyboard can be used to select text that was typed since the last mouse click. Simply press the "escape" key when you have finished typing. The characters you just typed will be highlighted. This is especially useful if, after typing in some text, you wish to make it the current text selection so you can copy the text to another place, or cut it, and so on. The purpose of invoking this selection command from the keyboard rather than from a menu is to support the fast typist who wishes to select a passage of text that was just typed in order to issue a cut, a font, or an emphasis change command, which may also be invoked from the keyboard. Perhaps you prefer to have an item in the text editor yellow button menu that selects the most recently typed characters; changing the menu is an exercise you can try once you know enough about the Smalltalk-80 system.
3.2 Inserting Text
Pressing a key on the keyboard always replaces the current selection by the typed character and automatically selects the gap following that character. If nothing is selected, the "zero-length selection" at the caret is replaced. To replace a passage of text, first select it and then type the replacement. The first keystroke deletes the original text. To insert between characters, select the gap between those characters and then type the insertion. Essentially, you are replacing nothing with something. The destructive backspace function always deletes the character preceding the selection, even if that character was there before the selection was made.
3.3 Issuing an Editing Command
When you issue a text editing command, you are sending a message to the text about the current selection. Selection always precedes commands. Every command is executed immediately when you issue it. No confirmation is required. Commonly-used editing commands are found in the yellow button menu. A brief description of each follows. again
This command attempts to repeat the last replace, copy, or cut edits you do.
58 How to Use the Text Editor
undo
copy cut paste
010 Figure 3.6a
The main purpose of undo is to reverse the effects of the last issued command. For example, paste in the last text cut out; cut out the last text pasted in; delete the last text inserted; or, if a text selection was replaced, paste it back. (Issuing two undo commands in sequence should leave you in the state you were in prior to the first undo.) Place a copy of the current text selection into a buffer. Delete the current text selection; save the text in a buffer. This command is illustrated in Figures 3.6a and 3.6b. Text is remembered in a buffer. Replace the current text selection with the remembered text. Assuming the text remembered is the text cut in Figure 3.6a, then the next sequence of figures illustrates the use of the paste command. Select the destination location (Figure 3.7a), select the command paste (Figure 3.7b), and then the inserted text becomes the selection (Figure 3.7c).
000 Figure 3.6b
Suppose you just selected some text (text A, such as demonstrat as shown in Figure 3.8a) and replaced it with other text (text B, such as illustrat as shown in Figure 3.8b). The command again will find text occurring after the caret that is just like text A and will replace it with text Β (as shown in Figures 3.8c and 3.8d on page 60). By holding down the "shift" key on the keyboard while selecting again, the replacements will be done as many times as is possible.
59 3.3 Issuing an Editing Command
I
100 i UUUl: Figure 3.7a
This is a illustration of the
Wlor
-
1;
i
1
i 1
This is a illustration of the text editor,
A
|l υιυ
1 again 1
i ji
j:
™ i print itl accept! IcancelJ
!| i !:
Figure 3.7b
Figure 3.7c
Suppose you just selected some text A and cut it out. The command again will find text occurring after the caret that is just like text A and will select it. You can then decide to cut it. Similarly, if you copy some text A, the command again will find text occurring after the caret that is just like text A and will select it (thus providing a text search capability in the editor). The again command is shared across views so that you can move into several views in order to do the same replacement in each.
60 How to Use the Text Editor
This is a illustration of the t e x t editor, This is \ j m e te used to demonstrate how to m ο ν e a n d h ο w t ο c ο ρ y t e ->•• t using the t e x t editor.
This is a g ^ Q m O ^ i u n of the text editor! This is strne text used to demonstrate how to move and how to copy text using the text editor.
000
000 Figure 3.8b
Figure 3.8a
I
This is a illustrator» of the text editor. This is some text used to demonstrate how to move and how to copy text using the text editor.
010 Figure 3.8c
Thii is a illustration of the text editor. This is some text jj used to Q ^ ^ ^ ^ Q
how
to
move and how to copy text using the text editor.
i
\ ji
000 Figure 3.8d
From the menu description, you can see that there is a "buffer" of information into which text that is typed, cut, or copied is stored. The contents of the buffer changes whenever you type new text, or you issue the cut or copy commands. It is possible to take information from one view and paste it to another view because this buffer is shared across views. Some people refer to this buffer as the scrap. The text editor in the standard system does not provide a way to view the information in the buffer; you can treat viewing the buffer as a possible exercise.
Moving and Copying Text
Some common editing commands such as "move text from here to there" and "copy text from here to there" cannot be issued by a single menu command because they require two parameters: the source selection and the destination selection. They may even involve more than
61 3.3 Issuing an Editing Command one view. A "move" is done by cut and paste. First, you select the source text and choose cut. The cut command deletes the selected text but leaves it in the hidden buffer where it can be retrieved by paste. Then you select the destination and choose the paste command to complete the move. This process was illustrated in Figures 3.6a and 3.6b. The destination can be in a different view than the source. A copy move is done by copy and paste, which is completely analogous to cut and paste, but does not delete the original text.
Searching for Text
Issuing Editing Commands Using Keys and the "Control" Key
There is no command for "searching for a sequence of characters." A search can be done as follows. Type the sequence of characters you wish to find, then select it and choose the cut command. Now choose the again command. If the sequence appears anywhere after the current selection (after the caret), it will become the text selection. If one instance of the text you want to find is already visible, select it, and choose the copy command. Then choose the again command. Various text editing commands can be issued by pressing the "control" key simultaneously with another key from the keyboard. When the "control" key is combined with a number, it means change the font of the current text selection. Conditional statements in the Smalltalk-80 language consist of the keywords ifTrue: and if False:. Since these are frequently needed, "control" combined with "t" or "f" effectively types the keyword ifTrue: or if False:, respectively. A summary of the special editing keys is shown next. The symbol Ctrl denotes the "control" key on the keyboard. type keys
action
Ctrl 0
Change the font of the text selection. The system default is sans-serif 12-point font. Changing a text selection to bold, italic, or underline is considered a change in font and is done by selecting the appropriate font number. The numbers depend on the current style being used. Change the font of the text selection. The system default is sans-serif 10-point font. Change the font of the text selection. The system default is sans-serif 10-point font, bold. Change the font of the text selection. The system default is sans-serif 10-point font, italic. Change the font of the text selection. The system default is serif 12-point font. Change the font of the text selection. The system default is serif 12-point font, bold.
Ctrl 1 Ctrl 2 Ctrl 3 Ctrl 4 Ctrl 5
62 How to Use the Text Editor Ctrl 6 Ctrl 7 Ctrl 8 Ctrl 9 ctrlt ctrlf Ctrl w
"delete" "backspace" Ctrl Ctrl b Ctrl c
Ctrl shift Ctrl shift b Ctrl shift c
Change the font of the text selection. The system default is serif 12-point font, italic. Change the font of the text selection. The system default is serif 10-point font. Change the font of the text selection. The system default is serif 10-point font, bold. Change the font of the text selection. The system default is serif 10-point font, italic. Insert the text ifTrue:. Insert the text if False:. cut the text selection and the word preceding the caret (typically used while typing and while there is no text selection simply to delete the last word typed). cut the current text selection, cut the text selection and the character before the selection. Underline the selected text. Make the selected text boldfaced. This is the system interrupt and should not be typed while text editing unless a process interrupt is desired (for details on such user interrupts, see Chapter 20). Remove any underline from the selected text. Make the selected text not boldfaced. This is a special system interrupt, used when the system seems dead and everything else fails (see Section 20.4).
Note that Ctrl w and "backspace" do a cut of the current text selection and of the word or character preceding the text selection. The undo command is supposed to be able to reverse the effects of a cut by pasting the saved information. However, in using Ctrl w or "backspace," two cut actions are really taken and only the last, the word or character deleted, is remembered. Therefore, undo will only paste the deleted word or character. All fonts are instances of class StrikeFont and are stored as an array in an instance of class TextStyle. The system default is accessible by sending TextStyle the message default. The message fontAt: can be sent to a TextStyle to access the fonts. The default TextStyle has 24 fonts. Fonts are indexed from 1 to 24, where the first 9 are the ones listed earlier; the one numbered 0 is actually font 10. Fonts are stored in triples—base, bold, and italic. The system includes fonts 10, 11, and 12—sans-serif 12 point fonts 13, 14, and 15—serif 10 point underlined
63 3.3 Issuing an Editing Command fonts 16, 17, and 18—serif 12 point underlined fonts 19, 20, and 21—sans-serif 10 point underlined fonts 22, 23, and 24—sans-serif 12 point underlined Suppose you want typing the "control" numbers to change the text font to a sansserif 10 point underlined, rather than a serif 12 point. You can change the affect of the text editor keyboard controls by evaluating the following expressions. TextStyle default fontAt: 4 put: (TextStyle default fontAt: 19) TextStyle default fontAt: 5 put: (TextStyle default fontAt: 20) TextStyle default fontAt: 6 put: (TextStyle default fontAt: 21)
Now when you type Ctrl 4 or Ctrl 5 or Ctrl 6, sans-serif 10 point fonts, underlined, will display. Typically you should also store the fonts you replace so that you can get them back again; either create a global variable or copy the TextStyle.
Inserting Delimiters About a Selection
Make a text selection (including a zero-width selection), then type one of the following control combinations in order to insert delimiters about the text. The control combinations are toggles, that is, if the selected text is already surrounded by the indicated delimiter, then the command removes it. type keys
insert delimiters
Ctrl Ctrl Ctrl Ctrl Ctrl
[and] (and) < and > " and " ' and '
[ ( < " '
An example of first delimiting some text using double quotes, and then removing the delimiters, is shown in the next sequence of figures. Text is selected in Figure 3.9a; in Figure 3.9b, the user types Ctrl " to delimit the selected words. The text selection is the sequence of delimited characters, as shown in Figure 3.9c; in Figure 3.9d, the user types Ctrl " again to remove the delimiters.
64 How to Use the Text Editor
1
1
Ι:;ί;:;:;:|:|:;:Ι:;:=:::^::;ί:::^:;Ι;Ι;:^:::^::;:::;:;:;!;:^:^:^:;:;:;:|:;::::|;::·:;:;; HMtMMHMMMM:::^::::E:::i:i:E::::::^:::::::::i::::::i:::::::::i:::::U::::i;
This is some text used to illustrate how to move and
: jl
how to 3 ^ f l 0 3 J ijjirig the
;
This is some text used to illustrate how to move and how to "copy tex^' using the text editor. This is a illustration of the text editor,
text editor, This i*a j; illustration of the text editor, I;
000
|i j| !i f. ii
000
Figure 3.9a
Figure 3.9b
I
This is some text used to illustrate how to move and how to " ^ ^ ^ ^ ^ ^ ^ " using the text editor. This is a illustration of the text editor,
i| r ij i; |
This is some text used to illustrate how to move and how to M M — « n using the text editor, This is a illustration of the text editor
1
000 Figure 3.9c
Figure 3.9d Clearly these kinds of commands could be placed on the pop-up menu as well, especially if you find it cumbersome to move from the mouse to the keyboard. There is a tradeoff, however, in the size of the menu. Cascaded menus, where selecting an item invokes a related menu, could be used. For example, the main text editor yellow button menu might include the item delimiters. Choosing this command would invoke a new menu whose items were each of the possible delimiters. The first menu could be left on the screen or not; leaving the first on the screen allows the user to change his or her mind by returning to it to select another item, rather than by aborting all action.
65 3.5 Summary of Terminology
3.4 The System Transcript
A "transcript" is a special kind of workspace known as a text collector. It is basically the same as a workspace in that you can use the text editor in it. In addition, it is possible to write and evaluate expressions in which messages to store characters are sent to a text collector. There is one special text collector that we refer to as the System Transcript. It typically appears at the top left corner of an initial Smalltalk-80 display. It is a standard system view, so it can be moved, framed, collapsed, and closed. If it is open on the screen, you will sometimes see text appear, informing you of some system event. You can use the System Transcript in the Smalltalk-80 methods that you write, sending the System Transcript messages to store descriptions of objects you create. For example, type, select, and evaluate the expression Transcript show: 'some text'; cr
For information on how to send messages by evaluating a typed expression, see Chapter 6. The System Transcript for the current project is referred to by the system global variable Transcript. The system transcript is primarily used as the place where comments to the user appear as a form of feedback when other visual feedback techniques are not available. For example, if the system scheduling mechanism fails, a message stating the problem and what to do about it is displayed in the System Transcript. When users are debugging methods and it is desirable to print periodic messages indicating the state of evaluation (rather than to interrupt execution), the System Transcript is a useful place in which to display the messages. When categories of classes are filed out or classes are recompiled, the name of each class appears in the transcript so you can tell what kind of progress is being made. If you do not already have a System Transcript on your display screen, you can obtain one by choosing the System Menu command system transcript.
3.5 Summary of Terminology
text collector
A workspace; the System Transcript is a kind of text collector. Whereas most workspaces are used for editing text directly, text collectors are primarily used for displaying information determined in print messages included in class methods.
66 How to Use the Text Editor text editor
A set of operations for creating and modifying a paragraph of characters.
caret
A symbol used to denote a text selection that contains no characters.
draw through
The activity of selecting a passage of text by pointing to one end of the passage, pressing the red button, and then moving to the other end of the passage before releasing the red button.
text selection
The sequence of characters of a paragraph that is currently highlighted.
How to Use Projects
68 How to Use Projects
Projects support your ability to manage several programming tasks at a time, without getting your work space too cluttered. You use projects the way you might use several desks in an office or several offices in a building—that is, as spaces in which to manage related information or activities. You might, for example, be working on two applications programs at one time. So you might have two projects, the top one and another; each application is developed in a different project so that you can create workspaces with information related to just the one project. Each project maintains information about the changes you make to class definitions and methods while you are working in its views. Thus you can use projects to keep separate records of the methods you develop for each application. Or, you might use projects in order to keep programming tasks separate from access to mundane daily work (letter writing, receiving and sending mail, retrieving an address from a database). Any classes created in one project are immediately available to all projects in the system. The global name space for variables is also shared across all projects. Thus if you create a variable in one project and change it in a second project, it will be changed as well in the first project. The primary support provided by projects is 1. maintenance of separate lists of changes to classes, and 2. visual layout of a set of views. The separate list of changes is a useful way to distinguish the changes to the shared classes that were needed to support the application in an individual project. (For information about how the system maintains references to the changes you make, see Chapter 23.) To practice creating and using projects, try the following sequence of actions. Choose the System Menu command project (Figure 4.1) and create the project view (Figure 4.2). You can type characters in the project view that describe the project; this is a way of documenting the purpose of the project. In the project view, select the yellow button command enter. The yellow button menu is shown in Figure 4.3. The result of choosing the command enter is shown in Figure 4.4. The display screen is now blank—no views are displayed. No activity has yet occurred in this project. Choose the System Menu command workspace and the System Menu command system transcript. The two views are shown in Figure 4.5. The views in the current project are not immediately accessible from other projects. Now choose the System Menu command exit project as shown in Figure 4.6.
69 How
Workspace
Workspace
restore display exit p r o j e c t SHBHBi file list b ro w s e r workspace system transcript s y s t e rn w ο rks ρ a c e
Figure 4.1
quit
Oio Workspace
Workspace
Figure 4.2
roo
to Use
Projects
70 How to Use
Projects
W ο rl· s ρ 3 c e 1
Wort spec el
lilllBl
1 again 1
iilillllii!gl^^-fc !!;|!:|:!:!!||!! ^ ^ ^ ^ 9
I copy l|i|i|| | CUt m£
^•••••••••\-\- _ _ _ _ _
!i|; I !i;i I ΗΓ: 1
Figure 4.3
Figure 4.4
οίοι
i 1
A
iirnin
accept! [cancel | EMM
L —
71 How to Use Projects
Figure 4.5
restore display
Workspace
project file l i s t browser workspace s y s t e m t re. η s c rip t s y s t e m w ο rks ρ a c 9 quit System Transcript|j;!;j;j;jji|i;j;:i:iU!j:;j
Figure 4.6
Ion
72 How to Use Projects
The display screen clears and the first collection of views reappears, including the project view (Figure 4.7). You can now do your work in this (top) project. Or you can re-enter the other project as you did before. Try re-entering, then return to the top project. Select the project view and then choose the blue button command close (Figure 4.7). Since there are views open in the project you are trying to close, a confirmer appears to warn you that you might be irreversibly destroying information (Figure 4.8). If it is okay, choose yes. The project view disappears and, with it, your access to the project's views and changes, if any.
Workspace
Wor^spacel
A
Figure 4.7
GDI
Γ under" | move frame |c oil a p :• e
73 How to Use Projects
i j Workspace|§|ΐ£
Worksp.: ,ce iiiniiiijiiiii
tamm
iii&i; Contents have not been saved. Are you 1 ;;;;;;;; certain that ; •'ou want to close'; ί/ίΠ"ί=ί:
Figure 4.8
ι''
6 5
no
1001 This particular implementation of projects creates a hierarchical organization, where the path to projects is through a view that exists in the "parent" project; each parent can have several "children" projects. The analogy is to workrooms whereby each room has several doors into other workrooms. For this reason, some people call project views "doors." An alternative design is to create a project browser that can be opened in any project by choosing an appropriate command from the System Menu. A project could be named, described, and accessed by choosing items in a project browser, in a way analogous to the way classes are named and described in a system browser. Creating a project browser is an exercise you might try to do when you are proficient in Smalltalk-80 programming. It is given as an example in Section 15.2.
Γ
Fundamentals of the Smalltalk-80 Language
5.1 Objects, Messages, and Methods Classes, Instances, and Subclasses Advantages of Object-Oriented Programming 5.2 Expression Syntax Class Descriptions Method Determination, self and super 5.3 System Components The System Class Hierarchy 5.4 Overview of the Programming Process 5.5 Summary of Terminology: General Concepts 5.6 Summary of Terminology: Syntax
76 Fundamentals of the Smalltalk-80 Language
The particular kinds of user interface components provided in the Smalltalk-80 system are designed to give you access to the elements of the Smalltalk-80 language. To understand the descriptions for evaluating expressions and for finding information in the system, you need an introduction to the concepts of object-oriented programming and the syntax for expressions in the Smalltalk-80 language, and you need an overview of the programming process. Subsequent sections suggest various expressions to try and describe the system components that support program development. You should turn to the companion book, Smalltalk-80: The Language and its Implementation by Adele Goldberg and David Robson, for a more thorough presentation of the programming language.
5.1 Objects, Messages, and Methods
The Smalltalk-80 language is based on a uniform use of objects and messages. An object is a uniform representation of information that is an abstraction of the capabilities of a computer. The two capabilities of a computer that are of interest in the language are the capability to store information and the capability to manipulate information. An object has the capability to store information. We say that an object has "private memory." An object also has the capability to manipulate its stored information or to carry out some activity. These are called the operations of an object. The set of operations is referred to as the object's message interface or message protocol. An object carries out one of its operations when an object sends it a message to do so. Each object knows the messages it can understand; associated with each such message is a procedure or method that describes how the object should answer the message. A crucial property of an object is that its private memory can only be manipulated by the operations in the object's interface. Computing is viewed as an intrinsic capability of objects that can be uniformly invoked by sending messages. Linking these concepts to ones more familiar to you, an object is like a computer consisting of data and procedures that operate on that data. An operation is invoked by calling on some procedure. Sending a message is the Smalltalk way to invoke a procedure; Smalltalk is a simulation of many computers communicating with one another. Objects and messages encourage modular design. The implementation of one object cannot depend on the internal details of other objects, only on how they respond to messages. In the Smalltalk-80 system, objects and messages are used to implement the entire programming environment. Objects are used to represent numbers, lists, text strings,
77 5.1 Objects, Messages, and Methods dictionaries, spatial locations, areas, text editors, processes, compilers, debuggers, and all other system components. Once objects and messages are understood, the entire system is accessible. The messages an object understands depend on what the object represents. Objects representing numbers understand messages that request arithmetic functions to be computed and their results returned. Objects representing lists and dictionaries understand messages requesting that information be stored or retrieved (in the form of other objects, naturally). Objects representing spatial locations and areas understand messages inquiring about their relation to other locations and areas. In many respects, you can think about real-world situations and identify the parts or components that play a role in these situations. These are the objects. These objects act out their roles by communicating with the other objects; that communication takes the form of a language of words—commands or informational data. These are the messages that make up the interface to the objects. A basic problem in designing Smalltalk programs is determining which kinds of objects should be described and what message names provide a useful language of interaction among these objects. In Smalltalk, the choice of message names is arbitrary, although there is a concrete syntax that must be followed. Appropriate choice of objects depends, of course, on the purposes to which the application will be put and the granularity of information to be manipulated. For example, if a simulation of an amusement park is to be created for the purpose of collecting data on queues at the various rides, then it would be useful to describe objects representing the rides, the waiting lines, workers who control the rides, and the people visiting the park. If the purpose of the simulation does not include monitoring the consumption of food in the park, then objects representing these consumable resources are not required. If the amount of money exchanged in the park is not to be monitored, then details about the cost of rides do not have to be represented.
Classes, Instances, and Subclasses
There are many objects in the Smalltalk-80 system. Objects that respond to the same messages in the same way are grouped together. When they are grouped together, their private memory is represented in the same way and their methods refer to their data with the same set of names. A group of objects related in this way is called a class. Objects in a group are called instances of the class. Programming in the Smalltalk-80 language consists of creating new classes, creating instances of classes, and specifying a sequence of message exchanges among all of these objects. Every object in the Smalltalk-80 system is an instance of a class. All instances of one particular class represent the same kind of system
78 Fundamentals of the Smalltalk-80 Language
component. Classes have names that describe the kind of component their instances represent. Instances of a class named Point represent spatial locations. Instances of a class named Rectangle represent rectangular areas. Instances of a class named Process represent independent processes. Refining existing class descriptions is a powerful way in which to approach Smalltalk-80 programming. Such refinement is supported by the ability to create a subclass of an existing class. A subclass describes a group of objects that inherit information from an already existing description. A subclass can add new functionality or private memory, and modify or prohibit existing functionality. Consider the amusement park example. Suppose we wish to create a simulation of this park. The first task is to determine the objects involved in the park. What do you think of when considering an amusement park? There is a merry-go-round, cotton candy, ferris wheels and roller coasters, tickets to buy, souvenirs to buy, a fun house, games, side shows (animals, strange people), a train ride, ice cream booth, cafeteria, sit-down restaurant, animal rides, lines of people waiting to get on a ride or to get a ticket, someone selling balloons, and so on. Oh yes, there are crying kids and crying parents, dizziness, stomach aches, and sunburn. Focusing our attention on the kinds of places, rather than the people or animals, we can organize the parts of an amusement park into rides, game booths, and places to buy things. One organization might divide the parts into places where you buy things and places where you do not buy things. Places where you buy things include rides, food vendors, and nonfood vendors. To create a Smalltalk-80 simulation, classes must be described for each of these kinds of objects. For example, we might create the class Ride; instances of Ride may be ferrisWheel or merryGoRound. Each Ride has a waiting line of some kind made up of customers waiting for service. This means that the private memory of each kind of Ride includes a reference to a waiting line. This line must be an instance of a class that describes the appropriate kind of data structure that can reference an ordered sequence of customers. Since everything is an object, and each object is an instance of a class, then a customer must be an instance of a class, perhaps of class ParkVisitor. At some time, a worker assigned to the ride announces "next, please" to the line; the next customer waiting is given service. At various times, customers arrive and enter the line, or they get tired of waiting and leave. The customers in the waiting line can be different kinds of objects. However, they all must be able to carry out the behavior appropriate to waiting in line and getting out of the line. So customers might be instances of ParkVisitor or they might be instances of a special kind of visitor, say an ElderlyParkVisitor, who gets preferential treatment at
79 5.1 Objects, Messages, and Methods the park. ElderlyParkVisitor could be created as a subclass of ParkVisitor so that all of the capabilities given a ParkVisitor are inherited by ElderlyParkVisitor as well. In addition, ElderlyParkVisitor might act differently—always entering a waiting line at the front instead of the rear. To create the Smalltalk-80 simulation, we will have to decide what messages the ParkVisitor, and thereby ElderlyParkVisitor, will understand —perhaps goToNextRide and buyTicket
Advantages of Object-Orien ted Programming
Programming in the Smalltalk-80 language consists of identifying jects, classifying them according to similarities and differences, and signing a language of interaction among these objects. These important organizing skills and communication skills that can taught using this form of computer programming. What are the advantages of this form of programming?
obdeare be
1. The information known privately to an object is protected—this information can only be accessed directly by the methods of the object. This means that the structure of an object (the representation of the information of an object) can be changed without affecting interactions with instances of other classes. This ensures that there is a structure or discipline by which objects interact and that a user can make changes or additions to very complex systems without getting caught in a maze of interdependencies. 2. The user accesses existing objects as well as creates new ones or modifies existing ones. Modification is done by adding a new message and its method to a class description, or by adding new data slots to the private memory of all the objects in a class. This means that the Smalltalk-80 language provides a simple and expressive model for the relationship among parts and wholes so that the process of building a system can draw on one's intuitive ability to synthesize and analyze. 3. The Smalltalk-80 system is built on the model of communicating objects. Large applications are viewed in the same way as the fundamental units from which the system is built. The interaction between the most primitive objects is viewed in the same way as the highest-level interaction between the computer and the user. 4. Objects support modularity. The complexity of the system is reduced by a minimization of interdependencies of system parts.
80
Fundamentals of the Smalltalk-80 Language Complexity is further reduced by grouping together similar parts, where this grouping is achieved through classes. Classes are also the chief mechanism for extension in the system. And subclasses support the ability to factor the system in order to avoid repetitions of the same concepts in many different places. Managing complexity is a key contribution of the Smalltalk-80 approach to software.
5.2 Expression Syntax
The syntax of the Smalltalk-80 language is simple, providing a way to refer to objects and messages and arguments using alphanumeric names. There is no restriction in the language on the length of a name; there are some restrictions on the use of special symbols. In this section, syntax diagrams for the language are presented. The diagrams are like those used, for example, in the Pascal User Manual and Report, Kathleen Jensen and Niklaus Wirth, Springer Verlag, 1978. The term being defined is shown at the left margin; each term is defined with respect to other terms (shown in boxes) or literals (shown in ovals or circles) in the language. The diagram helps determine whether an expression is syntactically correct. An expression is a sequence of characters that describes an object called the value of the expression. The four kinds of legal expressions are literals, variable names, message expressions, and block expressions. Q Literals Literals are numbers, symbol constants, character constants, strings, and array constants, as shown in Figure 5.1.
literal number symbol constant > character constant string
Figure 5.1
array constant
81 5.2 Expression Syntax
] Numbers The diagram for numbers is shown in Figure 5.2. Example numbers are 3 30.45 -14.0 13772 8M53 16rAC.DC
1.586e-3 16r1e10
digit 0
1 2
3
4
5
6
7
8
9
digits
number
| digits \-p(
*Cy+\ digiteK
Figure 5.2
• Characters The diagram for characters and character constants is shown in Figure 5.3. Note that in the syntax diagrams, a character is defined as any element from the ASCII character set other than double quote ( " ) or single quote ('); the definition of character constant is a character or a double quote or a single quote. Example character constants are $a $M $$$ $[ $@
82
Fundamentals of the Smalltalk-80 Language character constant
—^ character
letter
special character
= ) C@ character
Figure 5.3
83 5.2 Expression Syntax Strings
Figure 5.4 is the diagram for strings. Example strings are
'hi' 'the Smalltalk-80 system' 'can' ' t ' string
Figure 5.4 Symbols
Figure 5.5 is the diagram for symbols.
identifier
symbol identifier
binary selector
keyword
symbol constant Figure 5.5
symbol
84 Fundamentals of the Smalltalk-80 Language
Example symbol constants are #bill #M63
There will never be two symbols with the same characters; each symbol is unique—that is, any reference to a symbol made up of the same sequence of characters is a reference to the same symbol. Examples of binary selectors and keywords are given in subsequent sections. If you do look ahead, you will notice that the following are symbols. Smalltalk is an identifier * is a binary selector // is a binary selector at:put: is a keyword selector
Q Arrays An array is a simple data structure whose contents can be referenced by an integer index from 1 to a number that is the size of the array (Figure 5.6).
array
number
symbol
string
character constant
array
array constant
Figure 5.6
•M #
array
85 5.2 Expression Syntax
Example array constants are #(1 2 3) #('food' 'utilities' 'rent') #(('one' 1) ('not' negative) 0 -1) Q Comments In addition, comments can be placed anywhere within an expression or sequence of expressions (Figure 5.7). comment
Figure 5.7
Example comments are "This is a comment" " with an embedded quote " " symbol" " and an embedded single quote ' symbol"
Q Variables The memory available to an object is referenced by the use of variable names. A variable name is simply an identifier (Figure 5.8). variable name identifier
Figure 5.8
By convention, when identifiers are created by concatenating words, the first letter of each additional word is capitalized. For example BicPen redButtonPressed totalSpentOn:
Q Message Expressions Messages represent interactions between the components of the Smalltalk-80 system. A message requests an operation on the part of the receiver. A message expression describes a receiver, a selector, and possibly some arguments. The receiver and
£6 Fundamentals of the Smalltalk-80 Language
arguments are described by other expressions; the selector is specified literally. A unary selector is simply an identifier, and a binary selector is either a minus sign or one or two consecutive special characters. A keyword is an identifier with a trailing colon; the keyword selector is a concatenation of the keywords in a message. The diagrams for unary selector, binary selector, and keyword are shown in Figure 5.9. unary selector identifier binary selector
special character
special character keyword >
Figure 5.9
identifier
In the message expression ages at: 'James' put: 25 there are two keywords, at: and put:. The keyword selector, that is, the literal part of the message expression, is at:put:. The two arguments of the expression are 'James' and 25; the receiver is ages. Keyword selectors do not show up in expressions; hence there is no diagram for them independent of the diagram for symbol. However, they are the symbols stored as the keys of a class's message dictionary; they can be seen, for example, in one of the subview's of the system browser as described in Chapter 9.
There are three kinds of message expressions: unary, keyword, and binary. Diagrams for message expressions are shown in Figure 5.10. The following are unary expressions. theta sin BicPen home Pen new home
In the third example, a unary expression (Pen new) is parsed as a unary object description that is sent a unary message (home).
87 5.2 Expression S y n t a x primary variable name
literal
block
unary object description
unary expression unary object description
unary selector
binary expression binary object description
binary selector — * unary object description
keyword expression binary object description
keyword
message expression unary expression
binary expression
Figure 5.10
keyword expression
binary object description
88
Fundamentals of the Smalltalk-80 Language The following are binary expressions. 3 + 4 previousTotal - expenditure (sum / count) * reserve amount In the third example, the binary expression is formed as a binary object description ((sum count)) followed by a binary selector (*) followed by a unary object description (reserve amount). The binary object description is itself a unary object description that, as a primary, is a parenthesized expression. The following are keyword expressions. 3 max: 2 finances totalSpentOn: 'food' anArray at: 3 put: 100 HouseholdFinances expenditures totalSpentOn: (reasons at: i) In the fourth example, the keyword expression is formed as a binary object description followed by a keyword (totalSpentOn:) followed by a binary object description. The first binary object description is a unary expression that is the variable HouseholdFinances followed by the unary selector expenditures. The second binary object description is a primary, the parenthesized keyword expression reasons at: i. Π Parsing When the receiver or argument of a message expression is described by another message expression, the issue of how the expression is parsed arises. Parentheses can be used to indicate the order of evaluation when that order is different from the ordinary parse. The parsing rules are: 1. Unary expressions parse left to right 2. Binary expressions parse left to right 3. Binary expressions take precedence over keyword expressions 4. Unary expressions take precedence over binary expressions 5. Parenthesized expressions take precedence over unary expressions For example, expression
parses as
4 + 5-3 2 * theta sin frame width: otherFrame width * 2
(4 + 5) - 3 2 * (theta sin) frame width: ((otherFrame width) * 2)
1 89 5.2 Expression Syntax
Q Cascaded Messages Cascading specifies multiple messages to the same object. A cascaded message expression consists of one description of the receiver followed by several messages separated by semicolons. The diagram for a cascaded message expression is shown in Figure 5.11. cascaded message expression message expression
^
•
unary selector
binary selector
unary object description
keyword
binary object description
Γ Figure 5.11
For example, a cascaded message expression is BicPen home; up; turn: 89; go: 50-H; turn: 91; go: 200 which is equivalent to BicPen home. BicPen up. BicPen turn: 89. BicPen go: 50+i. BicPen turn: 91. BicPen go: 200 Π Assignments A literal constant will always refer to the same object, but a variable name may refer to different objects at different times. The object referred to by a variable is changed when an assignment expression is evaluated. Any expression can become an assignment by including an assignment prefix, that is, a variable name followed by a left arrow. For example quantity - 19 index «- initiallndex name «- ' Chapter 1 ' flavors «- # (vanilla chocolate strawberry rootbeer) foo <- array at: 4 BicPen <- Pen new home; turn: 89
90 Fundamentals of the Smalltalk-80 Language
Thus the definition of an expression is a primary, a message expression, a cascaded message expression, or an assignment, as shown in Figure 5.12. expression primary
f—>
Figure 5.12
V
message expression
variable nan «-
J
cascaded message expression
Q Block Expressions Blocks are objects used in many of the Smalltalk-80 control structures. A block represents a deferred sequence of actions. A block expression consists of a sequence of expressions separated by periods and delimited by square brackets (Figure 5.13). statements
expression
expression
block
Figure 5.13
Blocks may take one or more arguments. Block arguments are specified by including identifiers preceded by colons at the beginning of a block. The block arguments are separated from the expessions that make up the block by a vertical bar.
91 5.2 Expression Syntax
For example, [ [ [ [
quantity + 19] index <- initiallndex. index <- index + 1] :array | total <- total + array size] :x :y | BicPen goto: χ @ y]
Since a block is a primary, the following assignments are expressions. savedAmount «- [quantity + 19] incrementer «- [ index — initiallndex. index «- index 4- 1] sum — [ :array | total — total + array size] A block without any arguments is evaluated by sending it the message value. A block with one argument is evaluated by sending it the message value: anArgument. Blocks with multiple arguments are evaluated by sending messages with a value: keyword and argument for each of the block arguments. For example, [ quantity + 19] value [ :array | total - total + array size] value: # ( a b c d e f) [ :x :y | BicPen goto: χ © y] value: 100 value: 250 fj Control Structures Two kinds of control structure found in most programming languages are provided in the Smalltalk-80 system: conditional selection and conditional repetition. Conditional selection consists of a message to a Boolean object with block expressions as the arguments. There are four such messages whose keyword selectors are ifTrue:ifFalse:, ifFalse:ifTrue:, ifTrue:, and ifFalse:. For example, number < 0 ifTrue: [ absValue «- number negated] ifFalse: [ absValue - number] number < 0 ifFalse: [ absValue <- number] ifTrue: [ absValue <- number negated] number < 0 ifTrue: [ number <- number negated] number > = 0 ifTrue: [ number <- number negated] Conditional repetition is provided by a message to a block with the keyword selector whileTrue: or whileFalse:, and another block as an argument. Evaluation of the argument continues until the receiver evaluates to true or to false, respectively. These are like the Algol
92 Fundamentals of the Smalltalk-80 Language
"while" and "until" statements. Examples of two expressions that carry out the same actions are [index < = list size] whileTrue: [ list at: index put: 0. index - index+1]
and [index > list size] whileFalse: [ list at: index put: 0. index «- index+1]
In each case, the idea is to put the value 0 in each position in an array list, starting with some value of variable index and continuing until index exceeds the size of the array. • Methods A method describes how an object will perform one of its operations. A method is made up of a message pattern and a sequence of expressions separated by periods. A message pattern contains a message selector and a set of argument names for each argument that a message with that selector would have. A method may obtain some other variables for use during its execution. These are called temporary variables. A temporary variable declaration consists of a set of variable names between vertical bars. The default value of a method is the receiver itself. When another value is to be specified, one or more return expressions are included in the method. Any expression can be turned into a return expression by preceding it with an up arrow. The diagrams for a method are shown in Figure 5.14. Note that the up arrow is specified in the diagram for "statements." An example method in which a counter is incremented until the user presses the red button, and in which the final count is returned, is | tempVar | tempVar <- 0. [Sensor red Button Pressed] whileFalse: [tempVar «- tempVar + 1]. TtempVar The temporary variable is tempVar. It is initially assigned to the value 0. tempVar <- 0 Then the expression Sensor redButtonPressed
93 5.2 Expression S y n t a x
variable name message pattern unary selector
binary selector
variable name
keyword
variable name
method message pattern
temporaries
Figure 5.14
statements
is evaluated. This is a test of the hardware pointing device. As long as the red button is not pressed, the expression tempVar — tempVar + 1
is evaluated. This assignment changes the value of tempVar, incrementing it by 1. When the user presses the red button, the current value of tempVar is returned. Class Descriptions
Each class has a name that describes the type of component its instances represent. A class name serves two purposes; it is a simple way for instances to identify themselves, and it provides a way to refer to the class in expressions. Since classes are components of the Smalltalk-80 system, they are represented by objects. A class's name automatically becomes the name of a globally shared variable. The value of that variable is the object representing the class. By convention, the first letter of names of shared variables are capitalized. A description of a class has four parts. 1. A class name. 2. The superclass of the class.
94 Fundamentals of the Smalltalk-80 Language
3. A declaration of the variables available to instances. 4. The methods used by instances to respond to messages. The methods in a class description are divided into categories; the categories have names that indicate the common functionality of the methods. The classes in the Smalltalk-80 system are also grouped into categories. These two kinds of categorizations in the system are orthogonal to the semantics of the language; they are used to document the intended use of classes and methods, and they are useful in providing a way to index the system's functionality. The methods in a class have access to five different kinds of variables. These kinds of variables differ in terms of their scope, and how long they persist. 1. Instance variables exist for the entire lifetime of the object. They represent the current state of an object. 2. Temporary variables are created for a specific activity and are available only for the duration of the activity. They represent the transitory state necessary to execute a method. 3. Class variables are shared by all the instances of a single class. 4. Global variables are shared by all the instances of all classes. 5. Pool variables are shared by the instances of a subset of the classes in the system. The majority of shared variables in the system are either class variables or global variables, most of which refer to the classes in the system. Names of global variables are stored as the keys in a special dictionary named Smalltalk. In order to declare a new global variable, you evaluate an expression of the form Smalltalk at: #VarName put: varValue
To evaluate an expression, you type the appropriate expression in a workspace, select the text of the expression, and then choose the yellow button menu command do it. You can then use VarName in expressions that you evaluate in a workspace.
We said earlier that all Smalltalk-80 system components are represented by objects and all objects are instances of a class. Therefore, the classes themselves are represented by instances of a class. A class whose instances are themselves classes is called a metaclass. In the description of a class, it is necessary to distinguish between the messages sent to the instances of a class and those sent to the class itself. Messages sent to the class itself are stored in the message dictionary of the class's metaclass.
95 5.3 System Components
A class's metaclass is automatically created whenever the class is created. In the programming interface to the system, a menu in the system browser supports the user in specifying whether a message is to be sent to instances or to the class itself. The programming interface also supports creating class and message categories.
Method Determination, self and super
When a message is sent, the methods in the receiver's class are searched for one with a matching selector. If none is found, the methods in that class's superclass are searched next. The search continues up the superclass chain until a matching selector is found. The search for a matching selector follows the superclass chain and terminates at the root of the class hierarchy, which in the Smalltalk-80 system is class Object. If no matching selector is found in any class in the superclass chain, the receiver is sent the message doesNotUnderstand: with an argument that is the offending message selector (the one that could not be found). The response to the message doesNotUnderstand: is found in class Object; the result is to report an error to the programmer or user. A pseudo-variable name is similar to a variable name, however, the value of pseudo-variable name cannot be changed by an assignment. The names of variables in a message pattern are pseudo-variable names. In addition, there are special pseudo-variable names in the system. The pseudo-variable self refers to the receiver of a message. When a method contains a message whose receiver is self, the search for the method for that message begins in the instance's class, regardless of which class contains the method containing the pseudo-variable self. The pseudo-variable super is also available for use in a method's expressions. The pseudo-variable super refers to the receiver of the message, just as self does. However, when a message is sent to super, the search for a method does not begin in the receiver's class. Instead, the search begins in the superclass of the class containing the method. The use of super allows a method to access methods defined in a superclass, even if the methods have been overridden in subclasses.
5.3 System Components
The Smalltalk-80 system includes a set of classes that provide the standard functionality of a programming language and environment: arithmetic, data structures, control structures, and input/output facilities. The system includes objects representing both real and rational numbers. There are also classes for representing linear magnitudes (like dates and times) and random number generators. Most of the objects in the Smalltalk-80 system function as data structures of some kind. While most objects also have other functionality,
96
Fundamentals of the Smalltalk-80 Language there are a set of classes representing more or less pure data structures. These classes represent different types of collections. Objects and messages implement the standard control structures found in most programming languages. They provide conditional selection similar to the "if-then-else" statements of Algol and conditional repetition similar to its "while" and "until" statements. Two classes are provided to support these control structures. Booleans represent the two truth values and blocks represent sequences of actions. Booleans and blocks are used to create new kinds of control structures. Objects representing independent processes and mechanisms for scheduling and synchronous interaction are also provided. There are several classes in the Smalltalk-80 system that assist in the programming process. There are separate classes representing the source (human-readable) form and the compiled (machine-executable) form of methods. Objects representing parsers, compilers, and decompilers translate between the two forms of method. Objects representing classes connect methods with the objects that use them (the instances of the classes). Objects representing organizational structures for classes and methods help the programmer keep track of the system, and objects representing histories of software modification help link the efforts of other programmers. Even the execution state of a method is represented by an object. These objects are called contexts and are analogous to stack frames or activation records of other systems. Classes helpful for presenting graphical views represent points, lines, rectangles, and arcs. Since the Smalltalk-80 system is oriented toward a bitmapped display, there are classes for representing and manipulating bitmapped images. There are also classes for representing and manipulating the more specific use of bitmapped images for character fonts, text, and cursors. Built from these graphical objects are other objects representing rectangular windows, command menus, and content selections. There are also objects that represent the user's actions on the input devices and how these relate to the information being viewed. Classes representing specific viewing and editing mechanisms constructed from these components provide views for classes, contexts, and documents containing text and graphics. The views of classes provide the fundamental mechanism to interact with the software in the system. The Smalltalk-80 system allows communication with external media. The standard external medium is a disk file system. Objects represent individual files as well as directories. If a connection to a communications network is available, it can be accessed through objects as well. The System Class Hierarchy
Figure 5.15 is of the system classes that are presented in the companion book Smalltalk-80: The Language and its Implementation. Lines are drawn around groups of related classes; the groups are labeled to indicate the numbers of the chapters in which specifications of the classes can be found.
I
97 5.3 System Components Object Magnitude Character Date Time Number Float Fraction Integer LargeNegativelnteger LargePositivelnteger Smalllnteger LookupKey Association Link Process
Collection SequenceableCollection LinkedList Semaphore ArrayedCollection Array Bitmap DisplayBitmap RunArray String Symbol Text ByteArray Interval OrderedCollection SortedCollection
10
Figure 5.15
Bag MappedCollection Set Dictionary IdentityDictionary
Stream PositionableStream ReadStream WriteStream ReadWriteStream ExternalStream FileStream Random File FileDirectory FilePage
12
UndefinedObject Boolean False True
14
ProcessorScheduler Delay SharedQueue
15
Behavior ClassDescription Class MetaClass
16
J Point Rectangle BitBIt CharacterScanner Pen DisplayObject DisplayMedium Form Cursor DisplayScreen InfiniteForm OpaqueForm Path Arc Circle Curve Line LinearFit Spline
18 19
20
98 Fundamentals of the Smalltalk-80 Language
Several classes available in the standard Smalltalk-80 system are not listed in Figure 5.15. Some of these are the classes that support the implementation of the user interface, including View, Controller, ControlManager, and WindowingTransformation. The specific way in which these classes and subclasses of View and Controller are used to create the programming interface, as well as graphical and interactive interfaces to applications, will be described in a future companion book, Smalltalk-80: Creating a User Interface and Graphical Applications. Some of the classes that describe the standard program development tools are Browser Debugger MethodListDebugger FileModel FileList Inspector Contextlnspector Dictionary I nspector StringHolder ChangeList FilllnTheBlank Project TextCollector SyntaxError
There is a subclass of View and Controller for each of these; the subclass of View supports the way information about the development tool should be presented on the display screen, and the subclass of Controller describes the way in which the pointing device, menus, and the keyboard are used to interact with the development tool. There are classes for organizing classes and messages, and for keeping track of changes to classes and methods; these are ChangeSet ClassCategoryReader ClassOrganizer SystemOrganizer
There are classes that describe parsing, compilation, and decompilation. Compiler ParseNode AssignmentNode BlockNode
99 5.4 Overview of the Programming Process
CascadeNode Decompiler Encoder LeafNode Literal Node SelectorNode VariableNode MessageNode MethodNode ReturnNode ParseStack Scanner Parser
And there is a class that describes creating a new version of the system. SystemTracer
5.4 Overview of the Programming Process
Programming in the Smalltalk-80 system involves the specification of one or more class descriptions, creating instances of classes, and sequencing messages to the instances. In the course of using the system, you interact with various views that give you access to the classes in the system, messages, methods that implement messages, expressions in which messages are sent to objects, and intermediate execution states. The programming environment supports describing classes in an incremental fashion. The "class editor" is presented in the form of a browser, which is a way to present a hierarchical index to classes and to messages. Browsers are set up to help you find classes either by name or by category. You can find a message name under the class that uses it, and, given the name, you can find its implementors or senders. To determine the class of an instance, you send the instance the message class. To determine the category of a class, you send the class the message category.
The browser is used to retrieve descriptions of existing classes. It also provides a structure within which new classes are defined and existing classes are modified. When you use a browser to examine existing class descriptions, the source code for each method is retrieved from a special file.
100 F u n d a m e n t a l s of t h e S m a l l t a l k - 8 0 L a n g u a g e Some hardware/software configurations of the Smalltalk-80 system might not have sufficient local or remote secondary storage space for this file. In such cases, attempts to retrieve the source code will fail. In order to view the method, you must use the system decompiler. You decompile the resident compiled code by holding down the "shift" key on the keyboard while selecting the message selector to be retrieved. Alternatively, set the value of SourceFiles to be nil (that is, evaluate the expression SourceFiles <- nil), indicating that no sources and no changes files are available. Decompiling loses comments and the names of temporary variables.
A system browser looks like a rectangular area on the screen that is divided into five parts. The parts either indicate a categorization for classes or a categorization for the methods of a particular class. These categorizations are orthogonal to the language itself; they provide a way in which to organize and document the class description. Parts Two and Three describe the system browsers in detail. Classes are created by editing templates that are accessed via the system browser. The template for defining a new class as a subclass of an existing class, and for declaring the private and shared variables is NameOfSuperclass subclass: #NameOfClass instanceVariableNames: 'instVarNamel instVarName2' classVariableNames: 'ClassVarNamel ClassVarName2' poolDictionaries:" category: ' Category-Name'
In order to create a new class, you edit this template. You specify the names of classes (replacing NameOfClass and NameOfSuperclass), and you replace or delete the place holders for variable names, e.g., instVarNamel or ClassVarNamel. The result is a Smalltalk-80 expression. For example View subclass: #FinancialHistoryView instanceVariableNames: " classVariableNames: " poolDictionaries: " category: 'Financial-Histories'
When you evaluate the preceding expression, you create the new class whose name is FinancialHistoryView as a subclass of View. It has no new variables declared. The yellow button menu associated with the part of the browser in which the template is displayed includes the command accept. When accept is chosen, the expression is evaluated. If there are no errors in syntax, then the new class is added to the system. If the class already exists, then it is redefined (its superclass or its variables may be changed); in this case, all existing methods of the class and its subclasses are recompiled so that references to variables can be rechecked.
5.4 Overview of the Programming Process
The template for defining new methods is message selector and argument names "comment stating purpose of message " | temporary variable names | statements
It is displayed in a part of the system browser as a result of your selecting a class category, a class, and a class message category. The yellow button menu associated with the part of the browser in which the template is displayed includes the command accept. When accept is chosen, the method is compiled. If there are no syntax errors, the compiled method is stored in the selected class's method dictionary. You can develop your class description in parts. Each time you wish to add a method, you use the system text editor (as described in Chapter 3) and edit the method template. In order for the system to store the text as an actual method, you have to compile it. You compile the text by choosing the yellow button command accept. Compilation is done incrementally, method by method. Compilation is from Smalltalk-80 expressions into a bytecode instruction set which is interpreted by the Smalltalk-80 virtual machine.
As expressions are evaluated in a workspace, or as class descriptions are developed using a browser, information pertaining to each action is saved on a special disk file that we refer to as the "changes file." In this way, there is a file that represents an audit trail of each of your actions; this file can be used to recover your work in case of a system failure. A description of the recovery process is provided in Chapter 23. Your changes are also monitored in a kind of dictionary. We refer to this dictionary as the system "Change Set." It is useful as a reference for writing out a description of your final work (any class changes) onto a disk file. Typically, users share information, such as method descriptions, by sharing files of incremental changes or files of complete class descriptions. The system Change Set is documented in Chapter 23. The process of developing class descriptions is supported by the browser. Using it you can ask questions about existing classes. You can find out which methods in which classes send a particular message. And you can find out which classes implement a particular message. Support for finding out such information is described in Part Two; support for programming is described in Part Three. An execution interrupt occurs when you encounter a runtime error, you evaluate a breakpoint that you inserted in a method, or you type Ctrl c (the "control" key and the "c" key concurrently). You can create a debugging view onto the context of that interrupt. Notifiers for inter-
102 Fundamentals of the Smalltalk-80 Language
rupts and the debugger are described in Part Four. Note that you can edit a method within the debugger, compile it by choosing the yellow button command accept, and proceed with testing your work (without explicitly reloading the system). Changes you make are local to your copy of the system. When you have completed your work, you can save it in one of two ways. You can either save a textual description of your class descriptions by using the "file out" command available in the system browsers (see Chapters 9 and 22), or save a new image of the entire system by creating a snapshot (see Chapters 1 and 23). It is useful to keep a snapshot of your work, expecially if you have created several kinds of objects that have information state that has evolved during your work session. Files created using the first approach can be shared with other users (they can file in the descriptions) so that your class descriptions can become part of their personal systems.
5.5 Summary of Terminology: General Concepts
argument name
Name of a pseudo-variable available to a method only for the duration of that method's execution; the value of the argument names are the arguments of the message that invoked the method.
class
A description of a group of similar objects. An object that describes the implementation of a set of similar objects.
class variable global variable instance
A variable shared by all the instances of a single class. A variable shared by all the instances of all classes. One of the objects described by a class; it has memory and responds to messages.
instance variable
A part of an object's private memory. A variable available to a single object for the entire lifetime of the object.
interface message message pattern
The messages to which an object can respond.
method
A request for an object to carry out one of its operations. A message selector and a set of argument names, one for each argument that a message with this selector must have. A description of one of an object's operations; it is made up of a message pattern, temporary variable declaration, and a sequence of expressions. A method is executed when a message matching its message pattern is sent to an instance of the class in which the method is found.
103 5.6 S u m m a r y of Terminology: S y n t a x object
A component of the Smalltalk-80 system represented by some private memory and a set of operations.
pool variable
A variable shared by the instances of a subset of the classes.
primitive method
An operation performed directly by the Smalltalk-80 virtual machine.
protocol
Is a term used interchangeably with "interface," as in message protocol or message interface.
receiver
The object to which a message is sent.
subclass
A class that inherits variables and methods from an existing class.
superclass
The class from which variables and methods are inherited.
system classes
The set of classes that come with the Smalltalk-80 system.
temporary variable
A variable created for a specific activity and available only for the duration of that activity.
array
A data structure whose elements are associated with integer indices.
5.6 Summary of Terminology: Syntax
assignment
An expression describing a change of a variable's value.
binary message
A message with one argument whose selector is made up of one or two special characters.
block
A description of a deferred sequence of actions.
block argument
A parameter that must be supplied when certain blocks are evaluated.
cascading
A description of several messages to one object in a single expression.
expression
A sequence of characters that describes an object; the object is called the value of the expression.
keyword
An identifier with a trailing colon.
keyword message
A message with one or more arguments whose selector is made up of one or more keywords.
literal
An expression describing a constant, either a number, symbol constant, string, or array constant.
message argument
An object that specifies additional information for an operation.
message selector
The name of the type of operation a message requests of its receiver.
104 Fundamentals of the Smalltalk-80 Language
pseudo-variable name
An expression similar to a variable name. However, unlike a variable name, the value of a pseudo-variable name cannot be changed by an assignment.
symbol
A string whose sequence of characters are guaranteed to be different than those of any other symbol.
unary message variable name
A message without arguments. An expression describing the current value of a variable.
Τ
When used in a method, indicates that the value of the next expression is to be the value of the method.
self
A pseudo-variable referring to the receiver of a message. Responses to messages to self are found by starting the method search in the class of the receiver, continuing up the superclass chain, and terminating at class Object.
super
A pseudo-variable referring to the receiver of a message. Responses to messages to super are found by starting the method search in the superclass of the method in which super appears, continuing up the superclass chain, and terminating at class Object.
1 How To Evaluate Expressions
6.1 The do it Command 6.2 The print it Command 6.3 The System Workspace 6.4 Examples 6.5 Summary of Terminology
I
106 How to Evaluate Expressions
Commands or items in menus correspond to messages for an object. Choosing a command corresponds to sending a message to the object. Messages are also sent, that is, commands can also be issued, by evaluating Smalltalk-80 expressions. Any Smalltalk-80 message can be sent simply by typing the appropriate expression in a view that can contain text, selecting the expression, and choosing the yellow button command do it or the yellow button command print it. You select text representing a Smalltalk-80 expression to be evaluated in the same way you select any text to be edited.
6.1 The do it Command
Figure 6.1
Whenever evaluation of expressions is possible, the item do it will appear in the yellow button menu; choosing do it provides immediate execution of any Smalltalk-80 expression or sequence of expressions that is selected. It is common practice to keep around a workspace in which to type expressions that can be selected and evaluated, or from which to select previously typed expressions. Whenever you want to reevaluate an expression evaluated earlier, simply select the appropriate text in the workspace and choose the yellow button command do it. You may of course edit some of the existing text before you select and evaluate it. In a sense, text left in workspaces form templates for commands. When you choose the do it command (Figure 6.1), the selected expression is compiled. If an expression is not syntactically correct, a message to that effect will be inserted in the text (Figure 6.2). The point of location will precede the erroneous place in the expression. The insertion will be selected so that you can cut it out or replace it as soon as the error is understood.
107 6.1 The do it Command
Figure 6.2
As another example, the error might be that a term in the expression is not a variable that has been declared at a global level or as a temporary variable of a sequence of statements. If you evaluate an expression with a variable that is not recognized (Figure 6.3), a menu appears (Figure 6.4). It gives you the option to declare the variable, to call on a spelling corrector to help you determine the correct variable name, or to cancel the evaluation. One of the items must be chosen (Figure 6.5). Spelling correction is explained in Chapter 16. Evaluation is always carried out in the context of the view in which the do it command is issued. This is especially useful in a view of an interrupted process in which you are able to carry out debugging activities. In such a view, there is a menu from which you choose an interrupted message sent to an object, usually referred to as a messagesend; evaluation within the view is carried out in the context of the selected message-send. It is also useful in a view for inspecting the internal state of an object. In such a view, evaluation is carried out in the
BicPen spiral: k'OU anqlg;
a ga ιη υπdο c ϋρy
cut
ρ a 51 Q
Figure 6.3
Bio
prints it a c c Θρ t c a nc eI
108 How
to Evaluate Expressions
angle: 8y
Figure 6.4
I dQdare BicPen as | temp c I a. s s ν a r global w undeclared correct it abort
000 Works p..^
»
leicPenl spiral: 200 angle: 8':
| decla re BicPen a s | temp class \'3r gIoba 1 undeclared
Figure 6.5
100
correct it
context of the variables of the object under inspection. An example of a view for inspecting an object is given in Chapter 8. While the expression is being evaluated, the scroll bar will disappear. It will reappear as soon as evaluation is completed. This is a useful signal to you that you have to wait for the system to complete the actions associated with any message. Keep the cursor inside the view in which the evaluation was requested so that the scroll bar can reappear. If the cursor is outside the view, the scroll bar will reappear but quickly go away again. In many cases, the cursor will change shape while an evaluation is being carried out; the shape may be that of an hourglass (wait cursor) or of a slanted arrow with a star attached (execute cursor). Q Practicing Suppose you wish to create a new variable name that is globally accessible so that you can assign different values to the vari-
109
6.1 The do it Command able. First you have to store the new variable name in the dictionary Smalltalk. In the following example, the variable named is Frame. Smalltalk at: # Frame put: nil The above expression declares that Frame is a global variable name; its value is the object nil. Type the expression in a workspace, select it, and then choose the yellow button command do it (Figure 6.6). Now let's assign a new Rectangle to be its value. Type, select, and evaluate the expression (Figure 6.7) Frame <- Rectangle fromUser or Frame - Rectangle origin: 200 @ 300 extent: 150@200
Figure 6.6
aIItalk at: # Frame put: nil
print ι?
Figure 6.7
Oio
acceρt canceI
110 How to Evaluate Expressions
Both expressions are used to create new instances of class Rectangle. The expressions are well-formed because you declared the name Frame in advance. The system includes a dictionary named Undeclared. If you try to evaluate an expression that contains an undeclared variable name, then the name is stored in this dictionary. Before you can successfully declare it (that is, store it in the dictionary Smalltalk), you must remove it from Undeclared. You can remove it from Undeclared by evaluating Undeclared removeKey: #VariableName where VariableName is the name that was used without prior declaration. Alternatively, you can use one expression to remove the variable from Undeclared and store it in Smalltalk by evaluating Smalltalk declare: #VariableName from: Undeclared
6.2 The print it Command
Evaluating an expression returns a result that is an object that can print a description of itself. The result obtained by choosing the do it command is not printed. The command print it is identical to do it with the exception that the object resulting from evaluation prints its description after the text selection. The description then becomes the text selection. In a workspace, type the expression
3+4 Type the escape key. This selects the expression. Now choose the yellow button command print it (Figure 6.8a).
Smalltalk at: #Frarn9 put: nil FrarriQ *• R y c t a n q l e origin: 2 0 0' *j 3 0 0 Q χ 19 π t:
150 @ 2 0 0
agaιη υηdο cορy cut ρ a s 19
do it
mam a c c ajj t c a n c 91
Figure 6.8a
ΠΙ 6.3 The System Workspace The expression is compiled, evaluated, and then the result, 7, is inserted after the expression in the workspace (Figure 6.8b).
-Ι
Smalltall· at: # Frame put: nil FrarriQ «- Rectangle origin: 200 | ϊ ι 300 θ-tent: 150'Σ'200
Figure 6.8b
000
6.3 The System Workspace
A special workspace labeled the System Workspace is available in the system. Its purpose is to provide documentation or templates for some of the common expressions you might need to evaluate. Most of these expressions pertain to activities common to an operating system, activities such as opening or editing a file, reading a file, resetting the size of the display screen, or accessing the audit of changes you have made so far. There are also expressions for inquiring about methods, messages, and literals in the system. These expressions form templates for operations that you may wish to invoke. By editing the expressions in the System Workspace, you specify, for example, a particular file or a particular size for the screen. The System Workspace usually appears in the upper right screen area of an initial Smalltalk-80 system display. An image of a typical System Workspace is shown in Figure 6.9. An index of the use of expressions found in the System Workspace is provided in the back of the book. Notice that the System Workspace includes a template for declaring global variable names. You can find and edit it rather than typing the entire expression yourself (as suggested in Section 6.1).
112 How
to Evaluate Expressions
£malltalk-80 of April 1, 1983 Copyright (c) 1983 Xerox Corp, All rights reserved. Create File System SourceFiles +• A r r a y new: 2. SourceFiles a t ; 1 put; (FileStream oldFileNamed; Ί a s 11 a s t ρ a re η t. s ο u re e s'), SourceFiles at; 2 put: (FileStream oldFileNamed: ' I a. s 11 a s t ρ a. rent, c h a n g e s'), (SourceFiles at: 1) readonly. SourceFiles «- Disk «-nil,
|t
Files (FileStream oldFileNamed: 'changes, s t ' ) fileln. (File S t re a m fi 1 e Ν a. m e d: ' c h a n g e s, s t ' ) file 0 u t C h a. n g e s, (FileStream fileNamed; ' f i l e N a m e . s t ' ) edit,
Figure 6.9
0001
Changes (FileS t re a m file Ν a. m e d; ' c h a. n g e s. s t'') file 0 υ t C h a n g e s, S rn a. 111 a I k η ο C h a n g e s,
6.4 Examples
In order to give you some practice evaluating expressions, some examples of system variables and messages you can send to them are given in this section. Exercise 1: In a workspace, type the expression Transcript show: ' hello' Select the expression and then choose the yellow button command do it (Figure 6.10a). The special System Transcript is referred to by the global variable name Transcript. This expression is a message to Transcript to insert the characters in the string ' hello' (Figure 6.10b). The System Transcript usually appears at the upper left part of the initial Smalltalk-80 display screen. If one does not appear, you can create it by choosing the System Menu command system transcript.
113 6.4 Examples
Sy51Qm Τ r a . η s c r i p t I
Figure 6.10a
Figure 6.10b
1
Oio
114
How to Evaluate Expressions Exercise 2: Type and select the expression Rectangle fromUser and choose the yellow button command do it. The expression is a message to Rectangle to create an instance of itself by having you designate a rectangular area of the screen. Evaluate the same expression with print it this time (Figure 6.11a). Specify a rectangular area (Figure 6.11b). A description of the Rectangle prints in the workspace (Figure 6.11c). Exercise 3: Display is a global variable name that refers to the display form that represents all the bits on the screen. It is an instance of class DisplayScreen. You can change the size of the full screen by send-
Τ r a. π s c r i ρ t s h ο w : ' h e l l o '
a. g a ι π υ ΓΙ do cορ ν
cut ρaste do i t
Figure 6.11a
010 Transcript 5 how: 'hello'
•I
iRQctanqle fromUsen^^H
Figure 6.11b
100
Η Η Η Η Η Η Η Η Η 1
UJ5 6.4 Examples
P.
Figure 6.11c
J
Τ re η 5 c π ρ t .• h ο w : ' h e l l o '
000 ing a message to DisplayScreen, telling it the new coordinates. For example, DisplayScreen displayExtent: 512 @ 640 will modify the layout to be 512 dots wide by 640 dots high. An expression of this form is provided in the System Workspace. The width and height you try should not exceed the actual limits of the hardware you are using. You can change the image of the current display by sending messages to Display. For example, the expression Display gray will clear the screen to a gray tone. Suppose you type this expression in a workspace and then evaluate it using the command do it. There may be a side effect if you keep the cursor in the active workspace—in particular, the workspace's scroll bar will probably display itself after the expression is successfully evaluated.
Exercise 4: You can access the cursor display coordinates by sending a message to Sensor (which is an instance of InputSensor), as shown in the following sample messages. Sensor cursorPoint Sensor waitButton Sensor redButtonPressed
Will determine the screen coordinates of the cursor. Will wait until any button is pressed and then determine the current cursor point. Will determine whether only the red button is pressed.
116 How to Evaluate Expressions
Try these expressions using the yellow button command print it. Trying the third expression by evaluating it in a workspace is a bit tricky because you have to press the yellow button, release it to choose print it, and select the red button in the same time frame. It is simpler to evaluate the following two expressions Sensor waitButton. Sensor redButtonPressed
The first expression will wait until you choose a button before evaluating the second expression. Thus you can use these expressions to experiment with testing pressing one of the three buttons. More information about controlling the objects Display and Sensor can be found by examining the definitions of their respective classes, DisplayScreen and InputSensor. See Chapter 9 to learn how to find these definitions. Exercise 5: You can create an infinite recursion by evaluating a message that simply calls on itself. For example, suppose Pen responded to the message go by evaluating self go
If you sent a Pen the message go, you might notice right away that nothing is happening the way it should. Or you might not notice until your system starts running out of space and a notification, such as "low storage indicator," is displayed on the screen. In the first case, you can stop the recursion by typing Ctrl c, the system interrupt request. A view that is a notification that a process was interrupted appears. Chapter 18 describes how to handle notification views.
6.5 Summary of Terminology
compiling Display
message-send
nil
Checking for correct syntax and then translating into executable form. A global variable name that refers to the display form that represents all the bits on the display screen. It is an instance of class DisplayScreen. A message sent to an object. In a view of an interrupted process, the term message-send usually refers to a message from which a response has not yet been received. The only instance of class UndefinedObject; it is typically the value of variables that have not been assigned as yet.
z Sensor
6.5 Summary of Terminology A global variable name that refers to an instance of class InputSensor. User interactions with the system input/ output devices are tested by sending messages to an InputSensor.
Smalltalk
A global variable name that refers to the dictionary of all variable names known globally in the system, in particular, the names of all classes.
System Workspace
A special workspace containing expressions or templates for expressions that are useful for such operating system activities as opening and editing files, resetting display screen size, and accessing the references to any system changes.
Transcript
A global variable name that refers to a text collector, the System Transcript.
1
How to Make Pictures
7.1 Making Pictures with the Form Editor 7.2 Making Pictures with the Bit Editor 7.3 Making Pictures with Expression Evaluation Pens 7.4 Summary of Terminology
120 How to Make Pictures
Now that you know how to evaluate expressions, you can try creating some graphical images. The Smalltalk-80 system provides support for creating graphical images by freehand drawing using the display screen as the canvas and the pointing device as the brush, and by writing methods in which graphical objects are sent messages to construct an image. Simple images are represented by instances of Form. A Form has height and width and an array of bits (a bitmap) that indicates the white and black regions of the particular image being represented. A complex image can be represented in either of two ways: by a very large Form or by a structure that includes many Forms and rules for combining and repeating them in order to produce the desired image. An image that is drawn as a sketch (in a freehand manner) is an example of the first; text is an example of the second. Two sections of this chapter focus on how to make Forms by "painting" with a "brush" on the display screen using the pointing device to specify brush positions. These sections present the two interactive editors that are available in the Smalltalk-80 system: a Form Editor, which is a general set of tools for creating graphical forms; and a Bit Editor, which focuses on creating and modifying forms by selectively making each point (bit) of the form either black or white. A third section of this chapter discusses messages you can send to instances of Pen in order to create images on the screen. Chapters 18, 19, and 20 of the companion book, Smalltalk-80: The Language and its Implementation, provide further explanations and examples of methods for creating graphical images.
7.1 Making Pictures with the Form Editor
The basic idea of the Form Editor is to provide a canvas, an area of the screen in which drawings can be created, and a set of tools for placing paint on the canvas. All or part of the drawings can be saved on an external file and retrieved at later times. Figure 7.1 shows the canvas of the Form Editor on which some drawing has been done, and the menu of editing commands. The items in this menu are graphical images rather than text; as such, the menu is called an iconic menu. When the view for the Form Editor is not active, the iconic menu is hidden; when you select the view to make it active, the menu appears along the bottom edge of the view. Five tool functions comprise the basic graphical form vocabulary. These are: single-copy, repeat-copy, line, curve, and block. Each of these tools can be modified in its use by four variables that modify its effect on the screen: form source, color tone, grid spacing, and painting mode.
1
121 7.1 Making Pictures with the Form Editor
Figure 7.1
122 How to Make Pictures
The functions are represented in the iconic menu that appear when the Form Editor is invoked. To choose any tool or variable in the Form Editor, either move the cursor over the icon representing the desired action and click the red button, or type a corresponding key on the keyboard. You can press the red button and move the cursor over the icons; the current selection is highlighted by displaying a gray box within the icon. Releasing the red button chooses the current selection. The use of a gray box rather than complementing the icon was the aesthetic choice of the graphics artist who was involved in designing the editor.
The Form Editor is in a standard system view so that the standard blue button menu is available. However, the size of the viewing area can not be changed. A full screen editor can be created as well. Create a Form Editor by evaluating an expression of the form (Form new extent: 300 @ 400) edit or FormEditor openFullScreenForm
The message edit can be sent to any instance of Form. The system prompts you to choose the upper left corner of the viewing area. Note that the numbers you choose for the size of the Form should not exceed the width and height of your display screen. Moreover, in determining the height of the entire viewing area, you should allow for at least 112 pixels for the height of the menu. The second expression creates a new Form the size of the display screen and then creates the editor for it. The menu accessed by pressing the yellow button while you are in a Form Editor has two commands: accept and cancel. As in text editing, the picture being created does not modify the original Form unless the accept command is chosen. If at some stage of drawing you wish to experiment with different changes to a Form and you do not want to save versions on an external file, you can choose the accept command to store the current version, make some changes, and then choose the cancel command to restore the image to the earlier accepted version. An iconic menu appears at the bottom of the Form Editor view whenever the view is active. A labeled image of the menu is shown in Figure 7.2. The corresponding keys on the keyboard are shown in Figure 7.3. Notice that the keyboard arrangement lines up with the icon positions. A description of each icon follows. You can try each one. A suggested exercise follows the description of the editor.
123 7.1 Making Pictures with the Form Editor form source
tools Φ
r
modes
ιH J c m
α
D D ••• Figure 7.2
magnify
1 Q
1 1
gridding
color tones
3
1
w
Ε
•
··
η
5
4 R
retrieve
υ
Υ
τ
r
8
α
')
I
1
(I
0
I Ν
\
-
Ρ
]
a
D Π
Figure 7.3
Form Source
(Key a) Used to select or specify a Form that is used as the "brush" for painting. You are asked to designate a rectangular area of the screen. The image within that area becomes the new brush. You are then asked to designate a rectangular area whose contents become the new brush shape. You can designate this area from anywhere on the display screen.
Magnify
(Key z) Used for detailed editing of an area of the display screen. You are asked to designate the rectangular area within the canvas that is to be edited in its magnified form. Then you designate the upper left corner of the editing area in which each screen dot is magnified eight times its normal size. The upper left corner can be anywhere on the display screen such that the editing area fits on the screen. See the description of the Bit Editor later in this chapter.
Single-copy Tool
(Key s) When this tool is selected, the form source is copied onto the display screen at the position of the cursor whenever the red button is pressed.
Repeat-copy Tool
(Key d) When this tool is selected, the form source is copied onto the display screen at the positions of the cursor, as long as the red button is pressed.
f
124 How to Make Pictures
Line Tool
(Key f) Used to specify lines between two points. The form source is used as the "pen" to connect the end points. Move the cursor to the position of one of the end points and press red button. Keep the button pressed and move the cursor to the other end point. The line image "drags" along. Release the button to specify the second end point. The line appears. (Note that when this tool is used with gridding assistance, graphs of horizontal and vertical lines can be easily created.)
Curve Tool
(Key g) Used to specify a curve defined by three points (1, 2, 3). The curve begins and ends on points 1 and 2, and is tangent to the directed line segments formed by 1,3 and 2,3. As in the line tool, the form source is used as the "pen" to draw the curve. The three points for defining the curve are indicated by first moving the cursor to the desired position of point 1 and pressing the red button. Keep the button pressed and move the cursor to point 2. Release the button. Now move the cursor, essentially "dragging" out the curve to whatever shape is desired, and then click the button. The location of point 3 is implied by the positioning of the cursor. This technique implements a kind of "rubberband" approach to specifying the curve, similar to that used in specifying a line.
Block Tool
(Key h) Used to fill rectangular areas on the display screen with color tone. Designate the rectangular area. It fills with the current tone using the current painting mode.
Color tones are set by choosing one of the five colors; each is shown in the menu as an icon that is a square of the tone. White Tone
(Key x)
Light Gray Tone
(Key c)
Gray Tone
(Key v)
125 7.1 Making Pictures with the Form Editor
Dark Gray Tone (Key b) Black Tone (Key n) The form source is copied to the display screen according to one of the four modes that can be set. These are Over Mode
(Key j) Copy both the black and white portions of the form source onto the display. The result is to replace the currently displayed image with the form source.
Under Mode
(Key k) Copy only the black portions of the form source onto the display.
Reverse Mode
(Key I) Copy such that wherever the form source is black and the display is black, the display turns to white.
Erase Mode
(Key ;) Copy such that the black portions of the form source appear as white on the display.
The painting area has a grid associated with it in both the χ and y directions. You can set the size of the gridding. When gridding is not used, the brush can place paint anywhere in the canvas. The horizontal and vertical gridding can be used separately or together. When gridding is used, the paint is aligned on the grid boundaries. That is, the χ (when horizontal gridding is used) or y (when vertical gridding is used), or both χ and y (if both horizontal and vertical gridding are used) positioning of the source upper left corner is forced to align with the grid boundaries. Three icons represent the gridding controls. They are Horizontal Grid
(Key m) A toggle for turning the horizontal grid on and off. When the grid is on, the icon is highlighted.
Vertical Grid
(Key ,) A toggle for turning the vertical grid on and off. When the grid is on, the icon is highlighted.
Set Gridding
(Key .) Specify the horizontal and vertical grids. The integers represent the bits of the display screen. The initial value of
126 H o w to M a k e P i c t u r e s both grids is 8 bits. A prompter appears, first for the horizontal and then for the vertical grid. Type the number, not to exceed the screen width or height, followed by a carriage return key. Type only the carriage return to keep the value shown in the prompter.
The image in the entire painting area is not saved on an external file. Rather, the current form source is saved. To save everything, select everything as the form source. When a Form is retrieved from an external file, it becomes the current form source. Retrieve Form Source
(Key ')
Save Form Source
(Key /)
Change the form source to be the Form found on an external file. A prompter appears. Type the file name followed by a carriage return key. If no file name is given or if the name is not a well-formed file name, a confirmer appears stating that the file name is illegal, or the file was not found. You choose the menu item yes if you want to try another file name; choose no if you want to cancel the retrieve request. If the retrieval is unsuccessful, the form source does not change. Write a description of the current form source on an external file. A prompter appears. Type the file name followed by a carriage return key. If no file name is given, does nothing.
Note that it is possible to choose whether you want the paint brush/cursor to flash or not while you are "painting." The initial system arrangement is that the cursor flashes. To change it, evaluate the following expression before opening the Form Editor. FormEditor flashCursor: false The argument is true if the cursor should flash, false otherwise. • Default Setting When you first create the Form editing area, the settings for the tools and variables are • Form Source—a small, 8 x 8 black square • Tool—Repeat-copy • Mode—Over • Horizontal and Vertical Grids—both off • Grid setting—8 by 8
127 7.1 Making Pictures with the Form Editor fj Practice Painting Create a standard system view in which you can use the Form Editor by typing and evaluating the following expression (Figure 7.4) FormEditor openFullScreenForm
again undo copy cut ρ a. 5t9
Figure 7.4
010
print ι accept1 cancel
This will create an editor for a Form that uses the entire display screen, with the exception of the space needed for the iconic menu. The initial painting brush is a small 8 x 8 square with black tone. The tone is placed on the screen using the over mode. The painting tool is repeatcopy. Try it by moving the cursor around the canvas area, holding down the red button. You can draw a sketch. When the button is not pressed, no tone is placed on the screen. If you want to start over, choose the yellow button command cancel. Try the different color tones. Move the cursor into the iconic menu area. Notice that the shape becomes a normal cursor rather than the painting brush shape. Place the cursor over one of the gray tones and click the red button. Now move back to the canvas and sketch some more. Do this for each tone. Notice that white tone is useful for erasing. The speed with which you move the cursor makes a difference as to the smoothness of the sketching line. Try the different modes. Choose black tone. Choose the yellow button command cancel so that the painting area is clean. Place a thick stroke of black across the canvas. You have been using over mode. Now choose dark gray tone. Paint over some of the black on the canvas. Choose under mode and again paint over some of the black area already on the canvas. Notice that the tone is placed under the black strokes, not over. Try reverse and erase modes as well. A possible image resulting from following these instructions is shown in Figure 7.5.
128 How to Make Pictures
Figure 7.5 You should try each tool as well, changing paint tones and modes to test the various effects. For now, choose black tone and over mode. Now select line tool. Draw lines. You have no assistance with respect to gridding. Choose the yellow button command cancel so that the painting area is clean again. Choose horizontal grid and vertical grid. The gridding is now 8 by 8. That is, the lines you draw can be lined up on every 8 pixels, horizontally and vertically. It is, of course, possible to use only one of the grids at a time. Draw some vertical or horizontal lines to see how you can make use of the gridding (Figure 7.6). Choose set gridding and set each grid to 32 (Figure 7.7). Choose repeat-copy tool. Now try to paint (Figure 7.8). Choose horizontal grid and vertical grid again. These items are toggles so that the gridding will no longer be used when you are painting. Try the curve and block tools with different tones and modes (Figure 7.9).
129 7.1 Making Pictures with the Form Editor
J— Τ
I
Figure 7.6
Current horizontal grid ding is: 8. Type new horizontal ^ridding. :':2
" A
^ v , •··•·•••·•
Figure 7.7
c
130 How to Make Pictures
Figure 7.8
Figure 7.9
Figure 7.10
131 7.1 Making Pictures with the Form Editor
So far you have only used one brush shape (the default small square). Choose form source and designate an area from which to select a new brush shape. Try painting with it. Be careful to select something, i.e., do not select an all white area, else there will be no brush shape and you will see nothing for a brush on the canvas. If you do, simply type the key labeled a in order to select a brush again. Try making a brush that is a horizontal or vertical line and paint using the repeat-copy, line, or curve tools. Set the grids and try these brushes. You can make grid paper this way. Be sure that the mode is over when you try these experiments. Now choose the yellow button command cancel and start a fresh canvas. Choose a small square or circle for a brush. Choose black tone and over mode. Draw a simple little sketch, of a flower with a bee on it, perhaps. You probably had some trouble getting it just right-the pointing device is not, after all, a fine pen for sketching. It would be better if the bits on the screen were much larger. Choose magnify, designating the area around the bee (not too much) and then designating the origin so that a magnified view of all or part of the bee can be displayed. The view area for the magnified version of the bee should not overlap the original image on the screen. An example is shown in Figure 7.10. Note that you can not have a Form that contains more than 1024K bits. Since magnification is 8-fold, you should not select an area to be magnified that is larger than about 128 bits χ 128 bits.
132 How to Make Pictures
You are now using the Bit Editor (see the next section for details). While doing so, notice that the original bee changes while you are editing the enlarged bee. Click the red button outside the editor's area in order to exit the Bit Editor. Now make the bee your brush (choose form source) and turn the griddings on (choose horizontal gridding and vertical gridding). Choose repeat-copy and black tone and under mode and paint a swarm of bees, as shown in Figure 7.11.
Figure 7.11
You can save your work using save form source. Remember that the image you want to save must be the current form source (brush). Close the Form Editor by choosing the blue button command close. In using the Form Editor, there are some simple tricks to remember: 1. The under modd is preferred to over, especially when you want to place an image onto the canvas without erasing any portion of the neighboring image. 2. Modes reverse and erase are useful for obtaining interesting affects with mixing images. Using reverse, block tool, and black tone, you can reverse the video of all or parts of an image. 3. It is often easier to make straight lines by making the border of a view the paint brush and copying it to the canvas using under mode and the single-copy tool.
133
7.2 Making Pictim^rittTthe Bit Editor
7.2 Making Pictures with the Bit Editor
taSK
5
ΐ
i n V k e d f r m the F r m Editor as
°
°
°
in the previous section, or by evaluating an expression such as Form fromUser bitEdit
whT^T'
you
11
.ffe ^
the
rectangular area on the screen from
which the Form is defined. Then you designate the top left corner of t h " area m which the magnified view of the Form is to be displayed This area is a view containing both the magnified view and a view of the actual image. Editing takes place in the magnified view (Figure 7 12) The view of the Form for editing obtained using the message bitEdit i con tamed m a standard system view, so that the blue button menu an be invoked for closing the view.
Bit Editor
-L i_ Λ • Figure 7.12 Note that there are only two things you can do in the Bit Editor, choose black tone so that you can turn dots to black, or choose white tone so that you can turn dots Edf AH," ; U t y ° f S ° m e ° f Λ θ Ρ θ ™ E d l t ° r t o o l s W - W be use ul in he Β Editor. Adding these tools to the Bit Editor is an exercise you might try Also showing grxd for the bits is useful visual information. '
Entering the magnified area, the cursor shape changes to the crossHaxr cursor. The red button is used for setting dots in the magnT
134 How to Make Pictures
fied view to either black or white, A menu of colors appears below the magnified form. Choose one with the red button or by typing a key on the keyboard. The keyboard correspondences, which are aligned with the keys in the Form Editor, are color
key
black white
The yellow button is used for the commands accept and cancel in a way analogous to the use of these commands in the Form Editor. The blue button brings up the standard blue button menu. You can also create the Bit Editor by specifying an existing Form and sending it the message bitEdit. For example, Figure 7.13 shows the magnified image of the read-a-file cursor (eyeglasses). The cursor is obtained by sending the message read to class Cursor. Thus, the Bit Editor on it is obtained by evaluating the expression Cursor read bitEdit
Figure 7.13
135 7.2 Making Pictures with the Bit Editor
As another example, the result of evaluating (Form new extent: 64 @ 64) bitEdit is an editor on a newly created Form whose bits are all initially white. It is possible to create a Bit Editor that does not appear in a standard system view. Rather, the editor grabs complete control until you click any button outside the bit-editing area. This is the Bit Editor as it is accessed from the Form Editor. Q Opaque Forms The Smalltalk-80 system also includes a class named OpaqueForm that stores one of three colors, black, white, or transparent ("gray"). These Forms are especially useful in creating animations since any image that is underneath the transparent part of an opaque form will be visible. The message bitEdit is understood by an OpaqueForm to create a Bit Editor whose menu of colors includes a gray tone representing "transparent paint" (Figure 7.14). The keyboard correspondences are color black gray white
Figure 7.14
key
136 How to Make Pictures
7.3 Making Pictures with Expression Evaluation
Pens
Pictures can be made by direct drawing using the Form Editor or the Bit Editor. Alternatively, pictures can be made by sending messages to graphical objects. Generally, pictures made this second way are constructed in a highly structured manner by creating instances of class View or one of its subclasses. The Smalltalk-80 system has many examples of such views: BrowserView, InspectorView, and NotifierView are the primary components of the user interface. These views, in turn, contain subviews that are CodeViews, ListViews, SwitchViews, FormViews, DisplayTextViews, or StringHolderViews. Examples of StringHolderViews are ProjectViews, TextCollectorViews, and FillinTheBlankViews. A StringHolderView is a way of creating an image of any object that can present itself using information stored as a string. Primitive graphical objects are instances of Pen, Rectangle, and Quadrangle. We have already referred to Rectangle; you create a rectangle whenever you designate a rectangular area of the screen in which a view is displayed. The scroll bars are examples of the use of Quadrangle in the system. The next section explains how to use a Pen. In addition, the system includes the class DisplayObject; instances of subclasses of DisplayObject can be used in creating structured pictures. Example subclasses are Arc, Curve, Line, LinearFit, and Spline. A Pen is used for line drawing. It consists of a position on the screen, a direction in which to move, a Form that it uses for creating images, and a mask and a rule for combining the Form with its destination area on the display screen. A Pen is created by sending a message of the form BicPen «- Pen new
Here we refer to the new instance of the Pen as BicPen. Recall that if you wish to try this example, BicPen must be declared as a global variable. Rather than use the above assignment, you can evaluate Smalltalk at: #BicPen put: Pen new
We can constrain BicPen to draw only within a fixed boundary, which we call its clipping rectangle, by sending it the message frame: aRectangle. For example, BicPen frame: (200® 200 extent: 300 @ 300)
According to the above expression, BicPen will only draw in a square area 300 pixels by 300 pixels, starting at location 200, 200. Without
137 7.3 Making Pictures with Expression Evaluation
such a constraint, BicPen could have drawn anywhere on the screen. The center of a Pen's drawing area is known as its home. We can place BicPen at its center by sending it the message home. BicPen home
Initially, the tip or nib of BicPen is a 1 by 1 black dot with which we can draw thin lines. We can change the size of this nib by sending the message defaultNib:. The argument is an Integer, and the resulting nib is a square with length of side Integer. BicPen defaultNib: 8
The nib of BicPen is now an 8 by 8 black square. Alternatively, we can send BicPen the message sourceForm:. The argument is a Form. BicPen sourceForm: Cursor normal
The nib of BicPen is now the shape of the normal cursor, i.e., a slanted arrow. A Pen can receive messages asking it to change the state of its mask. black
Set the mask to black.
white
Set the mask to white.
And a Pen can receive a variety of messages asking it to change its position, the state of its ability to draw, and its direction. These consist of home down
Go to the center of the Pen's frame.
The ink form with which drawing is done should be positioned for drawing when the pen moves.
up
The ink form with which drawing is done should be positioned so that no drawing is done when the Pen moves.
turn: anlnteger
Change the direction in which the Pen will move by the amount, anlnteger, measured in degrees.
north
Orient the Pen towards the top of the display screen.
go: anlnteger
Move a distance equal to anlnteger pixels; draw using the source form if the ink form is positioned down.
place: aPoint
Place the Pen at location aPoint regardless of orientation; do not change the current direction, and do not draw.
goto: aPoint
Move the Pen to location aPoint, ignoring the current direction, but drawing if the ink form is positioned down.
138 How to Make Pictures
As described in subsequent chapters, you can see various ways to make designs with Pens by browsing to the examples in the instance or class methods. Two examples for you to try are given here. Pen new mandala: 30 diameter: 300 and
Pen new spiral: 200 angle: 89
The result of the first is shown in Figure 7.15, and of the second in Figure 7.16. After trying each example, you will want to choose the System Menu command restore display. Pen is the Smalltalk-80 version of the "turtles" designed many years ago at MIT's Logo laboratory and described in Seymour Papert's book MindStorms: Children, Computers, and Powerful Ideas (Basic Books, New York, 1980). Another excellent reference on the use of turtles is by Hal Abelson and Andrea diSessa, Turtle Geometry: The Computer as a Medium for Exploring Mathematics (Cambridge, MIT Press, 1981).
Figure 7.15
139 7.4 Summary of Terminology
Figure 7.16
7.4 Summary of Terminology
DisplayObject
A system class whose subclasses represent the graphical objects in the system, such as lines, circles, arcs, and splines.
Form
A system class that represents simple images. Instances of Form have height and width and an array of bits that indicate black and white regions of an image.
iconic menu
A menu whose items are presented as graphical images rather than as text.
opaque form
A Form that represents an array of bits each of which can indicate a black, a white, or a transparent region of the image.
Pen
A system class that represents a form source, a current display screen position, and a current direction in which to move. Instances of Pen are used to draw lines on the display screen.
How to Find Information in the System All information that you can seek about the Smalltalk-80 system involves information about existing objects or about objects that can be created. You can find out information about the internal state of an object using a system view called an Inspector. You can find out about the message interface to an object using a system view called a Browser. A System Browser gives you access to all the class descriptions available in the system, including comments about the classes, comments about the methods, and examples of how to use many of the classes. Other ways to find out about messages and methods involve creating system views called Message-Set Browsers. These views are created in response to queries to determine which methods send a particular message, which classes implement a particular message, or which methods reference a particular variable or literal. This part includes an introduction on how to find out about a running process, in particular, how to interrupt an activity to find out which objects are interacting to create that activity. The system views used in this exploration are Notifiers and Debuggers. More details about notifiers and debuggers are provided in Part Three. Several forms of on-line documentation and assistance will be identified: comments, explanations, templates, examples, and menus. In addition, the spelling correction capabilities of the Smalltalk-80 system are explained in Part Three. Comments. Each class description includes a command about the purpose of the class. A class comment is obtained (for reading or for editing) by choosing the yellow button command comment in the classnames subview of the browser. Other comments document the purpose of a method. These are found by choosing a message selector; the comment is the text within double quotes at the beginning of the method definition. Programmers can also document the design of a method by interspersing quoted text within the method itself.
%:;:;:;:;:;^^
Explanations. Suppose you want to understand an existing method. One form of explanation could be explanation about the tokens that appear in the method. You can select any token and then choose a command to obtain a short description of the role of the token. Because of the class and message structure of the system, it is possible to provide explanations about which messages are sent in a particular method, and to obtain browsers to answer queries as to which methods send a particular message, which classes implement a particular message, and which messages are sent in a particular method. These are the kinds of queries that a programmer must be able to make to determine the structure of the Smalltalk-80 system. The system browser as the program editing interface provides the framework for both the incremental development of class descriptions, as well as the context for accessing information about classes. Each new class added to the system by the programmer is accessible via a browser and can be queried in the same way as all system-provided classes. Templates. Whenever the system "knows" something about the form in which information should be provided, a template or a default solution is provided. The user edits the template, replacing descriptive words with the actual desired text. This means that the user does not have to remember syntax and can be prompted on the kind of information that is required. Templates are used to assist in defining classes and methods, and in commenting the system. Examples. In many of the descriptions of classes in the system, there are messages that consist of examples of how to interact with instances of the class. Examples show how to create a new instance or how to use an instance. These examples are typically messages to the class itself, where the method includes documentation comments and expressions to be evaluated. Since you can add your own methods, a strategy for learning how to use the system is to work out examples of your own that you store with the associated class. Menus. Menus are a form of assistance in the system. The items in a menu denote and remind you of the kinds of activities you can do. You choose an activity by pointing to the menu item, rather than having to remember the correct key words and having to type the words correctly. Items in a menu represent the behavior of an object; most likely, there is a message in the class description of the object that carries out the behavior represented by the menu item. You can learn about programming in the system by searching for these menu item/message correspondences. • Please Note The tutorial presentations in this part of the book assume that the system sources are available to you and accessible from your system. Without them, you can still use the system and access system class descriptions. However, you will not be able to access class and method comments nor actual method argument names. :·:·:£:·:·:·:·&:·:·:·:!3;:^
Finding Out About Instances
8.1 The Structure of an Inspector 8.2 Changing the Values of Variables 8.3 Sending Messages to an Object 8.4 Special Kinds of Inspectors Dictionary Inspector Model-View-Controller Inspector 8.5 Finding Out About a Running Process
144 Finding Out About Instances
In developing definitions or learning about the system, you can examine the named or indexable instance variables of an object. The message inspect can be sent to any object. The result is an inspector view of the object.
8.1 The Structure of an Inspector
An inspector is a view made up of two parts: one is a list menu of the names of the instance variables; the other is a text view in which the value of the selected variable is shown. As an example of using an inspector, try evaluating the expression (Rectangle origin: 10 @ 10 corner: 60 @ 60) inspect The result of evaluating the parenthesized expression is an instance of class Rectangle with origin at screen location 10, 10 and corner at 60, 60. Recall that 0, 0 is at the upper left corner of the display, and that χ increases to the right and y increases to the bottom of the screen. A message expression of the form aNumberi @ aNumber2 denotes an instance of class Point; the Point represents a location on the display screen whose Cartesian coordinates are aNumberi, aNumber2. This new Rectangle is then sent the message inspect. The result is that you are asked to designate a rectangular area in which the inspector will appear. An example inspector on this Rectangle is shown in Figure 8.1.
Figure 8.1
145 8.1 The Structure of an Inspector
The left subview of the inspector is the list menu. The menu contains the pseudo-variable name self, which refers to the inspected object. It also contains the instance variable names origin and corner. You choose items in the list menu by placing the cursor over the item and clicking the red button. Choose one of the variable names; a description of the value of the variable prints in the right subview (as shown in Figure 8.2a). Choose self from the list menu. A description of the Rectangle prints in the right subview (Figure 8.2b). Note the special print format for Rectangles that is displayed in the right text subview.
J
60'.*! 60
ii
<
5Qlf
origin
Figure 8.2a
100 000
•!
Fi 9 c t a ri q Ι Ρ
origin' cornQr
Figure 8.2b
000
10© 10 cornQr: 60'*'60
146 Finding Out About Instances
Choose the instance variable name corner. Press the yellow button. The pop-up menu that appears contains the single command inspect (Figure 8.3a). Choose inspect. You are asked to designate another rectangular area in which to display an inspector for the object referred to by corner. This object is an instance of class Point. Notice that the label of the inspector contains the name of the class of the inspected object (Figure 8.3b). Close this second inspector by choosing the blue button command close.
Rectangle 6 U'1:6 U 5Qlf
origin
aauaa
Figure 8.3a
010 Rectangle! 6 0 <*i 6 U 5Qlf
origin
Figure 8.3b
•00 000
60'a; 60
147 8.2 Changing the Values of Variables
8.2 Changing the Values of Variables
You can change the value of an inspected object's variables by typing an expression for the new value in the right subview and then choosing the yellow button command accept. Choose origin from the list menu of the inspector for the Rectangle you created earlier. Change the value 10 @ 10 to be 20 @ 15 simply by editing the text and choosing the yellow button command accept in the right subview of the inspector (Figure 8.4a). Now choose self in the list menu to see that the current description of the Rectangle has changed (Figure 8.4b). The private memory of an object is supposed to be protected from such direct manipulation. However, for testing or for debugging purposes, the ability to directly set the values of instance variables is very useful.
again undo
20@15
Figure 8.4a
010 Rectangle H ^ ^ I H H 8"
15 corner: 60@60
A 2U'*J
corner
Figure 8.4b
100 000
ij
148 Finding Out About Instances
Try another example. Create an array of arrays by typing and selecting the following expression in a workspace, and choosing the yellow button command do it. #(($a $b $c) $d ($e $f)) inspect
The first inspector presents an instance of class Array (Figure 8.5a). The object has three indexed variables. If you choose the first item in the list menu, self, a description of the instance is printed (Figure 8.5b). Choose item 1 in the menu of the inspector (Figure 8.5c). A description of the first element of the Array prints. Choose the yellow button command inspect (Figure 8.5d). Another inspector is created; it presents another instance of class Array, this time one with the three characters as its elements. Try inspecting the different variables. Item 2 in this second inspector is a Character (Figure 8.5e).
Figure 8.5a
( ( l a $b $c ) $d
($Q
$f
Figure 8.5b
j
149 8.2 Changing the Values of Variables
Figure 8.5c
Figure 8.5d
Figure 8.5e
150
Finding Out About Instances Choose the first element of the array in the second inspector (item 1 in the list menu) (Figure 8.5f). Now edit the text view so that it contains the text #(1 2) instead of the Character $a. Choose the yellow button command accept (Figure 8.5g). The value of the first element of the current array is now the two-element array of numbers 1 and 2. Choose self in the list menu to see the change (Figure 8.5h). Close both inspectors.
Figure 8.5f
($3 $b $c )
again undo
copy cut paste do it
print it
Figure 8.5g
DID
Γ
151 8.2 Changing the Values of Variables
Figure 8.5h To see how the information about an object can be multiply-viewed by the system views, create two inspectors on the same object. For example, try to inspect another instance of Rectangle by evaluating the expression Rectangle fromUser inspect You will first designate the area for the Rectangle and then the area for the inspector. Choose the item self in the list menu (Figure 8.6a). (Your rectangle will probably have different coordinates.)
I I
Figure 8.6a
100 000
2ΰ@2ΰ corner: 165@ 135 corngr
152 Finding Out About Instances Choose the yellow button command inspect (Figure 8.6b) to create a second inspector (Figure 8.6c). Choose origin in both inspectors (Figure 8.6d).
RectanqlQ ^ ^ ^ ^ ^ ^ H ^IJIOI^^I corner:
origin corner
Figure 8.6b
ΟΙΟ
165'*; 135
Β
I
Recta nqlej
origin corner
Figure 8.6c
100 000
23@22 corner: 165's: 135
απ g i n
corner
23@2'^ corner: 165<2! 135
r 153 8.2 Changing the Values of Variables
Rectangle I self corner
Figure 8.6d
100 000 You cannot use a more direct approach to creating the two inspectors, such as evaluating | rect | rect «- Rectangle fromUser. rect inspect. rect inspect because as soon as the first message, inspect, is sent to the rectangle instance, rect, the workspace loses control to the newly created and scheduled inspector. The last expression is never evaluated.
Change the value of one of the variables in one inspector (Figure 8.6e).
Fi 9 C 1 8 . Π CJI y
Figure 8.6e
Bio
again undo copy cut paste do it print it
Rectangle self corner
154 Finding Out About Instances
See that the other inspector knows about the change (Figure 8.6f). If the variable is already selected in the second inspector when its value was changed in the first, you will have to reselect it to see the changed value. Similarly, if self was selected, you must choose it again to see the change. Close both inspectors. The yellow button menu of the inspector's left subview contains only one item, inspect. Only the instance variables of the object are shown. As an alternative design, a command to inspect the class variables could be added. In some variations of the Smalltalk-80 system used within Xerox, this command is called classVars; it creates an inspector on a Dictionary whose keys are the class variable names and whose values are the values of the named variables.
Recta nqle SQlf
corner-.
Figure 8.6f
100 000
40 Φ 30
1
Rectangle ^ ^ ^ ^ ^ ^ H SQlf
40Φ30
j
8.3 Sending Messages to an Object
Another use of the right subview of an inspector is to test sending messages to the inspected object, or to test evaluating message expressions. For example, Rectangles understand messages for determining width, height, and area. In the right subview of the inspector for the first Rectangle that was created in an earlier example, type and select the following expression self area Note that in this example we assume the origin is at 20, 15 and the corner at 60, 60. Choose the yellow button command print it (Figure 8.7a). The result is printed (Figure 8.7b).
155 8.3 Sending Messages to an Object
!
5eIf arQaiOffl
<--'-•>< I4 /.,
::
010
000
Figure 8.7a
Figure 8.7b
ί
! ori cο
I
(60 - 20)
<
15 )H^Q
+
(60 -
ί
ίj ••
I
1
1
ti
000
000
Figure 8.7c
Figure 8.7d Is the result correct? Type and evaluate either self width * self height or (60-20) * (60- 15) as shown in Figures 8.7c and 8.7d. Both expressions compute the area and show that the result from evaluating the expression self area was correct. All evaluation in the inspector is done within the context of the inspected object's variables. Thus the expression corner - origin can be selected and successfully evaluated in the Rectangle's inspector because the variable names are known to the inspected object.
156 Finding Out About Instances
8.4 Special Kinds of Inspectors
Dictionary Inspector
The message inspect is implemented in class Object. Typically, the result of the method is to create the inspectors described in the preceding sections. In addition, the system includes two special inspectors, one for instances of class Dictionary and the other for instances of class View. Objects such as Dictionaries are represented with indexable instance variables. As demonstrated for an Array, the list menu of an inspector for such objects contains indices referring to the indexed variables. In the case of a Dictionary, the value of one of these variables is an association between a Dictionary key and a value. Figure 8.8a shows an example Dictionary. The special inspector for a Dictionary shows the Dictionary keys in the list menu, rather than the indices; choosing a key causes the associated value to display. Figure 8.8b shows this inspector for the example Dictionary. Editing the value and choosing the yellow button command accept stores a new value for the selected Dictionary key (Figure 8.8c). Since the system supports the special form of inspector for a Dictionary, you have to do something special to obtain the default kind of inspector. To create the examples, first create the Dictionary Test by evaluating the following expressions. Smalltalk at: #Test put: Dictionary new. Test at: #first put: 1. Test at: #second put: 2. Test at: #third put: 3. Test at: #fourth put: 4. Test at: #fifth put: 5.
Now create an inspector for Test. Test inspect The inspector will be like the one shown in Figure 8.8b. In the text part of this inspector, evaluate the expression super inspect
The new inspector that you create will be like the one shown in Figure 8.8a.
157 8.4 Special Kinds of Inspectors
Besides the command inspect, the yellow button menu of the left subview of a Dictionary inspector provides commands for adding and deleting elements from the Dictionary, add field and remove. Only add field shows when no item is selected. Certain Dictionaries in the Smalltalk-80 system are used for storing references to pooled variables; the keys of such Dictionaries are variable names that can be referenced in the methods of one or more classes in the system. The yellow button menu also provides a command, references, to search for and to create a message-set browser for all methods that contain references to the selected Dictionary key. Figure 8.8d shows the yellow button menu for the Dictionary inspector. Message-set browsers are described in Chapter 10.
Figure 8.8a
Figure 8.8b
.fifth
Τ
first fourth third
010 Figure 8.8c
Figure 8.8d
ιη5ρ«ct reference: add field re rn ο ν e
158
Finding Out About Instances Many objects in the Smalltalk-80 system are closely related to one another. In particular, the user interface of the system is implemented using subclasses of two classes, class View and class Controller. A View represents ways of presenting information on the screen; a Controller represents ways in which the user interacts with a screen view. Any View is related to a Controller and to another object, the object whose information is accessed in the View. This other object is referred to as a "model." Whenever you inspect a View, you typically want to inspect its related model or Controller. There is a special inspector in the system for inspecting the two main objects related to a View, as well as the View, whenever a View is sent the message inspect. An illustration of this inspector is shown in Figure 8.9. It is an inspector containing three subviews, each of which is itself an inspector—one for the model, one for the View, and one for the Controller. In the figure, the model is a system browser.
Model- ViewController Inspector
In order to try to create a special inspector for a View, evaluate the expression ChangeListView new inspect. Very few of this View's variables will be initialized as yet, but you can at least explore the structure of the special inspector.
Model: a Browser self C ο 11 e c t ί ο η s - U η ο r d e r e d organization className met a. protocol select ο r te tfvlode V i e w : a. Browser'v'iew rn ο d e I controller" superView transformation
Ο r d ere d C ο 11 e c t i ο η ί a S e I e c t i ο η Ι η Li s t V i Select io η Ι η List View a. Boolean View a. Β ο ο I e a n V i e w a. S e I e c t i ο η Ι η L ί s t V i e w a S e I e c t i ο η Ι η Li s t V i e w a. C ο d e V ί e w )
: ο η t r oiler: a S t a n d a r d '& ν s t e rn U ο η t r ο 11 e r r e d Β u 11 ο η Μ e s s a g e sa PopUpMenu yellowButtonMenu y e 11 o w B u t t ο η Μ e s s a
Figure 8.9
[000
r 159 8.5 Finding Out About a Running Process
8.5 Finding Out About a Running Process
A notifier provides a simple description of an activity or process at the time that the activity was interrupted. Interruption can occur because of a runtime execution error, or because you purposefully cause such an interruption. This purposeful interruption is accomplished by typing Ctrl c on the keyboard (that is, type "control" and the "c" keys at the same time). The notifier displays the reason for the interruption in the label of the view, and displays the sequence of messages that were invoked but not yet completed. Try to create a notifier by typing Ctrl c. The currently running process is interrupted. The notifier appears centered on the display screen. A possible interruption is shown in Figure 8.10a. Choose the yellow button command proceed in order to continue the process; when you choose proceed, the notifier is automatically closed.
I User Interrupt H | | | | H | | | H | | ^ B H ^ H ^ H I 11 S t a n d a rd S y 51 e rn 'J ο η t r ο 11 e n; 'J ο η t r ο 11 e r) • • i s 0 ο η t ro 1W a n t e d [ ] i π C ο η t r ο ΙΜ a n a g 9 r > > 5 e a. r c h F ο r A c t iveCuntr 011 Θ r [ ] ί η 0 r d e r 9 d C 011 e c t i 0 η f C 0119 c t i 0 η) > > lUUSHiEfiivl 0 η 9: ΰ r d 9 re d C ο 119 c t i 0 η > > d ο: U.^JJU ϋ rd 9 r 9 d C 0119 c t i 0 η (C ο 119 c t i 0 π) > > d 919 c t: i f Ν ο η 9:
Figure 8.10a
010 Typing Ctrl c can be used to interrupt a successfully running process that you wish to explore, perhaps to change the part of the system that supports the running process. Suppose you wish to know where text selection highlighting takes place in the system so that you can change the style of highlighting. While you are making a text selection, type Ctrl c (Figure 8.10b).
Γ
160 Finding Out About Instances
Interrupt
Pa. r a g ra ρ h > > d y Fo rPo i π t: Pa. r a g r a ρ h > > m ο υ s e S e I e c t : t ο: S t ri π g Η ο I d 9 rC ο π t ro 11 θ r f Pa ra g r a ρ h Ε d i t ο r) > > ρ ro c e s s Fi e d Β u 11 ο π S t ri η g Η ο I d e r C ο η trolls r( Pa ra g r a ρ h Ε d i t ο r) > > ρ ro c Q S S Μ Ο U S Q Β U 11 ο π s S t ri η g Η ο I d e rC ο η t ro 11 e ri Pa ra g ra ρ h Ε d i t ο r ϊ > > c ο η t ro IA c t ί ν i t ν
Figure 8.10b
000 The label of the notifier that appears indicates the reason for the interruption. User Interrupt The view displays a sequence of class names and message selectors whose method activations were interrupted. The notifier only displays the most recent class/message selectors of the interrupted execution. You can choose the yellow button command debug to obtain another view of the interrupted process. This view is called a debugger. It lets you explore the methods associated with the interrupted activity, to make needed changes, and then to proceed. Further details about the debugger are given in Part Three. A reason to interrupt a running process is to stop what appears to be a nonterminating process. When some activity seems to be taking too long, you can type Ctrl c, and then determine whether to proceed or to terminate the activity. To terminate, choose the blue button command close. The notifier view is non-preemptive. You can just leave it on the screen and do something else, returning to deal with the interrupted situation at a later time.
i
9 Finding Out About System Classes
9.1 The Structure of a System Browser 9.2 Messages to a Class versus Messages to an Instance 9.3 Browser Menu Commands Class-Category Menu Commands Class-Name Menu Commands Message-Category Menu Commands Message-Selector Menu Commands Text Subview Menu Commands 9.4 Browsing a Subset of the System Class Hierarchy Browser
;
162 Finding Out About System Classes
The main way to find out about classes in the system is to use a system class browser. A browser presents a hierarchical index to information. A Smalltalk-80 class browser presents a hierarchical index to classes in the system. This index is independent of programming logic; it is designed solely for user access to class descriptions via subject categories. The browser presents categories that organize the classes within the system, and categories that organize messages within each class. The information about a class that you can retrieve using a browser includes • a comment about the role of the class in the system • a description of the part of the system class hierarchy in which the class is found • a description of the variables of a class • a description of the messages and methods of the class, including comments about the use of the message and the design of the method • a classification of the class with respect to other classes • a classification of the messages of the class • access to all methods in the system that send a particular message • access to all methods in the system that implement a particular message • a list of all messages sent in a particular method The system browser also provides access to templates for defining new classes and templates for defining new messages, as introduced in Section 5.4. There are a number of class browsers in the Smalltalk-80 system, distinguished by the particular subset of classes that can be accessed. You obtain the browser for all of the classes in the system on the display screen by choosing the System Menu command browser. The browser that you see takes the form shown in Figure 9.1.
i
163 9.1 The Structure of a System Browser
S y s t e m B r o w s e r jjji CLASS
CLASS
MESSAGE
MESS/»LGE
CATEGORIES
NAMES
CATEGORIES
SELECT ORS
MENU
MENU
MENU
MEN U
nstancel
class TEXT
Figure 9.1
9.1 The Structure of a System Browser
The browser is made up of five subviews and two menu items labeled class and instance. When you first create a browser, the menu item instance is selected. This means that the messages you are able to retrieve are the ones sent to instances of the class, rather than to the class itself. When the menu item class is selected, the messages you are able to retrieve are the ones sent to the class itself. Four of the subviews are fixed list menus; the fifth is a view in which methods can be defined and modified using the text editor. We will refer to the various subviews of the browser by their labels in Figure 9.1. There is a yellow button menu associated with each subview of the browser, as shown in Figure 9.2. The commands in each menu are described in this chapter. Classes in the system are organized according to categories. In the full system browser, these categories are seen in a list menu in the first subview, which is labeled class categories menu in Figure 9.1. Choosing an item in the class-category subview causes a list of class names to appear in the adjacent subview. This adjacent subview is labeled class names menu in Figure 9.1. For example, if you choose the item Graphics-Primitives in the class-categories subview of the class
164 Finding Out About System Classes ;*;!::;:l*h;;;:i:i;h;;!!:;!:i*i;;*;:*
System Browser file out print out sρawη add category rename remove update edit all
file out print out S p 3. Vv' Γι
spawn hierarchy hierarchy definition c ο ITI m e η t protocols inst v a r rets class va.r refs class refs re η a. me remove
file o u t print out sρaw η add p r o t o c o l rename remove aqaiη undo cορy cut paste do it print it accept canceI format sρawη explain
file out print out sρawη senders imp lame η tors messaqe s mονe remove
Figure 9.2
browser, a list menu of four class names appears in the adjacent subview (Figure 9.3). One of the items that appears is the class name Pen. In addition, when a class category is selected, a template for defining a new class appears in the subview that is labeled text in Figure 9.1. The template is shown in Figure 9.3. You can edit this template in order to substitute proper names for the various parameters so that a well-formed expression is created that defines a class. When you choose the yellow button command accept, and if the edited information is syntactically correct, a new class is created (or an old one modified). The class is categorized under the class category selected in the first subview. The subviews of the browser are thus dependent on each other. A selection in one subview specifies the information for another subview. When a class is selected in the class-names subview, its list of categories of messages appears in the adjacent subview. This subview is labeled message categories menu in Figure 9.1. In addition, when a class is selected, the class definition appears in the text subview. An example in which the class name Pen is selected is shown in Figure 9.4. By choosing yellow button commands in the class-names subview, comments about the class and the class hierarchy of the selected class can be explored, and, if appropriate, modified.
165 9.1 The Structure of a System Browser
Graphics-View:: Graphics-Editors Ν a. m Q 0 f ο υ ρ e re I a s s 5 u b c I a s s: # Ν a rn e 0 f CI a s s i η 51 a. n c e V a. ri a. b I Q Μ a. m e 5: 'in s t V a rN a m e l in s t V a. rN a rn e 2' c I a s s V a. ri a. b 19 Ν a m e s: ' CI a. s s V a rN a. rn Θ 1 CI a 5 s V a rN a rn 9 2' poolDictionaries: " c a. t e g ο r y: ' G r a p h i c s - Pr i m i t i ν 9 s'
Figure 9.3
100 000 uollectionsCollections-:: Graphic s-Dis Graphic s-Pa.i Graphics-Vie Graphic s-Edi
Point Quadrangle Fi 9 c t a n g I e
initialize-release accessiηg coloring mονiηg geometric design:
BitBIt subclass: #Pen i η s t a η c e V a r i a b I e Ν a. rn e s: ' f r a rn e I o c a t i ο η d i r e c t i ο η ρ 9 η D ο w n c I a s s V a r i a b I e Ν a. rn e s; " poolDictionaries; " c a. 19 g ο r y: ' G r a. p h i c s - Ρ r i rn i t i ν e s'
Figure 9.4
000
166 Finding Out About System Classes
Collect ions-Strea 1 Collect ions-Suppo Point G r a ρ h i c s - D i s ρ I a y Quadrangle Rectangle Graphics-Paths Graphics-Views Graphics-Editors 1CII]IIBIMailllllH»=
initialise-re lease accessing coloring
ΟβΒΒΕΠΙ qeometrictoiesigns
dοw η fillln: go: goto: home η ο rt h
message selector and argument names "comment s t a t i n g purpose of message" | temporary variable names | s t a. t e m e η t s
Figure 9.5
When a message category is selected, a list of messages in that category appears in its adjacent subview. The subview is labeled message selectors menu in Figure 9.1. An example is shown in Figure 9.5. In addition, when a message category is selected, a template for defining a new method appears in the text subview. You can edit this template, specifying the message pattern, a comment, and the sequence of statements. When you choose the yellow button command accept, and if the method is syntactically correct, a new method is created. It is added to the description of the selected class, categorized in the selected message category. Choose a message selector. Its method appears in the text view. An example appears in Figure 9.6. You can edit the method using the text editor. You then recompile it and reinstall it automatically in the system by choosing the yellow button command accept in the text subview. Information about the method is provided in comments that also appear in the text view, usually at the beginning of the method. You can use the browser to find a message and its associated method in order to read the comments and to learn about the intended use of the message.
167 9.1 The Structure of a System Browser
dow η
ρ Graphics-Paths G ra. ρ h i c s - V i e vv s Graphics-Editors
fillln: go: goto;
home "Place t h e receiver a t the center of its frame, location *• frame center
Figure 9.6 The browser search approach implies that you need to know the category of a class in order to find it in the browser. Besides exploring in the browser, you can find out the category of a class by sending it the message category. For example, the answer from the message category to the class object Pen Pen category is Graphics-Primitives. Type this expression in a workspace, select it, and then choose the yellow button command print it. The category name is printed. Also, as will be described at the end of this chapter, it is possible to create a browser for a subset of the information in the system. To get a browser for a single class, you create an instance of class Browser, specifying the class. For example, try evaluating the expression Browser newOnClass: Pen to get a browser just for class Pen. Another approach might be to add a subview to the browser in which you can type a keyword, like a class name, to get the browser to automatically select the correct subview menu items, thus showing you the index hierarchy. Another possible feature is to be able to save the selected "query path" (the one, two, three, or four selected indices) in an additional menu so that the path can be selected directly.
168 Finding Out About System Classes
9.2 Messages to a Class versus Messages to an Instance
In the preceding examples, we have assumed that the browser menu item labeled instance was selected. Now choose the item labeled class (Figure 9.7). All messages browsed will now be ones that are sent to the class itself. These are primarily instance creation messages. In many cases, these messages consist of documentation comments or examples of how to create instances of the class. A good way to learn about the Smalltalk-80 system is to explore the classes and see what examples are provided. The example methods typically include a comment that you can select and evaluate in order to invoke the example. Choose the class category Graphics-Paths, and then choose the class name Spline (Figure 9.8). The browser menu item class should be selected. In the previous sequence of instructions, you had been directed to browse through the messages that can be sent to instances of a class. Now we can browse through the messages that can be sent to a class itself, in this case, to Spline. Message categories that are typical for classes include class initialization (messages to create class variables), instance creation (messages to create new instances of the class), constants, queries, or examples. The description of class Spline consists of the message category examples. Choose it. In the message-selectors subview, choose the message selector
CollQCtions-StrQa Collections-Suppo Graphics-Display Graphics-Paths Graphics-Views Graphics-Editors
instance creation examples Quadrangle Rectangle
Pen class instance VariableNames:
Figure 9.7
100 000
169 9.2 Messages to a Class versus Messages to an Instance
example. The selection of browser menu item class, category examples, and message selector example is shown in Figure 9.9a.
Collections-t Collections-:: Graphics-Prir Graphics-Dis 1
Spline class i η 51 a. n c e V a ri a b I e (\J a m e s: "
Figure 9.8
100 000 Collections-Streai Circle Collections-Suppol Curve Graphic s -Prirnit i ν a Line Graphics-Display I LinearFit G ra ρ h i c s - V ί e w s G raphics-Edit ο r s
^example "Designate points on the Path by clicking the red button. Terminate by pressing any other button, A curve will be displayed, through the selected points, using a square black form."
Figure 9.9a
100 000
| spline Curve a Form f la. g| a Form *- Form new extent: 8@8. a Form black. spline Curve *• Spline new. splineCurve form: a.Form. flag «- true, TflacH while True:
170 Finding Out About System Classes
The text subview now contains the definition of an example use of Splines. Read the comment to learn how to use the example. Now scroll to the end of the code and find text for the expression Spline example Select the expression and then choose the yellow button command do it so that you can try the example (Figure 9.9b).
C ο 11 e c t i o n s - S t r e a l C ι re I e G ο 11 e c t i ο η s - S υ ρ ρ ol C u r ν Θ G ί'δ. ρ h i c s - Pri m i t i ν a Line Graphics-Display I LinearFit Graphics-Views Graphics-Editors ifFalse: [flag«-false]]. s ρ I i η e C υ r ν e c ο m ρ u t e C u r ν e, spline C u r ν e i s Ε rn ρ t y ifFalse: [splineCurve displayOn: Display S e η s ο r w a i t Μ ο Β u 11 ο η t spline Curve
Figure 9.9b
pnn^it acceρt cancel format spawn explain
010 According to the documentation included in the method, you point to several places on the screen by moving the cursor and clicking the red button (Figure 9.9c); you terminate by clicking either the yellow or blue button. The result is a curve computed using the algorithms of the spline (Figure 9.9d). This example had the side effect of leaving marks about the screen. Choose the System Menu command restore display to clean things up. Explore other graphical objects and try the examples.
171 9.2 Messages to a Class versus Messages to an Instance
Gollections-StrQaj Circle C ο 11 e c t i ο η s - S υ ρ ρ οι C u r ν e Gr aρhics-Prirnitivel Line Graphics-Display I LinearFit Graphics-Views G r a p h i c s-Edit ο r s ifFalse: [ f l a g * - f a l s e ] ] . splineCurve computeCgp/e. • s ρ I i η e C υ r ν e i s Ε rn ρ t y ifFalse: [splineCurve display On: Display, Sensor w^cNoButton], t splineCurve
Figure 9.9c
KB 000 Collections-Strea C ο 11 e c t i ο η s - S u ρ ρ ο Graphics-Primitive Graphic s - D i s p l a y Graphic s - V i e w s Graphics-Editors ifFalse: [flag«-false spline C u r ν e c ο rn ρ υ t e s ρ line C u r ν e i s Ε rn ρ t ifFalse; [splineOBrye displayOn Sensor •t-splineCurve
Figure 9.9d
100 000
•
172 Finding Out About System Classes
9.3 Browser Menu Commands
A yellow button menu can be accessed in each subview of the browser. The menus were illustrated in Figure 9.2. The use of each command is summarized in this and in the following sections. There are three commands common to the four subviews containing list menus. These are commands for creating a file containing a version of the selected descriptions readable by the Smalltalk-80 interpreter (file out); for creating a file containing a human readable, well-formatted version of the selected descriptions (print out); and for creating a browser for a subpart of the system (spawn). In the Xerox systems, the command print out also creates a hardcopy version of the file.
Class-Category Menu Commands
file out
Creates a file whose name depends on the current menu selection. The file contains a Smalltalk-80 readable version of the descriptions of the selected item (classes in a category, single class, methods in a class protocol, or single method).
print out
Creates a file whose name depends on the current menu selection. The file contains a human readable ("prettyprinted") version of the descriptions of the selected item. (In a non-Xerox version of the system, this command may be identical to file out.)
spawn
Creates a browser in which only the classes included in the selected category can be accessed.
There are five additional commands in the menu of the class-category subview that pertain specifically to modifying the class categories. file out
Creates a file whose name is the selected class category, followed by a period and the characters St. The file contains a Smalltalk-80 readable version of the descriptions of the classes in the selected category.
print out
Creates a file whose name is the selected class category. (In the Xerox system, the name is followed by a period and the characters press.) The file contains a human readable ("pretty-printed") version of the descriptions of the classes in the selected category.
spawn
Creates a browser in which only the classes included in the selected category can be accessed.
173 9.3 Browser Menu Commands add Category
Adds a new item to the class-category menu. When you choose this command, a prompter appears in which you type the category name. Choose the yellow button command accept, or type the "carriage return" key, to indicate that you are finished typing. The new category name is inserted before the current selection, and then becomes the current selection. If no item is selected when this command is chosen, then the new category is added at the end of the menu.
rename
Changes the name of the currently selected category. A prompter appears in which you edit the category name. Choose the yellow button command accept, or type the "carriage return" key, to indicate that you are finished typing.
remove
Removes the currently selected category of classes from the system. If there are any classes classified under the selected category, a confirmer appears to make certain that you wish to remove all the classes from the system. Choose yes if you do, no if you do not.
edit all
Displays the category names and message selectors in each category in the text view of the browser. The categories into which the classes are sorted can be changed using the text editor (see Section 12.6).
Update
Makes certain that the classes viewed by the browser contain the latest information about these classes. This command is needed if new class descriptions are created outside this browser, for example, they are created by reading an external file, or by evaluating an expression, or by using a different browser. Such classes are categorized in a category not currently displayed in the browser.
When no class category is selected, the yellow button menu only contains the items add category, update, and edit all.
Class-Name Menu Commands
Commands in the yellow button menu for the class-name subview add queries you can make about the class—its position in the class hierarchy, a comment about the class, its definition, and its message categories. If no class name is selected, then the browser subview flashes to indicate that no yellow button menu items are appropriate. file out
Creates a file whose name is the selected class, followed by a period and the characters St. The file contains a Smalltalk-80 readable version of the description of the class.
174 Finding Out About System Classes
print out
Creates a file whose name is the selected class. (In the Xerox system, the name is followed by a period and the characters press.) The file contains a human readable version of the description of the class.
spawn
Creates a browser in which only the description of the selected class can be accessed.
spawn hierarchy
Creates a browser for the superclasses of the selected class, the selected class itself, and its subclasses, in hierarchical order.
hierarchy
Displays the names of the superclasses and subclasses of the selected class in the text view of the browser. The names are indented. A subclass name appears indented from the name of its superclass. Instance variable names declared in a class appear in parentheses after the class name.
definition
Displays the definition of the selected class in the text view of the browser. This definition can be edited. If you choose the yellow button command accept, the modified definition will be evaluated. In doing so, you can change the definition of the selected class; the system will recompile each method in the class and report any errors if previously declared variables are now undeclared. You can change the category of the class by editing the category name in the definition. The class-name menu will change appropriately. If you edit and change the class name of the definition, you can create a new class or modify one other than the selected class.
comment
Displays the current comment about the selected class in the text view of the browser. There is a default comment, namely This class has no comment, that appears when a more appropriate comment has not been provided. Edit the comment and choose the yellow button command accept to restore it.
protocols
The message categories or protocols into which the messages of a class are sorted can be changed. When you first create a class, no message categories are defined. You must add a category before you can define a method. Modifying message protocol is described in Chapter 11.
inst var refs
Displays a menu of the instance variables of instances of the selected class. Since instance variables are inherited, the menu shows the variables declared in each superclass, in alphabetical order; a line separates variables declared in each class. If you choose one of the items in the menu, a
175 9.3 Browser Menu Commands message-set browser, as described in Chapter 10, is created for all methods that refer to the selected instance variable. ClaSS var refS
Displays a menu of the class variables of instances of the selected class. Since class variables are inherited, the menu shows the variables declared in each superclass, in alphabetical order; a line separates variables declared in each class. If you choose one of the items in the menu, a message-set browser, as described in Chapter 10, is created for all methods that refer to the selected class variable.
ClaSS refS
Creates a message-set browser, as described in Chapter 10, for all methods that refer to the selected class.
rename
Changes the name of the selected class. A prompter appears in which you type the new class name. Choose the yellow button command accept, or type the "carriage return" key, to indicate that you are done typing. Creates a message-set browser on all methods that refer to the class.
remove
Removes the selected class from the system. When you choose this command, a confirmer will appear so that you can verify that you really want to carry out this destructive command. There is no "undo" command for retrieving removed classes.
Illustrations of some of the commands summarized above are given in the next sequence of figures. Figure 9.10a shows that class Pen is select-
ollections-i Collections-i Graphics-C'is Graphic 5-Pa 1 Graphic 5-Vie Graphics-Edi
Point Quad F;pr:r=JspavvTi hierat
subclass: # P e n i n s t a n c e VariableNar c I a s s V a r i a b I e Ν a. m e s: poolDictionaries: " c a t e g ο r y: ' G r a p h i c s -
Figure 9.10a
foio
176 Finding Out About System Classes
ed and that its hierarchy is to be displayed; Figure 9.10b shows the hierarchy. Figures 9.10c and 9.10d show a comment about class Pen.
Graphics-views Graphics-Editors
initiali:e-release accessing coloring moving geometric designs
Object () Bit Bit ('destForm' 'sourceForrn' 'halftoneForm' 'combination Rule' 'destX.' 'destY' 'width' 'height' 'sourceX' 'source'/' 'clipX' 'clip'/' 'clipWidth' 'clipHeight' ) Pen ('frame' 'location' 'direction' 'penDown' )
Figure 9.10b
000 Collections-S Collections-:: ISI9EISI3lfBEB39f
Graph ics-D is Graphic s-Pa.' Graphics-Vie Graphics-Edi
Object () Bit Bit ('destForm' 'so ' d e s t X ' 'destY' ' w i d t h ' 'PIULJIIL 'clipWidth' 'clipHeight' )
e F ο r m' ' c ο m b Ί η a t Ί ο η Fi u I e' sourceY' 'clipX' 'clipY'
Pen ('frame' ' l o c a t i o n ' ' d i r e c t i o n ' ' p e n D o w n ' )
Figure 9.10c
Oio
177 9.3 Browser Menu Commands
Collections-:: Collections-:: Graphics-Dis Graphics-Pa 1 Graphics-Vie Graph ics-Edi APens
Figure 9.10d
Point Quadrangle
Rectangle
initialise-release accessing coloring moving geometric designs
can scribble on the screen, drawing and printing at any angle.
000 Section 9.4 illustrates the spawn commands. Examples for commands inst var refs, class var refs, and class refs are given in Chapter 10 in which message-set browsers are explained. And the command rename is examined in Section 12.2.
Message-Ca tegory Menu Commands
The three common file and print commands appear in the yellow button menu of the message-category subview of the browser. In addition, commands that modify the message categories or protocols are provided. They are further explained in Chapters 11 and 12. file out
Creates a file whose name is a concatenation of the selected class and message category, followed by a period and the characters st; spaces are replaced by hyphens. The file contains a Smalltalk-80 readable version of the description of the methods in the selected message category of the selected class.
print out
Creates a file whose name is a concatenation of the selected class and message category. (In the Xerox system, the name is followed by a period and the characters press; spaces are replaced by hyphens.) The file contains a human readable version of the descriptions of the methods in the selected message category of the selected class.
178 Finding Out About System Classes
spawn
Creates a browser in which only the description of the selected category of messages for the selected class can be accessed.
add protocol
Adds another message category to the message-categories menu. A prompter appears in which you type the new name. The name is inserted before the currently selected category and then becomes the current selection. If no item is selected in the menu when this command is chosen, the new category is added at the end of the menu. If you type a name that already exists, it is moved to a new location (either before the current selection or at the end of the menu).
rename
Changes the name of the currently selected message category. A prompter appears in which you type the new name. If you type the name of a category that is already in the menu, no change happens.
remove
Removes the selected message category from the menu. If any messages are classified under this category, a confirmer appears to verify that you want to remove the messages from the system.
If no item is selected in the message-categories subview, then only the command add protocol is in the yellow button menu.
Message-Selector Menu Commands
Commands in the yellow button menu for the message-selector subview add queries you can make about methods and messages. file out
Creates a file whose name is a concatenation of the selected class and message selector, followed by a period and the characters st; spaces and colons are replaced by hyphens. The file contains a Smalltalk-80 readable version of the description of the method for the selected message selector.
print out
Creates a file whose name is a concatenation of the selected class and message selector. (In the Xerox system, the name is followed by a period and the characters press; spaces and colons are replaced by hyphens.) The file contains a human readable version of the description of the method for the selected message selector.
spawn
Creates a browser in which only the description of the selected message for the selected class can be accessed.
senders
Creates a message-set browser for all methods in the system in which the selected message is sent.
179 9.3 B r o w s e r M e n u C o m m a n d s Creates a message-set browser for all methods in the entire system which implement the selected message. Creates a menu of the message selectors for each message sent in the currently selected method. If you then choose one of these selectors, you create a message-set browser on all of its implementors. ΓΤΙΟνθ
Moves the selected message to another message category. A prompter appears in which you type the name of the designation message category. If it already exists, the message is reclassified. If the designation message category is new, it is added to the message-categories menu, at the end. The current message category remains the current selection. You can also type the name of a class and a protocol in order to copy the selected message to a different class. The syntax is className > protocolName. (If you type the class name of the currently selected class, the result is the same as though you did not mention the class name.)
remove
Removes the selected message from the selected class. A confirmer appears so that you can verify that you really want to carry out this destructive command. There is no "undo" command for retrieving removed messages.
The commands senders, implementors, and messages are explained in more detail in Chapter 10. Examples of modifying the protocols of a class are given in Chapter 11.
Text Subview Menu Commands
The yellow button menu for the text subview of the browser contains the text editing commands presented in Chapter 3 (again, undo, copy, cut, paste) and the expression evaluation commands of Chapter 6 (do it, print it). There are five additional commands. format
The system has some notion of how to format a method so that the indenting and line breaks increase the human readability of the code. Choosing this command when the text view contains a method (that you have retrieved but have not modified as yet), creates a "pretty-printed" version of the code. You can then modify it to suit your own style.
accept
In the context of a method, this means "compile" the code. If there are any syntax errors, display them; if not, the compiled method is stored into the system. In the context of a class definition or comment, the text is an expression that is evaluated. In the context of categories, the syntax is checked and the new categories stored.
180 F i n d i n g O u t A b o u t S y s t e m Classes Cancel
Text that appears in the subview has presumably been modified but you do not want to retain the modification. The text is replaced by the version prior to any modification. The commands accept and cancel work as pairs — cancel returns the text to the version last stored using accept.
Spawn
Creates a browser for the currently selected message and the current version of the method (which possibly has been modified but not stored). The text in the original browser will be restored as though you had chosen the cancel command. The text in the new browser is not yet accepted as the compiled method.
explain
The text in a method consists of a sequence of tokens, for example, syntactic entities such as Τ and ], and variable names. Select one. The result of choosing the command explain is to determine a comment that explains the use of the selected token. The comment is inserted into the text, after the token. It becomes the selected text.
Π Spawning a Message Browser As noted in the summary of commands, a way to create a browser on a single message is to choose the command spawn from the yellow button menu of the text subview of a browser. Suppose you have been editing a method, you have not yet saved the method by choosing the command accept, and then you decide that you want to put aside your work for awhile in order to explore the previous version of the method or to search in the browser for other information. Choose the spawn command. You are asked to designate a rectangular area for a browser for the currently selected message, with the edited text as the method. The text in the original browser will be restored as though you had chosen the cancel command. The text in the new browser is not yet accepted as the compiled method. You might also use spawn to copy a view of a method onto the screen while you use the full browser to find other information. Any browser view of a method in which the editor is available can be used to change the method and then to recompile and re-store it. Changes made to a method in any view are shared by the whole system (although you might have to specifically request an update to see shared changes). In the next figure, the text in the Pen method hilbertside: has been edited from the original (Figure 9.11a). Spawning causes the original method to show in the system browser and the edited version shows in a newly created message browser (Figure 9.11b). Note that the difference is in the formatting of the visible conditional statement.
181 9.3 Browser Menu Commands
Collections-Strea Collections-Suppo Point G ra ρ h i c s - D i s ρ I a y Quadrangle Graphic;-Pat h i RectanqlQ Graphics-view. 1 : Graphic 5-Editor":·
«iranniwaiifnuiaa
initialize-release accessiηg c ο Ι ο ri η g moving
™"™"»
A Hubert curve is a space-filling curve,"
Figure 9.11a
Dio
η = υ ifTrue: [τself t u r n : 1 8 0 ] , η > 0 ifTrue: [ a *- 9 0 , m <- η - 1] ifFalse: [ a *• - 9 0 . m *• η + 1 ] , self t u r n : a. self hilbert: 0 - m side: s, self t u r n : a. self hilbert: 0 - m side: s. self t u r n : a; go: s, self hilbert: m side: s.
dragon: filbertsiside: hilberts: mandala:dia meter spirahangle:
agaιη undo cορy cut ρaste do it print it accept cancel
S y s t e m Β ro w s e r I collect icms-Strea Collect ion s-Suppo Graphics-Display Graphics-Paths Graphics-Views Graphic s-Editors
Uuiiii Point Quadrangle Fi e c t a n g I e
hi|bert: η side: s "Draws an n t h lever Hilber A Hilbert curve is a space-fillii
η = υ ifTrue: [ t s e l f turn: 1 η > 0 ifTrue:
Figure 9.11b
000
[ a - 90, m *- η - 1 ] ifFalse: f a «- - 9 0 ,
hilbert: η side: s "Draws an n t h lever Hilbert curve d i r e c t l y into t h e display bitmap, A Hilbert curve is a space-filling curve."
η = U ifTrue: [ t s e l f t u r n : I S O ] , η > Ο ifTrue: [ a «- 9 0 , m <• η - 1] ifFalse: [ a *• - 9 0 . m *- η + 1 ] , self t u r n : a. self hilbert: Ο - m side: s, self t u r n : a, self self self self self
hilbert: 0 - m side: s. t u r n : a; go: ••,. hilbert: m side: s, t u r n : 0 - a; go: s; t u r n : 0 - a. hilbert: m side: s,
182 Finding Out About System Classes
Q Explanations There are several views in the system in which methods are retrieved and displayed, including the system browsers and the debugger. The yellow button menu in the text part of these views includes the command explain. You can choose this command to receive an explanation about a syntactic or semantic part of the method. The command explain works by examining the current text selection and determining what role the text plays in the method. The text selection must be a single token (such as a period, message keyword, or variable name) or a syntactic construct (that is, a single-quoted, or doublequoted sequence of characters, or characters delimited by square brackets). In Figures 9.12a and 9.12b, an explanation is requested and received for the left-arrow («-). The explanation is inserted after the current text selection and then becomes the text selection. The most significant explanation is for a single token that is a variable name or a message selector. The explanation will identify where the variable is declared, i.e., global, instance, class, or pool, and in which classes the message is defined, respectively. In Figures 9.13a and 9.13b, an explanation for the global variable Sensor is requested and received; it is an instance of class InputSensor. In Figures 9.14a and 9.14b, an explanation for the class name Form is obtained. Typically the explanation is a comment, but, in some useful cases, it is an expression that can be evaluated in order to obtain further information. For example, if the token selected is a class name, then the explanation is a comment and an expression that can be evaluated in order to create a browser for just that class. The result of choosing do it when the explanation is selected (Figure 9.14c) is to create a browser for class Form (Figure 9.14d). The best way to learn about explain is to try it. Once you learn how to use a browser and can retrieve a method, simply make selections of parts of the method and select the yellow button command explain. If no explanation is possible, it will say so.
183 9.3 Browser Menu Commands
Collect i o n s - S t r e a j Collect ion s-Suppol| Point G ra ρ h i c s - D i s ρ I a y I Q.u a. d r a n g I e G ra ρ h i c s - Pa t h s I R e c t a n q I e G re. ρ h i c s - V i e w s | Graphics-Editors
initialize-re lease I direction
^B^^SBSHHHI frame
coloring_ moving again location geomet undo gns sourceForm: width: copy cut frame: aRectangle paste "Set the rectangle in which the receive do it a w," print it frame Q aRectangle. acceρt self clipRect: aRectangle cancel
Figure 9.12a
Oio initialize-relea.se G ra p h ι c s - D ι s ρ I a y I Q.u a d ra η g I e G ra ρ h i c s - Pa t h s I R e c t a n g I e Graphic s-View s Graphics-Editors
direction f ra m e
coloring location rn ο ν i η g geometric designs sourceForm: width:
f r a m e : aRectangle
"Set the rectangle in which the receiver can draw," frame 4 aRectangle. self clipRect: aRectangle
Figure 9.12b
Doo
184 Finding Out About System Classes
ollections-Strea C oils c t i ο η s - 3 u ρ ρ ο G r a p h i c s - Pri m i t i ν e G r a. p h i c 5 - D i s ρ I a y Graphics-Views Graphics-Editors splineCurve *· Spline new. splineCurve form: a Form, flag *• true, [ f l a g ] while Τ rue:
Figure 9.13a
010
do it print it cept cancel
S e η s ο r re d B u t t ο η Pre s s e d if True: [splineCurve add: Sensor \ ••aitButton. S e η s ο r w a i t Ν ο Β u 11 ο η. a Form display On: Display a t : splineCurve l a s t ] ifFalse: [ f l a g ^ f a l s e ] ] , spline C u r ν e c ο m ρ u t e C u r ν e .
Collections-Strea Collections-Suppo Graphics-Primitive Graphics-Display Graphics-Views G r a p h i c s -Edit ο r s splineCurve *- Spline new. splineCurve form: a Form, flag «• true, [ f l a g ] whileTrue: [ Seηsοr w a i t Β u 11 ο η. Sensor r e d B u t t o n P r e s s e d Λ if Τ rue: [ s ρ I i η eC υ rν e a d d: S ens ο r w a i t Β u 11 ο η, S e η s ο r w a i t Ν ο Β υ 11 ο η.
Figure 9.13b
000
a. Form display Ο1 η: Display a t : splineCurve l a s t ] ifFalse:
185 9.3 Browser Menu Commands
C o l l e c t i o n s - S t r e a i Circle C ο 11 e c t i ο η s - S υ ρ ρ oj C υ r ν e G r a ρ h i c s - Pr i m i t ί ν a Li η e Graphics-Display I LinearFit Graphics-Views Graphics-Editor
splineCurve a Form flat a Form *• QQQ new extent: 8@8. a Form black. splineCurve «- Spline new, splineCurve form: a F ο r rn. flag *• true, [ f l a g ] while Τ rue: [Sensor "is a global variable, w a i t But ton.
Sensor is an InputSensor"
S e η s οr re d Buttο η Pres s e d if True:
Figure 9.14a
C o l l e c t i o n s - S t r e a l Circle C ο 11 e c t i ο η s - S υ ρ ρ ο I C u r ν e G ra ρ h i c s - Pr i m i t i ν a Line Graphics-Display I LinearFit Graphics-Views Graphics-Editors
splineCurve a Form fla a Form *· Form
new e x t e n t : 8@8. a Form black. splineCurve *• Spline new, splineCurve form: a Form, flag *· true, [ f l a g ] while Τ rue: rSensor "is a alobal variable.
Figure 9.14b
Sensor is an InoutSensot
186 Finding Out About System Classes
Collections-Streai Collect ions-Suppo Graphics-Primitive Grap hί c s - D is pi a y
U ire Ι θ Curve Line LinearFit
Graphics-Views Graphic s-Editors
| splineCurve a Form f l a a Form *· Form;
Figure 9.14c
010
new e x t e n t : 8@8. print 11 a Form black. a. c c e ρ t splineCurve «- Spline ne cancel s ρ I i η e C υ r ν e f ο r m: a F ο r rn format spawn flag *• true, explain [ f l a g ] while Τ rue; "is a global v a r i a b l e . Sensor is a n IrmutSensor"
initialize — re I e a. s e accessίηg cορyiηg disρIayiηg D i s ρ I a y Μ e d ί u m s u b c I a s s: # F ο r m i n s t a n c e V a r i a b l e N a r n e s : 'bits w i d t h height o f f s e t d a s s V a r i a b I e Ν a m e s: ' Ο η e Β i t F ο r m ' poolDictionaries: " c a t e g ο r y: ' G r a ρ h i c s - D i s ρ I a. y Ο b j e c t s' W
Figure 9.14d
?
BOD
1
187 9.4 Browsing a Subset of the System
9.4 Browsing a Subset of the System
As noted in the previous sections, in each of the browser subviews containing list menus, the yellow button menu includes the command spawn. Choosing this command creates a browser for accessing a subset of the information available from the system browser. In particular, you can create a System Category Browser by choosing the command spawn in the yellow button menu of the class-categories subview (Figures 9.15a and 9.15b). This browser gives you access to all the classes within the currently selected class category only.
u b c I a 5 s: # f\l a m e Ο f CI a s s b Ν a m e 5: ' i η 51V a r"N a m e 1 inst V a rN a m e 2' c I a 5 5 V a ri a b I e Ν a rn e s: ' CI a s s V a rΝ a m e 1 CI a s s V a rN a m 9 2' poolDictionaries: " c a teg ο ry: ' G ra ρ h i c s - Pri m i t i ν e s'
Figure 9.15a
ioio
188 Finding Out About System Classes
Pen Point Quadrangle Fi e c t a. n q I e NameC
instance Ν a rn e 0 f S u ρ e re I a. s s s υ b c I a. s s: # Ν a rn e 0 f CI a s s i η s t a. n c e V a ri a. b I e Ν a rn e s: 'in s t V a rN a. rn e l i η s t V a rN a m e 2' e I a. s s V a ri a. b I e Ν a m e s: ' CI a s s V a rN a. m e 1 CI a. s s V a. rN a rn e 2' poolDictionaries: " c a t e g o r y : ' G r a ρ h i c s - Ρ r i rn i t i ν e s'
Figure 9.15b
000 You can create a Class Browser by choosing the command spawn in the yellow button menu of the class-names subview (Figures 9.16a and 9.16b). This browser gives you access only to the description of the currently selected class.
initialize-re lease ssing ring
Graphics-Di; Graphic 3-Pa 1 Graphic s- Vie Graphic s-Edi A
9trie designs
BitBlt subclass: # P e n i η s t a n c e V an a b I e Ν a class Variable Ν a me s inst v a r refs class v a r refs ρ ο ο ID i c ΐ i ο η a ri e s: " class refs c a t e g o r y : 'Graphics rename remove
Figure 9.16a
ΟΪ0
on direction ρ en Down '
189 9.4 Browsing a Subset of the System
A
BitBlt subclass: # P e n i η s t a nee V a r i a b I e Ν a m e s: 'f r a m e I o c a t i ο η d i r e c t i ο η ρ e η D ο w η ' c I a s s V a ri a b I e Ν a rn e s: " poolDictionaries: " It c a teg ο ry: ' G ra ρ h i c s - Pri rn i t i ν e s'
Figure 9.16b
000 You can create a Message Category Browser (or "protocol browser") by selecting the command spawn in the yellow button menu of the message-categories subview (Figures 9.17a and 9.17b). This browser gives
Collections-Streaj C ο 11 e c t i ο η s - S u ρ ρ ο|| Point
1
Graphics - P a t h s Graphics-Views Graphics-Editors message s e l e c t o r and a r g u m e n t names " c ο rn rn e η ΐ s t a t i η g ρ u r ρ ο s e o f rn e s s a g e" | t e m p o r a r y v a r i a b l e names | s t a t e rn e η t s
Figure 9.17a
ioio
own lillln:
190 Finding Out About System Classes
Graphic; Graphic; down Graphic: fillln: Graphic: go: goto: rn e s s a g e h ο rn e "con message s e l e c t o r and argument η a me? "comment s t a t i n g purpose of message" | t e m p o r a r y v a r i a b l e names | s t a t e rn e η t s
Figure 9.17b
000 you access only to the methods of the currently selected category of messages. And you can create a Message Browser by selecting the command spawn in the yellow button menu of the message-selectors subview (Figures 9.18a and 9.18b). This browser gives you access only to the method of the currently selected message. The purpose in providing so many optional views of the system classes is to support your ability to constrain the information with which you are working. You might, for example, be developing an application class and prefer to have a browser that only accesses this one class. You might be copying code from classes in one category into your new class, and thus you might find it convenient to focus your attention by having a class-category browser for this category. More signficantly, you might create an applications/programming environment in which you want your user to have access to a subset only of the system, to protect the user from dealing with too much extraneous information, or to protect the system from the user.
191 9.4 Browsing a Subset of the System
Collections-Streal Collections-5uppo[ Point Quadrangle
initialize-rel acces5iηg coloring
goto: home north place; h '
u r a ρ hies -View s Graphics-Editor; turn: degrees "Change the direction t h a t the receiver f a c e ; by an a mo to the argument, degrees." direction *· (direction + degrees) \\ 3 6 0
Figure 9.18a
tile out send^fs implementors messages mονe re m ο ν e
ioio Collect ion s-S Collect ions-S Graphic s-Disp Graphics j Graphics Graphics turn: dec "Cha to the a direc
Figure 9.18b
ooo
:
degrees
"Change the direction t h a t the receiver faces by an amount egual to the argument, degrees," direction *• (direction + degrees) V\ 360
192 Finding Out About System Classes
Class Hierarchy Browser
Another interesting browser that you can spawn is a Class Hierarchy Browser. This browser gives you access to a class, its superclasses, and its subclasses. You create a class hierarchy browser by choosing the yellow button command spawn hierarchy in the class-names subview of a system browser (Figure 9.19a). The class-names menu of the new browser will consist of the names of the superclasses of the selected class, the selected class itself, and its subclasses, in hierarchical order. An example of a class hierarchy browser for Boolean, which is a subclass of Object and has two subclasses, True and False, is shown in Figure 9.19b. An example of a class hierarchy browser for Collection is shown in Figure 9.19c.
Kernel-Class Kernel-Meth Kernel-Proce Kernel-Supp Interface-Fr.
logical operations trolling ying ting
s.rchy definition £>bject subclass: #Bool comment i η s t a n c e V a r i a b I e Ν a protocols c I a s s V a r i a b I e Ν a rn e:inst var refs class var refs poolDictionaries: " class refs c a t e q ο r y: ' Κ e r η e I - <. rename re m ο ν e
Figure 9.19a
OiO
193 9.4 Browsing a Subset of the System
System Browser I logical cDeration; logical operations controlling cορyiηg ρ ri η t i η g
^Object subclass: #Boolean i η s t a n c e V a ri a b I e Ν a. m e s: " c I a s 5 V a ri a. b I e Ν a m e s: " ρ ο ο ID i c t ί ο η a ri e s: " c a t e g ο r y: ' Κ e r η e I ~ Ο b j e c t s'
Figure 9.19b
accessιηg t e s 11 η g adding removing converting private Object subclass: # u o l l e c t i o n i η s t a. n c e V a. ri a. b i e Ν a. m e s: " c I a. s s V aria, b I e Ν a. m e s: poolDictionaries: " c a. t e g ο r y: ' C ο 11 e c t i ο η s - A b s t r a c t '
Figure 9.19c
Finding Out About Messages and Methods
10.1 Which Methods Send a Particular Message? 10.2 Which Classes Implement a Particular Message? Renaming a Message Selector 10.3 Which Messages are Sent in a Particular Method? 10.4 Which Methods Reference a Particular Variable or Literal?
196 Finding Out About Messages and Methods
Message-set Browsers provide a way of collecting and exploring a group of related messages. The name reflects the idea that the response to the query is a set of methods. Since a method is specified by a class and a message selector, these sets are viewed as a set of class/message pairs. This kind of browser makes it possible for you to inspect and modify the methods associated with each pair. A message-set browser consists of two subviews. The top subview is a fixed list menu that indicates the names of the class/message pairs. When you choose one of the pairs, the associated method is displayed in the bottom subview. This bottom subview is a text subview in which you can edit the method and then choose the command accept to compile and store the changes. Message-set browsers are created in order to answer one of three kinds of queries about messages: • Which methods send a particular message? • Which classes implement a particular message? • Which messages are sent in a particular method? These queries can be made in a system browser by choosing the yellow button commands senders, implementors, or messages, respectively, in the message-selector subview. These are useful browsers to employ when you are tracking down erroneous behavior in your programs, or when you are interested in trying to find out how a message is used or implemented in the system. For example, the combination of examining the hierarchy of a class and of browsing all implementors of a message defined in that class, helps identify where the method for that message is actually found by the interpreter during execution (in the class or in one of its subclasses or superclasses).
10.1 Which Methods Send a Particular Message?
Choosing the command senders creates a message-set browser for all methods in the entire system in which the selected message is sent. If no such methods exist, then the word Nobody appears in the System Transcript (if the transcript is a scheduled view and is not collapsed). Suppose that you wish to understand how a particular message is used in the system. You can select the message in a class browser and read the comment. This will tell you the intended use of the message. You can then see examples of how to use the message by creating a message-set browser on all senders of the message. The next sequence of figures illustrates the steps: selecting a message in a class browser (Figure 10.1a), then choosing the command senders (Figure 10.1b).
Τ
197 10.1 Which Methods Send a Particular Message?
Numenc-Magn Numeric-Number
llectionj accessing testing eable removing enumerating printing
add All:
add: newObject "Include η e w Ο b i e c t a s ο η e of t h e r e c e i ν e r' s e I e m e η t s, Α η s w e r η e w Ο b i e c t, Τ hi s m e s s a g e s h ο υ I d η ο t be sent to i η s t a. n c e s ο f s υ b c I a s s e s of A r r a y e d C ο 11 e c t i ο η." self s u b c I a s s Fi e s ρ ο η s i b i I i t y
Figure 10.1a
100 000 Collect ions-Seque Collect ions-Text Collect ions-Array
removing enumerating printing
" Μ " ι τ " add: newObject "Include newObiect as one of the receiver's elements
] remove newObject, This message should not be sent to iristarrwsT-eiT""—
s u b c I a s s e s ο f A rra y e d C ο 11 e c t i ο η,"
A
self s υ b c I a s s Fi e s ρ ο η s i b i I i t y
Figure 10.1b
Dio
198 Finding Out About Messages and Methods
N u m e r i c - M a g n i t u Bag sortedcourits N u m e r i c - N u m b e r s Β a. g s ο r t e d ΕI e m e η t s Β e h* a ν i ο r a c c u rn u I a t e I n s t V a. rN a m e s: t ra ν e rs e d CI a s ses: C ο 11 e c t i ο ri s - U η ο rΒ d e h a ν ί ο r a. d d S u b c I a s s: C ο II e c t i ο η s - SequtΒ e h a. ν ί ο r a. 11A c c e s s e s Τ ο: CollectionsCollectionsadd: newOb "Include new Ob Ρ subclass self sub
Figure 10.1c
000 b y stem Brov Numeric-Ma Numeric-Nur
CI a. s s D e s c rip t i ο η s u b c 1 a. s s Of: ο 1 d C1 a s s; i η s t a n c e V a ri a b 11 Collect ion asBaq fc Collection a.sSet Collection class w i t h : C ο 11 e c t i ο ri c 1 a. s s w i t h: w i t h:
CollectionsC ο 11 e c t i ο η s Collections-Text addAII: dCollectiOn Collect ion s-*rra> "Include all the elements of aCollPcticm as the receiver's elements. add: newObject a Collection," "Include n e w 1 new Object. 1 subclasses oi self subclassl
Figure 10. Id
100 000
Answer
a.Collection do: [:each | self ^ Q each], ta Collection
r
199 10.2 Which Classes Implement a Particular Message
This gets the message-set browser (Figure 10.1c). Then choose one of the class/message pairs to see a method in which the message is used (Figure 10. Id).
10.2 Which Classes Implement a Particular Message?
Choosing the command implementors creates a message-set browser for all methods in the entire system which implement the selected message. If no such methods exist, then the word Nobody appears in the System Transcript (if it is scheduled and displayed on the screen). An example of finding all the implementors for the message selector add: is shown in Figures 10.2a and 10.2b.
Numeric-Mag nit υ Ν u m e ri c - Ν u m b e rs I A rra y e d C oils c ta.i ο cη c s 5; ι η g Collection5-Abstn Collection -Unordi S e q u e η c e a, b I e C ο I •Jollection - S s q u e re m ο ν ι η g Collect ion - Τ e χ t enum era. t i n g 'LOllect ion printing
add: newObject "Include n e w O b j e c t as one o f t h e receiver':, element.-, n e w O b j e c t , Τ hi·; me." sage should n o t be sent t o i n s t a n 3 u b c I a s s e s o f A r r a. y e d C ο 11 e c t i ο η." izlf
Figure 10.2a
Oio
subclassResponsibility
200 Finding Out About Messages and Methods
by stem Brov·, Ν υ me He-Mac Numeric-Nun" _: ο 11 e c t i ο ri s - L Joliections-:: Collections-Text Jollectioni-Arra·,
Collection add: Dictionary add; File D i r e c t o r y add: Ideηtit yDic tiοηary a dd Interval add: add: newObject •t self add: nevv'Obiec t
ithOc c urrenees:
add: nev/Object "Include newC new Object. Τ s υ b c Ι a. s s e s ο f self subcla.ssF
Figure 10.2b
100 000
Renaming a Message Selector
When you want to rename a message selector, you will find the commands senders and implementors very useful. Before renaming the message, you first find out if any subclasses exist that override the implementation of the message. You do this by choosing the yellow button command implementors in the message-selectors subview. This will give you a message-set browser that indicates which classes implement the message. Then you choose the yellow button command hierarchy in a class-names subview of a class browser. This will display the portion of the class hierarchy in which the selected class (the one that contains the message selector whose name you want to change) resides. If any of the subclasses of the selected class implement the message, you will have to rename them as well. In order to do the rename, first edit the original method in order to replace the message selector. Then choose the yellow button command accept. Now both the old and the new messages exist. Do the same for each subclass—you can do the editing in the message-set browser of the implementors. Second, select the message selector to be removed and then choose the yellow button command senders in the class browser message-selectors subview. This will give you a message-set browser on all methods that send messages with the old selector, unless none exist. Edit each method in which you wish to use the new message selector name. Close the message-set browser. Now choose the implementors command again, just to make certain that you found all the references
r
201 10.3 Which Messages are Sent in a Particular Method?
that have to be changed. If all are correctly changed, you can remove the old message in the class and in each subclass using the command remove from the yellow button menu of the message-selectors subview.
10.3 Which Messages are Sent in a Particular Method?
Choosing the command messages creates a menu of the selectors for each message sent in the currently selected method (Figures 10.3a and 10.3b). You can then select one of these in order to create a message-set browser on all of its implementors (Figures 10.3c and 10.3d). Notice that this menu is a list menu; it remains on the screen until you click a button. If you press the red button inside the menu area, you can select one of the menu items; when you release the button, the item is chosen. Like a pop-up menu, releasing the button outside the menu chooses no item. After clicking a button, the menu is removed from the screen.
C ο 11 e c t i ο η s - 'ό e q u 9 Collections-Text C ο 11 e c t i ο η 5 - A rra. y p o l l e d : aBlock "Evaluate aBlock w i t h each of the receiver's elementJ argument, (Jollect the resulting values into a collection t h a t is like the receiver, the new c ο 11 e c t i ο η. " | new Collection | new Collection *· self species new.
Figure 10.3a
Oio
self do: [:each | new Collect ίο η add: (aBlock value: each)], tnewCollection
Answer
202 Finding Out About Messages and Methods
System Browsgr ['• J υ m e ri c - Μ a g η i t u d] Γ-'.J u m e r i c - Ν u m b e r s I A r r a. y e d C ο 11 e c t i ο aη c c e s s ι η q t esΐ iηq Collect ions-Abstr; Collection lections-Unordi S e q υ e η c e a. b I e C ο I a d d i n g rernovinq I e c t i ο ri 5 - S e q υ e lections-Te^t lections-Array printing
™«™a
pollect: aBlock ado: " E v a l u a t e aBlock w i t h each of t h e receiver's elements as t blockCop· a r g u m e n t , Collect t h e resulting values into a c o l l e c t i o n t h a t is like t h e receiver, the n e w a. I u e: collection, "
Figure 10.3b
000
| newCoilectiori | n e w C o l l e c t i o r i - self s p e c i e s n e w , self d o : [ : e a c h | n e w C o l l e c t i o n a d d : ( a B l o c k v a l u e : e a c h ) ] , t η e w C ο 11 e c t i ο η
Numeric-Magnitu Ν υ m e r i c - Ν υ m b e r s I A r r a y θ d C ο 11 e c t iaοcηc e s s ι η g test i η q Co Gctions-Abstr; Co ection (Jollections-Unord ο e q u e η c e a. b I e < adding C ο 11 e c t i ο ri s - S e q υ e removing C ο 11 e c t i ο η s - Τ e ••• t printing Collect ions-Array
um-iitvi
detect: detect:ifNone do: inject :into: reiect:
collect: aBlock " E v a l u a t e a.Block w i t h e a c h of t h e receiver's elements as tjblockCo'ESyil a r g u m e n t , Collect t h e resulting values into a c o l l e c t i o n t h a t is like t h e receiver, the n e w collection, "
Figure 10.3c
100
| n e w C o l l e c t ion | newCollection *• self species new, self do: [:each | newCollection add: (aBlock value: each)] t newCollection
203 10.3 Which Messages are Sent in a Particular Method?
System Browser!
Implementors of add:
Numeric-Me.gnituc A r r 3 y e d (J o 11 e c t i o n add: Numeric-Numbers Ba.g add: Collection add: Collections-Unord D i c t i o n a r y add: add: C ο 11 e c t i ο η s - S e q υ FileDirectory e Collect ion ί Ο ο 11 e c t i ο η s - /
collect: aBloi "Evaluat argument, C resulting the new collect ίο
Figure 10.3d
000
| new (Jo newGolli self do: [ t ri e w C ο
The messages command is useful in trying to understand how a method actually works. It supports your ability to track down comments about the methods for each of the messages sent. Note that in the examples, the message blockCopy: appears as one of the messages in the selected method. This message is inserted by the compiler whenever a block is used in a method.
Q Practice Investigating Messages Using the system browser, choose class category Collections-Abstract (class-categories subview), choose class Collection (class-names Subview), and, in the class-names subview, choose the yellow button command hierarchy. The selections and hierarchy are shown in Figure 10.4. Collection is the top of a large hierarchy of data structures for the system. It is an abstract class, meaning no instances of it should be created. It serves the purpose of defining a common protocol for several similar classes, such as Set and OrderedCollection. Choose message category adding and then message selector add:. The method is defined as self subclassResponsibility. This means that subclasses of Collection for which instances can be created must reimplement the method in order to complete the description of the class.
204 Finding Out About Messages and Methods
ArrayedC n l l e r t i n a. c c e s s i η q maitJA<Mi testing :-i ο q υ e η c ea b l e Coli adding
Collect i 3 Γ -,Collect! nr sCollecti ΙιΓ sC ο 11 e c t i3 Γ s'• j ο 11 e c tJil Fr '•.iraphii.
i __, c1a ss
enumerating printing con verting
Ob j e e r [ )
": η 1
ΊΓ ) Ε ag ( - Li 1ι ΐ Ρ Γ ι ΐ ? ' ) f\ lappe dCollection ( 6 ο m a i ri ' m a. ρ' )
'c eqjer
Figure 10.4
100 000
ceableCollec t i o n
()
Arra v1 () EyteArray Compiledfvletho 1 () Fun Array ( r u n s ' '••, a I u e s' ) AltoFile A d d r e s : A r r a . ν i ' d i r e c t o r v '
Ί
Suppose you implemented the collection data structures and you want to find out whether all the subclasses of Collection are complete with respect to the message add:. One way to make this determination is to find all the classes that implement the message add: and see if all the subclasses of Collection are in the list. Some will not be, for example, class SequenceableCollection. This subclass is itself abstract. You can find where add: is implemented by choosing in the message-selectors subview the yellow button command implementors. The browser thus created is a message-set browser giving you a list of the classes in which the message add: is implemented. If you choose an item from this list, you can see the actual implementation. By selecting Collection in the browser and choosing the command hierarchy, you can determine all the subclasses of Collection to be compared to those referred to in the message-set browser. Find the message addAIIFirst: in class OrderedCollection. The class is categorized under Collections-Sequenceable; the message is categorized under adding. In the message-selectors subview, choose the yellow button command senders (Figure 10.5a). Watch the System Transcript; the word Nobody will appear (Figure 10.5b). This indicates that no objects in the system send the message; it was included for protocol completeness. (Recall that if no System Transcript appears on your screen, so that you can not try this example, you can create one by choosing the System Menu command system transcript.)
205 10.3 Which Messages are Sent in a Particular Method?
b y s t e m Τ ra n s c ri ρ t
j 11 e c: 11 ο η s - b υ ρ j
Γι ra phics-F'ri mi ti'
™*"™
ι
addAIIFirst: anOrderedCollection "Add each element of anOrderedCollection a t the of the receiver. Answer .anOrderedCollection."
ΓΙΊ ο ν e remove
ariOrdereduollection reverseDo: [:each | self addFirst: e a c h ] , tanC'rderedCollection
Figure 10.5a
Oio by stern Transcript Nobody
Linked List iollections-Te MappedC nllectic •1Ιΐ33ιΓι iollections-Arra Jollections-Stre o r t e d 1ect iοr
s
') ο 11 e c t i ο η s - S υ ρ |
iraphics-Prirniti addAIIFirst: anOrderedCollection ".Add e a c h e l e m e n t o f a n O r d e r e d C o l l e c t i o n a t t h e b e g i n n i n g of t h e r e c e i v e r . A n s w e r a. η Ο r d e r e d C ο 11 e c t i ο η," a n O r d e r e d C o l l e c t i o r i r e v e r s e D o : [ : e a c h | self a d d F i r s t : e a c h ] , τ a. η Ο rd e re d C ο 11 e c t i ο η
Figure 10.5b
ODO
206 Finding Out About Messages and Methods
10.4 Which Methods Reference a Particular Variable or Literal?
A message-set browser can also be obtained by sending one of several available messages to the object Smalltalk, an instance of SystemDictionary. All of the expressions listed in this section are present as templates in the System Workspace, so you can find them, edit the arguments, and evaluate the expressions. Smalltalk browseAIICallsOn: #keywordSymbol (where the keywordSymbol is a single keyword such as at:, put:, -f, or up) will create a message-set browser for all messages whose methods send a message with keyword keywordSymbol. The result of evaluating Smalltalk browseAIICallsOn: #add: is shown in Figure 10.6.
C1a s 3 D e s c r i ρ t ί ο η s u h c I a. s s Ο f: ο I d CI a s s: inst a n c e V a ή a b I e Ν a. m e 5 Collection a3Bag Collection as Set Collection class w i t h :
dddAII: aCollection "Include all t h e elements of aCollection as the receiver'. 1 : elements. A n s w e r aCollection,"
t a C ο 11 e c t i ο η
Figure 10.6
|00 000
207 10.4 Which Methods Reference a Particular Variable or Literal?
The
expression
Smalltalk browseAIICallsOn: #firstKeywordSymbol and: #secondKeywordSymbol creates a message-set browser for all messages in the system whose methods send a message with both keywords firstKeywordSymbol and secondKeywordSymbol. For example, the result of evaluating Smalltalk browseAIICallsOn: #at: and:
#at:put:
is shown in Figure 10.7. The messages browseAIICallsOn: and browseAIICallsOn:and: can be sent to individual classes to obtain a message-set browser for methods in the class and its subclasses.
Ι η ρ u t S e η 3 ο r c I a. 3 3 initialize Integer print On.1' a. s e: Μ eta. class name inEnvironment:3ub fc a s 3 0 f; a n d: i η s ΐ a n c e V a ri a Met a. class name in Ε η vironment:3ub : la. s 3 0 f: ί η 31 a n c e V a ri a b 1 e f\
at: anlndex put: anObject t do ma in at: (m a. ρ a t: a n I n d e χ
put:
anObject
I:;:;:::;:;:·:·:::::·: ::;:;·:;:::::;;::::::::::::;>::::::::: \\':\':\:]'·}::'\]'
]'•'·}' ·':'•
':[:'••[•
[:'::
;:;:::;:::;:;:::::;:;:;:;:;::;:::;:;::::
Figure 10.7
100 000
':-['\'\:[-\:[-[-·.-':'-: :;::.::.::.;;::.:;::.::,::.::
In order to obtain a message-set browser that provides access to all methods in the system that reference a particular literal, aSymbol, (see Chapter 5 for the definitions of syntactic parts), evaluate an expression of the form Smalltalk browseAIICallsOn: (aSystemDictionary associationAt: #aSymbol)
208 Finding Out About Messages and Methods
For example, the result of evaluating Smalltalk browseAIICallsOn: (Smalltalk associationAt: #Transcript) is shown in Figure 10.8, and the result of evaluating Smalltalk browseAIICallsOn: (TextConstants associationAt: #Centered)
is shown in Figure 10.9. An additional way to obtain all the implementors of a message is to evaluate an expression of the form Smalltalk browseAlllmplementorsOf: #messageSelector For example, the result of evaluating Smalltalk browseAlllmplementorsOf: #at:put:
is shown in Figure 10.10. An expression of the form Smalltalk browseAIISelect: aBlockWithOneArgument
creates a message-set browser on all methods such that when the block is evaluated with the method as its argument, the result is true. As an example, you can try Smalltalk browseAIISelect: [ :meth | meth numLiterals > 40]
creates a message-set browser showing methods that have more than 40 literals (Figure 10.11). Please note that the Smalltalk-80 system restricts methods to have no more than 64 literals.
209 10.4 Which Methods Reference a Particular Variable or Literal?
D e I a y c I a 5 s t e S t A b s ο l u t e D e I a y Ο f: f ο r: I a b e I: D e I a y c I a 5 5 t e s t R e l a t i ν e D e I a y Ο f: f ο r: label: Ε η c ο d e r d e c I a re U η d e c I a re d:
Fi ebtream
Fi I e S t re a m f i I e Ο υ t C h a n g e
fileln "Guarantee fileStrearn is readonly before fileln for efficiency and to eliminate remote sharing conflicts" refresh; or; cr; show: Tiling in from:'; crtab; show: self name; cr, self readonly, tsuper fileln
Figure 10.8
100 000 Pa r a g r a ρ h l e f t Μ a r g^n F ο rD Ί s ρ I a y F ο rLi η e:
centered "Set the alignment for the style with which the receiver displays its text so that text is centered in the c ο m ρ ο s i t i ο η rectangle," textStyle alignment:
Figure 10.9
|00 000
210 Finding Out About Messages and Methods
i
Implementors of at:put: Bag at:put; Dictionary at:put: FilePaqe atiput: IdQntityDictionarv at:p ut:
ft at: key put: value "Set the value a t <ey to be value."
Figure 10.10
100 000
| index | index - self findKe v'OrNil: key. (self basic At: inde: Λ == nil if True: II y + 1, [ t a l l y <- ta "elf basic A t: index put: key]. value Array at: ind ex. put: value, self fullCheck, rvalue
Β11Ε d 11 ο r c I a s s b υ 11 d (J ο Ι ο r fvi e η υ: c ο Ι ο r υ ο υ η t ΕχρIaiηer eχρΙaίηCha t Form cla.ss screenOut FormEditor· class setH.ey board M a p
Figure 10.11
211 10.4 Which Methods Reference a Particular Variable or Literal?
The yellow button menu items in the class-names subview of a system browser also support making inquiries about variable references. If you choose either inst var refs or class var refs (Figure 10.12a), a menu of the instance or class variables of the class is displayed (Figure 10.12b). If you choose one of the variables, a message-set browser is created for each method in the class or its subclasses that references the variable (Figure 10.12c). If you choose the class-names subview yellow button command class refs (Figure 10.13a), a message-set browser for all methods in the system that reference the class is created (Figure 10.13b).
CollectionsCollections-/! Collections-S Collections-:: Graphic s-Prir Graphic s-Dis S e q u e η c e a b I e C ο 11 e c t i ο η #OrderedCollection instanceVariableNa tlndex ? c I a 5 s V a r i a b I e Ν a. m e 3 poolDictionaries: " c a. t e g 0 r y: ' C 011 e c t i ο η s - S e q 1 J e η c e a. b I e'
Figure 10.12a
010
11
212 Finding Out About Messages and Methods
Interval C ο 11 e c ΐ i ο η s - Τ e χ tLinked List a c c e s 51 η g Collections-Array MappedCollectiori c o p y i n g Collect ion s-Strea adding C ο 11 e c t i ο η ; - S u ρ ρ ο Sorted C ο 11 e c t removing iοη 1 Graphic s-Primiti ·, en urn era. ting Graphic s-Display private S e q υ e Γι c e a b I e c ο 11 e c ΐ ί ο ηι r ι d. υ ι y ο uwc ι a s s: # Ο r d e r e d U ο 11 e c ΐ i ο η i Γι 51 a ri c e V a r i a b I e Ν a. m e s: ' f i r s 11 η d e χ I a. s 11 n d e χ cla ssVa riableNames: " p o o l D i c t i o n a ries: " c a t e g ο r y: ' C ο II e c ΐ i ο η s - S e q υ e η c e a b I e'
Figure 10.12b
000 Ο r d θ re d C ο 11 e c t i ο η m a keRocVnA t La s t Ο r d e re d C ο 11 Θ C t ί ο η fi η d: Ο rd e re d C ο 11 e c t i ο η re m ο ν e A11S υ c h Τ h a t: bequeηcec in 5 t a n d a 55 V poolD'n cateqi
Figure 10.12c
100 000
before: oldObject "Answer the element before oldObject, If t h e receiver doe? not contain oldObject or if the receiver contain:" no elements before oldObject, create an error message," | index | index - self find: o l d O b j e c t , index = Q ^ ^ Q Q ^ ifTrue: [t'self e r r o r F i r s t O b j e c t ] ifFalse: [ t s e l f basic At: index - 1]
913
10.4 Which Methods Reference a Particular Variable or Literal?
'•-· ο 11 e c 11 ο η s - '
Collections-.' Collections-?. C ο 11 e c t i ο η s - S
Graphic i-Prir 1 Graphics-Dis A
o e q u e η c e a b I e C ο 11 e c t i ο η ί η 51 a nee V a r i a b l e Ν a classVariableName poolDictionaries; " category:
re η a m e re rn ο ν e
'Collections-Sequenceable'
Figure 10.13a
jy stern Browser Collectio **~ C ο 11 e c t i ο Collect io Collect ioi Graphic.ίΟ ra ρ h i c s -
Β e h a ν i ο r a 11D y η a m i c S u ρ e re I a s s e B e h a v i o r alll η s t a n c e s Β e h a ν ι ο r a 11S u b c I a s •-. Ρ S
alllnstVarNarnes a n s w e r a n A r r a y of t h e na r e c e ι ν e r s i n s t a n c e ν a. r i a b I e s poolDictic
cateqory: self a c c u m u l a t e l n s t V a r N a m e s t r a v e r s e d CI a s s e s: S e t η e w. •t- η a m e s
Figure 10.13b
'
PART THREE How to Modify Existing Classes and Create New Classes
In Part Two, you were introduced to four standard system views: inspectors, browsers, notifiers, and debuggers. These views are used to find out about the objects that exist in the Smalltalk-80 programming environment. You can program by creating instances of existing classes and sending messages to these instances. If the capabilities of the existing classes are insufficient for accomplishing your programming tasks, you will have to modify one or more of the existing classes, or you will have to create new classes. The purpose of Part Three is to show you how to use the system browser for modifying existing classes and for creating new classes. The examples given demonstrate how inspectors can support you in testing the new classes that you add to the system. The organization of classes (class categories) and messages (message protocols) act as a form of documentation. Thus it is important to understand the system class organizations and how to create organizations for your applications classes. As in Part Two, we assume that the system sources are accessible to you. Without them, you will be able to access the methods. But you will not be able to access the class or method comments, nor the actual method argument names.
•ΗΗΗΗΒΗΜ
s
Ί
11 Modifying Existing Class Descriptions
11.1 Modifying Existing Methods 11.2 Modifying Protocols 11.3 Adding New Methods 11.4 Modifying Class Comments
218
Modifying Existing Class Descriptions Start by making certain that you have a system browser open on the display screen. If one does not already exist, choose the System Menu command browser. If one does exist, make it the active view. A newly created browser is shown in Figure 11.1.
Ν υ m e ri c - fvl a q η i t u d Ν urn eric-Numbers Collections-Abstrc Collect ion s-Unordi C ο 119 c t i ο η s - S e q υ e Collect i o n s - T e x t Collect ion?-Array*
Figure 11.1
000 In order to learn how to make a change to the system, you will be asked to follow several examples in which you change existing methods and add new methods to existing classes. The three examples provided here • use and modify the example of creating a geometric design with class Pen, • add the ability to class Array to create a bar chart, a graphical display of an array of elements, and • add the ability to class SequenceableCollection to compute all possible combinations of the elements of a collection.
11.1 Modifying Existing Methods
Exercise 1: Use class Pen to create geometric designs. For the first example, you have to find the existing method that you will modify. Choose class category Graphics-Primitives, class Pen, browser menu item class, message category examples, and message selector example. The method associated with the message example is shown in
219 11.1 Modifying Existing Methods the text subview of the browser. The result of these selections is shown in Figure 11.2a. Notice that at the end of the method is a comment (text enclosed in double quotes). To try this example use of class Pen, select the comment
Collect ion s-8trea.r C ο 11 e c t i ο η s - S υ ρ ρ ο Point Graphics-Display Quadrangle Graphic;-Paths Fi e c t a n q I e Graphics-Views Graphics-Editors Graphic s-Clocks
instance creation
"Draws a spiral in gray w i t h a pen t h a t is 4 pixels wide
bic *- Pen new, bic mask: Form gray. bic defaultNib: 4, bic com bin a tionFiule: Form under, 1 to: 50 do: [:i | bic go: i*4. bic turn: 8 9 ] "Pen example"
Figure 11.2a
000 Collect ions-Strear Jollections-Suppc graphics-Display G ra ρ h i c s - Pa t h s Graphics-Views Graphics-Editors Graphics-Clocks
Point Quadrangle Fi e c t a n q I e
example "Draws a. spiral in gray w i t h a pen t h a t is 4 ρ
Pen new, ask: Form gray. efaultNib: 4, omb in a tionFiule: Form under, 50 do: [:i | bic go: i:+:4, bic turn: 8 9 ]
Figure 11.2b
Dio
220 Modifying Existing Class Descriptions
text (do not select the double quotes), and then choose the yellow button command do it (Figure 11.2b). A geometric design appears on the screen (Figure 11.2c). System Brer· C ο 119 c 11 ο η s - ο t r e a r C o l l e c t ions-Suppoi
Graphics-Views G r a. phi c s - Ε 611 ο r s
Draws a spiral in qra.y with
4
^
bic ma.sk: Form qrzy. %; \/\\'\\\\'Ι1.| ί ^Ξ^ : Ι 11.!.'!. "%. % % bic defaultMib: 4.
Figure 11.2c
"''"'
"'"" '"' :fe s-*• * *• * * ' •-'-ifX" ••*.<*•*• * * - *
000 To create this design, you sent the class Pen the message example. The method associated with example was found in the class protocol for Pen. The first statement of the method creates an instance of Pen, and assigns it to the temporary variable bic. Instances of class Pen respond to messages to change their line drawing characteristics. In particular, mask: Form gray defaultNib: 4
combinationRule: Form under
The halftone mask that determines "color" of the drawing ink. Other masks include Form darkGray, Form lightGray, and Form black. The shape of the source form or "brush" is a 4 χ 4 square. Squares of different sizes can be used by specifying different integers as the message argument. The mode for mixing the bits of the source and destination Forms can be varied, either Form under, Form over, Form reverse, or Form erase, can be used as the message argument.
The second, third, and fourth statements of the example method send these messages in order to set the characteristics of bic. The fifth message is an iteration in which the Pen travels some distance (go: i * 4) and changes orientation (turn: 89); as the Pen travels, it paints a line using its current brush, mask, and combination rule.
221 11.1 Modifying Existing Methods
You can now experiment with variations of the example design. First, erase the geometric design that was the side effect of the previous example by choosing the System Menu command restore display. In the Pen method example, change the mask. Select the message gray sent to the Form (the second statement in the method) as shown in Figure 11.3a; then type the new message darkGray. The typing change is shown in Figure 11.3b. Change the size of the square brush. Select the message argument, 4, as shown in Figure 11.3c. Type the new argument, 2; the result is shown in Figure 11.3d. Now choose the yellow button command accept (Figure 11.3d). The message accept in this context means "compile the code." Compilation means translate the Smalltalk-80 statements into machine executable form (i.e., create an instance of CompiledMethod). The changed method is automatically loaded into the running system, ready for you to try. Select the expression Pen example (as you did earlier), and then choose the yellow button command do it. The modified geometric design shows on the screen (Figure 11.4). You can keep experimenting in this way. Instead of using the message defaultNib: to specify the brush shape, try the message sourceForm:. The message argument is an instance of class Form. (You can try using one of the cursors that exist, such as Cursor normal or Cursor crossHair). Also, try changing the mode of mixing bits to Form reverse when you use different source Forms, otherwise the results will be mostly black.
ollections-btrear Collect ions -Suppoi inBiuiiiiKMa
uma
G r a. ρ h i c s - D i s ρ I a y Graphics-Path; Graphics-Views Graphics-Editors Graphics-Clocks
bic *· Pen new. bic d e f a u l t Nib: 4, Λ bic c o m b i n a t i o n Rule: Form under, 1 t o : 5 0 do: [:i | bic go: i :+: 4. bic t u r n : 8 9 ] "Pen example"
Figure 11.3a
100
222 Modifying Existing Class Descriptions
Collections-Strear Collect ions-Suppo
Graphic 5-Views Graphics-Editors
"Draw? a. spiral in gray with a pen that is 4 pixels wide
bic *• Pen new, bic mask: Form darkGray^ bic default Nib: 4. \ bic combine.tionRule: Form under. 1 to: 50 do: [:i | bic go: i*4. bic turn: 89] "Pen example"
Figure 11.3b
000 Collect ions-Strea Collect ions-Suppo Graphics-Display Graphics-Paths Graphics-Views Graphics-Editors Graphics-Clocks
Point Quadrangle Rectangle
example " D r a w s a spiral in g r a y w i t h a. pen t h a t is 4 pixels wide.
I bic | bic *- Pen new, bic mask: Form dark Gray. bic default Nib: Ά bic combinationRXile: Form under, 1 to: 50 do: [:ί | bic go: i*4, bic turn: 8 9 ] "Pen example"
Figure 11.3c
loo
223 11.1 Modifying Existing Methods
Collections-Strear Collections-Suppo mBaannMiaiimmHa
Graphic 5-Display Graphic 5-Path s Graphic;-Views Graphics-Editors Graphics-Clocks
Point Quadrangle Fi e c t a n g I e
instance creation
agaιη example " D r a w s a spiral in g r a y w i t h a pen t h a t is 4 pixel undo copy cυt ρaste do it bic *• Pen new, print it bic mask: Form dark.Gray, bic default Nib: 2\ bic cornbinationFiule: Form under, format sρawη 1 to: 50 do: [:i | bic go: i:+:4, bic turn: 8 9 ] e χ plain "Pen example"
Figure 11.3d
ΟΪ0 Collect ions-Strea Collect ions-Suppo MlfcliflJWfcHdUIMUBfe Point Graphic s-Display Quadrangle Graphics-Paths Rectangle Graphics-Views Graphics-Editors Graphics-Clocks example "Draws a spiral in o,ra>
bic - Pen new, bic mask: Form darkGr bic defaultNib: 2. bic combinationFiule: F 1 t o : 5 0 d o : [:i | b i c g>
Figure 11.4
OUO
/
Τ
224 Modifying Existing Class Descriptions
11.2 Modifying Protocols
Exercise 2: Modify class Array to display bar charts. The next example demonstrates a way in which you can get another graphical effect on the screen. It was chosen primarily to introduce the mechanisms for adding a new method to an existing class, not to be a typical example of how to handle graphical presentation. There are a number of interesting ways to handle graphical presentation of information, such as views and menus. The approach taken in creating the Smalltalk-80 system user interface is introduced in Chapter 15. In this example, you will add one method to class Array. The result of the method is to create a bar-chart representation of the elements of an Array whose elements are numeric. As an argument to the message to Array, you specify the labels that will appear along the horizontal axis of the bar chart, one label for each element. To add a method to an existing class, you can use a system browser. Choose the class category Collections-Arrayed. Choose the class name Array. Make certain the menu item instance is selected. Your browser should resemble the one shown in Figure 11.5. Now you need to choose a message category. Let's assume the appropriate message category does not exist. You must create a new category.
(J ο 11 e c t i ο η s - S e q u e| Collections-Text , _ ' B y t e An-a. C ο 11 e c t i ο η s - S t re a ή R υ η A rra y C ο 11 e c t i ο η s - 5 υ ρ ρ ο ι G ra ρ h i c s - Pri m i t i ν e | Graphics-Display Graphics-Paths
comparing converting printi rig
A r r a v 6 d C ο 11 Θ c t i ο Γι ν a r i a. b I« S u b c I a s s: # A r r a y i η s t a η c e V a. r i a b I e Ν a rn e s: '' c I a. s s' v' a r i a b I e Ν a m 9 s: poolDictionaries: " c a t e q ο r ν: ' C ο 11 e c t ί ο η s - A r r a. y e d'
Figure 11.5
225 11.2 Modifying Protocols There are two ways to modify the message protocol of a class: 1. Use the commands in the yellow button menu of the messagecategory subview. 2. Choose the yellow button command protocols in the class-names subview. The first approach is the preferred one; the second, which involves direct editing of a textual presentation of all the categories, is available in case you have to do a large reorganization. An explanation of each follows. With the cursor in the message-category subview, but no category selected, press the yellow button. The menu has one item, add protocol (Figure 11.6a). Choose it. A prompter appears (Figure 11.6b) in which you type the new protocol name. After typing the name (graphical views is used in Figure 11.6c, although misspelled), choose the yellow button command accept or type the "carriage return" key on the keyboard. The new name is added to the message-category subview menu (Figure 11.6d). When you choose add protocol, the new protocol name is appended to the end of the message-category subview menu, and is selected. If a category was already selected when you invoked the add protocol command, then the new category is inserted before this selected one.
Collections-Sequ Collection;-Text ollect i o n s - S i r e * Collect ions-Sup ρ ο Graphics-Primitive rap hies -Display Graphics-Paths
comparing converting printing
A r r a y e d C ο 11 e c t Ί ο η ν a r Ί a b I e S u b c I a s s: # A r r a y i η s t a n c e V a r i a b I e Ν a m e s: " c I a s s V a r i a b I e Ν a m e s: " poolDictionaries: " c a t e g ο ry: ' C ο 11 e c t i ο η s - A rrd. y e d'
Figure 11.6a
ΟΪ0
226 Modifying Existing Class Descriptions
Collect ions-Sequel Collections-Text Byte Array C ο II e c t i ο η 5 - S ΐ re a Run r Array C ο 11 e c ΐ i ο η s - S u ρ ρ ο Graphic?-Primitive Graphics-Display Graphics-Paths
comparing converting printing
Enter new protocol name then accept or CR
A r r aye d Collect! ο η ν a r i a b I e b u b c I a s s: # A r r instance V a r i a b I e Ν a m e s: " class V a r i a b I e Ν β. m e s:? ' poolDictionaries: " c a ΐ e g ο r y: ' C ο 11 e c ΐ ί ο η s - A r r a y e d'
protocol name
Figure 11.6b
Collections-Seque Collections-Text
B y t e Array A rray C ο I! e c t ί ο η s - ο t re a Run r Collect ion s-Suppo Graphics-Primitive Graphics-Display Graphics-Paths
HMlBWIWMHaiBW
comparing converting printing
A r r a y e d υ ο 11 e c ΐ i ο η ν 3. r Ί a b I e Ό υ b c I a s s: Ί η s 13. η c e V a. ri a b I e ['•·] a rn e s: " c I a s s V 3. r i 3. b I e U a rn e s: poolDictionaries: " c 31 e g 0 r y: ' C 011 e c t i ο η s - A. r r a y e d Ί
Figure 11.6c
Enter n e w pro t o t t h e n a c c e p t or C grapica
r
Ί 227 11.2 Modifying Protocols
C ο 11 e c t i ο η s - S e q u e
ollections-Text Byte Array Collections-Strear Run Array C ο! I e c t i ο η s - S υ ρ ρ ο Graphic s -Primitive Graphics-Display Graphic ;.-Paths
comparing converting printing
^nessage selector and argument names "comment stating purpose of message" | temporary variable names | statements
Figure 11.6d
000 When a category is selected, the yellow button menu includes commands rename and remove, as well as add protocol. If you choose the command rename, a prompter appears that contains the selected name. Edit it, then choose the prompter yellow button command accept or type the "carriage return" key. For example, notice that we mistyped the name graphical views in Figure 11.6c. With the misspelled name selected, choose the command rename (Figure 11.7a). The prompter appears, showing the current name (Figure 11.7b). Edit the text and choose the yellow button command accept (Figure 11.7c). The name in the message-category menu changes (Figure 11.7d). If you choose the command rename, and the name you provide is the same as an already existing protocol name, then nothing changes.
228 Modifying Existing Class Descriptions
Jollections-beque 3ctiοηs-Τeχt >'J o II e c 11 ο η s - Ό t r e a t e c 11 ο η s - b u ρ ρ ο Graphics-Primitive Graphics-Display Graphics-Paths message select or and argument names "comment s t a t i n g purpose of message" | temporary variable names | s t a t e rn e η 1s
Figure 11.7a
010 System Browser υ 011 e c 11 ο η s - ο e q υ e ι Collections-Text
Byte Array Uollections-btrear Flu η Array
UBIIiaininwaiCTi
(J ο 11 e c 11 ο Γι s - b υ ρ ρ ο Graphic:.-Primitive Gra ρhic s-DisρIa y Graphic 3-Pa t h s l t i
comparing co η vert ing printing
H a i M
sage selector and argument η a. me; "co m m e ri t s t a t i n g purpose 0 f rn e 3 3 a g e" I temporary
Enter new protocol η am then a c c e p t or CFi
i a b I e η a rn e s
5 t a r e me η t s
Figure 11.7b
1
229 11.2 Modifying Protocols
iystern Browser I e c 11 ο η s - b e q u c I e c t iοn."-Ty:.< t Byte Array •Jollec t i u r i s - ' o t r e a r ] FiunArra ν 0 ο 11 e c t i ο ηs - S u ρ ρ ο Graphic s - Ρ r i m i t i ν e Graphic.s-Disp Id y Gra ρ hie s - P a t h s
com ρ a. n rig converting ρπηtΊηg
Enter n e w pro
rn e 5 5 a g e selector a. η d a r g υ m e η t η a m e s "c οΓΙΊmeη t sta tiηq purpose of message" | temporarv'
t h e n a c c e p t oil g r a p h i c a l vie1·,
i a b I e Γι a m e s
s t a t e m e ηts
Figure 11.7c
ΟΪ0 Collections-Seque Collect i o n s - T e x t Collections-Strea.H FiunArra Collect ions-Suppo G re. ρ h ί c s - Pr-i m ί t i ν e Graphic s - Di sρI a y ra phi c 5-Path 5
comparing co η v e r t i n g printing
message selector and argument names "comment s t a t i n g purpose of message" | t e m p o r a r y variable names | s t a. t e rn e η t s
Figure 11.7d
000
a. g a ι η undo
copy
do it print it
230 Modifying Existing Class Descriptions
If you choose the command remove, and there are no message selectors in the selected category, the category is immediately deleted. If there are messages in the selected category, a confirmer appears because the deletion means that all messages in the category are deleted (Figure 11.8). The second way of modifying the protocol for a class is to choose the yellow button command protocols in the class-names subview of the browser (Figure 11.9a). A list of message categories and message selectors within each category appears in the text subview of the browser (Figure 11.9b). The syntax for each category/selectors combination is of the form ('category name' selectoM selector2 selector3) To add a protocol, insert a new name, delimited by single quotes and embedded in parentheses. ('new name') An example is shown in Figure 11.9c in which the new category name graphical views is appended at the end. Choose the yellow button corn-
System Browser I e c 11 ο η _-. - s e q υ e lections-Text Byte Array u o l l e c t i o n s - S t r e a . r FiunArra ν Codec t i o n s - S u p p o Gra phic .'-Primitive Graphic s-Display Gra phic 5-Pa t h j
com ρ a ring convertinq
A, r e ν1 ο υ c e r t a. i η t h a. t y ο υ νν a n t ΐ ο remο νe all me t h ο d s in this p r o t o c o l "
messaqe s e l e c t o r and arqυmeηt '' c ο m m e η t ; t a t i η q ρ υ r ρ ο s e of mess a q e" | t e m ρ ο t'^v ν ν a r i a b I e η a m e s j statements
Figure 11.8
loo
is Lit era I print On: s t o r e On:
r 231 11.2 Modifying Protocols
GollectionsCollections-7 ollections-S| Collect ions-3 Graphic s-Prin Graphic s-Disj Graphics-PatTr?
Run.4
ι v e r t ing Ί ting
hierarchy definition comment
inst v3\r refs class v a r refs A r r a. y e d C ο 11 e c t i ο η ν a r / c class refs instanceVariableNa rename remove classVariableWarnei pool Dictionaries: " c a t e q ο r y: ' < J ο 11 e c t i ο η s - A r r a v e d'
Figure 11.9a
Oio Collections-::
Collections-! Collect ions-Ξ Collect ions-Ε Graphic s-Prin Graphic s-Dis| Graphics-Pat
ByteArra> FiunArra ν
c ο m pan' η g' h a s h h a s h fvl a ρ ρ e d Β y:) ' c ο η ν e r t i Γι g' a s A r r a y) ' p r i n t i n g ' isLiteral printOn: storeOn;)
Figure 11.9b
ooo
compering con verting printing
232 Modifying Existing Class Descriptions
Collect ions -Seque Collect ions-Text Collect ions-Strea Collections-Suppo G r a p h i c s - Primi t i ν Q G ra ρ h i c s - D ί 5 ρ I a y Graphics-Paths
comparing converting printing
(' c ο rn ρ a r i η g' h a s h h a s h Μ a ρ ρ e d Β y:) (' c ο η ν e r t Ί η g' a s A r r a y) ('printing' isLiteral printOn: storeOn:') ('graphical views' \
Figure 11.9c
010 C ο 11 e c t i ο η s - S e q υ e C ο II e c t ί ο η s - Τ e χ t J B ~ Byte Array C ο 11 e c t i ο η s - S t re a rj Fi u η A rra y Collect ions-Suppoj G ra ρ h i c s - Pri rn i t i ν e G ra phi c s -DΊ s ρI a y Graphics-Paths
comparing converting printing graphical vie
A r r a y e d C ο 11 e c t ί ο η ν a ri a b I e S u b c I a s s: # A rrs. y i η s t a n c e V a r i a b I e Ν a rn e s: " c I a s J V a r i a b I e Ν a m e s: '' poolDictionaries: " c a t e g ο ry: ' C ο II e c t i ο η s - A rra. y e d'
Figure 11.9d
BOO
r 233 11.3 Adding New Methods mand accept in the text subview to have the system check the syntax of the category specifications, and to add the category to the menu in the browser. The result is shown in Figure 11.9d.
11.3 Adding New Methods
Choose the new category graphical views. A template for defining a new method appears in the text subview of the browser, as shown in Figure 11.10a. You edit this template with the desired message pattern, comment, and statements. In Figure 11.10b, the message selector and argument names part of the template is selected; typing the actual pattern replaces the selected text (Figure 11.10c). The example message pattern is displayBarChartWithLabels: anArray. The name of the message argument has no semantic meaning in the Smalltalk-80 programming language. However, as a matter of style and documentation, the message argument name is made up from the name of the class or superclass of the instance that can be an argument to the message. In this example, the argument name indicates that the argument should be an instance of Array or of a subclass of Array.
Now select the comment part of the template (Figure ll.lOd) and type an appropriate comment. The comment shown in Figure ll.lOe includes an expression that is an example use of the method. Users of this method can browse to read the comment, and then see an example use of it by executing the expression.
Collections-Seqi Collections-Te Collect ions-S C ο 11 e c t ί ο η s - S u ρ ρ ο Graphics-Primitive Graphics-Displa Graphics-Paths
comparing converting ρ ri η t i η g
me;sage selector and argument names "comment stating purpose of message" | temporary variable names | statemeηts
Figure 11.10a
234 Modifying Existing Class Descriptions
C ο 11 e c t i ο η 5 - S e q u e C ο 11 e c t i ο η s - Τ s χ t WSIIEPHfflffBBIHSPI C ο 11 e c t i ο η 5 - S ΐ r Θ a r Collect i o n s - b υ ppo G ra ρ h i c s - F'ri rn i t i ν e G ra. ρ h i c s - D i 5 ρ I a y Graphic;-Path
comparing converting printing
"comment stating purpose of message" | temporary variable names statements
Figure 11.10b
100 C ο! I e c t i ο η s - S e q u e C ο II e c t i ο η s - Τ e χ t U ο II e c 11 ο η s - S ΐ r e a r Collections-Suppo G ra. ρ h i c s - Pri rn i t i ν e Graphics-Display Graphic s - P a t h s
comparing converting pri η tin
d ι s ρ I a. y Β a r U h a r t W11 h L a b e I s: a. n A r r a y "comment s t a t i n g purpose of rnessJ^e" | t e m p o r a r y variable names | s t a. t e m e η t s
Figure 11.10c
235 11.3 Adding New Methods
Dollections-Se Dollections-Te CollectionsCo He ct ions-Supp ο Gra ρ hies -Primitive Graphics-Display Graphics-Paths
comparing converting printing
d i s ρ I a y Β a rC h a f t W ί t h La b e I s: a n A rra y
| temporary variable name s t a. t e rn e η t s
Figure ll.lOd
Collect ions-Seque Collect ions-Text C ο 11 e c t i ο η s - S t re a r υ olle c 11 ο η s - b u ρ ρ ο Graphics-Primitive G r a p hies- D i s ρ I a y Graphics-Paths
cοmρaπηg converting
printing
d i s ρ I a y Β a rC h a r t W i t h La. b e I s: a n A rra y " C r e a t e a b a r c h a r t r e p r e s e n t a t i o n of t h e numeric c o n t e n t s of t h e instance. The message argument is a collection of labels t o use in i d e n t i f y i n g each column of the bar c h a r t , If the argument is nil, use indices for labels. T r y # ( 1 5 6 7 8) d i s p l a y B a r C h a r t W i t h L a b e l s : ^ ( ' s a l e s ' ' p r o f i t ' 'loss' | t e m p o r a r y variable names | statements
Figure ll.lOe
ran
1
236 Modifying Existing Class Descriptions
Now select the temporary variable names part of the template and replace it with rect spacing maxHeight factor labeling top dispRect. Then select the statements part and replace it (Figure ll.lOf).
CollQCtions-Arr
Collections-St η Byte Array C oily c t i ο η s - S u ρ Graphics-Primit Run A rr a. v Graphics-Displa Graphics-Paths Graphics-View Graphic s-Edi to
comparing converting printing
d i s ρ I a y Β a r υ h a rt W i t h La b e I s: a n A rra y "Create a bar chart representation of the numeric contents of the instance, The message argument is a collection of labels to use in identifying each column of the bar chart, If the argument is nil, use indices for labels, T r y # (15 6 7 S) d i s ρ I a y Β a rC h a r t W i t h La b els: # ('sales' ' ρ ro f i t ' 'loss' ' t o t a l ' ) " | rect spacing maxHeight f a c t o r labeling top dispRect | rect *• Rectangle from User, spacing *• rect w i d t h + self size // self size, maxHeight *• 0, 1 to: self size do: [ :i | maxHeight *• maxHeight max: (self at: 1)], f a c t o r *• (rect height - 30) / maxHeight,
1^
labeling *• (anArray == nil or: [ a n A r r a y size < self size]) not, Display fill: rect mask: Form white, 1 to: self size do: [ :i | (labeling if Τ rue: [ a n Array a t : i ] if False: [ i print String]) d i s ρ I a y A t: r e c t b ο 11 ο rn L e f t - (0 © 3 0) + (((' s ρ a c i η g + (i - 1)) + 1) (*! 0), ((self at: i) isKindOf: Number) ifFalse: [self error: 'element is not numeric'], top *• rect top + rect height-30-((self at: i) + f a c t o r ) aslnteger, dispRect *•
Figure ll.lOf
000
(rect I e f t + 1 + (s ρ a c Ί η g:+; (i - 1))) @ t ο ρι c ο r net": (r e c t I e f t + (s ρ a. c i η g * i) - 1) © (r e c t b ο 11 ο rn - 3 0), Display fill: dispRect mask: Form black, Display fill: (dispRect inset By: 2@2) mask: Form g r a y !
i
237 11.3 A d d i n g N e w M e t h o d s Note that since the template is simply unstructured text, you can select all of it and replace it with the desired method. The example did the selection and replacement in parts to emphasize the parts of a method that can be specified. The system will not force you to provide comments, nor will it enforce naming conventions.
There are eight statements in the method that are commented here. rect — Rectangle fromUser.
Create a new Rectangle. The user of the method will have to designate the origin and corner of the Rectangle. Be careful to provide sufficient space for the Rectangle.
spacing - rect width + self size // self size. Compute the amount of space that can be used for the width of each column. The pseudo-variable self refers to the Array. maxHeight — 0.
Determine the largest element of the Array.
1 to: self size do: [ :i | maxHeight - maxHeight max: (self at: i)). factor «- (rect height - 30) / maxHeight. Compute the scaling factor to get the bar chart columns to fill the available space. The height of each column is the Array element times this scaling factor. 30 is the space left for the labels. labeling - (anArray = = nil or: [anArray size < self size]) not. Compute a Boolean (true or false) that indicates whether the bar chart will be specially labeled. There are no special labels if the message argument anArray is nil, or if the message argument does not contain a label for each element. When there is no special label, the element index will be displayed. Display fill: rect mask: Form white. Display is an instance of DisplayScreen. The message filkmask: is used to paint a rectangular area of the screen with some "color." Here the rectangle is the space to display the bar chart; the color, all white, is the background for the bar chart.
The eighth statement is an iteration in which each column is printed. For each element of the Array, that is, for the index i starting at 1 and ending at the size of the Array, determine the label (it is either anArray at: i, or it is the index converted to a string, i printString) and display the label within and at the bottom of the rectangle (displayAt:). Make certain that the Array element is numeric; if not, report an error. Otherwise, compute the top (top) of the next column, then compute the column's rectangle (dispRect). Now modify the display screen to show the column; the column has a 2 χ 2 black border, so first display the column all in black (Display fill: dispRect mask: Form black) and then
238 Modifying Existing Class Descriptions display the gray area inset from the edge (Display fill: (dispRect insetBy: 2@2) mask: Form gray). 1 to: self size do: [••«I (labeling ifTrue: [anArray at: i] ifFalse: [i printString]) displayAt: rect bottomLeft - (0@30) +(((spacing * (i - 1)) + 1)@0). ((self at: i) isKindOf: Number) ifFalse: [self error: 'element is not numeric'], top - rect top + rect height - 30 - ((self at: i) * factor) aslnteger. dispRect «- (rect left+1 + (spacing * (i - 1))) @ top corner: (rect left+(spacing * i) - 1) @ (rect bottom-30). Display fill: dispRect mask: Form black. Display fill: (dispRect insetBy: 2@2) mask: Form gray]
After you have typed these eight statements, choose the yellow button command accept. The method is compiled and loaded into the system; the message selector appears selected in the message-selector subview of the browser. Check that you typed correctly. If not, edit the method and choose the command accept again. If you choose accept but have mistyped something, a syntax error message may be inserted into your code just before the point of the error. If this happens, cut out the error message and correct the (probably misspelled) token. Then choose the command accept again. Alternatively, a menu may appear that indicates an undeclared variable or message selector. One of the commands in the menu is abort. Choose it, then edit the method to correct the error, and choose the command accept again. Try the new method by selecting the expression in the comment and choosing the yellow button command do it (Figure 11.11a). First you are asked to designate the rectangle in which the bar chart will appear in the same way you designate a standard system view. A possible result is shown in Figure 11.11b. (Note that the image is not in a system view and cannot be selected for reframing, moving, closing, and so on. To erase the bar chart, choose the System Menu command restore display.) If you did not copy the method correctly, but what you typed was successfully compiled, two things could have happened. 1. You successfully obtained a result, but it does not look right. Recheck your method to find the difference between code presented here and what you typed. Edit the method, choose the command accept again, and then try the example again. 2. You did not get a bar chart, but instead a view called a notifier appears to tell you something is wrong. This notifier indicates a runtime error. It is like the one described at the end of Section 8.5. In the notifier, choose blue button command close, and then
239 11.3 Adding New Methods
Collect ion s-Seq Collections-Te; Collect ions-Sire Collections-Suppo Graphic 5-Primitive Graphic;-Display Graphics-Paths "
com ρ β. ring nvertinq printing
displayBarChartWithLabels: anArray "Create a bar chart representation of the numeric r instance. The message argument is a collertinn nf label identifying each column of the bar chart, If the flrqume indices for labels. Tr
rect spacing maxHeight factor labeling top dispFied rect *• Rectangle fromUser. spacing <- rect width + self size // self size maxHeight to· .-elf .-izp ,jo [ i | n,3 Height - no Heiur.r n,=
Figure 11.11a
Figure 11.11b
240 Modifying Existing Class Descriptions proceed as suggested for case 1. The most common runtime error is that an object does not understand a message sent to it. Often this is because a period or parentheses was forgotten, or you misspelled the message keywords. There are a number of ways in which you can modify the method to produce different effects. Try to change the background to light gray, rather than white (Display fill: rect mask: Form lightGray), and the column tone to dark gray instead of gray (Display fill: (dispRect insetBy: 2@2) mask: Form darkGray). A new bar chart created with these changes is shown in Figure 11.11c.
Figure 11.11c
Exercise 3: Modify SequenceableCollections to do combinations of the elements of the collection. This exercise is similar to Exercise 2 in that it demonstrates how to modify an existing class description in order to add new functionality to a class. It differs in that several methods, rather than just one, must be added. The new functionality is to obtain an OrderedCollection of all possible combinations (subsets or subcollections) of the elements of a SequenceableCollection. For example, the result of sending the Array #(a b c) the message combinations should be OrderedCollection ((a b c ) (b c ) (a c ) (c ) (a b ) (b ) (a ) ())
241 11.3 Adding New Methods
The design of the algorithm is to recursively call on a method that computes subsets of all the combinations of elements, eliminating one element at a time, and collecting the result of each call into an OrderedCollection. The index of the element to be eliminated is called the order of the elimination; it is an index into the SequenceableCollection. The top-level call to this method (combinations:) uses the message argument 0; the top-level call is specified in the method associated with the message combinations. The two messages, combinations and combinations:, will be categorized in message category enumerating of class SequenceableCollection. An instance of any subclass of SequenceableCollection, such as Array or String, will be able to compute all of its combinations. The two methods are as follows. combinations "Answer a collection containing all the combinations of the receiver's elements, e.g., # ( a b c) combinations. " Tself combinations: 0
combinations: order " Answer a collection containing a subset of all the combinations of the receiver's elements." | combinations | combinations <- OrderedCollection with: self. 1 to: self size - order do: combinations addAII: ((self copyWithoutlndex: i) combinations: self size - i)J. Tcombinations
The method for combinations: includes the expression self copyWithoutlndex: i
The message copyWithoutlndex: must be defined for SequenceableCollections. In the example, it is categorized in message category copying as shown on the next page.
Τ
242 Modifying Existing Class Descriptions
copyWithoutlndex: omitlndex "Answer a copy of the receiver, omitting the element at omitlndex, e.g., # ( a b c) copyWithoutlndex: 2 = # ( a c ) . " I copy | copy «- self species new: self size - 1. copy replaceFrom: 1 to: omitlndex - 1 with: self startingAt: 1. copy replaceFrom: omitlndex to: copy size with: self startingAt: omitlndex+1. Τ copy
Now that we know what we want to do, let's see how to use the Smalltalk-80 programming interface to add the methods. In a system browser, choose class category Collections-Abstract, class name SequenceableCollections, message category copying, and the browser menu item instance, as shown in Figure 11.12a. In the text subview, edit the text of the method template. Replace the message pattern, comment, and statements to specify the method for copyWithoutlndex: omitlndex. Choose the yellow button command accept (Figure 11.12b). The new method is added to the message-selector menu of the browser (Figure 11.12c).
Nurneric-Maqnitu Ν υ m e π c - Ν u m b e rs
A r r a ν e d C ο 11 e c t i ο r
_• υ 11«'.-1.1 ο η s - U η ο rd C o l l e c t ions-Seque C ο 11 e c t i ο η s - Τ e χ ΐ Collections-Arra> C ο 11 e c t i ο η s - S t r e a
Q η υ me re. ting convert inq
copy From: to: copyFieplaceAlli'vvi copy ReplaceFrom: t c ο ρ y W i t h: copy With out: shallow Copy
message selector and argument names "comment stating purpose of message" | temporary variable names | s t a. t e m e η t s
Figure 11.12a
J
243 11.3 Adding New Methods
Numeric-Mag nit υ d| Ν υ ΠΙ e ri c - Ν υ rn b e rs I A rra. y e d C ο 11 e c t ί ο η comparing accessiηg Collection Collections-LI nordi iiciinc wmic a d d i η g Collections-Sequel removing Collections-Text EySBHBBJ Collections-Array. enumerating Collection s-St rear co η verting
copy From: to: cop y Rep lace All: wi copyReplaceFrom:t c ο ρ y W i t h:
copy Without; s h a 11 o vv C ο ρ y
c ο ρ y W i t h ο υ 11 η d e χ: ο m i 11 n d e χ "Answer a copy of t h e receiver, omitting t h e element a t omitlnde E.g. # ( a b c ) c o p y W i t h o u t I n d e x : 2 = # ( a . c') " agaιη υηdo I copy | copy c ο ρ y <- s e l f s ρ e c i e s η e w : s e l f size - 1. cut c o p y r e p l a c e From: 1 t o : o m i t I n d e x - 1 w i t h : s e l f s t a r t i n g A t : 1. ρ a. s 19 c o p y r e p l a c e F r o m : o m i t I n d e x t o : c o p y size w i t h : s e l f s t a r t i n g A t : do it print it ο m i 11 n d e χ + 1, tcopv
Figure 11.12b
format sρaw η eχρIaiη
OiD Nurneric-Magnitudj Numeric-Numbers
i
Uollections-oequel Collections-Text C ο 11 e c t i ο η s - A rra y ι Collections-Strear
.rrayed(Jollection
cοmρaπηg a c c e s s i ri g adding removing enumerating converting
copyFrom:to: c ο ρ y Fi e ρ I a c e AII: •· copyReplaceFrorn:t copy With: c ο ρ y W Ί t h ο u t: s h a 11 o w (J ο ρ y
c ο ρ y W i t h ο υ 11 η d e χ: ο m i 11 n d e χ " A n s w e r a. c o p y o f t h e r e c e i v e r , o m i t t i n g t h e e l e m e n t a t o m i t I n d e x E.g. #(s. b c ) c o p y W i t h o u t I n d e x : 2 = #(s. c ) " I copy | c o p y *• s e l f s p e c i e s n e w : s e l f size - 1, c o p y r e p l a c e F r o m : 1 t o : ο mi t I n d e x - 1 w i t h : s e l f s t a r t i n g A t : 1. c o p y r e p l a c e F r o m : o m i t I n d e x t o : c o p y size w i t h : s e l f s t a r t i n g A t : o m i t I n d e x + 1. tcopyA
Figure 11.12c
Boo
244 Modifying Existing Class Descriptions
Q Formatting When we typed the method, we were not careful to format the statements (use indentation and line change so that the message selectors are clearly presented). Choose the yellow button command format to create a formatted version (Figure 11.13a). Edit the formatted statements to change anything you do not like. Choose the yellow button command accept to store the formatted version (Figure 11.13b). Q Testing Open a workspace in which you can try out the new method (choose the System Menu command workspace). Type the expression # ( a b c) copyWithoutlndex: 2
Select the expression and then choose the yellow button command print it (Figure 11.14a). Make sure that you get the result (a c). Try other SequenceableCollections, such as a String. 'string' copyWithoutlndex: 3 The result should be a new String, 'sting'.
These tests are shown in Figure 11.14b. If your results are different, check to make certain that you copied the method correctly. Edit the method if necessary, and then choose the yellow button command accept. Now choose the message category enumerating, as shown in Figure 11.15a. In the text subview, edit the text of the method template. Replace the message pattern, comment, and statements to specify the method for combinations:. Choose the yellow button command accept (Figure 11.15b). The new method is added to the message-selector menu of the browser. By choosing combinations: in the message-selector menu, it is deselected, and the method template appears again. Edit the template to specify the method for combinations. Choose the yellow button command accept (Figure 11.15c). The new message selector is added to the menu. In the workspace, try the new method. Type, select, and evaluate expressions such as those shown in the workspace in Figure 11.15d.
J
245 11.3 Adding New Methods
Numeric - M a qni tudl Ν u m e ri c - Ν u m b e r s | A rra y e d C ο 11 e c t icorn ο η ρ a. ring C ο 11 e c t i ο η accessing Collections-Unordi adding Collection:'-Seque) removin Collections-Text Collections-Array* enumerating Collections-Strear converting
copy From: to: copy Replace All: vvi cppyRepla.ceFrom:t c ο ρ y W i t h: copy Without: nmnwiMHimiMimRii
shallovvCopy
again c ο ρ y W i t h ο u 11 η d e χ: omit in d e χ undo "Answer a. copy of the receiver, omitting the element a t ο ι copy cut E.g. # ( a b c) copy Without Index: 2 = # f a c) paste copy | do it copy «- self species new: self size - 1. print i t w i t h : self s t a r t i n g At: copy replaceFrom: 1 to: om it Index - 1 accept copy replaceFrom: omit Index to: copy size w i t h : self s t a r t i n g At: cancel omit Index + I, rcopy A
Figure 11.13a
s ρ a^·1 η lex plain
ioio Ν υ m eric- Μ a gnit υ d Ν υ m e ri c - Ν υ m b e rsA rra yed Collection Collection Collections-Unordi ΙΗΓΊΓΓΗΠΠ™""™"'" Collections-Sequei Collections-Text Collect ions-Array C ο 11 e c t i ο η s - 3 t re a
comparing accessing adding removing
copy From: to: copy Replace A11: wi copyReplaceFrom:1 copy With: copy Without;
^opyWithoutlndex: ornitlndex
"Answer a copy of the receiver, omitting the element at E.g, #(a b c) copy Wit h out index: 2 = #(a c) " I copy | copy *- self species new: self size - 1. copy replaceFrom: 1
Figure 11.13b
Oio
to: omit Index - 1 w i t h : self s t a r t ing At: 1, copy replaceFrom: ο m i 11 n d e χ
246 Modifying Existing Class Descriptions
S ν stem Browser Numeric-Magni Numeric-Numl Collections-!.)! Collect ίο η s-Si
Collections-Τι Collect ions-Αι Collect ion s-Si copyWithoutl "Answer . E.g.
copy *- self specie:" new: self size - 1. copy replaceFrom: 1 to: omit Index - 1 with: self starting At: 1. cορy replaceFrom: omitlndex Figure 11.14a
Numeric-Mag Nurneric-Nurnt
#('a b c ) copy Without Index: 2 i a c ) Fro rn: 1
Collections-Ui Collection;-5 Collections-Τ Collection:"- Collection:-;^
'string' c ο ρ y W i t h ο u 11 η d e χ: 3|
copyWithoutl "Answer E.g. # i 3 I copy | copy *- self species new: self size - 1. copy replaceFrom; 1 to: omitlndex - I
Figure 11.14b
000
with: self startingAt: 1. c ορy replace From: ο rn i 11 n d e :•.
247 11.3 Adding New Methods
Ν u m e r i c - fvl 3. g η i t υ d Ν u m e ri c - Ν u rn b e rs Arra yedG'olle Collection ο 11 e c 11 ο η s - U η ο ollections-Sequei ο 11 e c t i ο η s - Τ e χ t ollect ions-Array 3ollections-Strea
comparing accessing a. d ding removing opying
collect: do: findFirst: find Last: re verse Do: select;
message selector and argument names "comment s t a t i n g purpose of message" | temporary variable names | statements
Figure 11.15a
|00 000 Ν u m e ri c - Μ a. q η i t u d Numeric-Numbers ArrayedCollection MiMiKMimre^iiia«c Collection C o l l e c t ions-IJ η ordi C ο 11 e c t i ο η s ~ S e q υ e Collections-Text Collect ions-Array Collections-'otrea
collect: do: findFirst: find Last: reverse re verse Do con v e r t inq sel a. q a ι η co rn b i η a t i ο η s: ο r d e r undo "Answer a. collection containing a subset of all the corn! c o p y ; of cut the receiver's elements." paste do it I combinations I print it c ο rn ρ a π η q accessing adding removing copying
co rn b i η a t i ο η s *• Ο r d e r e d C ο 11 e c t i ο η w i t h : self, 1 t o : self s i z e - o r d e r do: c ο rn b i η a. t i ο η s a d d All; ({self
Figure 11.15b
Oio
-c οmbiηa tiοηs
ancif
format sρawη explain c o p y W i t h o u t I n d e x : i) c o m b i n a t i o n s : self s i z e - h ] ,
248 Modifying Existing Class Descriptions
^L
Ν υ rn e r i c - Μ a g η i t ud| Ν υ m e ri c - Ν υ m b e rs | A rra y e d C ο 11 e c t i comparing οη Collection accessiηq Collections-U no rd addiηg Collect ion s-Seque removing Collections-Text copying Collect ions-Array C ο 11 e c t i ο η s - S t r e a converting c . | 3 j S
combinations: do: findFirst: findLast: re ν e rs e reverseDo: select: w i t h : do:
cοmbiηatiοηs "Answer a collection c o n t a i n i n g collect ions of a I again τι b i ri a. t i ο η s ο f uηdο the receiver's elements, e.g., # ( a b c) combinations,' copy cut ρa ste t s e l f combinations: Ο
do it print it
c a ms e I format spawn e χ plain
Figure 11.15c
010 b y stem B r o w s e r Numeric -fvla goi Numeric-Ν urn t Collec tions-Ui Collections -S
Collections-T Collection.·-A Collect ion s-S
combinations "Answ er the receiver':
# i a b c ϊ copy W i t h o u t Index: 2 (a c ) 'string' copyWithoutlndex: 3 'sting' # ( a b c) combinations OrdersdCollection ( ( a b Ί i b c Ί fa. c Ί i c Ί f a b Ί fb Ί f a Ί f'i )
5 Of
t s e l f com
Figure 11.15d
roo
J
r 249 11.4 Modifying Class Comments
11.4 Modifying Class Comments
In the previous section, you saw how existing methods can be edited and recompiled, how protocol names are specified, and how new methods are added to a class description. A method can include a comment about its intended use; comments can be interspersed among the statements in order to explain the algorithm. Comments can be provided for the class as a whole, to document its potential use in the system. In a system browser, choose class category Graphics-Primitives, and choose class name Rectangle. In the classnames subview, choose the yellow button command comment (Figure 11.16a). A comment about the selected class appears in the text subview (Figure 11.16b). You can edit this text. For example, you can insert more commentary. The changed comment is stored when you choose the yellow button command accept in the text subview (Figure 11.16c).
Graphics-Dis Graphics-Pal Graphics-Vie Graphic s-Edi Graphics-CIo Graphics-Suf
file out print out sρawη Pen spawn hierarchy Point hierarchy Ouadrar definition
UBSUS
inst va.r refs class v a r refs class refs
O b j e c t subclass: # R e c t a n c rename i η s t a n c e V a r i a b I e Ν a rn e: remove c I a s s V a r i a b I e Ν a m e s: poolDictionaries: " c a t e g ο r y ; ' G r-a ρ h i c s - Pri rn i t i ν e s'
Figure 11.16a
sing
ring iqle function I tion and rcn or nning
250 Modifying Existing Class Descriptions
•ΤΙΜΒΙΜΙΙΜΜΗΜΠ
Graphic s-Ois Graphic.--Pat Graphics Graphic s-Edi' Graph ics-CIo Graphics-Sup
accessιηg comparing rectangle function testing truncation and rot transforming copying
I usually represent a. rectangular area, on the sere en, Arithmetic functions take points as arguments and carry out scaling and translating operation? to create new Rectangles, Rectangle functions create new Rectangles by determining intersections of rectangles w i t h rectangles,
Figure 11.16b
000 Collect ions-Suppo Pen accessing Point comparing Graphics-Display rectangle function G ra ρ h i c s - Pa t h s Q.u a d ra η g I e testing Graphics-Views truncation and roi. Graphics-Editors transforming Graphics-Clocks G ra ρ h i c s - S υ ρ ρ ο rt ||,1U1.TJJ ,-:,a 5 5 c ο ρ y i ri g I usually represent a. rectangular area on the screen, I have knowledge of points on the corners and sides, and I can determine my dimensions^ Arithmetic functions take points as argument a g a. ι η arry out scaling and undo ectangle functions translating operations to create new Rectar copy of rectangles with create new Rectangles by determining inters c υ t rectangles, paste do it print it
Figure 11.16c
010
f ο rrn a t sρawη eχρIaiη
J
Γ
Modifying Existing Class Definitions
12.1 Name of Superclass 12.2 Name of Class 12.3 Instance Variable Declarations 12.4 Class Variable Declarations 12.5 Pooled Dictionary Declarations 12.6 Class Category
252 Modifying Existing Class Definitions
The class definition of an existing class is obtained by choosing the class name in a system browser, or by choosing the yellow button command definition in the class-names subview of a browser. The definition consists of six parts: • name of superclass • name of class • instance variable declarations • class variable declarations • pooled dictionary declarations • class category name Each of these parts can be changed by editing the text of the definition that appears in the text subview of the browser, and then choosing the yellow button command accept. The consequences of these actions will be described in the following sections.
12.1 Name of Superclass
Changing the name of the superclass means that you are changing the (inherited) methods to which instances of the class can respond, and you are changing the (inherited) variables that describe each instance. In the browser shown in Figure 12.1a, class category Graphics-Paths and class name Arc are selected. The superclass name has been selected in the definition of Arc. Change the superclass name by replacing the text. In Figure 12.1b, the superclass for Arc has been changed from Path to Object. Choose the yellow button command accept to indicate that you are done editing and that the change should be made. If the new name already exists or if the first letter is not capitalized, a notifier will appear on the screen. After you understand the problem, close the notifier and correct the definition. If the new name is acceptable, the system recompiles all the methods and will report if the change causes some methods to refer to undeclared variables. The report is displayed in the System Transcript view, as shown in Figure 12.1c. Both Arc and its subclass Circle have been recompiled. One of the methods of Circle refers to the variable form, which was declared in Path and is therefore no longer within the scope of the methods of class Circle.
r 253 12.1 Name of Superclass S ν stem T r a n s c r i p t lii
G r a. ρ h ι c s - S υ ρ ρ ο rj L ι η e a. r F11 Kerne I - O b j e c t ; Kernel-Classes subclass: # A r c ^stanceVariablef'James: ' q u a d r a n t radius c e n t e r classvariableNames: " pool Die tiona ries: " c a t e q ο r y: ' G r a ρ h i c s - Ρ a. t h s'
Figure 12.1a
BOO System
Transcript
A ra ρ h ι c s - ν ι e w s υ ι re I e A ratrh i c s - Ε d i t ο rsl C υ rv e Kern el-Objects Kernel-Classes
I bphne
again υηdο ect^ subclass: #A,rc i ri s t a nee V a. r i a b I e Ν a m e s: ' q υ a d r a n t r a d i υ s c enter cIass• ' /• a r i a b I e U a m e s; '' paste do it ρ col Diet ion a ries: print it c a t e g o r y : ' G r a p h i c s - Ρ a t h s'
Figure 12.1b
Bio
format spawn eχρIaiη
254 Modifying Existing Class Definitions
recompiling A r c . done recompiling Circle,,, (form is Undeclared' 1 : done a c c essιηg d i s ρ I a y i ri g arFit kernel-classes O b j e c t subclass: # A r c i π s t a. n c e V a. r i a. b I e Ν a m e s: ' q u a. d r a η ΐ r a d i υ s c e n t e r c I a s s V a. r i a. b I e Ν a. rn e s: '' poolDictionaries: c a t e g o r y : ' G r a. p h i c s - Ρ a t h s'
Figure 12.1c
000 As will be illustrated in the section on changing instance variable declarations (Section 12.3), adding or deleting instance variables means that any existing instances will automatically be updated. When appropriate, you must check to make certain that all existing instances properly initialize any new variables.
12.2 Name of Class
Editing the class name is a way to create a new class description with the same definition as the old. The new class will be categorized in the selected class category, unless the class category is changed in the definition text. Editing the class name is not the way to rename a class. You rename a class by choosing the yellow button command rename in the classnames subview (Figure 12.2a). A prompter appears in which you type the new class name. Type Pare. When you are done typing the name, terminate by choosing the yellow button command accept or by pressing the "carriage return" key (Figure 12.2b). This prompter is unscheduled, so you must respond. If you change your mind, simply leave no characters in the prompter and terminate.
255 12.2 Name of Class «•'item Τ ran script recompiling A r c . done re c ο is Urn:
tile out print out Lira ρ η ι c s - ν spawn Graphics-Ει spawn hierarchy Graphics-C hierarchy Graphics-S definitior Kernel-Obji c ο rn m e η ΐ Kernel-Clas protocol; ist VZA' r e t : Jbiect. subclass: # A r d , , , , , , f instance ν anable class Variable Ν am poolDictionaries: ' c a t e g o r y : ' G r a ρ h ι c s - Ρ a. t h s'
Figure 12.2a
re c ο rn piling A re... d ο η e re c ο r is lJn lira p h i c s - V i e w s
liraphics-Editors (_•» r a ρ h ι c s - UI o c k s Ι υ u r ν e Gr a. ρ hi i c s - S u ρ ρ ο r| Line Kernel-Objects Kerne I-Classes
accessιηq J i s ρ I a. y i ri g
Object^subclass: # A r c instance V a r i a b I e Ν a m e s: ' q u a d r a nra t α radius ant ι us cs class Variable Names: " Enter η poolDictiona ries: " then a.( c a t e g o r y : 'G r a ρ h i c s- Ρ a t hs' Pa n-: A
a a qaiη υηdο copy ; s Ν a rn e • CFi cut ρaste do it
print it
Figure 12.2b
Oio
cams el
256 Modifying Existing Class Definitions When you rename a class, the name in the browser menu is updated and is selected. All subclasses refer to the class by its new name. Compiled methods that refer to the class are also correct. However, since the system source code is just text stored on a local disk or stored on a remote file server, all the source code text does not have updated references to Pare. (This is potentially confusing. The system compiled-code references to Arc have effectively all been updated to Pare, but the source code text is handled independently.) To remind you to find each method in which the class is referenced, the system searches for all references to the class (as indicated in the System Transcript). If any exist, a special browser is created (Figure 12.2c). This is a message-set browser, as defined in Chapter 10. You are asked to designate the rectangular area for the browser. The browser menu will contain references to class/messages whose associated methods contain references to Pare. However, the text will still show the word Arc (Figure 12.2d). Replace the word with Pare and choose the yellow button command accept (Figure 12.2e). If you do this for all the methods, when you later browse the system, you will have the correct source code text.
b y 51 em Τ ra η 5 c riρ t recompiling Arc... done recompiling Circle... (form is U n d e c l a r e d ) done Searching for references t o this class...
arFit
accessιηg displaying
e Ke rn e I • Pare class example Obiect Pa. re d i s ρ I a y Ο η: t ra η s f ο rm a. t i ο η: c I i ρ ρ i η g Β ο χ: ru I e: m a s k:
Figure 12.2c
BOD
257 12.2 iName of Class System Transcript recompiling A r c . done recompiling Circle.., (forn is Undeclared1! done a. c c e s 51 η q
bea.rehing tor references to this class.,,
displaying
Pare class example
Figure 12.2d
aTransforrnation clippingBox: clipRect rule: anlnteger mask: aForrn | new A re tempCenter | new A re *• Q Q new, tempCenter *• a. Transformation apply To: self center, new Arc center: tempCenter χ truncated @ tempCenter y truncated, new Arc quadrant: self quadrant. new Are radius: iself radius * a Trans format ion
ODD
bystern Transcript lii recompiling A r c , done recompiling Circle... (form is Undeclared) done Searching for references to this class...
arFit
accessιηg displaying
Kernel. Pare class example b I e c JiaBiiMtiiaMBMiwnMiginiimiinimimmMiBBiiwtii
agaιη υηdo copy cut Integer
aTransforrnation clippingBox: clipRect ρ a. s t e mask: aForrn do it | new A re tempCenter | print it
new Arc - Pare new. tempCenter ·- a Trans formation a p c a ri» e I elf format center,
Figure 12.2e
Ion
new Arc tempCenter ri e w Arc new,A re
center: tempCenter χ trur s ρ a. w η explain y truncated, q υ a d r a n t: self q υ a d r a n t . radius: iself radius * a Trans f o r m a t ion
258 Modifying Existing Class Definitions
Alternatively, you can evaluate an expression to rename a class. The message rename: is understood by all class objects; the message argument is a String representing the new name for the class. For example, let's do the previous example again (the illustrations assume that you did not do it before) and change the name of class Arc to be Pare. As shown in Figure 12.3a, type and select the expression Arc rename: ' Pare' and choose the yellow button command do it.
O b j e c t subclass: # A r c ί η s t β. η c e V ar i a b I e Ν a m e s: ' q u a d r a n t radius c e n t e r classVariableNames: " poolDictionaries: " c a. t e g ο r y: ' G r a. ρ h ί c ί - P a t h s'
Figure 12.3a
010 The task is complete, although the view in the browser has not been updated (Figure 12.3b). Deselect the class category Graphics-Paths by pointing to it with the cursor and clicking the red button (i.e., choosing it again). Then choose the category again (Figure 12.3c). In this way, you request that the menu of class names be updated. Notice the item Pare is now at the end of the menu.
259 12.2 Name of Class
re compiling υ ι re 19... (ronr is Ur
j e c t subclass: # A r c i η s t a ri c e V a r i a b I e Ν a rn e s: ' q u a d r a n t r a d i υ s c e n t e r ' c I a s s V a r i a b I e f'•·] a. rn e 3: " poolDictionaries: " c a teg ο r y: ' G r a. p hie s -Pa. t h s'
Figure 12.3b
BOO System T r a n s c r i p t III recompiling Circle,,, (form is Urn:
Graphics^v'iews circle G ra ρ h i c s - Ε d i t ο rsi C υ rv e Graphics-Clocks I Line G ra ρ h i c s - S υ ρ ρ ο rj Line a rFi t Kernel-Ob iects Kernel-Classes Ν a rn e Ο to u ρ e re I a. s s s υ b c I a. s s: # Ν a rn e Ο f UI a s s i η s t a n c e V a ri a b I e Ν a rn e s: 'in s t V a. rN a m e l i η s t V a rf\l a rn e 2' c I a s s V a ri a b I e Ν a m e s: ' CI a s s V a rN a rn e 1 CI a s s V a rN a rn e 2' poolDictionaries: " c a t e g o r y : ' G r a. p h i c s - Ρ a t h s'
Figure 12.3c
|00 000
260 Modifying Existing Class Definitions
If you now select the definition of a subclass of Pare, Circle, in Figure 12.3d, its superclass properly refers to the new name. All of the compiled code works correctly. However, the source code has not been changed; it still shows the word Arc in the text. To update the source code, you will have to edit the text yourself. In the System Workspace, edit the template for browsing all calls on a particular object. Find an expression like the following and change the argument symbol to be #Parc. Smalltalk browseAIICallsOn: (Smalltalk associationAt: #Parc) S ν s t e rn Τ r a. n s cript r e c ο m piling Circle.,, (for rn is Urn: Sea. re to thi
d i s ρ I a. y i η g display box a.cce
Arc π
Pare subclass: # C i r c I e i η s t a. n c e V a. r i a. b I e f•' •] a m e s: ' ? c I a. s s V a. r i a. b I e Ν a. m e s: " poolDictionaries: " c a. t e g ο r y: ' G r a. ρ h i c s - F1 a. ΐ h s'
Figure 12.3d
100 000 Select the expression and choose the yellow button command do it. In this way you obtain the message-set browser that gives you access to all methods whose text references Arc rather than Pare, as previously shown in Figures 12.2c and 12.2d.
12.3 Instance Variable Declarations
To illustrate the effect of changing the instance variable declarations, an example of modifying Pare is given in this section (Pare was formerly Arc if you followed the previous example). Start by undoing the ex-
261 12.3 Instance Variable Declarations
ample of Figure 12.1b, so that Pare, once again, is a subclass of Path. Open a workspace and type the expressions shown in Figure 12.4a. Evaluating these expressions declares two temporary variables, aForm and anArc; creates a new instance of Form referred to by aForm; creates a new instance of Pare referred to by anArc; initializes the new Pare with radius 50.0, quadrant 4, and center wherever you point with the cursor and click any button (Sensor waitButton). (The cursor changes to an arrow with an asterisk—the execute cursor—until you click the button.) The Pare is then drawn on the display screen (Display). And, finally, an inspector for the Pare is created. The image of the Pare and the inspector for the instance are shown in Figure 12.4b.
System Browser (J iii 11 Q c 11 ο η s - Ό υ ρ
Graphics-Primit Graphics-Displa Graphics-Vie wi Graphics-Editor Path subclass i η s t a. ri c e V a classVariat poolDiction category: !
Figure 12.4a
010 Notice that the instance of Pare has five instance variables; their names appear in the menu of the inspector. Two of the variables are declared in the superclass Path, and three are declared in Pare. Now return to the browser and change the superclass of Pare to be DisplayObject (Figure 12.4c). The inspector is no longer correct. Close it by choosing the blue button command close (Figure 12.4d). Return to the workspace and once again evaluate the expressions that create a Form. A notifier appears (Figure 12.4e). The message form: was implemented in class Path. By changing the superclass of class Pare, the message form: is no longer part of the protocol of Pare. The instance variable form and the message form: must be specified in class Pare.
f
262 Modifying Existing Class Definitions
Workspace | a Form a. η A re | a F ο r m - For m η e w e χ tent: 1 © 3 Ο, a.Form black. a. n A re *• Pare new, a n A re form: a. Form, anA,re radius: 50.0. Ά
η Arc: Γ: ο η t o r
:= e Γι 3 Ο r W a i t Β U110 Γι,
: 4, •ι: Display.
Figure 12.4b
000 Workspace |a.Form anA,re (J ο 11 e c 11 ο η s - S υ ρ G r a p h i c s-Prim it LinearFit Graphics-Displa wnamiwaaaim Spline Graphics-Views Graphics-Edit ο
accessιηg displaying
aqaιη υηdo cορν Displa. y Object s υ b c I a s s: # Ρ a r c cut i η s t a. nee V a. r i a. b I e Ν a m e s: ' q υ a. d r a n t rρaad51 i e classVariableNames: " do it print it ρoo(Dictionaries: " c a. t e g ο r y: 'Graphic s - Ρ a t h s'
Figure 12.4c
ISU
c ante I format sρawη explain
010 i
263 12.3 Instance Variable Declarations
'..Vorkspace i; b vstern Browser!
I a Form a. n A re
Li η e lec tion j - b Gra μ hie 5-Prim it Lmea.rFit Graphic 5-CM;pic Bare
a c c e 5 51 ri g d i 5 ρ I a. y i η g
: radius c e n t e r
Figure 12.4d
001 space | |3Fc rrn an Are | 5 . s t e r ι Rrrr,,'^rl. Message not under stood: form:
^^^^^^^^^^raj.
Graph Pa re( O b j e c t ) • d o e . N o t U n d e r s t a n d Graph Graph U nde fined Ob j s e t • ••["'clt Graph Compiler.' -eve I u a t e: in: t o : η n t if y ing: if Fa il: Graph S t r i n g HolderC oritrc l e r ' . ' d i l t k. Displa b t r i rig Holder'. ontro 11 e r( Γ'.'Ι ο j s e Μ e η υ 'J o n t ro 11 e r) V M l l o w B u t t j n . A c t i v i r ν in el
Figure 12.4e
000
I":
re
olC'ic t i o n a ries:
inspect
f
264 Modifying Existing Class Definitions
First add the instance variable form to Pare. Edit the class definition and choose the yellow button command accept (Figure 12.4f). Now copy form: from Path to Pare. Choose the class category Graphics-Primitives, class Path, protocol accessing, and message selector form:. Choose the yellow button command move (Figure 12.4g).
Di.-playjb.ieet
;ubela;;
ι η ; t a r m «••••• a n a
# t
bit
r a d i u . " c Q ri t t i r
- r ι ΓΙ Γι a f i ^ -
lat.qnr-y 'Gra pr,n::.-Pa t t l l ^
Figure 12.4f
J o 11 e c 11 ο η." - b υ c
.it".? phn: .--Pa t h : . l i f a ρ hie _•-V i 9 ·•,·.•: l i f a p h i e .--Editor
t e ί 11 η q d ί ί ρ I a y 1 ri q d i s p l a y be rr? n.-forr
* t h y a f q u r n y n t , aFofrn, t
Figure 12.4g
rnrr
265 12.3 Instance Variable Declarations
In the prompter that appears, type Pare > accessing and then choose the yellow button command accept (Figure 12.4h). This then copies the method to class Pare. Do the same copying sequence for the message form so that both methods are in Pare (Figure 12.4i). Wor1 s System Browser
la Form a n A re
'Jollec tions -Sup In finite Form Ci rap hie s-Prim i OpaqueForm Pa i'^ qra ph Lira phic s-Pa t h s i'ir^ phic s - V i e w ; lira phic .-.-Editor TiHfcW»
I.
first Point: form testing d i s ρ I a y i Γι g display bo· a traηsforming
: aForrn "fvlal·^ the a r g u m e n t , a Form, trn form - a Form
Figure 12.4h
last offset again Type destmat undo (Ulass • pro toco cop then a c c e p t or Pan: do i t print jr
010 center:ra dius: center:ra dius:gi form torm: ^ qua.dra.nt quadrant: message s e l e c t o r and argument names 1 ' c ο m m e η t s t a. t i η g ρ u r ρ ο s e ο f me s s a g ί | t e m p o r a r y variable names | statement s
Figure 12.4i
266 Modifying Existing Class Definitions
Return to the workspace and once again evaluate the expressions that create a Form, a Pare, and an inspector for the Pare. This time the inspector shows four instance variable names in the menu (Figure 12.4J). Won .-t |a Form a n A.re j a Form - Form n e w e - t e n t : Ι'ϊ'οΰ. Collec t ion."-Sup Gf.? ρ hie :• -Prim it Line a Form blacl· . Li η s i anA,re - Pare n e w , Parti a n A.re form: a Form *p Splin anA,re r a d i u ; : 5 0 . 0 , r w a. i t Β υ 11 ο η
b v."tern Browser
α υ adrant
f jlTil
Figure 12.4j
000 The method for form: simply assigns a value to the instance variable form. If existing instances of Pare must have this variable initialized, evaluate an expression such as the following one. Pare alllnstancesDo: [ :each | each form: (Form new extent: 1 @30)]
12.4 Class Variable Declarations
Adding or deleting class variables is similar to adding or deleting instance variables in that the methods of the class and its subclasses are recompiled. If any method references a variable no longer in the scope of the method, the name of the variable is printed in the System Transcript. Typically, initialization of class variables is done in methods specified in the class protocol rather than in the instance protocol, although both are feasible. By convention, class protocol has a category class initialization and a message selector initialize whose method does the
267 12.5 Pooled Dictionary Declarations
class variable initialization. An example from class Cursor is shown in Figure 12.5.
"a.p hie."-Paths •a.phk s- V i e w s •aphie .-.-Editors -a ρ hies-Clocks ••? p h i e s - S u p p o r irnel-'jbiects
initialization initialize Ο i s ρ I a y fvl e d i υ m i n s t a n c e erea.tion Display Object c u r r e n t cursor Displa ySc re en c ο Γι s t a. n t s DisplayTe.:·: t
jnitidlize "Create all the standard cursors -I
-• υ
r
-•'-'
It·
Jur.-.u " onqin I.'urso r«.? α
Jurso - write J υ r :• υ • '•/•/ a i t
Z:urso • L> 1 aril· Jurso • « . e c u
Figure 12.5
000
Jur.-.i.i
_-. q υ.? r
Jurso
• η or ma
12.5 Pooled Dictionary Declarations
Adding a name of a pooled dictionary in the class definition means that any variable name declared as a key in that dictionary is now within the scope of the methods of the class and its subclasses. Deleting a pooled dictionary reference means that possibly several variables have been removed from the scope of the class methods. There is no special initialization needed if a pooled dictionary is added to a class definition. An example of class DisplayText in which a pooled dictionary, TextConstants, is declared as shown in Figure 12.6.
268 Modifying Existing Class Definitions
SystQm Browser •a p h i e s - P a t h s -aph.es-views •aphic s - E d i t o r s -aphics-Clocl· s •aphic s - S u p p o r i r n e l - u b i e c ts
Displa y Γνΐ e d ι υ m Oispla v j b i e c t Displa ν Sere en Form InfiriiteForm
a c c essιηq displa y i n g d i s p l a y bo· co η v e r t ing private
C'isplay'jbjec t subclass: #C'isplayTe • t i η s t a ri c e V a ri a b I e Ν a rn e s: ' t e • t t e • t S t ey
offset form
classVariableNarnPs: " ρ ο ο ( D i c t i o n a r i e s ; " Τ e • t C IJ η s t a n t s c a t e q o r y . ' G r a phic s - C ' i s p l a y '"'bjec t s '
Figure 12.6
000
12.6 Class Category
To change the category of class, you can edit the category reference in the class definition. The class is moved to the new category and the browser is updated. There are two cases of things you can do—move the class to an existing category, or move the class to a new category. In Figure 12.7a, the definition of class Path is shown in a browser. Part of the class category, originally Graphics-Display Objects, is selected. Replace the selected part by Primitives as shown in Figure 12.7b. Choose the yellow button command accept to indicate that Path should be moved to the existing category Graphics-Primitives.
269 12.6 Class Category
InfiniteForm Graphics-Paths OpaqueForrn Graphics-Views Graphics-Editors Paragraph Graphics-Clocks G ra ρ h i c s - S u ρ ρ ο π Kernel-Objects
accessing testing disρIayiηq display box a transforming addiηq
Display Object subclass: # P a t h i η s t a η c e V a ri a b I e Ν a m e s: ' to rrn c oils c t i ο η Ο f Po i η t s ' c I a s s V a r i a b I e Ν a m e s: " 1 poolDictionaries. " c • a. t e g ο r y: ' G r a p h i c s - y
Figure 12.7a
ion Graphics-Paths Graphics-Views Graphics-Editors Graphics-Clocks Graphics-Suppor Kernel-Objects
Form InfiniteForm OpaqueForm Paragraph
accessιηq testing disρIayiηq display box ac t r a n s forming addinr again
D i s ρ I a y Ο b j e c t s υ b c I a s s; # Ρ a t h instance V a r i a b I e Ν a m e s: 'for' rn ( c I a s s V a. ή a b I e Ν a m e s: " poolDictionaries: " c a t e g o r y : ' G r a ρ h i c s - Ρ r i m i t i ν e s'
undo copy do i t print it format spawn eχρIaiη
Figure 12.7b
Oio
270 Modifying Existing Class Definitions
In Figure 12.8a, the definition of class MappedCollection is shown in a browser. It is categorized under Collections-Sequenceable. The class category is changed to Collections-Miscellaneous after you choose the yellow button command accept (Figure 12.8b). Because this is a new category, the browser must be explicitly updated. Choose the yellow button command update in the class-category subview of the browser (Figure 12.8c). Scroll to the end of the class-category menu. The new category appears. Choose the new category, Collections-Miscellaneous, to see that MappedCollection is in the class-names menu (Figure 12.8d).
accessιηg addiηg cορyiηg ρο ri ηη t i η g :j ο 11 e c t i ο η :• - A m. ·, Ο rd e re d C ο 11 e c 11 : ο 11 e c t i ο η s - S t re .Η Ό ο r t e d C ο 11 e c t i οprivate η en υ me rating :ollectionj-Supp.|llBBBP| , , _ ο 11 e c t i ο η s u b c I a s s: # fvl a ρ ρ e d C ο 11 e c t i ο η i η s t a η c 9 V a r i a b I e Ν a m e s: ' d ο m a i η m a ρ ' c I a s 3 V a r i a b I e Ν a m e s: " p o o l D i c t i o n a r i e s : ?? c a t e g οry: ' C ο 11 e c t iο η 3 -1
Figure 12.8a
loo
271 12.6 Class Category
a. c c e s s ι η g a ddiηg imEiima.Wffllru.tn.1. c ο ρ y ί η g OrderedCollecticm p r i n t i n g private en υ me rat in a g a. ι η undo l e c t i ο η s υ b c I a s s: # Μ a ρ ρ e d C ο 11 e c t i ο η copy i n s t a n c e V a r i a b I e Ν a. rn e s: '6 ο m a. i η m a. p cut class 'ν' a. r i a b I e Ν a. m e s: " paste do It poolDictionaries: " print it c a t e g o r y : ' C o l l e c t i o n s - fvl i s c e 11 a. n e ο υ s' c a. n & e I
rormat spawn e χ ρ lair
Figure 12.8b
ioio η 11 Ρ Γ: t i ο sΓι- A b -
ϋ
rr re I n t e r v a l LinkedList b t Ordered Co 1 e c t o r η '-a d d spav. category b o r t e d c o l l e c 11 cl l rename c 1 a s. '•-] remo 1 s subclass: ιΦ* Ν 'Ί m n-ifni =, -A e d i t .^ ^ : :| rf'Ja.rr .bleNames: r . I ,=i ••, ·-.'•'aria.ble Names: -ι ri J a m e1 Cla.ssV'ar"N3me2' 'Cl·: ρ oolD c t i e r a r es: " c a t P g ο r v1 I l e c t i o n s - S eque n c «able file ο ut print c u t
f
\
;::-:::::
Figure 12.8c
Oio
•
'••••:••
•'.'•:•
:
• : • - ' - • [ . ' : • ' - • .
272 Modifying Existing Class Definitions
Sy
stem Browser I 51 e rn - υ ο m ρ i 1 e r ed 31 e m - Fl e 1 e a. s i ηMapp c
ect ίοr
F\W
Fik FiliI
Μ; rneOfSupercIa . 3 SUbC la instanceV'a.ri able Ν a me c a ^.Variable ρ ΓΙ η 1D i r r i η η a r
# N a . m sOf C l a s s 1 i η s t V arNa me 1 inst'v'a.rNa rn e is. '
c a t e g o r y : 'C j l l e c t i c n; -Γνΐ 3 c e l l a. " e ο u s'
Figure 12.8d
100 000 The two examples just presented show how to move a class into a new category, either one that existed or one that is created anew. It is possible to create a new category by choosing the command add category from the yellow button menu of the class-category subview. Adding a class category works in a way that is analogous to adding a new message protocol (see Section 11.2). The yellow button menu also includes the commands rename and remove. These also work in a way analogous to the commands used for renaming and removing message protocols. The command edit all is in the class-category subview yellow button menu. If you choose this command, the class categories and class names in each category appear in the text subview of the browser. The syntax for the categorization is like that for the organization of the message protocol/message selectors. You can modify the organization and then choose the text subview yellow button command accept. The syntax will be checked and, if correct, the class categorization will be updated. You should not attempt to remove access to a class by deleting it. You cannot specify more than one category for a class. And you cannot create a new class simply by inserting its name in a category.
r
Creating a New Class Description
13.1 Define a New Class 13.2 Define the Class Protocol 13.3 Define the Instance Protocol
274 Creating a New Class Description
Class Commander represents an object that controls several line-drawing Pens and coordinates their drawing a design. The class was presented as a graphics example in the book Smalltalk-80: The Language and its Implementation; it is presented here to illustrate the process of creating and testing a new class description. A Commander is an Array of Pens. Pens controlled by a Commander can be given directions by having the Commander enumerate each Pen and evaluate a block containing Pen commands. So, if a Commander's Pens should each go: 100, for example, then the Commander can be sent the message do: [ -.each | each go: 100] Alternatively, the Commander itself can be made to respond to the message go: 100, where the method associated with the message go: consists of the enumeration message. A Commander also responds to messages to arrange its Pens so that interesting designs based on symmetries can be created. The message shown in the figures is fanOut. The purpose of fanOut is to arrange the Pens so that their angles are evenly distributed around 360 degrees.
13.1 Define a New Class
You have already reviewed all the parts of the browser that are used in creating class descriptions, with the exception of declaring a new class by editing the template for a class definition. When you want to add a new class description to the system, you first decide on the class category in which you want to access the class. Choose that category. A template for specifying the class appears in the text subview. (See Section 12.6 on how to add a new category.) Class category Graphics-Display Objects is an appropriate category for class Commander. Choose this category (Figure 13.1a). The class definition template is in the form of a message to a class. The first word in the template represents the message receiver (NameOfSuperclass). It should be replaced by the name of the class that is to be the superclass of the new class. Select this word (Figure 13.1b). Type the superclass name; in this example, the superclass is Array (Figure 13.1c). The message pattern consists of keywords (those words with trailing colons) that should not be changed, and message arguments. None of the syntax for literals should be changed (that is, the hash mark # and the single quotes). The message argument for the keyword subclass: must be a symbol constant; the rest of the arguments must be string constants.
Τ
275 13.1 Define a New Class
iystern Browser 'Jollec t i o n s - b u p p Graphic. 5-Prirni tiv Lira ρ hies-Pa Graphics " V i e w s Gra p h i c s - E d i t o r s Graphics-Clocks
DisρIa yΜedium Display O b j e c t Displa ySc re en Display T e x t
nnaeiroKi
a m e Ο f b υ ρ e r c I a s s s υ b c I a s s: #· Ν a. rn e Ο f υ I a s s ι η s t a Γι c e V a. ri a b I e Ν a. rn e s: ' i η s t V a rf'J a rn e 1 i η s t V a rf'.J a. m c I a ; s V a r i a b I e i1·.] a rn e s: ' CI a s s V a r Ν a rn e l CI a s s V a r Ν a rn poolDic tiona.ries: c a t e g o r y : * G r a ρ h i c s - D i s ρ I a y > j b j e c t s'
Figure 13.1a
WO 000 'Stern Browser 1
• J o 11 e c 11 ο η s - b υ ρ ρ ι G r a. ρ h i c s - Ρ r i m i t i ν j C υ r s ο r Display Medium
Graphics-Paths Graphic;-views Graphics-Editor; Graphics-Clocks NarneOfSupercN
Display Object Display Screen DisρIa y Τ e; g i a g I i I M
s u b c l a s s : # Ν a. rn e Ο f (J I a. s s
i Γι s t a n e e V a r i a l^e Ν a rn e s: ' i η ; t V a r Ν a rn e 1 i η s t V a r Γ' J a rn e 2" c I a s ; V a r i a. b I e Ν a rn e s: ' CI a s s V a. r Ν a rn e l poolC'ic t i o n a r i e s : c a t s q ο r ·.·•: ' G r a ρ h i c s - C1 i s ρ I a y Ο b j e c t s'
Figure 13.1b
Coo
CI a ; s V a r Ν a rn e 2 '
276 Creating a New Class Description The desired class name is Commander. Select the first message argument NameOfClass (Figure 13.1c) and replace it with Commander (Figure 13.1d). Select the "dummy" instance variable names instVarNamel
System Browser
•.tray 5Ubda 5 5: i η 5 ΐ a n c e V β r i 3 b I e Ν 3 ΓΙΊ e :•: ' i rf^ t 'v 3 r Ν a m e l
in j t V a r I1··) a m e 2 '
p o o l C ' i c t i o n a r i e :>: c a t e q o r y : " Ίϋ r a ρ hie .-.-C'iipla y C'b j e c t : . '
Figure 13.1c
System Browser ;: ο 11 e c 11 η η ι - b u ρ μι ii"a p h i c j . - P r i m i t i v raphic 5 - Pa r h j 1 r τca phtc ; - Vie ν·.· _. i r a phic i - E d i t o r
IJ r"; ο r : pi a y Medium r.pla y j b j e c t ;pla y Sc re en
T i a ^ m g 3 r r a y ;. u b c I a 11: &' J ο m ΠΊ a n d e
ι Γι;. t a ri c e V a ri a b l e Ν a rri e J : '•instVarWame 1 instVarWame2 a me 1 Cla.ss poolC'ic riona r i e ; : c a t e q o r y : O r a phic ."-C'i.'pla y C'bjec t : · '
Figure 13. Id
277 13.1 Define a New Class and instVarName2, and remove them by choosing the yellow button command cut (Figure 13.le). Similarly, remove the "dummy" class variable names ClassVarNamel and ClassVarName2 (Figu^ 13.1f). (Notice
System Browser ollections-bupp raphic s-Primitiv Graphics-Path; Graphic ; - V i e w s Sraphics-Editor; Graphics-Clocks
Cursor D i s ρ I a v' Μ e d i υ m Display O b j e c t Display Screen Di;playText
5 ν subclass: # Commander instVarName2 instance V a ri a b I e • f'• J a . m einstVarNamel s: ' ' a rN a m e 1 c I a s s V a. rN a m ί c I a s s V a r i a b I e Ν a m e s: 'Class'· poolDictionanes: c a t e g o r y : ' G r a ρ h i c s - D i s ρ I a.Objects' ;·.
Figure 13. le
010 System Browser C ο 11 e c 11 ο η s - S υ ρ ρ G re ρ η ί c s - F'ri rn i t i ν C u r s o r D i ; ρ I a y fvl e d i υ m Graphic s-Pa ths D i s p l a y Ο Inject 'lira phic ; - V i e w ; Displa ν S c r e e η Graphic s-Editors D i s p l a y T e x t Graphics-Clocks •.ft' a v1 s υ b c I a ; s: # C ο m m a η ι J e r i η s t a n c e V a r i a b I e Ν a m e s: " class V a r i a b l e Nam ClassVarNamel ClassVo.rName2 poolDic t i o n a r i e ; : '" c a t e g ο r ν: ' G ra ρ h i c ; - C1 i ; ρ I aO b i e c t s '
Figure 13. If
Oio
278 Creating a New Class Description that if you do add class variable names, the first letter of the name should be capitalized.) Now evaluate the message expression by choosing the yellow button command accept. Class Commander is now defined in the system. Its name appears in the browser class-names menu (Figure 13.2). Because it is a subclass of Array, class Commander must be a "variable subclass," which means that its instances may have different numbers of indexable instance variables. The system automatically made this designation. All of the capabilities that support browsing, querying, and modifying system classes are available for this and any user-defined class.
a y ν a r i a b I e S u b c I a s s: # < J ο m m a n d e r instance V a r i a b I e Ν a m e s: " classVariabluNames: " poolDictioriaries: c a teg ο r y: ' G r a ρ h i c s - D i s ρ I a. y Ο b j e c t :
Figure 13.2
13.2 Define the Class Protocol
An instance of class Commander should be initialized by sending the class the message new: with an integer representing the number of Pens that the Commander must coordinate. The message new: must be reimplemented in the class protocol of Commander in order to create the Pen elements of the array. Choose the browser menu item class (Figure 13.3a). The message-category subview displays the categories for the class protocol; none have been specified as yet. Add the protocol name instance creation by choosing the yellow button command add protocol in the message-category subview (Figure 13.3b). The prompter
279 13.2 Define the Class Protocol
: ο ΓΙΊ m a ri d e r c I a s s i ri s t a ri c e V a r i a b I e Ν a m e s:
Figure 13.3a
100 000
:οmma nder cIa ss i η s t a n e e V a r i a b I e i'cJ a m e s: "
Figure 13.3b
foio
280 Creating a New Class Description
appears; type the new name and then choose the yellow button command accept (Figure 13.3c).
a c 11 ο η s - ο υ ρ ρ aphies-Primiti 1 ·,· •a ρ hie."-Pat h i ••a ρ hie 5 - V i e w s ••aphics-Editors •a. ρ hies - C l o c k s
again
ι η •-. τ
Λ.
ηΓ
Ρ
Uοmm3Γιder el3.ss i η s t a n c e V a r i 3. b I e Ν 3. m e s:
Enter new protocol then accept or CR ι r i ; 13. n e e e r e 311 ο η
undo copy cut ρ a. s t e do print it c a. nV e I
Figure 13.3c
010 The new protocol appears in the message-category subview (Figure 13.3d). It is automatically selected and the method template appears in the text subview. Edit the method template to specify the new method for new: (shown in Figure 13.3e). This method creates an instance of Commander and assigns it to the temporary variable newCommander. For each element of the Commander array, a new Pen is created and stored. The new instance is returned as the result of the method. Choose the yellow button command accept in the text subview to compile the method and add it to the class description.
r 281 13.2 Define the Class Protocol
Collections-Suppf Graphics-Prirnitiv Cursor Display Medium Graphics-Paths Display Object Graphics-Views Display Sere en Graphics-Editors DisplayText Graphics-Clocks message selector and argument names "comment stating purpose of message" | temporary variable names | statemeηts
Figure 13.3d
iooo •imiaimaMMII.il
new: η υ m b e rΟ fΡe η s " C r e a t e a Commander w i t h numberOfPens elements, e a c h o f /•/hich is a Pen," agaιη undo | newCommander | copy cυt nevvCommander - super n e w : numberOfPens. ρ a. s t e 1 t o : numberOfPens do: do i t [ :index | n e w C o m m a n d e r a t : index p u t : Pen n e w ] , print it t newCommarider
l
Figure 13.3e
Oio
cans el format spawn e 'plain
282 Creating a New Class Description
SystQm Brow;er 1 U ο 11 e c 11 ο η s - Ό υ ρ ρ|ι Commander L i r a p h i c ; P r i m i t i v ι:ur;or
Irfifeiti A U » B w ta η IHN D i;pl a. v Medium Graphic;-Pa t h ; Disp ay Object Graphic ; ν IPW; Disp Disp ay T e x t Graphic;-Clock;
usmmmam
new: numberOfPe n ; "Create a Ccrn rn a ri d e r w i t h η υber'JfΡeη; Γ e 1 err e η t ; , each of which i ; a Pen." | newCommar der | er - ;• uper new: jmberufPen;. η 1 to: number j f P e n ; do: [ :inde • | newC:ornma η der a r: inde • ρ υ t: F e Γι η e w ] . ι newComrna r derA
Figure 13.3f
000 The message selector new: appears in the message-selector menu (Figure 13.3f). Find out whether this method works. In the text subview, type the creation message Commander new: 4. (Note that we typically opened up a separate workspace in which to type and evaluate expressions. However, any text view in which the text editor and the do it command are available can be used.) Send the new instance of Commander the message inspect. The expression is shown in Figure 13.4. Select it and choose the yellow button command do it. You designate a rectangular area in which the inspector will appear. In the inspector, choose the pseudo-variable self. The value that prints shows that the array has four elements, each a Pen (Figure 13.5). Do not close the inspector because we will use it again. Now let's go back to the browser to add line-drawing messages to Commander. Before you will be able to make new selections in the browser, you have to indicate that the text you typed in the text subview was temporary and not to be saved. Do so by choosing the yellow button command cancel (Figure 13.6).
283 13.2 Define the Class Protocol
System Browser I 1
: ο 11 M c t i ο ri s -:- υ ρ ρ[Commander ι ] ' g r a p h i c 3 Primitivi cursor uftSlnntJkOmiUnKWPi D i s ρ 1 a ν Μ e d i υ rn Graphics-Pa ths Display Object Gra phic s-Views Displa yE'C re en Graphics-Editors Displa y T e x t Graphics-Clocks i η s t a ri c e ^ ^ a ^ ^ ^ l
Ι i
Figure 13.4
ΟΙΟ
new: numberOfPens "Create a Commander with nun berOfPens elements, each of which is a Pen," | ri e w C ο rn rn a r d e r | ri e w C ο rn rn a n d e r *~ s υ ρ e r η e w: η i.: o p y Pens, 1 t o : numberOfPens do: [ :iη de • :• | ri e w ' J ο m rn a n d e rB a τ^ j Pen τ newComma r der [p~rinf\it| accept «Commander new: 4) i n s p e c t ^ ^ ^ ^ l cancel forma t spawn e : •• ρ 1 a i η
System Browser c one c 11 ο η s - b υ ρ ρ ι Gra phios-Primitiv Ο ί s ρ I a. y Μ e d i υ rn Display O b j e c t Gra phics~Paths Gra phics- Views Displa y b c r e Graphics-Editors Graphics-Clocks ri e w : η υ rn b e r Ο f Ρ e η s '' C r e a t e a. C ο m rn a ri d e w h i c h is a. Pen." | n e w Comma n d e r |
Figure 13.5
100 000
ri e '·,•'.•' C ο rn rn a n d e r *• s υ \ι 1 t o : nurnberOfPens d [ :iη d e • · | η ew Cοη τ new 1 !: ο mm a nder ι C on ι rn ? nder ne
4 ι ins ρ
new],
\\\\\\\].\:\::::'V::'::\\':\\\':\'::':\':\':-']]]\:\]'.'[\':::\':':]\'-':'-\'-':
:'•':':'• :'-:'-\'-\':\':':'-:<'-:'-'.^
\]\^\'
284 Creating a New Class Description
n e w : numberufPens a. cj a ι η " > J r e a t e a ' J ο m m a n d e r w i t h η υ m b e rO f Ρ e ηυsri el dο ea eh οf •·hic h is a Pen." copy
cut
ρ a. s t e
newijommander - super new: numberufPeris.
do it . jt
ρΗη1
1 trr. numberufPens do:
Figure 13.6
010
[ : i η d e • | η e w C ο m m a nd e r a t : i η d e • put:F & S Q i l l ] · τ newComma nder | spawn jla.inl 4) inspect
13.3 Define the Instance Protocol
Now select the browser menu item instance and specify three protocols, distributing, moving, and geometric designs. You can use the add protocol command. A faster way to add more than one protocol is to choose the yellow button command protocols in the class-names subview (Figure 13.7a), and then edit the text subview as explained in Section 11.2 (Figure 13.7b). Choose yellow button command accept. Choose the category distributing and edit the method template to specify the method for fanOut (Figure 13.8a). This method consists of one enumeration statement in which each element of the Commander is retrieved (self at: index) and sent the message turn:. Each element is (360/ self size) degrees away from its neighbor. Choose the yellow button command accept. The message selector is added to the menu in the browser (Figure 13.8b). Return to the inspector for the instance of Commander created earlier. Inspect one of its elements by choosing the element (for example, element 2), and then choosing the yellow button command inspect (Figure 13.9a). An inspector for the Pen is created. Choose its instance variable direction and note that the value is 270.0 (degrees) (Figure 13.9b). This value is the default for all Pens.
285 13.3 Define the Instance Protocol
file out print out spawn spawn hierarchy j rap hies-Pa Graphic?-'·/ Graphics-Ed Graphic s -.rra y va riableSi in sta.nceV a. rial rename classVariableN remove poolDictionariw· category: ' G r a. p h i c s - D i s ρ I a. ylects' Ob
Figure 13.7a
Oio
'distributing' ί ' ΓΓι Ο V i Γι q' ) 'geori'ietric designs' )
cartel tormat spawn eχρIair
Figure 13.7b
Oio
286 Creating a New Class Description
ran out " A r r a n g e t h e Pen 5 so t h a t distributed around
their angles
o f o r i e n t a t ion i.rQ e v e n l y
3 6 0 degrees,'
a. g a. ι η undo
1 t o : self size do: iself a t : i n d e ^ i t u r n : ίindex - 1Ί t :
Figure 13.8a
self s i z e i ^
copy cυt Paste do it print it format spawn
010
e • ρIa iη
C ο 11 e c t i ο η s - b ι j ρ ρ Gra.phics-Primitiv (Jursor ΒΙΒΒΙΙΙΜΗΒΒΒΕΜ D i s ρ I a y fvl e d i υ η Graphic s-Paths Display O b j e c t lira ρ hie s - V i e w s Di splci ySc re en Graphic 3-Editors Display T e x t lira ρ hie s-Clocks fanOut
™"™
" A r r a n g e t h e Pens so t h a t t h e i r angles of o r i e n t a t i o n a r e eve η I; d i s t r i b u t e d around 3 6 0 degrees." 1 t o : self size do: [ :inde· | (self a t : in d e n t u r n : (index - 1) * ( 3 6 0 self s i z e i l
Figure 13.8b
ODD
287 13.3 Define the Instance Protocol
by5tern Browser! 1 J ο 11e c t1 ο η 5 - b υ ρ ρCore < man der Gra.phics-Primitiv< mονiηg Graphics-Display Display Medium Display O b j e c t geometric design; Graphic 5-Paths Graphic s-View s D i s ρ I a y S c re exL· Graphics-Editors Display Te t Comrnarider Graphic s-Clocks Pen fanOut "Arrange t h e Pens so d i s t r i b u t e d around 3 6 0 d
1 t o : self size do: [ :index | ί s e I f a t : i η d e χ ϊ 11.
Figure 13.9a
Oio b y stem B r o w s e r U ο 11 e c 11 ο η s - b υ ρ ρ < Graphic s-Primitivi Graphics-Display D i s ρ I a y Μ e d i u m m ο ν ι ΓΙ g Display Object geometric designs Lira ρ hie s - P a t h s Displa y b c r e i Gf aphic :•- v i e w s 1 'lira phic s - E d i t o r s D i s p l a y T e x t J ο m m a. n d e r Graphic s-'I.locks t h e Pens so t h a t
270.0
•00 Figure 13.9b
i
000
self 1
2
a Pen
288 Creating a New Class Description
Direct each of the Commander's Pens to "fan out" around 360 degrees by evaluating the expression self fanOut within the text subview of the inspector for the Commander. Type and select the expression, and then choose the yellow button command do it (Figure 13.10). Now check the value of the variable direction of the Pen whose inspector was created (Figure 13.11). This is the second of four Pens; each Pen orientation should differ by 360/4 = 90 degrees. The first Pen should remain at 270 degrees, the second should be at 270 + 90 = 360 = 0, as indicated. Continue to test the new Commander. In the inspector for the Commander, type the expression self do: [ :each | each defaultNib: 4. each go: 100] which directs each of the Pens to draw, with a 4 χ 4 square brush, a straight line 100 pixels long. Type and select the expression, and choose the yellow button command do it (Figure 13.12a). The result is a "plus" sign as shown in Figure 13.12b. Add more messages to the class description for Commander. Add the messages turn: (Figure 13.13) and go: (Figure 13.14) to the category moving. Add the message spirakangle: (Figure 13.15) to the category geometric designs.
stem B r o w s e r I e c 11 ο η s - b υ ρ ρ distributing Graphic s-Primitiv Display Medium mονiηg Graphics-Paths Display Object geometric design; Graphics-Views Display Sere* Graphics-Edit or s Display Text Commander Graphic 5-Clocks Pen η Out .-.rr Pen the Pens so t h a t distribu width height s o u r c e '••'•
source Ί' clip:-: clip ν clip Width clipHeight fra me I o c a t i ο ΓΙ
Figure 13.10
010
direction
pen Down
289 13.3 Define the Instance Protocol
bν;tern Browser! Collections-bupp Graphic: s-Primitiv Graphics-Display G r a p h i c s " Pa t h s Grs ρ hie s - V i e w s Lira ρ hie ."-Editor; Graphics-Clocks
Commander D i s ρ I a. y fvl e d i υ m geometric designs Display O b j e c t Displa v S c r e i Display T e x t (j ο rn m a. n d e r
fanuut the Pens so that
Figure 13.11
self 1
mm
a Pen self fa. η Out
100 000 ο ν stem Browser! Collect ion s-bupp<| Commander Gra. ρ hics-Prirniti vi Cursor 3 rap hi e*~ Display D i s ρ I a. y fvl e d i υ rn m ο ν i η g Graphics-Paths geometric designs Display O b j e c t Gra. ρ hie s-Views Display Sere* Ci raphics-Editors Displa y T e t Commander •jraphics- Clocks irtsteunim fanOut Penl the Pens so t h a t distribu width height s o u n ; e '••
Figure 13.12a
Dio
source ν clip.:-: clip Υ clip Width clipHeight fra me location
drectwo ρ en Dow η
Τ
290 Creating a New Class Description
Figure 13.12b
ο 11 e c ΐ ι ο η s - b υ ρ ρ distributing ra phic 3-Primiti'v C u r s o r D i 5 ρ I a. y Μ e d i υ m geometric design: i r a phi C5-Pa th3 Dii pi ay Object ir* phie 3~View5 Displa ν S ere en irz phie 5 — Ε d i t o r sDisplay Text a gaιη iraphie-.-ClueΚ3 £liIga undo
™"
turn: degrees "Tell each of the Pens t o turn degrees." self do: [ :eaeh j each turn: degree s i
copy cut ρa ste do it print it can* el forma, t s ρ a ν·.·1 η e χ ρ I a. i r
Figure 13.13
IDB
penDown
J
291 13.3 Define the Instance Protocol
e c 11 ο η s - b ι ρ h i c s - Pri m i t i ν j C υ r s ο r Displa yfvlediur Display O b j e c t Displa y b c r e e r ρ h ι c 5 - Ε1311 ο r j J D ι ;• ρ I a y Τ 9 χ t
distributing aeometric desiqr
ρ hie J - ' J I O C
qo "Toll each of t h y Pens t o qo d i s t a n c e . ' self do: [ :each | e a c h go: d i s t a n c e ^
Figure 13.14
Diu
ρ « η D ο w ri
ollect io n s - b raphic s-Primit
spiral: numberOfLines angle: degrees "Have e a c h Pen d r a w a double spiral." 1 t o : numberOfLines do: [ :i | self go: i, self t u r n : d e g r e e s !
cop do it print it
format spawn explain
Figure 13.15
οίο
ρeηDοw η
292 Creating a New Class Description
Now let's test these new messages. Create a workspace or use any text view to evaluate the test expressions. For example, in the inspector for the Commander, set the brush of each of its Pens to be a 1 χ 1 square, send each Pen home, and then direct the Commander to go: 50 and create the spiral geometric design. The expressions and the result are shown in Figure 13.16.
Commander self
self do: [ :each | ga. ch default Nib: 1, 9 a C h h Ο ΓΠ 9 ] .
self go: 50, self spiral: 60 angle: 89,
Figure 13.16
000 In a workspace, create a new Commander for six Pens, each with a l x l square brush. Direct the Pens to fan out, go a distance of 50 pixels, and then make a spiral design, as shown in Figure 13.17. You have now created and (incrementally) tested a new class description. To save your work, choose the yellow button command file out in the class-names or class-category subviews. This creates a file in which the class description is written in a format that can be read by another Smalltalk-80 system. The file name is the class name or class category name followed by a period and the characters st (meaning "Smalltalk" file). The class description is still part of your system. But if you start with a new system (or someone else wants to use your work), then note that the System Workspace includes a template for the expression for reading the file ((FileStream fileNamed: 'fileName')fileln). Suppose you choose file out in the class-names subview, with Commander selected. Then the file created is named Commander.st. To
Γ 293 13.3 Define the Instance Protocol
A 1 ΙΙϋ
ΙΙΙΙΙΙ
£... i3g;S|j V-/orkspacQ ^ ^ ^ ^ l ^ ^ ^ J | corn | corn *- 'Jo mm a rider riQvv: 6. u
• c ιj rn d ο ι
[ :each | each defaultNib: 1, 9 a c h h ι J rn 9 ] .
corn fanuut. C ιj ΓΓι q ij \ S U.
c ι j rn s ρ i r a 1: 6 0 a π q 1 e: S 9
Figure 13.17
000 read the file and thereby bring the definition of Commander into a new system, evaluate the following expression in that system (FileStream FileNamed: ' Commander.st') file In More information about saving your work and about external files is given in Part Five. As additional exercises, you might add the messages defaultNib: and home to class Commander. In each case, the Commander would distribute the message to its Pens. An interesting exercise to try is to modify the system browser so that you can retain reference to a full query — class category, class, protocol, and selector. The idea is to add a list menu subview to the browser that is initially empty. Add a browser yellow button command save query. When you choose this command, the current menu selections of the browser are saved as a menu item of the new list menu. If you choose such a menu item, the browser selections are all changed appropriately.
|Γ-1[<»4Ε*«»4
f-Jcc»**«»J
r«j[»a«>4 t>Jt<3HCi«»J
r-j[c>a«J
^
K« »"fcft h ft - jl 4 * ft - ll 4 » jf-SI 4 f iV—.ίΐ 41 ft - jl < > U*4E
Improving Performance
296 Improving Performance
We have seen that you can determine whether your methods work correctly by inspecting the state of the objects involved in the interactions. Another question you might ask is what percentage of the total time in evaluating the expression is spent carrying out various messages? You can answer this question by using the Smalltalk-80 spy. The purpose of the spy is to carry out an analysis of a block of code. The analysis consists of the (nested) sequence of message-sends and the total percentage of time taken up evaluating the original message. The spy creates a workspace labeled Spy Results in which this hierarchy is printed. The best way to understand the spy is to follow an example of its use. Suppose you are interested in analyzing the evaluation of the expression Smalltalk keys asSortedCollection
This expression takes all the entries in the System Dictionary, Smalltalk, and sorts their keys in alphabetical order. To spy on the execution of this sort request, evaluate the expression MessageTally spyOn: [Smalltalk keys asSortedCollection]
In other words, the spy is run by sending the message spyOn: to the class MessageTally. The analysis is carried out on the argument. When the analysis is completed, you are asked to designate a workspace in which three levels of information are printed. First, it indicates the number of tallies, that is, the number of times the execution of the expression was interrupted to determine which message currently is being sent. Then it provides a description of the tree, and itemizes the "leaves" of the tree (the messages at the lowest level of nesting). In sorting the keys of the SystemDictionary, Smalltalk, the tallies are 54 tallies
Note that if you try this example, you might get slightly different results because of differences in the statistical sampling (in the number of interrupts). The second level of information is the description of the tree itself. You can follow the sequence of message calls: 53.7% of the time was spent evaluating SortedCollection class new:; 22.2% in Collection asSortedCollection; and 24.1% in Dictionary keys. (By SortedCollection class new:, is meant send the message new: to the class SortedCollection.) Of the 53.7% in SortedCollection class new:, most of the time was spent in String < = , which in turn spent most of its time in primitives. The message asSortedCollection is primarily a call on add All:, which calls reSort, which calls sortto: recursively.
297 Improving Performance
Corresponding to each leaf of the tree is a number representing the relative amount of time spent executing the method. Thus, in sorting the keys of the System Dictionary, Smalltalk, 37.0% of the time was spent executing the message compare: for a String, 7.4% was spent in the method for SortedCollection sortto:, and so on. The purpose of the third level of information, **Leaves**, is to gather in one place many occurrences of some message that, if listed separately, appears insignificant. **Tree** 53.7 SortedCollection class new: 51.9 String < = 50.0 String compare: 37.0 primitives 11.1 Character asUppercase 24.1 Dictionary keys 24.1 Set add: 14.8 Set findElementOrNil: | 13.0 primitives 7.4 Set atNewlndex:put 7.4 Set fullCheck 5.6 Set grow 5.6 Set noCheckAdd: 5.6 Set findElementOrNil: 22.2 Collection asSortedCollection 22.2 SortedCollection addAII: 18.5 SortedCollection reSort | 18.5 SortedCollection sort:to: | 18.5 SortedCollection sort:to: | 16.7 SortedCollection sortto: | 14.8 SortedCollection sortto: | 11.1 SortedCollection sortto: | 5.6 SortedCollection swap:with: | 3.7 SortedCollection sortto: 3.7 Set do: **Leaves** 37.0 String compare: 18.5 Set findElementOrNil: 11.1 Character asUppercase 9.3 SortedCollection swap:with: 7.4 SortedCollection sortto: 3.7 Set do:
When you know where the execution is spending its time, you can try to improve that method to run faster, thus impacting overall execution of the activity.
τ
Examples of Creating or Changing Browsers
15.1 A Protocol Browser 15.2 A Project Browser 15.3 Modify Class Project 15.4 Change the System Menu
300 Examples of Creating or Changing Browser One of the typical kinds of things that programmers do in the Smalltalk-80 system is create special purpose browsers, either as additional software development tools or as applications. Example browsers for applications might be: calendar
browsing personal or group schedules for visitors, talks, trips out of town, meetings
electronic mail
browsing mail sent to you, your responses, and any notes about the mail
book index
browsing the information in a book (An example is given in a doctoral dissertation by Steve Weyer [Searching for Information in a Dynamic Book, Xerox PARC Technical Report SCG-82-1, February, 1982].)
budget
browsing a database of financial plans, income, and expenditures
Example browsers that count as software development tools might be a protocol browser or a project browser. A protocol browser is one that lets you access the complete protocol of a class; by "complete," we mean the messages implemented in the superclasses as well as in the class. A project browser gives you direct access to all existing projects, regardless of how they were created. Implementations for each of these two browsers are given in this chapter as models to follow as you try to figure out how to use the system components for creating views and controllers. Detailed tutorials on the implementation of the user interface and on creating graphical interfaces to applications are provided in the forthcoming book Smalltalk-80: Creating a User Interface and Graphical Applications. In trying these examples, you should be careful not to make mistakes while typing the text. If you find that you are making many mistakes and are confused by the error handling mechanisms of the system, you might put off reading this chapter until after you review Part Four "How to Find and Correct Errors."
15.1 A Protocol Browser
The first example browser is one in which you can examine the message interface of a particular class. This protocol browser should have the following characteristics: • The browser should have two subviews, one containing a list menu and the other editable text.
301 15.1 A Protocol Browser
• The list menu subview is a list of the messages implemented by a class and its superclasses. • The text subview is an area in which to edit the selected method, as you would in a message-set browser. • The message selectors should display in the list menu in alphabetical order. • The name of the class in which each message selector is defined should be indicated in the list menu. • Selecting a message selector should cause its method to display in the text subview. • The method should be editable and recompilable. • The standard queries about the message should be accessible, namely senders, implementors, and messages. We call this browser a Protocol Browser. This section contains stepby-step instructions for creating the browser. From this example, you can obtain a glimpse into some of the components that are available in the Smalltalk-80 system for creating graphical user interfaces, namely StandardSystemViews, CodeViews, SelectionlnListViews, and ActionMenus. In a system browser, create a new class category named InterfaceProtocol (Figures 15.1a and 15.1b). The new category is automatically selected and a template for defining the new class is displayed in the text subview. Edit the template to define Protocol Browser as a subclass of Object (Figure 15.2). It should have four instance variables, as follows: list
An OrderedCollection whose elements are Strings, each of which represents a message selector and the class in which the message is defined. This is the information that will be displayed in the list menu of the browser.
ClaSSDlCtionary
A Dictionary whose keys are message selectors and whose values are the classes in which the message is defined. This is used for looking up methods when an item in the list menu is chosen.
SeleCtedClaSS
Either nil, if no list menu item is selected, or the class defining the selected message selector.
SeleCtedSeleCtOr
Either nil, if no list menu item is selected, or the selected message selector.
302 Examples of Creating or Changing Browsers
jysterri Browser
i Γι 3 t a n c e V a r\ a b I e Ν a rn e 3: ' i η.-. t V a r Ν a rn « 1 in 3 t V 5 r f\J a rn c I a 3 3 V a r i a b I e Ν a rn e 3: ' CI a 3.-. V a r Ν a rn e l poolCMC t i c m a n e s :
> I: I a 3 3 V a r Ν a rn
"
c a 16 q ϋ r y: Ί η t e r f a c e - Β r ο ν·.·13 e r'
Figure 15.1a
010 Sy stem Browser I n t erf a ce-buppur In t erf a i:e-Li.-to Brew 3e r I n t erf a c e - Τ e · t Brow; er'v'iew I n t erra c e - fvl e Γι υ 3 fvl e t hi cd L i s t B r I n t erf a c e~F'rorn j t Enter
I n t erf a I n t «rr.=i c e - D e b L
r hi Μ Γι
Γι Μ VV
C •:
=ι Γ Γ Μ Γι Τ
1 irprr.=i r M-pr-nrr in j t
3
te
"Γ - |-
Ι
Α
j t i n t it
a Γι c e •••/ .=
C 1 ·: :•:•''•/?
r i a b l e
a q a ι Γι υ "η d ο i.opy cυΐ ρa -rρ
'J a
ΓΓΙ
e 3 "01 a 3 3'•'•a
rNa
c a Γι Γ ^
•/a rNa me^.1' 33VarMame2-
ρι.ι
teqory; 'In terract
Figure 15.1b
-Β r o w 3
Ho
j
303 15.1 A Protocol Browser
Inter fa ce-Erov·. Interface-Inspect Interface-Debugc I n t e r f a c e - F i l e Γνϊο Interface-Transc Interface-Project Interface-Chanq O b j a c t s υ b c I a s s: # Pro t ο c ο ΙΒ ro vv ; e r i ri s τ a n c e V a r i a b I e Ν a. rn e s: 'list c I a s s D i c t i οselectedCIa η a. r; ss selec t e d S e l e c t o r ' a. q a. ι η uηdο c la ss'v'a ri.3 bleNa mes: ^ poolC'ic tionaries: " >: a t e q o r v: ' I n t e r f a c e-Protoc o\'
copy cu ΐ
paste
do it p r i n t it caflfcel
Figure 15.2
format spawn
010
The ProtocolBrowser should have no class variables. Remember to cut out the "dummy" class variable names from the method template. After you have typed the class definition, choose the yellow button command accept. The new class is added to the class-names menu and is selected. In the class-names subview, choose the yellow button command comment (Figure 15.3a). The words This class has no comment appear in the text subview. Edit it to provide a comment on the role of the class (Figure 15.3b). Within the comment, you can also provide a template for creating an instance of the class, such as ProtocolBrowser openForClass: className Choose the yellow button command accept to save the comment. The protocol name private has no special meaning to the system. By convention, we use this name to categorize messages that are sent by the object to itself, rather than by other objects to it.
The next step is to define the instance creation message OpenForClass:. Choose the browser menu item class so that you can define class protocol. Note that when you choose class, the system attempts to guess what other selections you might also wish to see. Since you were examining the comment for class ProtocolBrowser, the system guessed you might want to see the comment about ProtocolBrowser's class (i.e., its metaclass). Currently this class has no comment.
Add the protocol name instance creation (Figures 15.4a and 15.4b).
304 Examples of Creating or Changing Browsers
System Browser il.gaciwaaM
Interfac e-Bt Ι η ΐ erf.? r e - | η Interface-D Interf.? c e-Fi Interfac : e r f a ce-T e-T I Ι Γ Ι Τterface-Pri Μ Μ 1 Int". e rf a c e ~C h .=ι ΓΙ η JlS ^I'bject
jubclass:
#Pro
i n ; t a nc e'v'a r i a blef\
ctionar
ζ. ρ ι Μ ,; r a d S e I e c t ο r
c la :• iVanable(\larriQ_": " puulC'ii: ΐ ί ϋ η a rie.": 1 CUP q η r v : ' I n t e r f a c e - Pro t ο c ο I'
Figure 15.3a
010 Inte rf a c e - Β ro vv Inte r f a c e -1 n s ρ e c t Inte rface-Debugc Inte rface-File Mo Inte rf a. c e - Τ ra η s c Inte rface-Projec a g a. ι η Inte r f a c e - C h a n c Thi cl3.ss r e p r e s e n t s a. b r o w s e r in w h i c h y o u c a n examine t h e undo copy rnessa.qe i n t e r f a c e of a p a r t i c u l a r class. cut ρ a. _-. t e do it Ρ r ο toe ο ΙΒ r ο w s e r ο ρ e η F ο r CI a. s s: c I a s s Ν a. rn e irint it
carle el format spawn explain
Figure 15.3b
Bio i
r 305 15.1 A Protocol Browser
Interface-Bro\ Interface-Inspect I n t e rfa c e - D e b υ q c Interface-File Mo I n t e r f a. c e - Τ η. η s c Interface-Project
Interface-Changj This class has no comment
Figure 15.4a
Bio Inter face-Browse lawiMfll.uiivaa, Interface-Inspect Interface-Debugc: Interface-File Mo Interface-Transc In terfa.ee-Project Interface-Changt This class has no comment
aqaιη υηdo Enter new ρ rot copy then a c c e p t or cut instance c r e a t i o n
do it irint it c a η"Λζ
Figure 15.4b
Oio
306 Examples of Creating or Changing Browsers
openForClass: aClass " Create and schedule a browser for the entire protocol of the class." | topView aPBrowser label | aPBrowser «- super new on: aClass. label <- ' Entire protocol of: ' , aClass name. topView <StandardSystemView model: aPBrowser label: label minimumSize: 200 @ 200. topView addSubView: (SelectionlnListView on: aPBrowser aspect: #selector change: #selector: list: #selectorList menu: #selectorListMenu initialSelection: nil) in: ([email protected] extent: [email protected]) borderWidth: 1. topView addSubView: (CodeView on: aPBrowser aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: ([email protected] extent: [email protected]) borderWidth: 1. topView controller open
In this method, the temporary variable aPBrowser is created as an instance of class ProtocolBrowser and is initialized by sending it the message on:. The label of the browser is then defined to be Entire protocol of < class name >
where < class name> denotes the place in which the actual name of the class appears.
15.1
307 A Protocol Browser
Interface-Browst Interface-Inspect I n t erf a c e-Debug: Interface-File Γνϊο I n t erf a ι i-Transc I n t erf a ι 5-Project again I n t e rf.3. c e - <_·' h a n α, ι<•. η s t a. n ι_· « ι undo o p e n F o r c l a ss: copy ''' _: r e a t e a n d s c h e d υ I e a. b r ο w s
Figure 15.5
010
| t o p V i e w a P B r o w s e r label | a Ρ Β r ο w s e r *• s u p e r n e w on: a CI a s s, can* el l a b e l - ' E n t i r e p r o t o c o l of: ", a C l a s s n a m e . torrna t spawn tορView S r a Γι d a r d S ν s t e m V i e w model: a P B r o w s e r label: label mini m υ m S i ζ e: 2 0 0' ϊ 1 2 ί to ρ V i e w a d d S u b V i e w : ι S e I e c t i ο η Ι η L i s t V i e w on: a P B r o w s e r a s p e c t : v? s e I e c t ο r
The rest of the method consists of four main steps. 1. Create an instance of StandardSystemView. 2. Create an instance of Selection I n ListView and make it a subview of the StandardSystemView. 3. Create an instance of CodeView and make it a subview of the StandardSystemView. 4. Send a message to the StandardSystemView to obtain its controller, that is, the class that provides the user interaction scheduling (StandardSystemController), and then send a message to the controller to open a rectangular area for itself on the display screen and to make its view the active view. The user will be asked to designate the rectangular area. Each of StandardSystemView, CodeView, and Selection I n ListView, are subclasses of View. View provides protocol for managing a hierarchical nesting of subviews, and for managing the windowing transformations needed so that the user can move and reframe the view and so that all the subviews will maintain their relative positions and sizes. The subview insertion message used in this example is addSubView:in:borderWidth. The first argument indicates the subview that is to be inserted, the second indicates the relative position and size
Τ
308 Examples of Creating or Changing Browsers
of the subview, and the third the width of the frame around the subview. Once your example protocol browser works, you can play with these numbers to see the affect of any changes.
When the StandardSystemView is created, it is informed of the object to be viewed on the display screen, its label, and its minimum size. A SelectionlnListView is one of the kinds of menus in the system. Its instance creation message requires six arguments. ΟΠ:
The object, one aspect of which is viewed by t h e list menu.
aspGCt:
A Symbol identifying the menu to other parts of the view.
Change:
A Symbol denoting the message selector for changing the
list:
A Symbol denoting the message selector for retrieving the
information that shows in the list menu.
list of strings that show in the list menu. menu:
A Symbol denoting the message selector for obtaining the yellow button menu; nil if there is no menu.
initiaiSelection:
A String representing the initial current selection; nil if no initial selection.
A CodeView represents a view of text that is editable and in which the command accept means to compile. Its instance creation message requires six arguments. On:
The object, one aspect of which is text.
aspect:
A Symbol denoting the message selector for retrieving the text that is displayed.
Change:
A Symbol denoting the message selector for changing the text that is displayed.
menu:
A Symbol denoting the message selector for obtaining the yellow button menu; nil if there is no menu.
initiaiSelection:
A String representing the initial current selection (subpart of the text displayed highlighted); nil if no initial selection.
Once you have defined the instance creation message openForClass:, then choose the browser menu item instance so that you can specify the instance protocol. In the message-category subview, choose the yellow button command add protocol so that you can add the protocol private (Figure 15.6a and 15.6b). Do the same for protocol names list access and text access.
309 15.1 A Protocol Browser
erface-Browse erf a c e-In spec t erface-Debugc erface-File Γνϊο erfa c e - T r a n s c erfa c e-Projec erface-Chanc ρ b j set s u b c I a s s: # Pro t ο,; η | Β η;, •..·•· s e r i η s t a η c e V a r i a b I e Ν a m e ;: 'list c I a s s D i c t ί ο η a r selectedSelector ' c I a ι s V a r i a b I e Ν a m es: " μ ο ο ID i c τ Ι η η a ri e ζ: r a t e q ο ry: " I n t e r f a c e - Pro t ο c ο I'
Figure 15.6b
IsHfaMAMIsfJBBM a qaιη Enter n e w r. υ η d ο t h e n a c c e p t cop ^"..ι b j e υ t subclass: # Ρ r ο ΐ ο c ο ΙΒ r ο w s e r i η s t a ri c e V a ri a b I e Ν a m e s: 'list c I a s s selec f edSelec f o r ' c la 5 s'v1 a ri a bleNa mes: poolC'ic tiona ries: c a t e q ο r ν: ' I n t e r f a c e - Pro t ο c ο I'
Figure 15.6a
310 Examples of Creating or Changing Browsers
Τ
Choose the protocol name private and edit the method template to specify the method for on:. on: aClass " Create the protocol browser for the class, a Class. " | defClass | list <- OrderedCollection new. classDictionary «- Dictionary new. aClass allSelectors asSortedCollection do: [ .selector | defClass — aClass whichClasslncludesSelector: selector. list a d d : s e l e c t o r p r i n t S t r i n g , ' ( ' , d e f C l a s s n a m e , ' ) ' . classDictionary add: (Association key: selector value: defClass)]
Only two of the instance variables are initialized, list and classDictionary. For each selector specified in the class (aClass allSelectors), the class in which the selector is defined is determined (whichClasslncludesSelector:) and then the selector, followed by a tab, left parenthesis, defining class name, and a right parenthesis, is added to list. The selector and the defining class are then stored as an entry in classDictionary. Remember to type carefully to specify a tab before the left parenthesis. The tab will be used in another method for distinguishing the selector from the class name.
Choose the yellow button command accept (Figure 15.7). The protocol name private has no special meaning to the system. By convention, we use this name to categorize messages that are sent by the object to itself, rather than by other objects to it.
You now have to define the messages that access the information for the SelectionlnListView and the CodeView. There are two list-accessing messages, selectorList and selector:; there are two text-accessing messages, text and acceptTextfrom:. The methods are shown in Figures 15.8, 15.9, 15.10, and 15.11. Note that in the implementaiton of selector:, the list menu item is a String that must be parsed to determine the selected selector and class. Instances of String respond to messages such as copyUpTo: that support the parsing. The message changed: is specified in class Object as broadcasting the fact that an object changed so that any dependents, such as a model, its view, or controller, can choose to update itself.
J
311 15.1 A Protocol Browser
System Browser In terrace-Brow.-ς I n t erf a ce-Inspect Interface-Debugc Interface-File Mo Interface-Trans c Interface-Project
text access list access
c r e a t e t h e p r o t o c o l b r o w s e r for t h e class, ;
| defClass | list *• Or d ere d C ο 11 e c t i ο η η e w,
Figure 15.7
cut paste do it print it rormat •spawn explain
c I a s s C' i c t i ο η a r y - D i c t i ο η a r ν η e ••• .••/. a Class a II Selectors a s S o r t e d C o l l e c t i o n do: [ '.selector | defClass - a Class whic hCIa s sine ludesSe lee tor: selector. list add: s e l e c t o r print S t r i n g , ' (\ def Cla ss n ame c l a s s D i c t i o n a r y add: ( A s s o c i a t i o n (•••ey: s e l e c t o r value: defC ass)!
Oio
iystem Brov/ser ire
In terrac Interfac Interfac e-File Mo In t erf a ce-Transc Interfac e-Project In t erf a ce - C h a n q <•. iCtorList " A n s w e r the
Figure 15.8
a. q a ι η undo copy
ist of strings t h a t show in t h e list menu.
312 Examples of Creating or Changing Browsers
I n t e r f 3. c e - Β r ο w s In t erf 3. ce-Inspect Interface-Debuge Interf3.ce-File fvio Interf3.ce-Tr3.ri5c Interface-Project Intyrfa.ce-Cha.nQ
select orList
selector: a.string "Answer t h e message selector for changing t h e in format ion t h a t shows in t h e list menu." aString = = nil ifTrue: [ s e l e c t e d S e l e c t o r *- nil. t s e l f ] . selectedSelector - ( a S t r i n g copyUpTo: C h a r a c t e r t a b ) a.sSymbol. selectedClass - classDictionary a t : selectedSelector. self changed: # t e t
Figure 15.9
000 Inter f a c e - B r o w ; Protoco Browser Interface-Inspect Interface-Debuge Interface-File Γνίο Interface-Transc Interface-Pro ject Iriterfa.ce-Cha.ru":
text access list a c c e s s ρ ri ν a t e
"Answer t h e symbol i d e n t i f y i n g t h e t e x t of t h e menu." s e I e c t e d S e I e c t ο r= = π i I ifTrue: [ t " asText] ifFalse: [ t (_-. e I e c t e d C las s s ο u r c e C ο d e A t: s e I e c t e d S e I e c t ο r) a. s Τ e χ t Am al··.e S e I e c ΐ ο r Β ο | d Ι η: s e I e c t e d CI a s s ]
Figure 15.10
BOO
τ
313 15.1 A Protocol Browser
'-:•'•.:'•.:'•.'•'•,••'•,•';•'•.'•'·/•'•.:':'': •':'•':'•':'•
\'•':'•'·.'•'•.'•:'•'•.'•'•.'-':'•
'•':'••:•'•:•'•.'•·.'·'·.'•·:••'•':'•':'•'•:•'
I •".
• ' •
'.
LJ
Figure 15.11
uuu
Inter fa ce-B ro w s ί I n t e r f a c e -1 n s ρ e c t I n t e rfd. c e - D e b υ q c Interface-File Mo
list access private
text
i::i:j
Interface-Transc Interface-Pro iect IHf=HFin{H c ι a. s :• I n t e rf a c e - Chang* acceptText: aText f r o m : aController ii;:| "Answer the message selector for changing the displayed text." i|i;|; | newSelector | i;;;ij newSelector *;::;;; selectedClass compile: aText B]\ classified: (selectedClass organization i;!jii cateqοrν0fΕ1 e·meηt; solectΡdSΜ|Μ,-. rηrΊ i;;i;; notifying: aController, iiiiij newSelector == nil ifTrue: [tfa. 56], W. newSelector == selectedSelector ifFalse: [self newSelectorList: iijiji π ο ν·,·'κ (=· 1 e'• t o r ] .
ttrue
^
Μ
Although we have not as yet specified the yellow button menus, you can now try out the protocol browser. Evaluate an expression of the form ProtocolBrowser openForClass: < className > In the workspace in Figure 15.12a, we substituted True for < className > to open a ProtocolBrowser on the class True, a subclass of Boolean (Figure 15.12b). If you select a menu item, the method shows in the text subview. Scrolling works. So does the blue button menu for framing, moving, and so on. Much of the programming work has already been done for you!
314 Examples of Creating or Changing Browsers
b ν stem B r o w s e r
Interface H^tse
In t e r r a c e- Β t-o ν. ProtoeolBrowser list ac rf a c -1 n s ρ e Γ τ -Debug ι: privat -File Γνϊο rfac - Τ ran sierra c e-P'ro iec t class Γη e s s a q e select ο r a. η d a r g υ m e η t η a m e s 11 Workspace ent s t a t i n g purpose of message
a c c e p t Te;< tifrom rρχt
|protocolBrowser openForClass: True
Figure 15.12a
010 b y stern B r o w s e r e-Brov·. -Inspect Intc In· rf a c -Debug·: Inti rf a c -File Γνίο i r f a c -Transc :erfac - Proiecd messa ge seIec tοr a nd a r "'on space *nT- i t a t i n q put
= (Object) = = (Object) a. d d D e ρ e η d e ri t: (Ο b j e c t') & alternativeObject " Ε ν a Ι υ a. t i η g c ο η ί υ η c t i ο η - - a n s w e r a Iterna tiveOb iec t since receiver is true t a Iterna t i v e O b j e c t
Ρ r ο toe ο ΙΒ r ο w :·αν ο ρ e η F ο r >'.
Figure 15.12b
000
i
315 15.1 A Protocol Browser
If you try to use the yellow button menu, you will receive an error notification. Leave the ProtocolBrowser on the screen. Let's define two messages, textMenu and selectorListMenu. Each of these creates an instance of class ActionMenu, an object that represents a pop-up menu that can have lines between its items. An ActionMenu is created with the message labels:lines:selectors.\ Here are the three arguments labels:
A String of the menu items, each item separated by a carriage return. The withCrs message to instances of String returns a String that substitutes a carriage return character in place of any \ characters. Thus you can use the \ to indicate the line change.
lines:
An Array of numbers indicating after which item to draw a line.
selectors:
An Array of message selectors that will be invoked if the corresponding menu item is chosen.
The convention is that the object being viewed will be sent the message, although in several notable cases, such as editing text, the controller (paragraph editor) receives the messages.
The yellow button menu for the CodeView is for text editing, as in a browser text subview. Edit the method template to specify the message textMenu (Figure 15.13a). Entire p r o t o c o l of: T r u e
System Bro'vvser I n t e r f a c e-Erc·.· ProtocolBrowser Interfac -Inspect I n t e r f a c -Debugc I n t erf a n -File fvio Interfaii -Transc I n t erf a c -Pro iec t
text access list access pnva te
a.cceptTextifrom: t
Μ
:•: t
"™ma textMenu '' A, ri _r. ••• .••/ e r a n m e η υ f ο r r e q υ e s t i η q e d i t s ο f t h e t e χ t ο f a. rn e t h ο d." τ A c t i ο Γι Μ e Γι υ l a b e l s : ' a q a i η \ υ η d ο \ c ο ρ y \ c υ t \ ρ a s t e \ a c c e ρ t '•·. c a n e e l ' vv i t h C Fi s lines: # ( 2 5 ) s e l e c t o r s : # ( a g a in u n d o c o p y S e l e c t i o n c u t p a s t e
Figure 15.13a
accept
cancel)
Τ
316 Examples of Creating or Changing Browsers
Since the messages are the standard ones used in all views in which paragraphs are edited (TextViews as well as CodeViews), you do not need to do anything further in order to use the yellow button menu. Return to the protocol browser you made earlier, and try using the menu (Figure 15.13b). Entire protocol of: True by;tern Browser! Interfac In t e rf a. c Interfac Interfac Interfa c Interfa c
-1 n s ρec τ -Debugc -File Γνΐο - T r a nsc -Prciiec τ
Object) = = (Object) a d d D e ρ e η d e Γι t: ( 0 b j e c t )
& alternativeObject "Evaluating conjunction - - a. η s ν·.·1 e r a. 11 e rn a t i ν e 0 b i e ο t since receiver is t r u ς
textMenu
alternativeObject
"Answer an rrienu f o r re
ι Ac t ion Men υ labels: 'again'·, υ Γι d ο' lines: # (2 5 ) selectors: # i again
Figure 15.13b
ρ ν:
η cut p
? ρ t c a n c e 11
010 The yellow button menu for the SelectionlnListView is for asking questions about the messages, similar to the queries available in the list menu of a message-set browser. It is defined in response to the message selectorListMenu (Figure 15.14). If the response to selectorListMenu is nil, then the subview will flash to indicate that no menu is appropriate. The three messages, browseSenders, browselmplementors, and browseMessages, will be sent to the ProtocolBrowser. Figures 15.15, 15.16, and 15.17 show their definitions, categorized under list functions.
J
317 15.1 A Protocol Browser
Entire protocol of: True
"it erf a c > Interface Interfax Interface I n t erf a o I nterfa c ι BHHUH selectorListMenu " Α η ivv e r 3 m e η υ f o r m 3l·ί η g queries .about rn e s s a g e s and rn e t h 0 d; selec tedSelec t o r = = nil if True: [ T n i l ] ifFalse: [ t A c t i 13 Γι Μ e ΓΙ υ l a b e l ; : 'sender ί '·•. i m ρ I e rn e η 10 r ί \ rn e ; 3 a g e s' w i t hi C Fi; lines: # ( ) selectors: # (b r 0 vv s e 5 e η d e r 3 b r ο '..·ν 3 e I rn ρ I e m e η 10 r 3 brovvseMessages;^ .
Figure 15.14
roo
t e rf a c e - Β ro vv Interfac e-Inspec Interface-Debug Interface-File Γ Interfac e-Transc Interfa c e-Projec Interfac e-Ghana browseSenders "C:reate
a message-set
browser f o rt h e methods t h a t
s e l e c t e d rn e ; s a g e " S rn a 111 a 11 b r ο ν·/ s e A11C a 113 Ο η: s e I e c t e d S e I e c 10 r
Figure 15.15
000
include t h i
318 Examples of Creating or Changing Browsers
Entire protocol of: True System Browser
Interface-υ ha rig browselrnplernentors "Create a message-set browser for the im pie me η tors of the selected message." Smalltalk brer
Figure 15.16
Ί ρ I e m e η t ο rz Ο f:
seIec tedbeIectοr
000 Entire protocol of: True
bn: w s elmpleme n t UAcUsreli eSenders
1 I'Ji bn:
Interfa.c Interfa.ce-Tra.nsc Interfa.ce-Projec Interface-Ghana b r ο w s e Γνΐ e s s a g e s "Create a menu of the messages in the selected method and t h e n , if t h e user selects a menu item, c r e a t e a messaqe-set browser for the methods t h a t implement it." S m a 111 a I \ s h ο w Μ e η υ Τ h e η Β ro w s e: ι' s e I e c t e d CI a. s s c ο rn pile d (vl e t h ο d A t; s e I e c t e d S e I e c t ο r) messages a. s S ο r t e d C ο 11 e c t i ο r^
Figure 15.17
319 15.1 A Protocol Browser
Now return to the protocol browser you created (or open a new one), and try out the menus for the top view (Figure 15.18). Close the browser when you are done experimenting.
System B r o w s e r I n t e rfac e - Β r ο w s e Interfa ce-Inspect Interfa ce-Debugc Interfa ce-File Mo I n t e r f a.c e - Τ r a. n s c Inter fa c e - P r o j e c t browseSenders " C r e a t e a. mes s a q e - s e t br ."elected messa.qe." Ό ΓΙΊ a 111 a
Figure 15.18
(Object) = = (Object) a. d d D e ρ e η d e η t: (Ο b j e c t ) |j m ρ I e m e^i t ο r s
& alternativeObject
| messages
"Evaluating conjunction - - answer a. 11 e rη a. t i ν e Ο b i e c t sin c e re c e i ν e r i s true t alternativeubiect
bro·
010 Notice that the yellow button menus for the Protocol Browser seem to work differently than the ones you have been using in the system in that they do not remember the last item you chose. This is because the menu is recreated each time you press the yellow button, rather than remembered as a class variable. The use of class variables to store the menu is described in the next section.
An interesting modification of this example is to be able to specify that protocol from one or more superclasses should not be included in the protocol browser. In particular, a user will probably not want to see the protocol of class Object included. Suppose we wish to create a protocol browser for only some of the protocol of a class. Protocol Browser openForClass: aClass without: aCollection The second argument would be an Array of classes whose protocol should be excluded. Add the message openForClass:without: to the class protocol of class ProtocolBrowser (Figure 15.19). The only difference between this method and that of openForClass: is the ProtocolBrowser creation message (on:without:) which must be implemented, and the label, which says Some of the protocol... rather than Entire protocol.... When
320 Examples of Creating or Changing Browsers
you add this new method and choose the yellow button command accept, another menu will probably appear stating that the message on:without: is new. Choose the command proceed as is, since your intention is to specify the missing message next (Figure 15.20).
1
Interface-Bro ·; I n t e r f a. c e -1 n s ρ e c t Ι η t er f a c e - D e b υ g c Interface-File Mo I n t e r f a c e - Τ ransc Interface-Project
Figure 15.19
ο ρ e η F ο r CI a. s S : a. <J I a. s s w i t h ο υ t: a U ο II e c t i ο η " C r e a t e arid schedule a b r o w s e r for p a r t of t h e p r o t o c o l of a again undo copy cut | top View a.PBrowser label | ρaste a.PBrowser *- super new on: a.Class w i t h o u t : aCollection. do it label - 'Some of t h e protocol of: \ a Class name. irint it top View «31 a. n d a. r d S y s t e m V i e w f ο rrn a. t model: aPBrowser label: label minimum Size: 2 0 0 © 2 ΰ ϋ . spawn t ο ρ V i e w a d d 3 υ b V i e w: e χ ρ lain (SelectionlriListView on: aPBrowser a s p e c t : # select or
010
τ
Interface-Brows ProtocolBrowser instance creatior ooenForClas: Interface-Inspect Interfa ce-Debugc Inter face-File ίνίο Interface-Transc Interface-Project Interfa ce-Chanqs ο ρ e η F ο r CI a s s: a UI a. s s w i t h ο υ t: a C ο 11 e c t i ο η " C r e a t e arid schedule a. b r o w s e r for p a r t of the p r o t o c o l of Pi
| top View aPBrowser label a Ρ Β r ο w ar - super η e w on: aClass without: aCollection label - 'Some of on:without: is a. new message top View -
Figure 15.20
100
b t a η ιj a. r d b y s t e m V i e w correct ι rrι υ m b ι ζ e: k' U U '£.' k' U U. model: aPBrowser I, abort t ο ρ V i e w a. d d 3 υ b V i e w: b e I e c t i ο η 1 η Li s t V i e w ο Γι: a PB ro w s e r a s ρ e c t: # s e I e c t ο r
321 15.1 A P r o t o c o l B r o w s e r You can create the new method openForClass.without: by copying the method for openForClass: and editing it, changing the first few lines. Similarly, you can create the new method on:without: by copying and editing the method for on:.
Now choose the browser menu item instance and the message category private, and then specify the method for on:without: (Figure 15.21). It differs from the method for on: only in checking the argument aCollection; if the defining class is in the collection, then the message is not added to the instance variable list. System Browser Interface-Browse lammiimiaimBaai-ii Interface-Inspect Interface-Debugc Interface-File Mo Interface-Transc I n t erf a ce-Project In t erf ace-Chang System-Support on: aClass without: aCollection
Figure 15.21
000
text access list access list functions
"Create the protocol browser for the class, a Class, but exclude the ρ r ο ΐ ο r ο I for a η ν c I a s s in the c ο 11 e c t i ο η, a C ο 11 e c t i ο η." I defClass | list - Order edCollect ion new, r I a s s D i c t i ο η a r y - D ί c t ί ο η a. r y η e w. a11:1 ass a II Selectors asSortedCollection do: fc [ selector | d e f CI a s s - i'jidsi· which υ I a s s Ι η c I u d e s s e I e c t ο r: selector. (aCollection includes: def Class) if False: [list add: selector print String, '(•', uafOli.S:· name, ' ) ' . classDictionary add: (Association Key: selector value; d e f C l a s s i ] ^
Figure 15.22 shows an example for class True when class Object is omitted. It was obtained by evaluating the expression Protocol Browser openForClass: True without: (Array with: Object) Only messages implemented in Boolean and True are accessible from this protocol browser. Another kind of protocol browser that you might try is to be able to switch between the messages to an instance of the class and the messages to the class itself, as is done in the system class browser. You can examine the implementation of class Browser for examples of how to create such a protocol browser. The implementation of file list provides another good example of how to create a simple browser. Examine the code for classes FileListView and FileListController.
322 Examples of Creating or Changing Browsers •stem EireI n t e rf a. c: e - Β ro w I n t erf a ce-Inspect Interfac e-Debuqc Interface-File Γνίο Interra c e-Tra nsc Interface-Project I n t e rf a c e - C h a. n q ί „. System-Support
on: aClass without Vorkspa ce
ate the pr
:ocol for a. ( Ρ r o t o c o IB r o w s e r ο ρ e n w i t h o u t : ι' Arra v1 w i t h :
1
True Ί
deepCopy ί Boolean) e q ν: (Β ο ο I e a n')
and: alternativeBlock " Ν ο η e ν a I u a. t i η q c o n j u n c t i o n - - a n s w e r t h e value of a l t e r n a t i v e B l o c k since the rec eiver is true." t a l t e r η a t i v e B l o c k value
si ifFalse: ri η q, ' (', d e f CI a s s η a. m e,
Figure 15.22
000
i c t o r value: d e f C l a s s ) ] ]
15.2 A Project Browser
The next example is a browser for creating and accessing projects. It could be used in place of the hierarchical access to projects available in the standard Smalltalk-80 system. We call this a Project Browser. It should have the following characteristics: • The browser should have two subviews, one containing a list menu and the other editable text. • The list menu should contain the titles of projects. • The text should be a description of the project; the user should be able to edit the text and to cancel any changes. • Selecting a project title should display the description in the text subview. • The yellow button menu in the list menu should support adding new projects, removing existing projects, and entering a project. Adding a new project should prompt the user to specify a project title. Removing a project should require a confirmation if the project has open views or unsaved changes.
323 15.2 A Project Browser
• Whenever a new project browser is created, it should provide access to every project in the system, regardless of the project in which each was created. A project browser can be created in a manner very similar to the protocol browser of the previous section. The list menu subview will be an instance of Selection I n ListView and the text subview will be a CodeView. However, the command accept in the CodeView will not mean compile; it will mean store the text as the description of the selected project. As in the Protocol Browser, commands do it and print it will not be supported in the example project browser. In a system browser, select the existing class category named Interface-Projects and then edit the template in the text subview to define ProjectBrowser as a subclass of Object (Figure 15.23). It should have two instance variables as follows. projects
A Set of all the instances of class Project that exist in the system.
currentProject
Either nil, if no list menu item is selected, or the currently selected Project.
The class ProjectBrowser has no class variables.
lnterfa.ee -Brow; I n t e rf a c e -1 η ι ρ e c tj Pro j e c t Interface-Debugd ProjectController Ι η t e rf a ι: e - Fi I e Mel Pro j e c t V i e v·/ Interface-Transc" ΙΙΜΜΜΙΚΗΜΗΙΒ»
Interface-Changs Ο b j e e t s υ b c I a s 3: # Pro j e c t Β ro w 5 e r i η 31 a. η e e V a r i a. b I e Ν a. rn e 3: 'projects c υ r r e η t Ρ r 1 c I a 3 3 V a r i a b I e Ν a rn e 3: p o o l D i c t i o n a r i e s : "' c a t e q 0 ry: 'Interface- Pro j e c 13'
Figure 15.23
ΟΪ0
324 Examples of Creating or Changing Browsers
After you have typed the class definition, choose the yellow button command accept. The new class is added to the class-names menu and is selected. In the class-names subview, choose the yellow button command comment and provide a comment on the role of the class (Figure 15.24). You can also provide an expression for creating an instance of the class. ProjectBrowser open. Choose the yellow button command accept to store the comment. The next step is to define the instance creation message open. Choose the browser menu item class so that you can define class protocol. Add the protocol name instance creation and then edit the method template to define the message open.
Interface-Brovv I n t e rf a. c e -1 n s ρ e c d Pro j e c t I n t e rf a c 9 - D 9 b υ q jiamia—«myjaai I n 19 rf a. c e - Fi I e Μ ο Pro j e c t C ο η ΐ ro Her l,n t erf a. c e - Τ ra η s c Pro i e c t V i e w Interfa.ce-Cha.nqi
a q a. ι η Τ h i s class r e p r e s e n t s a. b r ο w s e r f o r c r e a. t i rundo ccessinq p r o j e c t s , copy 1 ' j r 9 a 19 ο Γι 9 b y 9 • ' /aIua tiηq cυt Paste do i t Project Browser open print it c a nSe I p 9 χ ρ I a. i η
Figure 15.24
ioiD
325 15.2 A Project Browser
open " Create and schedule a browser for all the projects in the system " | topView aBrowser aBrowser «- super new initialize. topView <StandardSystemView model: aBrowser label: ' Project Browser' minimumSize: 200 @ 200. topView addSubView: (SelectionlnListView on: aBrowser printltems: true oneltem: false aspect: #currentProject change: #currentProject: list: #projectList menu: #projectMenu initialSelection: nil) in: ([email protected] extent: [email protected]) borderWidth: 1. topView addSubView: (CodeView on: aBrowser aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: ([email protected] extent: [email protected]) borderWidth: 1. topView controller open
This method is the same as the one used in creating a Protocol Browser, with the exception of the proportions used for the subviews, and the message sent to SelectionlnListView to create an instance. The message used here contains two additional arguments associated with the keywords printltems: and oneltem:. printltems:
A Boolean, either true or false. The argument of the keyword list: is a message to the browser. It returns an OrderedCollection, either of strings that can be printed in the list menu, or of objects that must be sent the message
326 Examples of Creating or Changing Browsers printString in order to obtain the entry in the list menu. If the argument to printltems: is false, the response will be strings; if the argument is true, then the message printString should be sent. We plan to keep a list of Projects rather than string representations of Projects, so the argument must be true.
oneltem:
If it is known that a list menu contains only one item, then it will be automatically selected if the argument to this keyword is true. There may be more than one Project, so the argument is false.
Once you have defined the instance creation message open, then choose the browser menu item instance so that you can specify the instance protocol. In the message-category subview, add the protocol names initialize-release, list access, list functions, and text access (Figure 15.25).
System Browser ini tializH-relea.se list a c c e s s list functions t e x t access
ect subclass: # P r o j e c t B r o w s e r iristanc e'v'ana.tilef'Ja.mes: 'projects c u r r e n t P r o j e c t ' c I a s s V a ri a. b I e Ν a. rn e s: " ρ oo I CM C tionaries: " c a t e q ο ry; Ί η t e rf a. c e - Pro j e c t s'
Figure 15.25
The message initialize is sent from the instance creation message open to initialize the instance variables. Only the instance variable projects is initialized; it is assigned an OrderedCollection of all the instances of class Project currently in the system (Figure 15.26). Under the category list access, define the method for projectList (Figure 15.27). This is the message sent to obtain the list of items for the list menu.
r
327 15.2 A Project Browser
terrace-Brows I n t e rf a c e -1 n s ρ e c tj Pro i e c t
initia ιζθ-re ease list access I n t e r f a c e - Fi I e Μ ο Pro j e c t C ο η t ro Her list functions Ι η t e r f a. c e - Τ r a. η s cl Ρ r ο ie c t V i e t e x t access
J
initialize
Interfa.ce-Chci.rig
p r o j e c t s - P r o j e c t aIllnstances
Figure 15.26
ooo System Browser I n t e rf a c e - Β ro w s ί Interra c e-lnspec t Project initialise-release Interface-Debuqc ProjectBrowser list access Interface-File Mo Pro iect Controller ist functions I n t e r f a c e - T r a n s c Pro iect View I n t erf a ce-uha.nqi
" A n s w e r t h e c o l l e c t i o n of items t o be displayed in t h e menu
Figure 15.27
ΕΠΟ
328 Examples of Creating or Changing Browsers
Also define methods for currentProject (Figure 15.28) and currentProject: (Figure 15.29); these are the messages used to set and change the reference to the currently selected project.
>ystern Browser I n t erf ace-Browsd—_ feI int erf a ce-Inspect! Project initialize-re I e a s e I n t erf a ce-Debuq ProjectBrowser list a.ccQS: Interra :e-File Mo ProiectCoritrollet i5t function; Interfa
11
project List
An:wer the currently selected project."
τ c urrentPro iec t
Figure 15.28
000 In t erf ace-Β rows ( Ι η t e r f a c e -1 n s ρ e c tj Pro j e c t initialize-release I currentProject Interface-Debug J| ProjectBro1 Interface-File Mo| Project Cent roller list function; project List Interface-Transc Project View text access
t'Q η t Pro j e c t: a Pro j e c t "Set the currently selected project to be a Project." currentProject *- a Project, self changed: # t e x t
Figure 15.29
000
329 15.2 A Project Browser
The second statement of the method for currentProject: is self changed: #text. The purpose of this message is to broadcast the fact that the list menu selection has changed and that, therefore, any objects dependent on the selection may wish to change. Subviews are dependent on one another and are notified when one another announces a change. The subview CodeView must change the text it displays whenever the menu selection changes. According to the arguments of the creation message for the CodeView, you must define methods for text (Figure 15.30) and acceptTextifrom: (Figure 15.31). The response from text is the current project's description, converted from a String to an instance of Text. The purpose of acceptTextifrom: is to store the String representation of the text that appears in the CodeView in order to update the description of the current project. These methods are defined under the category text
access. Although we have not as yet specified the yellow button menus, you can now try out the project browser. First use the System Menu command project to create two projects other than the one in which you are working (Figure 15.32). In each of them, type some text and choose the
I n t e r f a c e ! - B r o w se Interfa. c e -1nsρ e c t Project initia.li2e-relea.se I n t e rf a. c e - D e b u glaMHWriflmicM c list access I n t e r f a c e - F i l e Mo Project Controller ist functions Interfa.ce-Tra.nsc Project View Interfa.ce-Cha.nqi
"Answer the text to be displayed in the code view." c υ rre η t Pro i e c t is Ν i I ifTrue: [ t " asTe t] if False: [ t current Project contents as Text"!
Figure 15.30
ODD
330 Examples of Creating or Changing Browsers
BITOHMC1MIIMIIII
text
accept Text: aText from: whoCares "Store the text to be displayed in the code view," current Project content:.: a Text i t ring, •t true.
Figure 15.31
000 System Browser In t erf ace-Em v\ initialize-release Interface-Inspect Project Interface-Debugc Interface-File Γνϊο Project Controller list functions Interface-Transc Project Vie Vv1 Interface-Chang'
class a c c e ρ t Τ e χ t: a T e χ ΐ f r ο m: w h ο C a res "Store the text to be displayed in the code view," current Project contents: aText string, τ true
b c r e e η with sample browsers
Figure 15.32
i
331
15.2 A Project Browser yellow button command accept. This stores a description for each project so that you will be able to distinguish them in the browser. Evaluate the expression (Figure 15.33) ProjectBrowser open (Recall that this expression was included in the comment for the class ProjectBrowser.)
Interface-Browse Interface-Inspect Interface-Debugc Interface-File Mo Interface-Transc
Project
initialize-release
lawHm.imvMjj
Project Controller list function." r Ρ γ r a r. r ρ •-. •=; Project View
Interface-ijhanqi ••««,Ι.ΤΤ-J n. This class represent." a b r o w s e r f o r c r e a t i n
ccessing projects.
C r « a t e one b y e ν a I u a t i η q
ProjectBrowser open
Figure 15.33
010
J You are asked to designate a rectangular area in which the browser appears (Figure 15.34). In this new browser, you can select projects and the descriptions will be displayed. Since the project browser is constructed using a StandardSystemView, the blue button menu is immediately available. Notice, however, that each item in the projects menu simply refers to the words a Project, rather than to some unique label or title. Instances of class Project have no titles. To improve the projects menu, you will have to modify class Project to declare an instance variable for the title and to access the title. We will make this change to class Project in Section 15.3. We must now specify the yellow button menus. In this example, we will declare two class variables in which to maintain a reference to each menu so that they do not have to be recreated each time the yellow button is pressed (as was done in the protocol browser example), and so that the last selection is remembered.
332 Examples of Creating or Changing Browsers
System Browser Ι η t s rfa c e - Βrο w s e Interface-Inspect Projec Interface-Debugc In t erf ace-File Γνϊο Proi Interface-Transc Proi
a Project Project Project
I n t erf a re-Changs
be re en with pictures
This class represents a. brov·. C r e a t e ο η e b y eν a I u a t i η g Ρrο i e c t Β rο w s e r ο ρ e η
Figure 15.34
000 Project Browser Interface-Browse In terfa.ee-Inspect Project initialize-release Interface-Debugc list a. c c e s s Interface-File fvlo Project Controller list functions r ft y: Τ Λ Γ: Γ: •-, •-, Interface-Tronic Project View Μ
Interface-Chanqi Object subclass: # Project Browse r aga ιη ί η s t a n c e V a π a b I e Ν a m e s: ' ρ ro j e c t s c u rre η t Pro j e c tυ 'ΓΙ 6 ο c I a. s s V a r i a b I e Ν a. ΓΙΊ e s: ' Τ e • t fvi e η u Project Μ e η υ' copy cut poolDictionaries: " paste c a t e q o r y : ' I n t e r f a c e-Projec t s ' do it print it IS*
Figure 15.35
Bio
format spawn explain
333 15.2 A Project Browser
In the class-names subview of the system browser, choose the yellow button command definition. Edit the definition of the ProjectBrowser to add class variables TextMenu and ProjectMenu. Choose the yellow button command accept (Figure 15.35). The class ProjectBrowser is recompiled. (Note that this change can be made even though a ProjectBrowser may be open.) Under the instance protocol name text access, specify the method for textMenu (Figure 15.36). Project BrowserSystem Browser Interface-Brow si Interfax e-In spec t Pro i e c t ι η 111 ο 11; Η - f Ρ ι Η-3 Interface-Debugc i a i Interface-File fvio Projecfjontroller list f u n c t i o n s Interface-Transc Pro iect View
:-e a c c e p t T e • t:from
Inter fa ce-'-Jha.nqi
A n s w e r a menu t o r editing t h e re . r m thy code
Figure 15.36
000
c u r r e n t P r o j e c t is Nil if True: [ t n i l ] , Τ e: • t fvl e ΓΙ υ i s Ν i I i f Τ r υ e: [ T e x t Μ e η u - A, c t i ο η Γνΐ e η υ labels: ' a. g a i η \ υ η d ο \ c ο ρ y \ c υ t '•·, ρ a s t e \ a c c e ρ t \ c a n c e Γ w i t h C Fi ι lines: # ( 2 5 ) selectors: # (a g a ί η υ η d ο c ο ρ y S e I e c t i ο η c υ ΐ p a s t e a c c e ρ t c a n c e I) ] . t T«>: tlvienu
The menu is an instance of ActionMenu that is only created if the class variable TextMenu is nil; otherwise the menu is accessible as the class variable TextMenu. If there is no selection, then no text editor for a project description is needed. The method returns the value nil to indicate this. According to the implementation of ActionMenu, you try to obtain the menu when no project is selected, the subview will flash. If you now return to the project browser, you will notice that you can press the yellow button and obtain the menu. Modify one of the project descriptions to try the editor (Figure 15.37). (Notice that the commands do it and print it were not included in the menu.) Under the instance protocol name list access, specify the method for projectMenu (Figure 15.38).
1
334 Examples of Creating or Changing Browsers
System Browser I n t e rfa c e - Β rο w s e a Project I n t erf.a ce-Inspect Project a. Project In t e r r a c e - D e bug ι: Interface-File Γνϊο Project uon Interface-Transc Project Vie ν Interface-Cha, ngi t e χ t Γνΐ e η υ "Answer a. menu for
Figure 15.37
010
A J ere en with pictures a. q a. ι η υηdo copy cut paste
current Pro ject is Nil Text Menu isNil ifTn. canc\il [Textfvienu «- Acti I a b e I s: ' a. g a i η \ u r lines: #('2 5) selectors: # ( a. g a. i Γι ιJ η d ο c ο ρ y S e I e c t i ιJ η c υ t ρ a. s t e a. c c e ρ t c a n c el')], t Text Menu
Projec t Browserl System Browser Interface-Brows initia.lize-relea.se I currentProiect I n t e r f a c e -1 n s ρ e c tj Pro j e c t Interface-Debug Pro iPCTnrnwspr Μ 11 ~. τ across Ι η t e rf a c e - Fi I e Μ ol Pro i e c t"C ο η t ro Her projectList list functions Ι η t e r f a c e - Τ r 3. η s c I P r ο j e c t V i e teχ t a ccess Interface-Cha pro j e c t Μ en υ "Answer a menu for accessing or changing projects." current Project isNil ifTrue: [ t n i l ] , Pro j e c t Menu is Nil ifTrue: [Projectfvlenu *- ActionMenu labels: 'enter'··, add pro ject'1·. re move project" withCRs lines: # ( ) s e I e c t ο r s: # (e η t e r F'r ο j e c t a d d Pr ο i e c t re m ο ν e Pr ο j e c ΐ ) ] . tProiectMenu
Figure 15.38
ΟθΟ
J
335 15.2 A Project Browser
The menu has three commands. enter add project
Enter the selected project.
remove project
Remove the selected project, unless it is the one in which the user is currently running.
Add a new project to the menu. Prompt the user for a project title. Initially the new project has no description.
The messages associated with each item must be specified in the instance protocol of class ProjectBrowser. Figures 15.39, 15.40, and 15.41, show the methods for enterProject, addProject, and removeProject; they are each categorized under the protocol for list functions,
Project Browser Interface-Brow Ι η t e rf a. c e -1 n s ρ e c tl Proj e c t I n t e rfa c e - D e b u q \t-lJMJAi.\J.V}LU. I n t e rfa c e - Fi I e Μ οι Proj e c t C ο η t ro Her Inter face-Tr a η s c Ι Ρ r ο j e c t V i e w te χt a ccess ΙϋΜϋΗΙΜΜΒίηίΜΙ
Interface- C h a n q ί enterProject "Make the selected project the current one," currentProiect notNil ifTrue: rcurrentPrnject enter!
Figure 15.39
000 The method for removeProject has several interesting aspects. First, if no project is selected, the command means nothing. Second, if the project selected is the project in which you are currently running, deleting that project is very dangerous. The message error: will cause an error notification (notifier view) to appear, warning you that you are trying to do something that should not be done. If you try to remove the project in which you are running and get the notifier, simply choose the blue button command close to erase the notifier from the screen.
336 Examples of Creating or Changing Browsers
Project Browser!:;
addProject "Add another project to the menu of projects," | aProject | a P r ο j e c t *• Project η e w. project." add: aProject. currentProject *• aProject. self changed: # current Project
Figure 15.40
^ ^
000 Project Browser! Interface-Browse initialize-release I addProject Interface-Inspect Project list access I enterProject Interface-Debugc Interface-File Mo Project Controller Interface-Transc Project View text access
rernoveProject "Remove the currently selected project from the menu."
Figure 15.41
000
currentProject is Nil if True: [ t s e l f ] , currentProject == Project current if True: [•tself error: 'You can not remove the project in which you &.rti currently running.'], c υ rrii η t Pro j e c t re I e a s e. projects remove: currentProject if Absent: [ ] . ^ currentProject *- nil. self changed: # current Project^
,., Jiiilll
^ H |
337 15.2 A Project Browser
The third statement is currentProject release. The message release is sent to a Project so that it can remove from the system any views that it knows about. The style of using the viewing and controlling components of the system includes sending the message release to a view whenever it is erased from the screen and should no longer be accessible. You can improve on this method. For example, you might check to see if the project to be removed has any views or unsaved changes and, if so, you can inform the user and ask for confirmation. The system class Confirmer can be used for this purpose.
The last statement of the method broadcasts the fact that the menu changed again. Note that this time the argument is the Symbol #currentProject, whereas in the earlier example the argument was #text; these arguments help the CodeView decide what messages to send to the model to obtain updated information. Try the yellow button commands. Enter a project (Figure 15.42). Create some views in the new project, including a project browser (recall that to create a project browser you evaluate the expression ProjectBrowser open). Use the project browser to return to the original project. Try to remove a project, and to add a new one.
System Browser I n t erf a ι In t erf.a In t erf a add projfpt remove project Interface-Change
Screen w i t h sample browser s
rernoveProject "Remove the currently z>=
Figure 15.42
010
currentProject is Nil ifTru currentProject == Pro iec 1 [τ self error: 'You car •are currently running,'], c υrreη tPro iec t release. projects remove: currentProject if Absent: [ ] , currentProject - nil. self changed: # current Project
338 Examples of Creating or Changing Browsers
Notice that if no item is selected and you try to obtain the yellow button menu in the list menu subview of the project browser, the subview flashes. However, when no item is selected in the subview, it is appropriate to be able to invoke the command to add a new project. The method for projectMenu in class ProjectBrowser can be changed. One such change is shown in Figure 15.43. When the currentProject is nil, the menu is an ActionMenu of one item, add project; when currentProject is not nil, the menu is an ActionMenu of three items. (In fact, the class variable ProjectMenu is no longer used.) Figure 15.44 shows the yellow button menu that appears when no item is selected in the subview. We have fulfilled all but one specification for the ProjectBrowser. We still have to provide a prompter for the title of a new project. To do so, we must first modify class Project.
Project BrowserInterface-Browse Interface-Inspect Interface-Debuge Interface-File Mo Interface-Transc
Project ProjectBrowsQr Ρ reject uon tr oiler Project View
ink iali2e-relea.se list ace I i s t fυ η c t i ο η s t e x t access
current Project currentProject: project List
rface-Changl· Interface-
I
projectMenu " A n s w e r a m e η υ for accessing or changing projects."
Figure 15.43
000
current Pro ject is Nil i f Τ r u e: [ P r o j e c t Μ e η ι j *· A c t i o n M e n u labels: 'add p r o j e c t ' lines: #(') selectors: # ( a d d P r o j e c t ) ] if False: [ P r o j e c t M e n u - A c t i o n Menu labels: ' e η t e r \ a d d ρ r ο j e c t '·•. r e m ο ν e p r o j e c t ' w i t h G Fi s lines: •# () s e I e c t ο rs; # (' e η t e rPro i e c t a d d Pro j e c t re m ο ν e Pro j e c t ) ] . tProjectMenu .
339 15.3 Modify Class Project
Project Browser System Browser·! a Project a Project
Interface-Brow 3 I n t erf a ce -Ins pec Pro I«L: I n t e rf a c e - D e b υ q c Interface-File M"O Proiec Interfa c e-Tra nsc Proiec Interfa c e-Cha
projectMenu 1 ' A n s w e r a m e η υ fο r a c c ί
Figure 15.44
010
c υ t't'ii ri t Pro i e c t is Ν i I ifTrue: [Projer tMenu Labels: ' a d d proje if False: [ P r o j e c t M e n u labels: ' e n t e r '•·, a d d ρ r ο j e c t \ r e m ο ν e p r o j e c t ' w i t h >_: Fi s lines: # ( ) selectors: # ( e n t e r P r o j e c t addProjec t remo veProjec t ) ] . τ P r o j e c t Menu
X
15.3 Modify Class Project
Close any example project browsers and project views that you might have created by choosing the blue button command close in each view. In the system browser, choose the class name Project. The definition for Project displays in the text subview of the browser. Change the definition by adding the instance variable title (Figure 15.45). Choose the yellow button command accept. The class is recompiled. All existing instances of Project are updated to have one additional instance variable; in each case, the initial value of the variable is nil. Each of the existing projects must be given a title before you can change the way in which Projects print a description of themselves. One way to solve this problem is to create an inspector for all existing projects by evaluating the expression Project all Instances inspect (Figure 15.46a). There is at least one Project, the one in which you are currently running. Choose each project, one at a time, and open an inspector on it (Figure 15.46b). Choose the instance variable name title. In the text subview of the inspector, type a literal String that is the title for this project (Figure 15.46c). Choose the yellow button command accept to store the title. Do this for each existing Project. Close each inspector.
340 Examples of Creating or Changing Browsers
System Browser Interface-Brow si Interfax: Θ-Inspect In t erf 3 ce-Debug: Pro iect Browser Interface-File Γνϊο Pro ject Con t rollerIriterf3.ce-Tr3.nsc Pro iect View
initia.lize-relea. se controlling d e ρ eη dent s a c ce: c h a n q e rn a n a q e rn ι
miaiBiiiaiaiiiia»
private
I n t e r f a c e - υ hang n
a. q a ι η υ ηdo i η s t a η c e V a r i a. b I e f'• J a m e s: ' ρ r ο j e c t W i η d νο 3 • pr c ο ρ ν
b t r iη g Η ο I d e r subclass: # Ρr οj e c t
c 13. s s V a ri a. b I e I'J a. rn e s: ' C υ r r e n t Ρrο i e c t
?
poolDic tionaries: " c a t e qο r y: ' I n t e r f a c e - Pro i e c t s'
Figure 15.45
cut paste do it print it
a. n q e b e t
cancel rormat spawn explain
010 by stern Browser! Brov·. Ιη terra Inspect lnr.erfa Debug: Interra File Mo Pro j e c t BrowserInterra Transc Pro j e c t ControllerIn terra Pro iect View Interface-Chanqi
0
ir1iti3.lize-relea.se con trolling d e ρ e η dent s a. c c e c h a n q e rn a. n a q e rn private
ι gH older subclass: #Project . e V a. r i a. b I e Ν 3. rrι e s: ' ρ r ο j e c t W i η d ο w s ρ r ο j e c t C h a. n g e S e t title ' sηtPro iect '
Figure 15.46a
341 15.3 Mqdify Class Project
S ν 51 e m Β ro w s e r I
a Project
I n t e r f a c e - Β ro w s e Interface-Inspect Interface-Debugc Project Interface-File Mo Project I n t e r f a c e - Τ r a n s c Project Interface-Changs StringHolder subclass: # F ice Variable Nam Workspace Project alllnstances inspec
Figure 15.46b
TO Ordered. Collect ion Project
System Browser! Interface-Browse Interface-Inspect Interface-Debugc Project Brovv Interface-File Mo Project Cont Interface-Transc Project View
'Top Project'
Interface-Changs ci S t r i η q Η ο I d e r s u b c I a s 5:" # Pr ο j e ,. . ' li c e V a r i a b I e Ν a m e s: ' Workspace .-..·.-. i .-..-.<• U .-. I .-I
Ρ r ο j e c t allln s t a n c e s inspect
Figure 15.46c
BIO
agaιη uηdο copy cυt ρaste do it print it
342 Examples of Creating or Changing Browsers
Currently, when a Project prints a description of itself, it uses the default description, a Project, specified in the method for printOn: as defined in class Object. We want a Project to print its title instead. Create the protocol printing for class Project, and specify a new method for printOn: (Figure 15.47), You must also provide a message for setting the value of title that can be used in creating a new Project. The value should be an instance of String. Add the message title: to the category initialize-release (Figure 15.48). Now open a new project browser. You can see that each existing project now displays its title in the list menu (Figure 15.49).
Interface-Browse Interface-Inspect Inter fa ce-Debugc Project Browser Interface-File Mo Project Controller controlling Project View dependent;, acce: change maηagem lock access
aStream next Put AII: title
Figure 15.47
roc
343 15.3 Modify Class Project
System Browser Interface-Browse Interface-Inspect Interface-Debug: Interface-File Γνΐο Interface-Transc
Project Project Browser Project Cunt roller Pro jeer v i e w
•iii.u«K»iMaM«a»)
Interface-Changs
initiahze-release release printing controlling d e ρ e η d e Γι t s a c c e c h a. n g e m a. n a g e rn lock a c c e s s
t i t l e : a.String "Set the title of the project," title - aStrina
Figure 15.48
BOO Project Browser bvstem Browser Interface-Browse Interface-Inspect Interface-Debug: ProiectBr Interface-File Γνϊο Projec t C : Ι η t e rfi c e - Τ re η s cProject V'i, Interface-Changi title: abtrmg "i h e title of the ρ m i err
I
Project aliinstanc es inspect Ρ r ο i e c t Ει r ο w s e r ο ρ e η
Figure 15.49
Top Project
344 Examples of Creating or Changing Browsers
The next step is to change the method associated with addProject in class ProjectBrowser to prompt for a title. The new method is shown in Figure 15.50. It uses an instance of the system class FilllnTheBlank to request a title, then sends the newly created project the message title: in order to store the response. The two arguments in the creation of the FilllnTheBlank instance specify the noneditable text that appears in the upper subview, stating what kind of information is expected, and the editable text that appears in the lower subview. In this case, the "default" title, a Project, will appear in the lower subview; it can then be edited by the user.
addProject "Add another project to the menu of projects."
Figure 15.50
000
| a Project a3tring| •aString - FilllnTheBlank request: 'Title for Project?' i η i t i a IA n s w e r: 'a. Project'. a String isEmpty if Τ rue: [τ self], a Project *• Project new title: a String, projects add: a Project, current Project *- a Project, self changed: #current Project
The user of this kind of prompter can abort the action of adding a project by typing nothing in the lower subview. The second statement in the method for addProject tests to see if the response is nothing (isEmpty) and, if so, terminates (Τ self). Try it. Choose the yellow button command add project (as shown earlier). A prompter appears. The initial response is the default title a Project (Figure 15.51a). Edit the response and then choose the yellow button command accept (Figure 15.51b). The new project appears in the project browser menu (Figure 15.51c).
345 15.3 Modify Class Project
addProject "Add another project to the]
Figure 15.51a
BOO
| a Project aString| aString «- FilllnTheBlank request: 'Title for Project' initial A ri s w e r: 'a P r ο j e c t', a. String isEmpty if True: [ t s e l f j . aProiect *· Project new title: aString. project s add: a Project. current Project *· a Project. i.zlf changed: # current Project
Project Browser System Browser! Inter' τ·α>. c e - Β r ο w s s
Interface-Inspect Project Ι η t e rf a c e - D e h υ g >'•
Interface-File Mo, Project Con tro Interface-Transc Pro iect View
Top Ρ
agaιη υηdo T i t l e for Proiec copy cut Pro iect T w o
Interface-Change
fostaric»! addProject "Add a n o t h e r p r o j e c t t o the] | a Project
aString|
a S t r i n g - FilllnTheBlanl·
Figure 15.51b
Oio
request: ' T i t l e f o r P r o j e c t ? ' initial A n s w e r: ' a Pro j e c t ' . a String is Empty if True: [-tself], a P r o i e c t - Pro iect n e w t i t l e : aString, p r o j e c t s add: a Project. ο u r r e η t Ρ r ο j e c t *· a p r ο j e c t . self changed: # c u r r e η t P r o j e c t
do it [print i t
346 Examples of Creating or Changing Browsers
by stern Browser I Interface-Browse Interface-lnspec In t erf a ce-Debuqc Interface-File Mo Interface-Trans c
Top Project Proiect Two
Interface-Chanqt addProject "Add another project to the
Figure 15.51c
000
| a Project aString| a.Strinq *• FilllnTheBlank request: 'Title for Project?' i η i t i a IA n s w en 'a. Project'. a.Strinq isErnpty if Τ rue: [ t s e l f ] , a Project - Project new title: a String. projects add: a P r ο j e c t. current Project - a Project, self changed: # current Project
15.4 Change the System Menu
It would be more convenient to be able to create a project browser with the same ease that we can create a system browser, that is, by choosing an item from the System Menu. The creation of the System Menu is specified in the system class ScreenController. In the system browser, choose the class category Interface-Support and then choose the class name ScreenController. Choose the browser menu item class. The only message selector in the category class initialization is initialize. Choose it (Figure 15.52). The System Menu is a PopUpMenu. PopUpMenu is an alternative way to create menus that know about item labels and lines, similar to ActionMenu. A PopUpMenu does not store the messages associated with the menu items. Class ScreenController has two class variables in which the PopUpMenu and the corresponding array of messages are stored (ScreenYellowButtonMenu and ScreenYellowButtonMessages). To modify the System Menu, you must edit the method for ScreenController initialize. Delete the exit project and project items in the menu labels and insert project browser. The line numbers must change as well as the messages. Delete the messages exitProject and open Project, and insert the new message openProjectBrowser. Choose the yellow button command accept to recompile the method (Figure 15.53).
347 Change the System Menu
Kernel-Support Interface-Frame 1 ·.• Explainer class initializationhnitiaize MouseMenuContr Interface-Lists Interface-Text ScrollCont roller I n t e r f a c e - M e n us S t a n d a r d S y s t e m ί I n t e rf a c e - Pro m ρ t
initialize "Initialize t h e S y s t e m Menu."
Figure 15.52
iooo
S c r e e η Υ e 11 o w Β υ 11 ο η Μ e η υ *• PopUpΜenu labels: ' r e s t o r e display exit project project file list browser wori space
Kernel-Support Interface-Frame 1 ·/ Ε χ ρ I a i η e r MouseMenuContr Interface-Lists Interface-Text ScrollCont roller Interface-Menus StandardSysternC Interface-Prompt 'restore display project browserfile list browserworkspace system t r a n s c r i p t system workspace save quit'
Figure 15.53
Οίο
lines: # ( 1 7 ), S c re e η Υ e 11 o w B u t t ο η Μ e s s a g e s *# (re s t ο re D i s ρ I a y ο ρ e η Pro j e c t Β ro w ser
again undo copy cut paste do i t print it cane el f ο rm a t spawn explain
348 Examples of Creating or Changing Browsers
You need to update the class variables and to inform existing instances of ScreenController that the menu has changed. This is done by evaluating the expressions ScreenController initialize. ScreenController alllnstancesDo: [ :sc I sc initializeYellowButtonMenu] that appear at the end of the method initialize, as shown in Figure 15.54.
Kernel-Support Interface-Frame1·/ Ε χ ρ I a i η e r MouseMenuContr Interface-Lists KMMaMwnmmai Interface-Text be rollCont roller Interface-Menus Standardsvjtemf Interface-Prompt
MEMMIIIHEIIBC^IUI
lines: # ( 1 7 ), S c r e e η Υ e 11 o w B u t t ο η Μ e s s a g e s *# (r e s t ο r e D i s ρ I a y ο ρ e η Ρ r ο j e c t Β r ο w s e ο ρ e η F i I e L i s t ο ρ e η Β r ο ν·.·· s e r ο ρ e η W ο r k s ρ ο ρ Θ Γι S y s t e m W ο rks ρ a c e save q u i t ) .
Figure 15.54
η Τ ran script
010 The ScreenController must be able to response to the message openProjectBrowser. The method is shoiwn in Figure 15.55. Add this method to ScreenController. The System Menu is now changed so that you can try it out (Figure 15.56). Now that you can create project browsers using the System Menu, you will find that adding projects and removing projects must be broadcast in some way to all existing project browsers. Moreover, unless you are careful, broadcasting a message to change a browser will cause it to redisplay. If project browsers from different projects redisplay on the single display screen, this will look very peculiar. Thus you might prefer to add a menu item to the yellow button menu of the project browser list menu subview, update projects. You can broadcast the addition and removal information without updating the display of the browser, and then select the new menu item update projects to obtain the proper display. This is the technique adopted by the system browser. Perhaps you can think of an improved approach. Also note that if you do change the menu for the project browser, you must reset all the class variables referring to the menu.
349 15.4 Change the System Menu
Kern el-Sup port initialize-release Interface-Frame'· Ε χ ρ I a i η e r imiaitnKHaiimw! MouseMenuContr control defaults Interface "List 5 ScreenContro 9r Imenu messa< be rollCont roller cursor In terrace-Text Interface-Menus S t a n d a. rd S ν s t e m ( private Interface-Prompt
ex it Project ο pen Browser openF'roject ο ρ e η S y s t e m W ο rk ope η T r a n s c r i p t open Workspace
openProjectBrowser Ρ r ο j e c t Β r ο ν·.·1 s e r ο ρ e n ;
Figure 15.55
r e s t o r e dis play
Bro\ , 3 e r L kernel- .ιυμμ Interfac e-Fr Ε χ ρ 1 a i ri e r
b y s t e ΓΓΙ
"****η
Μ ουseΜ eηυυ οηt r
ffifl mm 'mm
t i i e 115.1 ,• WL.rK:.pd
I·."
It·
In t erf a ce-Li st s sv'stern t r a r script Screen Co rttrrtter Intarfac e-T 9 :•: Τ : = .crolir:onrroller system worl· space 3a ve In t erf a ce-M e η υ s quit Interfar e-Pt 0 ΓΓι p t i n s t a rice|i:;i:iyisisiSi::i, lines: # ( 1 7 ), S c >Ρ ρ Γι ' e l l o w B u t t o n M e s s a q e s # (r e 3t ο r e D i s ρ 1 a. y ο ρ e η Ρ r ο j e c ΐ Β r ο w s e r ο ρ e η F i 1 e L i s t ο ρ e η Β r ο w s e r ο ρ e η W ο r k s openTra ρa cί nscript ο ρ e ri S y 31 e η- Wori space 3 a .·•• e quit),
I
re en I: o ri t rj 11 e r i η i t i a 1 i r e, μμΓ. ι" :ontr Her alllnstancesDc : [:c owBu t t o n M e n u ] " iηit ia 1ir
Figure 15.56
is
How to Find and Correct Errors ΙΙΙΙΙΪΙ In the previous book parts, you were introduced to the views and menus that provide support in finding out information about existing system functionality and in creating new functionality. In examples presented, we attempted to minimize the errors you would encounter. The purpose of Part Four is to explain how to find and correct errors, in particular, syntax errors and runtime execution errors. The examples will ask you to create errors so that you can learn how to correct them. The errorhandling support takes the form of error correction aides, error notification (either in-line error messages or use of the notifier view), and the debugger view. The debugger is used to find an error that occurs during execution of an activity, and it is used to find out how an activity is implemented.
16 Spelling Correction
354 Spelling Correction A major area of research in the development of programming environments has been to provide on-line assistance to the programmer. Some of the earliest work in this area was done in the context of the development of the Interlisp programming environment under the research title of "programmer's assistant." [W. Teitelman, "Automated Programmering—The Programmer's Assistant," Proceedings of the Fall Joint Computer Conference, Dec. 1972; W. Teitelman and L. Masinter, "The Interlisp Programming Environment," IEEE Computer Magazine, April 1981, pp. 25-33]. One of the results of this research was the introduction of the DWIM, or "do-what-I-mean" spelling correction, approach to interaction and error handling. Adapted from this research on spelling correction, the Smalltalk-80 system includes the ability to assist the programmer by correcting misspellings of variable names and message selectors. Spelling correction is done within the context in which you are working, that is, within the scope of the variables and message selectors of a class definition or of an interrupted context. This chapter describes the spelling correction mechanisms as you might encounter them when evaluating expressions in a workspace. Chapter 17 explores the way in which the Smalltalk-80 parser reports syntax errors in method definitions, and the way the system uses the spelling corrector to help you correct these errors. And Chapter 18 illustrates how you are notified of runtime errors that are associated with unrecognized message selectors, and how the spelling corrector can help you determine the correct message selectors. Figure 16.1a shows a workspace in which the text consists of a temporary variable declaration for bic, and an expression to assign an instance of class Pen to the variable spelled bik. This could either be an undeclared variable name, or a misspelling. If you select this text and then choose the yellow button command do it, the system guesses that bik is an undeclared variable. This variable is selected and a menu of optional next actions is displayed (Figure 16.1b). Four of these actions involve declaring the variable; one tries to fix its spelling.
Figure 16.1a
Oio
355 Spelling Correction
Hf|fllHil|lii yy QΓ"Κ5P3.QP joJfliilflfifififlflfififlflflBfllffl|
illiiiiii 1
bic
1
iiiiiii:!:!:!:! I m i *• Ρ Ρ Π T I P W
declare b i k as
Figure 16.1b
nnn • UUU mm
t e rn ρ c 1 a. z 5 ν a. r global 1^ undeclared correct it abort
temp
Declares the variable to be a temporary. The variable name will be inserted into the text, delimited by the vertical bars. If the vertical bars do not already exist in the text view, they are added. (See Figures 16.4a, 16.4b, and 16.4c in which this declaration is illustrated.)
class var
Declares this variable to be a class variable of the class of the method in which the error was found. If the error is found in the text subview of the inspector, then this declaration will make the variable a class variable of the inspector. At the level of a workspace, the class is assumed to be UndefinedObject, the class of the object nil. (All class variable names must start with a capital letter.)
global
Declares this variable to be a global variable, which means that the variable is included in the system dictionary, Smalltalk. (All global variable names must start with a capital letter.)
undeclared
Leaves this variable undeclared, which means it is included in the system dictionary, Undeclared. A message that states that the variable is undeclared prints in the System Transcript, if it appears on the screen.
correct it
Tries to determine the most likely correction. (This is done by searching the known symbols in the system for the closest match.)
abort
Forgets the attempted evaluation.
356 Spelling Correction Choose the command correct it (Figure 16.1c). The system determines that the most likely correction for bik is bic. A confirmer is displayed indicating that the proposed correction is bic. Confirm the choice by choosing the command yes (Figure 16.Id). The correction replaces the erroneous variable in the text of the workspace (Figure 16.le) and the expressions are successfully evaluated.
•'> 0 Γ" Κ. i D 3 . L- θ
I
bic
ΒΒΒΒΒΒΒΙΠΗΗΗΙΙΗΗΙΗΙΗΗΗΗ
Ι
ImS *• Pen new declare bik a.5 | temp Ι class v a r 1 qlobal Ι j η declared}
Figure 16.1c
WMtt Π Ι ΜΠΠΜϋΙ Wwrt ϋϋϋϋϋϋί; ϋϋιίϋϋιΗ! ::::::::
abort ^j
100 Workspace
^
^
^
j
^
^ y *• Pen new
Confirm c o r r e c t i o n t o bic WMM
Figure 16. Id
IU0
i
yes ^ - ί
no
::ί|φ!Φ:>
In Figure 16.2a, a statement has been added to the text in the workspace, but the trailing colon for the keyword go was omitted. The attempt to evaluate the expressions fails. The erroneous message selector is selected, and a menu appears indicating that the problem is that the message go might be a new message (Figure 16.2b).
357 Spelling Correction
1 bic |
\
m
I :•£:
1
1 Figure 16. le
Figure 16.2a
I
ooo ι
i
a c c 9ρ t c a. π c 91
010 Mm Workspace | H | |
s i n ι bi ° ι
ijiiHiiii
iijiiiiiiiijjii! bic *- Pen new,
Wtitt Qo
5 a n 9 w rnessaqe 1
proceed | co rrec
Figure 16.2b
ιοο 11
;i:i;i;iii;i;i
358 Spelling Correction
The menu indicates three optional actions. proceed as is
Proceeds on the assumption that this message will eventually be implemented. This is a likely occurrence if you take a top-down approach to programming. This option really only has meaning in the context of compiling a new method, not in the context of evaluating an expression in a workspace.
correct it abort
Tries to determine the most likely correction. Forgets the attempted evaluation.
Choose the command abort. As shown in Figure 16.2c, the keyword go was corrected to be go:, and then a third statement was added. The attempt to evaluate these expressions fails (Figure 16.2d). A menu appears indicating that the problem is that the message trn: might be a new message. Choose the action correct it. The system guesses that turn: was intended (Figure 16.2e). Confirm that this is the correct message by choosing the confirmer menu item yes. The correction is made in the text of the workspace. The evaluation is restarted, and the new Pen draws a line on the display screen (Figure 16.2f).
Figure 16.2c
Bio
359 Spelling Correction
Wor bic *• Pen new, bic q ο; 10 0, b i Γ:
Figure 16.2d
| trn:i S d Π 9 W ΓΓι 9 S S d. q 9 .s is| proceed ·-. correct it ^^^^^^H abort
100 1 bic | bic *• Pen new. bic go: 100.
Confirm correction to turn:
Figure 16.2e
Figure 16.2f
100
I
y« £ j
no
360 Spelling Correction
For the next example, edit the statements in the workspace so that there are four expressions; the second (and new one) changes the form source (the "brush") of the Pen to be a new Form. Evaluate the statements (Figure 16.3a). The class name Form was misspelled as indicated by the menu that appears (Figure 16.3b). Choose the command correct it. The system guesses that an appropriate correction for Fom is Form (Figure 16.3c). Confirm by choosing the menu item yes. Evaluation is restarted, but another error is found (Figure 16.3d); a message is not known. Choose the abort command. Parentheses are needed. Notice also that the argument to extent: should be an instance of Point. Make both corrections (Figure 16.3e). Delete the declaration of bic as a temporary variable; evaluate the remaining expressions (Figure 16.4a). The system notices that bic is not declared (Figure 16.4b). Choose the item temp in the correction menu that appears. The declaration is inserted into the text (Figure 16.4c).
Figure 16.3a
I bic |
bic bic bic bic
Figure 16.3b
ioo
*- Ρ9Π new. so υ re 9 Form: go: 100. turn: 89
new extent: 20,
1
361 Spelling Correction
i bic | bic *• Pen new. bic source Form: [^Q new extent: 2u. bic go: 100, bic turn: 89 Confirm correction to Form
Figure 16.3c
:.·.·.™....-.-.-.·.·.·.·Λ-.-.·.-.......·.-Λ....·^!^^^ ! ;
ye; ^
100
no
8888888 8888888
V'/orl· 1 bic 1 bic «- Pen new, bic sourceForm: Form new extent: bic go: 100. bic turn: 89
Figure 16.3d
100
| sourceForm:extent: is a. new message proceed a s isl | correct it I *?P^
I bic I bic *- Pen new, bic source Form: (Form new extent: 20'1'IOj, bic go: 100. \ bic turn: 89
Figure 16.3e
000
362 Spelling Correction
I Worl·.space I β gaιη
Ibic *• Pen new.
undo source Form: (Form new extent: U 0 @ 1 U ) copy Ibic go: 100. cut paste Ibic turn: 89HH|^^HH
•anagit prir^ i t | a c c eρ ti
Figure 16.4a
r ,=i η r Ρ Ι Ρ
I
ΟΙΟ
• Pen new, bic source Form: (Form new extent: 20@10). bic go: 100. _ declare bic as bic turn: 89
Figure 16.4b
100
c I a. s s ν a. r global undeclared correct it abort
- Pen new, bic source Form: (Form new extent: 20@10), bic go: 100. bic turn: 89
Figure 16.4c
BOO
J
r
Syntax Errors
17.1 Variable Name or Message Selector Errors 17.2 Poorly-Formed Statements or Methods
364 Syntax Errors
A compiler is used in three places in the Smalltalk-80 system: 1. when you add a method to a class description by choosing the command accept in a system browser, 2. when you evaluate an expression by choosing either the command do it or print it, and 3. when you file in a class description from an external file. This chapter illustrates the kinds of syntax errors you can encounter in the first two cases; Section 22.2 describes the third case.
17.1 Variable Name or Message Selector Errors
The spelling corrector is a part of the syntax analysis available when you compile class methods. To illustrate the kind of syntax errors that you can encounter, follow an example implementation of the class FinancialHistory. We will continue to work on this FinancialHistory example for several consecutive chapters, so try to save your work between sessions. Add the class category Financial Tools and define the class FinancialHistory. The class definition is shown in Figure 17.1. (If you have forgotten how to add class categories and classes, review Chapter 9.) Choose the browser menu item class so that you can define a message understood by the class FinancialHistory. This message is an instance creation message. Add the class protocol instance creation. In protocol instance creation, type the method for initialBalance: shown in Figure 17.2a. Choose the yellow button command accept. The method for initialBalance: consists of sending the new instance of FinancialHistory the message setlnitialBalance: so that the instance variables can be initialized. This message is not implemented as yet, so a correction menu, like the ones introduced in Chapter 16, appears. The menu states that setlnitialBalance: is a new message (Figure 17.2b). The next thing you will do is define this message, so choose the action proceed as is to complete the compilation of the method initialBalance: (Figure 17.2c).
365 17.1 Variable Name or Message Selector Errors
b y s t e rn - (J h 3. η q e s S y s t e rn - C ο m ρ i I e r S y s t e rn - Fi e I e a s i η g Files-Streams Files-Abstract Files-Xerox A l t o
0 b j e c t s υ b c lass: # Fi η a n c i a IH i s t ο r y i η s t a. π c 9 V a r i a b I e Ν a m e s: ' c a s h 0 η Η a n d e χ ρ e η d i t u r ι c I a s s V a ri a b I e Ν a rn e s: " poolDictionaries: " c a t e g o r y : 'Financial Tools'
Figure 17.1
BOO 5 » ; t e rn - C h a n g e s 3 y s t e rn - C ο rn ρ i I e r FinancialHistory S y s t e rn - Fl e I e a. s i η q Files-Streams Files-Abstract Files-Xerox A l t o
instance creation
i η i t i a IB a. I a n c e: a rn ο υ Γι t " C r e a t e a. new FinancialHistory w i t h amount as the c u r r e n t cash a. g a ι Γι on hand." undo cορν s υ ρ e r η e w s e 11 n i t i a IB a. I a n c e: a rn ο υ η t cυt ρa ste do it print it
Figure 17.2a
Bio
c a n c* Term a t .-pawn explain
366 Syntax Errors
S y s t e rn - C h a n g 9 s S y s t e m - C ο rn ρ i I e r S y s t e ΓΙΊ - Fi e I e a. 3 i η cj Files-Streams Files-Abstract Files-Xerox A l t o
i ri i t i a. IB a I a n c e: a rn ο u η t " C r e a t e a n e w Fin a ncialHist ο r y w i t h a mount as t h e c u r r e n t cash on hand," t s υ ρ e r η e w jetlnitialBalance: amount
| setlnitialBalance'· is a. new messa gc correct it abort
Figure 17.2b
100 System-Changes S y s t e rn - C ο rn ρ i I e r FinancialHistory System-Releasing Files-Streams Files-Abstract Files-Xerox A l t o
instance creation initialBalance:
i Γι i t i a IB a. I a n c e: a m ο ι J η t " C r e a t e a n e w FinancialHistory w i t h amount as t h e c u r r e n t cash on hand," t s u p e r ne·
Figure 17.2c
setlnitialBalance: amount
BOO
J
367 17.1 Variable Name or Message Selector Errors
Now choose the browser menu item instance and add instance protocols transactions, inquiries, and private. Under private, we will categorize all messages that should only be sent by an instance of FinancialHistory to itself (self). Define setlnitialBalance: under the protocol private (Figure 17.3a). Notice that for the example, you are to mistype the instance variable cashOnHand—the 0 should not be capitalized. A correction menu appears indicating that cashonHand is not declared (Figure 17.3b). Choose the command correct it. A confirmer appears indicating that the probable correction is cashOnHand. Confirm by choosing the menu item yes (Figure 17.3c). As a result of your choosing yes, the corrected variable name is inserted into the method, the method is successfully compiled, and the message selector is added to the browser menu (Figure 17.3d).
System-Changes System-Compiler S ν s t e m - R e I e a. s i η q Files-Stream 5 Files-Abstract Files-Xerox A l t o
s e 11 n i t i a. IB a I a n c e: a rn ο υ η ΐ "Initialise t h e i n s t a n c e v a r i a b l e s of t h e new F i n a n c i a l H i s t o r cashonHand - amount, e x p e n d i t u r e s +- D i c t i o n a r y n e w
a. g a ι η υηdο copy
cut
ρaste do i t
print it c a n ci£ I
Figure 17.3a
010
f ο rrn a t spawn e 'plain
368 Syntax Errors
S y s t e m - C h a. n g e 5 S y s t e rrι - C ο m ρ i 1 e r System-Releasing; File;-Streams Files-Abstract Files-Xerox Alto
trans action; inquiries
; e 11 η i t i a. ΙΒ a. I a. η c e: a. m ο u η t "Initialize t h e instance variables of the new FinancialHistory a. rn ο υ η t. e χ ρ e η d i t u r e s *· D i c t i ο η a r y η e vv
declare cashonHand as
Figure 17.3b
temp c I a s s ν a. r global υ η dec I a. re
1DD
abort
y stem-Changes System-Compiler S y s t e rrι - Fi e I e a s i η g Files-Streams Files-Abstract Files-Xerc : A l t o
s e 11 n i t i a IE a. I a n c e: a m ο υ η t "Initialise the instance variables of t h e n e w FinancialHistory," a m ο υ η ΐ, expenditures *• D i c t i o n a r y n e w
confirm c o r r e c t i o n t o cashOnHand
Figure 17.3c
loo
369
17.2 Poorly-Formed Statements or Methods
.••5 t e r n - C h a n g e ; ,·' i t s rn - C ο m ρ i I e r S y s t θ rn - Pi e I e a s i η g| Files-Streams Files-Abstract Files-Xerox A l t o
transaction
inquiries
s e 11 n i t i a IB a I a n c e: a rn ο υ η ΐ "Initialize t h e i n s t a n c e v a r i a b l e s of t h e n e w FinancialHistor
e x p e n d i t u r e s *· D i c t i o n a r y n e w
Figure 17.3d
000
17.2 Poorly-Formed Statements or Methods
Choose the protocol transactions and specify the method for spend: amount for: reason (Figure 17.4a). Notice that you are to omit an argument. When you choose the yellow button command accept, a syntactic error is found (Figure 17.4b). The error message, Argument expected->, is inserted into the text, preceding the point of the error, so that an arrow points to the location of the error or to the location at which the error can be corrected. Type the correction so that the error message is replaced by the argument name reason, and choose the yellow button command accept again (Figure 17.4c). This time the new message totalSpentOn: is noticed (Figure 17.4d). We will define this message later so choose the action proceed as is. The method is compiled successfully and added to the class (Figure 17.4e).
370 Syntax Errors
b ν stem-Change; S y s1 e m - C ο rn ρ i I e r 5 y ; t e rn - R e I e a ; i η q File;-Streams Files-Abstract File;-Xerox Alto
inquiries private
spend: amount for: re a ; o η "Spend amount for the reason given, decrementing the available cash on hand," agaιη υηdo expenditures a t : put: (self t o t a l b p e n t O n : re a. son) + amount, copy cυΐ cashOnΗand - cashOnHand - amount paste do it print it
cartel
Figure 17.4a
format spawn e '.plain
ΟΪ0 by stem-Changes S ν s t e rn - C ο rn ρ i I e rFinancialHistorv S y s t e m - R e I e a. s i η g Files-Streams Files-Abstract Files-Xerox A l t o
transactions inquiries ρ ri ν a t e
spend: amount for: reason "Spend amount f o r t h e reason given, d e c r e m e n t i n g t h e a v a i l a b l e c a s h on hand," expenditures at: Argument expected - ; put: (self totalbpentOn: re a. son) + amount, cashOnHand - cashOnHand - amount
Figure 17.4b
BOO
371 17.2 Poorly-Formed Statements or Methods
5 y item-Change; S ν stern-Compiler nnancia History System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
transactions inquiries private
spend: a m o u n t for: r e a s o n "Spend a m o u n t f o r t h e r e a s o n g i v e n , d e c r e m e n t i n g c a s h on hand," e x p e n d i t u r e s a t : r e a s o n p u t : (self t o t a l S p e n t O n : re cashOnHand
*- c a s h O n H a n d
- amount
a g a. ι η ilable undo copy
cut paste do it print it format spawn
Figure 17.4c
e χ ρ I a. i η
Bio S y stem-Releasingl Fi I e s - S t re a m s Files-Abstract Files-Xerox Alto
spend: a m o u n t for: r e a s o n "Spend a m o u n t f o r t h e r e a s o n given, d e c r e m e n t i n g t h e a v a i l a b l e c a s h on hand,"
expenditures at: reason put: (self totalSpentOn: reason Ί + amount, cashOnHand - cashOnHand - amountj totalSpentOn: is a new message correct it I abort
Figure 17.4d
100
372 Syntax Errors
System Browser b y s t e rn - υ h a n g e s Ei y s t e rn - C ο m ρ i I e FinancialHistory r Ei y s t e rn - Fi e I e a.; i η g File;-Streams Files-Abstract Files-Xerox A l t η
transactions inquiries private
spend: amount for: reason "Spend amount for t h e reason given, decrementing the a v a i l a b l e cash on hand," expenditures a t : reason put: (self totalSpentOn: reason ϊ + a rn ο υ ΓΙ t. c a s h Ο η Η a η d - c a s h Ο η Η a η d - a rn ο υ η t
Figure 17.4e
000 The syntax errors you might make when you try to evaluate an expresson or compile a class method fall into three categories: 1. something expected was missing 2. there was a bracketing error 3. you tried to do something you can not do Expected parts of a method that can be missing are the argument name, as illustrated by the previous example in Figure 17.2a; an expression after an assignment symbol («-) or after a return symbol (T); a vertical bar; and a period or right bracket at the end of the method. Also nothing more might be expected if the compiler thinks the method has ended, although something more exists. Bracketing errors may exist for parentheses, comment quotes ("), square brackets, and string quotes ('). Another common mistake is omitting the period at the end of a statement (other than after the last statement of a method). Three things you can not do that will be noticed as syntactic errors are to store into a pseudo-variable (self, super, true, false, or an argument), to cascade to a constant or to super, and to cascade certain control messages (ifTrue:ifFalse:, ifFalse:ifTrue:, whileTrue:, and whileFalse:).
373 17.2 Poorly-Formed Statements or Methods To illustrate another syntactic error, add the method totalSpentFor: to class FinancialHistory; categorize it under inquiries as shown in Figure 17.5a. (For now, please ignore the fact that the message used in the method for spend:for: was totalSpentOn:, not totalSpentFor:. You are making this error so that we can illustrate another kind of error in Chapter 18.) Choose the yellow button command accept. A syntax error message is inserted into the text at the end of the method (Figure 17.5b) because, when you typed the method, you forgot the closing right bracket. Replace the error message with the right bracket and choose the command accept again. The method is added to the class (Figure 17.5c). Remember to save your work, either by making 1. a snapshot (see Sections 1.4 and 23.1) or 2. a file that describes the class. In the system browser, choose FinancialHistory and then choose yellow button command file out. The file name will be FinancialHistory.st.
y stern-changes s t e rrι - C ο rn ρ i I e r s t e rn - Fi e I e a. s i η g Files-Streams Files-Abstract Files-Xen: : Alto
t o t a IS ρ e η t Fο r: re a s ο η "Answer the amount spent for reason; expenditures."
0 if reason never used for
e ;•: ρ e η d i t υ r e s i η c I u d e s \<. e y: r e a. s ο η) if True: [ t expenditures a t : reason] ifFalse: [ t i j
Figure 17.5a
Bio
374 Syntax Errors
System-Changes System-Compiler System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
lameimnsiuia.il—
transactions ρ ri ν a. t e
t ο t a IS ρ e η t Fο r: re a s ο η "Answer the amount spent for reason;
0 if reason never used for
expenditures." (expenditures includes Key: reason) ifTrue: [ t expenditures a t : reason] if False: [ t u | iqht bracket
Figure 17.5b
BOO System-Changes S y s t e m - C ο m ρ i I e r[aiilSHMElliUMni S y s t e m - Fi e I e a s i η g Files-Streams Files-Abstract Files-Xerox A l t o
transactions private
t ο t a IS pent Fo r; re a s ο η "Answer the amount spent for reason;
0 if reason never used for
expenditures." (e χ ρ e η d i t u r e s include s Κ e y: r e a s ο η) ifTrue: [τexpenditures at: reason] ifFalse: [ + 0 ^
Figure 17.5c
ι
fflo
J
1 *
Notification of an Execution Interrupt
18.1 Incorrect Message Selector 18.2 Other Runtime Errors
376 Notification of an Execution Interrupt A message-send is the activity of sending a message to an object. A notifier is a view that is displayed on an interruption of a message-send. Since responding to a message involves sending a message, a notifier is basically a view on a sequence of message-sends. Each of the messages displayed in the view has been sent, but has not yet received replies. There are a number of ways to interrupt a message-send, four of which are described in Chapter 20: the programmer sets a breakpoint, the user types the "control" and "c" keys at the same time, the system runs out of space, and recursion occurs in the system error handler. This chapter explores interrupts that occur whenever a runtime error is encountered. Most runtime errors occur because a message was sent to an object that does not understand the message, that is, the message selector was not specified in the class of the object or in any of its superclasses. The error could be that the message selector was incorrect, or that the receiver of the message was the wrong kind of object. The other kinds of interrupts are discussed in Chapter 20.
18.1 Incorrect Message Selector
The FinancialHistory example in Chapter 17 will be used to illustrate the way a notifier is used to locate a runtime error. If the class is not already in your system, we assume you created a file containing the class description, as discussed at the end of Chapter 17. Evaluate the expression, (FileStream oldFileNamed: ' FinancialHistory.st') fileln to retrieve the class. Open a workspace and type the instance creation message FinancialHistory initialBalance: 450
This creates a new instance of FinancialHistory with 450 as the cash on hand. Inspect this new instance by sending it the message inspect. (Remember that the instance creation expression must be parenthesized as shown in Figure 18.1a, otherwise the precedence rules cause the message inspect to be sent to the number 450.) Create the inspector and examine the values of its variables (Figure 18.1b). In the text subview of the inspector, type an expression to spend some of that cash. self spend: 100 for: 'rent'
Evaluate the expression by choosing the yellow button command print it (Figure 18.1c). A notifier appears (Figure 18. Id). It consists of two parts: a title that states the reason for the execution interrupt, and a list of the last few interrupted message-sends.
377 18.1 Incorrect Message Selector
S y s t e m Β r o w serf; by stem-Changes S y s t e rn - C ο rn piler S y s t e rn - R e I e a s i η g Files-Streams Files-Abstract Files-Xerox A l t o
inquiries
private
class spend: amount for: reason amount for the reason given, decrementing the available
If totalSpentOn: reason) + amount, mount
Figure 18.1a
Dio System Browser by stem-Changes System-Compiler System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
spend: amount for: re·: Workspace ί F i η a n c i a IH i s t ο r y initial 450) inspect
Figure 18.1b
100 000
ilf totalSpentOn: reason) + amount, mοuηt
378 Notification of an Execution Interrupt
FinancialHistory System Browser S y s t e m - (J h a n q e s 5 y s 1e rn - C ο m ρ i I e r S y s t e rn - Fi e I e a. s i η q Files-Streams Files-Abstract Files-:: ere, • A l t o
self spend: 100 for: 'rent'
self
a. q a ι η υ ΓΙ d ο copy cυΐ ρaste do i t
eχρeηdι
financial Tools
spend: a m o u n t for: r e a s o n |-J a.mo amount for t h i ~ » Workspace! (Fi Γι a. η c i a ΙΗ i s t ο ry ί η i t i a IB a I a 4 5 0 ) ins p o e t
canceI
If t ο t a I s ρ e η t Ο η: r e a. s ο η) + a. mount. ΊΊ O IJ Π t
Figure 18.1c
010 FinaricialHistory b y stem Browser System-Chanqes S y s t e rn - C ο m pile r S y s t e rn - Fi e I e a s i η q Files-Streams Files-Abstract Files-Xere A l t o
self spend: 1OU for: ' r e n t ' Message not understood: totalSpentOn: F i η a η c i a ΙΗ i s t ο r y (Ο b j e c 11 > > d ο e s Ν ο t U η d e r s t a n d: Fi η a. η c i a ΙΗ i s t ο ry > > spend: f ο r: Financial Hi s t o r y ) ) Dolt C ο m pile r> > e ν a Ι υ a t e: i η: t ^ η ο t i f y i η q: i f Fa. i I: Co deCont roller) > dolt
spend: amount for: reason ,,, . ϋ amount f o r the 1 Workspace ί Fi η a η c i a ΙΗ i s t ο ry i η i t i a IB a I a. ι 4 5 0) i η s ρ e c t
Figure 18. Id
roo
IT t o t a l b p e n t o n : reason) + amount
379 18.1 Incorrect Message Selector
You might decide from this information that you have seen enough information, that everything is satisfactory, and that you want to proceed with the evaluation. You can do so by choosing the yellow button command proceed. Or you might want to stop the evaluation and do something else. You can do this by selecting the blue button command close. Of course, the view is non-preemptive; you can just leave it on the screen and do something else, returning to deal with the interrupted situation at a later time. The message shown in the Figure 18. Id says that the message totalSpentOn: was not understood. Of course, this happened because you specified the method for totalSpentFor:, not totalSpentOn:, when following the example in Chapter 17. The yellow button menu of the notifier includes the command correct. Choose it (Figure 18. le). The system determines that the message should probably have been totalSpentFor: (Figure 18.If). Choose the menu item yes in the confirmer to indicate your agreement. Evaluation proceeds, using the corrected message selector, so that the $100 is spent on rent. The method associated with spendfor: returns the FinancialHistory as its value (Figure 18.1g).
System
Browser
b y s t e rn - <J h a n g Θ S System-Compiler System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
self spend: 1UU for:
rent'
Fi η a η c i a ΙΗ i s t ο ry ί 0 b j e c t ) > > d ο e s Ν ο ΐ U η d erst a n d: Fin a η c ia ΙΗis t ο ry > > s ρ end: f ο r: FinancialHistory>>Dolt C ο rn ρ i I e r > > e ν a Ι υ a t e: i η: t ο: η ο t i f ]Pr u u ' , , 1 debuq υ ο d e <J ο η t r ο 11 e r > > d ο 11 ' —
5 ρ end: amount for: reason aamount m o for the 1
Workspace f
(Fi η a η c i a ΙΗ i s t ο ry i η i t i a IB a I a ι 4 5 0 ) inspect
If totalSpentOn: reason) + amount, mount
Figure 18. le
380 Notification of an Execution Interrupt
Fin a. ncialHistory System Browser! bystem-Cha ηges 5 ν s t e rn - C ο m ρ i I e r £i y s t e rn - R e I e a. s i η q Files-Streams File s - A b s t r a c t Files-Xerox A l t o
Tooly
self spend: 100 for: 'rent' Γνΐ ρ 5 ••, a g « η ο t υ η d erst ο ο d: t o t a. IS ρ e η t Ο η: F i η a η c i a ΙΗ i s t ο r y (Ο b j e c t ) > > d ο e s Ν ο t U η d e r s t a. n d Fi ri a. η c ί a ΙΗ ί s t ο r y > > spend: to r: Financ r e t r y w i t h selector: ying:ifFai UοmρiI totalSpentFor: C ri d ρ '•"·
sperid: amount for: reason ,, , kj amount for the •Vorkspa.ce ι (Fi ri a. η c i a. ΙΗ i s t ο ry i η i t i a. IB a I a ι 4 5 0 ) inspect
Figure 18. If
100 ι y stem Browser System-Changes System-CοmρiIer System-Re leasing Files-Streams Files-Abstract Files-Xerox Alto
spend: amount for: reason i l ,,, . W a m ο υ η t fο r t h e Workspace [ (Fi η a n c i a IH i s t ο ry ί η i t i a IB a. I a ι 4 5 Ο) i η s ρ e c t
Figure 18.1g
If t o t a l S ρ e η t Ο η: re a. s ο η ϊ + a m ο υ η t , mουηt
self spend: 1OO for: 'rent
If t o t a l b p e n t O n : reason) + amount
Boo
J
381
18.1 Incorrect Message Selector Unlike other uses of the spelling corrector, the correction was only temporary. You must use a system browser to find the method containing the error and to correct it (Figure 18.2). Once corrected, you can spend successfully $50 on food and $75 on a trip by evaluating the appropriate expressions in the inspector text subview (Figure 18.3). You can also choose cashOnHand and expenditures in the inspector to examine the instance variables (Figures 18.4 and 18.5). Keep the inspector for the FinancialHistory so that you can use it in Chapter 19. Fi η a η c i a. ΙΗ i s t ο r ν " I =: ρ If τη ρ η Η by stern-change; S y 51 e m - C ο rn ρ i I e r S y s t e rn - Fi e I e a s i η g Files-Stream;. Files-Abstract Files-Xerox Alto
ΙΠ fur: 'rent' *
inquiries private
spend: amount tor: reason "Spend amount for the reason given, decrement ι nq the a • ·•' a i ι a h ι · aqain cash on hand." cορy expenditures at: reason put: is elf totalbpentFor: reason' cut jnt. cashOnHand *- cashOnHand - amount do It print it
Figure 18.2
010
format spawn explain
382 Notification of an Execution Interrupt
3 y s t e rn Β ro w s e r System-Changes S y s t e rn - C ο m ρ i I e r System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
self spend: 1uO for: ' r e n t '
spend: .amount for: reason "Spend amount for the cash on hand," expenditure? at: reason put: (self totalbpentFor: re·; cash On Η and *• cashOnHand - amount
Figure 18.3
010 ••stem B r o w s e r I System-Changes S y s t e m - C ο rn ρ i I e r S y s t e rn - R e I e a s i η g Files-Streams Files-Abstract Files-"ero • Alto Tools spend: amount for: re·: "Spend amount fo cash on hand," expenditures at: reason put: (self totalbpentFor: reason) + amount, cashOnHand *• cashOnHand - amount
Figure 18.4
100 000
383 18.2 Other Runtime Errors
b ν s t e m Β ro w 5 e r bystem-Chanqes S y 51 e m - C ο rn ρ i I e rfin* S y s t e m - Fi e I e a ί i η q File s - S t r e a m s File s - A b s t r a c t Files-:.'ero • A l t o
FinancialHistory self cashOnHand
D i c t i ο η a ry ('rent'- > 1 υ ι 'food'->50 'trip'-;·75 )
Htv&nctal Tools spend: amount for: re: "Spend amount to cash on hand." expenditures at i«?:on put: ('self totalbpentFor: reason) + amount. cashOnHand *• cashOnHand - amount
Figure 18.5
18.2 Other Runtime Errors
A notifier appears (at the center of the display screen or at the center of the active view) whenever there is an execution interrupt due to an error in running a method. These runtime errors occur for a large number of reasons. As stated earlier, most often you will encounter an error because an object is sent a message to which it cannot respond. The label of the notifer is Message not understood: followed by the erroneous message selector. The notifier only displays the last few message-sends of the interrupted execution. You may determine that this is not enough information, either because the purpose of the interrupt was to explore further or because you do not know why the interrupt occurred. In this case, choose the yellow button command debug. The notifier is closed, and you are asked to designate a rectangular area in which a debugger will be created. The system debugger is described in Chapter 19.
384 Notification of an Execution Interrupt
Runtime errors caused by other than an incorrect message selector include: • Trying to create an instance of Character or Boolean. All Characters are defined at the time the system is created, and are immutable. Boolean is an abstract class with two subclasses, True and False, each of which has only one instance (true and false, respectively). • Trying to create instances with incorrect instance-creation messages (such as sending new to create a MappedCollection). • Trying to evaluate a BlockContext with the incorrect number of arguments. For example, if the BlockContext is of the form [ :i :j | i > j], then the message needed to evaluate it is of the form value: i value: j. A message to this BlockContext with any other number of value: keywords would be an error. • In numeric computation, attempting to divide by zero, creating a Fraction with denominator of zero, or taking the square root of a negative number. • In Collections, mismatched collection sizes for mapping operations, attempting to remove an element not in the collection, attempting to access elements of nonindexable collections using at:put:, attempting to store into an Interval or to remove elements from an Interval or an Array, using an object that is not an Integer as an index, attempting to store an object that is not a Character into a String, attempting to do a Dictionary lookup with a key or value that is not in the Dictionary, or using an index that is out of the bounds of the indexable collection. • Sending an object an inappropriate message (one to which instances of the superclass respond, but of which the subclass blocks the use), or sending an object a message that its class should have implemented but did not (the superclass implementation is probably self subclassResponsibility). • Sending control messages to objects that are not Booleans (ifTrue:ifFalse:, ifFalse:ifTrue:, ifTrue:, ifFalse:) nor BlockContexts (whileTrue:, whileFalse:).
19 Examining and Debugging Execution State 19.1 The Activation Stack 19.2 The Structure of a Debugger 19.3 The Context of a Message Receiver 19.4 The Context of an Interrupted Method 19.5 Evaluation Within the Context of an Interrupt
386 Examining and Debugging Execution State
To illustrate the use of the debugger, we will add another method to the class FinancialHistory which was used as an example in Chapters 17 and 18. The method will have an error in it that we can explore using a debugger.
19.1 The Activation Stack
Add the method for report, categorized under the instance protocol inquiries, as shown in Figure 19.1. Try it. Type the text self report in the text subview of the inspector for the FinancialHistory created as described in Chapter 18. Select the text and then choose the yellow button command print it (Figure 19.2). A notifier appears indicating that the message do: was not understood (Figure 19.3). The text displayed in the notifier indicates the last few messages sent before the interrupt occurred. The methods associated with these messages have not as yet returned their values. In conventional programming language parlance, this sequence of messages represents the activation stack that you wish to explore to understand the source of the error.
Financial History S y 519 m - U h a n g e s S y 51 e m - C ο m pile r S ys t e ΓΓΙ - R e I e a s i η g Files-Streams Files-Abstract Files-Xerox A l t o
totalbpentFor:
report "Answer a. String t h a t describes t h e current b a I a nce and again υηdο
expenditures,"
| a Stream | a.Stream - W r i t e S t r e a m on: String n e w , a. Stream next Put AII: 'Financial H i s t o r y ' ; cr, a. Stream next Put All: 'balance: ', a. Stream η e χ t Ρ υ t A11: c a. s h Ο η Η a n d; cr.
Figure 19.1
010
expenditures ρ r i η t Ο η: a. S t r e a m, taStream contents
copy cυt ρaste do it irint it can |el format spawn
387 19.1 The Activation Stack
System Browser S y s t e m - G h a. n g e s Syst em-CοmρiIer S ν s t e m - R e I e a. s i η q Files-Streams Files-Abstract Files-Xerox A l t o
BEHOBUL eχρeηdi
agaιη υηdo copy cut ρ a. s t e do it
report "Answer a. String tha.' expenditures." | a ο ΐ re am | a. Stream *• W r i t e S t r e a m on: String new, a. Stream next Put All: 'Financial H i s t o r y ' ; cr. a. Stream next Put All: 'balance: ', a.Stream nextPutAII: cashOnHand; cr, e χ ρ e η d i t υ r e s ρ r i η t Ο η: a. S t r e a. m. •t a Stream c o n t e n t s
Figure 19.2
mmxmmmmwttfmwMmm S y s t e m Β r o w s e r jjiiiiiiiiiiiiiiiiiiiiiiiiii; System-Changes System-Compiler S y s t e m - Fi e 1 e a s i η q Files-Streams Files-Abstract Files-Xerox A l t o
FinancialHistory|ii;jijii!:iii^^
S m a. 111 n t e g e r( 0 b j e c t ) > > d ο e s Ν ο t U η d e r s t a n d: W ri t e S t re a m (S t re a. m) > > η e χ t Pu t A11: Fi η a n c i a. IH i s t ο ry > > re ρ ο rt Fi η a η c i a. ΙΗ i s t ο r ν > > D ο 11 k C ο m ρ i Ι Ρ r> > e ν a 1 u a t e: i η: t ο: η η τ i fy i η g: i f Fa i I •
report "Answer a. String thai expenditures." | a.Stream | a.Stream *• WriteStrea rr on: S t r i n g r e w . a.Stream nextPutAII: 'F i r a n c i a l H i s t o r y ' ; cr, aStream nextPutAII: 'balance: '. aStream next Put All: c ashOnHand; cr, e χ ρ e η d i t υ re s ρ ri η 10 η: aStream,
Figure 19.3
000
t a S t r e a m cor tents
f
i;;| i!i: iii| |iji i;!:
388
Examining and Debugging Execution State The first message-send in the example notifier indicates that the receiver of the message was a Small Integer. There is a class name delimited by parentheses after the class name of the receiver. It denotes the class in which the message definition is specified. The example shows that the definition of the message doesNotUnderstand: is specified in Object. The second message-send indicates that the error came from sending the message nextPutAII: to an instance of WriteStream. The method associated with nextPutAII: was actually found in the description of the class Stream (a superclass of WriteStream). And the third message-send indicates that the message nextPutAII: was sent from the method associated with report that was sent to a FinancialHistory. The remaining message-sends have to do with the compilation and evaluation process, and can be ignored.
19.2 The Structure of a Debugger
Choose the yellow button command debug in the notifier (Figure 19.4). The notifier disappears and you designate a rectangular area for the debugger. The debugger is shown in Figure 19.5.
ϋϋϋϋϋ System Browserl;!; •;•;;;;;;;
. -
ι:·
ϋϋϋϋϋ S y s t e m - G ha n ge s ϋϋϋϋϋ S y s t e m - C o m p i l e r ϋϋϋϋϋ S y s t e rn - R e l e a s i n g ϋϋϋϋϋ F i l e s - S t r e a m s ϋϋϋϋϋ F i l e s - A b s t r a c t iiiiuiiii Files-Xerox A l t o l:l:;;;;l; iFSft^Jhie^iatli^^OlS:: ::;
F i n a n c i a l H i s t o r y |;ii|i iiiii iijiiiji ϋϋϋϋϋίϋϋϋϋϋϋϋί ϋϋϋϋίϋϋϋϋϋϋϋϋϋϋϋϋϋ
III.L4J.I,|.|.lJlll.l.l.llJJ.H,«il S m a 111 n t e g e r ( 0 b j e c t ) > > d ο e s Ν ο t U η d e r s t a n d: W ri t e S t re a rr (S t re a m) > > η e χ t Pu t A11: Fi η a. η c i a ΙΗ i s t ο r y > > re ρ ο r t |proceed| Fl η .=, η Γ i .=, ΙΗ i - r η f ...· > •-, Γι r, 11ESSSU Γ: η m ρ ί Ι α r :• > Q ·„• .=, 111 .=, f c · i n · r η · Γι,-, 1- Ρ |~ |~Ί,
ϋϋϋϋϋ report ;!;;;;; • expenditures." iiiiii! ϋϋϋΐ iiiiiii iiiiiii iiiiiii iiiiiii iiiiiii
Figure 19.4
ΟΙΟ!
I
| abtream | aStream - WriteStrea r" on: String rew. a Stream next Put All: 'Financial History'; cr. a Stream next Put All: 't a. la nee: ', a Stream nextPutAII: c ash On Η and; cr. expenditures print On: .s. Stream. t a Stream cor tents '
Γ ^ ' Μ Ι'
Τ· i I •
389
19.2 The Structure of a Debugger
S m a. 111 n t e g θ r ( 0 b j e c t ) > > d ο e s Ν ο ΐ U η d e r 51 a. n d: W ri t e S t re a. m (S t re a m) > > η e χ t Pu t A11: full s t a c k Fi η a η c i a IH i s t ο r y > > re ρ ο r t proceed FinancialHistory>>Dolt
Figure 19.5
010
self
The debugger presents some or all of the sequence of message-sends that occurred prior to the interrupt. It allows you to select each one in order to see the method and to determine at which point in the method the interrupt occurred. You can choose any message-send on the stack and cause evaluation to proceed from this selected point. You can also single-step through message-sends, checking the state of the variables in order to determine the source of the error. You can change the value of variables and proceed. If you evaluate expressions within the debugger view, evaluation will be carried out in the context of the currently selected message. You can also edit and recompile (accept) a method. A debugger view is made up of six subviews. You are already familiar with each of these subviews. The top two subviews are similar to the two subviews of a message-set browser; one is a menu of classes and messages, and the other is a text view in which the method associated with a selected message is displayed. The items in the class/message menu are the message-sends of the interrupted execution, identical in format to the message-sends displayed in a notifier. Each message-send displays the class of the receiver and the message selector of the message sent to the receiver. It also shows, in parentheses, the class in which the interpreter found the method for this message selector, if the implementation class is different from the class of the receiver. Selections in the first subview cause the corresponding methods to be
390 Examining and Debugging Execution State
displayed in the second subview. The methods can be edited, compiled, and installed (accepted), just as you are able to do in a browser. The bottom four subviews provide two inspectors. Information appears in these inspectors only if a class/message is selected in the top view. The first inspector allows you to explore the object that was sent the interrupted message; the second inspector allows you to explore the context of the selected message-send, that is, the temporary variables of the interrupted method. The debugger shown in Figure 19.5 illustrates the yellow button menu available when no class/message item is selected in the top subview. You can choose to ignore the problem and proceed, just as you could have done from the notifier. Or you can expand the number of class/message items in the menu. full Stack
When a debugger is first created, at most only the top nine message-sends appear. This command displays the complete stack of all the message-sends of the interrupted message-sending activity.
proceed
The debugger closes and evaluation continues just after the point of interruption. The point of interruption is a message-send that is completed with a reply that is assumed to be the value of the last expression evaluated in the method subview, or nil if no expression has been evaluated.
In order to follow the example in this chapter, do not choose a command from this menu. Instead, choose the second message-send in the top subview of the debugger (Figure 19.6a). Three things of interest happen. First, the method associated with the selected message is displayed. In the display of this method, the message that was last sent is selected in order to focus your attention at the point at which the interrupt occurred. Second, information is displayed in the menu parts of the two inspectors at the bottom of the debugger. And third, the yellow button menu in the top subview is changed. It now contains eight commands (Figure 19.6b).
391 19.2 The Structure of a Debugger
S rn a 111 η ΐ e q e r( Ο b j e c t ) > > d ο Θ S Ν Ο t U η d e r s t a n d:
WnteStreamfStream^nextPutAII F i n a n c i a l H i s t ο r y > > re ρ ο r t Fi η a η c i a ΙΗ i s t ο r y > > D ο 11
nextPutAII: aCollection "Append the elements of aCollection onto the reci •er, Ά nswer aCollection." a. C ο 11 e c 11 ο η t a C ο 11 e c t i ο η
Figure 19.6a
ooo
self nextPut:
a (J ο 11 e c t i ο ι
self c ο 11 e c t i ο η ρ Ο 5 i t i Ο Γι
read Limit
3 m a. 111 η 19 q θ r( Ο b j 9 c t ) > > d ο Θ S f'J ο t U η d e r s t a n d: full stacl· proceed a m ί S t re a m Ί > > η e χ t Pu t AII: restart FinancialHistory>>report senders F i η a η c i a ΙΗ i s t ο r y > > D ο 11 nextPutAII: aCollection "Append t h e elements of a C o l l e c t i o n ontc a C ο 11 e c t ί ο η," a C ο 11 e c r ι η η τ a C o 11 e c t i ο η
Figure 19.6b
Bio
self c ο 11 e c t i ο η ροsitiοη re a d Limit
implement or: messaqes step seηd
self next Put;
acollectioi
392 Examining and Debugging Execution State Senders
As in a class browser, creates a message-set browser on all methods that include an expression in which the currently selected message is sent. If no such methods exist, prints Nobody in the System Transcript (if the System Transcript is open on the screen).
implementors
As in a class browser, creates a message-set browser on all methods that implement the currently selected message. If no such methods exist, prints Nobody in the System Transcript (if the System Transcript is open on the screen).
messages
As in a class browser, creates a menu of all messages sent in the method associated with the currently selected message. Choosing one of these menu items creates a messageset browser on all of its implementors.
Step
Evaluates the next message to be sent in the selected method (see the full explanation of step in Chapter 21).
Send
This command is a refinement of the command Step. If the next message to be sent were evaluated, it would consist of a sequence of messages. The command send is a request to enter that next message at the top of the activation stack and be ready to evaluate the next message in its method (see the full explanation of send in Chapter 21).
full Stack
When a debugger is first created, at most only the top nine message-sends appear. This command displays the complete stack of all the message-sends of the interrupted message-sending activity.
restart
The debugger closes and evaluation starts from the beginning of the currently selected method.
proceed
The debugger closes and evaluation continues just after the point of interruption, assuming that the value of the expression forced to completion is the value of the last expression evaluated in the method text subview, or nil if no expression has been evaluated.
As described, when you make a choice in the debugger top subview, the corresponding method displays in the adjacent subview. A part of the method text is selected. This is the place at which evaluation will proceed next. Because some implementations of the Smalltalk-80 system might be too slow to allow for this selection determination, you can consider removing this selection capability from your system.
Q Viewing and Editing Methods You can edit and recompile (accept) a method that is displayed in the debugger. You do this in the same way as you edit and recompile in a class browser or in a message-set browser. All the functonality accessible from the text view of these
393 19.2 The Structure of a Debugger
kinds of browsers is available from the text view of the debugger, including the ability to explain tokens. The yellow button menu of the debugger text view, identical to that of the browser text view, is shown in Figure 19.7. If you recompile a method, that method becomes the top of the stack of message-sends. It is not necessary to return to the class browser, retrieve the method, and make the change. In the Smalltalk-80 system, wherever you can access a method (in any of the class browsers, message-set browsers, or the debugger), you can edit and recompile it. Note: suppose that the method you edit is inside a block, that is, the message-send item in the top view begins with [ ]. When you recompile, then the method containing the block becomes the top of the stack of message-sends. If the stack of message-sends contains multiple instances of a message-send, that is, a recursion exists, then you ought to make any edits to the method reference that is closest to the bottom of the stack. Suppose instead that you edit a method higher in the stack. All instances of that method lower in the stack will still refer to the old version of the method. The items in the top view change to reflect this fact; specifically, the message name changes to Dolt.
b m a. 111 η t e g 9 r( Ο b j e c t ) > > d ο e s Ν ο t U η d erst a n d: Fi η a η c i a ΙΗ i s t ο r y > > r e ρ ο r t Fi η a. n c i a IH i s t ο r y > > Dolt
nextPutAII: aCollection
agaιη "Append t h e elements of a C o l l e c t i o n onto t h e r, undo aCollection."
copy cut
aCollection ι a C ο II e c t i ο η
Figure 19.7
010
self c ο 11 e c t i ο η
position re ad Limit
ρaste
self nextPut:
doit print it accept c a n c e1 format spawn explain
a C ο 11 e c ΐ ι ο ι
Answer
394 Examining and Debugging Execution State
19.3 The Context of a Message Receiver
The left inspector of the debugger (bottom left pair of subviews) gives you access to the message receiver of the message selected in the top view of the debugger. The context of this message receiver is its state at the time the message was sent. In Figure 19.8a, WriteStream(Stream) > > nextPutAII: is selected; in the inspector, self refers to the instance of WriteStream. A WriteStream has four instance variables; collection refers to the String in which the description of the Financial History is being collected. As shown in Figure 19.8b, collection was ' FinancialHistory Balance:' at the point of interruption. This indicates that the next information, the cash on hand, failed to enter the WriteStream. Inspecting the variables can give you information about the state of information in the system at the moment the method was run. You can change the values of the variables, either by 1. evaluating expressions in the text part of the inspector that consist of messages to the object self;
b m a 111 n t e q e r ί Ο b ι e c t Ϊ > > d ο e S Ν Ο t υ η d e r s t a. n d Fi η a η c ι a. ΙΗ ι s t ο r y > > re ρ ο f t FiriaricialHistory>>Dult nextPutAII: aCollection " A p p e n d t h e e l e m e n t ί of a.Col l e c t i o n o n t o t h e r e c e i v e r . aCollectiori." a. u ο 11 e c 11 ο do: η [:v I self nextPut: v] t a. C ο 11 e c ΐ i ο η
Figure 19.8a
100 000
Write Stream ρ O 5111 η Γι
read Limit
a U ο 11 e c ΐ ι ο ι
Answer
395
19.4 The Context of an Interrupted Method
bmalllnteger(Object)>>doesP'Jot U n d e r s t a n d ; FinancialHisto r y > > re ρ ο r t Fi η a η c i a ΙΗ i s t ο r y > > D ο 11 nextPutAII: aCollection
"Append the elements of a.Collection onto the receiver. Answer aCollection."
Figure 19.8b
100 000
'Financial History balance: '
a C ο 11 e c 11 ο ι
2. evaluating assignments to the instance variables; or 3. selecting a variable, typing a new value in the text part, and then choosing the yellow button command accept. Then you can continue evaluation from the point of the selected message, having changed these values.
19.4 The Context of an Interrupted Method
The right inspector of the debugger gives you access to the state of the method associated with the selected message, when that method was first invoked. The currently selected method shown in Figure 19.9 has one message argument, aCollection, and a block argument, v. These two names are shown in the inspector. Choose one to see its current value. Notice that aCollection is 225, which is a Smalllnteger, not a Collection; hence the error.
396 Examining and Debugging Execution State
a 111 n t e q e r ί Ο b ι e c t ϊ > > d ο e s Ν ο t U η d e r s t a n d: Fi η a n c i a IH i s t ο r y > > re ρ ο r t F i η a η c i a ΙΗ i 51 ο r y > > D ο 11 nextPutAII: aCollection "Append t h e element.-, of a C o l l e c t i o n o n t o t h e receiver, aCollection,"
Answer
a. C ο 11 e c t i ο η t a Collect ion
Figure 19.9
100 000
self
'Financial Η is tor; balance: '
p Ο 31110 Γι
re ad Limit
19.5 Evaluation Within the Context of an Interrupt
Choose the next message-send, the message report to a Financial History. The method text selected indicates that the error occurred when cashOnHand was to be appended to the WriteStream, aStream (Figure 19.10a). Select the text cashOnHand in the method, and choose the yellow button command print it (Figure 19.10b). The value is 225, as we expected given the result in Figure 19.9 (Figure 19.10c). When you evaluate an expression that appears in the debugger method text, the evaluation takes place in the context of the interrupt, i.e., using the values of the receiver and the method at the time the selected method was interrupted. If you choose to proceed at this point by choosing the yellow button command proceed in the debugger top view, execution would proceed as though the value of the interrupted message send in the current method were the value of the last expression you evaluated, in this case, 225 (rather than the contents of the WriteStream as desired). If you proceed from a method without evaluating expressions, the assumed value of the method is nil. A String representation for cashOnHand should be the argument to nextPutAII:. This representation is obtained by sending cashOnHand the message printString. (Note that the result of sending the message printString to any object is a String that describes the object.)
397 19.5 Evaluation Within the Context of an Interrupt
n a n c i a l H i s t o r y li; S m a 111 η ΐ e q e r ( 0 b j e c t ) > > d ο e s Ν ο t U η d e r st a n d: W ri t e S t re a rn ί S t re a rn Ϊ > > η e χ t Pu t A11: Fi η a ή c i a ΙΗ i 51 ο r ν > > D ο 11 report "Answer a. String t h a t describes the current balance and expenditures." | a Stream | a. Stream *- Writes t re am on: String new, aStream next Put All: 'Financial History'; cr, a Stream next Put All: 'balance: '. a S t r e a rn Ι^^^ΜΜΗΙΠΞΠΙ^ΕΕΗΜΟΗΪΚΙ^ΒΙ, ιΐ: Γ , e χ ρ e η d i t u r e s ρ r i η t Ο η: a S t r e a rn, τ a S t re a m c ο η t e η t s
Figure 19.10a
000
self cashΟηΗa expert ditur
inancialHi s t o r y S rn a 111 η t e g e r( Ο b j e c t ) > > d ο e s Ν ο t U η d e rs t a n d: W ή t e S t re a m (S t re a rn) > > η e χ t Pu t A11: Fi η a η c i a ΙΗ i s t ο r y > > D ο 11 report " A n s w e r a String t h a t describes t h e c u r r e n t balance and agaιη undo copy | a.btrearn | cut a S t r e a m *- W r i t e S t r e a m on: String new, ρaste aStrea.m n e x t Put All: 'Financial H i s t o r y ' ; cr, do it
expenditures,"
a S t r e a m nextPutAII: 'balance: ', accapt canceI ο rm a t sρaw η eχρIaiη
expenditures p r i n t On: a S t r e a m . t aStream
Figure 19.10b
010
self cashOnHa expenditur
contents
a s t r earn
398 Kxamining and Debugging Execution State
b rn a 111 n t e g e r ( 0 b j e c t ) ••• > d ο e s Ν ο t U η d e r s t a n d: ,'V ri ΐ e S t re a. m ί S ΐ re a rn Ϊ > > η e χ t Pu t A11: FinancialHistory>>report F i n a n e i a I H i s t o r y >>Dolt report "Answer a String t h a t describes the current balan ce and expenditures." | a. Stream | a Stream *· WriteStream on: String new. a.S tream next Put All: 'Financial History'; cr. a Stream next Put All: 'balance: ', expenditures ρ r i η 10 η: a S t r e a m. ta. Stream contents
Figure 19.10c
000
elf a sh0ηΗa ι · ρ e η ι J i 11 J r
a a t re am
b m a 111 η t e q e r (Ο b j e c t ) > > d ο e s Ν ο ΐ U η d e r s t a n d: W ri ΐ e S t re a m ί S t re a m ϊ > > η e χ t Pu t A11: F i η a n c i a. IH i s ΐ ο r y > > D ο 11 report " A n s w e r a. String t h a t describes t h e c u r r e n t balance e χ ρ e η d i t υ re s," | a.S t r e a m | a S t r e a m *• W r i t e s t r e a m on: String new, a S t r e a m next Put All: 'Financial H i s t o r y ' ; cr, a.S t r e a m next Put All: ' b a l a n c e : ', a. S ΐ r e a m η e χ ΐ Ρ υ ΐ Α11: c a s h Ο η Η a η d ρ r i η t S t r i η g; cr, expenditures print On: a.S t r e a m . t a S t r e a rn c ο η t e η t s
Figure 19.11
010
self cashC η Η a ex per ditur
agaιη υηdo copy
cut ρ 3. s t e do it print it carfltei format sρawη e χ ρ I a. i η
399 19.5 Evaluation Within the Context of an Interrupt
Make the correction and choose the yellow button command accept (Figure 19.11). Notice that the method is now changed. It is placed at the top of the stack and selected in the debugger top view (Figure 19.12). Messages that had been initiated from the original form of this method have been terminated on the assumption that the change in the method may have changed the desired sequence of message sends. Choose the yellow button command restart in the top view. The FinancialHistory is re-sent the message report, and the successful result appears in the workspace (Figure 19.13). The result could be prettier in that the Dictionary expenditures needs better formatting. We will return to this problem in Chapter 20. (Note that your browser probably had report selected at the time you were using the debugger to change the method. The updated version of the method for report is obtained by reselecting report in the browser message-selector subview.)
Firi3.ncia.lHistory>:>Dolt C ο m pile r> > e ν a Ι υ a t e: i η: t ο: η ο t ί f y i η g: i f Fa. i I: senders C ο d e C ο η t r ο 11 e r > > d ο 11 implement o r C ο d e C ο η t ro 11 Θ r> > ρ ri n 111 m e s s a q« step report seηd :e a n d "Answer a. String t h a t describes the expenditure."." | a. S t r e a m | a S t r e a m n e x t Put AII: ' F i n a n c i a l H i s t o r y ' ; cr, a. S t r e a m n e x t P u t AII: ' b a l a n c e : ', a S t r e a . m η e χ t Ρ u ΐ A11: c a s h Ο η Η a n d ρ r i η ΐ S t r i η q; c r, e x p e n d i t u r e s ρ r i η t Ο η: a. Ξ t r e a m. τ a S t r e a. rn c ο η t e η t s
Figure 19.12
010
self ca.sl- On Η a expe η d i 11 J r
400 Examining and Debugging Execution State
1
self report^^^^^^^^^^M^B^
self expendi
•y9nBBEH5nnEJumraBSK9|
!
i Figure 19.13
Kinds of Execution Interrupts
20.1 Breakpoints 20.2 User Interrupts 20.3 Running Out of Space 20.4 Recursion in the System Error Handler
000
J
402 Kinds of Execution Interrupts
In Chapters 18 and 19, you have seen that execution interrupts can occur because of unanticipated runtime errors. It is possible to interrupt the execution of a message-send in order to examine the state of an object at the time it receives a message. There are three ways in which an interrupt can occur. 1. You set a breakpoint in a method. 2. You type the "control" and "c" keys (Ctrl c) at the same time. 3. An anticipated error condition occurs while a method is running. In the third case, the method includes a test for a possible error condition and, if found, evaluates an expression of the form self error: messageString
A notifier appears whose label is messageString. The label should be sufficient information to explain to the user why the error occurred. You can evaluate the expression Smalltalk browseAIICallsOn: #error: to see examples in the system where these tests occur.
20.1 Breakpoints
A breakpoint is set in a method by including an expression that creates a notifier. The two possible messages you can use are self halt and self halt: messageString
In each case, a notifier appears so that you can choose to proceed or choose to create a debugger. In the first case, the label of the notifier is Halt encountered
In the second case, the label is the argument messageString. An example of inserting a breakpoint is presented next. The example uses the description of class FinancialHistory presented in previous chapters. In the method associated with report in the class FinancialHistory, insert the expression self halt just before the point at which the Dictionary expenditures is added to the WriteStream (Figure 20.1). Choose the yellow button command accept.
403 20.1 Breakpoints FinancialHistor System-Changes I S y s t e m - C ο m ρ i I e r lljiiismJMKiKMWM y s t e m - Fi e I e a s i η g Files-Streams Files-Abstract
totalbpentFor:
Files-Xerox Alto report "Answer a String t h a t describes the current bale ηc a g a ι η υηdο expenditures," | aStream | aStream «- VVriteStream on: String new. aStream next Put AII: 'Financial History'; cr. aStream next Put A, II: 'balance: ', aStream next Put All: cashOnHand printString; cr,
Figure 20.1
010
self h a l t x e χ ρ e η d i t u r e s ρ r ί η t Ο η: a S t r e a m,
copy cut paste doit print it cancel format sρawη eχρIaiη
ta.Stream contents
In the inspector for the FinancialHistory, type and select the expression self report (Figure 20.2). Choose the yellow button command print it.
System Browser! System-Changes System-Compiler System-Releasing Files-Streams Files-Abstract Files-Xerox Alto
report "Answer a String thai expenditures." | aStream | aStream •*- WriteStream on: String new. aStream nextPut.AII: 'Financial History'; cr. β Stream next Put All: 'balance: '. aStream next Put AII: cashOnHand printString; cr,
Figure 20.2
010
self halt. e χ penditures ρ r i η t Ο η: a S ΐ r e a. m, t a S t re a m c ο η t e η t s
404 Kinds of Execution Interrupts
A notifier appears (Figure 20.3). Choose the yellow button command debug. Designate the rectangular area for the debugger and then choose the second message-send (FinancialHistory> > report) (Figure 20.4). The message halt is selected in the method text in the debugger. In the inspector for the message receiver, select the instance variable name expenditures and choose the yellow button command inspect (Figure 20.5). hna.ncia.lHistoryj||||||||||i||||i||||;|
S y s t e m Browser!::: S y 51 e m - C h a. n q e s bvstprn Compiler S y s t e rn - Fi e 1 e a. s i η q
=:olf ronnrt
\mmm&
iijilijii;
FIIP 5- S t r e a m s
Files-Abstract Files-.Her ox Alto
* J Fin a n c i a IHi s t οry (0b j Q c t) >>h a.11 Fi η a η c i a ΙΗi s t ο ry > > rep ο rt Fi η a. n c i a. IH i s t ο ry > > D ο Ι ΐ Γ: η rn ρ i Ι Ρ r > > e ν a Ι υ a t e :l^i: t ο; η ο t i f ν i η q: i f F.=t i 1: C ο d e C ο η t ro 11 e r) > d ο 11
report "Answer a String t h a expenditures," | a.Stream | a Stream *• VVriteStream on: String new, a.Stream nextPutAII: 'Financial History'; cr. a Stream nextPutAII: Ί a.lance: ', a.Stream nextPutAII: c ashOnHand print String; cr,
Figure 20.3
000
self halt, e χ ρ e η d i t υ r e s ρ r i η 10 η:=i Sf t a. S t r e a rn c ο r t e η t s •:'-':'·':'':'•':'•':'•
:'•:'•':
fpa rn,
1
405 20.1 Breakpoints
report "Answer a. String t h a t describes the current balance and e χ ρ e η d i t υ re s," | a. Stream | a.Stream *• WriteStream on: String new, a.Stream nextPutAII: 'Financial History'; cr. a Stream nextPutAII: 'balance: '. a Stream next Put All; cashOnHand print String; cr.
Figure 20.4
|00 000
expenditure s ρ r i η t Ο η: a S t r e a m, t a. S t r e a m c ο η ΐ e η t s self cashOnHar eχρeηditυr
abtream
Fi r. a n •-• i a I M i ••- 1- η
FinancialHistory(Object)>>halt FinancialHistory>>Dolt report "Answer a String that describes the current balance and expenditures." | a Stream | a.Stream *• WriteStrearn on: String new. a Stream nextPutAII: 'Financial History'; cr, a.Stream nextPutAII: 'balance: '. a Stream next Put All: cashOnHand print String; cr.
self J2Q. e χ ρ e η d i t υ r e s ρ r i η t Ο η: a S t r e a m. t a S t re a m c ο η t e η t s
Figure 20.5
Oio
icΐionary ( ' r e n t ' - ) 100 food'->5O 'trip'-;·75 )
a S ΐ re a m
406 Kinds of Execution Interrupts Designate the rectangular area for the inspector for the Dictionary expenditures. You can use this inspector to explore ways in which to print the keys and values of the Dictionary. In the text subview of the inspector, type, select, and evaluate the expression self keys (do the evaluation by choosing the yellow button command print it). The result is a Set of three elements, each of which is a String (Figure 20.6). Halt encountered.!
I i Γ Ρ Ι η a r. •-!.=• i M i - r •-.>-••••
Fi η a n c i a IH i s ΐ ο ry ( 0 b j e c t i > > hi a 11 Fi η a n c i a IH i 510 r ν > > D 011
report "Answer a String that describes the current balance and expenditure;·," I a stream | a.Stream *- WriteStn a S t r e a m η e χ t Ρ υ t A11: a S t r e am η extΡυ t A11: a S t re a rn η e χ t Pu t All: self halt. e χ ρ e η d i t u re s ρ ri η t Ο r taStream contents
Figure 20.6
000
Dictionary lf 'food'->50 a shΟηΗar
You can then try different methods for printing. An example method is shown in the inspector text subview in Figure 20.7a. The expressions format the keys and values in two columns using messages cr and tab; the text is printed in the System Transcript (Transcript) as shown in Figure 20.7b. (For this example to work, you should make certain that the System Transcript is visible on the display screen.) Close the inspector for expenditures. In the method for report, replace the printing expression for expenditures with a version of the "practice" print expressions. Make the change shown in Figure 20.8, and choose the yellow button command accept. If you then retry evaluating self report in the inspector for the FinancialHistory, a better formatted result is displayed (remember to choose the yellow button command print it so that you can see the result) (Figure 20.9). Close the debugger.
407 20.1 Breakpoints Halt encountered stem Transcript
that describes the current balance and
aStrearn *• W n t e S t n aStrearn next Put AII: aStream next Put All: aStream next Put All: self halt, e χ ρ e η d i t u r e s ρ r ί η 10 r taStrearn contents
Figure 20.7a
DiO
Dictionary Γ self ' f o o d ' - ) 5 0 'r cashOnHan
Halt encountered, System Transcript 'rent' 10U 'food' 50 'trip' 75 t h a t describes the current balance and
a Stream *• WriteStr aStream next Put All: aStrearn next Put.· a. Stream next Put,· self halt, e 'ipenditures print Or taStream contents
Figure 20.7b
Rio
Dictionary ( c a s h Ο η Η a r "food'->50 Ί self
408 Kinds of Execution Interrupts
Fi η a η c i a. ΙΗ i s t ο ry (Ο b j e c t ) > > h a 11 Fi η a η c i a ΙΗ i s t ο r y > ) D ο 11 " A n s w e r a String t h a t describes t h e c u r r e n t balance and expenditures." | a Stream | aStrearn *• WriteStreann on: String n e w . aStrearn n e x t Put All: 'Financial H i s t o r y ' ; cr. a S t r e a m n e x t Put All: ' b a l a n c e : '. a S t r e a m n e x t Put A11: cashOnHand print S t r i n g ; cr, expenditures keys do: [ :eachKey | a S t r e a m n e x t Put All: each Key; t a b . a S t r e a m n e x t Put All: (expenditures a t : each Key) print S t r i n g ; c *a S t r e a m c o n t e n t s
Figure 20.8
010
self cashOnHar
dictionary ('rent'-) 100 'food'->50 'trip'->75 )
aStream
Halt e n c o u n t e r e d , Fi η a η c i a ΙΗ i s t ο r y > > D ο 11 C ο rn ρ i I e r > > e ν a I u a t e: i η: t ο: η ο t Co d eC on t roller);· dolt " A n s w e r a String t h a t expenditures." | aStream | a Stream *- WriteStrearr a S t r e a m next Put All: 'Fii a S t r e a m nextPutAII: 'be a S t r e a m nextPutAII: c a expenditures keys do: [ :eachKey a S t r e a m nextPutAII: each Key; t a b , a S t r e a m nextPutAII: (expenditures a t : e a c h K e y ) p r i n t S t r i n g ; c r ] , t a S t re a rn c ο η t e η t s
Figure 20.9
000
self cashOnHar
D i c t i ο η a ry ( ' r e n t ' - > 10 Ο aStream 'food'-)5O 'trip'-)75 ) eachKey
409 20.3 R u n n i n g O u t of Space Be careful in inserting breakpoints in the system classes. Unless you understand the flow of message-sends, you might find yourself recursively creating notifiers if the code that creates the notifier, or that creates any of the views on the screen that you might select, uses the method you are interrupting.
20.2 User Interrupts
You can press the "control" key and the "c" key (Ctrl c) at the same time in order to interrupt immediately the execution of any code. A notifier appears whose label is User Interrupt
Choose the yellow button command proceed to continue the process. Typing Ctrl c is a way to interrupt a successfully running process that you wish to explore, to find out about and to possibly change the part of the system that supports the running process. Try an example. Open a workspace as the active view. With the cursor inside the workspace, type Ctrl c (Figure 20.10a). A notifier appears (Figure 20.10b). (The sequence you see in your notifier might be different than the one in the example figures due to the somewhat arbitrary timing of your typing Ctrl c.) The sequence of message-sends indicates that a SharedQueue was interrupted in its evaluation of peek. This message was sent from the method keyboard Peek to an InputState, which in turn was sent from primKbdPeek to an InputSensor. The message keyboardPressed tests to see if the user is pressing a key on the keyboard. It was sent from a StringHolderController; a StringHolderController provides the user interface to a StringHolder which is the implementation class for a workspace. Hence this is a way for you to find out which classes are involved in the implementation of the user interface. If you now open a debugger you can explore the StringHolderController and examine its instance variables and methods to learn more about the user interface objects.
20.3 Running Out of Space
A notifier appears on the screen if the system starts running out of memory space, either because you have created more objects than the system can handle, or because the objects you have created take up more space than is available. The label of this notifier is Space is Low
You should close the low space notification (it might be hanging onto a very large activation stack if the cause of the low space was infinite re-
410 Kinds of Execution Interrupts
System Browser S y s t e rn - < J h a. n g e s S y s t e rn - C ο m ρ i I e r 're ι S >• s t e rn - R e I e a ; i η g 7 f0< Files-Streams ' t r i File s-,Abst ran t Files--ero· Alto
F in a no ialHi story I
-•- | < : >••-•>-••- >-f ' F i r , =.!-..- I a I Ui.r ».-..·,.
transaction;
j
totalSpentFor:
private
ial Tods report \'
describes t h e current balance a n d
ng new, listory'; cr, d printString; cr,
Figure 20.10a
000 S y s t e m Β ro w s e r j
'fOl
'tri
t e rn - C h a n g e s t e rn - C ο rn ρ i I e r S y stt ee rn - Fi e I e a. s i η g s-Streams
Financia IHistory _ _ ] ..,.,„ ..,.,_,.,
?c;
transaction totalSpentFor: private
b h a. r e d Q. u e υ e > > ρ e e k Ι η ρ u t S t a. t e > > k e y b ο a r d Ρ e e k Ι η ρ υ t S e η s ο r > > ρ r i rn Κ b d Ρ e e \ • ^ Wor Ι η ρ u t S e ri s ο r > > k e y b ο a r d Ρ r e s s e d * S t r i η g Η ο I cJ e r C ο η t r ο 11 e r (Ρ a. r a. g r a. ρ h Ε d i t ο r) > > ρ r ο c e s s Κ e y b ο a. r d re
ng n e w , l i s t o r y ' j cr, d printString; cr,
Figure 20.10b
000
J
411 20.3 Running Out of Space
cursion). The low space might be due to an error in your code, such as infinite recursion, gobbling up space. Otherwise, the problem might be harder to trace, such as cyclic pointers; or the problem could be that your application needs more than the available space. In any case, protect yourself by filing out your work (as explained in Chapters 22 or 23) so that your work can be filed back into a new system image. Making a snapshot will not help you since you will simply be saving a system image that has insufficient space. If your application needs more than the space available in the initial system image, you might consider deleting other applications (sets of classes) that you do not require. You can use the system tracer to create a "clean image" (as described in Section 23.4). At the time that the low storage notification appears, you ought to have enough time (space) in which to save your work before the system crashes. A second warning will appear if you ignore the first and continue to use the system. At this point, you will probably not have time to save your work before the system crashes. If you want to monitor your space utilization, the System Workspace includes three expressions that you can evaluate to check on the actual space used, and to check on the number of object pointers used. Smalltalk oopsLeft Smalltalk coreLeft Smalltalk core
Amount of remaining space for object. Number of words of memory remaining. Number of words of memory currently being used. (This computation typically takes a long time.)
The result of Smalltalk core plus the result of Smalltalk coreLeft is less than the total amount of memory available to the system. The difference is the amount of space taken up by the Smalltalk-80 interpreter and resident tables of data for the interpreter.
20.4 Recursion in the System Error Handler
When the system error handling mechanism results in a recursion calling on the messages error: or halt or halt:, then the system is not able to handle the usual user interface control. Instead, a message appears in the System Transcript (if it is open on the screen): *'System Error Handling Failed**
followed by the error message followed by the last three message-sends indicating the recursive call that caused the failure, and then followed by **type < s > for more stack; anything else restarts the scheduler**
412 Kinds of Execution Interrupts
You have two choices. You can type the letter s on the keyboard to see some more of the activation stack (typically more indication of the recursive call), or you can type anything else in order to try to return to the usual user interface, notably to a browser to correct the problem. An example showing the appearance of the System Transcript is given in Figure 20.11. You can test this facility by evaluating the expression ErrorRecursion «- true and then creating an error. ErrorRecursion is a class variable of Object and is therefore globally accessible. It is used to test for recursive calls on the primitive routines for the error handler. For example, evaluate nil+ 3 If you type any key, other than s, to get the system to respond again (reschedule the ControlManager), the value of ErrorRecursion is automatically set to false. If the System Transcript is not open on the screen, the problem still exists but you can not see the comment about the failure. Your system will appear to be "dead." In such cases, type any key other than s and see if you can get the system to respond again. Whenever the System Transcript is not open, you take a chance on losing feedback about an error.
System Transccript|| **System Error Handling Failed** Message not understood: + U η d e f i η e d Ο b j e c t > > D ο 11 C ο m pile r> > e ν a I u a t e: i η: t ο: η ο t i f y i η g: i f F a i I: S t ri η g Η ο I d e rC ο η t ro 11 e r> > d ο 11 * * t y p e <s> f o r more s t a c k j a n y t h i n g else r e s t a r t s s c h e d u l e r * *
Figure 20.11
413 20.4 Recursion in the System Error Handler It is most likely that the reason the error handler failed is that you have modified incorrectly some critical part of the user interface. Your system is probably dead. One last resort that you can try is to type Ctrl shift c (all three keys at the same time, but you should press the Ctrl and shift keys first and then, while holding them down, press c). This puts you into a preemptive, teletypewriter-like interface in which you can type one expression and then evaluate it by typing the "escape" key. An image of this interface is shown in Figure 20.12. Editing in this interface is done using the "backspace" key. Only two lines are available, so if you type an expression on the second line, then the result will appear on the first line. If your user interface changes were conditional on some global flag, you can reset the flag and hope for the best. (If you are knowledgeable enough about the system, you can try to redefine the method causing the problem by evaluating the appropriate compile message to the class.) If Ctrl shift c does not work, then most likely the input/output handler is locked up. There is nothing you can do except start over with a new image, and turn to Chapter 23's section on crash recovery.
* * S y s t e m Error Handling Failed** Message n o t u n d e r s t o o d : + Undefined Ο b j e c t > > D ο 11 C ο rn pile r> > e ν a I u a t e: i η: t ο: η ο t i f y i η g: i f Fa i I: S t ri η g Η ο I d e rC ο η t ro 11 e r> > d ο 11 * * t y p e <s> for more s t a c k ; a n y t h i n g else r e s t a r t s s c h e d u l e r * *
WorKspacel ErrorRecursion *• t r u e .
Figure 20.12
[000
I Single-stepping Through an Execution
416 Single-stepping Through an Execution Two commands in the yellow button menu of the debugger top view, step and send, make it possible to step through the execution of a method, one message-send at a time, and observe the behavior of the message receivers. The method associated with the example for the system class Pen provides a sequence of messages that create graphical feedback so that you can observe the results as you step through the execution. In a system browser, find the method for example in the class protocol of Pen. Insert a breakpoint, self halt, at the beginning of the method, after the temporary variable declaration. Choose the yellow button command accept. The browser selections and the change to the method are shown in Figure 21.1.
Collections-Streal Collect ions-Supp G r a ρ h ι c s - D15 ρ I a y I Q.u a d re. η q I e Graphics-Paths Graphics-Views Graphics-Editor; Graphics-Suppcirt|jn5t
example "Draws a. spiral in qray with a pen that \i bic self halt. bic - Pen new, bic mask: Form gray, bic defaultNib: 4. bic combinationFiule: Form under, to: 50 do: [:i | bic go: i:+:4. bic turn: 8 9 ] 'Pen example"
Figure 21.1 Now select the text Pen example at the end of the method and choose the yellow button command do it. A notifier appears. In it, select the yellow button command debug (Figure 21.2). Designate a fairly large rectangular area for the debugger. Then choose the second messagesend; the first one is just an indicator for the message halt (Figure 21.3). Notice that the message halt is shown as the text selection in the second subview of the debugger. This selection is the next message that will be completed if you proceed (choose the yellow button command proceed), or if you choose the yellow button command step in the debugger top view.
417 Single-stepping Through an Execution
System Browser I C ο 11 e c t i ο η s - S t re a. Collect ions-Suppc Point G r a. ρ h i c s - D i s ρ I a yO.uadrangle Rectangle Graphics-Paths Graphics-views Graphic s - E d i t o H Graphic s - S u p p o i
ι η s t a n c e c re a 11 ο η
Pe η c lass (Ο bj e c t ) > > halt " D r a w s a s| Pen class>>example U η d e f i η e d Ο b j e c t > > D ο 11
example
Figure 21.2
,v i d e,
C ο m pile r> > e ν a. I u a t e: i η; t ο: η ο I p r o c e e d f * ί' •' Co deCont roller >>dolt self h a l t bic - Pen n* bic mask: Form g r a y , bic d e f a u l t N i b : 4, bic combine.tionRule; Form under, 1 t o : 5 0 do: [:i | bic go: i*4, bic t u r n : 8 9 ] "Pen example"
BIO i
Pen class(Object)>>halt UndefinedObject>>Dolt
^
example " D r a w s a. spiral in g r a y w i t h a. pen t h a t is 4 pixels wide,"
1 bic | self QQQ. bic *- Pen new. bic mask: Form g r a y , bic d e f a u l t N i b : 4, bic combination Rule: Form under, 1 t o : 5 0 do: [:i | bic go: i :+: 4. bic t u r n : 8 9 ]
Figure 21.3
100 000
"Pen example" A
self superclass methοdDic
bic I
A
418 Single-stepping Through an Execution
If you choose the yellow button command send, nothing will happen. Generally, when you have not selected the method at the top of the activation stack, then the first thing to do is to choose the yellow button command step. This will complete all the message-sends above the current selection. Choose the yellow button command step (Figure 21.4). full 5tack proceed re i t art senders imp lament or m e s 5 a. g e s
Halt QncountQrQd. Pen c I a. 5 s (Ο b j e c t ) > > h a. 11 UndefinedObiect>>Dolt
s end! example "Draws a spiral in g r a y w i t h a pen t h a t is 4 pixels wide. | blC
self bic *- Pen new, bic mask: Form gray, bic defaultNib: 4. bic combinationRule: Form under, 1 to: 50 do: [;j | bic go: i + 4, bic turn: 8 9 ] "Pen example"
Figure 21.4
010
self superclass methodDic
bic
The selected message-send goes to the top of the stack and the text selection is now new (Figure 21.5). That is, the message halt was completed and execution advanced to the next message. The text selection visually shows you what send or step will do if one of them is chosen. 1. The command step does a complete message-send. If you now choose step, new will be sent to Pen and the entire method associated with new to Pen will be evaluated. Assignments are quickly passed over, so in this case, the assignment to the temporary variable bic will also take place. 2. The command send will invoke the method for the message selected, in this case, new. The message-send new to Pen will become the first message-send in the top subview of the debugger. The text selection should indicate the next message-send, the first message that is not an assignment. All assignments of the form variable <- variable or variable <- constant, up to the point indicated by the text selection, will be carried out immediately.
419 Single-stepping Through an Execution
UndefinedObject>>unboundMethod Compiler>>evaluate:in:to:notifying:ifFail: CodeController»dolt example "Draws a spiral in gray with a pon that is 4 pixels wide. | bic | self halt.
Figure 21.5
100 000
bic rna.sk: Form gray. bic defaultNib: 4. bic com bin a. tionRule: Form under, 1 to: 50 do; [:i j bic go: i*4, bic turn: 8 9 ] "Pen example" self
bic
s u ρ e re I a s s m e t h o d Die
Assuming your situation is as shown in Figure 21.5, choose the yellow button command send. The message-send Pen class > > new is entered at the top of the activation stack and displayed in the debugger (Figure 21.6). Malt encDuntered.
^ ^ ^ ^ ^ ^ ^
Pen class • -e · ample U η d e fi η e d 0 bj e c t > > u η b ο υ η d Μ e t h ο d C ο m ρ i 1 e r > > e ν a Ι υ a t e: i η: t d: η o t i f y i η q: i f Fa ί 1:
k »
new | quill quill *• super ^ ^ Q . quill destForrn: Display. quill frame: Display bound ing Box. quill sourceOriqin: Ο(>ΙίΟ, quill mask: Form black, quill defaultNib: 1. quill combine.tionRule: Form paint. quill down,
Figure 21.6
100 000
nnill mrfh.
self method Die
A
quill
A
420 Single-stepping Through an Execution
The first message-send, new to super, is selected. The method that is displayed is a sequence of initialization messages to the variable quill. The right inspector of the debugger shows the temporary variable name quill in its menu; choose quill (Figure 21.7). You can now observe the initial change in the value of quill from nil to a Pen. In the top view, choose the yellow button command step and notice that the value of quill is now an instance of Pen (Figure 21.8). If you wish to see subsequent changes in the instance variables of quill, you will have to inspect quill and rechoose each variable as you step through the method. If you just use the command step several times, you will eventually reach a point where the return expression, Τ quill, is selected (Figure 21.9). If you choose send now, nothing will happen. This last message is an action that completes the method; you must choose step in order to complete a method.
cIass>>eχamρIe U η d Θ f ί η e d Ο b j Θ C t > > u η b ο υ η d Γνΐ e t h ο d C ο m pile r> > e ν a luate:in:to: η ο t if y i ng: i fFa.il F'Q η
quill quill quill quill
d e s t F ο r rn; D ί s ρ I a y. frame: Display boundingBox, sourceOrigin: 0@0, mask: Form black.
quill quill quill quill
d e f a u l t N i b : 1. cornbinationRule: Form p a i n t , down, home.
iinill north.
self superclass me thod Did
Figure 21.7
nil
121
Single-stepping Through an Execution
Pen class>>example U η d e fi η e d 0 bj e c t > > u η b ο u η d Μ e t h ο d C ο m pile r> > e ν a I u a t e: i η: t ο: η ο t i f y i η g: i f Fa i I:
I quiii ι quill *- super new, quill quill quill quill
frame: Display boundingBox. sourceOrigin: CKS'ij, mask: Form black, defaultNib: 1,
quill combine.tionFiule: Form paint. quill down, quill home,
Figure 21.8
U η d e fi η e d Ο bj e c t > > υ η b ο υ η d Μ e t h ο c Compiler»evaluate:in:to:notifying:ifFail quill *• super new, quill destForm; Display, quill quill quill quill quill quill quill quill
Figure 21.9
frame: Display boundinqBox, sourceOrigin: O@O, mask: Form black, defaultNib: 1, com bin a tionFiule: Form paint down. home, north.
422 Single-stepping Through an Execution
Choose the yellow button command step. The method is completed and is removed from the activation stack. The action is reflected in the debugger (Figure 21.10). The message new has now been sent successfully to Pen. The assignment to bic is carried out immediately, and the next message selected is gray to Form. This is precisely the state the debugger would have reached if, at the point shown in Figure 21.5 when new to Pen was the text selection, you had chosen yellow button command step instead of send. In the inspector for temporary variables, choose the name bic in the menu; bic is an instance of Pen. In the menu of the inspector, choose the yellow button command inspect and create an inspector for bic (Figure 21.11). In the text subview of the inspector for bic, type halftoneForm displayAt: Sensor waitButton Select the text and choose the yellow button command do it (Figure 21.12a). Click any button somewhere on the screen where the area is clear and you will be able to see the result. A black, 16 χ 16 square is displayed; this is the default mask for a Pen (Figure 21.12b).
U η define d Ο b j e c t > > υ η b ο υ η d Μ e t h o d C ο m ρ i Ι Θ r > > e ν a I u a. t e: i η: t ο: η ο t i f y ί η q: ί f F a i I: C o d e C o n t roller) >do It example " D r a w 5 a spiral in g r a y w i t h a pen t h a t is 4 pixels wide.
self hair, bic *- Pen new, bic d e f a u l t N i b : 4, bic combinationFiule: Form under. 1 t o : 5 0 do: [:i | bic go: i+ 4, bic t u r n : 8 9 ] "Pen example"
self super :lass rn e t h cdDic
Figure 21.10
bic
423 Single-stepping Through an Execution
U η d Θ fi η e d 0 b j e c t > > υ η b ο υ η d Μ e t h o d C ο m pile r> > e ν a. I u a. t e: i η: t ο: η ο r i f y i η q: i f Fa i I: C ο d e C ο η t ro 11 e r> > d ο 11 example "Dra·.
s ρ i r a. I in q r a. y w i t h a. pen t h a t is 4 ρ i :•; e I s ν ν i d e.
I bic | self halt, bic *- Pen new, bic defaultNib: 4. bic combina.tionFiule: Form under, 1 t o : 50 do: [:i | bic go: i*4, bic t u r n : 8 9 ] "Pen example"
Figure 21.11
Bio
self superclass rn e t h ο d D i c
a Pen
Halt encountered. U η d e f i η e d 0 b j e c t > > υ η b ο υ η d Γνΐ e t h c C ο rn ρ i I e r > > e ν a. I u a t e: i η: t ο: η ο t i f y i η C ο d e C ο η trolls r > > dolt example "Draws a spiral in qray ν I bic | self halt. bic *· Pen new, bic mask: Form qray. bic defaultNib: 4. bic cornbina.tionRule: Form under, 1 to: 50 do: [:i | bic go: i*4. bic turn.: 8 9 ] "Pen example"
Figure 21.12a
Bio
self superclass method Die
Pen
424 Single-stepping Through an Execution
Halt en c ο υ η t e re d,
U η d e f i η e d Ο b j e c t > > υ η b ο υ η d M e tself hc C ο rn ρ i I e r > > e ν a I u a t e: i η: t ο: η ο t i f ydestForrn iη sourceForm C ο d e G ο η t r ο 11 e r > > dolt
example "Draws a spiral in gra;
half ton eForr combination destX destY width height sourceX sourceΥ clipX clip Υ
I bic | self halt. bic - Pen new. bic mask: Form gray, bic defaultNib: 4. bic combinationRule: Form under. :+: 1 to: 50 do: [:i | bic go: i 4. bic turn: 8 9 ] "Pen example" self superclass methodDic
btc
a Pen
Figure 21.12b
Now return to the debugger and choose the yellow button command step in the top subview. The message gray is sent to Form. The next message is mask: to bic. Choose the command step again. Return to the inspector for bic and reevaluate the expression halftoneForm displayAt: Sensor waitButton Click any button somewhere on the screen where the area is clear and you will be able to see the result. A gray, 16 χ 16 square is displayed; this is the new mask for bic (Figure 21.13). Returning to the debugger, keep stepping through the method (choosing the command step); examine the variables of the Pen, bic, by choosing variable names in the inspector menu or evaluating expressions as already illustrated. You will change the size of the nib, the source Form, and the combination rule for bic. These evaluations will go very slowly since a simulator for the Smalltalk-80 interpreter is used. Sending defaultNib: will be especially slow, perhaps one-half minute on some machines.
Eventually, the text selection will be the message to: 50 do: [ :i | bic go: i*4. bic turn: 89] (Figure 21.14). If you were now to choose the command step, you would watch the Pen draw the 50 lines that make up the spiral design; the drawing would be carried out in an excrutiatingly slow manner. Rather than choosing the command step at this point,
425 Single-stepping Through an Execution
Halt e n c o u n t e r e d .
Pen
h a I f t ο η e Fo rm d i s ρ I a y A t: self 5 e η s ο r w a i t Β υ 11 ο η U η d e fi η e d 0 bj e c t > > υ η b ο υ η d M e t h c destForm C ο rn pile r> > e ν a I u a t e: i η: t ο: η ο t i f y i η sourceForm C ο d e G ο η t r ο 11 e r > > d ο 11 halftone For r combination example destX "Draws a spiral in gra; destY width height I bic | sourceX self halt. sourceΥ bic *- Pen new. clipX bic mask: Form gray. clip Υ bic defaultNib: 4. bic combine.tionFiule: Form under. 1 t o : 50 do: [:i | bic go: i*4. bic turn: 8 9 ] "Pen example"
self superclass method Die
bic
a Pen
Figure 21.13
U η d e fi η e d Ο bj e c t > > u η b ο υ η d Μ e t h ο d G ο rn pile r> > e ν a. I u a t e: i η: t ο: η ο t i f y i η g: i f Fa i I Code C ο η t ro 11 e r> > dolt example "Draws a spiral in gray w i t h a. pen t h a t is 4 pixels vvidi I bic | self halt. bic - Pen new, bic mask: Form gray, bic defaultNib: 4, bic combination Rule: Form under. to: 5U do: [:i I bic qo: i*4. bic turn: 89] I"Pen example"
Figure 21.14
010
selfsuperclass rnethodDic
a Pen
426 Single-stepping Through an Execution
choose the command send so that you can see, more quickly, the Pen design. Assuming you choose the yellow button command send in the top subview of the debugger (Figure 21.14), the message to:do: to a Smalllnteger is placed at the top of the activation stack (Figure 21.15). The first expression in the method associated with to:do: is an assignment, and it is carried out immediately. The text selection is at the second expression, a comparison of the temporary variable nextValue with the argument stop. In the right inspector of the debugger, choose the temporary variable name nextValue so that you can watch the value change as the iteration proceeds; nextValue is initially 1 (Figure 21.16). Choose the yellow button command step to evaluate the test for the iteration; the next message is value:. Choose step again. A small line is drawn, and the selection goes to + . Choose step again. The value of nextValue is now 2; the display of the change in value for nextValue is automatically updated (Figure 21.17). Continue to choose step for awhile, say until the value of nextValue is 4, and you can see the drawing of 3 lines of the spiral design (Figure 21.18). You can now complete the example by choosing the yellow button command proceed in the top subview (Figure 21.19). Or you can close the debugger by choosing the blue button command close, and thereby abort the execution of the example.
Halt encountered,
Pen
Srna nteaerfNumben>>to:do:
Pen c la Ji>>ex ample U η d e fi η e d Ο bj e c t > > u η b ο υ η d Μ e t h ο d C ο m pile r> > e ν a. Ι υ a t e: i η: t ο: η ο t if ν i η q: i f Fa. i I:
to: stop do: aBlock "Create an Interval from the receiver up to the argument, 5top, incrementing by 1. For each element of the interval, evaluate th· block, aBlock." | nextValue | nextValue - salf.
[nextValue QQQQ]
Figure 21.15
100 000
while Τ rue: [aBlock value: nextValue, η e χ t V a Ι υ e *- η e χ t V a I u e + 1 ] self
5 tup aBlock
427 Single-stepping Through an Execution
Pen class>>example U η d e fi η e d 0 bj e c t > > υ η b ο υ η d M Q t h o d C o m pile r > > e ν a I u a t e: ί η: t ο: η ο t i f y i η g: i f Fa. i I:
to: stop do: aBlock "GreatΘ an Interval from the receiver up to the argument, stop, incrementing by 1. For each element of the interval, evaluate the block, aBlock."
Figure 21.16
100 000
| next Value | next Value «- self, [nextValue Q j j ^ ^ ] while Τ rue: [aBlock value: next Value, next Value *• next Value + 1] self
stop aBlock Μ Μ Μ
fiua
Pen cla.5S>>example U η d e f i η e d Ο b j e c t > > D ο 11 C ο rn pile r> > e ν a I u a t e: i η: t ο: η ο t ί f y i η g: i f Fa i I:
to: stop do: aBlock "Create an Interval from the receiver up to the argument, stop, incrementing by 1. For each element of the interval, evaluate the block, aBlock," k | nextValue | | next Value *- self. [nextValue g^g]^Q] whileTrue: [aBlock value: nextValue, nextValue *• nextValue + 1]
roo self
Figure 21.17
stορ aBlock •naamauia
428 Single-stepping Through an Execution
Pen Halt encountered.
Ι
Κ ^. 11= 1- •-• >-..-.[Γ.-..-Γ.-.
.-•!! -r >-.I z. •• .• A
jiTia. InteaeriNurnberι;·;·ΐο:αο: Pen class>>example UndefinedObject>>Dolt C ο m ρ i I e r > > e ν a I u a. t e: i η: t ο: η ο t i f y i η c\; i f F a. i t o : stop do: aBlock " C r e a t e a n I n t e r v a l from t h e r e c e i v e r up t o t h e a r g u m e n t , s t o p , incrementing b y 1. For each element of t h e i n t e r v a l , e v a l u a t e th> block, aBlock." | next value | next'v'aluQ *- self, [nextValue ''..= stop] while Τ rue:
f
|
*
[aBlock QQj^^^QQQ ηeχtVaIue - ηeχtV aIue + 1 ] stop aBlocI
self
Figure 21.18
000 Pen
System Browser 'Jollec t i o n s - b t r e a C ο 11 e c t i ο ri s - S υ ρ ρ ο «reiiiiiregaiiinMi«i Graphics-Display Graphics-Paths Graphics-View s Graphics-Editors Graphics-Support example "Dravvs ^
^
^
self h ai;t:, * ;/' bic - P^^^& b i c m a s [•.: F ο ί bic d e f a u l t Ν i b: %^S0S b i c c ο m b i ΓΙ a t i ο ri Fi υ ίϋι;;;;-|^|ρ 1 t o ; 50 do: [:i | bic §^$
Figure 21.19
Ooo
: 89]
PART
FIVE
External Files
Your work in developing Smalltalk-80 code can be saved in a variety of ways, all of which will be described in Part Five. • Make a file on which new class definitions and descriptions, or parts of class descriptions are stored. This kind of a file is useful in sharing information among different users of Smalltalk-80 system images. • Make a file on which any changes to existing class descriptions are stored. This involves filing out with respect to the system change set. • Make a "snapshot," a file containing an executable image of the current state of the system. The system can be started up from this file. • Make an audit trail. As you are working, a log of the changes you make to class descriptions is automatically kept on a special file. It is part of the mechanism for storing source code. This file also contains each evaluation action. It can be used for recovering from major disasters that occur before you have saved your work (with the exception, perhaps, of disk crashes).
The File System
22.1 Writing Code onto a File File Formats 22.2 Accessing the Contents of a File File List Browser 22.3 Retrieving the Contents of a File Syntax Error View 22.4 Getting Started Revisited Sources and Changes Files Decompilation
432 The File System
The purpose of this chapter is to describe the mechanisms available in the Smalltalk-80 system for filing code in and out. In using the programming system, you should be aware of how access to the source code is handled, and how the system supports you in remembering changes you make to the system. Source code and changes are stored in files that exist on either your local disk or on a network-based file server. If the file of source code is not available to you, you can still browse the system methods by using a decompiler. The end of this chapter reviews the use of the sources and changes files and the decompiler; further details about sources and changes are given in Chapter 23. At Xerox PARC, work in progress on an application is typically stored in personally managed snapshots. The purpose of maintaining snapshots is that they represent a collection of objects, whereas files are needed because we do not understand, as yet, how to transfer external objects, and we do understand how to transfer descriptions of objects. Files, therefore, are our primary communication medium. Periodically, files containing class descriptions and changes to system classes are made, especially when the programmer wishes to work in a new release of the system. The programmer accesses a new release and then files in the new class definitions and methods. To share additions to the system, either bug fixes or new functionality, files (rather than snapshots) are made and then stored on a shared network-based file server; an announcement of the availability of the files is made using a form of electronic mail. Throughout this chapter's discussion, it should be understood that the system makes no distinction between local disks for storing files and remote files stored on network-based file servers, other than in naming the file. (The name of a remote file includes the name of the file server and directory, and the system must request any log in identification. Smalltalk-80 systems that provide access to file servers must implement the network protocols and provide prompters for obtaining log in identification.) Because most of the computers used by the Smalltalk-80 developers are shared, files are rarely stored on local disks, with the exception of the latest system release image and changes files. All users are expected to back up their work, snapshots, or files of class descriptions, on a file server.
22.1 Writing Code onto a File
There are two ways to write code onto a file. The usual way is to select the yellow button commands in the system browsers that provide general access to class descriptions. Four layers of information can be selected for filing out from the various subviews of a system browser. • The code that describes all the classes within a class category. Choose the yellow button command file out in the class-categories subview of the browser. The file name is the class category followed by an extension. • The code that describes an individual class. Choose the yellow button command file out in the class-names subview of the browser. The file name is the class name followed by an extension.
433 22.1 Writing Code onto a File
• The code that describes the methods associated with a category of messages in an individual class. Choose the yellow button command file out in the message-category subview of the browser. The file name is the class name or metaclass name followed by a hyphen followed by the category name followed by an extension. • The code associated with one method of an individual class. Choose the yellow button command file out in the message-selectors subview of the browser. The file name is the class name or metaclass name followed by a hyphen followed by the message selector followed by an extension. In each case, the "extension" for the file name is a period followed by the characters St. The class name is inserted in front of the messagecategory and message-selector when creating the file name for the third and fourth subview. Any invalid file character in the selection is replaced by hyphens; invalid file characters include space, <, >, = , > = , and < = . Examples of file names associated with various selections is given in Figures 22.1a, 22.1b, 22.1c, and 22. Id, in which the command file out is chosen in each of the four menu subviews of a system browser. The information written onto the files using the command file out is in the form of expressions that can be evaluated to reconstruct the class descriptions.
| ^ B | accessing Collec :ions-Array String 1 testing Colledc i ο η 5 - S t re a S y m b ο 1 I copying 1 printing Collec j i o n s - S u p p j T e χ t Graph Graph printout ewr-~ --pvTi EUSa c l ass | 1 ι:;:;:!:; aslnte add category A rename je of the receiver." remove update edit all
1 asCharacter
jijiiijii
asLowercase asSymbol asUppercase
!|!ijj!;| jjjjjjijj i|!|!|iji
Μ
ill!
"
Collections -Text .st
Figure 22.1a
ΟΙΟ Ϊ
|
|||ΜΠΠ
Βιβϋϋιϋΐ!!
: : i : : : : : : : : o : : ;:·:· • :·':'·:'·: : : : : : • : · : ·:•:::: : : : : : • : • : • : • : • : : : • : • :•:·
434 The File System
Collections C ο 11 e c t i ο η s C ο 11 e c t i ο η s Graphic 5-Pr Graphics-C
accessιηg testing ying •iting
ΤΘ:
ρπη sρaw η s p a w n hierarchy hierarchy ^aslnteger d e fi η i t i ο η comment "Answer the /alu protocols •t ν a I u e ι rut var refs class var refs class refs rename remove
asCharacter asLowercase a s S y rn b ο I asUpperca.se
is*
Character.st
Figure 22.1b
010 C ο 11 e c t i ο η s - A rr a ;·! S t π η g C ο 11 e c t i ο η s - S t r e a S y rn b ο I C ο 11 e c t i ο η s - S υ ρ ρ j Τ e χ t G ra ρ h i c s - Pri rn i t i ν I Graphics-Display
comparing
pnntir
asciiValue "Answer the value of the receiver." t value
Figure 22.1c
Oio
sρaw η add protocol! re η a rn e remove
Character-accessing .st
435 22.1 Writing Code onto a File
C ο 11 e c t i ο η s - A rra i S t ri η g G ο 11e c t i ο η .-· - S t r e a S y m b ο I C ο 11 e c t i ο η s - S υ ρ ρ J Τ e χ t G r a p h i c s - Pri rn i t i ν I Graphic 5-Display!
asciiValue
"
m t a l w 3
'
comparing testing copying printing convertinq
" A n s w e r the value of the receiver." τ value
digit V a I u e
spawn senders implementors rn e s s a. g e s ΠΊ ο ν e remove
Character-ascii Value.st
Figure 22. Id
010 Alternatively, choose the yellow button command print out in each of the subviews of the browser in order to obtain a "pretty printed" version of the descriptions. The file name extension is a period followed by some sequence of characters indicating the format of the contents (at Xerox PARC, the characters are press). Typically, the contents of a file created using the command print out cannot be evaluated as Smalltalk-80 expressions. The command print out is reserved as a system dependent message for creating the best possible pretty-printed version. Because printing formats differ among hardware systems, the pretty-printed version defaults to being the same as file out in the basic version of the Smalltalk-80 system.
File Formats
The format for a file created using the command file out is described in the paper by Glenn Krasner entitled "The Smalltalk-80 File Code Format" in the book he edited, Smalltalk-80: Bits of History, Words of Advice. A summary of that paper is given here. The file format contains exclamation marks as special delimiters. Text up to, but not including an exclamation mark, is treated as an expression that can be evaluated. If an exclamation mark is the first character in the next chunk of text to be read, then all but this first character are treated as an expression and evaluated. The result of the evaluation is an object. This object then takes over the task of reading
436 The File System
the file, stopping when the object determines that its task is completed. In this way, a class can read and install new methods. Figure 22.2 shows a file out of part of the class description for Collection. The file starts with a String that indicates the date and time at which the file was created, and the version number of the system from which it was made. The exclamation mark delimits the String from the next chunk of text, which is a message to Object to create a new subclass, Collection, with no variable declarations and categorized under Co I lections-Abstract. The exclamation mark delimits this message from the next, which is a message to the new class Collection to store a comment about itself. The next exclamation mark is followed immediately by another. The chunk of text is a message to Collection to create a new category, accessing, and to start reading the methods for that category. The class Collection, then, becomes the file "reader." It installs a method for size. The exclamation mark after the method is followed immediately by an exclamation mark, indicating the Collection can stop reading the file. The next text chunk creates the message category testing for Collection, and the methods follow. The "pretty printed" version for printing part of the class Collection is shown in Figure 22.3. This format can not be read by the system, but is somewhat easier for a human being to read.
22.2 Accessing the Contents of a
File
I,
Instances of external files can be created by evaluating an expression of the form FileStream fileNamed: ' fileName'
The response to this expression is an instance of FileStream that can be sent messages for reading and writing information onto the file it accesses. Note that FileStream also responds to messages with selectors oldFileNamed: and newFileNamed: in order to open access to external files that already exist (oldFileNamed:) or do not already exist (newFileNamed:).
I
437 22.2 Accessing the Contents of a File
'From Smalltalk-80 of March 9, 1983 [v29] on 15 March 1983 at 9:35:22 p m ' ! Object subclass: #Collection instanceVariableNames: " classVariableNames: " poolDictionaries: " category: ' Collections-Abstract'! Collection comment: ' I am the abstract class of all collection classes.'! .'Collection methodsFor: ' accessing'! size "Answer how many elements the receiver contains." I tally | tally - 0. self do: [ :each | tally - tally + 1]. Τ tally! ! '.Collection methodsFor: ' testing'! includes: anObject "Answer whether anObject is one of the receiver's elements. " self do: [ :each | anObject = each ifTrue: [ftrue]]. tfalse! isEmpty "Answer whether the receiver contains any elements. " Tself size = 0!
Figure 22.2
occurrencesOf: anObject "Answer how many of the receiver's elements are equal to anObject." I tally | tally - 0. self do: [ :each | anObject = each ifTrue: [tally - tally + 1]]. Τ tally! !
438 The File System
From Smalltalk-80 of March 9, 1983 [v29] on 15 March 1983 at 9:35:22 pm Object subclass: #Collection instanceVariableNames: " classVariableNames: " poolDictionaries: " category: ' Collections-Abstract' Collection comment: ' I am the abstract class of all collection classes.' Collection methodsFor: ' accessing' size "Answer how many elements the receiver contains." I tally I tally - 0. self do: [ :each | tally - tally + 1]. Ttally Collection methodsFor: ' testing' includes: anObject "Answer whether anObject is one of the receiver's elements." self do: [ :each | anObject = each ifTrue: [ttrue]]. τ false isEmpty "Answer whether the receiver contains any elements." τ self size = 0 occurrencesOf: anObject "Answer how many of the receiver's elements are equal to anObject."
Figure 22.3
I tally | tally - 0. self do: [ :each | anObject = each ifTrue: [tally <- tally 4- 1]]. Ttally
439 22.2 Accessing the Contents of a File
For example, create the file whose name is testFile, and practice writing text into it, by evaluating the following sequence of expressions. I aFile | aFile «- FileStream fileNamed: ' testFile'. aFile nextPutAII: ' The beginning of the file.'. aFile cr. 1 to: 50 by: 10 do: [ :each | aFile nextPutAII: each printString. aFile cr]. aFile nextPutAII: ' The end of the file.'. aFile close
FileStream is a subclass of ReadWriteStream; the messages for writing into the file are like those of any ReadWriteStream. Using a system browser, you can explore the messages available for writing text into a file. Note that instead of using the expression aFile nextPutAII: each printString in the statements for writing on the file, you could have used each printOn: aFile and the result would have been the same.
File List Browser
The simplest way to open a file and access its contents is to choose the System Menu command file list. You are asked to designate a rectangular area in which the file list view is displayed. This standard system view consists of three subviews. You type text in the top subview to specify file names or patterns for file names (of either existing or new files). A pattern is a sequence of characters that can contain the special characters * or # ; * matches any sequence of no, one, or more characters, and # matches any one character. When you choose the yellow button command accept in the top subview, the next subview, the filenames subview, displays a list menu containing all the names of the files in the local disk that match the names you specified in the pattern subview. When you choose a file name from the menu, the contents of the selected file is displayed in the bottom text subview. If the file system you are using allows the characters * and # in a file name, then you will want to choose other characters for pattern matching purposes, and it will be necessary to change the String matching routines. The method to be changed is String match:.
440 The File System
The form of the pattern subview is a sequence of file names delimited by "carriage returns," that is, each file name or pattern is placed on a separate line. Suppose you type story and then choose the yellow button command accept in the top view (Figure 22.4a). We are assuming that the file story did not exist before. The file-names menu displays one item (Figure 22.4b). story Choose it. The item is selected. Nothing else happens. The yellow button menu offers five commands (Figure 22.4c). get contents
Retrieve the contents of the selected file, and display the contents in the text subview.
file in
Retrieve the entire contents of the selected file, reading and evaluating the text according to the file format for class descriptions and expressions.
copy name
Copy the text of the file name into the text editor buffer so that it can be "pasted" into other text views.
FilQ List 51 o r v.
Figure 22.4a
Rio
aqaιπ undo cορy cut ρ a. 51 Q
44J_ 22.2 Accessing the Contents of a File
Figure 22.4b
File L i
r
^ ^ ^ ^ H
5tory A qet con tent s ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ _ file in ^^^^^^^^^^^^^^^ copy η am Q 1 . rename | Λ re m o v e j
Figure 22.4c
010
442 The File System rename
Change the name of the selected file. A prompter appears, with the name of the selected file. Edit it with the new file name. Type the "carriage return" key or choose the yellow button command accept to indicate that you have completed the file name. The menu of file names will be updated. If you type an improper file name, or no file name at all, a confirmer will appear to determine whether you want to try again to specify a file name. Examples of this command are given later in this chapter.
remove
Delete the selected file from the file directory. A confirmer appears to determine whether you really want to remove the selected file. Choose yes if you do, no if you do not.
Whenever you retrieve the contents of a file, information is presented in the System Transcript (if it is visible on the display screen). This information tells you which class and which method is currently being read and compiled. In this way, you can monitor the progress of the file retrieval. Choose the yellow button command get contents (Figure 22.5a). The file contents is empty. The text subview displays - new file -
File L i s t l | i i l | l l l l 5tory A ι i
\
Figure 22.5a
ΟΪ0
copy name 1 rename | remove 1
443 22.2 Accessing the Contents of a File
to indicate that a new file will be created if you edit and store the contents of the text subview. Keep in mind that the new file will be created only if the contents are saved onto the file. Edit the text subview as though you were working in a regular workspace. The yellow button menu contains the text editing commands plus three additional commands, file it in, put, and get (Figure 22.5b). file it in
Read and evaluate the text selection. This selection should be in the file-out format, which includes the exclamation mark.
put
Save the edited information onto the file. One level of back up on the file is maintained. The original version is renamed to the given file name with a trailing $ appended; the new version is stored as the currently selected file name.
get
Retrieve all the information currently in the file.
File List
-{\e w
again undo copy cut pastQ do it
print it file it in put get
Figure 22.5b
[Din
444 The File System File List story.
One9 upon the
again undo copy cut paste do it print it file it in
Figure 22.5c
010 Edit the contents and then choose the yellow button command put (Figure 22.5c). The cursor changes to a writing pen when a file is being written; it looks like eyeglasses when a file is being read. During the time it takes for the system to access the file, the cursor looks like an hourglass, meaning "wait" because it may take noticeable time to find the file you requested.
The commands put and get are the external file counterparts to accept and cancel. Although the contents of the file are retrieved when you select a file name, you might make changes that you later wish to throw away. In a workspace, you would choose the command cancel; in the file browser text subview, you choose the command get. In the top subview, replace story by storage and choose the yellow button command accept. The file-names subview changes again (Figure 22.6a). Choose the single item, storage. Choose the yellow button command get contents (Figure 22.6b). Again, we are assuming that you requested a new file. Edit the text subview and then choose the yellow button command put (Figure 22.6c).
445 22.2 Accessing the Contents of a File
Once upon the time.,^
Figure 22.6a
ίοϊο storage
cορy πame rename remove
Figure 22.6b
ioio
446 The File System
File List 51 orageA
The foil owing if. documentation about the memory storage system, a. g a. ι η undo copy cut ρaste do it print it file it in
put
Figure 22.6c
KE3L1
010
Now in the top subview, replace all the text with the pattern stor* As stated earlier, the top part of the file list view can contain explicit file names or patterns for the names. String-matching provides two special notations for matching an arbitrary substring. * match any number of characters, including none # match exactly one character Note that s*y matches story, as does #t*y and story*. If you type stor* in the pattern subview and then choose the yellow button command accept, then the list menu will contain (at least) storage story Choosing each item and then choosing get opens the previously created file. Rename story to be tale. Choose the yellow button command rename (Figure 22.7a). A prompter appears (Figure 22.7b).
447 22.2 Accessing the Contents of a File
File List stor storage story
get contents file in copy name remw/e
Figure 22.7a
Oio File List stor*. storage
again New name for file undo copy cut ρaste do it print it
ΕΞΧΕ a net I
Figure 22.7b
'Τ'
448 The File System
Replace the text in the prompter with the file name tale, and then choose the yellow button command accept. The file name tale is selected automatically (Figure 22.8). If you created the file testFile suggested earlier in this section, you might use the file list view now to see its contents. Since any number of file names or patterns, separated by a "carriage return," can be typed in the top view, you can simply add this file name to the pattern already in the view. In addition to creating a file list view as just described, instances of external files can be accessed for editing by evaluating an expression of the form (FileStream fileNamed: 'fileName') edit The text subview part of the file list view, only, is created. The label of the view is the name of the file. In Figure 22.9a, the expression (FileStream fileNamed: 'tale') edit is typed, selected, and evaluated in a workspace. In Figure 22.9b, a simple view of the contents of the file is shown. The yellow button menu is like that available in the file list view.
Figure 22.8
449 22.2 Accessing the Contents of a File
Figure 22.9a
( F i I 9 ο t r Q a m filaMa rnΘd: ' t a l e 7 ' 1 Qdit
Figure 22.9b
450 The File System
22.3 Retrieving the Contents of a File
Class descriptions that were stored on a file whose name is fileName, using the browser command file out, can be retrieved by evaluating an expression of the form (FileStream oldFileNamed: 'fileName') fileln
This expression is provided in the System Workspace for your convenience. Whenever you read class descriptions from a file that create a new class category, any open system browsers will have to be informed of the new category. In the class-categories subview of the system browser, choose the yellow button command update.
Syntax Error View
Since files are created by choosing the file out command in a browser subview, there are three reasons why an error can exist in a file you try to read. 1. Variables or messages that had been a part of your image at the time you created the file are not in the version into which you are now filing. 2. You used a file list view and edited the text directly, creating a syntax error (which is why you should not edit class descriptions this way!). 3. You selected the text of a file and chose the yellow button command file it in, but did not select the correct sequence of characters. As you are filing in information from a file, a status report is printed in the System Transcript (if it is open on the display screen). If, when filing in, undeclared variables are encountered, a statement showing the variable name and the fact that it is undeclared prints in the System Transcript. The system will store the method anyway, as though compilation had been successful, and you will have to use the browser to find and correct the error. Similarly, if an unknown message selector is encountered in a method, the process of filing in will be interrupted. A notifier will appear on the screen. You can ask the spelling corrector to determine a possible new selector. If the determination is acceptable, you choose the menu item yes. This will store the right information in the system and continue reading the file. Or you can use the debugger, find and correct the error, and then proceed (choose the yellow button command
451 22.3 Retrieving the Contents of a File
proceed) to continue reading the file. Or you can simply proceed to continue reading the file, without correcting the error and, therefore, without storing the information in the system. In each case, the text in the file will not be changed. If a syntax error exists in the expressions that are filed in from an external file, a special view will be created on the screen. It is the Syntax Error View. Its purpose is to report the error and give you an opportunity to edit the expression. A syntax error view consists of one text view that displays the expression to be evaluated, or the method to be compiled and stored in a class description. To create an example of a syntax error, file out the class FinancialHistory that you had created as an example in Part Four. You do this by choosing the class name FinancialHistory in a system browser, and then choosing the yellow button command file out in the class-names subview. Use the file list view to retrieve the contents of the file you created; the file name is FinancialHistory.st (Figure 22.10).
System Browser
financialhistory.st
Systern-Releasin Files-Streams Files- A b s t r a c t Files-Xerox Alto
'From Small t a l k - 8 0 , version 2, of April 1, Object subclass: # Fin a n 19 8 3 ο η 2 5 Μ a y 19 8 3 a t 10: 17: 12 a m'! iηs ta nc e Va ήa bIeΝa c I a s s V a r i a b I e Γ0 a m e sΟ b j e c t s υ b c I a s s; # Fi η a n c i a IH i s t ο r y poolDictionaries: " i η s t a η c e V a ή a b I e Ν a m e s: ' c a s h Ο η Η a n d c a t e g o r y : 'Financial expenditures ' c I a s s V a r i a b I e Ν a m e s: '' poolDictionaries: " c a t e g o r y : 'Financial Tools'!
IFinancialHistory methodsFor: 'transaction. 1 :'!
Figure 22.10
000
spend: amount for: reason
452 The File System
Next, create some syntax errors in this file. Find the first occurrence of an assignment expression and insert an extra left arrow, or find a keyword in a message pattern and add an extra colon. Choose the yellow button command put to store the syntax error into the file (Figure 22.11). While the text is being written on the file, the cursor changes to the shape of a pen.
by stem Browser! Systern-Releasin Files-Streams Files-Abstract Files-Xerox Alto
ftttaii
bject subclass: instance'v'ariafc class Varia bleW poolDictionarie cat «gory; 'Fin a
again expenditures at: reason undo total Spent For: reason) + ar copy cur. cashOnHand cash':
ρa ste
do it IFmancialHistory methodsFolprint it |es'! [file it inl
report "Answer a String that hrfm^. current balance and expenditures."
Figure 22.11
010
the
| a Stream | a Stream *• WriteStream on: String ne a. S t· r e a m η e χ t Ρu t A11: 'Fin a. n c i a I H i s t ο r
In the menu subview of the file list view, choose the yellow button command file in (Figure 22.12a). A syntax error view appears indicating that an expression is expected after the first left arrow (Figure 22.12b). Text describing the syntax error is inserted into the method at the point of the error; the text is selected. You edit the method to correct it, just as you would in a browser text subview. Choose the yellow button command accept to recompile the method (Figure 22.12c). Now choose yellow button command proceed (Figure 22.12d). The correction you made is known to the system, but no change has been made to the text on the file itself. You either have to file out again to create a corrected file, or you have to use the file list view to access the contents of the file and make the correction. During filing in, expressions can be evaluated. For example, an expression that creates a new class description might appear in the text in the file. If evaluating the expression generates a runtime error during the file in, then a syntax error view will appear. The poorly-formed expression will be displayed in the view. For example, suppose you
453 22.3 Retrieving the Contents of a File
System Browser S y s t e ΓΙΊ - Fi e I e a. s i η Files-Streems File.-.-Abstract Files-Xerox A l t o
Object subclass: # Fin a. n i η s t a. n c e V a. r i a. b I e Ν a.! Fi η a ri c ί a. ΙΗ ί s t ο r y m e t h ο d s For: ' t r a. n s a c t i ο η s'! c I a. s s V a ri a. b I e Ν a m e s poolDictionaries: spend; amount for: reason
catequry: 'Financial
"Spend amount for the reason given, decrementing the available cash on hand," expenditures at: reason put: (self totalSpentFor: reason) + amount, cashOnHa.nd *• *• cashunHa.nd - amount!
Figure 22.12a
ΟΪ0
! Fi η a η c i a. ΙΗ i s t ο ry rn e t h ο d s Fo r: ' ί η q u i ri e s'!
S y s t e m - Fi e I e a. s ι Files-Streams Files-Abstract Files-Xerox A l t o
spend: amount for: reason "Spend amount f o r t h e reason given, decrementing t h e a v a i l a b l e c a s h on hand," e x p e n d i t u r e s a t : reason p u t : (self t o t a l Spent For: reason) + amount, c a s h Ο η Η a. n d *• C3.sh0nH3.nd - amount
: ra.ns a c t ions'!
son given, ;h on hand," t: (self
nt, ?.nd - amount! ! nquiries"!
Figure 22.12b
454 The File System
Svstern Browser
finaricialhistorv.st
S y s t e m - Fi e I e a s 11 Files-Streams
Files-Abstract Files-Xerox Alto
spend: amount for: re as or "Spend amount for the re a. so ρ niwar decrementing the available cash sxpenditures at: reason put: totalbpentFor: reason) + amount, rashunHand *• cashunHand
Figure 22.12c
son given, ?h on hand," t: (selr nt. nd - amount
010 File List System
Browser
financial hist or v.st
S ν s t e nri - R e I e a s i η Files-Streams fifwinc Files-Abstract Files-:: ero • A l t o
Toots
spend: amount for: reason "Spend amount f o r t h e re a q a ι η in, decrementing t h e available a undo s.nd, copy expenditures a t : reason ρ c υ t paste totalSpentFor: reason) + a mo do i t c a shun Hand *- cashOnHai print it unt a. c c e ρ t c a. n c e I
nvgeaw
Figure 22.12d
010
:rans a c t ions'!
son given, r.h on hand." t: (self nt, *nd - amount! ! nquiries'!
455 22.3 Retrieving the Contents of a File
modify the file Financial Η istory.st so that instead of trying to create Financial History as a subclass of Object, the expression contains the name Oject (i.e., there is a typo) (Figure 22.13a). Choose the yellow button command put to store the change. Now choose the yellow button command file in in the menu sub view of the file list. A notifier will appear (Figure 22.13b). Open a debugger and select the message-send Dolt to see the erroneous expression. You can edit the expression and then select the yellow button command accept (Figure 22.13c). The expression is stored so that the information is now known to the debugger; the file is not corrected. To continue the process of filing in, you must choose the yellow button command proceed in the top subview (Figure 22.13d). If, instead of correcting the error in the syntax error view, the notifier, or the debugger, you close the view by choosing the blue button command close, the process of filing in is discontinued and the file is closed.
iilililiii; by stem Browser]; ;•;•:;;;;:; ilillililii; ;;i|ilil|;i illlliliili
bystem-fieleasin Files-Streams Files-Abstract Files-Xerox Alto
Si
liil|||i;l Object subclass: # l|l|i|:|lil instanceVariat illllili; class Variable Ν :|l|;|l|;|;; poolDictionarie Ι|Ι|Ι|Ι|Ι|ί category: 'Fine
I:;:;:::::;:;:;:;:;:;:;:;:;:;:;:;:;:-:;:;:::;:;:;::;;:;:;:;:::;:;:
Figure 22.13a
000 iS
financialhistory.st
i|l; Iii:
'From Smalltalk-80, version 2, of April 1, 1983 on 25 May 1983 a t 10:17:12 am'!
l;l| ;l;i
Ol'ect subclass: #FinancialHistory ^ instanceVariableNames: 'cashOnHand expenditures ' class Variable Names: " poolDictionaries: " category: 'Financial Tools'!
|;|l ill; |l|l |i|l ill; ;|ii
IFinancialHistory methodsFor: 'transactions'!
;|;;
1
n1 m
'•':•': ''•':'•':'•':'•': ''•':'·':'•]'·': ''•':''•':'•':'•': :^ i ; * j I i ^ j i ; i ; : ; ^ j : ; -';:; f ; -: .r r j i ; -" j -:: - : :
I:;:::;:::::;:;:::::;:::;:·:;:;:::;:::;:;:;:::;:;:;:::::;::::::::: :;:;:;·::;:;:;:;:|:;:;:;:::;:;:;:;:|:;:;:;·::;:|:;:::;:;:;:;·::|:;
SDend: amount for: reason
iiil
456 The File System
U η d e f i η e d 0 b j e c t (Ο b j e c t ) > > d ο e s Ν ο t U nderstand: U η d e f ί η e d Ο b j e c t > > D ο 1t Gompiler>>evaluate:in:to:notifyinq:ifFail: I k - 8 0 , version 2, of April 1, G ο m ρ i I e r c I a s s > > e ν a I u a t e: f ο r: η ο t i f y i η g: I o g gVIay e d: 1 9 8 3 a t 10:17:12 am'! C ο rn ρ i I e r c I a s s > > e ν a. I u a\ e: f ο r: I o g g e d: > s: # Fi η a n c i a IH i s t ο r y pooiuictionanes: " i η s t a η c e V a r i a b I e Ν a m e s: ' c a s h Ο η Η a n d c a t e g o r y : 'Financial expenditure!. ? c I a s s V a. r i a b I e Ν a m e s: " poolDictionaries: " c a t e g o r y : 'Financial Tool;.'!
! Fi η a η c ί a ΙΗ i s t ο ry m e t h ο d s Fo r: ' t ra. η s a c t ί ο η s'!
Figure 22.13b
000
ι a end: amount for: reason
• UndefinedObject(Object)>>doesNot Understand: Compiler) >evalu a te:in:to:not if ying:if Fail: Compiler class>>evaluate:for:notifying:logged: Dolt
agaιη t Object undo s υ b c I a s s: # Fi η a n c i a IH i s t ο r y copy i η s t a. η c e V a ri a b I e Ν a m e s: ' c a s h Ο η Η a n d e χ ρ e η d i t u r e; cut paste c I a s s V a ri a b I e Ν a m e s: " do it poolDictionaries: " print it c a t e g o r y : 'Financial Tools' format spawn explain
Figure 22.13c
010
self
457 22.4 Getting Started Revisited
Compiler>>evaluatQ:in:to:notifyinq:ifFail: full s t a c k C ο m ρ i I e r c I a. s s > > e ν a. I u a. t e: f ο r: η ο tifyincj: C ο m ρ i I e r c I a s 5 > > Θ ν a I u a t e: f ο r: I o q g e d: C ο m ρ i I e r c I a 5 s > > e ν a I u a t e: I o g g e d:
Dolt t Object
Figure 22.13d
010
senders implementors messages
self
22.4 Getting Started Revisited
Sources and Changes Files
Recall that in Section 1.3 you were introduced to the names of the external files needed to run the Smalltalk-80 system—the image, sources, and changes files. The sources and changes files contain text for methods stored in the format shown in Figure 22.2. When you use a browser to access a method, the system has to retrieve the source code for that method. Initially all the source code is found in the file we refer to as the sources file. This file might be stored on your local disk or it might be on a network-based file server, shared among several Smalltalk-80 system users. As you are evaluating expressions or making changes to class descriptions, your actions are logged onto an external file that we refer to as the changes file. If you change a method, the new source code is stored on the changes file, not back into the sources file. Thus the sources file is treated as shared and immutable; a private changes file must exist for each user. The executable form of methods is compiled code (an instance of class CompiledMethod). The location of the source code corresponding to the compiled code is stored as part of the representation of a compiled method.
458 T h e File S y s t e m The sources, changes, and image files must be used in a coordinated way because of this retrieval reference in the image to one of the the two external files.
The two external files for sources and changes are referenced as elements of a global variable, the array named SourceFiles. The first element of the array is the sources file, the second is the changes file. The System Workspace contains the following expressions for changing the reference to the sources file. SourceFiles at: 1 put: (FileStream oldFileNamed: 'filename.sources'). (SourceFiles at: 1) readonly.
If you rename the sources files, you can inform the system by evaluating this expression. You can change the reference to the changes file (SourceFiles at: 2) in a similar way. Extensive access to the changes file, either to merge the work represented on two or more such files or to create a new one, is available in the Smalltalk-80 system. This access, the change manager, is presented in Chapter 23. Decompilation
i.
When you do not have access to the sources file, because it is not available on your local disk (perhaps there was not enough space) or you do not have access to a remote file server where it is stored, then it is not possible to browse methods in the way described in Chapter 9. Your system, however, contains the compiled version of the methods, and the system includes a decompiler. If you use the decompiler, you can obtain the text for methods, even though you can not obtain comments or the names of arguments and temporary variables. There are two ways to inform the system to decompile, rather than to try to access the sources file.
if1' 1. Hold down the left "shift" key on the keyboard at the same time that you choose a message selector in the message-selector subview of a system browser. 2. In the System Workspace, evaluate the expression
y
SourceFiles «- nil The system will notice that the global variable SourceFiles is not an array referencing two files, as expected, and will decompile methods when you try to access them in a browser. In addition, the changes file will not be maintained.
..'
ft.
Ϋ"
System Backup, Crash Recovery, and Cleanup
23.1 Saving Your System State 23.2 The System Change Set Change-Set Browser 23.3 The System Audit Trail Crash Recovery Change-Management Browser Conflict Resolution 23.4 Creating a "Clean" System Creating a New System Image Static Checks Condensing Sources and Changes 23.5 Version Management
460 System Backup, Crash Recovery, and Cleanup
This chapter covers four aspects of the system that fall in the category of housecleaning support. Once again, we review the use of a snapshot as a way to save your work. We discuss the availability of the change set for monitoring the changes you make to classes and for supporting your ability to create files for sharing your work. While you are using the system, each addition or change to the system and each evaluation that you make is stored on an external file. This "audit trail" can be used by you to recover from a system crash and to merge the work of several programmers. After you work for awhile in a system image, housecleaning is needed to create new versions of the system image, changes, and sources files. This chapter includes an explanation of how to create "clean" system files. Version management is a general problem that is not directly supported by the standard system views. Research has been conducted in this area, and an experimental form of version management is used by the Smalltalk research team at Xerox PARC. A brief review of this research is provided in the last section of this chapter.
23.1 Saving Your System State
Periodically you might wish to save the current state of your work in the form of a system image. This is especially appropriate if you are going to make changes whose behavior you are not clear about, and which might, therefore, crash the system. Creating a snapshot is also appropriate if you feel that the amount of space for object storage is very low and you do not want to take a chance on losing your work. And it is important to save your work periodically if you feel that your hardware is not sufficiently reliable. The System Menu contains the command save. Choose this command (Figure 23.1a). When you choose the command save, a prompter appears. It contains the name of the image file currently being used (Figure 23.1b). Note that the extension for the file name is not included. (Note also that this is the first part of the name found as the first element of the global array, SourceFiles.) If you want to use this same file name, then choose the yellow button command accept, or simply type the "carriage return" key (Figure 23.1c). For some systems, to gain performance, part of the display screen turns white while the snapshot is being created on the file. It restores as soon as the file is completely written.
461 23.1 Saving Your System State
restore display e • it project projec t file" list browser worf space s y s t e m t ra π s c ri ρ t s y s t e m w ο c\ s ρ a c e
Figure 23.1a
Οίο
Figure 23.1b
again undo
Enter name for
Figure 23.1c
ΟΙΟ
snapshot
462 System Backup, Crash Recovery, and Cleanup If you want to use a different name than the one that appears in the prompter, then edit the text in the prompter. To terminate, choose the yellow button command accept, or type the "carriage return" key. A new file for the image is created; the name is the name you gave in the prompter followed by a period followed by the characters im (an abbreviation for "image"). The image file must be coordinated with the file containing the changes made in this image of the system. Thus another new file is created; the name is the name you gave in the prompter followed by a period followed by the characters changes. If you request a snapshot and then change your mind while the prompter is visible, delete all the text from the prompter. Choose the yellow button command accept, or type the "carriage return" key. When you back up your work on another personal disk or on a network-based file server, you should save both the image file and the changes file. When you want to use these files again, you should use them with the same interpreter you used when the files were created. Access to snapshot is also available when you choose System Menu quit. You are given the choice, then, to save, then quit.
23.2 The System Change Set
Within each project, a set of changes you make to class descriptions is maintained. (Projects are described in Chapter 4.) Using a browser view of this set of changes, you can find out what you have been doing. Also, you can use the set of changes to create an external file containing descriptions of the modifications you have made to the system so that you can share your work with other users. Sharing work, such as an application, involves sharing files of new class descriptions and sharing files of any changes you have to make to existing system classes. Information is added to the set of changes whenever you • change an existing method • add a new method • remove a method • change the category of a message • change an existing class definition • change a class comment • add a new class • rename an existing class
463 23.2 The System Change Set
• remove a class • change the category of a class These changes occur either by your system interactions (expression evaluations or method compilations), or by your retrieving information from a file (filing in). That is, the file contains class definitions or method definitions, and these are modifications to the system noted in the change set. If you change a method several times, there will be only one entry for that method in the change set. Keep in mind that an independent set of changes is maintained by each project. If you want to maintain a set of changes for each activity in which you participate, you can create a project for each. The changes you make to class descriptions, and the addition of classes to the system, however, are shared among all the projects that you create. Q Accessing the Set of Changes The set of changes can be accessed in the system by sending the single instance of SystemDictionary, Smalltalk, the message Smalltalk changes Smalltalk is a global variable that is a dictionary whose keys are the names of all the other global variables in the system, notably the names of existing classes. The set of changes is an instance of class ChangeSet and is bound to a class variable of SystemDictionary named SystemChanges.
The expression Smalltalk changes asSortedCollection may be found in the System Workspace. If you evaluate this expression by selecting the text and then choosing the yellow button command print it, you see a description of the changes you have made so far. Try this when you first start using the system, and try it again after you have compiled some methods and/or have defined some classes. An example result of evaluating the expression is shown in Figure 23.2. The changes displayed are the ones that existed in the system after • the class FinancialHistory was added to the system (as described in Chapter 13) • an instance of FinancialHistory was created and inspected • several messages were sent to the instance • a new method was added to class Dictionary to modify printOn: • the method for report was changed to use printOn:
464 System Backup, Crash Recovery, and Cleanup
Files (File S t re a. m oldFile Ν a rn e d: T i n a. η c i a ΙΗ i s t ο r y. s t ' ) fi 191 n. (Fi I e S t re a m file Ν a. rn e d: 'file Ν a. m e. s t ' ) file Ο u t C h a. n g e s. (FileStream fileNa.med: 'fileNarne.st') edit.
Changes S m a. 11t a I k η ο C h a. n g e 5. (Fi I e S t re a m file Ν a m e d: 'file Ν a. rn e. s t ' ) file Ο υ t C h a. n g e 5 F 0 r: S t r e a m. S t r e a. m r e m ο ·.,.· e F r ο rn C h a n g e 5.
"vtew the currenr changes' S rn a. 111 a. Ik b r 0 w 3 e C h a. n g e d Γνΐ e s 5 age s S rn 3.111 a I k c h a. n q e s a. s S 0 r t e d C ο 11 e c t i ο η I
('Dictionary printOn: - change' 'FinancialHistory - add' ) Inquiry
Figure 23.2
000
S rn a 111 a. I k b r ο ;we A111 rn ρ I e rn e η t ο r s Ο f: # rn e s s a g e S e I e c t ο r S rn a. 111 a I k. b r ο w ; e A11C a 113 Ο η: # rn e s s a. g e S e I e c t ο r C o l l e c t i ο η b r 0 13 e A11C a. 11 ί Ο η: # t i rn e 3 Fi e ρ e a. t: 5 rn a. 111 a. I k b r 0 ieAIICa.llsQn: w # a t : and: # a t : p i j t :
The changes show only that class FinancialHistory was added, and that a method in class Dictionary was added. The fact that expression evaluations were carried out is not stored in the set of changes. Q Removing Entries From the Set of Changes There are three ways to remove entries from the set of changes for the current project. 1. Remove all the entries from the set of changes by evaluating the expression Smalltalk noChanges. 2. Remove all the entries that have already been saved on a file. This is automatically done whenever you file out from a system browser. For example, if you file out a class description, all entries about the class are removed from the set of changes; if you file out a particular method, any reference to the method is removed. 3. Remove all entries that refer to a particular class, ClassName, by evaluating an expression of the form ClassName removeFromChanges Whenever you start with a new system image and you want to make certain that the change set contains only subsequent changes, you
465 23.2 The System Change Set
should evaluate the expression Smalltalk noChanges; the expression appears in the System Workspace. If you create a new class definition, the set of changes indicates that the class was added to the system. Henceforth, any changes to this class are not entered into the change set. This is because it is understood that the class is new and, therefore, everything about the class is new. If you file in a new class definition and then wish to maintain information about subsequent changes to the class, you should remove the class from changes using the message removeFromChanges or, if appropriate, sending Smalltalk the message noChanges. A typical way in which several people can work together on a project is to maintain independent changes files. A file created by one person is filed into the system, the change set is emptied, and then all new changes logged. Then a file of the changes is created. The next person retrieves the original file and then retrieves the file of changes. • Storing the Set of Changes on a File Changes to class descriptions (class definitions, comments, and methods) can be saved on an external file by evaluating an expression of the form (FileStream fileNamed: ' fileName') fileOutChanges
Alternatively, changes pertaining only to a specific class, ClassName, can be filed out by evaluating an expression of the form (FileStream fileNamed: ' fileName') fileOutChangesFor: ClassName
The process of filing out the changes does not modify the set of changes, so that the changes can be filed out again, especially if additional changes are made later in the working session. Rather than keeping a snapshot of your work, you might prefer to back up periodically by creating files of changes. As noted earlier, the process of filing out a class by choosing the yellow button command file out in a system browser causes references to that class to be removed from the set of changes. One strategy to use in creating external files for sharing your work is, first, to file out any classes that you added to the system, and second, to file out the remaining contents of the set of changes. The set of changes should then contain only changes to system classes. Change-Set Browser
You can create a view of the set of changes that is like a message-set browser. This is done by evaluating the expression Smalltalk browseChangedMessages
that appears in the System Workspace. Try it (Figure 23.3).
466 System Backup, Crash Recovery, and Cleanup
Files (F i I e 51 r e a. m ο I d F i I e Ν a m e d: T i n a Γι c i a IH i s ΐ ο r y. 51 "ι f i I e I n (F i I e S t r e a. m file Ν a . m e d: ' f i I e Ν a m e,; t'') f i I e Ο u t C h a n q e 5, i'FileStream fileNamed: 'fileName,5t'''i edit. Changes S rn a 111 a. I \ η ο C hi a. n g e ;, (Fi I e S t re a m file Ν a m e d: ' f i I e Ν a. rn e, s t ' file Ο ι j t C h a n g e ; For: S t r e a m, S t r e a m re mo ν eFrο rn C h a nge.-.. 1 V ι1 e '.· '.·' f Μ € c u rre η f cfts π α e s' Smalltalk browseChanggdMessagei S m a 11 ΐ a I k c h a. η g e s a. s S ο r ΐ e d C ο 11 e c t i ο η b ο r t ( ' D i c t i o n a r y print On: - c h a n g e ' ' F i n a n c i a l H i s t o r y - a d d ' ) inquiry S m a. 111 a I k b r ο w 5 e A111 m ρ I e m e η t ο r s Ο f: # m e 5 5 a g e S e I e c t ο r S rn a 111 a I k b r ο w 3 e A11C a. 115 Ο η: # rn e s s a g e S e I e c ΐ ο r
Figure 23.3
010
C ο 11 e ο ΐ i ο ri b r ο w :• e A11C a 11." Ο η: # ΐ i rn e •; Fi e ρ e a t: S m a l l t a l k brovvseAIICall^On: ^ a t : a n d : , » a t : p u t :
If there are no changes, then no browser is created and the word Nobody appears in the System Transcript (if it is visible on the display screen). The change-set browser shown in Figure 23.4 is a view of the same information that was printed in the workspace of Figure 23.2. The two parts of the change-set browser are identical to a message-selector browser as described in Chapter 10. The top subview is a list menu; the yellow button menu associated with it is the same as the yellow button menu associated with a message-selector subview of a browser. If you choose one of the class/ message pairs, the method associated with the message appears in the text subview of the change-set browser. You can file out or print out the method, and spawn a message-selector browser for the currently selected message. You can inquire about senders, implementors, and messages in the method. And you can move the message to a new message category, or you can remove the method from the system. You can not modify the change set using commands in the change-set browser. Notice that the fact that a new class was added to the system does not appear in the change-set browser; only changed methods are accessed using this browser.
467 23.3 The System Audit Trail
System VvOrkjpa.ee File Ν a m e d: ' Fi η a. n c i a. IH i s t ο ry. s t ' ) f i I e Ι η, ef'Jamed: 'file Ν a me, s t') file Ο υ t C h a. n q e s.
printOn: aStream
Figure 23.4
100 000
| tooΜany | t ο ο [·Λ a n y *• β. Stream position + self ma. x. Print, aStream next Put All: self class name, ' ('. aStream cr, self a. s s ο c i a. t i ο η s D ο: [:element | aStream position > t o o M a n y if True: [ a S t r e a m next Put.' ',,.etc.,,)'. t s e i f ] , element print On: aStream. aStream c r ] , a. Stream next Put: $)
23.3 The System Audit Trail
The storage of changes in the Smalltalk-80 system takes two forms: an internal form as a set of changes (actually a set of objects describing changes), and an external form as a file on which your actions are logged while you are working (in the form of executable expressions or expressions that can be filed into a system). The previous section described a browser to access the internal form; this section describes a browser to access the external one. All the information stored in the internal change set is also written onto the changes file. In addition, when you make a snapshot, the changes file is marked with the notation " —-SNAPSHOT-— " so that you can use a change-management browser (described later) to request a view only of the information stored in the changes file since your last snapshot. You can also look at the file and see what changes occurred between snapshots. The changes file serves two important uses: to provide information for recovery from a crash, and to support a way of sharing code
468
System Backup, Crash Recovery, and Cleanup implemented by a group of programmers, including finding and resolving conflicting changes.
Crash Recovery
Because the changes file maintains a log of each of your actions, you can use it to recover from a system crash, that is, any situation in which you find that you can no longer communicate with the system and therefore can not safely save your work. Recovery can be done in two ways. After a crash, start up a previous system image that you can run (presumably the last snapshot that you successfully made and saved). Evaluate a message such as Smalltalk recover: 5000
The argument, 5000, represents the number of characters from the end of the changes file that you wish to copy. The characters are copied onto a file named st80.recent. A view of this new file will be created on the screen. Explore it. Find the last place in the file containing the text " -—SNAPSHOT-— " . This is the point at which you wrote the last snapshot. If you can not find this text on the file, you will have to reevaluate the message recover: again, this time with a larger number. Now that you found the point at which you had previously saved your work, you can use the yellow button command file it in in the view of the file st80.recent to selectively evaluate and file in the changes you had made up to the time of the crash.
ChangeManagement Browser
Alternatively, you can use a browser that we refer to as the Changemanagement Browser. This browser lets you access your do it or print it evaluations, as Well as method definitions, whereas the change-set browser described in Section 23.2 does not. Moreover, the order in which you made changes is retained in the changes file and presented in the change-management browser. The order of changes is not retained in the internal change set. You can use this ordering information to back up to a previous version of a method. The change-management browser lets you • examine the contents of one or more changes files • examine the method changes stored in the change set • configure a new changes file • redo any of the changes or evaluations • determine whether there is any conflicting implementations of a method in two or more changes files To open a change-management browser that has no initial change content, evaluate the expression
469 23.3 The System Audit Trail
ChangeListView open To open a change-management browser that initially displays all the actions stored in the current changes file since your last snapshot, evaluate the expression ChangeListView recover Or you can specify a changes file (fileName) whose content should be displayed initially in the change-management browser. Evaluate the expression ChangeListView openOn: (ChangeList new recoverFile: (FileStream oldFileNamed: ' fileName')) All of these expressions are provided in the System Workspace. Select and evaluate the first one (Figure 23.5).
Τ i rrι e m i II i s e c ο η d s Τ ο Fi u η: [ S y s t e m Ο rg a n i ζ a. t ί ο η ρ π η t S t ri n g ] M e s s a g e T a l l y spy Οτι: [ B e h a v i o r compile AII], (File S t r e a m ο I d F i I e Ν a rn e d: ' s ρ y, r e s u 11 s') edit Change Management and Crash recovery ,. "•Create a. blank v<ew tor change recovery
Γι
_,
ChangeListView open. "Create a. view for change recovery from a given file' ChanqeL is t View op en Οτι: (ChangeList new recoverFile: (Fi I e S t re a. m ο I d Fi I e Ν a m e d: 'file Ν a m e. s t')), "After a crash, create a view to browse changes since the last snapshot:' C h a. n g e Lί s t V i e w r^c ο ν e r,
Smalltalk recover: 5000.
Figure 23.5
010 The empty change-management browser is shown in Figure 23.6. It consists of three major parts: the top part containing a list menu, the middle part containing several browser menu items that control the kind of information that will display in the menu, and the bottom part in which text is displayed and can be edited. With the cursor in the top subview, press the yellow button to observe the menu (Figure 23.7). The
470 System Backup, Crash Recovery, and Cleanup
show file file
Figure 23.6
5how category category I selector
same
••' category elector I
same
000
show file file
|
type
check conflicts :heck with system
Figure 23.7
471 23.3 The System Audit Trail
menu commands allow you to specify changes files to read or to write, and allow you to operate on a single item or on a group of items in the list menu. Two commands invoke conflict analysis on the items in the list menu. Q Commands that specify changes files file in
A prompter appears in which you type the name of a changes file. When you choose the yellow button command accept, references to the contents of this file are added to the browser menu. If you change your mind and want to abort this command, type nothing in the prompter and choose the yellow button command accept or type the "carriage return" key.
ίίΐθ OUt
A prompter appears in which you type the name of a changes file. When you choose the yellow button command accept, the items in the browser
menu that are not
marked for removal are stored in the file. If you change your mind and want to abort this command, type nothing in the prompter and choose the yellow button command accept or type the "carriage return" key. ΓΘΟΟνΘΓ last Changes
Adds to the browser menu references to the contents of the
display System
Adds to the browser menu references to the methods in the
current changes file since the last snapshot.
Changes
internal change set.
Q Commands that operate on a group of items do all
Evaluates each expression or new definition that is refer-
remove all
Marks every item in the browser menu for removal.
restore all
Unmarks every item in the browser menu that is currently marked for removal. Creates another change-management browser whose menu is identical to the currently displayed menu.
enced in the browser menu and is not marked for removal.
Spawn all forget
Deletes every item in the browser menu that is currently marked for removal.
Q Commands that operate on a single item d o it
Evaluates the item that is currently selected, whether or not it is marked for removal. The item is either an expression, or a class or method definition.
472 System Backup, Crash Recovery, and Cleanup
remove it restore it
spawn it
Marks the item that is currently selected for removal. Unmarks the item that is currently selected and that is marked for removal. Creates a message-selector browser for the current definition in the system of the item that is selected. You can then visually compare to see if the changes file specifies a different definition, and then you can decide which one you prefer to use.
Commands that check for conflicts check conflicts
A prompter appears in which you type the name of a changes file. When you choose the yellow button command accept, an analysis is done of all the items in the changemanagement browser menu to see if any of them refer to the same message selector, but specify different definitions. Any conflicts found are written on the file.
check with system
A prompter appears in which you type the name of a changes file. When you choose the yellow button command accept, an analysis is done of all the items in the changemanagement browser menu to see if any of them refer to the same message selector, but specify different definitions. Also checks to see if any item specifies a different definition than is currently in the system. Any conflicts found are written on the file.
If you start with an empty change-management browser, and choose the yellow button command display system changes, you access the same information that is shown in the change-set browser. If you start with an empty change-management browser, and choose the yellow button command recover last changes, you access the same information that is shown if you evaluate the expression ChangeListView recover. Assume that the internal change set is the one displayed in Figure 23.2, and that you have not made a snapshot since you made these changes. Choose the yellow button command recover last changes in the top subview of the change-management browser. The information shown exceeds that available from the change-set browser (Figures 23.8a and 23.8b). In addition to method definitions (such as FinancialHistory spend:for:), the change-management menu contains • class defines (for example, define FinancialHistory) • expression executions (for example, dolt self spend: 100 for: ' rent') • category changes
473 23.3 The System Audit Trail
Small talk-SO.change5.j|| dolt 'From S m a l i t a i k - 8 0 , version 2, of ... define Fi η a n c i a IH i s t ο ry Fi η a η c i a ΙΗ i s t ο ry s ρ end: f ο r: Fi η a η c ia ΙΗ i s t ο ry rep ο rt Fi η a η c i a ΙΗ i s t ο ry t ο t a IS pent Fo r: Fi η a η c i a ΙΗ i s t ο ry s e 11 n i t i a IB a I a n c e: show file
file
Figure 23.8a
show cateqor;·, class
tyρe
category I selector
same
ODD I:-:::;:·:;:;::;;:;:;:::;:;:;:;:::;:;:::;:;:::;:;:::;:-:::;:::::;:::::;:·:::::::::;:•:::;:::;:;:::::;:;:•:;:;:: Sma II talk- iO.chanqes.liiiii;!; ;:;:::;:;:::;:;:|:;:;:::;:;:::;:::::;:::::;:::;i;:::::i:·:;:::::;:::::;:::::;:·:::;:::::::::;:::::::::::::::::: Die tio nan. print C n: dolt self spend: 100 for : 'rent' dolt self spend: 75 for: 'food' dolt self spend: 50 for: 'trips' dolt self report dolt sma IItalk c h a n g e s asSortedC :.llect ... ; : ; : ; : ; : ; : ; : ; : > ; : ; : ; : : : ; : : : ; : ; : : : ; : ; : : : ; : ; : : : ; : ; : : : ; : • : : : : : : : ; : ; : • : : : : : : : ; : • : : : : : : : : : ; : : : : : ; : : : : : • : • : ; : • ; : : ; : •
Β FI
Figure 23.8b
show category
shov • file file
tv P.
|
class
rao
category 1 selector 1
same
474 System Backup, Crash Recovery, and Cleanup These "special" changes are shown indented from the left margin of the list menu. Π Display Options and Filters The menu items in the second part of the change-management browser let you obtain more information. Click the red button while the cursor is in the rectangle labeled show file (Figure 23.9). This "turns on" the option to see which changes file the list items came from, useful if you have accessed multiple files. Click again to "turn off" this option.
smalltalk-SO.changes, I;! Ό rn a 1113.1 k - ο υ, c h a n g e s,)dolt 'From s m a l l t a l k - u u , version id, of ;' 8 m a 11t a I k- 8 0, c h a n g e; d «fine Fi η a n c i a IH i s t ο ry ' S m a 111 a I k - ο U, c h a η g e s,' ΐ F i η a η c i a ΙΗ i s t o r y s ρ e η d: f ο r: ' S m a 111 a I k - 8 0 .change;,) F i η a n c i a IH is t ο r y r e ρ ο r t ' S rn a 111 a I k - 8 0. c h a η g e s,) F i η a no i a ΙΗ i s t ο r y t ο t a. IS ρ e η t F ο r: (S rn a 111 a. Ik.- 8 0. c h a η g e s,) Fin a η c i a ΙΗ i s t ο r y s e 11 n i t i a. IB a Ian c e: show c a t e g o r y file
Figure 23.9
1
*y P Q
1 ^
category
select ο r
100 000 Now click the red button while the cursor is in the rectangle labeled show category (Figure 23.10). This "turns on" the option to see the category of the methods referenced in the list menu. The remaining menu items provide a filter on what information should be shown in the list menu. Choosing one of the items "turns on" the filter indicated. The filters only have meaning if an item in the top subview is selected. The basic idea is to remove any items from the menu that do not match exactly the filtered part of the selected item. An item is made up of at most five parts: file name, type (dolt, define, method, and so on), class, message category, and message selector. Thus the possible attributes for filtering items are
I
475 23.3 The System Audit Trail
Small t a l k - SO, c ha rig es. () dolt 'From Small talk- 80, version 2, of () define FinancialHistory (t r'a η 5 a c t ί ο η s) Fi η a η c ί a IH i s t ο ry s ρ end: f ο r: (ί η q u i r i e 5) F i η a n c i a IH i s t ο r y report (i η q υ i ri e s ί Fi η a n c i a ΙΗ ί ί t ο ry t ο t a IS pent Fo r: (ρ r i ν ate') F i η a. η c i a ΙΗ i s t ο r y ζ e ΐ Ι η i t ί a IB a I a n c e: show file file
Figure 23.10
type
100 000 file
The changes file for all items should be the same as that of the selected item.
type
The type (evaluation, class definition, method definition) of all items should be the same as that of the selected item.
class
The class to which the items refer should be the same as that of the selected item.
category
The class category for each item should be the same as that of the selected item.
selector
The message selector of each item should be the same as that of the selected item.
same
All items should be precisely the same (this makes it possible to see multiple entries that are possibly conflicting definitions).
Suppose the menu item selected is a method definition and you choose the filter labeled type (Figure 23.11). Then the only items displayed in the menu are method definitions. Choose the filter type again, that is, "turn off" this filter. Suppose the menu item class is FinancialHistory and you choose the filter labeled class (Figure 23.12). Then the only items displayed in the menu are method definitions for FinancialHistory. You can explore the change-management browser further by marking and unmarking items for removal, and spawning related browsers using the appropriate commands in the yellow button menu.
476 _ _ System Backup, Crash Recovery, and Cleanup
b m 31113.1 k- ο υ, c hi a. n g e s. 'transactions) FinancialHistory spend:for: i η q u i ri e s) Fi η a. n c i a IH i 5t ο ry re ρ ο r t i η q u i ri e s ) Fi η a. n c i a IH i s ΐ ο ry ΐ ο ΐ a IS pent Fo r: ρ ri ν a. t e) Fin a η c i a ΙΗ i s ΐ ο ry s e 11 n i t i a IΒ a I a n c e: in." l a n c e c r e a t i o n ) Financial History class i nit ia IB a lance: inquiries) FinancialHistory report show file file
iateqory I
selector
I
same
spend: amount f ο r :Ύ e a s ο η "Spend amount for the reason given, decrementing the available cash on hand,"
Figure 23.11
100 000
expenditures a t : reason put: (self totalSpentFor: reason) + amount. cashOnHa.nd *- cashOnHand - amount
brnalltalk-bU.changes. d e f i η e Fin a η c i a ΙΗ ί s t ο r v1 transactions) FinancialHistory spendifor: inquiries) FinancialHistory r e p o r t i η q υ i r i e s) Fin a η c i a ΙΗ i s t ο r ν t ο t a 15 ρ e η t F ο r: ρ ri ν a. t e) Fi η 3. η c i a ΙΗ i s t ο ry s e 11 n i t i a IB a. I a n c e: inquiries) Financie.IHistory r e p o r t show file file spend: amount for": r e a s ο η "Spend amount for t h e reason given, d e c r e m e n t i n g the a v a i l a b l e cash on hand,"
Figure 23.12
100 000
expenditures a t : reason p u t : (ssif t o t a l S p e n t F o r : reason) + a m ο u η t. cashOnHand - ca s h u n Η a n d - amount
477 23.4 Creating a "Clean" System
Conflict Resolution
Detecting conflicts between method definitions is described in the paper "Managing the Evolution of a Smalltalk-80 System" by Steve Putz in the Smalltalk-80 implementation considerations book, Smalltalk-80: Bits of History, Words of Advice. The main reason conflict checking is needed is that work done by different people can affect the same methods. When work is done in parallel by several programmers, each programmer submits a changes file. It is not possible to file-in each changes file, one at a time, since one file may undo (redo improperly) the definition provided in another file. A conflict analysis routine is available in the system to examine code files and report the ways in which they conflict. Whenever two or more submissions define the same method, all conflicting definitions are appended to a "conflict report" file. It is then up to the programmers involved to determine how to resolve the conflicts, often by writing a new method that merges the needed functionalities. Conflict checking is requested by choosing one of two commands in the yellow button menu of the top subview of the change-management browser, conflicts among the menu items (check conflicts) or conflicts among the menu items and the system methods (check with system). For each command, you must type a file name in a prompter and choose the yellow button command accept. The file is then created. When the analysis is completed, you can use the file list view to examine the file. Missing from the audit trail (changes file) is date stamping on each entry, back linking to alternative definitions, and "person" stamping (that is, associating the name of the person who made the change), all of which can be useful when multiple persons participate in a project and share the use of an image and its changes file.
23.4 Creating a "Clean" System
If you use an image long enough, modifying system methods and adding new methods, you will eventually create a very large audit trail on your changes file. Most methods will be referenced in this changes file rather than in the sources file. When you then want to create a new system release, you will want to clean up your system so that it has the following characteristics. 1. All up-to-date definitions and methods are on the sources file. 2. The changes file is empty (except for the date and version comment). 3. You are assured that there are no unreferenced objects in the system image.
478 System Backup, Crash Recovery, and Cleanup Even when you are not releasing a new system, you may want to keep your changes file as short as possible. The changes file grows to include definitions for methods that override one another. That is, in the process of programming, you might try several versions of a method before settling on a definition. Each version will appear in the changes file, even though the system compiled method only refers to the last one. The most common "clean up" needed, then, is to condense your personal copy of the changes file, leaving the shared sources file untouched.
Creating a New System Image
A new system image is created by a process we call "doing a VMemwrite," that is, writing a new file that contains an image of the virtual system. The idea of a VMem-write is to trace every accessible object, and write a copy of each object onto a disk image. This determines which objects are actually being used and which are occupying space unnecessarily. The end result is to release any possible free space. Moreover, the resulting clone can pe started up and run, just like a snapshot. Some care is taken so that objects appear in the same order in the data space as they do in the system object table. This aspect of the implementation is covered in Part Four of the book Smalltalk-80: The Language and its Implementation.
The second purpose of a VMem-write is to allow any transformation of the system, such as changing the bytecode set or the structure of a class of objects (for example, the representation of floating-point numbers), which can not be done while you are interacting with the system. To initiate the VMem-write, evaluate the expression SystemTracer writeClone In this case, no special transformations will be carried out. The result is a new image written on a file named clone.im which you rename according to whatever system version naming conventions you have. One of the common transformations done with the VMem-write is to clamp out (remove) classes. You might want to do this because your system includes some applications that you wish to remove in order to have a version of the system that takes up less space. Or you might want to do this because you have developed an alternative implementation of an application and had been using both versions until the new one was stable; now you are ready to eliminate the original version. For the most part, you do not need a VMem-write to eliminate classes from
479 23.4 Creating a "Clean" System
your system since you can use the command remove in the class-names subview of a system browser. To clamp out classes, use a different message to SystemTracer. SystemTracer writeCloneWithout: aSetOfClasses
where the argument is an instance of Set whose elements are the classes that you do want to clamp out. The method associated with SystemTracer writeCloneWithout: will do two things. 1. Remove the class references from the system dictionary, Smalltalk. 2. Remove any class categories that become empty as a result of removing the classes. This means that the running image (the image from which you create the VMem-write) will be irreparably modified, so make sure that you have backed up your system image appropriately. Before doing any VMem-write, you might want to clamp out some message protocols for various classes. You do this directly by using the system browser to remove the protocols from the class. Again, this means that you are irreparably modifying the source image, so make sure that you have backed up your system image. Included in the description of class SystemTracer is a clamping mechanism called winnowing. Its purpose is to cull out all unreferenced messages, with the exception of ones you specifically name. Then, based on these deletions, cull out more, and so on. This is basically a first attempt to understand how to drop out major parts of the system. You can explore this feature by examining the comment and the method associated with the message winnow: in class SystemTracer.
Static Checks
Before creating a new image, you will want to check for things that might be wrong with the current image. The system includes class Checker that contains many messages that support your doing static checks of the system. You can check for messages implemented but not sent by any method (this situation might be acceptable if the message is there for semantic completeness of a protocol), and messages sent but not implemented (this suggests a possible runtime error). An important thing to check for is the existence of obsolete classes. Send Checker the message obsoleteClasses. The response is an OrderedCollection of the classes in the system that have been made obsolete. A class becomes obsolete when it is removed from the system, but one or more instances exist. To remove the obsolete class, all instances must be deleted. You remove the instances by finding all references to them and setting the references to nil.
480 System Backup, Crash Recovery, and Cleanup
Condensing Sources and Changes
The purpose of condensing changes is to remove all redundancies from the changes file. Condensing also removes all logged information other than one copy of the changed method definitions. To condense your changes file, evaluate the expression Smalltalk condenseChanges
In the System Transcript, you can observe the name of each class and message category as the source code for each is written onto the new changes file. The final name of the changes file is the name of the current one. If you want to merge your changes file into a sources file, evaluate an expression of the form Smalltalk newSourceFile: prefixName without: aCollectionOfClasses
where prefixName is a String representing the file name. Evaluating this expression creates two files whose names are prefixName.sources and prefixName.changes
The second file is empty except for the date and version comment. Besides writing the method definitions, all class definitions are written and everything is alphabetically ordered, by class name, on the sources file. An example of using this expression is Smalltalk newSourceFile: Smalltalk versionName without: Array new
in which the prefix file name is the current system version name and no classes are omitted.
23.5 Version Management
In his paper, Steve Putz also describes a special application he developed for managing the evolution of the Smalltalk-80 system. The system he describes supports users in reporting bugs and bug fixes, and in
481 23.5 Version Management
suggesting or announcing new applications (we call these "goodies"). The central feature of this development support system is a networkbased database containing information about the past and proposed changes to the system, as well as bug reports and application announcements. The database also contains documentation about system changes and released system versions. This version management system is considered experimental and was not provided as a part of the standard Smalltalk-80 system. A summary of the version handler is provided here; if you are interested in more details about this area you should examine the Putz paper. The interface to the system version handler is done using a special browser. There are actually three different browsers that filter information from the database of system changes and system release documentation: a version browser, a new feature browser, and a bug report browser. The version browser supports you in examining the changes introduced in the currently selected version of the system, the changes submitted that were not included in the version release, remaining known bugs, and the known bugs for which fixes can be retrieved but are not as yet incorporated into the system. Figure 23.13a shows an example of a version browser. It consists of two subviews, one is a list menu and the other displays text. Each of the four kinds of information that you
;:;:!:::!::Η:ί:::!ΗΗ:!:!:!:!:·:ί:;:!:!:;:!:ί:;:|:ί:!:!: ;r;r-:;j;:;j;:;:;;:;r;if::;;F:;:;;::;:;:;:;:;:;:;::;;F::;:
ρ |
V28 Small talk-80 Irnaqe Version: ST80V28 V'29 Smalltalk-80 Imaqe Version: ST80V29 V3O Smalltalk-80 Image Version: ST80V30
|
Τ
I l l l Date: 18 Apr 83 15:57:26 PST Ijiiiililiiij From-Version: V30 HI; ΠΙΐΗΐϊϋίΙΪ changes: C409, C4 10, C4 11, C4 12, C4 14, C4 15, C4 16, C4 17 ;||! Subject: Smalltalk-80 Image Verson: ST80V3 1 ΠΗΐΠΜπΠ F r o m : P u t z |!!|| image-file: ST80V3 1 | ; | | sources-file: ST80V30 ;i|iijijii;ii virtual-macine: EB |||!| know η-bugs: 6 1, Β 16, B27, 852,656, B59, B62, Β72 Β 100, Β 1 15, υ ||| Illllll 8 129, Β 137, Β 166, Β 169, Β 170, Β 172, Β 176, Β 182, Β 183, Β 184, liiiiiiiii;:; Β 188, Β 193, Β 195, Β 196, Β 197, Β 198, Β 199, Β 2 00, Β20 1, Β202, iiiiiji!:; Ι|Ι|!ΐί;||!ί| Β203, Β204, Β205, Β206, Β207, Β208
Figure 23.13a
1001 0001
i;i;;:i::ji;i changes: ;;!;:|;;Η!|; -- Double-clicking now works better when quotes are involved,
lijiiiiiij
482 System Backup, Crash Recovery, and Cleanup
can access is presented in a menu associated with the top subview of the version browser (Figure 23.13b). Choosing a menu item creates a browser that presents the requested information. Recent Smalltalk-80 Versions m
Smalltalk-: 30 V29 :Smalltalk-: 30 V 3 0 :Smalltalk-; 30 V31 Srnallta!k-80
Irn Ξι. qe Irn He Irn a _^e Ima qe
8 JV 23 8 JV 2 browse c h c η q e s ST 8 S version: brow se b j g s Kfel 1•H browse buq fixes b "owse r e ν·,·' qoodie. 1 = re trie ·,· e v e rsion p: Τ
V Qt'z- ο ri: ν ers ο η: V ers ο Γι:
ST ST
1 ^^^^^
J1 ^
0 a t Ρ 1 R Δ η r F:": 15 Frorn- version: '•·, 3 0 c h a n J\QS: C:4U9 04 1 c 1 1, 0 4 12, r 4 14 , C4 15 0 4 16, 0 4 17 S u b j e et: Smallt 3lk-F j Irn a /infz· o ri: 3 Τ 8 JV3 1 From: P u t ; i rn a g e-file: STS J •·..·• 3 so υ re es-file: ST8 0 V" 31j v i r t u . -ι I - rn seine: Ε Β V-. η ο ν·/η-bugs: Β , Β 1 B59, Β62, B72 , Β 100 , EM 15, B2" \ Ε £/"' Β 5 Β 129 , Β 137, Β 166, Ε; 1 6 9 Ε: 7 0 , EM 7 "', Β176, EM 32, EM 8 3 , Β 184, Β Ibb , Β 193, Β 195, b 1 9 6 b y 7, b 1 - i ; - i, Β 199, Ει J U, B20 1, B202, BvijL- , B2U4, Β - U -•, d U n. U 7, b 2 Ji; •
Figure 23.13b
010
Ohan ^es: - - D o u b l e - -lickir
no·
orks be t t er ν • h e ri q υj t e s •brid i n •/dived,
Figure 23.14 shows a browser that was created by asking to see all the known bugs in the currently selected version of the system. It was obtained by choosing yellow button command browse bugs in the top view of the version browser. The numbers in the menu subview of the "bugs" browser correspond to those cross-referenced in the version handler. Browsers are available that are used for submitting bug reports or fixes or goodies, and for composing a new system version. The bug report and bug fix browser is a modification of an electronic mail retrieval browser. The user can browse for a reported bug and then fill out a form that documents the proposed fix (Figure 23.15). The bug fix is then added to the database when the user selects the command accept in the yellow button menu of the browser. If a bug fix is selected in the report browser, a cross reference from the bug fix to the bug report is stored so that someone browsing bug reports will be told about the proposed bug fix.
23.5
483 Version Management
B59 Bug Report: Defining new class causes search of system B72 Bug Report: scrolling due to output into system transcript Β 10 0 Β υ g R e ρ ο r t: Τ e χ t 5 e I e c t i ο η Β υ g browse fixes' Β 115 Β υ g R e ρ ο r ΐ: dependent s ma y c ο η t a ί η d u ρ I i c a t submit fb Β 12 9 Β u q R e ρ ο r t: Β r ο vv s e r D i s ρ I a y G litches A
Figure 23.14
Oio
Date: 16 July 1982 9:09:07 am From-Version: V 19 Subject; Bug Report: Inspectors on large objects From: hag me. η η I inspected a fairly large object. It was a sequencer! collection of about 120 entries. Around 60 of the entries in the collection were not selectable from the inspector, This is very bad since it is natural to assume t h a t w h a t you see in an inspector is all there is to an object, Smalltalk is very good about not having special rules for different cases (also called "yeah, but ,,," in most systems), I think t h a t this ' f e a t u r e ' should be changed to either: ( I ) do the right thing, (2) put 3 dots in the left pane (..,) or (3) have a yellow b u t t o n select to get to see the full object. I think t h a t (1) is the correct solution and is in keeping w i t h the rest of the system,
^ c t : Bug Fix: c t r l - c and browser scrollbars From: Υ our Μ a me S ο u re e-File: [File η e ] < S m all t a I k£; 0 S u ρ ρ ο r"t > f i I e Ν a. m e, s t bugs-fixed: Β 1 DescriptionOfF/x
Figure 23.15
000
484 System Backup, Crash Recovery, and Cleanup
Figure 23.16 is a browser for "goodies" that was obtained by choosing the yellow button command browse new goodies in the top view of the version browser. "Goodies" are new ideas for the system, new applications or user interface changes or performance improvements, that have been contributed by any user who has access to the network-based database for the Smalltalk-80 system. If you are interested in using a goodie, you choose a command from the yellow button menu of the goodie browser so that class descriptions for the goodie are filed into your system. Each goodie description is associated with a file of class descriptions that implement the goodie.
C334 Goodie: Even Better Move and Collapse C34 3 C352 C367 C 4 13
G ο ο d i e: f i ν e - ρ a. η e d b r ο w s e r Goodie: Icon;, f o r collapsed v i e w s b r o w s e source file si Goodie: F a s t e r recompiling o f el as·; b r o w s e bugs fixed file in changes Gi ο ο die: Pre 11 i e r c I o c k
d a t e : 16 February 19bL-i 6 : 0 4 : 4 c prn from-version: V 2 8 s u b j e c t : Goodie: Even B e t t e r M o v e and Collapse from: F'utz s ο u re e - f i I e: < S rn a 111 a \ k'3 0 S u ρ ρ ο r t > Ε ν e η Β e 11 e r M ο ν e - s ρ, s t In a n s w e r t o Glenn's last t w o goodies, here is a version w h i c h makes a Form o u t of t h e w i n d o w and lets t h e user d r a g a r o u n d t h e w i n d o w w i t h t h e mouse.
Figure 23.16
010
N o t e t h a t this is w h a t Laura, does in t h e Rehearsal World, Also n o t e t h a t on m e m o r y - p o o r machines (e.g. Dolphin) this ma.y e x c e r c i s e t h e c o m p a c t o r or run t h e s y s t e m o u t o f memory, I suppose a t e s t could be p u t in w h i c h checks core L e f t f i r s t , b u t v i r t u a l memory w o u l d be a. much nicer solution.
New system versions are created by choosing items from a menu of submitted bug fixes and goodies in order to compose a list of changes that should be checked for conflicts and then incorporated into a running system. Bug fixes might conflict with one another in the sense that they change the same methods. The system conflict analyzer can be used to check for any such conflicts, leaving it up to you to resolve the differences. This approach to version management was successfully used in managing the refinement of the Smalltalk-80 system.
Appendix 1 Financial History Views and Controllers This appendix contains a complete listing of three class descriptions: FinancialHistory, FinancialHistoryView, and FinancialHistoryController. These three classes implement a simple model for monitoring income and expenditures (FinancialHistory), viewing that model as two bar charts (BarChartView and FinancialHistoryView), and interacting with that model in order to increase income or expenditures. A sample screen image of the bar charts is shown in Figure A.I in which the yellow button menu is showing. The menu has two items: spend and receive. Choosing either one of these brings up a prompter in which the user specifies the reason why money is being spent or received (Figure A.2). Once a reason is specified, a prompter appears in which to specify the amount of money (Figure A.3). The appropriate bar chart is then updated (Figure A.4). If the reason given is new (Figures A.5, A.6, and A. 7), the bar chart is reorganized to display the new bar. The view is created as a standard system view so that the blue button menu is available (Figure A.8). This example is given to you as another sample of how to use the classes View and Controller that are provided in the Smalltalk-80 system as basic building blocks with which to construct interactive graphical interfaces. It is unlike the examples in Chapter 15 in that a different approach to creating the yellow button menu is used. The format for presentation is that of a class implementation description as introduced in the book Smalltalk-80: The Language and its Implementation. The example makes use of prompters (instances of the class FilllnTheBlank). The first class, FinancialHistory, was described in Chapters 17, 18, and 19. This version of the class adds access to the instance variable incomes as well as expenditures. Note the addition of the changed mes485
486 Financial History Views and Controllers
-inancial Historv
pend receive
rent food utilities Figure A.I
010
Receive from what'
Figure A.2
pay
interest
487 Financial History Views and Controllers
financial History
Figure A.3
Figure A.4
488 Financial History Views and Controllers
ReceivQ from what?
rent
Figure A.5
food utilities
pay
interest
:iav
interest
000 1300 600
400 200
How much from qift ? 500
Figure A.6
BOO
rent
489 Financial History Views and Controllers
"inancial History
Figure A.7
under move frame collapse close
rent
Figure A.8
food utilities
490 Financial History Views and Controllers
sages to receive:from: and spend:for: to notify any objects dependent on these variables that there was a change. class name superclass instance variable names category class methods
FinancialHistory Object ' cashOnHand incomes expenditures ' ' Financial Tools '
instance creation initialBalance: amount " Create a FinancialHistory with amount as the initial balance. " Tsuper new setlnitialBalance: amount new " Create a FinancialHistory with 0 as the initial balance." Tsuper new setlnitialBalance: 0 instance methods
transactions receive: amount from: source " Receive amount of money from source, and increment cash on hand by this amount." incomes at: source put: (self totalReceivedFrom: source) + amount. cashOnHand «- cashOnHand + amount, incomes changed
spend: amount for: reason " Spend amount of money for reason and decrement cash on hand by this amount." expenditures at: reason put: (self totalSpentFor: reason) + amount. cashOnHand «- cashOnHand - amount, expenditures changed inquiries
cashOnHand " Answer the current balance? " τ cashOnHand
expenditures " Answer the Dictionary of expenditures." t expenditures
491 Financial History Views and Controllers
incomes " Answer the Dictionary of incomes. " τ incomes
totalReceivedFrom: source " Answer the total amount of money received from source. " (incomes includesKey: source) ifTrue: [ Τ incomes at: source] ifFalse: [TO]
totalSpentFor: reason " Answer the total amount of money spent for reason." (expenditures includesKey: reason) ifTrue: [texpenditures at: reason] ifFalse: [TO] private
setlnitialBalance: amount " Initialize the instance variables. " cashOnHand «- amount, incomes — Dictionary new. expenditures «- Dictionary new
You can create an instance of Financial History, and spend and receive money, by evaluating the following expressions. Smalltalk at: #HouseholdFinances put: nil. HouseholdFinances «- Financial History initialBalance: 1560. HouseholdFinances spend: 700 for: ' rent'. HouseholdFinances spend: 78.53 for: ' food'. HouseholdFinances receive: 820 from: ' pay'. HouseholdFinances receive: 22.15 from: ' interest'. HouseholdFinances spend: 135.65 for: ' utilities'. HouseholdFinances spend: 146.14 for: ' f o o d ' . In the above expressions, HouseholdFinances is created as a global variable. Then the instance of the class FinancialHistory is created and several messages are sent to it. At this point, if we were to view the incomes and expenditures of HouseholdFinances as two bar charts, we would see the image shown in Figure A.I. The next step is to create a special bar-chart viewing mechanism for a Dictionary. Class BarChartView has no variables declared.
492 Financial History Views and Controllers class name superclass category instance methods
BarChartView View ' Financial Tools '
accessing
barFrame " Answer the area available for the bars. The response to insetDisplayBox is implemented in the superclass View." tself insetDisplayBox insetBy: (50 @ 10 corner: 10 @ 50)
labelCount "Answer the number of labels needed. Although this is specified as a constant, it should probably be an instance variable. " T5
maximumValue "Answer the maximum value on the y-axis. The message model, whose response must be a kind of Dictionary, is implemented in the superclass View. " | total | total self model values inject: 0 into: [ :sum :value |sum + value]. t(total / self labelCount roundTo: self units) * self labelCount
numberOfColumns " Answer the number of bars needed in the chart. " Tself model size
positionFor: value "Answer the relative position within the chart for value. " tself barFrame height * value / self maximumValue
units "Answer the unit increment of values used to compute the ticks on the y-axis. Although this is a constant, it probably should be an instance variable.. " Π 00 displaying displayView " Display the x- and y-axis labels and then the bars. This message is
493 Financial History Views and Controllers sent from View's implementation of the message display, in which the View requests display of each of its subparts. " self displayXLabels. self displayYLabels. self displayBars
displayXLabels | corner| corner <- self barFrame bottomLeft. self model keys do: [ :key | key displayAt: corner + (self barFrame width - 20 / (self numberOfColumns * 2) @20) - (key asDisplayText boundingBox extent / 2). corner
displayYLabels | count label increment | count <- self labelCount. increment <- self maximumValue / count. label - 0. count timesRepeat: [label printString displayAt: (self barFrame bottomLeft - (35 @ ((self positionFor: label)+ 7))). label <- label + increment]
displayBars | height bar corner | corner <- self barFrame bottomLeft. self model keys do: [ -key | height - self positionFor: (self model at: key), bar
update: aParameter " Some values have changed, so update the view. " self display
494 Financial History Views and Controllers
You can try out the bar chart viewing mechanism on any Dictionary with numeric values whose keys are instances of String or Text. In particular, try the following expressions in order to see the bar chart for the HouseholdFinances expenditures. | aBarChartView | aBarChartView «- BarChartView new. aBarChartView model: HouseholdFinances expenditures. aBarChartView window: Rectangle fromUser. aBarChartView insideColor: Form white. aBarChartView borderWidth: 2. aBarChartView display
The third statement asks you to specify the screen area in which the bar chart will be displayed. The expression Rectangle fromUser means that you are to designate a rectangular area. Make it large enough to accommodate the text for all the keys in the Dictionary, HouseHoldFinances expenditures. The definition of a BarChart is faulty in several ways. First, the units are designated as 100. If all the values of the Dictionary are less than 100, then an error (division by zero) will occur when you try to display the bar chart. Second, the number of labels (labelCount) is specified as 5, true in our example, but probably not all the time. You can improve the class description by parameterizing these values. To see the problem, try the following expressions. | aDict aBarChartView | aDict «- Dictionary new. aDict at: ' 1 'put: 10. aDict at: ' 2 ' put: 20. aDict at: ' 3 ' put: 30. aDict at: ' 4 ' put: 40. aDict at: ' 5 ' put: 50. aDict at: ' 6 ' put: 60. aBarChartView «- BarChartView new. aBarChartView model: aDict. aBarChartView window: Rectangle fromUser. aBarChartView insideColor: Form white. aBarChartView borderWidth: 2. aBarChartView display
The next step is to create a viewing mechanism for FinancialHistory that groups together the bar charts for incomes and expenditures within a single view. Class Financial History View specifies a view that consists of
495 Financial History Views and Controllers two views, the bar charts. It is a subclass of View, and adds no new variables. class name superclass category class methods
FinancialHistoryView View ' Financial Tools'
instance creation open: aFHModel " Create a standard system view of the FinancialHistory, aFHModel, that consists of two bar charts, one for expenditures and one for income. " | aFHView aBCView topView | " First create the top view that is a standard system view and provides the blue button menu for moving, framing, collapsing, and closing the view." topView <- StandardSystemView new. topView model: aFHModel. topView borderWidth: 2. topView insideColor: Form lightGray. topView label: ' Financial History'. " Create the FinancialHistoryView and make it fill the top view. " aFHView «- self new model: aFHModel. topView addSubView: aFHView. " Create the bar chart of expenditures and place it inside the FinancialHistoryView. Its interior should be white, its border 2 pixels wide, and it should have no user interaction independent of the one provided for FinancialHistoryView." aBCView — BarChartView new model: aFHModel expenditures. aBCView window: (10® 10 extent: 35@35). aBCView insideColor: Form white. aBCView borderWidth: 2. aBCView controller: NoController new. aFHView addSubView: aBCView. " Create the bar chart of incomes similar to that of the one for expenditures. " aBCView <- BarChartView new model: aFHModel incomes. aBCView window: (55@10 extent: 35®35). aBCView insideColor: Form white. aBCView borderWidth: 2. aBCView controller: NoController new. aFHView addSubView: aBCView.
496 Financial History Views and Controllers " Standard system views have standard system controllers that respond to the message open by asking the user to designate the rectangular area in which the view will be displayed." topView controller open instance methods
controller access defaultControllerClass " Answer the name of the class that provides the usual user interaction for this class." τ FinancialHistoryController
Note that the last method, defaultControllerClass, specifies that the user interaction for a FinancialHistoryView is handled by a FinancialHistoryController. You will not be able to add this method to the system until you declare the class FinancialHistoryController, as follows. A MouseMenuController is a system controller that provides the mechanisms for storing and retrieving pop-up menus. FinancialHistoryController is like this class except it provides a particular yellow button menu for items spend and receive. When these items are chosen, the corresponding messages, spend and receive, will be sent to the FinancialHistoryController. class name superclass class variable names category class methods
FinancialHistoryController MouseMenuController ' FHYellowButtonMenu FHYellowButtonMessages' ' Financial Tools '
class initialization initialize " Specify the yellow button menu items and actions. "
FHYellowButtonMessages - #(spend receive). FHYellowButtonMenu «PopUpMenu labels: 'spend receive'
497 Financial History Views and Controllers instance methods initialize-release initialize " Make certain that the instance knows about the menu items. " super initialize. self initializeYellowButtonMenu
menu messages
receive " Ask what amount is being received for what reason, and then update the FinancialHistory accordingly. Use the prompter, a FillinTheBlank, to obtain the needed information. (Note that comma is the String concatenation operator. Also note that no special care is being taken to make sure that the number is a positive one—perhaps you might want to add this condition.)"
| spendOn amount | spendOn *- FillinTheBlank request: ' Receive from what?'. spendOn isEmpty ifTrue: [Tself]. amount «- FillinTheBlank request: ' How much from ' , spendOn,' ? ' . amount isEmpty ifTrue: [Tself]. amount — Number readFrom: (ReadStream on: amount). model receive: amount from: spendOn
spend " Ask what amount is being spent for what reason, and then update the FinancialHistory accordingly. Use the prompter, a FillinTheBlank, to obtain the needed information. (Note that comma is the String concatenation operator. Also note that no special care is being taken to make sure that the number is a positive one—perhaps you might want to add this condition.). " | spendOn amount | spendOn <- FillinTheBlank request: ' Spend for what?'. spendOn isEmpty ifTrue: [Tself]. amount - FillinTheBlank request: ' How much for ' , spendOn,' ? ' . amount isEmpty ifTrue: [Tself]. amount <- Number readFrom: (ReadStream on: amount). model spend: amount for: spendOn
498 Financial History Views and Controllers
control defaults isControlActive " sensor, declared as an instance variable in the superclass Controller, is an instance of InputSensor. It can determine the cursor location, and whether mouse buttons or keys on the keyboard are pressed." τ super isControlActive & sensor blueButtonPressed not private initializeYellowButtonMenu " yellowButtonMenu:yellowButtonMessages: is specified in the superclass MouseMenuController; the response is to create the correct menu image and corresponding messages." self yellowButtonMenu: FHYellowButtonMenu yellowButtonMessages: FHYellowButtonMessages
After defining the class FinancialHistoryController, remember to define the message defaultControllerClass in FinancialHistoryView. To initialize the menus before trying to use the class, you evaluate the expression FinancialHistoryController initialize You can then evaluate FinancialHistoryView open: HouseholdFinances in order to try out the user interface as shown in the figures. These classes are offered as initial ideas with which you can play. There are several modifications to try. Make certain that only the part of the view that needs to redisplay does whenever there is a change. Try to change the user interface to the bar chart so that you can point to a bar and "drag" it up in order to change the value in the Dictionary (that is, instead of providing NoController as the user interface to a BarChartView, create a new controller that handles the user red button actions). Be careful that the scale on the axis of the chart is appropriate for such action. Try to create viewing mechanisms that display pie charts or graphs instead of bar charts. Make a view in which the expenditures or incomes are shown as both graphs and bar charts, and make certain that both views update correctly when the Dictionary changes.
Appendix 2 Smalltalk-80 Software Development Do's and Don'ts
As a software engineer at Xerox Special Information Systems (XSIS), I am responsible for the ongoing support of the Xerox 1100 Scientific Information Processor Smalltalk-80 System. I participate in the development of Smalltalk-80 virtual machine implementations and virtual image releases. In the past, as a member of the Publishing Systems Department, I developed an experimental interactive page make-up editor with the Smalltalk-76 programming environment (precursor to the Smalltalk-80 system). I also observed and supported the development of two major applications with the Smalltalk-80 system at XSIS. As a result of these experiences, I would like to share with you several important "do's and don'ts" for Smalltalk-80 software development. Π First and foremost: Do read the documentation. Perhaps this statement should be printed on the cover, or even emblazoned on your machine, rather than located at the end of a book that you have probably just finished reading! Early Smalltalk-76 and Smalltalk-80 development projects at XSIS began with seasoned software engineers who had no prior experience with Smalltalk programming, nor did they have offline documentation. Their success in the beginning should be credited to their programming background, but also to the user support provided in the Smalltalk-80 environment. However, several system features and techniques that would have simplified their development efforts were not discovered until well into the projects, when early versions of this book became available. Change management, system tracing, and performance analysis were several useful tools that they had not discovered on their own. 499
500 Appendix 2
Q Before embarking on your first Smalltalk-80 development project: Do understand the basic language concepts. The basic language concepts are outlined in Chapter 5 of this book and summarized in Section 5.5. This recommendation may seem obvious, but it is so easy to develop software by copying and editing existing system code. Often the new programmer, anxious to use the system, starts programming before learning about the object and message-sending metaphor of the Smalltalk-80 language. Q Whether your development team consists of one person, or many: Do understand and use the change manager. The change manager is one of the most important tools for software development in the Smalltalk-80 environment. It is described in Section 23.2 "The System Change Set" and Section 23.3 "The System Audit Trail." This facility tracks and helps you to maintain all changes you have made to the system. It allows you to selectively browse them, remove them, incorporate them into another version of the system, check for conflicts, and prepare the changes for release to other members of the development team or to end users. Should a system crash occur, the change manager can recover all changes since the system's state was last saved. [ ] i i the outset of a project involving two or more programmers: Do assign a member of the team to be the version manager. Refer to Section 23.5 "Version Management" to learn about the kinds of tools the version manager might create. The responsibilities of the version manager consist of collecting and cataloging code files submitted by all members of the team, periodically building a new system image incorporating all submitted code files, and releasing the image for use by the team. The version manager stores the current release and all code files for that release in a central place, allowing team members read access, and disallowing write access for anyone except the version manager. Much of this process can be automated. Q In the course of software development: Do not modify system classes when subclassing is possible. It is more desirable to subclass an existing system class, using multiple inheritance When appropriate, rather than to modify system class definitions and behavior. There are two reasons for this. The first relates to managing changes. It is more difficult to track changes to system classes than it is to track changes that are concentrated in a single, user-defined subclass of a system class. The second reason involves compatibility with new system releases. It is more difficult to incorporate your software into a new version of the Smalltalk-80 image if your system changes conflict with changes in the new version, that are needed to improve the basic system rather than a specific application. There are indeed cases when it
501
Appendix 2 is appropriate to change system classes, but it is important to understand the potential impact before doing so. Q Do browse the system to find existing features that can be exploited in your applications. Refer to Part Two of this book "How to Find Information in the System." Unlike traditional programming, about 90% of Smalltalk-80 programming typically consists of making relatively small modifications and enhancements to existing code. The programmer searches the system for classes and methods that demonstrate behavior similar to the desired functionality of the new application, and then extends the behavior through the mechanism of subclassing or copying and editing. Graphical interactive applications are created by extending the existing hierarchy of classes that support viewing and controlling behaviors. Q Do not be at the mercy of the system; if you do not like something, change it. Several XSIS customers comment about various details of the system that they would prefer to have changed. Examples are the size of the system font or the functionality of a particular system view or the way a particular method is written. My response to these comments is to remind the customer that the system is designed so that they can easily and freely change it. This concept is a new one to many people because traditional programming environments carefully protect system code from modification. The Smalltalk-80 environment treats system code and user code alike. Mold the system into an environment that suits your needs. The researchers designed the system so that they could experiment with creating new systems; the changeability of all of the system parts is a necessary attribute of this research. The easy changeability of system code, of course, means that you can make changes that crash the system. Therefore, make certain you have saved your work before trying something that changes system code that you might not fully understand. For creating applications that can not be changed by the end user, you might want to try mechanisms for protecting the code—for example, hiding the existence of certain classes from your users. Q Do share your creative 'goodies" with a friend. Your creativity will inevitably result in novel yet natural extensions to the environment. Michael Malcolm, an XSIS software engineer, did not like the way text selection was handled originally, so he cleverly enhanced the old technique and shared it with other Xerox Smalltalk-80 programmers. It was such a useful extension to the system that it was incorporated into all subsequent releases. This "goodie" became part of the system because he packaged it so that other programmers could easily file it into their images for experimentation, and because he announced its existence over the Xerox electronic network to ensure its broad availability.
502 Appendix 2
The Smalltalk-80 environment provides such a rich set of interactive software development tools that the programmer's time shifts from finding the path of least resistance through a complex web of system utilities to actually writing code. With this system, my belief that programming is an art is at last fulfilled. And finally: Do have fun! Prepared by Evelyn Van Orden Xerox Special Information Systems
System Workspace Index
Expression in System Workspace
Explanation and Reference
Create File System
This is the code needed to initialize a file system when the Smalltalk-80 system is first installed. The example is for the Xerox Alto file system.
Disk - AltoFileDirectory new
The global variable Disk references the file directory.
SourceFiles — Array new: 2
The global variable SourceFiles references the sources and changes files. See Section 22.4.
SourceFiles at: 1 put: (FileStream oldFileNamed: 'Smalltalk-80.sources')
The first element of SourceFiles is a FileStream on the sources file. See Sections 1.2 and 22.4.
SourceFiles at: 2 put: (FileStream oldFileNamed: 'Smalltalk-80.changes')
The second element of SourceFiles is a FileStream on the changes file. See Sections 1.2 and 22.4.
(SourceFiles at: 1) readonly
The sources file should be read-only. The system VM-writer is used to update the sources file. See Section 23.4. 503
504 System Workspace Index SourceFiles - Disk - nil
When these variables are nil, it is assumed that no sources can be accessed so that the decompiler should be used when browsing class descriptions. In addition, no changes file (audit trail) will be maintained. See Section 22.4.
Files
Information about external files is found in Chapters 22 and 23.
(FileStream oldFileNamed: 'fileName.st') fileln
Read the class descriptions and expressions stored on a file. See Section 22.3.
(FileStream fileNamed: 'fileName.st') fileOutChanges
The information maintained in the system change set can be stored on a file. See Section 23.2.
(FileStream fileNamed: 'fileName.st') edit
A view of the contents of a file can be created. See Section 22.2.
Changes
While you are working in a project (Chapter 4), a set of class and method changes is maintained. See Section 23.2.
Smalltalk noChanges
Initialize the set of changes. See Section 23.2.
(FileStream fileNamed: 'fileName.st') fileOutChangesFor: Stream
Changed definitions for a particular class can be filed out. See Section 23.2.
Stream removeFromChanges
References in the set of changes to a particular class can be removed. See Section 23.2.
Smalltalk browseChangedMessages
View the current changes in a browser. See Section 23.2.
Smalltalk changes asSortedCollection
View the current changes as a SortedCollection. See Section 23.2.
505 System Workspace Index Inquiry
The system supports your making many inquiries about the relationships among the objects. See Chapters 8, 9, and 10.
Smalltalk browseAlllmplementorsOf: #messageSelector
Like the menu item implementors in the message-selector subview of a browser. See Section 10.4.
Smalltalk browseAIICallsOn: #messageSelector
Like the menu item senders in the message-selector subview of a browser. See Sections 10.4 and 12.2.
Collection browseAIICallsOn: #timesRepeat:
Like the menu item senders in the message-selector subview of a browser, except constrained to the methods of a particular class. See Section 10.4.
Smalltalk browseAIICallsOn: # a t : and: #at:put:
Like the menu item senders in the message-selector subview of a browser, except accesses information about two message selectors rather than just one. See Section 10.4.
Smalltalk browseAIICallsOn: (Smalltalk associationAt: #Transcript)
Obtain a message-set browser that provides access to all methods in the system that reference a particular literal found in Smalltalk. See Section 10.4.
Smalltalk browseAIICallsOn: (TextConstants associationAt: #Centered)
Obtain a message-set browser that provides access to all methods in the system that reference a particular literal found in the pool dictionary TextConstants. See Section 10.4.
Smalltalk browseAIICallsOn: (Object classPool associationAt: # DependentsFields)
Obtain a message-set browser that provides access to all methods in the system that reference a particular literal found in one of Object's pool dictionaries. See Section 10.4.
Smalltalk browseAIISelect: [:meth meth numLiterals > 40]
Obtain a message-set browser on all methods such that, when the block is
506 System Workspace Index evaluated with the method as its argument, the result is true. See Section 10.4. FileStream instanceCount
Answer the number of instances of the class that exist in the system.
FormView alllnstances inspect
Create an inspector on the collection of all the instances of the class that exist in the system. Inspectors are presented in Chapter 8.
Undeclared inspect
Create an inspector on the pool of variables that the user tried to reference but that were found to be undeclared. See Section 6.1.
Dependents
Access objects that have been declared as dependents of one another (for example, a particular view is dependent on the object it views).
(Object classPool at: #DependentsFields) keys
DependentsFields is a Dictionary, a class variable of Object in which knowledge about object dependencies is stored. It is sometimes referred to as a "soft field." Its keys are the objects that have other objects dependent on them.
(Object classPool at: # DependentsFields) keysDo: [:each (each isKindOf: TextCollector) ifTrue: [each release]]
This is a useful expression for searching for a particular kind of object, here instances of TextCollector, that may have dependents. If there are dependents, they are sent the message release, that is, break the dependency. This is needed to make certain that undesired cyclic pointers are destroyed.
Globals
Names in Smalltalk other than classes and pools.
507 System Workspace Index Disk
A FileDirectory.
Sensor
An InputSensor. See example uses in Section 6.4 and Chapter 21.
Display
A DisplayScreen. See example uses in Sections 6.4 and 11.3.
ScheduledControllers
A ControlManager. See Section 2.5.
Transcript
A TextCollector. See Section 3.4.
Processor
This single instance of ProcessorScheduler coordinates the use of the physical processor by all processes requiring service.
SourceFiles
Array of FileStreams. See Section 22.4.
SystemOrganization
A SystemOrganizer, the basis of the hierarchical indexing for the system browser. See Chapter 9.
Pool Dictionaries Smalltalk
A SystemDictionary in which reference to all global variables, especially classes, is maintained. See Sections 6.1 and 10.4.
AltoFilePool
A pool dictionary known to AltoFile, AltoFileDirectory, and AltoFilePage.
FilePool
A pool dictionary known to ExternalStream, File, FileDirectory, and FilePage.
TextConstants
A pool dictionary known to ArrayedCollection, CharacterBlock, CharacterBlockScanner, CharacterScanner, CompositionScanner, DisplayScanner, DisplayText, Paragraph, ParagraphEditor, StrikeFont, TextLinelnterval, and TextStyle.
508 System Workspace Index Undeclared
A global dictionary in which to store the names of variables the user improperly tries to reference. See Section 6.1»
Smalltalk removeKey: #GlobalName
Remove a particular entry from the Dictionary Smalltalk.
Smalltalk declare: #GlobalName from: Undeclared
Add a particular entry from Undeclared to Smalltalk, effectively declaring the variable. See Section 6.1.
Transcript show. (3 + 4) printString; cr
Display the result of evaluating 3 + 4 in the System Transcript, Transcript. See Section 3.4.
Smalltalk frills: false
For slow machines, some of the automatic selection that happens in the debugger and browsers can be turned off by evaluating this expression.
Display
Evaluate expressions to Display or to DisplayScreen to change the display area used by the system.
DisplayScreen displayExtent: 1024 @808
Make the screen 1024 dots wide by 808 dots high. See Section 6.4.
DisplayScreen displayExtent: 640® 480
Make the screen 640 dots wide by 480 dots high. See Section 6.4.
Measurements
Take some measurements of the amount of space being used in the system. Evaluating these expressions typically takes a long time.
Smalltalk core
Amount of memory—number of objects, number of words of data. See Section 20.3.
Smalltalk oopsLeft
Number of objects that can still be created. See Section 20.3.
Smalltalk coreLeft
Amount of memory left for your programming. See Section 20.3.
509 System Workspace Index MethodContext instanceCount
Instances of MethodContext hold all the dynamic state associated with the execution of a CompiledMethod. In addition to their inherited state, this includes the receiver, a method, and temporary space in the variable part of the context. This expression is a way to determine the number of interrupted executions of a method that are known to the system.
Disk freePages
Amount of space left on your disk for files.
Time millisecondsToRun: [SystemOrganization printString]
Length of time in milliseconds it takes to evaluate the expression(s) in the block.
MessageTally spyOn: [Behavior compileAII]
Do an analysis of the performance of the expression(s) in the block. See Chapter 14.
(FileStream oldFileNamed: 'spy.results') edit
Examine the file on which a performance analysis has been stored.
Change Management and Crash Recovery
Recovering from system crashes is discussed in Chapter 23.
ChangeListView open
Create a blank view for change recovery. See Section 23.3.
ChangeListView openOn: (ChangeList new recoverFile: (FileStream oldFileNamed: ' fileName.st'))
Create a view for change recovery from a given file. See Section 23.3.
ChangeListView recover
After a crash, create a view to browse changes since the last snapshot. See Section 23.3.
Smalltalk recover: 5000
Copy the most recent 5000 characters to the file named ST80.recent and open an edit window on it. See Section 23.3.
Menu Command Index
abort 238, 355, 358 accept to compile 24, 26, 100-101, 164, 166, 174, 179, 200, 221, 238, 242, 244, 252, 256, 280, 284, 303, 308, 310, 320, 324, 333, 346, 364, 369, 373, 389, 392, 399, 402, 406, 416, 452 to store 37, 48, 134, 147, 156, 173-175, 180, 225-227, 233, 249, 254, 265, 268, 272, 278, 284, 303, 331, 339, 395, 439-440, 444, 448, 455, 460, 462, 471, 477 add category 173, 272 add field 156 add protocol 178, 225-227, 278, 284, 308 again 57, 58-59, 61, 179 browser 42, 43, 162, 218 cancel 37, 131, 134, 180, 282, 444 category 475 check conflicts 472, 477 check with system 472, 477 class 163, 168, 218, 278, 364, 475 class refs 175, 213, 303, 324 class var 355 class var refs 175, 211 close 20, 40, 48, 72, 132, 146, 238, 261, 379, 426, 455 collapse 48 comment 174, 249, 303, 324 continue 23 copy 58, 60-61, 179 copy name 440 correct 379 correct it 355, 356, 358, 367 cut 58, 60-62, 179 510
debug 160, 383, 388, 416 definition 174, 252, 333 display system changes 471, 472 do all 471 do it 106, 107-110, 170, 179, 182, 220, 238, 258, 260, 282, 288, 354, 364, 416, 422, 471 edit all 173, 272 enter 42,68 exit project 42, 68 explain 180,182 file 475 file in 440, 452, 455, 471 file it in 443, 450, 468 file list 42, 439 file out 172, 173, 177, 178, 292, 373, 432-433, 451, 471 forget 471 format 179,244 frame 47,48 full stack 390, 392 get 443,444 get contents 440, 442, 444 global 355 hierarchy 174, 200, 203-204 implementors 179,199, 200, 204, 392 ingpect 146, 152, 284, 404, 422 instance 163,168, 224, 284, 321 inst var refs 174, 211 messages 179, 201, 203, 392 move 47, 179, 264 no 20, 36, 40, 48,126 paste 58, 61,179 put 443, 444, 452, 455
511 Menu Command Index
print it 106, 110, 154, 167, 179, 244, 364, 376, 386, 396, 403, 406 print out 172, 174, 177, 178, 435 proceed 159, 379, 390, 392, 396, 409, 416, 451, 453, 455 proceed as is 320, 358, 364, 369 project 42, 68, 329 protocols 174, 225, 230 quit 22, 40, 43 Quit, without saving 23 references 157 recover last changes 471, 472 remove 156, 173, 175, 178, 179, 201, 227, 230, 272, 442, 479 remove all 471 remove it 472 rename 173, 175, 178, 227, 254, 272, 442, 446 restart 392,399 restore all 471 restore display 42, 138, 170, 238 restore it 472 same 475
save
24, 43, 460
Save, then quit selector 475
23, 24, 462
send 392, 416, 417, 426 senders 178, 196, 200, 204, 392 show category 474 show file 474
spawn 172, 174, 178, 180, 187-191 spawn all 471 spawn hierarchy 174, 192-193 spawn it 472 step 392,416-428 system transcript 43, 65, 68, 204 system workspace
temp type
43, 44
355,362 475
undeclared 355 under 47
undo update
58, 62, 175, 179 173,270
workspace 16, 35, 43, 68, 244 yes 20, 36, 40, 48, 72, 126, 173, 360, 367, 379
Subject Index
t 92, 104 Abelson, Hal 138 ActionMenu 301, 315, 333, 338, 346 activation stack 386 argument name 102 array 84, 103, 148-150, 218, 224-233, 237, 243, 274 assignment 89, 91, 103 audit trail 467-468, 477 binary message expression see message, binary Bit Editor 31, 49 123, 131-139 block 87, 90, 91-92, 103, 208 argument 90-91, 103 BlockContext 384 see also block Boolean 91, 192, 313, 321, 325, 384 boot button 14 breakpoints 402-408,416 browser 32, 35, 42, 49, 52, 99-101, 161-193, 218-244, 249, 252, 274, 381 see also Menu Command spawn; message-set browser; Project Browser; Protocol Browser Browser 167 button 11, 12 see also standard system view blue 20, 26, 47 red 16, 20, 23, 26, 34, 52, 122-124, 133, 474 yellow 16, 18, 22, 24, 26, 40 caret 52,66 see also text, selection 512
cascaded message expression see message, cascaded categories 100-101, 162-169, 173 class 268-272,274 message 174, 178, 179, 225-233, 278-280 ChangeListView 158, 409, 472 changes 68, 101-102 see also file, changes change set 462-463, 467 classes 98 Change-Management Browser 467-477 Change-Set Browser 465-467, 472 character 80-84, 148-150, 384 Checker 479 class 77-79, 102 see also browser; categories, class; class editing; variable, class abstract 203-204 definition 252 description 93-95, 100 hierarchy 162, 164, 174, 176 name 173-175,254-260 obsolete 479 references 175 template 100,274-278 class browser 188 see also browser class editing adding new methods 233-248 adding protocol 224-232 categories 268-272 creating new class 274-278 modifying comments 249-250
513 Subject Index
class editing (cont.) modifying existing methods 218-223 renaming see renaming variable declarations 260-268 class hierarchy browser 192-193 see also browser; hierarchy click 12, 13, 26, 258, 261 see also button; text, selection double 12, 26, 53-56 single 52 CodeView 301, 306-310, 315, 316, 323, 325, 329, 337 Collection 192, 203, 384 Commander 279-293 commands see menu comments 85, 162, 166, 174, 196, 203, 249-250 compactor 31 compilation 98-101, 116, 221, 393 see also Menu Command accept complimenting 32 see also highlighting confirmer 20, 27, 31, 36, 37, 40, 48, 49, 72, 173, 175, 178, 230, 356, 360, 367, 379 conflict analysis 471-472, 477 control keys see text editor control manager 7, 27, 46-47, 413 control structures 91-92, 372 conditional selection 61, 91 conditional repetition 91 Controller 98 cursor 4, 23, 27, 30-31, 34, 39, 40, 49, 108 crossHair 133 eyeglasses 134,444 execute 26, 108, 261 hourglass 26, 108, 444 writing pen 444, 452 Cursor 31, 32, 134, 137, 221, 267 data structures 95-96 debugger 160, 383, 386-400, 416, 450-451, 455 debugging 65, 107, 147, 385-400 see also debugger; inspector; notifier decompilation 98, 458 delimiters see text editor Dictionary 156-157 diSessa, Andrea * 138 Display 114-116, 237-240, 261 display screen 2, 4, 7-10, 15, 122-126 see also graphics Display Object 136, 261 DisplayScreen 114-115
documentation 111, 141-142, 162, 168, 481 see also browser; categories; comments; examples; explanations; menu; spelling correction; System Workspace; templates draw through 52, 66 see also text, selection editing class descriptions see class editing pictures see Bit Editor; Form Editor programs see class editing text see text editor error handler 411-414 see also debugger; notifier escape key 110 see also text, selection examples in the book see Commander; FinancialHistory; Project Browser; Protocol Browser in the system 168-171, 218-220 execution interrupt 101-102, 116, 159-160, 401-414 evaluation within context of 396-400 notification of 375-384 explanations 180, 182-186 expression 80, 103 see also block; variable; message evaluation 18, 105-117, 452 see also Menu Command do it and print it file 4, 14-15, 96, 102, 126, 172, 431-458 changes 14, 24, 26, 27, 100, 457-458, 467-468 see also changes command 24 condensing sources and changes 480 formats 435-436 see also retrieving information; saving information image 14, 24, 26, 27, 464, 477-478 see also snapshot remove 442 rename 442, 446-448 run 14,24 sources 14, 27, 100, 256, 457-458 see also SourceFiles file list browser 42, 49, 321, 439-449, 451
514
Subject Index FileStream
293, 436, 439, 448, 450, 465
FilllnTheBlank
filters
344
474-475
FinancialHistory 472
364-388, 402, 406, 451, 463-464,
flashing 20, 26, 30, 34, 37, 49 font 61-63 see also text Form 31, 120-123, 126-127, 131-135, 139, 220-223, 237, 240, 261, 422-424 opaque 135, 139 Form Editor 31, 49, 120-131 formatting 179, 244 global variables see variable, global graphics see Bit Editor; Form; Form Editor; user interface; view gridding 124-130 see also Form Editor hardware systems 4-6, 100 hierarchy see class, hierarchy; Class Hierarchy Browser; Protocol Browser; Menu Command hierarchy and spawn hierarchy highlighting 12, 30 text 32, 52, 57 see also text, selection identifier see selector; variable, name image file see file, image inspector 107-108, 144-158, 261-266, 282, 284-288, 355, 376, 386, 390, 403 see also debugger for dictionaries 156-157, 406 instance 77-79, 102 variable see variable, instance interface 76-77, 102-103 see also user interface interrupt system control-c 62, 159-160 keyboard 4, 7, 122-123, 134-135 keys 7 keyword message expression 6, 103 see also message, keyword Krasner, Glenn 435 literal 80, 87, 103, 208 Masinter, L. 354
menu 2, 13, 18, 27, 49 cascaded 64 commands 104 fixed 35, 36, 163 iconic 120-123, 139 list 36, 37, 163 locked 37 pop-up 35, 36, 40, 201 selection 12, 36, 122 system see System Menu message 1, 27, 76, 102, 162 argument 103 binary 86-88, 103 cascaded 89, 103 expression 85-89 implementors see Menu Command implementors keyword 86-88, 103 pattern 102 protocol see interface receiver see receiver selector see selector senders see Menu Command senders unary 86-88, 104 Message Browser 190-191 see also browser Message Category Browser 189-190 see also browser message-send 107, 116, 376, 388-390, 409, 418-420 message-set browser 157, 175, 178-179, 196-213, 256, 260, 392, 465 MessageTally 296 metaclass 94-95 method 1, 27, 76, 92-93, 101, 102, 196 see also message-set browsr literals 208 primitive 103 template 101, 233, 280 value of 92 mouse 4, 11, 27, 52 see also buttons images 12, 13 nil 109, 116, 301, 355, 396, 479 notifier 159-160, 238, 252, 261, 376, 383, 386-388, 402, 404, 409, 411, 416 number 81 object 1, 27, 76-80, 103
515 Subject Index Object 95, 156, 192, 301, 310, 319, 321, 323, 388, 436 object-oriented programming 1 OrderedCollection 203,204,240-241,310, 326,479 Papert, Seymour 138 paragraph see text; text editor parsing 88 pattern match 439, 446 Pen 136-139, 164, 175-176, 180, 218-223, 354, 360, 416-424 see also Commander performance 296-297 Point 144, 146, 360 pointing device see mouse pool variable see variable, pool PopUpMenu 346
see also menu, pop-up press 12,26 see also button printing 172, 406, 436 see also Menu Command print out program editor see browser programming environment 76, 99-102, 354 project 2, 32, 42, 49, 67-73, 463 Project 337-344 Project Browser 73, 322-339, 342-346 prompter 24-27, 41, 49, 126, 173, 175, 178, 179, 225-227, 254, 265, 278, 344, 446-448, 460-462, 471, 477 see also FilllnTheBlank
scheduled 41 unscheduled 41 protocol see categories, message; interface Protocol Browser 189, 300-322 pseudo-variable 95 see also self; super Putz, Steve 477, 480 quitting see stopping procedures receiver 85-86, 103 context of 394-395 recovery 175, 468 see also changes; Change Management browser; snapshot Rectangle 109-110,114,144-145,151-155, 237,249 rectangle designation 16, 34, 123-124, 133, 146, 180
release 12,26 see also buttons renaming see also Menu Command rename class name 174-175, 254-260 message selector 200-201 retrieving information see also recovery pictures 126 programs 376, 442, 450-457, 465 text 442, 443 run file see file, run running out of space 409-411 runtime errors 375-384 saving information 24, 43, 373, 411 see also snapshot pictures 126, 132 programs 172-174, 177-178, 292-293, 432-435 system changes 462-465 system state see snapshot ScreenController 346,348 scroll bar 11, 27, 37-40, 46, 108 scrolling 38-40 see also scroll bar for selection 56 selection see menu, selection; text, selection; view, selection SelectionlnListView 301, 306-310, 316, 323, 325 selector 85-86, 103, 201 self 95, 104, 116, 145, 147, 282, 367, 394 Sensor 115-117, 261, 422 SequenceableCollection 204, 218, 240-244 Set 203 side comments 4 single-step execution 392, 415-428 see also debugging Smalltalk 94, 108-110, 117, 136, 156, 206-208, 260, 296-297, 355, 411, 463-465, 480 snapshot 23, 26, 411, 460-462, 467-468 SourceFiles 458,460 sources see file, sources spawning 180 see also Menu Command spawn spelling correction 107, 353-362, 367, 381 spy 296-297 standard system view 7, 28, 32,37,46,127,133,439 blue button menu 47-48 StandardSystemController 307
516
Subject Index StandardSystemView 301, 306-309, 337 start up procedures 13, 457-458 static checks 479 stopping procedures 22,43 StrikeFont 62 see also font String 83, 241, 244, 310, 329, 339, 396 subclass 78, 95, 103, 256 see also class subview 7, 27 super 95, 104, 156 superclass 95, 103 see also class specifying name of 252-254 symbol 83, 104 syntax errors 101, 106-107, 238, 363-374, 450-457 syntax error view 451-457 system classes 95-99, 103 image 478-479 see also file, image sources 142 System Browser see browser System Category Browser 187 see also browser System Menu 37, 40-43, 65, 346-349 System Transcript 32, 43, 49, 65, 196, 199, 204, 252, 256, 266, 355, 392, 406, 412-414, 450, 466, 480 System Workspace 32, 43, 45, 49, 111-112, 117, 206, 260, 411, 450 SystemDictionary see Smalltalk SystemTracer 99, 478-479 Teitelman, W. 354 templates 100-101, 106, 111, 162-166, 233, 279 see also System Workspace temporary variable see variable, temporary testing 244, 282, 292 see also debugger; inspector text buffer 60 copy 52, 57-58, 60-61 delete 52, 57-59 font 52 insert 57-58 move 60-61 paste 58 replace 52,57-58 search 59, 61 selection 18, 30, 52-58, 63, 66, 159-160 Text 329
text collector 65 see also System Transcript text editor 6, 51-66, 163, 179 see also text buffer 58 commands 57-64, 179-180 control keys 61 delimiters 54,63-64 TextStyle 62-63 see also font; text editor, control keys TextView 316 transcript see System Transcript Transcript 65, 112, 117, 406 typing 46 see also keyboard; keys; text editor unary message expression see message, unary Undeclared 110,355 UndefinedObject 355 user interface 1, 76, 158, 300-301 classes 98, 158 components 15 user interrupts 409-410 variable see also class definition; inspector class 94, 102, 175, 266-267, 355 global 65, 68, 93-94, 102, 109, 111, 355 instance 94, 102, 174, 260-266 name 85, 104 pooled 94, 103, 267-268 pseudo-variable 104, 372 references 211 temporary 92-94, 103, 220, 354, 355, 426 undeclared 107, 110, 252 version management 480-483 view 2, 7, 11, 37, 48, 68, 337 see also browser; inspector active 11, 28, 45 close 20 collapsed 7, 28 deselection 45 inactive 32,45 overlapping 47 selection 30, 32, 45 View 98, 136, 158, 307 visual cues 2, 37 window see view workspace 16, 18-21, 32, 34, 36, 43, 45, 46, 52, 106, 261, 292, 354, 376, 409 see also System Transcript; System Workspace Xerox 14, 23-24, 154, 172-174, 177, 432
Halt encountered. UndefinedObject(Object)>>halt UndefinedObject>>Dolt CompilQr>>Qvaluate:in:to:notifying:ifFail: CodeController>>dolt CodeController(TextController)>>yellowButtonActivity
| See Chapters 18 and 20 Syntax Error! User Interrupt! NotifierView(StandardSystemView)>>labelDispla NotifierView(StandardSystemView)>>containsPo Not if ierGontroller(Cont roller)) >viewHa5Cursor NotifierController(Mou5eMenuController)>>contrc align: aPointi with: aPoint2 "Answer a new Quadrangle translated by aPoint2 - aPointi."
"Answer the message selector for changing the displayed text," | newSelector | newSelector *• Expression expected ->*selectedClass compile: aText
See Section 22.3 t Quadrangle region: (super translateBy: aPoint2 aPoint 1) borderWidth: borderWidth borderColor: borderColor insideColor: insideColor
Quadrangle self origin corner borderW borderCt insideCo
0@0 corner: 92@20
See Chapters 19 and 21 Q@0 corner: origin 92@20 corner border border
0@20 a Point
See Chapter 8
J5t| File List
stSO.rQCQnt.j 'instance creation7! opQnOn: aBrowser withControllQr: a Controller "aController may contain changes that haven't already been accepted" | topView tQxtView | (topView *• self model: aBrowser label: 'System Browser' minimumSize: 200@150)
filenarne-or-pattern
-new
See Section 22.2 and 23.3
See Section 22.2
Smalltalk-80. changes,] () dolt 'From Smalltalk-80 of 18 April 19 .,, (instance creation) Form class byteScanLineOfWidt (instance creation) Form class readAISFile: i (instance creation) Form class readFrom: j (converting) ByteArray runDecodeFrom: ! (converting) ByteArray runEncodeOn: example \ j show file "Draws a spiral in gray j with a pen that is 4 pixels \ ·; file | type J class categor>jselector| same wide." i | bic | | bic *• Pen new, I bic mask: Form lightGray. I bic defaultNib: 4. | bic combinationRule: Form I under, I
Changed Messages
See Section 23.2
!
i
See Section 23.3
Smalltalk-80: The Interactive Programming Environment provides an introduction to the user interface to the Smalltalk-80 system — a personal, integrated, interactive programming environment. The book Is divided into five parts. Part One introduces the user interface to the Smalltalk-80 system. Part Two is an explanation of the support provided for finding information about objects that exist in the Smalltalk-80 system. Part Three provides an illustrated description of how to explore the class descriptions available In the system, and of how to use the editors for implementing new class descriptions. Part Four presents the support available for finding and correcting errors, while Part Five introduces access to external files and such system housekeeping support as crash recovery and change management. The book is written to encourage specific practice and exploration. A brief introduction to the Smalltalk-80 language is also provided in order to explain the ways in which the user interface components provide access to the language components. For a more in-depth understanding of the language; readers may use this book In conjunction with Smalltalk-80; The Language and Its Implementation, by Adele Goldberg and David Robson (Addison-Wesley, 1983), which includes reference material for the system classes. Adele Goldberg is Manager of the Software Concepts Group at the Xerox Palo Alto Research Center (PARC), the team responsible for the development of the Smalltalk-80 system. This is one of a series of four books documenting the history, development, nature; and implementation of this revolutionary programming environment. Other books in the Addison-Weslev Smalltalk-80 Series Smalltalk-80: The Language and its Implementation (11371-6) Smaljtalk-80: Bits of History, Words of Advice (11669-3) Smalltalk-80: Creating a User Interface and Graphical Applications (11370-8)
Τ«»Γ»*1
Π _ "Ϊ Π Ί
Τ t
"1 «Ί "η