newton toolkit user’s guide

202
Newton T oolkit User ’s Guide

Upload: pablomarx

Post on 03-Jan-2016

36 views

Category:

Documents


3 download

DESCRIPTION

Newton Toolkit User’s Guide

TRANSCRIPT

Page 1: Newton Toolkit User’s Guide

ð

Newton Toolkit User’s Guide

Page 2: Newton Toolkit User’s Guide

ð Apple Computer, Inc.© 1993, 1994, Apple Computer, Inc.All rights reserved. No part of this publication or the software described in it may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Computer, Inc., except in the normal use of the software or to make a backup copy of the software. The same proprietary and copyright notices must be affixed to any permitted copies as were affixed to the original. This exception does not allow copies to be made for others, whether or not sold, but all of the material purchased (with all backup copies) may be sold, given, or loaned to another person. Under the law, copying includes translating into another language or format. You may use the software on any computer owned by you, but extra copies cannot be made for this purpose. Printed in the United States of America.The Apple logo is a registered trademark of Apple Computer, Inc. Use of the “keyboard” Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws.No licenses, express or implied, are granted with respect to any of the technology described in this book. Apple retains all intellectual property rights associated with the technology described in this book.This book is intended to assist application developers to develop applications only for licensed Newton platforms.

Apple Computer, Inc.20525 Mariani AvenueCupertino, CA 95014408-996-1010

Apple, the Apple logo, APDA, AppleLink, AppleTalk, LaserWriter, Macintosh, Macintosh Quadra, MPW, Newton, and PowerBook are trademarks of Apple Computer, Inc., registered in the United States and other countries.Finder, the light bulb logo, MessagePad, NewtonScript, Newton Toolkit, PowerBook Duo, ResEdit, and System 7 are trademarks of Apple Computer, Inc.Adobe Illustrator and PostScript are trademarks of Adobe Systems Incorporated, which may be registered in certain jurisdictions.FrameMaker is a registered trademark of Frame Technology Corporation.Helvetica and Palatino are registered trademarks of Linotype Company.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation.

Simultaneously published in the United States and Canada.

LIMITED WARRANTY ON MEDIA AND REPLACEMENT

If you discover physical defects in the manual or in the media on which a software product is distributed, APDA will replace the media or manual at no charge to you provided you return the item to be replaced with proof of purchase to APDA.

ALL IMPLIED WARRANTIES ON THIS MANUAL, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE LIMITED IN DURATION TO NINETY (90) DAYS FROM THE DATE OF THE ORIGINAL RETAIL PURCHASE OF THIS PRODUCT.

Even though Apple has reviewed this manual, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS MANUAL, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS MANUAL IS SOLD “AS IS,” AND YOU, THE PURCHASER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY.

IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS MANUAL, even if advised of the possibility of such damages.

THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty.

Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.

Page 3: Newton Toolkit User’s Guide

iii

Contents

Figures and Tables xi

Preface About This Book xv

How to Use This Book xvRelated Books xviConventions xviiDeveloper Products and Support xviii

Chapter 1 Installation and Setup 1-1

System Requirements 1-1Installing NTK on the Macintosh 1-2Installing the Toolkit App on the Newton 1-5

Making the Physical Connection 1-5Downloading the Toolkit App 1-6

Making an Inspector Connection 1-7Troubleshooting 1-8

Chapter 2 Programming With theNewton Toolkit 2-1

Terms and Concepts 2-1The NTK Development Process 2-3

Page 4: Newton Toolkit User’s Guide

iv

Chapter 3 A Quick Tour of NTK 3-1

Starting Up NTK 3-2Setting Up a New Project 3-2Starting a Layout File and Adding It to the Project 3-4Laying Out Application Elements 3-8Customizing a View Template 3-9

Editing a Slot 3-10Adding a Slot 3-11

Building and Downloading a Package 3-12Adding a Linked Layout 3-14

Laying Out a Linked View 3-15Linking a Layout 3-17Adding a Button That Displays the View 3-19

Defining Your Own Proto 3-21Laying Out a Proto and Adding It to the Palette 3-21Using Your Proto 3-25

Using the Inspector 3-26Connecting the Inspector 3-26Executing Commands 3-27Looking at a Frame 3-28Making a Change in a Running Application 3-30

Chapter 4 Using the Newton Toolkit 4-1

Setting Up a Project 4-1Project File 4-2Project Settings 4-3

Application Settings 4-4Package Settings 4-6

Setting Preferences 4-7Layout Settings 4-8Browser Settings 4-9

View List 4-9Slot List 4-9

Page 5: Newton Toolkit User’s Guide

v

Text Views 4-10Packages 4-10Connection 4-10Heap Sizes in KBytes 4-11

Laying Out Views 4-11Drawing, Resizing, and Moving Views 4-13

Drawing a View 4-13Resizing a View 4-16Moving a View 4-17Aligning Views 4-18Ordering Views 4-19

Previewing 4-20Naming and Declaring Views 4-21Linking Multiple Layouts 4-22Creating User Protos 4-24Creating Print Format Templates 4-25

Browsing and Editing Templates 4-26Browsing Templates 4-26Adding Slots 4-28Editing Slots 4-30Editing Text 4-32Searching for Text in Files 4-34

Listing Instances of a String 4-34Finding Instances of a String 4-35Finding Slots in the Hierarchy 4-36

Building a Project 4-37The Build Environment 4-38

Global Data File 4-38Project Data File 4-39Variables and Constants 4-42Platform Files 4-43Resources 4-44Merging Packages 4-45

Page 6: Newton Toolkit User’s Guide

vi

Build Sequences 4-46Building an Application 4-47Building a Book 4-48Processing a Layout File 4-49

Error Messages 4-50Debugging With the Inspector 4-51

Chapter 5 Debugging 5-1

The Inspector 5-1Using the Inspector 5-2

Tracing the Execution of Your Application 5-3Examining the Program Stack 5-5Breaking for Exceptions 5-8Displaying Information in the Inspector Window 5-9Printing Objects in the Inspector Window 5-10Displaying the Contents of a View 5-13Displaying the View Hierarchy 5-14

Debugging Variables 5-15Debugging Functions 5-16Newton Programming Problems and Tips 5-23

Common Programming Problems 5-23Setting the Wrong Slot Value 5-23Forgetting to Set the Function Return Value 5-25Producing Memory Problems With Dangling Frame

References 5-26Generating Unexpected Comparison Results With nil

Values 5-26Using nil in Expressions 5-28Trying to Resize a Read-Only Object 5-29Text Is Not Drawing 5-30Problems with Printing and Communications 5-31

Page 7: Newton Toolkit User’s Guide

vii

Programming Tips for Debugging 5-31Using Global Variables to Examine Exceptions 5-32Maintaining View State 5-32Accessing the Parent of a View 5-33Peeking Into a Soup 5-33

Chapter 6 NTK Commands 6-1

File Menu 6-1New Layout (Command-N) 6-1New Proto Template (Command-T) 6-2New Print Format 6-2Open (Command-O) 6-2Link Layout 6-2Close (Command-W) 6-3Save (Command-S) 6-3Save As 6-3Save a Copy In 6-4Save All (Command-M) 6-4Revert 6-4Page Setup 6-4Print One 6-5Print (Command-P) 6-5Quit (Command-Q) 6-5

Edit Menu 6-5Undo (Command-Z) 6-5Cut (Command-X) 6-6Copy (Command-C) 6-6Paste (Command-V) 6-6Clear 6-6Duplicate (Command-D) 6-6Select All (Command-A) 6-6Select Hierarchy 6-7Select in Layout 6-7

Page 8: Newton Toolkit User’s Guide

viii

List (Command-L) 6-7Find (Command-F) 6-8Find Next (Command-G) 6-8Find Inherited 6-9Newt Screen Shot 6-9Show Clipboard 6-9Toolkit Preferences 6-9

Project Menu 6-10New Project 6-11Open Project 6-11Add Window 6-11Add File 6-11Add Book File 6-11Remove File 6-11Update File 6-12Build Package (Command-1) 6-12Download Package (Command-2) 6-12Export Package to Text 6-12Install Toolkit App 6-13Mark as Main Layout 6-13Project Data 6-13Settings 6-13

Layout Menu 6-14Layout Size 6-15Autogrid On 6-15Set Grid 6-15Move To Front 6-16Move To Back 6-16Move Forward 6-16Move Backward 6-17Alignment 6-17Align 6-18Preview (Command-Y) 6-18

Page 9: Newton Toolkit User’s Guide

ix

Browser Menu 6-18Template Info (Command-I) 6-18New Slot (Command-=) 6-19Rename Slot 6-20Delete Slot 6-20Templates by Type 6-20Templates by Hierarchy 6-21Slots by Name 6-21Slots by Type 6-21Show Slot Values 6-21Apply (Command-E) 6-21Revert 6-21

Window Menu 6-22Open Inspector 6-22Connect Inspector (Command-K) 6-22New Browser (Command-B) 6-22

Appendix A Keyboard Text-Editing Commands A-1

Setting the Insertion Point A-1Selecting Text A-3Manipulating Selected Text A-4Deleting Text A-5Changing the Meaning of the Next Keystroke A-6

Appendix B Keyboard Shortcuts B-1

Page 10: Newton Toolkit User’s Guide

x

Appendix C Using Resources C-1

About Resources C-1Resource Files C-2Adding Resource Files to a Project C-2Using Resources C-2

Opening and Closing Resource Files C-3Extracting Resource Data C-4

Using the Resource-Handling Functions C-6Using 'PICT' Resources C-7

Making a Bitmap From a 'PICT' Resource C-7Using External Sound Resources C-8

Resource Functions C-9Opening and Closing Resource Files C-9Retrieving Resources C-10

Summary of Resource-Manipulation Functions C-15Opening and Closing Resource Files C-15Getting Resource Data C-15

Appendix D Specialized Slot Editors D-1

Script Slots D-1View Attributes D-2

viewBounds D-2viewFlags D-4viewFormat D-4viewJustify D-4viewEffect D-5viewTransferMode D-5

Specific Slots D-5

Index IN-1

Page 11: Newton Toolkit User’s Guide

xi

Figures and Tables

Chapter 1 Installation and Setup 1-1

Table 1-1 Hardware and software requirements 1-2

Chapter 2 Programming With theNewton Toolkit 2-1

Figure 2-1 The Newton application development process 2-4

Chapter 3 A Quick Tour of NTK 3-1

Figure 3-1 Layout window and palette 3-5Figure 3-2 A browser window 3-11

Chapter 4 Using the Newton Toolkit 4-1

Figure 4-1 The project window, with the main layout file selected 4-3

Figure 4-2 The Project Settings dialog box 4-3Figure 4-3 The Toolkit Preferences dialog box 4-8Figure 4-4 Layout window and palette 4-12Figure 4-5 A layout window with the layout view in place 4-15Figure 4-6 The Alignment dialog box 4-18Figure 4-7 The layout window in layout and preview

modes 4-21Figure 4-8 The Template Info dialog box, for naming and

declaring views 4-22Figure 4-9 Declaring views across linked layout files 4-24Figure 4-10 A browser window with the view flags slot open

for editing 4-27Figure 4-11 The New Slot dialog box 4-29Figure 4-12 The Editor pop-up menu in the New Slot

dialog box 4-29

Page 12: Newton Toolkit User’s Guide

xii

Figure 4-13 Initial contents of evaluate, script, and text slots 4-30

Figure 4-14 The number, Boolean, rectangle, and picture slot editors 4-31

Figure 4-15 The Inspector window with a help message displayed 4-33

Figure 4-16 The dialog box for searching with List 4-34Figure 4-17 The dialog for searching with Find 4-36Figure 4-18 Inspector window 4-51

Chapter 5 Debugging 5-1

Table 5-1 Debugging variables 5-15Table 5-2 Exception handling global variables 5-32

Chapter 6 NTK Commands 6-1

Figure 6-1 The dialog for searching with List 6-7Figure 6-2 The dialog for searching with Find 6-8Figure 6-3 The Toolkit Preferences dialog box 6-10Figure 6-4 The Project Settings dialog box 6-14Figure 6-5 The Layout Size dialog box 6-15Figure 6-6 The Set Grid dialog box 6-16Figure 6-7 The Alignment dialog box 6-17Figure 6-8 The Template Info dialog box, for naming and

declaring views 6-19Figure 6-9 The New Slot dialog box 6-19Figure 6-10 The Rename Slot dialog box 6-20

Appendix A Keyboard Text-Editing Commands A-1

Table A-1 Moving the insertion point A-2Table A-2 Selecting text with keyboard commands A-3Table A-3 Manipulating selected text A-4Table A-4 Deleting text with keyboard commands A-5Table A-5 Changing the interpretation of the next

keystroke A-6

Page 13: Newton Toolkit User’s Guide

xiii

Appendix B Keyboard Shortcuts B-1

Table B-1 Keyboard equivalents to menu items B-1Table B-2 Keyboard commands that affect the hierarchy B-3

Appendix C Using Resources C-1

Figure C-1 Adding a named 'PICT' resource to a picture slot C-7

Appendix D Specialized Slot Editors D-1

Table D-1 Meaning of viewBounds fields for horizontal justification D-3

Table D-2 Meaning of viewBounds fields for vertical justification D-3

Page 14: Newton Toolkit User’s Guide

PREFACE

xv

About This Book

This book introduces the Newton Toolkit (NTK), an integrated environment for developing Newton applications. You program Newton applications in NewtonScript, an object-oriented language developed for the Newton family of personal digital assistants (PDAs).

How to Use This Book

This book is both a tutorial introduction and a reference guide to NTK. You use this book in conjunction with The NewtonScript Programming Language and the Newton Programmer’s Guide.

This book contains six chapters:

n Chapter 1, “Installation and Setup,” contains instructions for installing the Newton Toolkit on your Macintosh computer, attaching a Newton PDA, installing Toolkit software on the Newton, and setting up a debugging connection.

n Chapter 2, “Programming With the Newton Toolkit,” introduces Newton programming terminology, describes the Newton development process, and introduces the basic components of the Newton Toolkit.

n Chapter 3, “A Quick Tour of NTK,” is a tutorial designed to familiarize you with the basic process of application development in NTK.

n Chapter 4, “Using the Newton Toolkit,” describes the components of the Newton Toolkit in detail.

Page 15: Newton Toolkit User’s Guide

PREFACE

xvi

n Chapter 5, “Debugging,” explains how to use the debugging commands available through the Inspector and offers a few debugging guidelines.

n Chapter 6, “NTK Commands,” is a summary of the items available in the NTK menus.

Related Books

This book is one in a set of books included with the Newton Toolkit development environment. You’ll also need the other books in the set:

n Newton Programmer’s Guide. This book is the definitive guide and reference for Newton programming. It explains how to write Newton programs and describes the system software routines that you can use to do so.

n The NewtonScript Programming Language. This book describes the NewtonScript programming language.

n Newton Book Maker User’s Guide. This book describes how to use Newton Book Maker and the Newton Toolkit to make Newton digital books and to add online help to Newton applications. This book is included only if you purchased the Newton Toolkit package that includes Book Maker.

Page 16: Newton Toolkit User’s Guide

PREFACE

xvii

Conventions

This book uses the following font and syntax conventions:

Courier The Courier font represents material that is typed exactly as shown. Code listings, code snippets, and special identifiers in the text such as predefined system frame names, slot names, function names, method names, symbols, and constants are shown in the Courier typeface to distinguish them from regular body text.

italics Text in italics represents replacable elements, such as function parameters, which you must replace with your own values.

boldface Key terms and concepts are printed in boldface where they’re defined. Words defined in this book appear in the glossary in the Newton Programmer’s Guide.

… An ellipsis in a syntax description means that the preceding element can be repeated one or more times.

An ellipsis in a code example represents code not shown.

[ ] Square brackets enclose optional elements in syntax descriptions.

Page 17: Newton Toolkit User’s Guide

PREFACE

xviii

Developer Products and Support

APDA is Apple’s worldwide source for a large number of develop-ment tools, technical resources, training products, and information for anyone interested in developing applications on Apple platforms. Every four months, customers receive the APDA Tools Catalog featuring current versions of Apple’s development tools and the most popular third-party development tools. Ordering is easy; there are no membership fees, and application forms are not required for most products. APDA offers convenient payment and shipping options including site licensing.

To order product or to request a complimentary copy of the APDA Tools Catalog:

APDAApple Computer, Inc.P.O. Box 319Buffalo, NY 14207-0319

If you provide commercial products and services, call 408-974-4897 for information on the developer support programs available from Apple.

Telephone 1-800-282-2732 (United States)1-800-637-0029 (Canada)716-871-6555 (International)

Fax 716-871-6511

AppleLink APDA

America Online APDA

CompuServe 76666,2405

Internet [email protected]

Page 18: Newton Toolkit User’s Guide

System Requirements 1-1

CHAPTER 1

Installation and Setup

The Newton Toolkit (NTK) runs on a Macintosh computer in 32-bit mode with a minimum of 8 megabytes of RAM. NTK includes a small application—the Toolkit App—that runs on a Newton Personal Digital Assistant (PDA).

This chapter describes how to

n install NTK on a Macintosh computer

n download the Toolkit App to a Newton

n establish a debugging connection between the Macintosh and the Newton

n troubleshoot installation and setup

System Requirements

Table 1-1 lists NTK’s hardware and software requirements.

Note

Downloading to a Newton also requires one free serial port on the Macintosh. u

Page 19: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

1-2 Installing NTK on the Macintosh

Installing NTK on the Macintosh

The Newton Toolkit is shipped with an installation script, which you run from the distribution disk. Before installing NTK, verify that each distribution disk is locked (that is, that the write-protect slider is open) to protect the contents from accidental overwriting.

Follow the steps in this section to install NTK on the Macintosh.

1. Insert the disk Newton Toolkit Installer.

The disk opens to show the release notes and the Installer.

2. Double-click the release notes and read them to see if there are any updates to the installation procedure. If not, close them and continue with these directions.

Table 1-1 Hardware and software requirements

Recommended Minimum

Macintosh Model Quadra 25 Mhz 68030-based Macintosh

Available RAM 8 megabytes 8 megabytes

Operating System System 7.1.xor higher

System 7.0 with System 7 Tune-Up

System Settings 32-bit mode 32-bit mode

Page 20: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

Installing NTK on the Macintosh 1-3

3. Double-click the Installer icon to begin installation.

If you’re installing NTK for the first time, of if you’re simply updating an earlier release, leave the Easy Install item selected in the pop-up menu in the top-left corner of the window. You can also choose Custom Install to selectively install parts of the software or Custom Remove to selectively remove parts of the software.By default, the Installer puts NTK in a folder named Newton Toolkit on your startup disk. If you want to change the destination, click Select Folder and specify a new or different folder.

4. Click Install.The Installer begins copying and configuring software; it displays progress reports and prompts you to insert disks when necessary.

5. Insert disks as prompted until the Installer reports that installation is complete.

6. Click Quit to quit the Installer.

Page 21: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

1-4 Installing NTK on the Macintosh

The Newton Toolkit folder contains the NTK application and various support tools:

n The EditorCommands file, which is used by NTK and which must remain in the same folder as NTK.

n The NTK Definitions file, which contains a list of compile-time constants and functions available in NTK. This file is for your information only and can be put anywhere.

n The Platforms folder, which at this release contains a file named MessagePad. Platform files contain data specific to a Newton platform. The Platforms folder must remain in the same folder as NTK.

n The Toolkit App package, which contains a companion application that runs on a Newton. Instructions for installing the Toolkit App appear in the next section.

n The Newton Book Maker application, for generating book files that can be read into NTK. This application is documented in the Newton Book Maker User’s Guide.

n The Newton Package Installer, a stand-alone utility that downloads packages to a Newton. You are free to ship this utility as an installation tool for your customers.

n The TextText application, for reading the release notes. This file can be stored anywhere.

Page 22: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

Installing the Toolkit App on the Newton 1-5

n Release notes for the Newton Toolkit, the Platform files, and Newton Book Maker. These files are for you information only and can be put anywhere.

The Installer also installs fonts in the System Folder if necessary and places the Apple Modem Tool and AppleTalk ADSP Tool in the Extensions folder in the System Folder.

Installing the Toolkit App on the Newton

You can install the Toolkit App over either a direct serial connection or an AppleTalk network connection. Once you’ve installed the Toolkit App, it manages subsequent installation of NTK packages and supports the Inspector, an interactive debugger that lets you modify applications from NTK while they’re running on the Newton.

Making the Physical ConnectionYou can connect your development system directly to a Newton with a null modem cable, that is, a serial cable in which pins 2 and 3 are crossed over (pin 2 on the Macintosh end connects to pin 3 on the Newton end of the cable; pin 3 on the Macintosh end connects to pin 2 on the Newton end). This cable is also known as a direct serial cable and is often sold as a printer cable. You can use Apple cable model M0197, part number 590-0552.

You install the cable between the serial connector on the Newton and one of the serial ports on the Macintosh. You can use either the modem serial port or the printer serial port; NTK is configured to use the modem port by default.

Note

Make sure that no other piece of Macintosh software is using the same serial port. u

If both the Macintosh and the Newton are connected to an AppleTalk network, you can also download over the Toolkit App over the network.

Page 23: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

1-6 Installing the Toolkit App on the Newton

Downloading the Toolkit AppThis section describes how to install the Toolkit App on a Newton with a serial connection to one of the built-in serial ports on the Macintosh.

1. On the Macintosh, start NTK by double-clicking the application icon.The Macintosh displays the open-file dialog box, for opening an NTK project.

2. Dismiss the dialog box by clicking Cancel.

3. Choose Install Toolkit App from the Project menu.NTK displays the connection settings and prompts you to initiate the connection on the Newton.

4. On the Newton, open the Extras drawer, and then tap the Connection icon.The Connection application opens on the Newton screen.

5. Verify that the connection setting matches your configuration.

6. Tap Connect.The Newton reports that the Connection application is waiting for a response. In a few seconds, the dialog disappears, and a toollbox icon labeled Toolkit appears in the Extras drawer.NTK Toolkit App installation is complete.

To install the Toolkit App over an AppleTalk network, you must change NTK’s communication settings through the Toolkit Preferences item in the Edit menu. On the Newton, you must select the zone and name of the host Macintosh in the Connection application on the Newton.

Page 24: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

Making an Inspector Connection 1-7

Making an Inspector Connection

An Inspector connection lets you issue commands directly to the Newton from a window on the Macintosh. You can establish an Inspector connection only over a serial line.

To open and test an Inspector connection

1. On the Macintosh, choose Connect Inspector from the Window menu.NTK displays the connection settings and prompts you to initiate the connection on the Newton.

2. On the Newton, open the Toolkit App by tapping its icon in the Extras drawer.

3. Verify that Macintosh serial is selected; if it’s not, change the selection.

4. Tap Connect Inspector.The Macintosh and the Newton establish communication, and the Macintosh displays the Inspector window.

5. In the Inspector window, type

x := 1/5;

6. Press Enter.The Inspector displays a reference and the value of x .

#440D2F1 0.200000

Page 25: Newton Toolkit User’s Guide

CHAPTER 1

Installation and Setup

1-8 Troubleshooting

Troubleshooting

If you have trouble launching NTK, try these troubleshooting strategies:

n Verify that the Macintosh is using 32-bit addressing. You set the addressing mode in the Memory control panel, available through the Control Panel item in the Apple menu.

n Verify that the folder containing the Newton Toolkit application also contains a Platforms folder that contains the MessagePad file.

n Read the release notes.

If you have trouble downloading the Toolkit App or making an Inspector connection, try these troubleshooting strategies:

n Verify that you’re using a null modem cable.

n If you’re using a Powerbook or Powerbook Duo, verify that the modem is set to External Modem.

n If you’re using a Powerbook Duo, turn off AppleTalk through the Chooser.

n If you’re using a Quadra AV, verify that you’re not using the World port.

n Delete the Newton Toolkit Preferences file in the Preferences folder in the System Folder before launching NTK, and then re-establish communica-tions settings through the Toolkit Preferences item in the Edit menu.

n Reset the Newton.

n If the Newton has little free space, remove some software through the Memory item in Preferences.

n Verify that the Apple Modem Tool and the AppleTalk ADSP Tool are installed in the Extensions folder in the System Folder.

n Read the release notes.

Page 26: Newton Toolkit User’s Guide

Terms and Concepts 2-1

CHAPTER 2

Programming With theNewton Toolkit

The Newton interface is a graphical one, in which the user manipulates elements on the screen to accomplish a wide range of tasks.

The Newton Toolkit is an integrated environment tailored to the graphical nature of the Newton environment. This chapter introduces the concepts and terminology used in Newton programming and outlines the software development process.

Terms and Concepts

Views are the basic building blocks of most applications. The individual items on the Newton screen—radio buttons, for example—are all views, and there may be views that are not visible.

You lay out views using NTK’s graphical editor. When you draw a view, NTK creates a template, that is, a data object that describes how the view will look and act on the Newton. You build your application from a collection of templates that describe the application’s elements.

Page 27: Newton Toolkit User’s Guide

CHAPTER 2

Programming With the Newton Toolkit

2-2 Terms and Concepts

A template is a frame, the basic data structure in NewtonScript. A frame is an object containing a collection of named data references called slots. You define a view’s characteristics and behavior by specifying the contents of the slots in its template.

You use the NewtonScript programming language to write the code that controls the behavior of a view. NewtonScript is an object-oriented language developed for the Newton. It is described in The NewtonScript Programming Language.

Views are created from templates when your application executes on the Newton. The process of making an object, such as a view, at run time, from a template, is called instantiation.

A view has two parts: the visual object you see on the screen, and a frame in memory containing transient data used at run time. This frame is sometimes called the view frame.

Note that applications can also include non-graphical components, such as communication services, that have no visible manifestations. Like views, these objects are described by templates and are instantiated at run time into a frame that exists in working RAM.

Newton applications are stored on ROM-based PCMCIA cards or in a protected part of the Newton memory. Unlike some computers, the Newton does not copy an application (in this case, a collection of templates) into working RAM when executing it. Therefore, templates are read-only objects. Views are their dynamic, writable counterparts.

When the Newton instantiates a view, it creates a view frame in working RAM. The view frame contains a pointer to the template. Information is read from the template as needed. If a value changes at run time, a slot is added to the view frame, and the new value is stored there. This memory-use strategy allows applications to use relatively small amounts of working RAM.

This architecture also makes available to your application all templates built into the Newton ROM. When you use a view template from the NTK palette (described in Chapter 4, “Using the Newton Toolkit”), your application

Page 28: Newton Toolkit User’s Guide

CHAPTER 2

Programming With the Newton Toolkit

The NTK Development Process 2-3

doesn’t have to contain the full template. Instead, NTK references the templates in the Newton ROM, and places only your modifications in the application.

The Newton Programmer’s Guide contains a full description of the Newton view system and the templates and functions you use when programming a Newton application.

The NTK Development Process

You manage an application under development as an NTK project, that is, the collected files and specifications NTK needs to build a data package that can be downloaded to and executed on the Newton. The section “Setting Up a Project” beginning on page 4-1 describes how you organize a project in NTK.

You lay out an application’s visual interface with NTK’s graphical editor and a palette of view templates. The graphical editor creates layout files, that is, Macintosh files containing the templates that describe the application’s views. The section “Laying Out Views” beginning on page 4-11 describes the graphical editor and palette.

You use the NTK browser to search through and edit the templates in a layout file. The section “Browsing and Editing Templates” beginning on page 4-26 describes the NTK browser.

Once you’ve programmed your application, you use NTK to build a package, that is, a data object that can be installed on the Newton. The section“Building a Project” beginning on page 4-37 describes the build cycle. You also use NTK to download the package to the Newton.

You can study and alter your application while it’s running with the Inspector, NTK’s interactive debugger. Chapter 5, “Debugging,” describes the Inspector.

Figure 2-1 illustrates the application development process.

Page 29: Newton Toolkit User’s Guide

CHAPTER 2

Programming With the Newton Toolkit

2-4 The NTK Development Process

Figure 2-1 The Newton application development process

Page 30: Newton Toolkit User’s Guide

3-1

CHAPTER 3

A Quick Tour of NTK

This chapter illustrates the Newton application development process and introduces the major components of NTK.

You can follow this tutorial to create, build, download, and examine a simple application. The tutorial illustrates

n starting up NTK

n setting up an application project

n laying out the application’s visual interface

n coding the application

n building an application package and downloading it to a Newton

n inspecting the application while it’s running.

Note

This tutorial assumes that you’re running NTK on a Macintosh with a serial connection to a Newton, as described in Chapter 1, “Installation and Setup.” u

The next chapter, “Using NTK,” describes the primary components of NTK in approximately the same order they’re introduced in this tutorial. You might want to read the two chapters in parallel.

Page 31: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-2 Starting Up NTK

Starting Up NTK

1. If NTK is not already running, double-click the Newton Toolkit application icon to start NTK.

NTK displays its startup screen followed by a file-open dialog box.

2. For this tutorial, click Cancel.

Setting Up a New Project

You build a Newton application from a collection of files, which you coordinate through a project file. The first step in creating an application is to start a project file.

1. Choose New Project from the Project menu.NTK presents the standard file-save dialog box.

2. Create a new folder named Hello folder, and change the project name from Untitled Project-1 to Hello.prj .

Page 32: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Setting Up a New Project 3-3

3. Click Save.NTK displays the blank project window.

4. Choose Settings from the Project menu.NTK displays the Project Settings dialog box, through which you specify the information NTK needs to build an application package.

NTK sets up default name and symbol strings based on the name of your project.

5. Change the symbol to Hello:TUT

Page 33: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-4 Starting a Layout File and Adding It to the Project

6. Change the package name to Hello:TUT

7. Click OK.

“Setting Up a Project” beginning on page 4-1 describes all the fields in the Project Settings dialog box.

Starting a Layout File and Adding It to the Project

NTK provides a graphical editor for arranging the visual elements of your application.

You typically start with the application base view, the screen image that appears when the user starts the application. The application base view is the ancestor of all other views in an application. It’s the hub of the application, both visually and structurally.

1. Choose New Layout from the File menu.NTK displays a layout window and a palette of view templates—protos, view classes, and a special NTK element called a linked subview—illustrated in Figure 3-1. The buttons on the palette represent the view templates that are built into the Newton.The default layout window represents the screen of the Newton MessagePad.

2. Press and hold the mouse button with the pointer on the Selection pop-up menu.NTK displays the names of all the view templates on the palette. For faster identification, protos appear in the pop-up menu without the proto prefix.

3. Release the mouse button, and move the pointer over the buttons on the palette. The name visible in the Selection menu changes as you move the pointer over the buttons. The name of each template appears when the pointer is over its button. You can select a template by either clicking its button or choosing it from the Selection pop-up menu.

Page 34: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Starting a Layout File and Adding It to the Project 3-5

Figure 3-1 Layout window and palette

4. Using either the buttons or the pop-up menu, select protoApp , which appears as App in the pop-up menu.

The name App now appears in boldface in the Selection pop-up menu; only the selected entry appears in boldface.The protoApp defines a view with a few basic application features: a title bar, a status bar, and a close box.

Selection pop-up menu

View alignmentbuttons

View templatebuttons

User-definedproto pop-upmenu

Page 35: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-6 Starting a Layout File and Adding It to the Project

Most applications use either the protoApp proto or the clView view class for the application base view. For descriptions of the system-defined protos and view classes, see the chapters “Working With Proto Templates” and “Working With View Classes” in the Newton Programmer’s Guide.

5. Draw the base layout view, positioning it approximately as shown here.

The rectangle you define here determines the size and location of the application on the Newton screen.NTK labels your new layout view protoApp , using the name of the proto from which it was constructed.

6. Choose Template Info from the Browser menu.NTK displays the Template Info dialog box, which lets you name and declare view templates. (Declaring a view allows you to access the view symbolically from another view, as described briefly in “Naming and

Page 36: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Starting a Layout File and Adding It to the Project 3-7

Declaring Views” beginning on page 4-21 and in more detail in the “Views” chapter in the Newton Programmer’s Guide.)

7. Type the name baseView , and then click OK.

8. Save the layout file by choosing Save As from the File menu, typing the name main Hello.t , and then clicking Save.

9. Choose Add Window from the Project menu.NTK adds the layout main Hello.t to the project file.

10. Activate the project window (by clicking the title bar) to see the list of files in the project, which at this point includes only the file main Hello.t .

NTK designates the first layout file you add to a project the main layout file, that is, the layout file containing the application base view. The bullet next to the filename marks the main layout file. You can change the designated main layout file through the Project menu.

11. Choose Save from the File menu to save the project file.

Page 37: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-8 Laying Out Application Elements

Laying Out Application Elements

You lay out the elements of an application within the application base view.

In this section of the tutorial, you add a view that accepts handwritten input from the user.

1. Activate the layout window, now titled main Hello.t , by clicking its title bar.

2. Using either the buttons on the palette or the Selection pop-up menu, select protoLabelInputLine .

3. Draw out a rectangle inside the application base view, imitating the size and location shown here.

Page 38: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Customizing a View Template 3-9

4. To see what the view will look like on the Newton screen, choose Preview from the Layout menu.

You can toggle between layout mode and preview mode by choosing the Preview command or by pressing Command-Y on the keyboard.

5. Save the layout file by choosing Save from the File menu.

Customizing a View Template

When you lay out a view, NTK creates a view template, a frame containing the named slots that define the view.

You can edit view templates with NTK’s browser. The browser displays a list of templates and a list of slots within the selected template. When you select a slot for editing, the browser invokes a slot editor of the appropriate type.

Page 39: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-10 Customizing a View Template

Editing a SlotIn this section, you change the application’s title by editing the title slot in the application base view template.

1. Select the application base view by clicking within the baseView view but outside the protoLabelInputLine view. Small selection marks appear in the corners of the selected view.

2. Choose New Browser from the Window menu.NTK displays a browser window for the base view, as illustrated in Figure 3-2.The template list shows the templates for the selected view and all its children. The slot list shows the slots for the view that’s selected in the template list. The slot pop-up menus list system-defined slots you can add to your templates. When you open a slot for editing, you work in the slot editor area.

3. Click protoApp:baseView to select it.NTK displays in the slot list the slots for that template.

4. Double-click the title slot to open it for editing.NTK displays the slot’s current contents, Application , in the editing area.

5. Select the default text and change it toHello, world

6. Apply the change by clicking the Apply check mark in the bottom-left corner of the browser window.

You can also apply a change by pressing Command-E or choosing Apply from the Browser menu.If the layout window is still in preview mode, you can see the name change as soon as you apply the change. If the layout window is in layout mode, activate the layout window and then choose Preview from the Layout menu to see the change.

RevertApply

Page 40: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Customizing a View Template 3-11

Figure 3-2 A browser window

7. Save the layout file.Saving with either the browser window or a layout window active saves the layout file for the template you’re editing.

Adding a SlotYou can add system-defined slots to a view through the pop-up menus labeled Specific, Methods, and Attributes, located below the slot list in a browser window.

You can also define and add your own slots by choosing New Slot from the Browser menu, as described in “Adding Slots” beginning on page 4-28.

Slot listTemplatelist

Slot editorarea

Slot pop-up menus

Page 41: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-12 Building and Downloading a Package

In this section of the tutorial, you add a label to the application’s pen-input view by adding a label slot to the view template.

1. Activate the browser window by clicking its title bar.

2. Select protoLabelInputLine from the view list by clicking it.NTK displays the slots defined for that view.

3. Choose label from the Specific pop-up menu.NTK invokes the text editor and displays the default label, Label . It adds the label slot to the slot list.

4. Replace the default label with the text My Message

5. Apply the change by clicking the Apply check mark (or by pressing Command-E or choosing Apply from the Browser menu).

6. Save the layout file by choosing Save from the File menu.

Building and Downloading a Package

At almost any point after you’ve laid out an application base view, you can build your application into a package, which you can download and run on a Newton.

Note

To download, you must have connected a Newton and installed the Toolkit App, as described in Chapter 1, “Installation and Setup.” u

1. Choose Save All from the File menu.

2. Choose Build Package from the Project menu.NTK builds the package and places it in the project folder.NTK always places the package in a file called projectname.pkg.

Page 42: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Building and Downloading a Package 3-13

3. Choose Download Package from the Project menu.

Note

This tutorial assumes there is no Inspector connection open. If you’ve made an Inspector connection, the Inspector handles the downloading from this point. u

The Macintosh reports its communication settings and prompts you to initiate the connection on the Newton.

4. Verify that the message describes your configuration.

5. Tap the Toolkit App icon in the Extras drawer on the Newton.The Toolkit App opens.

6. Tap Download Package.The Macintosh reports progress during the download. When downloading is complete, the application appears in the Extras drawer on the Newton.

Page 43: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-14 Adding a Linked Layout

7. Open the application by tapping its icon.

8. Test the application by writing in the input view.

9. Close the application when you’re done.

Adding a Linked Layout

As an application grows more complex, the layout window can become cluttered. You can split your application into logical modules and keep your layout windows manageable by laying out child views in separate template files and linking them into the application through an element called a LinkedSubview , available through the NTK palette.

In this tutorial, you lay out a floating window in a separate layout file and link it to the application base view. You make it available to the user by adding to the base view a button that, when pressed, sends an Open message to the linked view.

Page 44: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Adding a Linked Layout 3-15

Laying Out a Linked ViewIn this section, you create a template for a linked view that displays a message when the user presses a button.

1. Choose New Layout from the File menu.

2. Choose Save As from the File menu, type the name floater Message.t , and click Save.

3. Choose Add Window from the Project menu to add floater Message.t to the project list.Add Window adds the active layout to the project list; Add File displays a dialog box that allows you to add a file from anywhere on the desktop.

4. Select protoFloatNGo from the palette.

Like all layout files, a layout file for a linked view must have a main layout view—in this case, a view based on protoFloatNGo —which is the parent of all other views in the file.

5. Draw the view, positioning it approximately as shown here.

Page 45: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-16 Adding a Linked Layout

The rectangle you specify in this step defines the size and location of the linked view.

6. Choose Template Info from the Browser menu, name the view floaterLink , and then click OK.

7. Select protoStaticText from the palette.

8. Lay out the text view within the layout view approximately as shown here.

This rectangle defines the location of the static text message within the linked view.

Page 46: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Adding a Linked Layout 3-17

9. With the protoStaticText view still selected, choose New Browser from the Window menu. NTK displays a new browser.

10. Click protoStaticText to display the slots in that template.

11. Double-click the slot name text to open the slot for editing.The browser displays the default text, Static Text .

12. Select the default text and replace it with your own message, such asHello, world, from a linked view

13. Close the browser window by clicking the close box in the top-left corner.NTK automatically applies pending changes when you close a browser window.

14. Choose Save All from the File menu to save both the layout file and the project file.

Linking a LayoutTo link a separate layout file into an application, you first add the LinkedSubview template to any view in the main layout file or in another layout file linked to the main layout file. Then you use the Link Layout item in the File menu to establish the link.

1. Activate the main layout window (main Hello.t) by clicking its title bar.

2. If the layout is in preview mode, change it to layout mode.

Page 47: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-18 Adding a Linked Layout

3. Select LinkedSubview from the palette.

4. Lay out the linked subview approximately as shown here.

The placement of the linked subview doesn’t matter. The position of the view itself is determined by the linked template (in this case, the floaterLink template in the layout file floaterMessage.t ).

5. With the linkedSubview view still selected in the layout window, choose Template Info from the Browser menu (or press Command-I).

6. Type in the name floaterLink , but don’t click OK yet.This tutorial uses the same name for the linking view and for the layout view in the external layout file because the two templates share the same place in the view hierarchy. “Linking Multiple Layouts” beginning on page 4-22 explains how NTK processes linked subviews and the layout files they’re linked to.

Page 48: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Adding a Linked Layout 3-19

7. Click the box labeled “Declare To:”If floaterLink had more named ancestors, they would appear in the pop-up list. In this example, only baseView is available.

Declaring the linked subview is not necessary for linking. You declare the view in this step so that the button you add in the next section can send an Open message to its sibling, the floaterLink view.

8. Click OK.

9. With the floaterLink view still selected, choose Link Layout from the File menu.NTK displays the file-select dialog box.

10. Select the filename floaterMessage.t , and then click Open.The main Hello.t layout window now reflects that floaterLink is linked to the linked view floaterMessage.t .

Adding a Button That Displays the ViewTo incorporate the floater view into the application’s interface, this tutorial adds a button to the application’s base view and sets up the button to send an Open message to the linked view when it’s tapped.

1. With the main Hello window still active, choose protoTextButton from the palette.

Page 49: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-20 Adding a Linked Layout

2. Draw the button, positioning it approximately as shown here.

The rectangle you draw in this step determines the size and position of the button on the Newton screen. All descendants of the application base view must be contained entirely within the application base view; any portions that fall outside aren’t visible on the Newton.

3. Use Template Info to name the new view showFloaterButton

4. Activate the browser window by clicking its title bar.

5. Select protoTextButton:showFloaterButton from the view list, and then double-click the buttonClickScript slot to open it for editing.NTK invokes the script slot editor and displays a skeletal function statement.

6. Insert an instruction to send an Open message to the floaterlink view, so that the text reads:

func()begin

floaterLink:Open();end

Page 50: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Defining Your Own Proto 3-21

7. Apply the change.When you apply a change to a slot that contains NewtonScript code, NTK checks the syntax. It displays an alert if it finds any syntax errors, but it applies the change in any case.

8. Double-click the text slot to open it for editing.This slot specifies the text on the button itself.

9. Change the default button text toShow Linked View

10. Close the browser window by clicking the close box in the top-left corner.

11. Save the file.

Defining Your Own Proto

This section of the tutorial creates a user proto—a proto defined by you, not built into the Newton—that contains three radio buttons. If you needed the view in only one place, you’d likely lay it out as a standard layout file. Defining a layout as a proto, however, opens up two opportunities:

n You can use the same template in different views or applications.

n Your application can use the proto to create views as needed at run time.

Laying Out a Proto and Adding It to the Palette

1. Choose New Proto Template from the File menu to open a proto layout window.You set up a proto template the same way you set up any other layout file: you establish the layout base view and place other elements within it.

Page 51: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-22 Defining Your Own Proto

2. Select protoRadioCluster from the palette.

The protoRadioCluster proto provides a container view for radio buttons.

3. Draw the layout base view approximately as shown here.

Page 52: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Defining Your Own Proto 3-23

4. Select protoRadioButton from the palette.

This proto defines a single, labeled radio button.

5. Draw a wide, shallow rectangle within the cluster view.

Page 53: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-24 Defining Your Own Proto

6. Make two duplicates of the radio button (with the new radio button view selected, press Command-D twice or choose Duplicate from the Edit menu twice), and then position the buttons approximately as shown here.

7. Select the layout view, protoRadioCluster , and use the Template Info command to name it myRadioButtons

8. Save the layout file as myRadioButtonsProto.t

9. Choose Add Window from the Project menu.NTK adds the file myRadioButtonsProto.t to the project.NTK also adds myRadioButtonsProto to the User pop-up menu in the palette.

10. Choose Save All to save the project file without activating it.

Page 54: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Defining Your Own Proto 3-25

Using Your ProtoOnce you’ve saved your proto and added it to the project, NTK gives you access to it through the palette.

1. Activate the main Hello.t window.

2. Click the User button to activate the User proto pop-up menu.

The proto myRadioButtonsProto is now selected.

3. Draw a view in the lower part of the application base view.Regardless of where you try to draw the new view, NTK places it where you placed the layout view for the proto myRadioButtonsproto , because the view inherits its location from its proto. You could override the inherited location by adding a viewbounds slot to the view.

4. Choose Save All from the File menu.

Page 55: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-26 Using the Inspector

5. Choose Build Package from the Project menu.

6. Build and download the package, as described in “Using the Inspector” beginning on page 3-26.You can configure NTK to download a package automatically when it’s built through Toolkit Preferences, described in “Setting Preferences” beginning on page 4-7.

7. Open the application and test the linked template and the radio buttons. Close the application when you’re done.

Using the Inspector

The Inspector is an interactive debugger that lets you browse the Newton object storage system and execute NewtonScript code on the Newton.

Note

To use the Inspector, you must have installed the Toolkit App on the Newton, as described in Chapter 1, “Installation and Setup.” u

Connecting the Inspector

1. On the Macintosh, choose Connect Inspector from the Window menu.The Macintosh reports its communication settings and prompts you to initiate the connection on the Newton.

2. Verify that the message describes your configuration.

Note

You can make an Inspector connection only over a serial link. u

3. On the Newton, tap the Toolkit icon in the Extras drawer.

Page 56: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Using the Inspector 3-27

The Toolkit application opens.

4. If necessary, change the connection setting.

5. Tap Connect Inspector.The Toolkit App reports that it’s opening the Inspector.

When the Inspector connection is established, the Inspector window opens on the Macintosh.

Executing CommandsCode you enter in the Inspector window is compiled on the Macintosh and executed on the Newton.

The Inspector compiles and executes your keystrokes only when you explicitly request it by selecting and entering text. If no text is selected when you press Enter, the Inspector processes the current line.

1. In the Inspector window, type:

x := 1/3;

2. Press Enter.The Inspector displays a reference to the object x and its value.

#441A4C1 0.333333

You can enter and execute any valid NewtonScript code in an Inspector window. The Newton always prints to the screen a reference and the value of the last statement evaluated.

Page 57: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-28 Using the Inspector

3. Type:

GetRoot():SysBeep();

The GetRoot function returns the Newton’s root view. This line sends the SysBeep message to the root view.

4. Press Enter.The Newton sounds the system beep, and the Inspector window displays a reference and the value of the statement.

#1A TRUE

5. Place the two statements together on two lines:

GetRoot():SysBeep();

x := 1/3;

6. Select both lines and press Enter.The Newton executes both lines but displays the reference and value of only the last statement evaluated.

#44126F1 0.333333

Looking at a FrameThis section of the tutorial looks at the Hello application developed earlier in this chapter. It assumes you have built and downloaded the application at least as far as adding the linked layout and that you have not changed the Toolkit Preferences.

1. Open the Hello application on the Newton by tapping its icon.

2. Open the floating window by tapping the Show Linked View button.

3. Type in the Inspector window:

debug("floaterLink");

Page 58: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

Using the Inspector 3-29

4. Press Enter.The Inspector displays the view frame for the view instantiated from the floaterLink template.

#440C359 {_Parent: {_Parent: {#4407939},

_proto: {#600044BD},

viewCObject: 0x1108C45,

floaterlink: <2>,

viewclipper: 17861715,

base: <1>,

viewFlags: 5},

_proto: {viewBounds: {#600047BD},

stepChildren: [#600047FD],

_proto: {#2D3},

debug: "floaterLink",

preallocatedContext: floaterlink},

viewCObject: 0x1108E20,

base: <1>,

viewFlags: 65}

You can specify how many layers of child views the Debug command displays by setting the PrintDepth parameter, described in Chapter 5, “Debugging.”

5. Close the floater window by tapping the close box.

6. Put the insertion point anywhere in the line debug("floaterLink") ; and then press Enter.The Inspector responds NIL, because the view is not instantiated.

Page 59: Newton Toolkit User’s Guide

CHAPTER 3

A Quick Tour of NTK

3-30 Using the Inspector

Making a Change in a Running ApplicationIn this final section of the tutorial, you change the name of the button while the application is running by changing the value of the text slot in its view frame.

1. Type

SetValue(Debug("showFloaterButton"), 'text, "Tap Here");

2. Press Enter.The text on the button changes to Tap Here.

3. Close the Hello application by tapping its close box, and then open it again by tapping the icon.The text reverts to Show Linked View, because the change affected only the view frame that existed while the application was running, not the view template from which the view was instantiated.

For a description of the debugging commands available in the Inspector, see Chapter 5, “Debugging.”

Page 60: Newton Toolkit User’s Guide

Setting Up a Project 4-1

CHAPTER 4

Using the Newton Toolkit

This chapter describes how you use NTK to

n set up a project

n establish your NTK preferences

n lay out an application’s views with the graphical editor

n edit the view templates through the browser

n build a package

n debug an application with the Inspector

Setting Up a Project

You manage an application under development as an NTK project, that is, the collected files and specifications NTK needs to build a data package that can be installed and executed on the Newton.

Page 61: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-2 Setting Up a Project

NTK builds an application from

n a project file, which contains a list of the files you’ve put in the project and a set of project specifications

n the project data file, which contains your application’s installation and removal scripts and any expressions you’ve defined for the build

n layout files, which contain templates for the views you’ve laid out in NTK’s graphical editor

n resource files, which contain resources used during the build.

You can also use NTK to create interactive books, that is, books that can be read with the Newton Book Reader built into the Newton ROM. To make a book, you supply the text in a book file, which you can create with the Newton Book Maker application. When NTK builds a project that contains a book file, it builds a book, not an application, although a Newton book can contain a number of small application-like elements. The documentation that accompanies the Book Maker application describes interactive books and the Book Reader.

Project FileYou start a project by creating a project file. When the project file is open, NTK displays the project window, which lists the files in the project. Figure 4-1 illustrates a project window. The files of type Proto and PrintFormat shown in Figure 4-1 contain customized protos and templates formatted for printing.

You create a project file through the New Project item in the Project menu. You add layout files to the project through the Add Window and Add File items. You add resource files through the Add File item, and you add a book file through the Add Book File item. A project can contain no more than one book file.

You build the active project—that is, the project whose project window is open—by choosing Build Package from the Project menu. The build procedure is described in “Building a Project” beginning on page 4-37. You can download the package to a Newton through the Download Package command.

Page 62: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Setting Up a Project 4-3

Figure 4-1 The project window, with the main layout file selected

Project SettingsYou set project specifications through the Settings item in the Project menu, which displays the dialog box illustrated in Figure 4-2.

Figure 4-2 The Project Settings dialog box

Application settings

Package settings

Page 63: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-4 Setting Up a Project

Application Settings

Name Specifies the text that appears beneath the application’s icon in the Newton Extras drawer. This field has no effect on books, whose title is specified in the book file.

Debug build Adds a slot named debug to each view that you name through Template Info in the Browser menu. The value of the debug slot is the view’s name. If you create your own debug slot for a view, NTK does not override that definition.Debug build also sets a constant named debugon to true . You can test the debugon constant with an if statement to conditionally compile debugging code that’s to be included in the application only if Debug build is in effect. This line, for example, prints a message to the Inspector window.

if debugon then

print (“Executing this code”);

When the application is compiled, the compiler removes simple conditional statements that always evaluate to nil . The example here is stripped whenever debugon is nil . Note that a compound conditional, such asif debugon and version2 then is not stripped.

Symbol Specifies the application’s unique symbol, the alpha-numeric string by which the application identifies itself to the Newton root view. This field has no effect on books.At the end of the build, if you’ve not created a slot with the name appSymbol in the application base view, NTK creates one and places in it the symbol you specify here. If the slot exists already, NTK doesn’t overwrite it.To ensure uniqueness across all third-party products, PIE DTS maintains a registry of developer signatures. Apple recommends you build your application symbols and package names from your company’s registered

Page 64: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Setting Up a Project 4-5

signature and your application name, using this convention:name:signature

A developer with the signature SURF, for example, might identify a checkbook application with the symbol checkb:SURF .To register your signature, contact the registry at PIESYSOP on AppleLinkorPIESYSOP, MS 305-2A20525 Mariani Ave.Cupertino, CA 95014Please supply this information:Company nameContact personMailing addressPhone numberE-mail addressFirst choice of signatureSecond choice of signatureNote that your registered name and signature is publicly available unless you make special arrangements with DTS.

AutoClose Identifies this as an AutoClose application, that is, one that closes when another AutoClose application opens. Use AutoClose unless your application has a particular need to be available in conjunction with others. (A calculator, for example, is significantly more useful without AutoClose in effect.)

Icon file Selects a resource file containing the application’s icon resource. The pop-up menu lists all resource files listed in the project file.

Page 65: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-6 Setting Up a Project

Icon name Selects a named 'PICT' resource from the file specified in the Icon file pop-up menu. NTK uses this resource for the icon that represents the application in the Extras drawer on the Newton.NTK can use only 'PICT' resources for the icon. You can supply a mask in a 'PICT' resource whose name is the icon’s resource name followed by an exclamation point. If an icon is named wave, for example, NTK looks for a mask with the name wave! . (A mask is a parallel bitmap used to display the icon when it’s selected. If you don’t supply your own mask, NTK creates one.) Instructions for creating 'PICT' resources appear in Appendix C, “Resources.”The selected icon appears to the right of the pop-up menus. Icons are typically 32 by 32 pixels. If you specify a larger image, it’s scaled to 32 by 32 in the Settings dialog box. It’s displayed full size, however, on the Newton.

Package Settings

Platform Specifies the model of Newton on which the application will run. The Platform pop-up menu lists the platform files stored in the Platforms folder in the same folder as the NTK application.

Delete old package on downloadAutomatically removes a package with the same name before downloading a package. If you don’t select this option, you must remove an old package through the Memory item in the Extras drawer on the Newton before downloading a new package with the same name.

Page 66: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Setting Preferences 4-7

Name Specifies a package name, that is, the name of the package as it will be installed on the Newton. Each package on the Newton must have a unique name.The recommended conventions for creating package names are the same as those for symbol names, described on page 4-5.

Copyright Specifies the content of the copyright statement embedded in the package header. This text is not displayed on the Newton.

Store on Newton Determines whether the package is saved in compressed or uncompressed format. Compressed format takes up less space on the Newton. Uncompressed format runs faster and uses less battery power.

Version Specifies the version number placed in the package. In case of conflict between packages with the same name, the version number allows the Newton system software to identify the newer and older versions. This number must be an integer in the range 0 to 9999.

Copy protected Sets a field in the package header that marks the package as copy-protected. The copy-protection field is not a lock; it is a convention respected by the software that copies packages.

Setting Preferences

You can adjust your own NTK environment through the Preferences item in the Edit menu. Figure 4-3 illustrates the Toolkit Preferences dialog box.

Page 67: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-8 Setting Preferences

Figure 4-3 The Toolkit Preferences dialog box

Layout SettingsThe layout settings control the graphical editor you use to lay out views.

Grid on Turns on autogrid in new layout windows. Autogrid constrains the placement and sizing of views to align with a layout grid. You can control the resolution of the grid, and you can turn the grid on or off for an indivi-dual window, through the Layout menu.

Page 68: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Setting Preferences 4-9

Size Sets the initial screen size for layout windows.Regardless of the Size setting, you can customize the screen for an individual layout window through the Layout Size item in the Layout menu.

Arrow keys move bySets the number of pixels by which the selected view is moved or resized when you press an arrow key.

With Shift key Sets the number of pixels by which the selected view is moved or resized when you press an arrow key while holding down the Shift key.

Browser SettingsThe browser settings control the display of templates and slots in browser windows.

View List

Sort by Sets the sort order for names in the template list. The Hierarchy option sorts templates by their position in the parent/child hierarchy; Name sorts alphabetically by proto name.

Text style Sets the text style in which the template names are displayed.

Slot List

Sort by Sets the ordering of names in the slot list. The Name option orders slots alphabetically by name; Type orders slots alphabetically by data type.

Text style Sets the text style in which the slot names are displayed.Show slot value Adjusts the display to show the slot value after each

slot name.

Page 69: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-10 Setting Preferences

Text ViewsThe text view settings control the handling of text by the slot editors.

Auto indent Enables automatic indenting, in which the editor auto-matically indents a new line to the indent of the previous line.

Tabs Sets the width of a tab.Text style Sets the text style.

PackagesThe packages settings control the package-build procedure.

Auto save before building packageSaves all open files in the project before building a package. If any of the files haven’t yet been saved, NTK prompts you for filenames.

Auto download after building packageAutomatically downloads the package to the Newton after a build.

ConnectionThe connection settings establish the communications protocol and port for the connection between the Macintosh and the Newton.

Type Sets the communications protocol for the connection with the Newton.

Port Sets the communications port for the connection with the Newton.

Page 70: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-11

Heap Sizes in KBytesThe heap sizes settings establish the sizes of the two NTK heaps.

Main heap Sets the size of the main frames heap that’s created when you launch NTK. The main frames heap holds your frame data while you’re working in NTK.Note that a change to this setting doesn’t take effect until you quit and restart NTK.

Build heap Sets the size of the heap that holds application frame data during the build. This heap is created each time you build. It needs to be approximately the size of the package being built.

If you run out of heap space during a build, NTK reports the problem and specifies which heap is too small. You can then adjust heap sizes through these settings.

NTK tries to allocate additional memory from available temporary memory first. If that fails, NTK tries to allocate memory in the application partition. If NTK reports that it can’t allocate heap space, try making more memory available by quitting other applications, or increase the size of NTK’s partition through the Get Info item in the Finder.

Laying Out Views

You use NTK’s graphical editor to lay out views in a window that represents the Newton screen.

Figure 4-4 illustrates the MessagePad layout window and the palette of components, which NTK displays when you open a layout file or choose New Layout from the File menu.

Page 71: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-12 Laying Out Views

Figure 4-4 Layout window and palette

The graphical editor saves the views you lay out in a layout file, which contains a hierarchy of templates. Each layout file must have a single layout view, which contains all other views in the layout. The layout view can contain any number of child views, which themselves can contain any number of child views, and so on.

The view that opens when the user taps an application’s icon is the application base view. The application base view is the ancestor of all other views in the application.

Selection pop-up menu

View alignmentbuttons

Templatebuttons

User protopop-upmenu

Page 72: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-13

You lay out an application by laying out views from the palette. The palette includes buttons and pop-up menus that let you add these elements:

n view classes, the basic building blocks of view templatesThe view class clParagraphView , for example, is the generic text view, used for static or editable text. The view classes are built into the Newton.

n protos constructed from the view classesThe protos, also built into the Newton, provide ready-to-use elements like radio buttons and slide controls.

n user protos, that is, protos you define yourselfYou can base your user protos on view classes, system protos, or other user protos.

n linked subviews, an NTK device for bringing into the hierarchy views laid out in separate layout files.You can break up your application into logical modules and then link the files together through linked subviews. Using multiple layout windows reduces the clutter in your layout windows as you add more complexity to your application.

The Newton Programmer’s Guide describes the view classes and protos in the chapters “Working With View Classes” and “Working With Proto Templates.” This chapter describes linked subviews in “Linking Multiple Layouts” beginning on page 4-22.

The view alignment buttons align selected views as illustrated on the buttons.

Drawing, Resizing, and Moving ViewsYou use the graphical editor to draw views using the mouse and a palette of templates.

Drawing a View

To add a view to your application, you select the template you want from the palette and then draw out the view in the layout window.

Page 73: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-14 Laying Out Views

You can select a template by either clicking one of the buttons or selecting an entry from one of the two pop-up menus. The Selection pop-up menu near the top of the palette contains the view classes and proto templates built into the Newton ROM. The User pop-up menu contains proto templates you’ve created and added to the project. You activate the selection pop-up menu by clicking the Selection button (the button with an arrow on it); you activate the User pop-up menu by clicking the User button (the button with the letter U on it).

Once you’ve activated a component, move the cursor to the layout window. To draw a view:

1. Place the tip of the arrow cursor where you want any corner of the view to appear.

2. Press and hold the mouse button.The cursor changes to a crosshair.

Hold the mouse button while you drag the cursor to the opposite corner.

3. Release the mouse button.

The rectangle you’ve defined on the screen marks the location of the view as stored in the viewBounds slot in the frame’s template. You can anticipate different platforms by adjusting the view bounds when a view is instantiated, as described in the “Views” chapter in the Newton Programmer’s Guide.

Page 74: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-15

Figure 4-5 illustrates a layout window with only a layout view.

Figure 4-5 A layout window with the layout view in place

The label in the upper-left corner of the view shows the view class or proto template on which the view is based. After you’ve named a view, its name appears instead.

Selection marks appear at the edges of a selected view. The selected view is the target of whatever view-editing instructions you make through the mouse or keyboard. You select a view by clicking it. To select multiple views, hold down the Shift key while clicking.

Page 75: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-16 Laying Out Views

Selection marks appear at the drawing edges of a view. The protoApp view illustrated in Figure 4-5 has a small border between the outline of the view and the area available for drawing; therefore, the selection marks are inset slightly.

Resizing a View

You can resize a view with either the mouse or the keyboard.

To resize a view with the mouse:

1. Select the view.

2. Place the cursor on the bottom-right corner of the view. When the cursor is placed for resizing, it changes to a two-headed arrow.

3. Press and hold the mouse button while you drag the corner.

4. When the view is the size and shape you want, release the mouse button.

You can select and resize multiple views at once. If you simply resize multiple views with the resize cursor, NTK resizes the views proportionally, so that the selected views retain their relative sizes. If you hold down the Option key while resizing multiple views, NTK resizes all the views by the same absolute amount.

To resize a view with the keyboard:

1. Select the view.

2. Hold down the Option key while pressing one of the arrow keys.The Right-arrow key enlarges the view by moving the right edge one pixel to the right. The Left-arrow key shrinks the view by moving the right edge one pixel to the left. The Down-arrow enlarges the view by moving the bottom edge one pixel down. The Up-arrow shrinks the view by moving the bottom edge one pixel up.

resize cursor

Page 76: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-17

To change the size of a view by five pixels at a time, hold down both the Shift key and the Option key while pressing an arrow key. You can set the number of pixels views are resized through the Toolkit Preferences item in the Edit menu, described on page 4-9.

Moving a View

To move a view with the mouse:

1. Place the cursor anywhere on the view (except the bottom-right corner) and press the mouse button.The cursor changes to the shape of a hand.

2. Hold the mouse button while you drag the view, and release the button when the view is in the position you want.

If you press and hold the Shift key while moving a view, NTK constrains the movement to either the vertical or the horizontal axis, depending on which direction you move in first.

To move a view with the keyboard:

1. Select the view.

2. Press any of the arrow keys.The arrow keys move the view one pixel in the direction of the arrow. You can move the view five pixels at a time by holding down the Shift key while you press the arrow key.You can set the number of pixels a view is moved by the arrow key alone and by Shift-Arrow key through the Toolkit Preferences item in the Edit menu, described on page 4-9.

You can select and move multiple views at once.

move cursor

Page 77: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-18 Laying Out Views

Aligning Views

You can align the sides or centers of two or more views by selecting the views and clicking one of the alignment buttons on the palette.

You can perform more sophisticated alignments through the Alignment and Align items in the Layout menu. Choosing Alignment displays the dialog box, illustrated in Figure 4-6.

Figure 4-6 The Alignment dialog box

As you select various alignment options, the objects in the sample rectangle move to show the effect. Once you’ve set up your alignment rules through the Alignment dialog box, click Apply to apply them to the selected views. You can later choose Align from the Layout menu to apply the most recent Alignment rules to the selected views.

Page 78: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-19

Vertical Spacing

The options to the right of the sample rectangle control vertical spacing. You can either align or distribute selected views during one alignment.

You can align the tops, centers, or bottoms of selected views. When aligning tops and bottoms, NTK aligns all selected views to the top of the topmost view or the bottom of the bottommost view. When aligning centers, NTK centers all views over the line halfway between the top of the topmost view and the bottom of the bottommost view.

You can distribute the selected views so that the tops, centers, or bottoms are evenly spaced, or so that the distance is the same between the tops and bottoms of adjacent views.

Horizontal Spacing

The options below the sample rectangle control the horizontal spacing. You can either align or distribute selected views during one alignment.

You can align the left sides, centers, or right sides of selected views. When aligning left and right sides, NTK aligns all views with the view furthest to the left or right, respectively. When aligning centers, NTK centers all views over the line halfway between the outer sides of the most distant views.

You can distribute the selected view so that the left sides, centers, or right sides are evenly spaced, or so that the distance between the edges of adjacent views is the same.

Ordering Views

Views are drawn on the Newton screen in the order in which they appear in the drawing list. Views that appear later in the list can obscure views drawn earlier.

Within each sibling group, views are added to the drawing list in the order you lay them out in NTK’s graphical editor. You can move a view one place ahead in the drawing list by choosing Move Backward from the Layout menu. You can move a view one place back in the drawing list by choosing Move Forward. You can move a view behind all its siblings in the drawing

Page 79: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-20 Laying Out Views

list by choosing Move To Front, and you can move a view ahead of its siblings in the drawing list by choosing Move To Back.

You can also reorder views by selecting them in the browser template list and pressing Option-Up arrow (to move a view forward in the drawing list) or Option-Down arrow (to move a view back in the drawing list).

PreviewingYou ordinarily draw views with the graphical editor in layout mode, in which NTK displays the rectangular extents of the views and their names. You can see a closer approximation of how the views will look on the Newton screen by choosing Preview from the Layout menu.

Figure 4-7 illustrates a simple view in layout mode and preview mode.

Views based on the most commonly used protos appear in preview mode much like they’ll appear on the Newton screen. Text is displayed only in the default font, and a protoStaticText view can display no more than 255 characters. User protos are not displayed.

You can toggle between layout and preview modes by choosing Preview from the Layout menu or pressing Command-Y.

Preview mode is fully implemented for the templates protoApp , ProtoCheckBox , protoLabelInputLine , protoRadioButton , protoStaticText , protoTextButton , protoPictureView , protoSlider , clGaugeView , and protoRadioCluster .

Page 80: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-21

Figure 4-7 The layout window in layout and preview modes

Naming and Declaring ViewsYou name and declare views through the Template Info item in the Browser menu.

You must supply unique names for

n views that declare themselves to other views and

n views to which other views declare themselves.

layout mode preview mode

Page 81: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-22 Laying Out Views

You should also name all views that you’ll need to identify through the browser template list. You don’t need to name all views—NTK identifies unnamed views with a label based on the name of the view’s proto.

When you choose Template Info, NTK displays the dialog box illustrated in Figure 4-8.

Figure 4-8 The Template Info dialog box, for naming and declaring views

You name a view by typing into the Name field. You activate the Declare To pop-up menu by clicking its check box. Press and hold the mouse button with the cursor on the menu to see a list of the view’s named ancestors. Choose the target view from this pop-up menu.

You must name a view before you can declare it. Declaring a view places a slot for that view into the template in which you are declaring it, allowing symbolic access from the parent to the child. The “View” chapter in the Newton Programmer’s Guide contains a more complete discussion of declaring views.

Linking Multiple LayoutsYou can organize your application into logical modules by laying it out in multiple layout windows. You link the individual files in two steps:

Page 82: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-23

1. In either the main layout file or a layout file that’s linked to the main layout file, lay out a small reference view, using the LinkedSubview element from the palette.

2. Link the linked subview to the external layout file by choosing Link Layout from the File menu.

The section “Adding a Linked View” beginning on page 3-17 illustrates how to link a separate layout file into an application.

If you make a link to a layout file that’s not already in the project, NTK automatically adds the file to the project. If you remove a linked file from a project (with the Remove File item in the Project menu), you also remove the information about links to that file.

The linked subview is a placeholder in the parent view. When the parent template is processed, the templates in the linked layout file replace the linked subview template. The name of the linked subview, however, replaces the name of the layout view in the linked file.

To declare a view in the linked layout file to an ancestor in the other file, you must declare the placeholder view (the linked subview) in its parent file. Child views in the linked layout file then declare themselves to the layout view in the linked layout file; they send messages up the hierarchy by referencing the placeholder view.

For example, consider a placeholder view with the name birds , in the baseView template in the main layout file. The layout view in the linked layout file is named bees , and it has a child named eggs , as illustrated in Figure 4-9.

In this example, the view birds declares itself to baseView , and the view eggs declares itself to bees . To send a message to its parent, the view eggs sends the message to birds . To send a message to eggs , baseView sends the message to birds.eggs .

Page 83: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-24 Laying Out Views

Figure 4-9 Declaring views across linked layout files

If you assign the same name to the placeholder view and the main layout view in the linked layout file, you don’t need to remember which name to reference.

Creating User ProtosYou can use the New Proto Template item in the File menu to start your own proto layout. You save the layout in a separate file and add it to the project through the Project menu.

baseView bees

eggsbirds(placeholder)

declare todeclare to

Before the build

baseView

birds

eggs

After the build

send message

Page 84: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Laying Out Views 4-25

Once you’ve added your proto to the project, you can lay out views based on it by choosing it from the User proto pop-up menu on the palette. For compatibility with the menu, give your proto layout files filenames that start with a standard alphanumeric character; don’t start filenames with punctuation, slashes, or other special characters (specifically, - , ! , ; , ^ , <, / , or ( ).

The section “Defining Your Own Proto” beginning on page 3-21 illustrates how to define and use your own proto template.

During the application build, NTK adds to the application’s base view one slot for each proto template you’ve defined. Each slot has the name pt_ filename and contains a reference to the user proto.

Creating Print Format TemplatesYou can use the New Print Format item in the File menu to start a print format template, that is, a template formatted for hard-copy printing. You save a print format template in a separate file and add it to the project through the Project menu.

During the build, NTK processes each print format file in the project and creates a constant named layout_ filename that points to the processed file. You use this constant in the format frame, which is required in the application base view of any application that prints. A format frame must contain at least a title slot and a mainFormat slot; the mainFormat slot references the format file, as illustrated in this example.

myFormatFrame := {title: “Print Record”,auxForm: nil,

textScript: 'myTextScript,

attachment: true,_proto: ROM_coverPageFormat,mainFormat: layout_myFormat

};

Page 85: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-26 Browsing and Editing Templates

The mainFormat slot in this example references a print format layout file named myFormat.

For more information on printing, see the “Routing” chapter in the Newton Programmer’s Guide.

Browsing and Editing Templates

You use the NTK browser and slot editors to customize your templates.

Browsing TemplatesA browser window lets you examine the templates in a local view hierarchy and the slots within each template.

You open a browser window by selecting a view and choosing New Browser from the Window menu. You can examine and edit slots in the template for the selected view or any of its descendants. If you want access to all of the templates in a layout file, choose New Browser with no view selected, with the layout view selected, or with the layout file selected in the project window. You can keep several browser windows open at once.

Figure 4-10 illustrates a browser window with the viewFlags slot open for editing.

The template list in the top-left corner lists the templates in the view hierarchy. The slot list to the right lists the slots in the selected template. Highlighting around either the template list or the slot list shows which is active; you can change the selection in the active window by pressing the Up arrow or Down arrow key.

You open a slot for editing by double-clicking its name in the slot list. The browser then displays the slot’s contents in the editing area in the lower part of the window. If you’ve changed the selection since opening a slot, clicking on the slot-name button in the editing area restores the template and slot selections.

Page 86: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Browsing and Editing Templates 4-27

Figure 4-10 A browser window with the view flags slot open for editing

You can resize the three panes of the window by moving the boundaries with the mouse. You can customize the amount of information displayed and the text styles used in the template and slot lists through Toolkit Preferences, described in “Setting Preferences” beginning on page 4-7.

NTK provides different editors for different kinds of slots. Figure 4-10, for example, illustrates the view flags slot editor. “Editing Slots” beginning on page 4-30 describes the basic slot editors; Appendix D, “Slot Editors,” lists the specialized slot editors

The Apply and Revert buttons in the bottom-left corner allow you to apply or cancel any editing you’ve done to a slot since the last revert or apply. When you click Apply (or press Command-E or choose Apply from the Browser menu), NTK places any outstanding changes into the slot. NTK

Slot list

Editing area

Template list

Proto pop-up menus

Revert button

Apply button

Movable boundaries

Slot-namebutton

Page 87: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-28 Browsing and Editing Templates

checks for syntax errors in NewtonScript code. It reports errors in the Inspector window but applies the changes in any case. NTK automatically applies changes to a slot when you

n open a different slot for editing

n close the browser window

n save the file in which the slot is stored

n build a package.

Adding SlotsYou can add the slots defined by the Newton system software through the three proto pop-up menus:

n Specific—lists the proto-specific slots in the proto template on which the selected template is based

n Methods—lists the system-defined methods, that is, the code that executes when a view receives one of the system messages

n Attributes—lists attributes, that is, the view characteristics used by the Newton when displaying and manipulating views.

You add your own slots to a template through the dialog box illustrated in Figure 4-11, which NTK displays when you choose New Slot from the Browser menu.

The name centered at the top of the window’s content area (protoApp in this example) is the name of the template you’re adding slots to or—if the template isn’t named—a label based on the name of the template’s proto. You can add any of the system-defined slots through the proto pop-up menus, and you can add your own slot by typing the slot name into the Slot Name field.

Whenever the Slot Name field contains the name of a system-defined slot, the description field contains a brief description of the slot.

Page 88: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Browsing and Editing Templates 4-29

Figure 4-11 The New Slot dialog box

When you’re defining your own slots, you specify a slot type—which implies a slot editor—through the Editor pop-up menu, illustrated in Figure 4-12. The slot types are documented in the following section.

Figure 4-12 The Editor pop-up menu in the New Slot dialog box

When you’ve established a slot name and editor, click Add. To dismiss the dialog box, click Done.

Slot description field

Template name or label

Page 89: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-30 Browsing and Editing Templates

Editing SlotsYou use the five basic slot editors listed in this section to edit slots of the types available through the New Slot dialog box. NTK also supplies specialized edtiors for editing various system-defined slots, listed in Appendix D, “Slot Editors.”

You edit evaluate, script, and text slots with the text editor described in “Editing Text” beginning on page 4-32.

An evaluate slot is a slot that’s evaluated in place, that is, during the build when the compiled code is executed. You use evaluate slots to embed data that’s available only during the project build into the templates that will be used on the Newton. The value of the slot is set to the value returned by the last statement executed.

A script slot holds a function definition that’s compiled during the build for execution at run time. During the build, NTK processes evaluate and script slots the same way—that is, NTK first runs the slot contents through the compiler, and then executes the resulting code with the NewtonScript interpreter. The result for an evaluate slot is a value. The result for a script slot is a function.

A text slot holds text. During the build, NTK simply places the specified text in a text slot.

Figure 4-13 illustrates the initial displays for evaluate, script, and text slots.

Figure 4-13 Initial contents of evaluate, script, and text slots

Note that if you delete the keywords func() , begin , and end from a script slot, it becomes equivalent to an evaluate slot; conversely, if you place a function in an evaluate slot, it’s equivalent to a script slot.

Evaluate slot Text slotScript slot

Page 90: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Browsing and Editing Templates 4-31

Number, Boolean, rectangle, and picture slots use editors tailored to their data. Figure 4-14 illustrates the initial display for these four slot types.

Figure 4-14 The number, Boolean, rectangle, and picture slot editors

A number slot can hold either an integer or a real number. If you enter an integer in the range –536,870,912 to 536,870,911, NTK stores it as type integer . If you enter an integer outside that range or a number containing a decimal point, NTK stores it as type real .

A Boolean slot can hold only the value true or nil .

Boolean slot

Rectangle slot

Picture slot

Number slot

Page 91: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-32 Browsing and Editing Templates

The rectangle slot holds four integers. NTK automatically calculates the width and height. In your own rectangle slots, you can use the four integers however you want. In a viewBounds slot, the meanings of the four values depend on the value of the template’s viewJustify slot, as documented in Appendix D, “Slot Editors.”

The picture slot editor lets you place a 'PICT' resource in a slot. You specify a resource file and a named icon within that file. The File pop-up menu displays all resource files in the project. Named 'PICT' resources within the selected file appear in the Picture list. The selected picture appears in the rectangle to the right of the resource list. NTK displays the width and height in pixels. If the image is larger than the space in the editing area, NTK scales it to fit, for your viewing purposes only.

A picture’s mask is a parallel 'PICT' resource that’s used to display the image when it’s selected. To supply your own mask, place it as a resource in the same file, with a trailing exclamation point on the resource name and check Include Mask!. If the resource is named wave, for example, the mask takes the name wave! . If you don’t supply your own mask, NTK generates a simple one automatically from the original.

Editing TextYou edit text in slots, the project data file, and the Inspector window with a text editor that follows the basic Macintosh user interface conventions:

n The blinking cursor marks the current insertion point, that is, the place where keystrokes are inserted. You change the insertion point by moving the cursor with the mouse and clicking at the new insertion point.

n You select text by holding down the mouse button and dragging the cursor through the text to be selected. Double-clicking selects the word in which the cursor appears. Triple-clicking selects an entire line.

n The Cut, Copy, and Paste items in the Edit menu (and their keyboard equivalents: Command-X, Command-C, and Command-P) delete selected text from the slot and place it on the clipboard, copy the selected text to the clipboard without deleting it, and paste the contents of the clipboard, respectively.

n Keystrokes replace selected text.

Page 92: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Browsing and Editing Templates 4-33

You can also navigate, select, and manipulate text with the arrow keys and keystroke combinations listed in Appendix A, “Keyboard Text-Editing Commands.”

As a help mechanism, NTK supplies argument information when you’re entering global functions and common messages. When you type a left parenthesis after a token that’s listed in the editor’s internal database, NTK displays a help line in the space to the left of the horizontal scroll bar. To see the arguments for the selValue function, for example, type

setValue(

The help message appears in a box to the left of the horizontal scroll bar, in either the browser or the Inspector window, as illustrated in Figure 4-15.

Figure 4-15 The Inspector window with a help message displayed

The search and display are triggered by the typing of the parenthesis, not by the position of the cursor.

Help message

Page 93: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-34 Browsing and Editing Templates

Searching for Text in FilesThe Edit menu contains a number of items that let you search for a specified string in layout files, the project data file, or an Inspector window.

Listing Instances of a String

The List item identifies all instances of a string in a template file or in all template files in a project. You specify the string and the search criteria through the dialog box illustrated in Figure 4-16.

Figure 4-16 The dialog box for searching with List

Select one of the radio buttons at the top of the window to specify the files to be searched.

In Layout Searches only the layout file for the active browser or layout window.

In Project Searches all layout files in the open project.

Page 94: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Browsing and Editing Templates 4-35

Select one of the four radio buttons below the string field to specify the target of the search.

Frame With Name Searches for frames whose name contains the specified string.

Slot With Name Searches for slots whose name contains the specified string.

Text in Slot Searches for a slots whose value contains the specified string.

All Searches for the specified string in a frame name, slot name, or slot value.

You can limit the search by checking one or both of the boxes.

Case Sensitive Finds only strings that match the capitalization of the specified string.

Whole Word Finds only instances in which the specified string appears as a word, that is, in which the specified string is not embedded within other text.

When you click Find, NTK finds and lists all occurrences of the specified string. You can double-click any of the entries to open or activate a browser window with that entry selected. If NTK finds no instances of the string, it sounds the system beep.

Finding Instances of a String

The Find and Find Next items search through text in the active window to find and select a specified string.

Find displays a dialog box, illustrated in Figure 4-17, in which you specify the string and search specifications.

The Whole Word option finds only instances in which the specified string appears as a word, that is, in which the specified string is not embedded within other text. The Case Sensitive option finds only strings that match the capitalization of the specified string.

Page 95: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-36 Browsing and Editing Templates

Figure 4-17 The dialog for searching with Find

When you click Find, NTK finds and selects the next occurrence of the speci-fied string. If NTK finds no instances of the string, it sounds the system beep.

The Find Next item finds the next occurrence of the string specified in the most recent Find dialog box.

The Find and Find Next items are available when you’re editing the project data file or a slot that contains text and when you’re working in the Inspector window.

Finding Slots in the Hierarchy

The Find Inherited item finds and selects in the layout file the view that contains a slot with the same name as the slot selected in the browser slot list.

The Find Inherited command looks first in the parent of the selected template. If it doesn’t find the selected slot there, it continues up the parent hierarchy to the top level. When it finds a slot with the same name as the selected slot, NTK opens another browser window, with the slot and its template selected. If it doesn’t find the slot in any template in the hierarchy, NTK sounds the system beep.

Page 96: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-37

Building a Project

NTK builds a package file—that is, a file containing the application or book as it will be installed on a Newton—from the files listed in the project file.

A package file consists of a header containing package information and one or more parts containing code and data. An application is stored in a part of type form ; a book is stored in a part of type book . When a package is installed on the Newton, the Newton operating system automatically opens the package and dispatches the parts to the appropriate handlers.

NTK compiles and executes NewtonScript code, and processes templates and book files, to produce a data object that can be used by the Newton. The compiler compiles the text in the various source files, and the interpreter executes the resulting code at predetermined points. The code that executes during the build creates the objects that are placed in the application package. Objects in memory during the build are not necessarily available at run time.

Some of your code executes on the Newton, some on the Macintosh, and some in both places. The Newton and the Macintosh are running essentially the same interpreter, but the kinds of commands executed tend to be different. Some functions—such as those that handle resources—are available only on the Macintosh. The Newton Programmer’s Guide, which documents the other Newton programming functions, identifies functions that are available only at compile time. The resource-handling functions are described in this book in Appendix C, “Resources.”

The next section, “The Build Environment,” describes the files that are not explicitly in the project file but that affect the project build. The section “Build Sequences” beginning on page 4-46 describes the order in which files and templates are processed and steps through the processing of a template.

Page 97: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-38 Building a Project

The Build EnvironmentDuring the build, NTK processes the layout files you create with the NTK graphical editor and list in the project file. Before and during the build, NTK also processes a number of other special files.

This section describes

n the global data file, which is compiled and executed when you open NTK

n the project data file, which is compiled and executed at the beginning of a build

n the platforms files, which contain platform data and utility functions.

This section also describes the constants and variables you can use to access and manipulate files during the build.

Global Data File

The global data file is an adjunct to NTK. You can place in it NewtonScript code that you want available from any project.

The global data file—a file with the name GlobalData in the same folder as the NTK application—is compiled and executed once each time you open NTK. Code you place in the global data file is available at compile time to any project you build.

If the compiler encounters an error in the global data file, it displays the error type, filename, and line number. When you dismiss the error dialog box, NTK quits. The prudent course is to develop code in the project data file (documented in the next section) and move it to the global data file only when it’s debugged. If you cannot launch NTK because of a problem in the global data file, you can bypass it by removing the file from the folder. You can create and edit a global data file with any application that can produce simple text files.

Page 98: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-39

Project Data File

The project data file is an adjunct to your project—it’s a way to make declarations available to your project at compile time.

NTK compiles and executes the project data file as the first step in the build.

The project data file is stored in the same folder as the project file. You create and edit the project data file by choosing Project Data from the Project menu.

You can place in the project data file

n a script named InstallScript , which is run when the package is installed on the Newton

n a script named RemoveScript , which is run when the package is removed

n other valid NewtonScript code.

This example illustrates a simple project data file that defines constants for the application symbol and package name and defines install and remove scripts that register an application with the system Find and Intelligent Assist services.

constant kAppSymbol := '|Hello:TUT|;

constant kPackageName := "Hello:TUT";

InstallScript := func(partFrame)

begin

SetAdd( FindApps, kAppSymbol, true );

partFrame.result := regTaskTemplate(myTemplate);

end;

RemoveScript := func(partFrame)

begin

SetRemove( FindApps, kAppSymbol );

unRegTaskTemplate(partFrame.result);

end;

Page 99: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-40 Building a Project

Defining constants in the project data file makes them available to code that’s executed during the application build. “Build Sequences” beginning on page 4-46 describes the build sequence in detail.

To access a variable from the project data file in a run-time script, place a reference to it in an evaluate slot, described on page 4-30.

You can use the NewtonScript constant syntax or the compile-time function DefConst to define constants and initialize them in your project data file, as described in the section “NewtonScript Code” on page 4-41.

InstallScript

The install script is an optional script that’s executed when a package is installed on the Newton—when the card containing it is inserted or when the package is downloaded.

After NTK processes the project data file, it looks for a variable with the name InstallScript . If one exists (that is, if you’ve defined an install script in your project data file), NTK places it in the package as the install script for the part.

The install script is a function with one argument:

InstallScript( partFrame)

partFrame The part frame for your application. This frame has a slot named theForm , which contains a reference to your application’s base template.

RemoveScript

The remove script is an optional script that runs when your application is removed from the Newton—when the card containing it is removed, when you remove a package through NTK, or when the user removes your application through Memory Preferences.

After NTK processes the project data file, it looks for a variable with the name RemoveScript . If one exists (that is, if you’ve defined a remove script in your project data file), NTK places it in the package as the remove script for the part.

Page 100: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-41

The remove script is a function with one argument:

RemoveScript( partFrame)

partFrame The part frame for your application.

The RemoveScript runs after an application’s card has been removed. The theForm slot in partFrame therefore contains an invalid reference.

NewtonScript Code

NewtonScript code in your project data file is compiled and executed at the beginning of a project build. You use it to create objects that you want available throughout the build.

You can use the NewtonScript constant syntax to create constants with literal values for use throughout your project. The sample project data file on page 4-39, for example, creates constants for the application’s symbol and package name:

constant kAppSymbol := '|Hello:TUT|;

constant kPackageName := "Hello:TUT";

You can use the compile-time function DefConst in your project data file to create constants and initialize them with arbitrary expressions.

DefConst ( sym, expr)

sym A symbol that names the value

expr An expression that defines the value of the symbol

The DefConst function creates a constant referenced by the specified symbol and with the specified expression value.

The DefConst function is available only at compile time.

You can use DefConst to make compile-time values available at run time without adding a slot to the application base view. You could incorporate your own resource, for example, by calling GetPictAsBits in a definition:

refNum := OpenResFileX("HD:NTK:HappyProject:Joy.rsrc");

DefConst('kWren,GetPictAsBits("Wren", true));

CloseResFileX(refNum);

Page 101: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-42 Building a Project

You can access the bits from within the application templates by sending the CopyBits message:

:CopyBits(kWren,5,5,modeMask);

Functions you define with DefConst can be called with the NewtonScript call syntax or the Apply function. You could, for example, define a function with the symbol kFunction :

DefConst('kFunction,func(x,y) x + y);

You could then call the function within your application, without regard to inheritance, with

call kFn with (2,40);

The DefConst function accepts any valid expression that can be evaluated at compile time.

Variables and Constants

NTK defines a number of variables and constants that you can use to access files and templates during the build.

HOME Variable

NTK defines a variable called HOME that contains the pathname of the folder containing the open project file. You can use this variable to reach other files within the same folder during the build.

This line, for example, opens a resource file

rNum = OpenResFileX(HOME & "myResources.rsrc");

Layout-File Constants and V ariables

When NTK finishes processing a layout file (that is, a standard layout file, a print format layout file, or a user proto layout file), it creates a constant named layout_ filename that references the view hierarchy defined by that file. You can use the layout-file constant in conjunction with the .form

Page 102: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-43

command in the BookMaker application to incorporate the layout files for any small, application-like elements included in your book files. The .form command, which is documented in the manual that accompanies the Book Maker application, requires the height and width of the layout base view, which you can get from the viewBounds slot for the view as displayed in the browser.

You can also use the layout-file constants in other situations where you need a reference to the template, as long as you’re careful to use the constant only after it’s created.

When NTK processes a print format layout file, it also creates a variable named printFormat_ filename, which also references the view hierarchy defined by that file. This variable is redundant with the layout_ filename constant; it remains for backward compatibility with earlier releases.

Platform Files

The platform files—stored in a folder named Platforms in the same folder as NTK—contain data tailored to different Newton products and a collection of Newton system definitions. The platform files also contain a number of utility functions and definitions for constants that reference them. The constant that represents a function is the function name with the prefix k and the suffix func (that is, k functionnamefunc ).

The release notes for each platform file list the functions in that file. The functions are available at compile time; you can make them available at run time by incorporating them into your application in one of two ways:

n In your application base view, define an evaluate slot with the same name as the function and initialize it to the corresponding constant. To use the NewInfo function, for example, you create a slot named NewInfo and set its value to kNewInfofunc . You can then call the function by sending a message to the application base view.

n Call the function with the NewtonScript call syntax or the Newton Apply function. This strategy saves space and time, because it does not require a slot in the base view and avoids inheritance lookup; it also works in code that doesn’t have access to your base view, such as the

Page 103: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-44 Building a Project

remove script. This strategy does not work for functions used as methods, which must be invoked using message sending. The Newton Programmer’s Guide identifies which functions are used as methods and which are global functions.

Resources

NTK recognizes a number of functions that let you incorporate Macintosh-style resources into your application. These functions—for opening and closing resource files and retrieving resources from them—are available on the Macintosh during the build, but they’re not available on the Newton at run time. Therefore, you can manipulate resources only in code that’s executed only during the build. You typically manipulate resources in the project data file.

You supply resources in resource files that you’ve added to the project file through the Add File item in the File menu. You open a single resource file with the OpenResFile function; you open multiple resource files with the OpenResFileX function. You close resource files with the CloseResFile and CloseResFileX functions.

NTK supplies the GetPictAsBits function for handling 'PICT' resources and the two functions GetSound and GetSound11 for handling 'SND ' resources. You can use the functions GetResource and GetNamedResource to retrieve any other resources that your code can handle.

The following code in the project data file, for example, opens a resource file named named Joy.rsrc, retrieves 'PAT ' and 'SND ' resources, and closes the resource file.

refNum := OpenResFileX(Home & "Joy.rsrc");

gCheckerBoard :=

GetNamedResource("PAT ","checkerBoard", 'pattern);

gChickadee := GetSound("chickadee");

CloseResFileX(refNum);

Page 104: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-45

To embed the resources in your application, place them in evaluate slots in your application base view. In this example, two evaluate slots are initialized to the compile-time global variables gCheckerBoard and gChickadee .

See Appendix C, “Resources,” for a more complete description of the functions that handle resources.

Note that NTK automatically handles 'PICT' resources that you use for your application’s icon and in picture slots in your templates. For a description of the picture slot editor, see “Editing Slots” beginning on page 4-30.

You can create resource files on the Macintosh with the ResEdit application, available from the Apple Programmer’s and Developer’s Association (APDA). You can draw your pictures in any graphics program, and then paste them as 'PICT' resources into a resource file in ResEdit.

Merging Packages

NTK builds one part from the files listed in a single project file. After it assembles that part, it examines the folder in which the project file is stored for other package files with the names include.pkg [n]. If it finds any, NTK copies the parts in those packages and includes them in the project package.

You can place any number of other packages in the folder. The first package to be included has no number in its filename, and subsequent packages have the next highest integer appended. That is, to include two other packages in a build, put the packages in files with the names include.pkg and include.pkg1. Once the progression is broken (when, for example, NTK finds no file named include.pkg2), NTK stops searching.

Page 105: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-46 Building a Project

The added parts come before the newly created part in the package. If, for example, the project folder contains two package files, include.pkg containing parts A and B, and include.pkg1 containing a single part C, the final package contains four parts, in this order: A, B, C, new part.

The package attributes of the packages being merged are ignored; the final package contains only the package attributes established for the current build through the Project Settings dialog box. Name, symbol, and other part settings remain intact for each part.

The order of the parts in the package determines the order in which the Newton operating system dispatches the parts—it determines, for example, the order in which the install and remove scripts are executed.

Build SequencesThis section describes

n the order in which files are processed when NTK builds an application or a book and

n how NTK processes a layout file

Part A

Part generated

Final packageinclude.pkg1

Project files

Part C

include.pkg Part generated

New part

Part B

in this build

in this build

Part A

Part B

Part C

New part

New part

Page 106: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-47

Building an Application

When you choose Build Package from the Project menu, NTK first scans the project file to determine whether it contains a book file. If not, NTK builds an application, following this sequence:

1. Compile and execute the project data file.Memory objects created by the project data file are available to the templates processed during the rest of the build.

2. Process the templates in the print format files, as described in the section “Processing a Layout File” on page 4-49.As it processes each print format file, NTK creates a constant with the name layout_ filename, as it does for every layout file it processes. It also creates a variable with the name printformat_ filename.

3. Process the templates in the layout files (starting at the main layout and recursively processing the view hierarchy), as described in the section “Processing a Layout File” on page 4-49.After it processes each layout file, NTK creates a constant with the name layout_ filename that contains a reference to the layout view for that file.Note that when NTK reaches a template that’s based on an unprocessed user proto, it must process first the proto and then the template. Whenever it adds a user proto to an application, NTK places in the application base view a slot with the name pt_ filename that contains a reference to the user proto. NTK also creates the layout_ filename constant when it processes a proto file, as it does for every layout file it processes.

4. Process any unprocessed user protos.This step incorporates into the application any protos you’ve supplied for creating views at run time only.As usual, NTK creates the layout_ filename constant for each proto file.

NTK always processes the main layout file first and processes other layout files as they are encountered in the view hierarchy. Print format files are processed before all other layout files but in no guaranteed order among themselves.

Page 107: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-48 Building a Project

Building a Book

When you choose Build Package from the Project menu, NTK first scans the project file to determine whether it contains any book files. If it does, NTK builds a book, following this sequence:

1. Compile and execute the project data file.Memory objects created by the project data file are available to the templates processed during the rest of the build.

2. Process the templates in the print format files, as described in the section “Processing a Layout File” on page 4-49.After NTK processes a print format layout file, it creates a constant with the name layout_ filename, as it does for every layout file it processes. NTK also creates variable with the name printformat_ filename that contains a reference to the view hierarchy defined by that file.

3. Process all top-level layout files—that is, those that are not linked as subviews into other layout files—as described in the section “Processing a Layout File” on page 4-49.Note that the layout files linked as subviews are processed as part of the processing of the templates that contain them.After it processes each layout file, NTK creates a constant with the name layout_ filename that contains a reference to the file.Note that when NTK reaches a template that’s based on an unprocessed user proto, it must process first the proto and then the template. NTK also creates the layout_ filename constant when it processes a proto template file.

4. Process any unprocessed user protos.This step incorporates into the book any protos you’ve supplied for creating views at run time only.As usual, NTK creates the layout_ filename constant for each proto file.

5. Compile and execute the book file.

Page 108: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Building a Project 4-49

Processing a Layout File

When NTK processes a layout file, it starts by processing the template for the layout view, the parent of all other templates in the file. In the course of processing a template, NTK processes all of its children. Therefore, the processing of a layout file begins and ends with the layout view, which is the first template in a file whose processing is started and the last template whose processing is completed.

After it finishes processing the template for the layout view, NTK creates the constant layout_ filename, which contains a reference to the view hierarchy defined by that file.

NTK processes each template in four steps:

1. Check the proto or viewclass slot, if one is present. If the template is based on an unprocessed user proto, process that proto.

2. Compile and execute code in the beforeScript slot, if it’s present.Memory objects created in the before script are available to evaluate slots in the template and its descendants.The beforeScript slot exists only during the build and only during the processing of the current template; the beforeScript slot does not appear in the frame that results from the processing of a template.The beforeScript and afterScript slots let you execute code specific to a template during the build. You can use the beforeScript slot to define functions and data that will be available during the processing of a single template, the same way you use the project data file, described in “Project Data File” beginning on page 4-39, to define functions and data that will be available during the entire build.

3. Process the template itself:n create the template and add the proto or view class slotn create the slots altered or added through the browser

As it creates each slot, NTK establishes the slot’s value. When it creates an evaluate or script slot, NTK compiles and executes any NewtonScript code in the slot. The result for a slot that contains code is a value. The result for a slot that contains a function statement is a function.

Page 109: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-50 Building a Project

n create the stepchildren slot (described in the “Views” chapter of the Newton Programming Guide)

n process the template’s children, adding each child to the stepchildren array as it’s created.

4. Compile and execute code in the afterScript slot, if it’s present.The view context is available to the after script through the variable thisView , which is a reference to the view template. You can use thisView to add slots or change the value of existing slots. This code in an afterScript slot, for example, would conditionally add an extra debug slot:

if debugOn then thisView.debugInfo := data to be saved;

This code creates the extra slot only when the Debug build option is set. “Application Settings” beginning on page 4-4 documents the Debug build option.

s WARNING

The thisView variable gives your after script access to any slot in a view. Use it carefully. s

The code in the afterScript slot is not part of the final application.

You can create beforeScript and afterScript slots for any view through the New Slot item in the Browser menu, documented in “Adding Slots” beginning on page 4-28. Create the slots as evaluate slots with the names beforeScript and afterScript .

Error MessagesIf NTK cannot build a package because of problems with the project—if, for example, it could not find a referenced user proto—it displays an error message describing the problem. NTK often displays additional information in the Inspector window, if it’s open.

If NTK encounters errors in the NewtonScript code contained in the project, or if it encounters an error in downloading, it displays an error message with the error number. You can look up error numbers in the “Errors” appendix in the Newton Programming Guide.

Page 110: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

Debugging With the Inspector 4-51

Debugging With the Inspector

The Inspector is an interactive debugging environment that lets you study your application and make changes while it’s executing. You can make an Inspector connection through the Toolkit App running on a Newton attached to the Macintosh by serial cable, as described in Chapter 1, “Installation and Setup.”

You communicate with the Newton through the Inspector window, illustrated in Figure 4-18.

Figure 4-18 Inspector window

Help field

Trace Offbutton

Page 111: Newton Toolkit User’s Guide

CHAPTER 4

Using the Newton Toolkit

4-52 Debugging With the Inspector

You make a connection to the Newton with the Connect Inspector item in the Windows menu. You can save the contents of the Inspector window through the File menu, and you can open the Inspector window without connecting to the Newton by choosing Open Inspector from the Windows menu.

You edit text in the Inspector window with the editor described in “Editing Text” beginning on page 4-32 and in Appendix A, “Keyboard Text-Editing Commands.”

The help field displays the parameters and return values of functions and common messages when you type a left parenthesis after a function or message name. The Trace Off button turns off a stack trace, as described in Chapter 5, “Debugging.”

You execute code you’ve typed in the Inspector window by selecting the text and pressing Enter. If you press Enter with no text selected, the Newton executes the current line.

The Inspector window gives you access to the NewtonScript interpreter and the object store on the Newton. You can call any of the debugging functions described in Chapter 5, “Debugging,” and you can execute any valid NewstonScript code in the Inspector.

During a project build, and when you’re editing templates in the browser, NTK displays warnings and error messages in the Inspector window.

“Using the Inspector” beginning on page 3-26 is a tutorial that introduces the Inspector.

Page 112: Newton Toolkit User’s Guide

The Inspector 5-1

CHAPTER 5

Debugging

This chapter describes the debugging facilities that you can use with the Newton PDA and the Newton Toolkit to inspect and debug your applications. This chapter describes

n the Inspector, the interactive debugger that is built into NTK

n debugging functions you can add to your NewtonScript programs for use with the Inspector

n common NewtonScript programming problems

The Inspector

The Inspector is an interactive debugger that lets you browse the Newton object storage system, issue debugging commands, and execute NewtonScript code on the Newton.

You use the Inspector by typing commands in the Inspector window. You open the Inspector window by choosing Open Inspector from the Window menu, an you can save the contents of an Inspector window by choosing Save or Save All from the File menu.

Page 113: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-2 The Inspector

You establish an Inspector connection to a Newton (and open the Inspector window if it’s not already open) by choosing Open Inspector command from the Window menu. You can make an Inspector connection to a Newton attached with a serial cable to the Macintosh, as described in “Installing the Toolkit App on the Newton” beginning on page 1-5.

Once you’ve connected the Inspector to your Newton, you can directly execute NewtonScript statements by typing them into the Inspector window and pressing the Enter key.

Using the InspectorYou can use an Inspector connection to perform a number of debugging activities, including:

n directly executing NewtonScript statements

n tracing the flow of execution

n examining the stack

n breaking automatically whenever an exception occurs on the Newton

n browsing and debugging views and other objects

n setting breakpoints at specific locations in your Newton program

n displaying memory statistics

You can type NewtonScript statements into the Inspector window to execute code on the Newton from your Macintosh keyboard.

The output of any printing function calls that you have embedded in your NewtonScript programs is directed to the Inspector window.

After you have connected the Inspector to your Newton and downloaded your application package, you can debug, modify, and again download your application from within the Newton Toolkit. If you select automatic down-loading in your Toolkit Preferences, your modified program application is automatically downloaded into the Newton every time you rebuild it. You can then debug using this cycle:

Page 114: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-3

1. Run your application on the Newton. The Inspector displays any output and traces execution.

2. If necessary, use the Inspector’s debugging functions to determine what problems you need to address.

3. Make necessary changes to your application with NTK.

4. Rebuild your application package in NTK.

5. Return to step 1.

You can interrupt the execution of your application by calling the BreakLoop function. Then, while the program is paused, you can use the other debug-ging functions to examine memory and the flow of control. The debugging functions are described in the section “Debugging Functions” beginning on page 5-16.

Tracing the Execution of Your Application

You can watch the flow of control through your application by telling the Inspector to trace the program execution. To trace the execution of every function call that occurs, type:

trace := 'functions

The Inspector then reports each function call with a message similar to this example.

Sending TrackHilite(18070494) to #440F671

=> TRUE

This example shows the TrackHilite message being sent. The numbers you see are references to frames. The reference in parentheses is the argument list to the TrackHilite message. The last reference is the view to which the message was sent. The second line (which starts with =>) is the return value from the TrackHilite method.

When you tell the Inspector to trace the flow of function calls, a lot of output is sent to your screen. If you want to follow the execution of your program even more closely (and generate even more output), you can tell the

Page 115: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-4 The Inspector

Inspector to trace every frame and variable access. You do this by setting the value of the trace variable to anything other than nil or 'functions . Typically, you use the value true :

trace := true

The output you get in the Inspector window with this same message after setting trace to true looks something like this example:

#1A TRUE

Sending TrackHilite(18070456) to #44193C9

get #4404191 / #477.penSoundEffects = TRUE

get #44193C9.viewCObject = 17864138

get #44193C9 / #38B.viewFlags = 515

set #44193C9 / #38B.viewFlags = 33554947

get #44193C9.viewHiliteScript = NIL

=> TRUE

Sending buttonClickScript() to #44193C9

Calling Print(#600E446D)

"The button has been clicked"

=> NIL

Calling breakLoop()

Sending hilite(NIL) to #44193C9

get #44193C9.viewCObject = 17864138

get #44193C9.viewFlags = 33554947

set #44193C9.viewFlags = 515

=> TRUE

get #44055F9 / #3B9BFD.viewIdleFrequency = 30000

Page 116: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-5

get #44055F9 / #3B9BFD.viewIdleScript = #28F09D

get #4419B41 / #4408AF1.userConfiguration = #4404191

// AND LOTS MORE OUTPUT AFTER THIS

Note

The output displayed in the Inspector window shows the internal address of each object, prefaced by the pound sign (#). You can ignore these address values. u

To turn off tracing, click the Trace Off button at the bottom of the Inspector window, or type

trace := nil

The Inspector does not immediately attend to this statement, which means that the volumes of information appearing in your Inspector window continue to appear after you have typed the statement. Clicking the Trace Off button works almost immediately.

Examining the Program Stack

While your Newton program is paused in a break loop, you can examine the state of the program stack with the StackTrace function. A trace is displayed in the Inspector window when you type

StackTrace()

The trace consists of an array of activation records, each of which represents the run-time call stack and contains five slots:

class The class name of the frame, which is always StackFrameInfo .

CodeBlock The name of the function for the activation record. This is generally the name of a method or of a global function. Some NewtonScript functions that do not have names show up as NIL in this slot.

Page 117: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-6 The Inspector

programCounter The value of the program counter. You can ignore this.receiver The receiver for the activation record. If the receiver has

a slot named debug, then that slot’s value is shown here. Otherwise the value will be NIL unless the receiver is a global variable, in which case, the variable’s name will be shown here.

contextFrame An array of symbols. There is one symbol for each parameter to the frame’s function and one symbol for each local variable. The parameters are listed first, followed by the local variables.

This example shows a simple stack trace:

[{class: StackFrameInfo,

CodeBlock: NIL,

programCounter: 2,

receiver: NIL,

contextFrame: []},

{class: StackFrameInfo,

CodeBlock: "functions.breakLoop",

programCounter: NIL,

receiver: NIL,

contextFrame: []},

{class: StackFrameInfo,

CodeBlock: buttonClickScript,

programCounter: 5,

receiver: NIL,

contextFrame: []},

{class: StackFrameInfo,

CodeBlock: viewClickScript,

programCounter: 10,

receiver: NIL,

contextFrame: [unit]}]

Page 118: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-7

The entire trace is enclosed in square brackets ([ and ] ). Each stack frame is enclosed in curly brackets ({ and } ).

The most recent function activation record appears at the top of the output, which means that you can trace through the sequence of functions by tracing backwards through the CodeBlock values. In the example above, the flow of functions is as follows:

NIL->functions.breakloop->buttonClickScript->

viewClickScript

The first two elements of the array represent the activation records for the StackTrace call and for the BreakLoop call that halted execution prior to the stack trace. These two elements are generally not of value to you.

To examine the values of parameters and local variables in the stack frames, you need to know how many parameters each function requires. You can then count the parameters to get to the local variables. For example, suppose you have a function myFcn:

myFcn: func(value)

begin

local x := 2;

breakloop();

return value+x;

end

If you call the function and print out a stack trace from the break loop, you see this frame in the output:

{class StackFrameInfo,

CodeBlock: myFcn,

programCounter: 6,

receiver: "vars.myFrame",

contextFrame:[value,x]}

Page 119: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-8 The Inspector

Because you have defined myFcn with one parameter, you know that value is a parameter and that x is thus a local variable.

The StackTrace function is described on page 5-18. Code blocks, receivers, and context frames are described in the chapter “Functions” in The NewtonScript Programming Language.

Breaking for Exceptions

You can raise exceptions in your NewtonScript programs to modify the flow of execution when certain conditions arise. You can also define exception handlers to take action upon certain conditions. The Inspector automatically reports exceptions that are raised by your code or by the Newton system software. NewtonScript exception handling is described in The NewtonScript Programming Language.

The Inspector reports on all exceptions that occur during the execution of your Newton application. You can optionally tell the Newton to automatically interrupt the execution of your program whenever an exception occurs. To do so, type

breakOnThrows := true

Then, whenever an exception occurs, the Newton stops execution and allows you to examine the stack, debug frames, or perform other debugging tasks in the Inspector. To resume execution of your Newton application, type

ExitBreakLoop()

You can disable the interruption of execution whenever an exception is raised by typing

breakOnThrows := nil

The Inspector continues to report each exception that is raised, but your program is not interrupted.

Page 120: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-9

Displaying Information in the Inspector Window

You can display the value of your Newton objects in the Inspector window by typing the object name. For example, if you type:

myView.text

Then you’ll see in the Inspector window the value of the slot named text in the view referenced by myView.

You can display object values from within an application by embedding the Print , Write , and Display functions. Each of these functions takes an object and displays the object’s value.

The Print function displays an object and adds a newline character. The Write function is like the Print function, except that it does not append a newline character to the output. The Display function is like the Write function, except that it attempts to make the output more readable by adding quote marks and similar punctuation.

The following example shows the differences that result from using each of the three functions to print some text followed by the value of a slot in a view. The slot that is printed is a text slot with the value “TAP HERE” in a text-button view.

These statements:

Print("My view has the following value: ");

Print(myview.text);

Print("\n");

produce the following output in the Inspector window.

"My view has the following value: "

"TAP HERE"

"

"

#2 NIL

Page 121: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-10 The Inspector

These statements:

Write("My view has the following value: ");

Write(myview.text);

Write("\n")

produce the following output in the Inspector window.

My view has the following value: TAP HERE

#2 NIL

These statements:

Display("My view has the following value: ");

Display(myview.text);

Display("\n")

produce the following output in the Inspector window.

"My view has the following value: ""TAP HERE""

"#2 NIL

The Print , Display , and Write functions are described in more detail in the section “Debugging Functions” beginning on page 5-16.

Printing Objects in the Inspector Window

When using the Inspector to view objects, you can set the value of the printDepth variable to control how many levels of frames are displayed. The default value of printDepth is 1; the range of values is 0 to 3.

Each of the three display functions (Print , Display , and Write ) produces the same output when displaying a frame in the Inspector window.

Page 122: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-11

The following examples show the displayed results of printing a view with different print depths. This is what the results look like when printDepth is 0.

printDepth:=0;

print(myview)

{_Parent: {#4409731},

_proto: {#600E4285},

viewCObject: 0x110957D}

If you set printDepth to 1 and print the same view, you get the following results.

printDepth:=1

print(myview)

{_Parent: {_Parent: {#4405799},

_proto: {#600E406D},

viewCObject: 0x1108B2A,

viewclipper: 17862493,

base: <1>,

viewFlags: 5},

_proto: {text: "TAP HERE",

buttonClickScript: <CodeBlock, 0 args

#600E4345>,

viewBounds: {#600E4575},

viewJustify: 6,

_proto: {#38B},

debug: "MyButton"},

viewCObject: 0x110957D}

Page 123: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-12 The Inspector

If you set printDepth to 2, you get a great deal of information. The first few lines of the results are shown here:

printdepth:=2#8 2

print(myview)

{_Parent: {_Parent: {_Parent: {#4409D59},

_proto: {#47F}, viewCObject: 0x1107CB7,

RemoveOldMeetingsForm: {#4405369},

downButton: {#44055C9},

// lots more output goes here

Setting the value of printDepth to 3 adds another level of frames to the results. The beginning of those results is shown here.

printdepth:=3

#C 3

print(myview)

{_Parent: {_Parent: {_Parent: {ioStopping: NIL, classes: {#4403CD9},

extras: [#4407C89],

navigator: {#4403E89},

AvailablePrinters: [#4403F39],

international: {#4404DA1},

routing: {#4403E11},

poweroffhandlers: [#4403F61],

// lots more output goes here

Page 124: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-13

Displaying the Contents of a View

You can display the contents of a view with the Debug function. When you type

Debug("myButton")

the Debug function searches through the templates looking for one that matches "myButton" ; if it finds one, it displays the contents of that view.

The Debug function attempts to match a template by examining the value of the slot named debug in the template. The template is considered a match if it contains a debug slot and if the value of that slot starts with the specified template name.

When Debug finds a match, it displays the view contents in the Inspector window and returns the view as its value. Debug prints the view using the same format as the Print function does for views. This means that the value of the printDepth variable controls how much information is displayed, as described in the section “Printing Objects in the Inspector Window” beginning on page 5-10.

NTK automatically creates a debug slot for any named template in your project. You can also add a slot named debug to any frame in your program and assign the slot a unique name. This allows the Debug function to find that frame.

To access the view for a template in the Inspector, you call the Debug function and assign the view that it returns to a variable. For example, to access the view for a template named myButton , you type

myView := Debug("myButton")

You can then use myView to access the view.

The Debug function is described on page 5-17.

Page 125: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-14 The Inspector

Displaying the View Hierarchy

You can display the hierarchy under a view with the DV function. When you type

DV(myView)

the following information is displayed for the view referenced by myView and its children:

name The name of the view or its proto template (if it’s based on a proto template and is not otherwise named).

address An internal reference to the object address. This value is prefaced with the pound (#) sign and can be ignored.

bounds The bounds frame of the view (left, top, right, bottom).number A hex number that is the value of the viewFlags slot.viewFlags A list of the viewFlags set for the view.

Here’s an example of DV output for a text button view that has no children:

MyButton #44132D9 [ 67, 67,167,183]

40000203 vVisible vReadOnly vClickable

Here is an example of DV output for a simple application view that does have children, including the view shown above:

MyApp #4409679 [ 8, 9,219,316] 10000005

vVisible vApplication vHasChildrenHint|protoTitle #4409C89 [ 65, 7,162, 23] 40000003

vVisible vReadOnly|protoStatus #4409CE9 [ 8,298,219,316] 50000001

vVisible vHasChildrenHint||analogClock #4409D51 [ 12,298, 29,315] 60000201

vVisible vClickable vHasIdlerHint||protoPicture #4409D21 [200,300,213,313] 40000203

vVisible vReadOnly vClickable|MyButton #4409D39 [ 67, 67,167,183] 40000203

vVisible vReadOnly vClickable

Page 126: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

The Inspector 5-15

The first view listed is the view specified as the parameter to DV. In this case, the view is the top-level view of a simple application that includes a text-button child view. The child views are listed in hierarchical order. Each child view is preceded by one or more vertical bars to indicate where in the hierarchy the view is found. One vertical bar indicates that the view is a direct child of the parent, two bars means the view is a child of a child, and so on.

The DV function is described on page 5-18.

Debugging VariablesAs described in the previous section, the Inspector uses several variables to control how your debugging session operates. Table 5-1 summarize these variables.

Table 5-1 Debugging variables

Variable Value Explanation

breakOnThrows true Execution automatically breaks whenever an exception is raised.

nil The Inspector continues to report exceptions, but does not cause an execution break.

trace 'functions Prints tracing information whenever a function is called.

true Prints tracing information whenever a function is called or whenever a variable is referenced.

This option generates a tremendous amount of output in the Inspector window.

nil Disables the display of execution tracing information.

continued

Page 127: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-16 Debugging Functions

Debugging Functions

This section describes the debugging functions that are built into the Newton system software. You can use these functions in the Inspector window to find and view objects in memory, set breakpoints, and perform other debugging operations. The following functions are described briefly here and in more detail later in this section.

n The BreakLoop function interrupts the execution of your program

n The Debug function returns a reference to a named template

n The Display function prints an object in the Inspector window.

n The DV function prints out the hierarchy under a view.

n The ExitBreakLoop function resumes the execution of your program.

n The GC function performs a garbage collection on the NewtonScript heap.

n The GetLocalFromStack function returns the value of a local variable.

n The Print function prints an object in the Inspector window.

n The StackTrace function prints a stack trace in the Inspector window.

n The Stats function prints out Newton memory statistics.

n The Write function prints an object in the Inspector window.

printDepth 0 Sets the number of frame levels to print to 0.

1 Sets the number of frame levels to print to 1.

2 Sets the number of frame levels to print to 2.

3 Sets the number of frame levels to print to 3.

Table 5-1 Debugging variables (continued)

Variable Value Explanation

Page 128: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Debugging Functions 5-17

BreakLoop

BreakLoop()

Halts execution and allows you to examine the state of your application on the Newton. Execution is halted within the frame that is currently being executed. While execution is halted, you can type NewtonScript and debugging statements into the Inspector window to examine and modify your Newton program.

You can type slot names directly into the Inspector window to access or set their values. For example, suppose that you have a slot named myTotal in the current frame and that its current value is 102. If you type

myTotal

the Inspector displays

#1BC 102

The first number is an object system reference to the value, and the second number (the integer 102) is the value of the slot.

If you want to change the value of a slot, you can use a NewtonScript assign-ment statement. For example, you can change the value of the myTotal slot to 211 by typing

myTotal := 211

IMPORTANT

To resume normal program execution, you must use the ExitBreakLoop function, which is described on page 5-19. s

Debug

Debug( templateName)

Scans the templates in the system looking for one with a debug slot whose value matches the value of the templateName parameter.

templateName The string name of the template you want to examine.

Page 129: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-18 Debugging Functions

This function scans all of the templates in the system looking for a match and returns the view for that template. If no match is found, the Debug function returns nil .

The Debug function attempts to match a template by examining the value of the slot named debug in the template. The template is considered a match if it contains a debug slot and if the value of that slot starts with templateName.

When Debug finds a match, it displays the view contents in the Inspector window and returns the view as its value. Debug displays the view contents using the same format as the Print function does for views. This is described in the section “Displaying the Contents of a View” beginning on page 5-13.

Display

Display( object)

Displays the value of the object in the Inspector window.

object An object that you want displayed in the Inspector window.

The Display function provides you with the ability to print any NewtonScript object. This function produces almost the same output as do the Print and Write functions. Display appends a newline character to its output and also adds quotation marks and other punctuation to enhance the readability. The Display function is useful for debugging, but does nothing while executing on a stand-alone Newton.

The Display function always returns nil .

You can see an example of using the Display , Print , and Write functions in the section “Displaying Information in the Inspector Window” on page 5-9.

DV

DV(view)

Displays the contents of a view and the contents of its children in the Inspector window. DV also flashes the view on the Newton screen to provide you with a visual indication of its location.

view The view object that you want to display.

Page 130: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Debugging Functions 5-19

The DV function always returns nil .

A quick way to display the contents of a view is to use the Debug function, as described on page 5-17, to get a view object and call DV on that object. For example, the following line finds the view for the template named "myButton" and prints the contents of that view and its children:

Dv(Debug("myButton"))

There are three special symbols that you can specify for the view argument. These symbols are evaluated at run time:

n 'viewFrontMost returns the frontmost view on the screen that has the vApplication flag set in its viewFlags slot

n 'viewFrontMostApp returns the frontmost view on the screen that has the vApplication flag set in its viewFlags slot, but not including floating views (those with vFloating set in their viewFlags slot)

n 'viewFrontKey returns the view on the screen that accepts keys (there can be only one view that is the key receiver)

If a view is visible on the screen, DV produces a display of the view contents in the Inspector window, as shown in the section “Displaying the View Hierarchy” beginning on page 5-14. If the view is not visible, DV produces the following output:

No View found(hidden?)

ExitBreakLoop

ExitBreakLoop()

Exits a break loop that was invoked with the BreakLoop function and resumes normal program execution. The BreakLoop function is described on page 5-17.

The ExitBreakLoop function always returns nil .

Page 131: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-20 Debugging Functions

GetLocalFromStack

GetLocalFromStack( level, symbol)

Displays the value of the local variable symbol. The level argument specifies which receiver’s local variables you want to examine.

The GetLocalFromStack function returns t he value of the variable symbol as its function value.

GetLocalFromStack accesses the receiver information in the activation records that are shown when you call the StackTrace function. This means that the first two levels (levels 0 and 1) are related to the BreakLoop call and are not of value. To access a variable that is local to the current receiver, use level 2. For example, suppose that you have a simple method defined as follows:

func()begin

local str:="myString";

breakloop();

end

When this method executes, a break loop is entered. At that time, you can type the following in the Inspector window:

getlocalfromstack(2,'str)

The result displayed in the Inspector window is shown here.

#600E347D "myString"

GC

GC()

Forces a garbage collection in the NewtonScript heap. The frames heap is a reserved area of system memory from which space for all NewtonScript objects is allocated by the system.

Page 132: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Debugging Functions 5-21

GC frees all allocated objects that are no longer referenced. The Newton system software automatically performs a garbage collection when memory is needed, so you almost never need to call this function. The one exception is when you are about to call the Stats function, which is described on page 5-22.

The GC function always returns nil .

Print

Print( object)

Displays the value of the object in the Inspector window.

object An object that you want displayed in the Inspector window.

The Print function provides you with the ability to print any NewtonScript object. Print is similar to the Write and Display functions except that Print appends a newline character after displaying the object’s value in the window and does not add any punctuation. It is useful for debugging, but does nothing while executing on a stand-alone Newton.

The Print function always returns nil .

You can see an example of using the Print , Display , and Write functions in the section “Displaying Information in the Inspector Window” on page 5-9.

StackTrace

StackTrace()

Prints a stack trace in the Inspector window. The section “Examining the Program Stack” beginning on page 5-5 shows a stack trace and describes how to use the information in the trace.

The StackTrace function always returns nil .

Page 133: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-22 Debugging Functions

Stats

Stats()

Prints out memory statistics in the Inspector window. The NewtonScript heap is a reserved area of system memory from which space for all NewtonScript objects is allocated by the system.

The Stats function returns the number of bytes of memory that are available. To get an accurate result, you need to call the GC function before calling Stats . The output of the Stats function looks like this:

Free: 30608, Largest: 28384

Write

Write( object)

Displays the value of the object in the Inspector window.

object An object that you want displayed in the Inspector window.

The Write function provides you with the ability to print any NewtonScript object. This function produces the same output as does the Print function, except that Write does not append a newline character to its output. It is useful for debugging, but does nothing while executing on a stand-alone Newton.

The Write function always returns nil .

You can see an example of using the Write , Print , and Display functions in the section “Displaying Information in the Inspector Window” on page 5-9.

Page 134: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-23

Newton Programming Problems and Tips

This section describes several common Newton programming problems and provides some programming tips to help with debugging your applications.

This section addresses

n setting the wrong slot value because of the inheritance rules

n forgetting to set the function value before exiting the function

n producing memory problems due to dangling frame references

n generating unexpected comparison results when a value is nil

n generating errors when using nil in an expression

n trying to resize a read-only object

n drawing text that is not appearing on the screen

n attempting to print from within communications code

n using global variables to examine exceptions

n accessing the built-in error codes and messages

Common Programming ProblemsThis section describes a number of common problems that developers can encounter when programming with NewtonScript.

Setting the Wrong Slot Value

You often need to set the value of slots in a view in one of the methods that you implement for the view. If you aren’t explicit about which values of the view you are setting, you can cause unintentional effects. This is because NewtonScript will automatically create a slot for you if you make an assignment to a slot that doesn’t exist.

Page 135: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-24 Newton Programming Problems and Tips

If the slot you are setting already exists in the view, your assignment always works properly. For example, the assignment to the slot named time in the following example always works as expected.

myTemplate := {

viewClass: clView,

viewBounds: SetBounds(0,0, screenWidth, screenHeight),

viewFlags: vApplication,

debug: "myTemplate",

time: 0,

viewSetupDoneScript: func()

time := Time()

...

}

If the slot you are setting does not already exist in the view, then NewtonScript creates it as a local variable within the scope of the method only. If the slot exists only in the parent of your view, its value will be set in the parent view. If these are not the results that you intend, you need to be explicit about which view you want to affect. For example, suppose that in the above view there was no slot named time and that the parent view did include a slot named time . Then, the assignment

time := Time()

would assign the value of the Time function to that slot in the parent view.

You can use the special pseudo-variable self to make sure that the slot is created in your view if it does not yet exist. The value of self is always the current receiver. In the following example, a slot named time is created in the myTemplate view when the assignment statement is executed.

myTemplate := {

viewClass: clView,

viewBounds: SetBounds(0,0, screenWidth, screenHeight),

viewFlags: vApplication,

debug: "myTemplate",

Page 136: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-25

viewSetupDoneScript: func()

self.time := Time()

...

}

Using self ensures that the slot is created if it does not exist in the current receiver.

Similarly, if you want to be sure that you are accessing or creating a slot in the parent of your view, use the Parent method, as shown here:

self:Parent().time := Time()

For more details on how inheritance affects setting slot values, see The NewtonScript Programming Language.

Forgetting to Set the Function Return Value

In NewtonScript, every function has a value. Since you can put a return in the middle of a function, you can easily forget to return a value. If the caller expects a value back from your function and you don’t assign one explicitly, the function result might be garbage. It’s a good idea to make sure that every pathway through your function returns a value.

For example, the following function could produce undesirable effects.

diff : func(n1, n2)

begin

if (n1=nil) or (n2=nil) then return;

if (n1 > n2) then return n1 - n2

else return n2 - n1;

end

In this example, if either of the parameter values is nil , the function exits without your having explicitly established the return value of the function.

Page 137: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-26 Newton Programming Problems and Tips

Producing Memory Problems With Dangling Frame References

Another common programming problem in the Newton world is dangling frame references. As long as you maintain a reference to a child view, the Newton garbage collector cannot free the child view. If you keep many of these references around in your application, you might get the following error:

Frames Out of Memory

The solution is to clean up (set to nil ) your child view references when you are done with the views. This allows the garbage collector to collect the memory for the view frame, thus leaving more memory available in the NewtonScript heap.

Generating Unexpected Comparison Results With nil Values

An interesting situation that you might encounter in your NewtonScript programs occurs when you mistype the name of a slot in a comparison. If you mistakenly type a nonexistent slot name, then NewtonScript considers its value to be nil , which can then generate the wrong result. For example, suppose that you are using a function like the following:

MyCompareFrame: func(frame1, frame2)

begin

if (frame1.date = frame2.date) and

(frame1.month = frame2.month) then

return true;

else

return nil;

end

Page 138: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-27

Now suppose you want to compare the following two frames:

frame1 := {

day: 5, // note day instead of date

month: 12,

};

frame2 := {

day: 3, // note day instead of date

month: 12,

};

You would make this call:

MyCompareFrame(frame1, frame2)

This generates a result of true . This is because neither frame1 nor frame2 contains a slot named date , which is what the MyCompareFrame function is comparing. The statement

frame1.date = frame2.date

evaluates to

nil = nil

which causes the function to return true .

The best solution to this problem is to check both values and to explicitly handle the case when one or both is nil . You could change the function as follows.

MyCompareFrame: func(frame1, frame2)

begin

if (frame1.date = nil) or

(frame2.date = nil) or

(frame1.month = nil) or

(frame2.month = nil) then

return nil;

Page 139: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-28 Newton Programming Problems and Tips

if (frame1.date = frame2.date) and

(frame1.month = frame2.month) then

return true;

else

return nil;

end

Using nil in Expressions

If you use a non-numeric value in a mathematical expression, you’ll generate an error. For example, the following buttonClickScript method generates an exception:

func()

begin

local index:=0;

local str:="myString";

print("The button has been clicked");

index := index + StrPos(str, "xyz", 0);

print("Reached the end of the button click script");

end

If you use this method, you’ll see the following output in the Inspector window:

"The button has been clicked"

Exception |evt.ex.fr.type;type.ref.frame|: [-48404]

Expected a number. Got: {value: NIL}

You get this output because the StrPos function does not find the substring "xyz" and thus returns nil as its value.

You can also generate this error if you define a template that is based on a system proto and you forget to define one of the required numeric slots. If the value of one of these slots is used in a computation, then an exception is

Page 140: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-29

raised. For example, if you create a template based on the protoInputLine proto and do not define the viewLineSpacing slot, an error occurs because that value is used in the viewDrawScript method of the template.

Another way to generate an unexpected run-time error is to misspell a variable name in a mathematical expression. For example, the typographic error in this statement:

index := indx + 1;

generates the following exception:

Exception |evt.ex.fr.intrp;type.ref.frame|: [-48807]

Undefined variable "indx"

{Symbol: indx}

Trying to Resize a Read-Only Object

This is a common and frustrating error. It is almost always caused by attempt-ing to resize a template, which is a read-only object. The two most common cases, which are described in this section, are:

n trying to resize an array that is stored in a template

n trying to add children to a view whose stepChildren array is stored in a template.

If you include a slot in one of your frames that has an array defined as its default value, then the array is stored in the template, which is read-only. For example:

myArray: [1, 2, 3, 4]

When you instantiate the template at run time, a RAM-based view is created that inherits the read-only array. If you try to modify this array by adding elements to it, an error occurs.

Page 141: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-30 Newton Programming Problems and Tips

To successfully add elements to the array, first you need to clone it to create a RAM-based copy. You can do this with the following statement:

myArray := Clone(myArray);

Cloning the array copies the read-only array into RAM, creates a new myArray slot in the RAM-based view, and puts a reference to the RAM copy of the array in that slot.

A resizing error can also occur with slots that contain frames and strings. The error is less common with strings since they are usually replaced rather than resized.

Another instance of trying to resize an object that is read-only occurs when you define a template that is composed of multiple sub-templates. The template contains a stepChildren array that is predefined. When you instantiate the template at run time, a RAM-based view is created that inherits the read-only array. If you want to add children to the view at run time, first you need to clone the stepChildren array, as shown here:

self.stepChildren := Clone(self.stepChildren);

AddArraySlot(self.stepChildren, newKidInTown);

If you are not sure whether your view has a stepChildren slot, you need to use the HasSlot function. If the slot does not exist in the RAM-based view, you must clone it before adding elements.

Text Is Not Drawing

If you’ve passed a valid string to the MakeText function, but the text does not appear on the screen, it’s likely that the rectangle you’ve specified in the arguments to MakeText is too small. Try passing a larger rectangle to the MakeText function.

Page 142: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-31

Problems with Printing and Communications

You might be having problems with the Print , Write , or Display functions in your communications code, especially if you’ve placed them inside of state frames. These problems occur for two reasons:

n The serial port is already in use for other communications. Only one communications channel can be open at any time.

n The Print statements are generating a lot of interrupts. This interferes with the serial line and causes hang-ups in the communications.

If you need to issue a quick message from within your communications code and need to avoid calling Print , Write , and Display , you can use the system notification facility instead. For example, you could display a quick message with the following code.

GetRoot():Notify(kNotifyAlert,

EnsureInternal("My Comms App"),

EnsureInternal("Help, I'm dying!!!"));

Another technique that you can use to help detect these communications problems is to create an error array in the application base view. You can then add strings to this array from within your communications code, as shown here:

AddArraySlot(GetRoot().kAppSymbol.DebugArray,

"My Comms App:" && myDebugData);

Programming Tips for DebuggingThis section provides several suggestions to help you add debugging code to your applications.

Page 143: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

5-32 Newton Programming Problems and Tips

Using Global Variables to Examine Exceptions

If you are handling exceptions in your application, you can use the global variables shown in Table 5-2 to discover information about the exception. Note that the values of these variables are assigned by the top-level (system) exception handler, which means that you can use the values reliably only after the exception alert message has been displayed on the Newton screen.

IMPORTANT

The system assigns the current exception values to lastEx , lastExError , and lastExMessage after the exception message has been displayed on the screen. These variables are probably not useful when you set BreakOnThrows to true in the Inspector. s

Maintaining View State

If you need to maintain the state of a view, you should store your state information in a soup. If you maintain the view state in a view frame, you could lose the state information when the view is closed.

For example, you might need to maintain a state variable that tracks whether a check box is checked in a certain view. To do so, store the state variable in a soup.

Table 5-2 Exception handling global variables

Variable Description

lastEx the string name of the most recent exception that occurred on the Newton

lastExError the integer error code of the most recent exception

lastExMessage the string message associated with the most recent exception, if the exception contained a message

Page 144: Newton Toolkit User’s Guide

CHAPTER 5

Debugging

Newton Programming Problems and Tips 5-33

Accessing the Parent of a View

Whenever you need to access the parent of a view, use the Parent function to find the parent. For example:

myParent := myView:Parent();

Do not directly reference the parent by accessing the _parent slot in the view.

Peeking Into a Soup

You can peek at entries in a soup by using a cursor to navigate through the soup. To initialize a cursor, you can use the Query function as shown here.

curs := Query(uSoup,{type: 'index})

This approach is not generally recommended because it doesn’t specify an index path. However, it works because all soups have an index on the _uniqueId slot, which is used as the index path.

Page 145: Newton Toolkit User’s Guide

File Menu 6-1

CHAPTER 6

NTK Commands

This chapter describes the commands available through NTK’s menus.

File Menu

You use the File menu to create, save, print, and otherwise manipulate files.

New Layout (Command-N)Opens a new, untitled layout window.

You use this command to start a file containing the templates for your application’s views. You name the file when you save it.

“Laying Out Views” beginning on page 4-11 describes how to lay out views in a layout file. “Starting a Layout File and Adding It to the Project” beginning on page 3-4 illustrates how to start and use a layout file.

Page 146: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-2 File Menu

New Proto Template (Command-T)Opens a new, untitled proto layout window.

You use this command to lay out your own protos. You name the file when you save it. Start proto layout filenames with an alphanumeric character; do not start with punctuation, slashes, or other special characters.

“Creating User Protos” on page 4-24 describes user protos. “Defining Your Own Proto” beginning on page 3-21 illustrates how to define and use proto templates.

New Print FormatOpens a new, untitled print-format layout file.

You use this command to lay out templates formatted for printing on paper instead of displaying on the screen. You name the file when you save it.

“Creating Print Format Templates” beginning on page 4-25 describes how you reference print format templates.

Open (Command-O)Opens a saved layout file. The Open command displays a dialog box through which you specify the file to be opened.

You open a project file and the project data file through the Project menu. You open browser windows and the Inspector window through the Windows menu.

Link LayoutBrings an external layout file into the local hierarchy, by linking the external file to a linked subview template selected in a layout window. The Link Layout command displays the standard save-file dialog box for identifying the external layout file.

Page 147: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

File Menu 6-3

“Linking Multiple Layouts” beginning on page 4-22 describes linked layouts. “Adding a Linked View” beginning on page 3-16 illustrates how to link layout files.

Close (Command-W)Closes the active window and its associated file. Close can affect a layout file, a project file, a browser window, or the Inspector window. (Closing a browser window does not close its associated file, which is closed only when the layout window for that file is closed.)

If you close a window that’s been edited since its file was last saved, NTK displays a dialog box that gives you a chance to save changes before closing the window.

Save (Command-S)Saves the file associated with the active window. The saved file replaces the previously saved file of the same name. The file remains open.

The Save command affects only the one active window, that is,

n the layout file for the active layout window,

n the layout file for the active browser window,

n the project file associated with the project window

n the Inspector file, or

n the project data file.

Save AsSaves a new copy of the file associated with the active window. The Save As command opens a file-save dialog box, through which you specify the new name and location. Save As changes the name of the active window and closes the file associated with the window’s previous name.

Page 148: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-4 File Menu

You use Save As to name or rename a layout file and to create a new file. Save As is not available when the Inspector window or project data window is active, because you can’t change those names.

Save a Copy InSaves a separate copy of a layout or Inspector file, with the name and location you specify through the file-save dialog box. The Save a Copy In command does not change the name or path of the active window and leaves its associated file open.

You use Save a Copy In to back up a file or to put a copy of a file into another project.

Save All (Command-M)Saves all open layout files, the project file, and the Inspector and project data file if they’re open. If you’ve not yet saved a file associated with one of the layout windows, NTK prompts you for the necessary filename.

Use Save All before each project build to ensure that all files in the project contain all changes you’ve made.

RevertRestores the last saved version of the file associated with the active window. Any changes you’ve made since the last save are discarded. Any browser windows open on a layout file are closed when you revert the file.

Page SetupDisplays the Page Setup dialog box, which lets you specify the paper size and printing orientation for printing the active window.

Page 149: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Edit Menu 6-5

Print OnePrints one copy of the file associated with the active window on the printer already selected through the Chooser. This command prints without displaying the Print dialog box for your verification.

Print (Command-P)Prints the file associated with the active window.

When you choose Print, NTK displays the print dialog box, which identifies the selected printer and lets you verify or change the printing options.

Note

You must select Color/Grayscale in the printing dialog box to print a layout. u

Quit (Command-Q)Closes all open files and quits the Newton Toolkit. If you have made changes since saving any open files, NTK prompts you to save or discard the changes before closing the files.

Edit Menu

You use the Edit menu to manipulate the contents of a window—editing views in a layout window, for example, or text in a browser window.

Undo (Command-Z)Cancels the last change made to a view in a layout window or to a slot in a browser window. If, for example, you’ve just deleted a view from a layout, choosing Undo restores the view.

If NTK cannot undo the last operation, this command reads Can’t Undo and is disabled. You cannot undo changes to a slot after you’ve applied them.

Page 150: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-6 Edit Menu

Cut (Command-X)Deletes the current selection in the active window and places it on the Clipboard. You can then paste the material elsewhere. (Cut replaces anything previously copied or cut to the Clipboard.)

Copy (Command-C)Places on the clipboard a copy of the current selection in the active window. You can then paste the material elsewhere. (Copy replaces anything previously copied or cut to the Clipboard.)

Paste (Command-V)Pastes the contents of the Clipboard at the current insertion point.

If you’re pasting into a layout window, Paste places the contents of the Clipboard inside the selected view.

ClearDeletes the current selection without placing the material on the Clipboard.

Duplicate (Command-D)Makes a copy of the currently selected view or views and places the copy slightly offset from the original in the same parent view.

Select All (Command-A)Selects everything in the active window (that is, all views in a layout window, all text in an editor, or all files in a project window).

Page 151: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Edit Menu 6-7

Select HierarchySelects all child views of the selected view or views in a layout window. Selection continues down the hierarchy to the last child view.

Select in LayoutSelects the view in a layout window that corresponds to the currently selected view template in a browser. To use the Select in Layout command, first select a template in a browser template list.

Shortcut: Double-click on a template name in a browser window to select the corresponding view in its layout window.

You can also use Select in Layout to select invisible or hidden views.

List (Command-L)Finds and lists instances of a string in the active layout file or in all layout files in a project. The List command displays a dialog box, illustrated in Figure 6-1, in which you specify the string you want to find and select search specifications.

Figure 6-1 The dialog for searching with List

Page 152: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-8 Edit Menu

“Listing Instances of a String” beginning on page 4-34 describes the settings in the List dialog box.

Find (Command-F)Finds a character string in the active text window.

The Find command displays a dialog box, illustrated in Figure 6-2, in which you specify the text you’re interested in and a pair of search specifications.

Figure 6-2 The dialog for searching with Find

The Find command is available only when a text window is active or a text slot is open for editing.

“Finding Instances of a String” beginning on page 4-35 describes the Find dialog box.

Find Next (Command-G)Finds the next instance of the character string and search criteria specified in the last use of the Find command, which is documented in “Finding Instances of a String” beginning on page 4-35.

Page 153: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Edit Menu 6-9

Find InheritedFinds the first occurrence of the currently selected slot in the parent view template hierarchy. The Find Inherited command is available only when a browser window is active.

The Find Inherited command looks first in the parent of the selected template. If NTK doesn’t find the selected slot there, the search continues up the parent hierarchy to the file’s layout view (that is, NTK does not search across linked layouts). When it finds a slot with the same name as the selected slot, NTK opens another browser window, with the slot and its template selected. If it doesn’t find the slot in any template in the local hierarchy, NTK sounds the system beep.

Newt Screen ShotPlaces a bitmap of the Newton screen on the Macintosh Clipboard. This item is available only when the Inspector is connected.

Show ClipboardOpens the Clipboard window.

Toolkit PreferencesDisplays the Toolkit Preferences dialog box, illustrated in Figure 6-3, through which you set various characteristics of the Toolkit.

When you click OK, NTK stores your current settings in a file name Newton Toolkit Preferences in the system Preferences folder.

The fields in the Toolkit Preferences dialog box are described in “Setting Preferences” beginning on page 4-7.

Page 154: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-10 Project Menu

Figure 6-3 The Toolkit Preferences dialog box

Project Menu

You use the project menu to manage your application project.

Page 155: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Project Menu 6-11

New ProjectCreates and opens a new project file and opens a project window.

The project file is the list of files that make up the application, that is, the files that NTK processes during the build. You add files to the project file through the Add Window and Add File commands.

Open ProjectOpens an existing project file. You can have only on project open at a time.

Add WindowAdds the file associated with the active layout window to the project.

Add FileAdds a file to the project from anywhere on the desktop. The Add File command displays a dialog box through which you specify the name and location of the file.

Add Book FileAdds a book file to the project from anywhere on the desktop. The Add Book File command displays a dialog box through which you specify the name and location of the book file. A book file is the output from the Book Maker application.

Remove FileRemoves the selected file or files from a project.

Page 156: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-12 Project Menu

Update FileVerifies that all entries in the project file can be resolved to files that currently exist. When it can’t resolve an entry, NTK displays a dialog box, through which you identify the correct target file.

You use Update Files to update the project file when you’ve moved or renamed a file since adding it to a project.

Build Package (Command-1)Builds a package, including the files listed in the project file and following the specifications in Project Settings and Toolkit Preferences.

NTK places the package file in the same folder as the project file. The name of the package file is the name of the project with the suffix .pkg.

The section“Building a Project” beginning on page 4-37 describes how NTK builds a package.

Download Package (Command-2)Downloads the package file for the open project to a Newton.

You must install the Toolkit App on the Newton, as described in Chapter 1, “Installation and Setup,” before you can download a package to it.

Export Package to TextWrites the contents of the project data file and all files in a project into a text file. The name of the file is the project name with the suffix .TEXT.

You can open this file in any application that recognizes text files.

Page 157: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Project Menu 6-13

Install Toolkit AppInstalls the Toolkit App on a Newton PDA connected to the development system.

The Toolkit App handles the downloading of packages and supports the Inspector.

Chapter 1, “Installation and Setup,” describes how to set up a connection between the development system and the PDA prior to downloading the Toolkit App.

Mark as Main LayoutDesignates the selected file in the project window as the main layout file—that is, the layout file whose base view is the application base view.

This item does not affect book projects, because book projects have no main layout file.

Project DataOpens a window for editing the project data file.

The project data file is the first file processed during a build. It contains an application’s install and remove scripts as well as declarations and other NewtonScript code referenced throughout the project.

SettingsDisplays the Project Settings dialog box, illustrated in Figure 6-4, through which you establish the project specifications described in “Project Settings” beginning on page 4-3.

Page 158: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-14 Layout Menu

Figure 6-4 The Project Settings dialog box

Layout Menu

You use the layout menu to control the layout environment and manipulate views in the layout window.

Page 159: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Layout Menu 6-15

Layout SizeDisplays a dialog box, illustrated in Figure 6-5, that lets you set the size of the layout in pixels.

Figure 6-5 The Layout Size dialog box

If you choose a platform from the Platform pop-up menu, NTK fills in the width and height from the information in the platform file. If you choose Custom from the pop-up menu, NTK lets you set your own values for the width and height of the layout.

Autogrid On Turns Autogrid on and off. Autogrid constrains the corners of views to nodes on the grid. The default grid resolution is 8 by 8 pixels. You can change the resolution through the Set Grid command.

Set GridOpens the dialog box, illustrated in Figure 6-6, that lets you change the grid size used with Autogrid. The units are pixels.

Page 160: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-16 Layout Menu

Figure 6-6 The Set Grid dialog box

Move To FrontMoves the selected view in front of its siblings on the screen by placing it behind its siblings in the drawing list.

“Ordering Views” on page 4-19 describes how views are ordered.

Move To BackMoves the selected view behind its siblings by placing it ahead of its siblings in the drawing list.

“Ordering Views” on page 4-19 describes how views are ordered.

Move ForwardMoves the selected view one step behind other views in the drawing list, so that it’s drawn after the view it previously preceded.

You can also move a view forward by selecting it in the browser template list and pressing Option-Down arrow.

“Ordering Views” on page 4-19 describes how views are ordered.

Page 161: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Layout Menu 6-17

Move BackwardMoves the selected view one step ahead of other views in the drawing list, so that it’s drawn before the view it previously followed.

You can also move a view backward by selecting it in the browser template list and pressing Option-Up arrow.

“Ordering Views” on page 4-19 describes how views are ordered.

AlignmentOpens the dialog box, illustrated in Figure 6-7, through which you establish a view alignment scheme that’s applied to the selected views when you click Apply or subsequently choose Align.

Figure 6-7 The Alignment dialog box

“Aligning Views” beginning on page 4-18 describes the Alignment dialog box.

A subset of the alignment options appears on the drawing palette.

Page 162: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-18 Browser Menu

AlignAligns the selected views using the alignment scheme specified through Alignment.

You can apply the simplest alignment schemes to selected views by clicking one of the alignment buttons on the drawing palette.

Preview (Command-Y)Toggles the layout screen between layout mode and preview mode. In Layout mode, NTK shows the rectangular extents of each view on the screen. In preview mode, NTK displays the views approximately as they would appear on the Newton screen.

“Previewing” beginning on page 4-20 describes preview mode.

Browser Menu

You use the Browser menu to manipulate slots and to control how the browser displays templates and slots.

Template Info (Command-I)Opens a dialog box in which you can name and declare a selected view. A view name operates as a symbol in NewtonScript. Declaring a view allows you to access it symbolically from the view in which it’s declared and from descendants of that view.

Figure 6-8 illustrates the Template Info dialog box.

“Naming and Declaring Views” beginning on page 4-21 describes the Template Info dialog box.

Page 163: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Browser Menu 6-19

Figure 6-8 The Template Info dialog box, for naming and declaring views

New Slot (Command-=)Opens a dialog box, illustrated in Figure 6-9, for adding new slots to the selected template.

Figure 6-9 The New Slot dialog box

“Adding Slots” beginning on page 4-28 describes the New Slot dialog box.

Page 164: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-20 Browser Menu

Rename SlotOpens a dialog box that lets you rename the selected slot.

Figure 6-10 The Rename Slot dialog box

If the slot is open for editing, Rename Slot applies outstanding changes and closes the slot editor before changing the name.

Note that changing the name of the slot does not change existing occurrences of the name in scripts. Changing the case of a name through Rename Slot changes the name.

Delete SlotDeletes the selected slot from the view template.

Templates by TypeLists templates alphabetically by type.

Page 165: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

Browser Menu 6-21

Templates by HierarchyLists templates by hierarchy, with sibling views listed in the order they’re created.

Slots by NameOrders slots alphabetically in the browser slot list.

Slots by TypeOrders slots by type in the browser slot list.

Show Slot ValuesDisplays the value of each slot next to the slot name in the browser slot list.

Apply (Command-E)Inserts into the slot changes made in a slot editor.

RevertDiscards any changes made since the last Apply, or since the slot was opened for editing if no changes have been applied.

Page 166: Newton Toolkit User’s Guide

CHAPTER 6

NTK Commands

6-22 Window Menu

Window Menu

You use the Window menu to open browser windows and to open the Inspector window or connect the Inspector.

Open InspectorOpens the Inspector without making a connection to a Newton PDA. You can have only one Inspector window open at a time.

Connect Inspector (Command-K)Connects the Inspector to a Newton PDA with the Toolkit App installed and a connection to the development system. If the Inspector window is not open, Connect Inspector opens it.

Chapter 1, “Installation and Setup,” describes how to set up a connection between the development system and the PDA and how to install the Toolkit App. Chapter 5, “Debugging” describes the commands available through the Inspector.

New Browser (Command-B)Opens a new template browser on a layout file selected in a project window or at the level of the selected view in a layout window.

You use the broser to edit templates in a layout file. “Browsing and Editing Templates” beginning on page 4-26 describes the browser.

Page 167: Newton Toolkit User’s Guide

Setting the Insertion Point A-1

APPENDIX A

Keyboard Text-Editing Commands

This appendix lists the keyboard commands for navigating and manipulating text in NTK slots, the project data file, and the Inspector window.

You can use the keyboard to

n specify an insertion point

n select text

n manipulate selected text

n delete text

n change the effect of the next keystroke

The keyboard text-editing commands operate relative to the current insertion point or the selected text. “Editing Text” beginning on page 4-32 describes the basic NTK text editor.

You can reverse the last keyboard command by pressing Command-Z (Undo).

Setting the Insertion Point

You can set the insertion point with the commands in Table A-1. If text is selected when you set the insertion point, it is simply deselected.

Page 168: Newton Toolkit User’s Guide

APPENDIX A

Keyboard Text-Editing Commands

A-2 Setting the Insertion Point

Table A-1 Moving the insertion point

Motion Keystrokes

Back one character Left arrowControl-B

Forward one character Right arrowControl-F

Down one line Down arrowControl-NOption-Down arrow

Up one line Up arrowControl-POption-Up arrow

To beginning of word, or back one word

Option-Left arrowOption-B

To end of word, or to end of next word

Option-Right arrowOption-F

To beginning of line Command-Left arrowControl-ACommand-Option-Left arrow

To end of line Command-Right arrowControl-ECommand-Option-Right arrow

To next page Page downCommand-Down arrowControl-V

To previous page Page upCommand-Up arrowOption-V

To beginning of text Option-<Command-Option-Up arrow

To end of text Option->Command-Option-Down arrow

Page 169: Newton Toolkit User’s Guide

APPENDIX A

Keyboard Text-Editing Commands

Selecting Text A-3

Selecting Text

You can select text with the commands listed in Table A-2. If text is already selected when you issue one of the text-selection commands, the selection is extended.

Table A-2 Selecting text with keyboard commands

Selection Keystrokes

One character back Shift-Left arrow

One character forward Shift-Right arrow

One word back Option-Shift-Left arrow

One word forward Option-Shift-Right arrow

Back to beginning of line Command-Shift-Left arrowCommand-Option-Shift-Left arrow

Forward to end of line Command-Shift-Right arrowCommand-Option-Shift-Right arrow

Previous line Shift-Up arrowOption-Shift-Up arrow

Next line Shift-Down arrowOption-Shift-Down arrow

Back to beginning of page Command-Shift-Up arrow

Forward to end of page Command-Shift-Down arrow

Back to beginning of text Command-Option-Shift-Up arrow

Forward to end of text Command-Option-Shift-Down arrow

Page 170: Newton Toolkit User’s Guide

APPENDIX A

Keyboard Text-Editing Commands

A-4 Manipulating Selected Text

Manipulating Selected Text

You can use the commands listed in Table A-3 to manipulate selected text. As the table shows, NTK supports the customary Macintosh commands for cutting (Command-X), copying (Command-C), and pasting (Command-V).

Table A-3 Manipulating selected text

Manipulation Kaystrokes

Indent selection left Command-[

Indent selection right Command-]

Transpose selection with one character forward

Control-T

Cut selection to Clipboard Command-X

Copy selection to Clipboard Command-C

Paste contents of Clipboard over selection

Command-V

Page 171: Newton Toolkit User’s Guide

APPENDIX A

Keyboard Text-Editing Commands

Deleting Text A-5

Deleting Text

You can delete text with the keyboard commands listed in Table A-4. The NTK keyboard editing commands do not place deleted text onto the Clipboard; to delete the selection and place it on the Clipboard, use Command-X.

Table A-4 Deleting text with keyboard commands

Scope of deletion Keystrokes

Selection only ClearShift-Clear

Selection or one character back DeleteShift-Delete

Selection or one character forward

Control-DDelete forwardShift-Delete forward

Selection or one word back Option-Delete

Selection or one word forward Option-DOption-Delete forward

Selection and to end of line Control-K

Selection and to end of text Command-DeleteCommand-Option-DeleteCommand-Delete forwardCommand-Option-Delete forward

Page 172: Newton Toolkit User’s Guide

APPENDIX A

Keyboard Text-Editing Commands

A-6 Changing the Meaning of the Next Keystroke

Changing the Meaning of the Next Keystroke

You can use the key combinations listed in Table A-5 to modify the interpretation applied to the next keystroke.

Table A-5 Changing the interpretation of the next keystroke

Kaystrokes Effect

Control-[Escape

Interpret next keystroke as Option-keystroke

Control-U Multiply next keystroke by four

The sequence Control-U Option-B, for example, moves the insertion point back four words

Control-Q Quote next character—that is, ignore any special meaning and insert character code into text

The sequence Control-Q Option-B, for example, inserts an integral sign; Option-B alone moves the insertion point back one word

Page 173: Newton Toolkit User’s Guide

B-1

APPENDIX B

Keyboard Shortcuts

This appendix lists keystroke combinations that invoke NTK menu items and that affect views in a layout or Browser window.

The Command key on a Macintosh keyboard is the key with the propeller symbol and, possibly, an open Apple symbol.

Table B-1 Keyboard equivalents to menu items

Key combination Effect

Command-N New Layout

Command-T New Proto Template

Command-O Open

Command-W Close

Command-S Save

Command-M Save All

Command-P Print

Command-Q Quit

Command-Z Undo

Command-X Cut

Command-C Copy

Command-V Paste

Command-D Duplicate

Command-A Select Allcontinued

Page 174: Newton Toolkit User’s Guide

APPENDIX B

Keyboard Shortcuts

B-2

The keyboard commands listed in Table B-1 move templates within the view hierarchy. You can issue these commands with a template selected in a browser window. When a view is selected in a layout window, the Option key in combination with the arrow keys resizes the view, as described in “Resizing a View” beginning on page 4-16.

Command-L List

Command-F Find

Command-G Find Next

Command-1 Build Package

Command-2 Download Package

Option-Down arrow Move Forward

Option-Up arrow Move Backward

Command-Y Preview

Command-I Template Info

Command-= New Slot

Command-E Apply

Option-Down arrow Move Forward

Option-Up arrow Move Backward

Command-K Connect Inspector

Command-B New Browser

Table B-1 Keyboard equivalents to menu items (continued)

Key combination Effect

Page 175: Newton Toolkit User’s Guide

APPENDIX B

Keyboard Shortcuts

B-3

Table B-2 Keyboard commands that affect the hierarchy

Key combination Effect

Option-Left arrow Move the template one layer up in the hierarchy

Option-Right arrow Move the template one layer down in the hierarchy

Option-Up arrow Move the template one place up in the drawing list (that is, move view backward)

Option-Down arrow Move the template one place down in the drawing list (that is, move view forward)

Page 176: Newton Toolkit User’s Guide

About Resources C-1

APPENDIX C

Using Resources

A resource is a piece of data stored on the development system and incorporated into a Newton application during the project build. You can use resources to bring data from other sources into your application. NTK explicitly supports 'PICT' resources and 'SND ' resources, and it includes functions for retrieving any other resources your application can handle.

This appendix describes how to embed 'PICT' and sound resources in Newton applications and how to retrieve your own resources.

About Resources

A resource is a collection of data with a defined structure, stored in a designated resource file. Each resource has a type—an identifier specifying the format used to store the data—and a resource number that’s unique within resources of the same type.

The Macintosh environment provides predefined resource types for commonly used data formats such as pictures, sounds, and fonts. NTK recognizes these resource types and provides functions that let you make use of Macintosh-style resource data in your Newton application.

The functions described in this appendix—for opening and closing resource files and retrieving resources from them—are available on the Macintosh during the build. They’re not available on the Newton at run time. Therefore, you can manipulate resources only in code that’s executed during the build.

Page 177: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-2 About Resources

Resource FilesResource data itself can come from a number of sources—it may be the out-put from a utility program that captures sound or picture data and stores it in a file; it can be described textually and then compiled in a Macintosh application development environment such as the Macintosh Programmer’s Workshop (MPW); or it can be copied, cut, pasted, and otherwise manipu-lated with a resource-editing program like ResEdit. (ResEdit and MPW are available from APDA.)

Compiled resource data ultimately resides in a file known as a resource file. Macintosh resource files in NTK are customarily identified by a .rsrc filename extension.

A single resource file can contain multiple resources of dissimilar types.

Adding Resource Files to a ProjectTo include a resource file in a project, list it in the project file through the Add File item in the File menu.

Using ResourcesYou can include 'PICT' resources in an application by inserting them into any picture slot. To retrieve other resources, you must

1. open the resource file

2. extract the resource data

3. embed the resource data into the application

4. close the resource file.

You must retrieve resources in code that executes only on the Macintosh—typically in your project data file.

Page 178: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

About Resources C-3

Opening and Closing Resource Files

NTK automatically opens and closes the resource files containing 'PICT' resources that you acess through the picture slot editor or the Project Settings dialog box. You need to open and close resource files only if you’re manipu-lating the resources directly—when you’re using sound resources, for example, or when you’re using resources specific to your application.

Manipulating Single Resource Files

To open and close resource files one at a time, use the OpenResFile and CloseResFile functions. OpenResFile accepts as its argument the pathname to the resource file to be opened; this function closes the currently open resource file and opens the one specified by its argument. CloseResFile accepts no arguments; it expects only one resource file to be open when it’s called. This example illustrates opening and closing two resource files sequentially.

// open first rsrc file; note use of HOME variable

OpenResFile(HOME&"My1stResourceFile.rsrc");

// do things with My1stResourceFile while it’s open

. . .

// next call to OpenResFile closes My1stResourceFile.rsrc

OpenResFile ("HD:Folder:MyNextResourceFile.rsrc");

// do things with MyNextResourceFile while it’s open

. . .

// close .rsrc files before exiting Project Data

CloseResFile();

Manipulating Multiple Resource Files

If you need to open multiple resource files to compile your application, you’ll need to use the OpenResFileX and CloseResFileX functions, rather than their single-file counterparts.

The OpenResFileX function accepts as its argument the pathname to the resource file to be opened but does not close any resource files that are

Page 179: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-4 About Resources

currently open. This function returns a reference to the resource file that it opens; you later pass the reference to the CloseResFileX function to specify which resource file to close.

This example shows how to open and later close two resource files at once.

// save the refnum -- you’ll need it to close the file

refNum1 := OpenResFileX(HOME&"Happy.rsrc");

refNum2:= OpenResFileX("HD:Folder:Joy.rsrc");

. . .

// do things with resources while files are open

// close resource files before exiting Project Data

CloseResFileX(refNum1);

CloseResFileX(refNum2);

Extracting Resource Data

Once the resource file is opened, you’ll need to extract the resource data itself. You can use the functions GetResource and GetNamedResource to retrieve from an open resource file any resources that your code can handle.

Because a resource file can contain multiple resources of any type, NTK provides functions for extracting resources in various ways. For example, you can specify the resources to be retrieved by name or by resource ID.

Each Macintosh resource is identified by a number that is unique within its resource type; this number is called its resource ID and is assigned when the resource is created. The GetResource function retrieves from the open resource file the resource having the specified type and ID number. The resource is returned as a binary object having the class symbol specified by the final argument to this function. This example uses GetResource to retrieve a resource.

OpenResFile(HOME&"Happy.rsrc");

myPict:= GetResource( ' PICT ' , 1001, 'picture)

CloseResFile();

Page 180: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

About Resources C-5

This code returns resource number 1001 of type 'PICT' as a binary object of class 'picture ; the binary object returned is assigned to the compile-time variable myPict .

Each resource has a resource ID; you can also assign a name string to a resource. This name string can be used in conjunction with a resource type to specify the resource that the GetNamedResource function is to retrieve from an open resource file. Like GetResource , the GetNamedResource function also accepts an argument specifying the class that the returned binary object is to have. This example illustrates the GetNamedResource function.

gCheckerBoard := GetNamedResource( 'PAT ' ,

"checkerBoard", 'pattern);

This line returns the resource named checkerBoard of type 'PAT ' as a binary object of class 'pattern ; the binary object returned is assigned to the compile-time variable gCheckerBoard .

Specialized Resource Extraction Functions

The resource-extraction funcions described here do not interpret or process the binary resource data and therefore work with resources of all types. NTK also provides several specialized resource extraction functions that interpret or process the retrieved resource data in some way; these functions are described later in this appendix, in the sections “Using 'PICT' Resources” and “Using External Sound Resources.”

Extracting Raw Binary Data

You can also use various data-extraction functions to return raw binary data from a custom resource of your own design. For more information on these data-extraction functions, see the section “Data Extraction Functions” in the “Utility Functions” chapter of the Newton Programmer’s Guide.

Page 181: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-6 Using the Resource-Handling Functions

Defining custom resources is not discussed in this book; for detailed information about creating Macintosh-style resources, see

n the “Resource Manager” chapter of Inside Macintosh: Overview

n the “Resource Manager” chapter of Inside Macintosh: More Macintosh Toolbox

n the chapter “The Resource Compiler and Decompiler” in MPW: The Macintosh Programmer’s Workshop Development Environment.

n the documentation that accompanies ResEdit.

Using the Resource-Handling Functions

Current versions of NTK and the Newton object system support some kinds of resources more fully than others. As the Newton object system and NTK continue to evolve, the use of external resources of all types will be more tightly integrated with the object system, with corresponding support being added to NTK.

The use of 'PICT' resources is well supported in the Newton object system and NTK. For many of the system-supplied view prototypes, NTK locates the appropriate resource automatically when an external resource file is included in the application’s NTK project file.

On the other hand, the object system does not currently supply any proto-types that use external sound resource files; thus, you need to do a little more work to incorporate them in your application.

This section describes how NTK handles 'PICT' and sound resources and describes data extraction functions that are specialized for these resource types.The information in this appendix is based on version 1.05 of the Newton ROM and version 1.0 of Newton Toolkit.

Page 182: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

Using the Resource-Handling Functions C-7

Using 'PICT' ResourcesYou can draw your pictures in any graphics program, and then paste them as 'PICT' resources into a resource file in ResEdit. You add the resource file to an NTK project through the Add File item in the Project menu.

NTK lets you add named'PICT' resources to picture slots in your templates through the standard picture slot editor, illustrated in Figure C-1

Figure C-1 Adding a named 'PICT' resource to a picture slot

The File pop-up menu contains all resources files that have been added to the project file. The Picture list shows all named 'PICT' resources in the selected file. For more information on the picture slot editor, see “Editing Slots” beginning on page 4-30.

Making a Bitmap From a 'PICT' Resource

NTK also supplies the GetPictAsBits function for extracting bitmaps from 'PICT' resources. NTK uses this function when manipulating the resources you access through the picture slot editor.

The GetPICTAsBits function retrieves a 'PICT' resource by name from an open resource file, converts the 'PICT' to a bitmap, and returns a frame containing a bitmap object. It accepts as its arguments the name of the 'PICT' resource to be retrieved and a Boolean value specifying whether to

Page 183: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-8 Using the Resource-Handling Functions

retrieve the mask for the bitmap from the resource. This function is described completely in the “Resource Functions” section of this Appendix.

The following code example retrieves the 'PICT' resource named Daphne and stores it in the compile-time variable gDaphBits. Note that the mask is not used. To make the bitmap available to the application, you would use the compile-time global gDaphBits to initialize an evaluate slot in the application’s base view.

OpenResFile(HOME&"MyPicts.rsrc");

gDaphBits := GetPictAsBits("Daphne", nil);

CloseResFile();

You can make the bitmap data available by storing it in an evaluate slot in your application’s base view.

The “Drawing” chapter in the Newton Programmer’s Guide illustrates how you can use bitmap data when drawing.

Using External Sound ResourcesYou can use any program that saves 'SND ' resources to create sounds for your application. Some Macintosh models have a built-in sound-sampling program. NTK supplies the two functions, GetSound and GetSound11 , for extracting sound data from these resources.

The GetSound function reads a sound sampled at 22kHz and returns a Newton sound frame; the GetSound11 function reads a sound sampled at 22kHz, down-samples and filters it to produce data simulating the same sound sampled at 11kHz, and returns a Newton sound frame. The GetSound11 function reduces the space required to store sound data, at the expense of some of the resolution offered by a comparable 22kHz sample. Both functions expect the resource file containing the sound resource to be open already, and both functions accept as their sole argument a string specifying the name of the sound resource.

The following code example retrieves by name the 'SND ' resource chickadee and stores it in the compile-time variable gChickadee. To

Page 184: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

Resource Functions C-9

make the sound data available to the application, you would create a compile-time global gChickadee to initialize an evaluate slot in the application’s base view.

OpenResFile(HOME&"MySounds.rsrc");

gChickadee := GetSound("chickadee");

CloseResFile();

See the “Working With Sound” chapter in theNewton Programmer’s Guide for more complete information on using sound in Newton applications.

Resource Functions

This section describes the functions used to make frame objects from resource data.These function are available only during compile time—they are not available at run time.

Opening and Closing Resource FilesThis section describes the functions you use for opening and closing resource files.

OpenResFile

OpenResFile( pathToFile)

Opens the specified resource file.

pathToFile A full or partial pathname to the resource file to be opened. The HOME variable may be used in this pathname. Pathnames that contain spaces must be enclosed in double quotation marks.

This function opens only one resource file at a time. If another resource file is open, OpenResFile closes it before opening the file specified by the value of the pathToFile parameter.

Page 185: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-10 Resource Functions

Note

To open multiple resource files at one time, use the OpenResFileX function. u

OpenResFileX

OpenResFileX( pathToFile)

Opens the specified resource file and returns a reference to the open file. The reference that this function returns is typically saved in a local variable and passed as the argument to the CloseResFileX function.

pathToFile A full or partial pathname to the resource file to be opened. The HOME variable may be used in this pathname. Pathnames that contain spaces must be enclosed in double quotation marks.

CloseResFile

CloseResFile()

Closes the currently open resource file.

CloseResFileX

CloseResFileX( fileRef)

Closes the specified resource file.

fileRef A reference to the file to be closed; this reference is returned by the OpenResFileX function and must be saved for use with CloseResFileX .

Retrieving ResourcesThis section documents the functions to use to retrieve resources from an open resource file. You can retrieve resources by type and either name or resource ID.

Page 186: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

Resource Functions C-11

GetNamedResource

GetNamedResource( typeString, nameString, class)

Retrieves from an open resource file the resource specified by nameString and typeString and returns the resource data as a frame having the specified class symbol.

typeString A four-character string specifying the resource type of the data to be retrieved

nameString A string specifying the name of the resource to be retrieved.

class The symbol to be stored in the class slot of the frame returned by this function

GetResource

GetResource( typeString, id, class)

Retrieves the specified resource from an open resource file and returns the resource data as a frame having the specified class symbol.

typeString A four-character string specifying the resource type of the data to be retrieved

id A numeric string specifying the resource ID of the data to be retrieved

class The symbol to be stored in the class slot of the frame returned by this function

GetSound

GetSound( nameString)

Retrieves the specified 22KHz sound resource from the currently open resource file and returns a Newton sound frame.

nameString A string specifying the name of the sound resource to be retrieved. The sound must have been sampled at 22kHz.

Page 187: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-12 Resource Functions

If the specified sound is not sampled at that rate, NTK reports a compiler error:

//-- Compiler Error:Sound resource:"Boing" must be sampled at 22 KHz

To retrieve a sound samples at 11 Hz, use the GetSound11 function.

The sound frame that this function returns has the following slots.

sndFrameType The format of this sound frame. Currently, Newton sound frames always have the symbol 'simpleSound in this slot; future Newton devices may store other values here.

samples A frame of class 'samples containing the binary sound data. The sound data must have been sampled at 11Khz or 22KHz.

samplingRate A floating-point value specifying the rate at which the sample data is to be played back

dataType A code that reflects the data type. Currently, the value of this slot is always 1, indicating 8-bit samples.

compressionType A code that reflects the compression strategy. Currently, the value of this slot is always 0 (zero), indicating no compression.

GetSound1 1

GetSound11( nameString)

Retrieves the specified 11KHz sound resource from the currently open resource file and returns a Newton sound frame.

nameString A string specifying the name of the sound resource to be retrieved. The sound must have been sampled at 11KHz. If the specified sound is sampled at 22 Khz, NTK down-samples the sound (with filtering) from 22 Khz to 11 Khz, and returns a Newton sound frame that packages this sound as an 11kHz sample.

Page 188: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

Resource Functions C-13

The sound frame that this function returns has the following slots.

sndFrameType Specifies the format of this sound frame. Currently, Newton sound frames always have the symbol 'simpleSound in this slot; future Newton devices may store other values here.

samples A frame of class 'samples containing the binary sound data. The sound data must have been sampled at 11Khz or 22KHz.

samplingRate A floating-point value specifying the rate at which the sample data is to be played back

dataType Currently, the value of this slot is always 1, indicating 8-bit samples.

compressionTypeCurrently, the value of this slot is always 0 (zero), indicating no compression.

GetPictAsBits

GetPictAsBits( nameString, maskToo)

Retrieves the specified 'PICT' resource by name from an open resource file, converts the 'PICT' to a bitmap, and returns a frame containing a bitmap object and an optional mask.

nameString A string specifying the name of the resource to be retrieved.

maskToo A Boolean value indicating whether to construct a mask for the bitmap.

If you specify true , GetPictAsBits constructs a mask for the bitmap and returns it with the bitmap.

If you specify nil , GetPictAsBits searches for a mask, a 'PICT' resource in the same file with the resource name nameString! —that is, the name of the primary resource with an exclamation point appended.

Page 189: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

C-14 Resource Functions

If the value of the maskToo parameter is nil but no such resource is found, GetPictAsBits returns only the primary resource.

The bitmap object returned by this function is a frame with the following slots:

bits A reference to a binary object containing the bitmap data

bounds A bounds frame specifying the dimensions of the bitmap; for example,

{left: 0,

top: 0,

right: bitmapWidth,

bottom: bitmapHeight}

mask This slot is included only if a mask has been constructed or supplied. It contains a reference to a binary object containing the mask bitmap.

Note

'PICT' resources are stored much more compactly as binary 'PICT' objects (obtained with GetNamedResource ) than as bitmap objects (obtained with GetPictAsBits ). u

Page 190: Newton Toolkit User’s Guide

APPENDIX C

Using Resources

Summary of Resource-Manipulation Functions C-15

Summary of Resource-Manipulation Functions

This section categorizes the resource-manipulation functions by task.

Opening and Closing Resource FilesOpenResFile( pathToFile)OpenResFileX( pathToFile) // for multiple filesCloseResFile()CloseResFileX( fileRef)// for multiple files

Getting Resource DataGetNamedResource( typeString, nameString, class)GetResource( typeString, id, class)GetSound( nameString)GetSound11( name)GetPictAsBits( nameString, maskToo)

Page 191: Newton Toolkit User’s Guide

Script Slots D-1

APPENDIX D

Specialized Slot Editors

This appendix describes the specialized slot editors you use for editing the system-defined slots. The description of the viewBounds slot, which is a simple rectangle slot, specifies the meanings of the four integers under different justification settings.

Script Slots

You edit the slots containing system-defined messages with the basic NTK text editor described in “Editing Text” beginning on page 4-32.

The system messages appear in the Specific and Methods pop-up menus in the browser and New Slot dialog boxes. When you add one of these slots, NTK places the skeletal structure of the method in the slot. If you add a viewStrokeScript slot, for example, NTK defines the initial slot contents as

func(unit)

begin

end

If a method takes no parameters or requires no special return value, NTK sets the initial contents to the simple function statement

func()

begin

end

For descriptions of the standard methods, see the chapter “Handling System Messages” in the Newton Programmer’s Guide.

Page 192: Newton Toolkit User’s Guide

CHAPTER D

D-2 View Attributes

View Attributes

The view attributes slots contain various specifications that the Newton uses to create, display, and manipulate views. Some of the slots contain a single value or string. The viewOriginX and viewOriginY slots, for example, each contain a number, which you edit through the number editor. The viewFont slot contains a single string that specifies a font name. You edit it and the other attribute slots containing text with the standard NTK text editor, described in “Editing Text” beginning on page 4-32.

This section illustrates the specialized editors you use to use to edit the more complex view attributes slots. For detailed descriptions of the fields, see the chapter “Views” in the Newton Programmer’s Guide.

viewBounds

The viewBounds slot defines the bounds of a view. NTK automatically fills in the viewBounds values when you lay out a view in the graphical editor. The values in the four slots are relative to the parent or sibling view, and the exact meaning varies with different justification strategies, as defined in the viewJustify slot. Table D-1 summarizes the meanings of the Left and Right fields with different horizontal view justification settings. Table D-2 summarizes the meanings of the Top and Bottom fields with different vertical view justification settings.

Page 193: Newton Toolkit User’s Guide

APPENDIX D

Specialized Slot Editors

View Attributes D-3

Table D-1 Meaning of viewBounds fields for horizontal justification

Justifi cation Meaning of Left Meaning of Right

Left Relative The offset from the parent’s or sibling’s left edge to the view’s left edge.

The offset from the parent’s or sibling’s left edge to the view’s right edge.

Right Relative The offset from the parent’s or sibling’s right edge to the view’s left edge.

The offset from the parent’s or sibling’s right edge to the view’s right edge.

Center Relative The left offset of the view’s center from the parent’s or sibling’s center.

The total width of the view.

Full Relative The offset of the view’s left edge from the parent’s or sibling’s left edge.

The offset of the view’s right edge from the parent’s or sibling’s right edge.

Table D-2 Meaning of viewBounds fields for vertical justification

Justifi cation Meaning of T op Meaning of Bottom

Top Relative The offset from the parent’s or sibling’s top edge to the view’s top edge.

The offset from the parent’s or sibling’s top edge to the view’s bottom edge.

Bottom Relative

The offset from the parent’s or sibling’s bottom edge to the view’s to the view’s top edge

The offset from the parent’s or sibling’s bottom edge to the view’s bottom edge.

Center Relative The vertical offset of the view’s vertical center from the parent’s or sibling’s center.

The total height of the view

Full Relative The offset of the view’s top edge from the parent’s or sibling’s top edge.

The offset of the view’s bottom edge from the parent’s or sibling’s bottom edge.

Page 194: Newton Toolkit User’s Guide

APPENDIX D

Specialized Slot Editors

D-4 View Attributes

viewFlags

viewFormat

viewJustify

Page 195: Newton Toolkit User’s Guide

APPENDIX D

Specialized Slot Editors

Specific Slots D-5

viewEffect

viewTransferMode

Specific Slots

The slots in the Specific pop-up menu represent the slots that are specific to the selected proto. These slots hold methods or simple values that you edit with one of the standard slot editors.

Page 196: Newton Toolkit User’s Guide

IN-1

Index

A

activation records 5-5Add Book File command 4-2, 6-11Add File command 4-2, 4-44, 6-11Add Window command 4-2, 6-11afterScript slots 4-50Align command 6-18Alignment command 4-18 to 4-19, 6-17application base view 3-4, 4-12Apply command 4-27, 6-21AutoClose 4-5Autogrid On command 6-15Automatic download option 4-10Automatic indent option 4-10Automatic save option 4-10

B

base viewapplication 3-4layout 3-15

beforeScript slots 4-49books

adding a book file to a project 4-2build sequence 4-48

Boolean slots 4-31BreakLoop function 5-3, 5-17breakOnThrows variable 5-8, 5-15browser 4-26 to 4-33

browsing templates 4-26 to 4-28editing templates 4-28 to 4-33Preferences settings 4-9tutorial 3-9 to 3-12

build heap 4-11Build Package command 4-47 to 4-50, 6-12

application build sequence 4-47book build sequence 4-48Preferences settings 4-6processing templates 4-49 to 4-50project settings 4-4

C

class slot 5-5Clear command 6-6Clone function 5-30cloning 5-30Close command 6-3CloseResFile function C-10CloseResFileX function C-10codeBlock slot 5-5compression 4-7Connect Inspector command 4-52, 6-22contextFrame slot 5-6Copy command 6-6copying read-only objects 5-30copy protection, build option 4-7copyright, package 4-7Cut command 6-6

D

debug build option 4-4Debug function 5-13, 5-17

Page 197: Newton Toolkit User’s Guide

INDEX

IN-2

debugging 5-1 to 5-33cycle with Inspector 5-2examining the stack 5-5 to 5-8functions for 5-16 to 5-22trace 5-3tracing execution flow 5-3 to 5-5tutorial 3-26 to 3-30variables for 5-15 to 5-16

debugging functions 5-16 to 5-22debug slot 4-4, 5-13declaring views 4-21DefConst function 4-41 to 4-42Delete Slot command 6-20Display function 5-9, 5-18displaying values 5-9

controlling the depth 5-10Debug function 5-13Display function 5-9DV function 5-14Print function 5-9Write function 5-9

Download Package command 4-2, 6-12automatic Preferences setting 4-10

Duplicate command 6-6DV function 5-14, 5-18

E

error messages 4-50evaluate slots 4-30exceptions

breaking for 5-8ExitBreakLoop function 5-8, 5-17, 5-19Export Package to Text command 6-12

F

filesadding to project 4-2layout 4-2, 4-22print format 4-25proto 4-24resource 4-5saving 4-10

Find command 4-35 to 4-36, 6-8Find Inherited command 4-36, 6-9Find Next command 4-35 to 4-36, 6-8functions

BreakLoop 5-3, 5-17Clone 5-30CloseResFile C-10CloseResFileX C-10Debug 5-13, 5-17Defconst 4-41Display 5-9, 5-18DV 5-14, 5-18ExitBreakLoop 5-8, 5-17, 5-19GC 5-20GetLocalFromStack 5-20GetNamedResource C-11GetPictAsBits C-13GetResource C-11GetSound C-11GetSound11 C-12HasSlot 5-30OpenResFile C-9OpenResFileX C-10Print 5-9, 5-21StackTrace 5-5, 5-21Stats 5-22Write 5-9, 5-22

Page 198: Newton Toolkit User’s Guide

INDEX

IN-3

G

GC function 5-20GetLocalFromStack function 5-20GetNamedResource function C-11

example C-5GetPictAsBits function C-13GetResource function C-11

example C-4GetSound11 function C-12GetSound function C-11global data file 4-38Grid on setting 4-8

H

hardware requirements 1-2HasSlot function 5-30heap sizes 4-11HOME variable 4-42

I, J

icon, application 4-6indenting 4-10Inspector 4-51 to 4-52, 5-1 to 5-16

connecting 1-7, 5-2tutorial 3-26 to 3-30using 5-2 to 5-15

installationconnecting a Newton to a Macintosh 1-5installing NTK on a Macintosh 1-2 to 1-5installing the Toolkit App on a Newton 1-6troubleshooting 1-8

install scripts 4-40Install Toolkit App command 1-6, 6-13instantiation 2-2

K

keyboard text-editing commands A-1 to A-6

L

lastExError variable 5-32lastExMessage variable 5-32lastEx variable 5-32layout_filename constant 4-42, 4-49layout base view 3-15layout files

constants and variables referencing 4-42 to 4-43

creating 3-4, 4-11defined 2-3, 4-12linking 3-17 to 3-19, 4-22 to 4-24

layout Preferences settings 4-8Layout Size command 6-15layout size setting 4-9layout view 4-12linked subviews 3-14, 3-17, 4-23 to 4-24

defined 4-13LinkedSubview template 4-23

Link Layout command 4-23, 6-2List command 4-34 to 4-35, 6-7

M

main heap 4-11Mark as Main Layout command 6-13masks 4-32Move Backward command 4-19, 6-17Move Forward command 4-19, 6-16Move To Back command 4-20, 6-16Move To Front command 4-20, 6-16

Page 199: Newton Toolkit User’s Guide

INDEX

IN-4

N

nameapplication 4-4package 4-7

naming views 4-21New Browser command 4-26, 6-22New Layout command 4-11 to 4-13, 6-1New Print Format command 4-25, 6-2New Project command 4-2, 6-11New Proto Template command 4-24, 6-2New Slot command 4-28 to 4-29, 6-19Newt Screen Shot command 6-9number slots 4-31

O

object values, displaying 5-9Open command 6-2Open Inspector command 4-52, 5-1, 5-2, 6-22Open Project command 6-11OpenResFile function C-9

example C-3OpenResFileX function C-10

example C-4

P

packages 4-37copy protecting 4-7defined 2-3downloading 4-10version number 4-7

Page Setup command 6-4Paste command 6-6'PICT' resources C-7 to C-8

in application icon 4-6in picture slots 4-31 to 4-32

picture slots 4-32platform files 4-43

specifying 4-6platform project setting 4-6Preferences settings 4-7 to 4-11Preview command 4-20, 6-18preview mode 4-20Print command 6-5printDepth variable 5-10, 5-16printFormat_filename variable 4-43print format templates 4-25, 4-47Print function 5-9, 5-21Print One command 6-5programming problems 5-23 to 5-33

comparing with nil 5-26 to 5-28dangling frame references 5-26forgetting the function value 5-25printing in communications code 5-31resizing read-only objects 5-29 to 5-30setting the wrong slot value 5-23 to 5-25text not drawing 5-30using nil in expressions 5-28 to 5-29

programming tips 5-23 to 5-33accessing parent view 5-33examining exceptions 5-32maintaining view state 5-32peeking into a soup 5-33

Project Data command 6-13project data files 4-39 to 4-42project files 4-2projects

adding files 3-7, 4-2defined 2-3managing 4-1 to 4-7project settings 4-3 to 4-7project windows 4-2setting up 3-2

protos 4-13

Page 200: Newton Toolkit User’s Guide

INDEX

IN-5

Q

Quit command 6-5

R

read-only objectscopying 5-30

receiver slot 5-6rectangle slots 4-32Remove File command 6-11remove scripts 4-40 to 4-41Rename Slot command 6-20resource files C-2

adding to a project 4-44, C-2for application icon 4-5opening and closing C-3 to C-4, C-9 to C-10

resources 4-44 to 4-45, C-1 to C-15application icon 4-5 to 4-6'PICT' 4-6, 4-32, C-7 to C-8retrieving C-4 to C-6, C-10 to C-14'SND ' C-8 to C-9

Revert command 6-4, 6-21

S

Save a Copy In command 6-4Save All command 6-4Save As command 6-3Save command 6-3script slots 4-30Select All command 6-6Select Hierarchy command 6-7Select in Layout command 6-7Set Grid command 6-15Settings 4-3 to 4-7Settings command 4-3 to 4-7, 6-13Show Clipboard command 6-9

Show Slot Values command 6-21Size setting 4-9slots

creating 4-28 to 4-32displaying in browser 4-9editing 4-30 to 4-33in stack trace 5-5searching for 4-34 to 4-36slot types 4-30 to 4-32

Slots By Name command 6-21Slots By Type command 6-21'SND ' resources C-8 to C-9software requirements 1-2stack trace 5-5StackTrace function 5-5, 5-21Stats function 5-22symbols, application 4-4 to 4-5

T

tabs, setting 4-10Template Info 3-7, 4-21Template Info command 4-21 to 4-22, 6-18templates

defined 2-1displaying in browser 4-9editing 3-9 to 3-12, 4-26 to 4-33processing 4-49 to 4-50searching for 4-34 to 4-36

Templates By Hierarchy command 6-21Templates By Type command 6-20text

editing 4-32 to 4-33, A-1 to A-6searching for 4-34 to 4-36setting display characteristics 4-10setting tabs 4-10

text slots 4-30Toolkit App, installing 1-6Toolkit Preferences command 4-7 to 4-11, 6-9Trace Off button 5-5

Page 201: Newton Toolkit User’s Guide

INDEX

IN-6

trace variable 5-15tracing execution flow 5-3 to 5-5

stopping 5-5troubleshooting 1-8

U

Undo command 6-5Update File command 6-12user proto templates

creating 4-24example 3-21 to 3-24

V

variables defined by NTK 4-42 to 4-43version number, package 4-7viewBounds slot fields D-2view classes 4-13view frames 2-2viewFrontKey 5-19viewFrontMost 5-19viewFrontMostApp 5-19views

aligning 4-18 to 4-19declaring 4-21defined 2-1displaying contents 5-13displaying hierarchy 5-14displaying in browser 4-9drawing 3-5 to 3-6, 4-13 to 4-16moving 4-17naming 3-6, 4-21ordering 4-19previewing 4-20resizing 4-16

W, X, Y, Z

Write function 5-9, 5-22

Page 202: Newton Toolkit User’s Guide

THE APPLE PUBLISHING SYSTEM

This Apple manual was written, edited, and composed on a desktop publishing system using Apple Macintosh computers and FrameMaker software. Proof pages were created on an Apple LaserWriter Pro 630 printer. Final page negatives were output directly from the text and graphics files. Line art was created using Adobe™ Illustrator. PostScript™, the page-description language for the LaserWriter, was developed by Adobe Systems Incorporated.

Text type is Palatino® and display type is Helvetica®. Bullets are ITC Zapf Dingbats®. Some elements, such as program listings, are set in Apple Courier.

LEAD WRITERSue Luttner

WRITERSGary Hillerson, Sue Luttner, John Perry

PROJECT LEADERChristopher Bey

ILLUSTRATORPeggy Kunz

EDITORDavid Schneider

PRODUCTION EDITORRex Wolf

PROJECT MANAGERGerry Kane

Special thanks to Larry Breed, Bob Ebert, Mike Engber, Norberto Menendez, Jeff Piazza, Peter Potrebic, Kent Sandvik.