Newton Programmer’s Guide For Newton 2.
Apple Computer, Inc. © 1996 Apple Computer, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Computer, Inc., except to make a backup copy of any documentation provided on CD-ROM. Printed in the United States of America.
Table of Contents Figures and Tables Preface xxxiii About This Book xliii Who Should Read This Book xliii Related Books xliii Newton Programmer’s Reference CD-ROM xliv Sample Code xlv Conventions Used in This Book xlv Special Fonts xlv Tap Versus Click xlvi Frame Code xlvi Developer Products and Support xlvii Undocumented System Software Objects xlviii Chapter 1 Overview 1-1 Operating System 1-1 Memory 1-3 Packages 1-4 System Services 1-4 Object Storage System 1-5 View System 1-6 Text Input and Rec
Communications Services 1-11 NewtonScript Application Communications Routing Through the In/Out Box 1-13 Endpoint Interface 1-14 Low-Level Communications 1-14 Transport Interface 1-14 Communication Tool Interface 1-15 Application Components 1-15 Using System Software 1-17 The NewtonScript Language 1-18 What’s New in Newton 2.
Effects of System Resets on Application Data Flow of Control 2-8 Using Memory 2-8 Localization 2-9 Developer Signature Guidelines 2-9 Signature 2-9 How to Register 2-10 Application Name 2-10 Application Symbol 2-11 Package Name 2-11 Summary 2-12 View Classes and Protos 2-12 Functions 2-12 Chapter 3 Views 2-7 3-1 About Views 3-1 Templates 3-2 Views 3-4 Coordinate System 3-6 Defining View Characteristics 3-8 Class 3-9 Behavior 3-9 Location, Size, and Alignment 3-10 Appearance 3-20 Opening and Closing Ani
Changes to Existing Functions and Methods 3-31 New Warning Messages 3-32 Obsolete Functions and Methods 3-32 Using Views 3-32 Getting References to Views 3-32 Displaying, Hiding, and Redrawing Views 3-33 Dynamically Adding Views 3-33 Showing a Hidden View 3-34 Adding to the stepChildren Array 3-34 Using the AddStepView Function 3-35 Using the BuildContext Function 3-36 Creating Templates 3-36 Making a Picker View 3-37 Changing the Values in viewFormat 3-37 Determining Which View Item Is Selected 3-37 Comple
Chapter 4 NewtApp Applications 4-1 About the NewtApp Framework 4-1 The NewtApp Protos 4-2 About newtApplication 4-4 About newtSoup 4-5 The Layout Protos 4-5 The Entry View Protos 4-8 About the Slot View Protos 4-9 Stationery 4-11 NewtApp Compatibility 4-11 Using NewtApp 4-12 Constructing a NewtApp Application 4-12 Using Application Globals 4-13 Using newtApplication 4-14 Using the Layout Protos 4-16 Using Entry Views 4-19 Using the Required NewtApp Install and Remove Scripts Using Slot Views in Non-NewtA
Creating a DataDef 5-8 Defining DataDef Methods 5-9 Creating ViewDefs 5-11 Registering Stationery for an Auto Part 5-13 Using the MinimalBounds ViewDef Method 5-14 Stationery Summary 5-15 Data Structures 5-15 Protos 5-15 Functions 5-17 Chapter 6 Pickers, Pop-up Views, and Overviews 6-1 About Pickers and Pop-up Views 6-1 Pickers and Pop-up View Compatibility 6-2 New Pickers and Pop-up Views 6-2 Obsolete Function 6-4 Picker Categories 6-4 General-Purpose Pickers 6-4 Using protoGeneralPopup 6-7 Map Pickers
Specifying the List of Items for a Popup Summary 6-41 General Picker Protos 6-41 Map Pickers 6-45 Text Picker Protos 6-46 Date, Time, and Location Pop-up Views Number Pickers 6-53 Picture Picker 6-53 Overview Protos 6-54 Roll Protos 6-57 View Classes 6-58 Functions 6-59 Chapter 7 Controls and Other Protos 6-37 6-50 7-1 Controls Compatibility 7-1 Scroller Protos 7-2 Implementing a Minimal Scroller 7-3 Automatic Arrow Feedback 7-3 Scrolling Examples 7-4 Scrolling Lines of Text 7-4 Scrolling in the Dates
Selection Tab Protos 7-25 Gauges and Slider Protos 7-25 Time Protos 7-27 Special View Protos 7-28 View Appearance Protos 7-30 Status Bar Protos 7-31 Chapter 8 Text and Ink Input and Display 8-1 About Text 8-1 About Text and Ink 8-1 Written Input Formats 8-2 Caret Insertion Writing Mode 8-3 Fonts for Text and Ink Display 8-3 About Text Views and Protos 8-3 About Keyboard Text Input 8-4 The Keyboard Registry 8-5 The Punctuation Pop-up Menu 8-5 Compatibility 8-6 Using Text 8-6 Using Views and Protos for Te
Handling Input Events 8-38 Testing for a Selection Hit 8-38 Summary of Text 8-39 Text Constants and Data Structures 8-39 Views 8-42 Protos 8-43 Text and Ink Display Functions and Methods Keyboard Functions and Methods 8-49 Input Event Functions and Methods 8-50 Chapter 9 Recognition 8-47 9-1 About the Recognition System 9-1 Classifying Strokes 9-3 Gestures 9-4 Shapes 9-5 Text 9-6 Unrecognized Strokes 9-7 Enabling Recognizers 9-8 View Flags 9-9 Recognition Configuration Frames 9-9 View Flags vs.
Recognizing Standard Gestures 9-25 Combining View Flags 9-26 Recognizing Text 9-27 Recognizing Punctuation 9-28 Suppressing Spaces Between Words 9-28 Forcing Capitalization 9-29 Justifying to Width of Parent View 9-29 Restricting Input to Single Lines or Single Words Validating Clipboard and Keyboard Input 9-29 Using the vAnythingAllowed Mask 9-30 Summary 9-31 Constants 9-31 Data Structures 9-33 Chapter 10 Recognition: Advanced Topics 9-29 10-1 About Advanced Topics in Recognition 10-1 How the System U
Providing the _recogPopup Slot 10-22 Accessing Correction Information 10-23 Using Custom Dictionaries 10-24 Creating a Custom Enumerated Dictionary 10-24 Creating the Blank Dictionary 10-25 Adding Words to RAM-Based Dictionaries 10-26 Removing Words From RAM-Based Dictionaries 10-27 Saving Dictionary Data to a Soup 10-27 Restoring Dictionary Data From a Soup 10-28 Using Your RAM-Based Custom Dictionary 10-28 Removing Your RAM-Based Custom Dictionary 10-30 Using System Dictionaries Individually 10-30 Working
Chapter 11 Data Storage and Retrieval 11-1 About Data Storage on Newton Devices 11-1 Introduction to Data Storage Objects 11-2 Where to Go From Here 11-6 Stores 11-6 Packages 11-7 Soups 11-7 Indexes 11-8 Saving User Preference Data in the System Soup 11-10 Queries 11-10 Querying for Indexed Values 11-10 Begin Keys and End Keys 11-12 Tag-based Queries 11-14 Customized Tests 11-14 Text Queries 11-15 Cursors 11-16 Entries 11-17 Alternatives to Soup-Based Storage 11-18 Dynamic Data 11-18 Static Data 11-19 Co
Retrieving Existing Soups 11-33 Adding Entries to Soups 11-34 Adding an Index to an Existing Soup 11-35 Removing Soups 11-36 Using Built-in Soups 11-36 Making Changes to Other Applications’ Soups 11-37 Adding Tags to an Existing Soup 11-37 Using Queries 11-37 Querying Multiple Soups 11-38 Querying on Single-Slot Indexes 11-38 Querying for Tags 11-41 Querying for Text 11-43 Internationalized Sorting Order for Text Queries 11-44 Queries on Descending Indexes 11-45 Querying on Multiple-Slot Indexes 11-47 Limit
Chapter 12 Special-Purpose Objects for Data Storage and Retrieval 12-1 About Special-Purpose Storage Objects 12-1 Entry Aliases 12-1 Virtual Binary Objects 12-2 Parts 12-3 Store Parts 12-4 Mock Entries 12-4 Mock Stores, Mock Soups, and Mock Cursors 12-6 Using Special-Purpose Data Storage Objects 12-7 Using Entry Aliases 12-7 Using Virtual Binary Objects 12-8 Creating Virtual Binary Objects 12-8 Modifying VBO Data 12-10 VBOs and String Data 12-12 Using Store Parts 12-12 Creating a Store Part 12-13 Getting
Drawing Compatibility 13-8 New Functions 13-8 New Style Attribute Slots 13-8 Changes to Bitmaps 13-8 Changes to the HitShape Method 13-8 Changes to View Classes 13-9 Using the Drawing Interface 13-9 How to Draw 13-9 Responding to the ViewDrawScript Message 13-9 Drawing Immediately 13-10 Using Nested Arrays of Shapes 13-10 The Transform Slot in Nested Shape Arrays 13-11 Default Transfer Mode 13-12 Transfer Modes at Print Time 13-12 Controlling Clipping 13-12 Transforming a Shape 13-13 Using Drawing View Clas
Chapter 14 Sound 14-1 About Newton Sound 14-1 Event-related Sounds 14-2 Sounds in ROM 14-2 Sounds for Predefined Events 14-2 Sound Data Structures 14-3 Compatibility 14-3 Using Sound 14-4 Creating and Using Custom Sound Frames 14-4 Creating Sound Frames Procedurally 14-5 Cloning Sound Frames 14-5 Playing Sound 14-5 Using a Sound Channel to Play Sound 14-5 Playing Sound Programmatically 14-6 Synchronous and Asynchronous Sound 14-7 Advanced Sound Techniques 14-8 Pitch Shifting 14-9 Manipulating Sample Data
Creating the labelsFilter slot 15-14 Creating the storesFilter slot 15-14 Adding the Filing Button 15-14 Adding the Folder Tab View 15-14 Customizing Folder Tab Views 15-15 Defining a TitleClickScript Method 15-15 Implementing the FileThis Method 15-15 Implementing the NewFilingFilter Method 15-16 Using the Folder Change Notification Service 15-18 Creating the doCardRouting slot 15-18 Using Local or Global Folders Only 15-19 Adding and Removing Filing Categories Programmatically 15-19 Interface to User-Visi
Implementing Find Overview Support 16-21 The FindSoupExcerpt Method 16-21 The ShowFoundItem Method 16-22 Replacing the Built-in Find Slip 16-24 Reporting Progress to the User 16-24 Registering for Finds 16-25 Summary 16-26 Finder Protos 16-26 Functions and Methods 16-28 Application-Defined Methods 16-28 Chapter 17 Additional System Services 17-1 About Additional System Services 17-1 Undo 17-1 Undo Compatibility 17-2 Idler Objects 17-2 Change Notifications 17-2 Online Help 17-3 Alerts and Alarms 17-3 Use
Using Alerts and Alarms 17-11 Using the Notify Method to Display User Alerts 17-11 Creating Alarms 17-11 Obtaining Information about Alarms 17-12 Retrieving Alarm Keys 17-12 Removing Installed Alarms 17-13 Common Problems With Alarms 17-13 Using the Periodic Alarm Editor 17-14 Using Progress Indicators 17-15 Using the Automatic Busy Cursor 17-15 Using the Notify Icon 17-15 Using the DoProgress Function 17-16 Using DoProgress or Creating Your Own protoStatusTemplate 17-18 Using protoStatusTemplate Views 17-1
The Task Frame 18-11 The Entries Slot 18-11 The Phrases Slot 18-11 The OrigPhrase Slot 18-12 The Value Slot 18-12 Resolving Template-Matching Conflicts 18-13 Compatibility Information 18-14 Using the Assistant 18-15 Making Behavior Available From the Assistant 18-15 Defining Action and Target Templates 18-15 Defining Your Own Frame Types to the Assistant 18-16 Implementing the PostParse Method 18-17 Defining the Task Template 18-18 Registering and Unregistering the Task Template 18-19 Displaying Online Help
Dates 19-8 About the Dates Application 19-8 Dates Compatibility 19-9 Using the Dates Application 19-10 Adding Meetings or Events 19-11 Deleting Meetings and Events 19-12 Finding Meetings or Events 19-13 Moving Meetings and Events 19-14 Getting and Setting Information for Meetings or Events 19-15 Creating a New Meeting Type 19-17 Examples of Creating New Meeting Types 19-19 Miscellaneous Operations 19-20 Controlling the Dates Display 19-21 Using the Dates Soups 19-22 To Do List 19-22 About the To Do List App
Fax Soup Entries 19-34 About Fax Soup Entries 19-34 Using Fax Soup Entries 19-34 Prefs and Formulas Rolls 19-35 About the Prefs and Formulas Rolls 19-35 Prefs and Formulas Compatibility 19-36 Using the Prefs and Formulas Interfaces 19-36 Adding a Prefs Roll Item 19-36 Adding a Formulas Roll Item 19-36 Auxiliary Buttons 19-36 About Auxiliary Buttons 19-36 Auxiliary Buttons Compatibility 19-36 Using Auxiliary Buttons 19-37 Icons and the Extras Drawer 19-38 About Icons and the Extras Drawer 19-38 Extras Drawer
Chapter 20 Localizing Newton Applications 20-1 About Localization 20-1 The Locale Panel and the International Frame 20-1 Locale and ROM Version 20-2 How Locale Affects Recognition 20-2 Using the Localization Features of the Newton 20-3 Defining Language at Compile Time 20-3 Defining a Localization Frame 20-4 Using LocObj to Reference Localized Objects 20-4 Use ParamStr Rather Than “&” and “&&” Concatenation Measuring String Widths at Compile Time 20-6 Determining Language at Run Time 20-6 Examining the A
Routing Formats 21-5 Current Format 21-8 Routing Compatibility 21-8 Print Formats 21-8 Using Routing 21-8 Providing Transport-Based Routing Actions 21-9 Getting and Verifying the Target Object 21-10 Getting and Setting the Current Format 21-11 Supplying the Target Object 21-12 Storing an Alias to the Target Object 21-13 Storing Multiple Items 21-14 Using the Built-in Overview Data Class 21-14 Displaying an Auxiliary View 21-15 Registering Routing Formats 21-16 Creating a Print Format 21-18 Page Layout 21-18
Protos 21-38 Functions and Methods 21-39 Application-Defined Methods 21-40 Chapter 22 Transport Interface 22-1 About Transports 22-1 Transport Parts 22-2 Item Frame 22-2 Using the Transport Interface 22-5 Providing a Transport Object 22-5 Installing the Transport 22-5 Setting the Address Class 22-6 Grouping Transports 22-7 Sending Data 22-8 Sending All Items 22-9 Converting an E-Mail Address to an Internet Address 22-9 Receiving Data 22-9 Handling Requests When the Transport Is Active 22-12 Canceling an
Chapter 23 Endpoint Interface 23-1 About the Endpoint Interface 23-1 Asynchronous Operation 23-2 Synchronous Operation 23-3 Input 23-3 Data Forms 23-4 Template Data Form 23-5 Endpoint Options 23-7 Compatibility 23-7 Using the Endpoint Interface 23-8 Setting Endpoint Options 23-8 Initialization and Termination 23-10 Establishing a Connection 23-11 Sending Data 23-11 Receiving Data Using Input Specs 23-12 Specifying the Data Form and Target 23-13 Specifying Data Termination Conditions 23-14 Specifying Flag
Chapter 24 Built-in Communications Tools 24-1 Serial Tool 24-1 Standard Asynchronous Serial Tool 24-1 Serial Tool with MNP Compression 24-4 Framed Asynchronous Serial Tool 24-4 Modem Tool 24-6 Infrared Tool 24-8 AppleTalk Tool 24-9 Resource Arbitration Options 24-10 AppleTalk Functions 24-12 The Net Chooser 24-13 Summary 24-16 Built-in Communications Tool Service Option Labels Options 24-16 Constants 24-18 Functions and Methods 24-21 Chapter 25 Modem Setup Service 24-16 25-1 About the Modem Setup Se
Chapter 26 Utility Functions 26-1 Compatibility 26-2 New Functions 26-2 New Object System Functions 26-2 New String Functions 26-3 New Array Functions 26-3 New Sorted Array Functions 26-3 New Integer Math Functions 26-4 New Financial Functions 26-4 New Exception Handling Functions 26-4 New Message Sending Functions 26-4 New Deferred Message Sending Functions 26-4 New Data Stuffing Functions 26-5 New Functions to Get and Set Globals 26-5 New Debugging Functions 26-5 New Miscellaneous Functions 26-5 Enhanc
Appendix The Inside Story on Declare A-1 Compile-Time Results A-1 Run-Time Results A-2 Glossary Index GL-1 IN-1 xxxi
Figures and Tables Chapter 1 Overview 1-1 Figure 1-1 Figure 1-2 Figure 1-3 Chapter 3 Chapter 4 Views System software overview 1-2 Communications architecture 1-12 Using components 1-16 3-1 Figure 3-1 Figure 3-2 Figure 3-3 Figure 3-4 Figure 3-5 Figure 3-6 Figure 3-7 Figure 3-8 Template hierarchy 3-3 View hierarchy 3-5 Screen representation of view hierarchy View system coordinate plane 3-7 Points and pixels 3-7 Bounds parameters 3-11 View alignment effects 3-18 Transfer modes 3-22 Table 3-1 view
Chapter 5 Stationery Figure 5-1 Figure 5-2 Figure 5-3 Figure 5-4 Chapter 6 The IOU extension in the New picker 5-3 The IOU extension to the Notes application The Show menu presents different views of application data 5-4 The default viewDef view template 5-12 Pickers, Pop-up Views, and Overviews Figure 6-1 Figure 6-2 Figure 6-3 Figure 6-4 Figure 6-5 Figure 6-6 Figure 6-7 Figure 6-8 Figure 6-9 Figure 6-10 Figure 6-11 Figure 6-12 Figure 6-13 Figure 6-14 Figure 6-15 Figure 6-16 Figure 6-17 Figure 6-18 Figu
Chapter 7 Figure 6-35 Figure 6-36 Figure 6-37 Figure 6-38 Figure 6-39 Figure 6-40 Figure 6-41 Figure 6-42 Figure 6-43 Figure 6-44 Figure 6-45 Figure 6-46 Figure 6-47 Figure 6-48 A protoOverview example 6-22 A protoSoupOverview example 6-23 A protoListPicker example 6-24 A ProtoListPicker example 6-26 Creating a new name entry 6-27 Highlighted row 6-27 Selected row 6-27 Pop-up view displayed over list 6-28 Slip displayed for gathering input 6-28 A protoRoll example 6-35 A protoRollBrowser example 6-36 Exam
Chapter 8 Figure 7-23 Figure 7-24 Figure 7-25 Figure 7-26 Figure 7-27 Figure 7-28 Figure 7-29 Figure 7-30 Figure 7-31 Figure 7-32 A protoAMPMCluster view 7-15 A protoDragger view 7-16 A protoDragNGo view 7-16 A protoGlance view 7-17 A protoStaticText view 7-17 A protoBorder view 7-18 A protoDivider view 7-18 A protoTitle view 7-18 A protoStatus view 7-19 A protoStatusBar view 7-19 Table 7-1 Scroller bounds frame slots Text and Ink Input and Display Figure 8-1 Figure 8-2 Figure 8-3 Figure 8-4 Figure 8-5
Chapter 9 Chapter 10 Recognition 9-1 Figure 9-1 Figure 9-2 Figure 9-3 Figure 9-4 Figure 9-5 Figure 9-6 Figure 9-7 Figure 9-8 Recognizers create units from input strokes 9-5 Recognition-related view flags 9-9 Text-corrector picker 9-14 Handwriting Recognition preferences 9-16 Text Editing Settings slip 9-17 Fine Tuning handwriting preferences slips 9-17 Handwriting Settings slip 9-18 Use of protoRecToggle view in the Notes application 9-19 Recognition: Advanced Topics Figure 10-1 Figure 10-2 Figure 10-
Chapter 12 Special-Purpose Objects for Data Storage and Retrieval Table 12-1 Chapter 13 Parts and type identifiers Drawing and Graphics Figure 13-1 Chapter 15 Table 13-1 Summary of drawing results Find 13-11 15-1 Two examples of filing button views 15-2 Filing slip 15-3 Creating a local folder 15-4 Filing slip without external store 15-5 Filing slip for 'onlyCardRouting 15-5 A protoNewFolderTab view 15-6 A protoClockFolderTab view 15-7 Choosing a filing filter 15-8 16-1 Figure 16-1 Figure 16-2 F
Figure 16-9 Chapter 17 Figure 16-10 The ShowFoundItem method displays the view of an overview item 16-9 Typical status message 16-24 Table 16-1 Overview of ROM_SoupFinder methods Additional System Services Figure 17-1 Figure 17-2 Figure 17-3 Figure 17-4 Figure 17-5 Figure 17-6 Figure 17-7 Figure 17-8 Chapter 18 Chapter 19 17-1 User alert 17-3 Alarm slip with Snooze button 17-4 A view based on protoPeriodicAlarmEditor 17-4 Busy cursor 17-5 Notify icon 17-5 Progress slip with barber pole gauge 17-6
Chapter 20 Chapter 21 Chapter 22 Chapter 23 Localizing Newton Applications Figure 20-1 The Locale settings in Preferences Table 20-1 Using the kIncludeAllElements constant Routing Interface 20-2 In Box and Out Box overviews 21-2 Action picker 21-3 Transport selection mechanism for action picker Format picker in routing slip 21-7 Auxiliary view example 21-15 Table 21-1 Routing data types Transport Interface 20-13 21-1 Figure 21-1 Figure 21-2 Figure 21-3 Figure 21-4 Figure 21-5 21-6 21-7 22
Chapter 24 Chapter 25 Chapter 26 Built-in Communications Tools Figure 24-1 Figure 24-2 Figure 24-3 Default serial framing 24-5 NetChooser view while searching 24-14 NetChooser view displaying printers 24-14 Table 24-1 Table 24-2 Table 24-3 Table 24-4 Table 24-5 Table 24-6 Table 24-7 Table 24-8 Summary of serial options 24-2 Summary of serial tool with MNP options Summary of framed serial options 24-5 Summary of modem options 24-7 Summary of Infrared Options 24-8 Summary of AppleTalk options 24-10 Reso
P R E F A C E About This Book This book, Newton Programmer’s Guide, is the definitive guide to Newton programming, providing conceptual information and instructions for using the Newton application programming interfaces. This book is a companion to Newton Programmer’s Reference, which provides comprehensive reference documentation for the routines, system prototypes, data structures, constants, and error codes defined by the Newton system.
P R E F A C E ■ The NewtonScript Programming Language. This book comes with the Newton Toolkit development environment. It describes the NewtonScript programming language. ■ Newton Book Maker User’s Guide. This book comes with the Newton Toolkit development environment. It describes how to use Newton Book Maker and Newton Toolkit to make Newton digital books and to add online help to Newton applications. ■ Newton 2.0 User Interface Guidelines.
P R E F A C E Sample Code 0 The Newton Toolkit development environment, from Apple Computer, includes many sample code projects. You can examine these samples, learn from them, and experiment with them. These sample code projects illustrate most of the topics covered in this book. They are an invaluable resource for understanding the topics discussed in this book and for making your journey into the world of Newton programming an easier one.
P R E F A C E ■ Italic typeface. Italic typeface is used in code to indicate replaceable items, such as the names of function parameters, which you must replace with your own names. The names of other books are also shown in italic type, and rarely, this style is used for emphasis. Tap Versus Click 0 Throughout the Newton software system and in this book, the word “click” sometimes appears as part of the name of a method or variable, as in ViewClickScript or ButtonClickScript.
P R E F A C E 2. Edit the viewBounds slot to match the values shown in the book. 3. Add each of the other slots you see listed in the frame, setting their values to the values shown in the book. Slots that have values are attribute slots, and those that contain functions are method slots.
P R E F A C E Undocumented System Software Objects When browsing in the NTK Inspector window, you may see functions, methods, and data objects that are not documented in this book. Undocumented functions, methods, and data objects are not supported, nor are they guaranteed to work in future Newton devices. Using them may produce undesirable effects on current and future Newton devices.
C H A P T E R Figure 1-0 Table 1-0 1 Overview 1 This chapter describes the general architecture of the Newton system software, which is divided into three levels, as shown in Figure 1-1 (page 1-2). The lowest level includes the operating system and the low-level communications system. These parts of the system interact directly with the hardware and perform basic operations such as memory management, input and output, and task switching.
C H A P T E R 1 Overview Figure 1-1 System software overview Application Components NewtonScript Application Program User Interface Components System Services Find Filing Sound Book Reader Routing and Transport Endpoint Communications Imaging and Printing Intelligent Assistant Stationery Text Input and Recognition View System Object Storage System Operating System Operating System Low-level Communications System Newton Hardware 1-2 Operating System
C H A P T E R 1 Overview Another operating system task of interest is the Inker. The Inker task is responsible for gathering and displaying input from the electronic tablet overlaying the screen when the user writes on the Newton. The Inker exists as a separate task so that the Newton can gather input and display electronic ink at the same time as other operations are occurring.
C H A P T E R 1 Overview The system performs automatic memory management of the NewtonScript heap. You don’t need to worry about memory allocation or disposal in an application. The system automatically allocates memory when you create a new object in NewtonScript. When references to an object no longer exist, it is freed during the next garbage collection cycle. The system performs garbage collection automatically when it needs additional memory.
C H A P T E R 1 Overview Object Storage System 1 This system is key to the Newton information architecture. The object storage system provides persistent storage for data. Newton uses a unified data model. This means that all data stored by all applications uses a common format. Data can easily be shared among different applications, with no translation necessary. This allows seamless integration of applications with each other and with system services. Data is stored using a database-like model.
C H A P T E R 1 Overview The object storage system is optimized for small chunks of data and is designed to operate in tight memory constraints. Soups are compressed, and retrieved entries are not allocated on the NewtonScript heap until a slot in the entry is accessed. You can find information about the object storage system interface in Chapter 11, “Data Storage and Retrieval.” View System 1 Views are the basic building blocks of most applications.
C H A P T E R 1 Overview Text Input and Recognition 1 The Newton recognition system uses a sophisticated multiple-recognizer architecture. There are recognizers for text, shapes, and gestures, which can be simultaneously active (this is application-dependent). An arbitrator examines the results from simultaneously active recognizers and returns the recognition match that has the highest confidence. Recognition is modeless.
C H A P T E R 1 Overview Stationery 1 Stationery is a capability of the system that allows applications to be extended by other developers. The word “stationery” refers to the capability of having different kinds of data within a single application (such as plain notes and outlines in the Notepad) and/or to the capability of having different ways of viewing the same data (such as the Card and All Info views in the Names file).
C H A P T E R 1 Overview Imaging and Printing 1 At the operating system level, the Newton imaging and printing software is based on an object-oriented, device-independent imaging model. The imaging model is monochrome since the current Newton screen is a black-and-white screen. NewtonScript application programs don’t call low-level imaging routines directly to do drawing or image manipulation.
C H A P T E R 1 Overview Besides the sounds that are built into the system ROM, you can import external sound resources into an application through the Newton Toolkit development environment. For information about using sound in an application, see Chapter 14, “Sound.” Book Reader 1 Book Reader is a system service that displays interactive digital books on the Newton screen. Digital books can include multiple-font text, bitmap and vector graphics, and on-screen controls for content navigation.
C H A P T E R 1 Overview If you want to allow the user to search for data stored by your application, you need to implement certain methods that respond to find messages sent by the system. You’ll need to supply one method that searches your application’s soup(s) for data and returns the results in a particular format, and another method that locates and displays the found data in your application if the user taps on it in the find overview.
C H A P T E R 1 Overview The communication architecture is flexible, supporting complex communication needs. The architecture is also extensible, allowing new communication transport tools to be added dynamically and accessed through the same interface as existing transports. In this way, new communication hardware devices can be supported. The Newton communications architecture is illustrated in Figure 1-2.
C H A P T E R 1 Overview ■ transport interface ■ communication tool interface The first two, routing and endpoint interfaces, are available for NewtonScript applications to use directly. The transport interface is a NewtonScript interface, but it isn’t used directly by applications. A transport consists of a special kind of application of its own that is installed on a Newton device and that provides new communication services to the system.
C H A P T E R 1 Overview interface. You need to use the transport or endpoint interfaces only when writing custom communication tools. Endpoint Interface 1 The endpoint interface is a somewhat lower-level NewtonScript interface; it has no visible representation to the Newton user. The endpoint interface is suited for real-time communication needs such as database access and terminal emulation. It uses an asynchronous, state-driven communications model.
C H A P T E R 1 Overview Communication Tool Interface 1 Underlying the NewtonScript interface is the low-level communications system. This system consists of a communications manager module and several code components known as communication tools. These communication tools interact directly with the communication hardware devices installed in the system. The communication tools are written in C++ and are not directly accessible from NewtonScript—they are accessed indirectly through an endpoint object.
C H A P T E R 1 Overview application using these components, Newton applications tend to be much smaller in size than similar applications on desktop computers. A simple example of how you can construct much of an application using components is illustrated in Figure 1-3. This simple application accepts names and phone numbers and saves them into a soup. It was constructed in just a few minutes using three different components.
C H A P T E R 1 Overview The NewtApp framework consists of a special collection of protos that are designed to be used together in a layered hierarchy to build a complete application. For more information about the NewtApp protos, refer to Chapter 4, “NewtApp Applications.” Using System Software 1 Most of the routines and application components that comprise the Newton system software reside in ROM, provided in special chips contained in every Newton device.
C H A P T E R 1 Overview The NewtonScript Language 1 You write Newton applications in NewtonScript, a dynamic object-oriented language developed especially for the Newton platform, though the language is highly portable. NewtonScript is designed to operate within tight memory constraints, so is well suited to small hand-held devices like Newton. NewtonScript is used to define, access, and manipulate objects in the Newton system.
C H A P T E R 1 Overview The NewtApp framework is not suited for all Newton applications. If your application stores data as individual entries in a soup, displays that data to the user in views, and allows the user to edit some or all of the data, then it is a potential candidate for using the NewtApp framework. NewtApp is well suited to “classic” form-based applications. Some of the built-in applications constructed using the NewtApp framework include the Notepad and the Names file.
C H A P T E R 1 Overview Protos 1 There are many new protos supplied in the new system ROM. There are new pop-up button pickers, map-type pickers, and several new time, date, and duration pickers. There are new protos that support the display of overviews and lists based on soup entries. There are new protos that support the input of rich strings (strings that contain either recognized characters or ink text). There are a variety of new scroller protos.
C H A P T E R 1 Overview clParagraphView now support ink text. There are several new functions that allow you to manipulate and convert between regular strings and rich strings. Other functions provide access to ink and stroke data, allow conversion between strokes, points, and ink, and allow certain kinds of ink and stroke manipulations. There are several new functions that allow you to access and manipulate the attributes of font specifications, making changing the font attributes of text much easier.
C H A P T E R 1 Overview The implementation of undo has changed to an undo/redo model instead of two levels of undo, so applications must support this new model. Recognition 1 Recognition enhancements include the addition of an alternate high-quality recognizer for printed text and significant improvements in the cursive recognizer. While this doesn’t directly affect applications, it does significantly improve recognition performance in the system, leading to a better user experience.
C H A P T E R 1 Overview The Dates application includes a comprehensive interface that gives you the ability to add, find, move, and delete meetings and events. You can get and set various kinds of information related to meetings, and you can create new meeting types for the Dates application. You can programmatically control what day is displayed as the first day of the week, and you can control the display of a week number in the Calendar view.
C H A P T E R 1 Overview There have been significant changes in the handling of binary (raw) data. For input, you can now target a direct data input object, resulting in significantly faster performance. For output, you can specify offsets and lengths, allowing you to send the data in chunks. Additionally, there is now support for multiple simultaneous communication sessions. Utilities 1 Many new utility functions are available in Newton 2.0.
C H A P T E R Figure 2-0 Table 2-0 2 Getting Started 2 This chapter describes where to begin when you’re thinking about developing a Newton application. It describes the different kinds of software you can develop and install on the Newton and the advantages and disadvantages of using different application structures. Additionally, this chapter describes how to create and register your developer signature.
C H A P T E R 2 Getting Started don’t follow the “classic” form-based model. For example, some types of applications that might use this approach include games, utilities, calculators, and graphics applications. The advantage of using the minimalist approach is that it’s simple and small. Usually you’d choose this approach because you don’t need or want a lot of built-in support from a comprehensive application framework, along with the extra size and overhead that such support brings.
C H A P T E R 2 Getting Started automatically manage many routine programming tasks. For example, some of the tasks the protos support include filing, finding, routing, scrolling, displaying an overview, and soup management. The disadvantage of NewtApp is that it is structured to support a particular kind of application—one that allows the creation, editing, and display of soup data.
C H A P T E R 2 Getting Started Other Kinds of Software 2 There are other kinds of software you can develop for the Newton platform that are not accessed by the user through an icon in the Extras drawer. These might include new types of stationery that extend existing applications, new panels for the Preferences or Formulas applications, new routing or print formats, communication transports, and other kinds of invisible applications.
C H A P T E R 2 Getting Started when it is moved to another store (it is deactivated then reactivated), or when the user deletes the application icon in the Extras Drawer. Packages can also be deactivated without removing them from the store. When a package is removed as a result of the user deleting it from the Extras Drawer, the system also executes the DeletionScript function in each of the package frame parts. This occurs before the RemoveScript function is executed.
C H A P T E R 2 Getting Started IMPORTANT Any changes that you make to the system in the InstallScript function must be reversed in the RemoveScript function. For example, if you register your application for certain system services or install print formats, stationery, or other objects in the system, you must reverse these changes and remove or unregister these objects in the RemoveScript function.
C H A P T E R 2 Getting Started Effects of System Resets on Application Data 2 Two kinds of reset operations—hard resets and soft resets—can occur on Newton devices. All data in working RAM (the NewtonScript heap and the operating system domain) is erased when a hard or soft reset occurs. Unless a hard reset occurs, soups remain in RAM until they are removed explicitly, even if the Newton device is powered down. Soups are not affected by soft resets, as they are stored in the protected storage domain.
C H A P T E R 2 Getting Started When the operating system cannot obtain enough memory to complete a requested operation, it may display a dialog box advising the user to reset the Newton device. The user can tap the Reset button displayed in the dialog box to reset the system, or can tap the Cancel button and continue working. The user may also initiate a soft reset by pressing a hardware button provided for this purpose. This button is designed to prevent its accidental use.
C H A P T E R 2 Getting Started IMPORTANT If you don't remove references to unused soups, entries, cursors, and other objects, the objects will not be garbage collected, reducing the amount of RAM available to the system and other applications. ▲ Localization 2 If your application displays strings, and you want your application to run on localized Newton products, you should consider localizing your application.
C H A P T E R 2 Getting Started Examples of valid signatures include NEWTONDTS Joe’s Cool Apps 1NEWTON2DTS What the #$*? SW How to Register 2 To register your signature, you need to provide the following information to the Newton Development Information Group at Apple. Company Name: Contact Person: Mailing Address: Phone: Email Address: Desired Signature 1st choice: Desired Signature 2nd choice: Send this information to the e-mail address NEWTONDEV@applelink.apple.
C H A P T E R 2 Getting Started Examples of valid application names include Llama Good Form 2 Fun 4 U Chess Note It’s recommended that you keep your application names short so that they don’t crowd the names of other applications in the Extras drawer. ◆ Application Symbol 2 The application symbol is created by concatenating the application name, a colon (:), and your registered developer signature. This symbol is not normally visible to the end user.
C H A P T E R 2 Getting Started Summary 2 View Classes and Protos 2 clView 2 aView := { viewClass: clView, // base view class viewBounds: boundsFrame, // location and size viewJustify: integer, // viewJustify flags viewFlags: integer, // viewFlags flags viewFormat: integer, // viewFormat flags ...
C H A P T E R Figure 3-0 Table 3-0 3 Views 3 This chapter provides the basic information you need to know about views and how to use them in your application. You should start with this chapter if you are creating an application for Newton devices, as views are the basic building blocks for most applications. Before reading this chapter, you should be familiar with the information in Newton Toolkit User’s Guide and The NewtonScript Programming Language.
C H A P T E R 3 Views This section provides detailed conceptual information on views and other items related to views. Specifically, it covers the following: ■ templates and views and how they relate to each other ■ the coordinate system used in placing views ■ components used to define views ■ application-defined methods that the system sends to views ■ the programmatic process used to create a view ■ new functions, methods, and messages added for 2.
C H A P T E R 3 Views Figure 3-1 shows a collection of template frames that might make up an application. The frame at the top represents the highest-level parent template. Each template that has children contains a viewChildren (or stepChildren) slot whose value is an array of references to its child templates. Figure 3-1 Template hierarchy Parent Template {Slot: data Slot: data . . . viewChildren: [frameRef, frameRef]} Child Template Child Template {Slot: data Slot: data . . .
C H A P T E R 3 Views Views 3 A template is a data description of an object. A view is the visual representation of the object that is created when the template is instantiated. The system reads the stored description in the template and creates a view on the screen—for example, a framed rectangle containing a title.
C H A P T E R 3 Views application base view. (Think of the view hierarchy as a tree structure in which the tree is turned upside down with its root at the top. The top-level parent view is the root view.) Figure 3-2 shows the set of views instantiated from the templates shown in Figure 3-1. Note that this example is simplified in that it shows a separate template for each view. In practice, multiple views often share a single template.
C H A P T E R 3 Views Figure 3-3 shows an example of what this view hierarchy might represent on the screen. Figure 3-3 Screen representation of view hierarchy Child B Parent View Child C Child A Child D The application base view of each application exists as a child of the system root view. The root view is essentially the blank screen that exists before any other views are drawn. It is the ancestor of all other views that are instantiated.
C H A P T E R 3 Views Figure 3-4 View system coordinate plane –6 –5 –4 –3 –2 –1 –6 –5 –4 –3 –2 –1 1 1 h 2 3 4 5 6 2 3 4 5 6 Figure 3-5 v Points and pixels Grid lines Point Pixel About Views 3-7
C H A P T E R 3 Views As the grid lines are infinitely thin, so a point is infinitely small. Pixels, by contrast, lie between the lines of the coordinate grid, not at their intersections. This relationship gives them a definite physical extent, so that they can be seen on the screen. Defining View Characteristics 3 A template that describes a view is stored as a frame that has slots for view characteristics.
C H A P T E R 3 Views Opening and closing animation effects The viewEffect slot defines an animation to be performed when the view is displayed or hidden. Other attributes Some other slots define view characteristics such as font, copy protection, and so on. Inheritance links The _proto, _parent, viewChildren, and stepChildren slots contain links to a view’s template, parent view, and child views. These different categories of view characteristics are described in the following sections.
C H A P T E R 3 Views Handling Pen Input 3 The use of the vClickable viewFlags constant to control pen input is important to understand, so it is worth covering here, even though it is discussed in more detail in “Recognition” (page 9-1). The vClickable flag must be set for a view to receive input. If this flag is not set for a view, that view cannot accept any pen input.
C H A P T E R 3 Views The distance from the left origin of the parent view to the left edge of the view. The distance from the top origin of the parent view to the top edge of the view. The distance from the left origin of the parent view to the right edge of the view. The distance from the top origin of the parent view to the bottom edge of the view.
C H A P T E R 3 Views View Size Relative to Parent Size 3 A view is normally entirely enclosed by its parent view. You shouldn’t create a view whose bounds extend outside its parent’s bounds. If you do create such a view, for example containing a picture that you want to show just part of, you need to set the vClipping flag in the viewFlags slot of the parent view. If you do not set the vClipping flag for the parent view, the behavior is unpredictable.
C H A P T E R 3 Views viewSetupFormScript: func() begin local b := GetAppParams(); self.viewbounds := RelBounds( b.appAreaLeft, b.appAreaTop, min(200, b.appAreaWidth), // 200 pixels wide max min(300, b.appAreaHeight)); // 300 pixels high max end Don’t blindly size your application to the full extents of the screen. This might look odd if your application runs on a system with a much larger screen. Do include a border around your application base view.
C H A P T E R 3 Views ■ horizontal alignment of the view relative to its parent or sibling view ■ vertical alignment of the view relative to its parent or sibling view ■ text limits For example, you could specify these alignment attributes for a button view that has its text centered within the view and is placed relative to its parent and sibling views: vjCenterH+vjCenterV+vjSiblingRightH+vjParentBottomV+oneLineOnly If you don’t specify an attribute from a group, the default attribute for that gro
C H A P T E R 3 Views Table 3-1 viewJustify constants (continued) Constant Value Description vjParentCenterH 16 The difference between the left and right view bounds is used as the width of the view. If you specify zero for left, the view is centered in the parent view. If you specify any other number for left, the view is offset by that much from a centered position (for example, specifying left = 10 and right = width+10 offsets the view 10 pixels to the right from a centered position).
C H A P T E R 3 Views Table 3-1 viewJustify constants (continued) Constant Value Description vjParentCenterV 64 The difference between the top and bottom view bounds is used as the height of the view. If you specify zero for top, the view is centered in the parent view. If you specify any other number for top, the view is offset by that much from a centered position (for example, specifying top = –10 and bottom = height–10 offsets the view 10 pixels above a centered position).
C H A P T E R 3 Views Table 3-1 Constant viewJustify constants (continued) Value Description noLineLimits 0 (Default) No limits, text wraps to next line. oneLineOnly 8388608 Allows only a single line of text, with no wrapping. oneWordOnly 16777216 Allows only a single word. (If the user writes another word, it replaces the first.) Text limits Indicate that a bounds value is a ratio vjNoRatio 0 (Default) Do not use proportional alignment.
C H A P T E R 3 Views Figure 3-7 View alignment effects Justify v jFullV Horizontal alignment of view contents 3-18 About Views Vertical alignment of view contents
C H A P T E R 3 Views Figure 3-7 View alignment effects (continued) Parent viewBounds: {left:0. Top:25, Right:175, Bottom:75} Sibling View Each of the paragraph views has the same viewBounds: {left:0. Top:100, Right:175, Bottom:150} viewBounds: {Left:0, Top:23, Right:185, Bottom:43} viewBounds: {left:175. Top:175, Right:0, Bottom:225} viewBounds: {left:0.
C H A P T E R 3 Views viewOriginX and viewOriginY Slots 3 These slots can be read but not written or set. Instead, use Setorigin to set the origin offset for a view. For more information, see “Scrolling View Contents” (page 3-41). If you use these slots to specify an offset, the point you specify becomes the new origin. Child views are drawn offset by this amount. This is useful for displaying different portions of a view whose content area is larger than its visible area.
C H A P T E R 3 Views IMPORTANT Many views need no fill pattern, so you may be inclined to set the fill pattern to “none” when you create such a view. However, it’s best to fill the view with white, if the view may be explicitly dirtied (in need of redrawing) and if you don’t need a transparent view. This increases the performance of your application because when the system is redrawing the screen, it doesn’t have to update views behind those filled with a solid color such as white.
C H A P T E R 3 Views Drawing Transfer Mode for Views 3 The viewTransferMode slot specifies the transfer mode to be used for drawing in the view. The transfer mode controls how bits being drawn are placed over existing bits on the screen. The constants that you can specify for the viewTransferMode slot are listed and described in Table 2-6 (page 2-14) in the Newton Programmer’s Reference. The transfer mode is used to specify how bits are copied onto the screen when something is drawn in a view.
C H A P T E R 3 Views Opening and Closing Animation Effects 3 Another attribute of a view that you can specify is an animation that occurs when the view is opened or closed on the screen. If an effect is defined for a view, it occurs whenever the view is sent an Open, Close, Show, Hide, or Toggle message. Use the viewEffect slot to give the view an opening or closing animation.
C H A P T E R 3 Views ■ fxZoomCloseEffect—opposite of fxZoomOpenEffect. This value shrinks the image of the view from a point in the center until it disappears or closes on the screen. ■ fxZoomVerticalEffect—the view expands out from a horizontal line in the center of its bounds. The top half moves upward and lower half moves downward.
C H A P T E R 3 Views _parent stepChildren viewChildren Contains a reference to the parent template. This slot is created when the view opens. Note that it’s best to use the Parent function to access the parent view at run time, rather than directly referencing the _parent slot. Contains an array that holds references to each of the template’s child templates. This slot is created and set automatically when you graphically create child views in NTK.
C H A P T E R 3 Views IMPORTANT Remember that the viewChildren and stepChildren arrays contain templates, not views. If you try to send a message like Hide to one of the objects listed in this array, the system will probably throw an exception because it is not a view. During run time, if you want to obtain references to the child views of a particular view, you must use the ChildViewFrames method. This method returns views from both the viewChildren and stepChildren slots.
C H A P T E R 3 Views Declaring a View 3 Before diving into the discussion of view instantiation, it is important to understand the term declaring. Declaring a view is something you do during the application development process using the Newton Toolkit (NTK). Declaring a view allows it to be accessed symbolically from another view. In NTK, you declare a view using the Template Info command.
C H A P T E R 3 Views For a more detailed technical description of the inner workings of declaring a view, see Appendix A, “The Inside Story on Declare.” Creating a View 3 A view is created in two stages. First, a view memory object (a frame) is created in RAM. This view memory object contains a reference to its template, along with other transient run-time information. In the following discussion, the phrase, “creating the view” is used to describe just this part of the process.
C H A P T E R 3 Views 5. The viewChildren and stepChildren slots are read and the child views are instantiated using this same process. As part of the process, the following messages are sent to each child view, in this order: ViewSetupFormScript, ViewSetupChildrenScript, and ViewSetupDoneScript. 6. The ViewSetupDoneScript message is sent to the view. 7. The view is displayed if its vVisible viewFlags bit is set. 8.
C H A P T E R 3 Views View Compatibility 3 The following new functionality has been added for the 2.0 release of Newton System Software. See the Newton Programmer’s Reference for complete descriptions on each new function and method. New Drag and Drop API 3 A drag and drop API has been added. This API now lets users drag a view, or part of a view, and drop it into another view. See “Dragging and Dropping with Views” (page 3-40) for details.
C H A P T E R 3 Views New Alignment Flags 3 The viewJustify slot contains new constants that allow you to specify that a view is sized proportionally to its sibling or parent view, both horizontally and/or vertically. A change to the way existing viewJustify constants work is that when you are using sibling-relative alignment, the first sibling uses the parent alignment settings (since it has no sibling to which to justify itself).
C H A P T E R 3 Views New Warning Messages 3 Warning messages are now printed to the inspector when a NewtonScript application calls a view method in situations where the requested operation is unwise, unnecessary, ambiguous, invalid, or just a bad idea. Obsolete Functions and Methods 3 The following functions and methods are obsolete with version 2.0 of the Newton System Software: ■ Confirm, which created and displayed an OK/Cancel slip. Use AsyncConfirm instead.
C H A P T E R 3 Views Displaying, Hiding, and Redrawing Views 3 To display a view (and its visible child views), send it one of the following view messages: ■ Open—to open the view ■ Toggle—to open or close the view ■ Show—to show the view if it had previously been opened, then hidden ■ To hide a view (and its child views), send it one of the following view messages: ■ Close—to hide and possibly delete it from memory ■ Toggle—to close or open the view ■ Hide—to hide it temporarily You can
C H A P T E R 3 Views Showing a Hidden View 3 In many cases, you might think that you need to create a view dynamically. However, if the template can be defined at compile time, it’s easier to do that and flag the view as not visible. At the appropriate time, send it the Open message to show it. The typical example of this is a slip, which you can usually define at compile time. Using the Newton Toolkit (NTK), simply do not check the vVisible flag in the viewFlags slot of the view template.
C H A P T E R 3 Views If at some point after the child views have been created you want to modify the contents of the stepChildren array and build new child views from it, you can use the RedoChildren view method. First, make any changes you desire to the stepChildren array, then send your view the RedoChildren message. All of the view’s current children will be closed and removed. A new set of child views will then be recreated from the stepChildren array.
C H A P T E R 3 Views To remove a view created by AddStepView, use the RemoveStepView function. This function takes two parameters: the parent view from which you want to remove the child view, and the view (not its template) that you want to remove. For details on an easy way to create a template dynamically, see “Creating Templates” (page 3-36). Using the BuildContext Function 3 Another function that is occasionally useful is BuildContext. It takes one parameter, a template.
C H A P T E R 3 Views needed values. Your template is only a two-slot object in RAM. The user proto resides in the package with the rest of your application. The conventional, RAMwasting alternative would have been: template := Clone(PT_dynoTemplate); template.viewBounds := RelBounds(x, y, width, height); Note that for creating views arranged in a table, there is a function called LayoutTable that calculates all the bounds. It returns an array of templates.
C H A P T E R 3 Views Each of the three return values contains three elements: ■ Element 0: the subview that is highlighted. This subview is usually a clParagraphView, but you need to check to make sure. A clPolygonView is not returned here even if HiliteOwner returns a clEditView when a clPolygonView child is highlighted. ■ Element 1: the start position of the text found in the text slot of a clParagraphView. ■ Element 2: the end position of the text found in the text slot of a clParagraphView.
C H A P T E R 3 Views Typically, modal views are used for slips. For example, if the user was going to delete some data in your application, you might want to display a slip asking them to confirm or cancel the operation. The slip would prevent them from going to another operation until they provide an answer. Use AsyncConfirm to create and display a slip that the user must dismiss before continuing.
C H A P T E R 3 Views Animating Views 3 There are four view methods that perform special animation effects on views. They are summarized here: ■ Effect—performs any animation that can be specified in the viewEffect slot. ■ SlideEffect—slides a whole view or its contents up or down. ■ RevealEffect—slides part of a view up or down. ■ Delete—crumples a view and tosses it into a trash can. Note that these animation methods only move bits around on the screen.
C H A P T E R 3 Views ■ GetDropDataScript— is sent to the source view when the destination view is found. ■ ViewDropScript— is sent to the destination view. You must add the object to the destination view. ■ ViewDropMoveScript— is sent to the source view. It is used when dragging an object within the same view. ViewDropRemoveScript and ViewDropScript are not called in this case. ■ ViewDropRemoveScript — is sent to the source view. It is used when dragging an object from one view to another.
C H A P T E R 3 Views In the latter kind of scrolling, the child views are moved within the parent view by changing their view bounds. Newly visible views will be opened for the first time, and views which have scrolled completely out-of-view will be closed. The viewOriginX and viewOriginY slots are not used. For information about techniques you can use to optimize scrolling so that it happens as fast as possible, see “Scrolling” (page 3-46), and “Optimizing View Performance” (page 3-44).
C H A P T E R 3 Views To determine if a given view is highlighted, check the vSelected bit in the viewFlags. vSelected should not be set by your application, but you can test it to see if a view is currently selected (that is, highlighted.) If BAND(viewflags,vSelected) <> 0 is non-nil, the view is selected. Creating View Dependencies 3 You can make one view dependent upon another by using the global function TieViews. The dependent view is notified whenever the view it is dependent on changes.
C H A P T E R 3 Views To lay out a view containing a vertical column of child views, send the view the message LayoutColumn. Optimizing View Performance 3 Drawing, updating, scrolling, and performing other view operations can account for a significant amount of time used during the execution of your application. Here are some techniques that can help speed up the view performance of your application.
C H A P T E R 3 Views views). Also, if there are multiple dirty views that are in different view hierarchies, their closest common ancestor view is redrawn, potentially causing many other views to be redrawn needlessly.
C H A P T E R 3 Views view of your application, you should set to nil those slots that aren’t needed when the application is closed, since they are wasting space in the NewtonScript heap. It is especially important to set to nil slots that reference soups and cursors, if they are not needed, since they use relatively much space. If your application is gathering data from the user that needs to be stored, store the data in a soup, rather than in slots in one of the application views.
C H A P T E R 3 Views Summary of Views 3 Constants 3 Class Constants Constant Value clView 74 clPictureView 76 clEditView 77 clKeyboardView 79 clMonthView 80 clParagraphView 81 clPolygonView 82 clRemoteView 88 clPickView 91 clGaugeView 92 clOutline 105 viewFlags Constants Constant Value vNoFlags 0 vVisible 1 vReadOnly 2 vApplication 4 vCalculateBounds 8 vClipping 32 vFloating 64 vWriteProtected 128 vClickable 512 vNoScripts 134217728 Summary of Views 3-4
C H A P T E R 3 Views viewFormat Constants Constant Value vfNone 0 vfFillWhite 1 vfFillLtGray 2 vfFillGray 3 vfFillDkGray 4 vfFillBlack 5 vfFillCustom 14 vfFrameWhite 16 vfFrameLtGray 32 vfFrameGray 48 vfFrameDkGray 64 vfFrameBlack 80 vfFrameDragger 208 vfFrameCustom 224 vfFrameMatte 240 vfPen(pixels) pixels 256 vfLinesWhite 4096 vfLinesLtGray 8192 vfLinesGray 12288 vfLinesDkGray 16384 vfLinesBlack 20480 vfInset(pixels) pixels 65536 vfLinesCustom 57344 vfSh
C H A P T E R 3 Views viewTransferMode Constants Constant Value modeCopy 0 modeOr 1 modeXor 2 modeBic 3 modeNotCopy 4 modeNotOr 5 modeNotXor 6 modeNotBic 7 modeMask 8 viewEffect Constants Constant Bit Flag Integer Value fxColumns(x) ((x-1) << fxColumnsShift) x-1 fxRows(x) ((x-1) << fxRowsShift) (x-1)*32 fxHStartPhase (1 << fxHStartPhaseShift) 1024 fxVStartPhase (1 << fxVStartPhaseShift) 2048 fxColAltHPhase (1 << fxColAltHPhaseShift) 4096 fxColAltVPhase (1 << fxColAl
C H A P T E R 3 Views Constant Bit Flag Integer Value fxCheckerboardEffect fxColumns(8)+fxRows(8)+fxColAltVPhase+ fxRowAltHPhase+fxDown 155879 fxZoomVerticalEffect fxColumns(1)+fxRows(2)+fxUp+ fxRowAltVPhase 165920 fxColumns(2)+fxRows(2)+fxUp+fxLeft 199713 fxColumns(2)+fxRows(2)+fxUp+fxLeft+ fxColAltHPhase+fxRowAltVPhase 236577 (1 << fxRevealLineShift) 262144 fxDown+fxRevealLine 393216 1 << fxWipeShift) 524288 fxZoomCloseEffect fxZoomOpenEffect fxRevealLine fxPopDownEffect fxWipe fxBa
C H A P T E R 3 Views Functions and Methods 3 Getting References to Views view:ChildViewFrames() view:Parent() GetRoot() GetView(symbol) Displaying, Hiding, and Redrawing Views view:Open() view:Close() view:Toggle() view:Show() view:Hide() view:Dirty() RefreshViews() SetValue(view, slotSymbol, value) view:SyncView() viewToMove:MoveBehind(view) Dynamically Adding Views AddStepView(parentView, childTemplate) RemoveStepView(parentView, childView) AddView(parentView, childTemplate) BuildContext(template) M
C H A P T E R 3 Views view:RevealEffect(distance, bounds, sound, methodName, methodParameters) view:Delete(methodName, methodParameters) Dragging a View view:Drag(unit, dragBounds) Dragging and Dropping an Item view:DragAndDrop(unit, bounds, limitBounds, copy, dragInfo) Scrolling View Contents view:SetOrigin(originX, originY) view:SyncScroll(What, index, upDown) Working With View Highlighting view:Hilite(on) view:HiliteUnique(on) view:TrackHilite(unit) view:TrackButton(unit) HiliteOwner() GetHiliteOffse
C H A P T E R 3 Views ViewScrollUpScript() ViewOverviewScript() ViewAddChildScript(child) ViewChangedScript(slot, view) ViewDropChildScript(child) ViewIdleScript() sourceView:ViewDrawDragDataScript(bounds) sourceView:ViewDrawDragBackgroundScript(bounds, copy) destView:ViewGetDropTypesScript(currentPoint) src: ViewGetDropDataScript(dragType, dragRef) destView:ViewDragFeedbackScript(dragInfo, currentPoint, show) sourceView:ViewDropApproveScript(destView) sourceView:ViewGetDropDataScript(dragType, dragRef)
C H A P T E R Figure 4-0 Table 4-0 4 NewtApp Applications 4 NewtApp is a collection of prototypes that work together in an application framework. Using these protos you can quickly construct a full-featured application that includes functionality like finding and filing. Whether or not you have written an application for the Newton platform before, you should read this chapter.
C H A P T E R 4 NewtApp Applications You can create most kinds of applications with the NewtApp framework. If your application is similar to a data browser or editor, or if it implements an automated form, you can save yourself a significant amount of time by using the NewtApp framework.
C H A P T E R 4 NewtApp Applications The parts of the NewtApp framework are designed to fit together using the two-part NewtonScript inheritance scheme. Generally speaking, the framework is constructed so the user interface components of your application (such as views and buttons) use proto inheritance to make methods and application-state variables, which are provided by NewtApp (and transparent to you), available to your application.
C H A P T E R 4 NewtApp Applications Note This drawing does not depict the protos as they would appear in a Newton Toolkit layout window. ◆ The basic NewtApp protos are defined here in very general terms. Note that unlike Figure 4-1, this list includes the proto for storing data, which does not have a visual representation in a layout file. ■ The newtApplication proto is the application’s base view.
C H A P T E R 4 NewtApp Applications About newtSoup 4 Application data is stored in persistent structures known as soups in any Newton application. In a NewtApp application, soup definitions, written in the newtApplication.allSoups slot, must be based on the newtSoup proto. Within a soup, data is stored in frames known as entries. In turn, entries contain the individual slots in which you store your application’s data.
C H A P T E R 4 NewtApp Applications Figure 4-2 A roll-based application (left) versus a card-based application The page-based application is a hybrid of the card-based and roll-based applications. Like the card-based application, the page-based application shows only one entry at a time. However, unlike the card-based application but like the roll-based application, an entry may be longer than a screen’s length.
C H A P T E R 4 NewtApp Applications Figure 4-3 Calls is an example of a page-based application The overview protos are also layouts; they include the newtOverLayout and newtRollOverLayout protos. The NewtApp framework code that governs soups, scrolling, and all the standard view functionality, is implemented in the layout protos. A main (default) view layout and an overview layout must be declared in the allLayouts slot of the newtApplication base view.
C H A P T E R 4 NewtApp Applications The Entry View Protos 4 The entry view is the focal point for operations that happen on one soup entry frame at a time. These include functions such as displaying and updating data stored in the entry’s slots. The NewtApp framework has three entry view protos: newtEntryView, newtRollEntryView, and newtFalseEntryView.
C H A P T E R 4 NewtApp Applications Note that the header bar contains the Action and Filing buttons on its right side. These buttons appear on the header bar to prevent any ambiguity regarding the entry to be acted upon by those buttons. In addition, the header bar contains a Title and icon on the left. When the icon is tapped, the Information slip appears, as shown in Figure 4-5.
C H A P T E R 4 NewtApp Applications data which they format appropriately. For example, the number views (newtNumberView and newtRONumberView) format number data (according to the value of a format slot you set). The labelled input-line slot view protos provide you with a label, which you may specify, for the input line. Additionally, the label may include a picker (pop-up menu). These views also format a particular kind of data.
C H A P T E R 4 NewtApp Applications Figure 4-6 The smart name view and system-provided people picker Stationery 4 Stationery, an extension you can add to any NewtApp application, is tightly integrated with the NewtApp framework. Stationery consists of two components that work together: a data definition (dataDef) and a view definition (viewDef). The dataDef provides a definition of the data to be used in the stationery. It is registered in conjunction with its display component, which is a viewDef.
C H A P T E R 4 NewtApp Applications Some NewtApp protos are usable in your non-NewtApp applications. For example, there is a newtStatusBarNoClose proto, see page 3-29 in the Newton Programmer’s Reference, that is unique to NewtApp, which may be used, without special provision, in a non-NewtApp application. Other NewtApp protos—specifically the slot views—can function only within a simulated NewtApp environment.
C H A P T E R 4 NewtApp Applications responsibility for its operation is 100% yours. If you are going to redistribute it, you must make it clear in your source files that the code descended from Apple-provided sample code and you have made changes. The sample is an application for gathering data that supports the system services routing, filing, and finding. It presents two views of the data to be collected: a required default view; “IOU Info” (and an alternate “IOU Notes” view); and a required overview.
C H A P T E R 4 NewtApp Applications One other global, unique to this application, is set. It is the constant kAppTitle, set to the string "Card Starter". Using newtApplication 4 This proto serves as the template for the application base view. This section shows you how to use it to set up the ■ application base view ■ application soup ■ status bar; for layout-level control of the appearance and disappearance of its buttons.
C H A P T E R 4 NewtApp Applications ■ Optional. Set the statusBarSlot to contain the declared name of the status bar so layouts can use it to control the buttons displayed on it. Use the symbol 'status to set it. If you wish to override a system message like ViewSetupFormScript, which is called before a view is displayed on the screen, make sure to call the inherited method at the end of your own ViewSetupFormScript method.
C H A P T E R 4 NewtApp Applications Use code similar to the following example to set the allSoups slot: allSoups:= { IOUSoup: {_proto: newtSoup, soupName: "IOU:PIEDTS", soupIndices: [ {structure: 'slot, path: 'title, type: 'string}, {structure: 'slot, path: 'timeStamp, type: 'int}, { structure: 'slot, path: 'labels, type: 'tags } ], soupQuery: {type: 'index, indexPath: 'timeStamp}, soupDescr: "The IOU soup.
C H A P T E R 4 NewtApp Applications where items is replaced by the value of the appObject slot set in the newtApplication base view. An example of this message from the Names application is shown in Figure 4-7. Figure 4-7 The message resulting from a nil value for forceNewEntry Using newtOverLayout 4 The slots you must set for an overview are shown in the Overview Layout browser in Figure 4-8. Figure 4-8 The overview slots Follow these steps to create the required overview layout: 1.
C H A P T E R 4 NewtApp Applications 3. Set the masterSoupSlot to the symbol 'IOUSoup. This correlates to the name of the soup as it is set up in the newtApplication.allSoups slot. See “Setting Up the Application Soup,” beginning on page 4-15. 4. Add the forceNewEntry slot. Leave it with the default value true. This causes a new entry to be created if a user tries to open an empty folder. 5. Add a viewFormat slot and set the Fill value to White.
C H A P T E R 4 NewtApp Applications menuRightButtons:=[ newtActionButton, newtFilingButton, ] Be sure to add the Overview Layout template file to your NTK Project window. Creating the Default Layout 4 This is the view you see upon opening the application. Since it will eventually contain views that display the data, it needs to know about the application soup. The masterSoupSlot identifies the application soup to the layout proto.
C H A P T E R 4 NewtApp Applications Follow these steps to ready your application for the slot views: 1. Drag out a newtEntryView proto on top of the newtLayout proto. 2. Optional. Name it theEntry. There are no unusual slots to set in an entry view. Therefore, you are ready to add the header and slot view protos. 3. Drag out a newtEntryPageHeader across the top of the newtEntryView. 4. Under the header, drag out a newtStationeryView proto that covers the rest of the entry view.
C H A P T E R 4 NewtApp Applications frame containing slots with references to all the viewDef layout templates that work with that dataDef. The recommended way to name the corresponding allDataDefs and allViewDefs slots is to set the slot names to the data symbol constant, as shown in the following code examples. Set the allDataDefs slot to return a frame with references to all the application’s dataDefs, as follows: result := {}; result.(kDataSymbol) := GetLayout("IOUDataDef"); // result.
C H A P T E R 4 NewtApp Applications You should create a text file, which you save as Install&Remove.f, into which to copy the functions: InstallScript := func(partFrame) begin partFrame.removeFrame := (partFrame.theForm):NewtInstallScript(partFrame.theForm); end; RemoveScript := func(partFrame) begin (partFrame.removeFrame):NewtRemoveScript(removeFrame); end; This file should be the last one processed when your application is built.
C H A P T E R 4 NewtApp Applications Certain slots must be added to these base view slots for your application to be able to utilize the false entry view and the slot views. First, you must be sure to add a target slot and targetView slot, so that the false entry view can set them when an entry is changed. Second, you should include a method that sends the Retarget message to the false entry view when an entry is changed.
C H A P T E R 4 NewtApp Applications omitted if your base application view’s soup slot is set to the default name dataSoup. ■ Add a soupQuerySlot and set it to the symbol 'cardSoupQuerySpec. This symbol should match a slot defined in your application base view. The slot may be omitted if your base application view’s soup query slot is set to the default name soupQuery.
C H A P T E R 4 NewtApp Applications Summary of the NewtApp Framework 4 Required Code 4 Required InstallScript 4 InstallScript := func(partFrame) begin partFrame.removeFrame := (partFrame.theForm): NewtInstallScript(partFrame.theForm); end; Required RemoveScript 4 RemoveScript := func(partFrame) begin (partFrame.removeFrame):NewtRemoveScript(removeFrame); end; Protos 4 newtSoup 4 myNewtSoup := { _proto: newtSoup, // NewtApp soup proto soupName: "MyApp:SIG", // a string unique to your app.
C H A P T E R 4 NewtApp Applications AddEntry: //Adds the entry to the specified store func(entry, store) ... AdoptEntry: // Adds entry to the application soup while func(entry, type)... // preserving dataDef entry slots CreateBlankEntry: // Returns a blank entry func() ... DeleteEntry: // Removes an entry from its soup func(entry) ... DuplicateEntry: // Clones and returns entry func(entry) ... DoneWithSoup: // Unregisters soup changes and soup func(appSymbol) ...
C H A P T E R 4 NewtApp Applications newtApplication 4 myNewtAppBaseView := { _proto: newtapplication, // Application base view proto appSymbol: '|IOU:DTS| //Unique application symbol title: "Roll Starter" // A string naming the app appObject: ["Ox", "Oxen"]// Array with singular and // plural strings describing application’s data appAll: "All Notes" // Displayed in folder tab picker allSoups: { //Frame defining all known soups for app mySoup: { _proto: newtSoup, ...
C H A P T E R 4 NewtApp Applications dateFindSlot: pathExpression // Enables dateFind for your // app. Path must lead to a slot containing a date. routeScripts: //Contains default Delete and Duplicate //route scripts. labelsFilter: //Set dynamically for filing settings layout: // Set to the current layout newtAppBase: //Set dynamically to identify, for //instance, view to be closed when close box tapped retargetChain: // Dynamically set array of views // to update.
C H A P T E R 4 NewtApp Applications Find: // Default Find method as defined in framework. func(text, results, scope, findContext)... ShowLayout:// Switches display to specified layout. func(layout)... NewtDeleteScript:// Deletes entry. func(entry, view)... // Referenced in routeScripts array NewtDuplicateScript:// Duplicates entry. func(entry, view)... // Referenced in routeScripts array GetAppState:// Gets app preferences, sets app, & returns func()... // prefs. Override to add own app prefs.
C H A P T E R 4 NewtApp Applications newtAZTabs myAZTab:= { _proto: newtAZTabs, PickActionScript: func(letter)...
C H A P T E R 4 NewtApp Applications newtPrefsView 4 aPrefsView:= { // The preferences view _proto: newtPrefsView } newtLayout 4 aBasicLayout:= { // The basic layout view _proto: newtLayout, name: "", // Optional. masterSoupSlot: 'mainSoup, // Required. // Symbol referring to soup from allSoups slot forceNewEntry: true, //Forces new entry when empty //folder opened.
C H A P T E R 4 NewtApp Applications newtRollLayout 4 myRollLayout:= { // Dynamically lays out child views _proto: newtRollLayout, // using protoChild as default protoChild: GetLayout("DefaultEntryView"), // Default view name: "", // Optional. masterSoupSlot: 'mainSoup, // Required. // Symbol referring to soup from allSoups slot forceNewEntry: true, //Forces new entry when empty //folder opened.
C H A P T E R 4 NewtApp Applications forceNewEntry: true, //Creates blank entry for layout menuRightButtons:[], //Replaces slot in status bar menuLeftButtons:[], //Replaces slot in status bar nothingCheckable: nil, //True suppresses checkboxes Abstract: //Returns shapes for items in overviews func(targetEntry, bbox)..., //Override to extract text GetTargetInfo: //Returns frame with target information func(targetType)..., HitItem: //Called when overview item is tapped. func(index, x, y)...
C H A P T E R 4 NewtApp Applications currentViewDef: //Set to current viewDef currentStatView: //Set to current context of viewDef StartFlush: // Starts timer that flushes entry func()..., EndFlush: // Called when flush timer fires func()..., EntryCool: // Is target read-only? True report func(report)..., //displays write-protected message JamFromEntry: // Finds children’s jamFromEntry and sends func(otherEntry)...
C H A P T E R 4 NewtApp Applications newtEntryRollHeader 4 aRollHeader:= { // Header/divider bar for page or // roll-style apps _proto: newtEntryRollHeader, hasFiling: true // Nil is no filing or action buttons isResizable: true // Nil is no drag resizing } newtEntryViewActionButton 4 anEntryActionButton:= {// Action button to use on headers // and within entry views _proto: newtEntryViewActionButton } newtEntryViewFilingButton 4 anEntryFilingButton:= {// Filing button to use on headers // and w
C H A P T E R 4 NewtApp Applications newtTextView 4 editableTextView:= {// This is the editable text view _proto: newtTextView, path: 'pathExpr,// Text stored/retrieved from here styles: nil,// Plain text. tabs: nil,// Tabs not enabled. jamSlot: 'jamPathExpr,// New path for JamFromEntry. TextScript: // Returns a text representation of data func()..., // JamFromEntry: // Retargets to jamPathExpr if not nil func(jamPathExpr)...
C H A P T E R 4 NewtApp Applications longFormat: yearMonthDayStrSpec,// for LongDateStr shortFormat: nil, // for ShortDateStr function TextScript: // Returns a text representation of data func()..., // JamFromEntry: // Retargets to jamPathExpr if not nil func(jamPathExpr)..., // } newtTextDateView 4 editableTextDateView:= {// Editable text and date view.
C H A P T E R 4 NewtApp Applications newtROTextPhoneView 4 readOnlyTextPhoneView:= {// Displays phone numbers _proto: newtROTextPhoneView, path: 'pathExpr,// Data stored/retrieved from here TextScript: // Returns a text representation of data func()..., // JamFromEntry: // Retargets to jamPathExpr if not nil func(jamPathExpr)...
C H A P T E R 4 NewtApp Applications newtROEditView 4 readOnlyEditView:= { // A text display view, which // may have scrollers _proto: newtROEditView, optionFlags: kNoOptions, // disables scroller //kHasScrollersOption enables scroller doCaret: true, //caret is autoset viewLineSpacing: 28, path: 'pathExpr,// Data stored/retrieved from here ScrolltoWord: // Finds words, scrolls to it, and highfunc(words, hilite)...
C H A P T E R 4 NewtApp Applications newtStationeryView 4 stationeryView:= { // Used as bounding box and container // view for viewDef _proto: newtStationeryView } newtEntryLockedIcon 4 entryLockedIcon:= { //Shows lock if slot is on locked media _proto: newtEntryLockedIcon icon: nil,// Can also be: lockedIcon Retarget : // displays either lock or unlocked icon func()..., SetIcon: // Changes target.(path) value to its func()...
C H A P T E R 4 NewtApp Applications usePopup: true,// When true with labelCommands array // picker is enabled access: 'readWrite,// Could be 'readOnly or 'pickOnly flavor: newtTextFilter,// memory: nil, // most recent picker choices path: 'pathExpr,// Data stored/retrieved from here ChangePopup: // change picker items before they display func(item, entry)..., // UpdateText: // Used with Undo to update text to new text func(newText)...
C H A P T E R 4 NewtApp Applications newtROLabelNumInputLine 4 aDisplayLabelNumberInputLine:= {// Labelled number display line _proto: newtROLabelNumInputLine, label: "",// Text for input line label flavor: newtNumberFilter,// path: 'pathExpr,// Data stored/retrieved from here UpdateText: // Used with Undo to update text to new text func(newText)...
C H A P T E R 4 NewtApp Applications _proto: newtLabelSimpleDateInputLine, label: "",// Text for input line label access: 'readWrite,// Could be 'readOnly or 'pickOnly flavor: newtSimpleDateFilter,// path: 'pathExpr,// Data stored/retrieved from here UpdateText: // Used with Undo to update text to new text func(newText)...
C H A P T E R 4 NewtApp Applications UpdateText: // Used with Undo to update text to new text func(newText)..., // } newtNRLabelTimeInputLine 4 pickerLabelTimeInputLine:= { // Input through TimePopup picker _proto: newtNRLabelTimeInputLine, label: "",// Text for input line label access: 'pickOnly,// Could be 'readOnly flavor: newtTimeFilter,// Don’t change path: 'pathExpr,// Data stored/retrieved from here UpdateText: // Used with Undo to update text to new text func(newText)...
C H A P T E R Figure 5-0 Table 5-0 5 Stationery 5 Stationery, which consists of new data formats and different views of your data, may be built into an application or added as an extension. Once incorporated, these data formats and views are available through the pickers (pop-up menus) of the New and Show buttons. Stationery works best when incorporated into a NewtApp application. It is part of the NewtApp framework and is tightly integrated into its structures.
C H A P T E R 5 Stationery A dataDef is based on the newtStationery proto and is used to create alternative data structures. The dataDef contains slots that define, describe, and identify its data structures. It also contains a slot, called superSymbol, that identifies the application into which its data entries are to be subsumed. It also contains a name slot where the string that names the dataDef is placed. This is the name that appears in the New picker.
C H A P T E R 5 Stationery Figure 5-1 The IOU extension in the New picker When you choose IOU from the New picker, an IOU entry is displayed, as shown in Figure 5-2. Figure 5-2 The IOU extension to the Notes application The Show button offers different views for the display of application data. These are generated by the viewDefs defined for an application. For example, the choices in the Show button of the built-in Names application include a Card and All Info view of the data.
C H A P T E R 5 Stationery Figure 5-3 The Show menu presents different views of application data Stationery Registration 5 Your stationery, which may be built as part of an application or outside of an application (as an NTK auto part), must be registered with the system when an application is installed and unregistered when an application is uninstalled.
C H A P T E R 5 Stationery Getting Information about Stationery 5 By using the appropriate global function, you can get information about all the dataDefs and viewDefs that have been registered and thus are part of the system registry. These functions include GetDefs, GetDataDefs, GetAppDataDefs, GetViewDefs, and so on. For details on these functions, see Newton Programmer’s Reference. You can also obtain application-specific stationery information.
C H A P T E R 5 Stationery The dataDef component of your stationery should use a FillNewEntry method to define its own discrete soup entry structure. Note that it is your responsibility to set a class slot within each entry. The value of the class slot must match the dataDef symbol and is used by the system when routing the entry (via faxing, mailing, beaming, printing, and so on). An example of how to use FillNewEntry follows.
C H A P T E R 5 Stationery newEntry.class := kDataSymbol; newEntry.viewStationery := kDataSymbol; newEntry.(kDataSymbol).dueDate:=time(); newEntry; end; Extending the Notes Application 5 You may extend an existing application, such as the built-in Notes application, by adding your own stationery. This is done by building and downloading an NTK auto part that defines your stationery extensions.
C H A P T E R 5 Stationery A call to the global function GetDefs in the NTK Inspector window returns a series of frames describing dataDefs that have been registered with the system. An excerpt of the output from a call made in the Inspector window follows.
C H A P T E R 5 Stationery The following example uses the constant kSuperSymbol as the value of the superSymbol slot. It is defined as follows in the Extend Notes Definition.f file: constant kSuperSymbol := 'notes;// Note's SuperSymbol Once you have created an NTK layout, named the template iouDataDef, and saved the file under the name iouDataDef, you may set the slots of the iouDataDef as follows: ■ Set name to "IOU". This shows up in the New button’s picker.
C H A P T E R 5 Stationery // Generic entry definition: DefConst('kEntryTemplate, { class: kDataSymbol, viewStationery: kDataSymbol,// vestigial; for Notes // compatibility title: nil, timeStamp: nil, height: 176, // For page and paper roll-type apps // this should be the same as height // slot in dataDef and viewDefHeight // slot in viewDef (if present) }); // This facilitates writing viewDefs that can be reused kEntryTemplate.
C H A P T E R 5 Stationery Here is an example: TextScript: func(item,target) begin item.text := "IOU\n" & target.(kDataSymbol).who && "owes me" && NumberStr(target.(kDataSymbol).howMuch); item.text; end; Creating ViewDefs 5 ViewDefs may be based on any of the generic view protos. You could use, for instance, a clView, which has very little functionality. Or, if you wanted a picture to display behind your data, you could base your viewDef on a clPictureView.
C H A P T E R 5 Stationery Add the protos that will display the data and labels to the working application. The protos used here include: ■ newtSmartNameView ■ newtLabelNumInputLine ■ newtLabelDateInputLine ■ newtLabelTimeInputLine You can read more about these protos in Chapter 4, “NewtApp Applications.” They should be aligned as shown in Figure 5-4. Figure 5-4 The default viewDef view template Set the slots of the newtSmartNameView as follows: ■ Set the label slot to "Who".
C H A P T E R 5 Stationery Set the slots of the newtLabelNumInputLine as follows: ■ Set the label slot to "How Much". ■ Set the path slot to [pathExpr: kDataSymbol, 'howMuch]. This path slot must evaluate to a slot in your data entry frame that contains a number (or a place to store one). Add a newtLabelDateInputLine at the top of the default template so that it is aligned as shown. Then set the slots as follows: ■ Set the label slot to "Date Due".
C H A P T E R 5 Stationery Using the MinimalBounds ViewDef Method The MinimalBounds method must be used in a viewDef when the size of the entry is dynamic, as it is in a paper-roll-style or page-style application. It’s not necessary for a card-style application, which has a fixed height; in that case you should set a static height for your viewDef in the viewDefHeight slot. The MinimalBounds method is used to compute the minimal size for the enclosing bounding box for the viewDef at run time.
C H A P T E R 5 Stationery Stationery Summary 5 Data Structures 5 ViewDef Frame 5 myViewDef := { _proto: anyGenericView, type: 'editor, // could also be 'viewer or a custom type symbol: 'default, // required; identifies the view name: string, // required; name of viewDef version: integer, // required; should match dataDef viewDefHeight: integer, // required, except in card-style MinimalBounds: // returns the minimal enclosing func(entry)...
C H A P T E R 5 Stationery newtStationeryPopupButton 5 aStatPopup := { // used to construct New and Show buttons _proto: newtStationeryPopupButton, form: symbol, // 'viewDef or 'dataDef symbols: nil, // gathers all or specify:[uniqueSym,…] text: string, // text displayed in picker types: [typeSym,…],// type slots of viewDefs sorter: '|str<|,// sorted alphabetically by Sort function shortCircuit: Boolean, // controls picker behavior StatScript: // called when picker item chosen func(stationeryItem)...
C H A P T E R 5 Stationery newtRollShowStationeryButton 5 aRollShowButton := { // the Show button in paper roll apps _proto: newtRollShowStationeryButton, types: [typeSym,…],// can specify type slots of viewDefs sorter: '|str<|,// sorted alphabetically by Sort function shortCircuit: Boolean,// controls picker behavior StatScript: // called when picker item chosen func(stationeryItem)..., // define actions in this method SetUpStatArray:// override to intercept picker items to func()...
C H A P T E R Figure 6-0 Table 6-0 6 Pickers, Pop-up Views, and Overviews 6 This chapter describes how to use pickers and pop-up views to present information and choices to the user. You should read this chapter if you are ■ creating your own pickers and pop-up views ■ taking advantage of built-in picker and pop-up protos ■ presenting outlines and overviews of data Before reading this chapter, you should be familiar with the information in Chapter 3, “Views.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews More sophisticated picker protos allow multiple selections and use a close box to dispatch the view. With some picker protos, you must determine when and how the picker is displayed. You open a picker view by sending the Open message to the view, or by calling the PopupMenu function.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ protoDateDurationTextPicker ■ protoRepeatDateDurationTextPicker ■ protoDateNTimeTextPicker ■ protoTimeTextPicker ■ protoDurationTextPicker ■ protoTimeDeltaTimePicker ■ protoMapTextPicker ■ protoCountryTextPicker ■ protoUSstatesTextPicker ■ protoCitiesTextPicker ■ protoLongLatTextPicker New date, time, and location pop-up views let the user specify new information in a graphical view—changing the date on a calendar, for example.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ protoPeoplePopup The following two protos are data types that support the protoListPicker: ■ protoNameRefDataDef ■ protoPeopleDataDef Obsolete Function 6 The DoPopup global function used in system software version 1.x is obsolete; it is supported in version 2.0, but support is not guaranteed in future releases. Use the new PopupMenu function instead.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-1 Button ■ After button is tapped, it is highlighted and picker is shown to the right of it. The protoPopInPlace picker is a text button that displays a picker when tapped. When the user chooses an item from the picker, the text of the chosen item appears in the button. For information about the slots and methods for this picker, see “protoPopInPlace” (page 5-6) in Newton Programmer’s Reference.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Programmer’s Reference. Figure 6-4 shows the types of objects you can display in a protoPicker. Figure 6-4 A protoPicker example Simple string Thin separator line Twodimensional grid Thick separator line Icon with string Bitmap ■ The protoGeneralPopup is a pop-up view that has a close box. The view cancels if the user taps outside it. This can use this proto to construct more complex pickers.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoTextList picker is a scrollable list of items. The user can scroll the list by dragging or scrolling with the optional scroll arrows and can choose one or more items in the list by tapping them. The scrollable list can include shapes or text. For information about the slots and methods for this picker, see “protoTextList” (page 5-20) in Newton Programmer’s Reference. Figure 6-6 shows an example of a protoTextList.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews The protoGeneralPopup sends a pickCancelledScript to the callbackContext specified in the New method. However, it does not send a pickActionScript back; instead, it sends an Affirmative message to itself. You supply the method and decide what call to make to the context and what information to send back. To put other objects in the protoGeneralPopup, just drag them out in NTK.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-8 ■ The protoProvincePicker displays a map of North America. When the user taps a province, the PickWorld message is sent to your view. For information about the slots and methods for this picker, see “protoProvincePicker” (page 5-31) in Newton Programmer’s Reference. Figure 6-9 shows an example of a protoProvincePicker. Figure 6-9 ■ A protoProvincePicker example The protoStatePicker displays a map of North America.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews the slots and methods for this picker, see “protoWorldPicker” (page 5-34) in Newton Programmer’s Reference. Figure 6-11 shows an example of a protoWorldPicker. Figure 6-11 A protoWorldPicker example Text Pickers 6 Text picker protos allow the user to specify various kinds of information by picking text representations. Each of these protos displays a label picker with a string that shows the currently selected data value.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoDateTextPicker is a label picker with a text representation of a date. When the user taps the picker, a protoDatePopup is displayed, which allows the user to specify a different date. For information about the slots and methods for this picker, see “protoDateTextPicker” (page 5-37) in Newton Programmer’s Reference. Figure 6-13 shows an example of a protoDateTextPicker.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-14 A protoDateDurationTextPicker example Before tap 6-12 After tap ■ The protoRepeatDateDurationTextPicker is a label picker with a text representation of a range of dates. When the user taps the picker, a protoDateIntervalPopup is displayed, which allows the user to specify a different range.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-15 A protoDateNTimeTextPicker example Before tap After tap ■ The protoTimeTextPicker is a label picker with a text representation of a time. When the user taps the picker, a protoTimePopup is displayed, which allows the user to specify a different time. For information about the slots and methods for this picker, see “A protoTimeTextPicker example” (page 6-13) in Newton Programmer’s Reference.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-17 A protoDurationTextPicker example Before tap After tap ■ The protoTimeDeltaTextPicker is a label picker with a text representation of a time delta. When the user taps the picker, a protoTimeDeltaPopup is displayed, which allows the user to specify a different time delta. For information about the slots and methods for this picker, see “protoTimeDeltaTextPicker” (page 5-53) in Newton Programmer’s Reference.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-19 A protoMapTextPicker example Before tap After tap ■ The protoCountryTextPicker is the same as protoMapTextPicker. ■ The protoUSstatesTextPicker is a label picker with a text representation of a U.S. state. When the user taps the picker, a popup displays that allows the user to select a new state from an alphabetical list.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoCitiesTextPicker is a label picker with a text representation of a city. When the user taps the picker, a popup displays that allows the user to select a new city from an alphabetical list. For information about the slots and methods for this picker, see “protoCitiesTextPicker” (page 5-58) in Newton Programmer’s Reference. Figure 6-21 shows an example of a protoCitiesTextPicker.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Date, Time, and Location Pop-up Views 6 You can use the protos described in this section to present pop-up views to the user for setting or choosing specific types of values. The Newton System Software provides the following pop-up protos for date, time, and location values: ■ The protoDatePopup allows the user to choose a single date.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoDateNTimePopup allows the user to choose a single date and time. For information about the slots and methods for this proto, see “protoDateNTimePopup” (page 5-67) in Newton Programmer’s Reference. Figure 6-25 shows an example of a protoDateNTimePopup. Figure 6-25 ■ The protoDateIntervalPopup allows the user to choose an interval of dates by specifying the start and stop dates.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoMultiDatePopup allows the user to specify a range of dates. For information about the slots and methods for this proto, see “protoMultiDatePopup” (page 5-72) in Newton Programmer’s Reference. Figure 6-27 shows an example of a protoMultiDatePopup. Figure 6-27 ■ The protoYearPopup allows the user to choose a year. For information about the slots and methods for this proto, see “protoYearPopup” (page 5-73) in Newton Programmer’s Reference.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The protoAnalogTimePopup allows the user to choose a time with an analog clock. For information about the slots and methods for this proto, see “protoAnalogTimePopup” (page 5-76) in Newton Programmer’s Reference. Figure 6-30 shows an example of a protoAnalogTimePopup. Figure 6-30 ■ The protoTimeDeltaPopup allows the user to choose a time period (a delta).
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Number Pickers 6 This section describes the protos available to allow users to pick numbers. The Newton system software provides the following protos for picking numbers: ■ The protoNumberPicker displays a picker from which the user can select a number. For information about the slots and methods for this picker, see “protoNumberPicker” (page 5-81) in Newton Programmer’s Reference. Figure 6-33 shows an example of a protoNumberPicker.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Overview Protos 6 You can use the protos described in this section to create overviews of data. An overview allows the user to see all of data in a soup or an array scrolling list. The user can select individual items and open them to see the detail. Overview protos include: ■ The protoOverview provides a framework for displaying an overview of the data in your application.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-36 ■ A protoSoupOverview example The protoListPicker provides a scrollable list of items. Items can be from a soup, an array, or both. The user can select any number of items in the list. For information about the slots and methods for this proto, see “protoListPicker” (page 5-93) in Newton Programmer’s Reference. “Using protoListPicker” (page 6-26) has a more extensive example and discusses how to use this proto.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-37 A protoListPicker example ■ The protoPeoplePicker displays a list of names and associated information from the Names application. For information about the slots and methods for this proto, see “protoPeoplePicker” (page 5-110) in Newton Programmer’s Reference. ■ The protoPeoplePopup is similar to the protoPeoplePicker, except that protoPeoplePopup displays the picker in a pop-up view.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews You also need to define the following slot in your protoOverview: cursor This should be a cursor-like object. You use the object stored in this slot to encapsulate your data. The cursor-like object must support the methods Entry, Next, Move, and Clone. An example is given below. In addition, you must provide a mechanism to find an actual data item given an index of a displayed item.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ Move, which moves the “cursor” a given number of entries and returns that entry or, if there is no item in that place, nil. ■ Clone, which returns a copy of the “cursor” that is modifiable independent of the original “cursor.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-39 Creating a new name entry When the pen comes down in any column, the row/column cell inverts as shown in Figure 6-40. Figure 6-40 Highlighted row When the pen is released, if it is within the first column, the item is either checked to show that it is selected or unchecked to show that it is not. See Figure 6-41.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews pop-up view is displayed to allow the user to select any option or enter a new one. See Figure 6-42. Figure 6-42 Pop-up view displayed over list If the user selects “Add new price” (or if there were one or no options already available to them), the user can enter a new price as shown in Figure 6-43. Figure 6-43 Slip displayed for gathering input The proto is driven by a frame contained in the pickerDef slot.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews The picker definition (described in the next section) is a data definition frame that is provides the routines to create a name reference from an entry, an entry alias, another name reference, a straight frame, or just to create a canonical empty name reference (if no data is provided). It also retrieves the data from a name reference. Finally, it provides some information about the name reference to support actions like tapping and highlighting.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews See “Column Specifications” (page 5-3) in Newton Programmer’s Reference for details of the slots. Having a Single Selection in a List Picker 6 The key to getting single selection is that single selection is part of the picker definition and not an option of protoListPicker. That means the particular class of nameRef you use must include single selection. In general, this requires creating your own subclass of the particular name reference class.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Validation and Editing in protoListPicker 6 The built-in validation mechanism is not designed to deal with nested soup information. In general, you gain more flexibility by not using a validationFrame in your pickerDef, even if you have no nested entries.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews // NOTE: returns the edit slip that is opened GetLayout("editor.t"):new(tapInfo.nameRef, tapInfo.editPaths, why, self, 'EditDone, context); else begin // the item is valid, so just toggle the selection context:Tapped('toggle); nil; // Return . end;.. end; The example above assumes that the base view of the layout editor.t has a New method that opens the editor and returns the associated view. The editor can be designed to fit your data.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Changing the Font of protoListPicker 6 The mechanism described here will probably change in the future. Eventually you may be able to set a viewFont slot in the list picker itself, just as you can set viewLineSpacing now. In the meantime, you need a piece of workaround code. You must set the viewFont of the list picker and also include this workaround code.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews if x > selectIndent then begin // get a temporary cursor based on the cursor used // by soup overview local tCursor := cursor:Clone(); // move it to the selected item tCursor:Move(itemIndex) ; // move the application’s detail cursor to the // selected entry myBaseApp.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Roll Protos 6 You can use the protos described in this section to present roll views in your applications. A roll view is one that contains several discrete subviews that are arranged vertically. The roll can be viewed in overview mode, in which each subview is represented by a one-line description. Any or all of the subviews can be expanded to full size. The individual subviews are contained in objects based on protoRollItem.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Figure 6-45 A protoRollBrowser example Collapsed View Expanded View View Classes 6 There are two view classes that you use for pickers: ■ The clOutline view class displays an expandable text outline. Figure 6-46 shows an example.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews ■ The clMonthView view class displays a monthly calendar. Figure 6-47 shows an example. Figure 6-47 Example of a month view Selected day Current day Specifying the List of Items for a Popup 6 You specify the item list for protoPicker, protoTextList, protoPopUpButton, proptoPopupInPlace, and PopUpMenu in an array. In the simplest case, this is an array of strings, but it can contain different kinds of items: simple string A string.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Table 6-1 Item frame for strings and bitmaps Slot name Description item The item string or bitmap reference. pickable A flag that determines whether the item is pickable. Specify non-nil if you want the item to be pickable, or nil if you don’t want the item pickable. Not-pickable items appear in the list but are not highlighted and can’t be selected. mark A character displayed next to an item when it’s chosen.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Table 6-2 Item frame for string with icon (continued) Slot name Description indent An integer that defines a text indent to use for this item and subsequent icon/string items. This integer specifies the number of pixels to indent the text from the left side of the picker view. You can use it to line up a number of text items that may have icons of varying width. Specify –1 to cancel the indent effect for the current and subsequent text items.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Table 6-3 Item frame for two-dimensional grid (continued) Slot Name Description cellFrame Optional. The width of the separator line between cells, used for highlighting purposes. If you don’t specify this slot, the default is 1 pixel. outerFrame Optional. The width of the border line around the cells, used for highlighting purposes. If you don’t specify this slot, the default is 2 pixels. mask Optional.
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Summary 6 The following sections summarize the reference information in this chapter. General Picker Protos 6 protoPopupButton 6 aProtoPopupButton := _proto: viewFlags: viewBounds: viewJustify: text: popup: ButtonClickScript: PickActionScript: PickCancelledScript: ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews iconSetup: icon frame, labelCommands: array, // items in list iconBounds: boundsFrame, // bounds of largest icon iconIndent: integer, // indent of text from icon checkCurrentItem: Boolean, // true to check selected item indent: integer, // indent of picker from label textIndent: integer, // indent of text LabelActionScript:function, // returns selected item TextSetup: function, // gets initial item TextChanged: function, // called upon item value chang
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoGeneralPopup 6 aProtoGeneralPopup := { _proto: protoGeneralPopup, viewBounds: boundsFrame, viewFlags: constant, cancelled: Boolean, // true if user cancelled // pop-up view context: view, // view with pick scripts New: // open pop-up view Affirmative: function, // user taps pop-up view PickCancelledScript:function, // called in pop-up view // cancelled ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews formatFlags, frame, // // scrollAmount: integer, // currentSelection: string, // selectedCells: array, // declareSelf: symbol, // ViewSetupFormScript: function, // SelectThisCell: function, // selected ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Map Pickers 6 protoCountryPicker 6 aProtoCountryPicker := { _proto: protoCountryPicker, viewBounds: boundsFrame, autoClose: Boolean, // true to close picker on selection listLimit: integer, // maximum items listed PickWorld: function, // called when selection is made ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Text Picker Protos 6 protoTextPicker 6 aProtoTextPicker := { _proto: protoTextPicker, label: string, // picker label indent: integer, // indent labelFont: fontSpec, // font for label entryFont: fontSpec, // font for picker line Popit: function, // user tapped picker PickActionScript: function, // returns selected item PickCancelledScript: function, // user cancelled picker TextSetup: function, // returns text string ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews PickActionScript: function, PickCancelledScript: function, ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews time: format: increment: integer, symbol, integer, PickActionScript: function, PickCancelledScript: function, ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoMapTextPicker 6 aProtoMapTextPicker := { _proto: protoMapTextPicker, label: string, // picker label labelFont: fontSpec, // label display font entryFont: fontSpec, // picked entry font indent: integer, // amount to indent text params: frame, PickActionScript: function, // returns selected item PickCancelledScript: function, // user cancelled picker ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoCitiesTextPicker 6 aProtoCitiesTextPicker := { _proto: protoCitiesTextPicker, label: string, // picker label labelFont: fontSpec, // label display font entryFont: fontSpec, // picked entry font indent: integer, // amount to indent text params: frame, PickActionScript: function, // returns selected item PickCancelledScript: function, // user cancelled picker ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoDatePicker 6 aProtoDatePicker := { _proto: protoDatePicker, selectedDates: array, // selected date DateChanged: function, // called when date is selected Refresh: function, // update view with new dates ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoYearPopup protoYearPopup := { _proto: protoYearPopup, New: function, // NewYear: function, // DoneYear: function, // PickCancelledScript: function, // ... } 6 creates pop-up view called when year changes called on close box tap user cancelled picker protoTimePopup protoTimePopup := { _proto: protoTimePopup, New: function, // NewTime: function, // PickActionScript: function, // PickCancelledScript: function, // ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoTimeIntervalPopup 6 protoTimeIntervalPopup := { _proto: protoTimeIntervalPopup, New: function, // creates pop-up view PickActionScript: function, // returns selected item PickCancelledScript: function, // user cancelled picker ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Overview Protos 6 protoOverview 6 aProtoOverview := _proto: viewBounds : viewFlags : viewFont : lineHeight: selectIndent: nothingCheckable: SelectItem: SetupAbstracts: Abstract: HitItem: IsSelected: { protoOverview, boundsFrame, constant, fontSpec, integer, // height of items in pixels integer, // specifies left margin Boolean, // true for no checkboxes function, // to record selected items function, // set up entry function, // return shape given
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoListPicker 6 aProtoListPicker := { _proto: protoListPicker, declareSelf : symbol, // Set to 'pickBase defaultJustification :constant, viewFlags : constant, viewBounds : boundsFrame, lineHeight: integer, // height of items in pixels listFormat: formatFlags, pickerDef: frame, // defines list behavior selected: array, // references to selected items soupToQuery: string, // union soup to query querySpec: frame, // query to use selected: array, // mo
C H A P T E R 6 Pickers, Pop-up Views, and Overviews protoNameRefDataDef 6 aProtoNameRefDataDef := { _proto: protoNameRefDataDef, name: string, // name to identify picker in // top left corner class: symbol, // specify class for new name // references entryType: symbol, // class for new soup entries columns: array, // column specifications singleSelect: Boolean, // single selection if non-nil soupToQuery: string, // union soup to query querySpec: frame, // query to use validationFrame:frame, // checks
C H A P T E R 6 Pickers, Pop-up Views, and Overviews Validate: function, // // ModifyEntryPath: function, // GetRoutingInfo: function, // GetItemRoutingFrame:function, // GetRoutingTitle: function, // PrepareForRouting:function, // ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews allCollapsed: index: Boolean, integer, declareSelf: ...
C H A P T E R 6 Pickers, Pop-up Views, and Overviews browsers: array, // frame with array of outline // items viewFont: fontSpec, viewFlags : constant, viewFormat: formatFlags, clickSound: frame, // sound frame for taps OutlineClickScript:function, //called when user taps item ... } clMonthView 6 theMonth := {... viewclass: clMonthView, viewBounds: boundsFrame, viewflags: constant, labelFont: fontSpec, dateFont: fontSpec, selectedDates: array, viewSetupFormScript: function, ...
C H A P T E R Figure 7-0 Table 7-0 7 Controls and Other Protos 7 Controls are software objects that provide various user interface capabilities, including scrolling, selection buttons, and sliders. You use the controls and other protos described in this chapter to add these features to your NewtonScript applications. This chapter gives a general description of the controls and related protos provided in Newton System Software.
C H A P T E R 7 Controls and Other Protos ■ four new date and time protos: protoDigitalClock, protoSetClock, protoNewSetClock, and protoAMPMCluster ■ two special view protos: protoDragger and protoDragNGo Scroller Protos 7 Scrollers allow the user to move vertically or horizontally through a display that is bigger than the view. The Newton System Software provides a number of scrollers to allow users to scroll their views.
C H A P T E R 7 Controls and Other Protos ■ The protoUpDownScroller is centered on the right side of a view and provides vertical scroll arrows. For more information about the slots and methods for this scroller, see “protoUpDownScroller” (page 6-5) in Newton Programmer’s Reference. Figure 7-3 shows an example of a protoHorizontal2DScroller view. Figure 7-3 ■ A protoUpDownScroller view The protoHorizontalUpDownScroller is centered at the bottom of a view and provides vertical scroll arrows.
C H A P T E R 7 Controls and Other Protos viewRect, and dataRect. Each of these slots is a bounds frame with the following form: {left: 0, top: 0, right: 10, bottom: 10} You usually create these bounds frame slots with the utility function SetBounds, which is described in “SetBounds” (page 2-34) in Newton Programmer’s Reference.
C H A P T E R 7 Controls and Other Protos Scrolling in the Dates Application 7 Scrolling in the Dates application allows the user to see the 24 hours in a day, 7 hours at a time. When there is only interesting data in a certain range of the day, the application sets the dataRect for that time frame. This tells the scroller to blacken a scroll arrow when the data time frame is not displayed in the viewRect, providing additional visual feedback to the user.
C H A P T E R 7 Controls and Other Protos Keep in mind that if you set scrollAmounts to values other than the default, your method must check the value passed to it and scroll that amount. Note In general, you should discourage double-tapping, since inadvertently tapping twice can cause a double-tap action to occur. ◆ Advanced Usage 7 If you want more control over the arrow feedback, don’t use the scrollRect, viewRect, or dataRect slots at all; instead, use the SetArrow and GetArrow methods.
C H A P T E R 7 Controls and Other Protos ■ The protoPictureButton creates a picture that is a button. For more information about the slots and methods for this button, see “protoPictureButton” (page 6-9) in Newton Programmer’s Reference. Figure 7-6 shows an example of a protoPictureButton view. Figure 7-6 A protoPictureButton view Picture Buttons ■ The protoInfoButton includes an information button in a view. When the user taps this button, a picker containing information items appears.
C H A P T E R 7 Controls and Other Protos ■ The protoRadioButton creates a radio button child view of a radio button cluster (based on protoRadioCluster). Each radio button is a small oval bitmap that is labeled with text. For more information about the slots and methods for this button, see “protoPictRadioButton” (page 6-18) in Newton Programmer’s Reference. Figure 7-9 shows an example of several radio buttons in a cluster.
C H A P T E R 7 Controls and Other Protos ■ The protoLargeCloseBox creates a picture button with an “X” icon that is used to close the view. For more information about the slots and methods for this box, see “protoLargeCloseBox” (page 6-22) in Newton Programmer’s Reference. Figure 7-12 shows an example of a protoLargeCloseBox view. Figure 7-12 A protoLargeCloseBox view Large Close Box Note See Newton 2.
C H A P T E R 7 Controls and Other Protos Implementing a Simple Button 7 To provide a simple button in your application, pick a button proto to use, set the appropriate slots in the button object, and (in most cases) define one or more scripts for the button. The following is an example of a template that includes protoTextButton: aButton := {...
C H A P T E R 7 Controls and Other Protos Selection Tab Protos 7 You can use the protos described in this section to display alphabetic selection tabs on the screen. There are two tab protos that you can use: ■ The protoAZTabs displays alphabetical tabs arranged horizontally in a view. For more information about the slots and methods for this proto, see “protoAZTabs” (page 6-28) in Newton Programmer’s Reference. Figure 7-15 shows an example of a protoAZTabs view.
C H A P T E R 7 Controls and Other Protos Gauge and Slider Protos 7 You can use the gauge and slider protos described in this section to display gauges. Each slider presents a gauge view that indicates the current progress in relation to the entire operation. There are three protos and one view class available for defining sliders: ■ The protoSlider creates a user-settable gauge view, which looks like an analog bar gauge with a draggable diamond-shaped knob.
C H A P T E R 7 Controls and Other Protos ■ The clGaugeView class is used to display objects that look like analog bar gauges. Although the clGaugeView class is available, you should use the protoGauge to display bar gauges. purpose as is the protoGauge proto. For more information about the slots and methods for the protoGauge proto, see “protoGauge” (page 6-35) in Newton Programmer’s Reference.
C H A P T E R 7 Controls and Other Protos ChangedSlider: func() begin SetVolume(viewValue); :SysBeep(); end, ...} The example above initializes the slider gauge to indicate the current system volume, which it retrieves from the user configuration that is maintained by the Newton System Software. The range of allowable volume values is from 0 (the default for minValue) to 4. Whenever the user moves the slider and lifts the pen, the viewValue slot is updated and the ChangedSlider method is called.
C H A P T E R 7 Controls and Other Protos Figure 7-22 A protoNewSetClock view ■ The protoSetClock time proto also displays an analog clock with which the user can set a time value. Although this proto is still available for use, it has been updated to the protoNewSetClock, which you should use instead. ■ The protoAMPMCluster time proto displays A.M. and P.M. radio buttons in a protoNewSetClock view.
C H A P T E R 7 Controls and Other Protos // initialize with current time ViewSetupFormScript: func() begin time := time(); end, ...}; Special View Protos 7 You can use the protos described in this section to provide special-purpose views in your applications. There are seven special view protos: ■ The protoDragger creates a view that can be dragged around the screen with the pen.
C H A P T E R 7 Controls and Other Protos ■ The protoDrawer creates a view that looks and acts like the base view of the Extras Drawer. For more information about the slots and methods for this proto, see “protoDrawer” (page 6-49) in Newton Programmer’s Reference. ■ The protoFloater creates a draggable view that is horizontally centered within its parent view and floats above all other nonfloating sibling views within an application.
C H A P T E R 7 Controls and Other Protos View Appearance Protos 7 You can use the protos described in this section to add to the appearance of your views in certain ways. There are three view appearance protos: ■ The protoBorder is a view filled with black. You can use this proto as a border, a line, or a black rectangle. For more information about the slots and methods for this proto, see “protoBorder” (page 6-56) in Newton Programmer’s Reference. Figure 7-28 shows an example of a protoBorder view.
C H A P T E R 7 Controls and Other Protos Status Bar Protos 7 You can use the protos described in this section to display a status bar at the bottom of a view. There are two status bar protos: ■ The protoStatus creates a status bar, which includes a close button and an analog clock, at the bottom of a view. For more information about the slots and methods for this proto, see “protoStatus” (page 6-59) in Newton Programmer’s Reference. Figure 7-31 shows an example of a protoStatus view.
C H A P T E R 7 Controls and Other Protos Summary 7 Scroller Protos 7 protoLeftRightScroller 7 aProtoLeftRightScroller := { _proto: protoLeftRightScroller, scrollView: viewTemplate, scrollRect: boundsFrame, // extent of scrollable area dataRect: boundsFrame, // extent of data in the view viewRect: boundsFrame, // extent of visible area xPos: integer, // initial x-coord in scrollRect yPos: integer, // initial y-coord in scrollRect scrollAmounts: array, // line, page, dbl-click values pageThreshhold:i
C H A P T E R 7 Controls and Other Protos protoHorizontal2DScroller 7 aProtoHorizontal2DScroller := { _proto: protoHorizontal2DScroller, scrollView: viewTemplate, scrollRect: boundsFrame,// extent of scrollable area dataRect: boundsFrame,// extent of data in the view viewRect: boundsFrame,// extent of visible area xPos: integer, // initial x-coord in scrollRect yPos: integer, // initial y-coord in scrollRect scrollAmounts: array, // line, page, dbl-click values pageThreshhold:integer, // lines before p
C H A P T E R 7 Controls and Other Protos Button and Box Protos 7 protoTextButton 7 aProtoTextButton := { _proto: protoTextButton, viewBounds: boundsFrame, viewFlags: integer, // viewFlags constants text: string, // text inside the button viewFont: fontFlags, viewFormat: formatFlags, viewJustify: justificationFlags, viewTransferMode: integer, // view transfer constants ButtonClickScript: function, // when button is tapped ButtonPressedScript: function, // while button is pressed ...
C H A P T E R 7 Controls and Other Protos protoOrientation 7 aProtoOrientation := { _proto: protoOrientation, viewFlags: integer, // viewFlags constants viewBounds: boundsFrame, viewJustify: justificationFlags, ... } protoRadioCluster aProtoRadioCluster := { _proto: protoRadioCluster, viewBounds: boundsFrame, clusterValue: integer, // InitClusterValue: function, // ViewSetupFormScript: function, // ClusterChanged: function, // SetClusterValue: function, // ...
C H A P T E R 7 Controls and Other Protos viewValue: integer, ViewDrawScript:function, ... } // current value of radio button // to highlight button protoCloseBox 7 aProtoCloseBox := { _proto: protoCloseBox, viewFlags: integer, // viewFlags constants viewBounds: boundsFrame, viewJustify: justificationFlags, viewFormat: formatFlags, ButtonClickScript:function, // called before closing ...
C H A P T E R 7 Controls and Other Protos protoRCheckbox aProtoRCheckbox := { _proto: protoRCheckbox, viewBounds: boundsFrame, viewFormat: formatFlags, viewFont: fontFlags, // text: string, // indent: integer, // buttonValue: value, // viewValue: value, // ValueChanged: function, // ToggleCheck: function, // ...
C H A P T E R 7 Controls and Other Protos viewValue: minValue: maxValue: ViewSetupFormScript: ChangedSlider: TrackSlider: ... } integer, integer, integer, function, function, function, // // // // // // gauge value minimum gauge value maximum gauge value set initial gauge value slider moved viewValue changed protoGauge aProtoGauge := { _proto: protoGauge, viewBounds: viewValue: minValue: maxValue: gaugeDrawLimits: ViewSetupFormScript: ...
C H A P T E R 7 Controls and Other Protos Time Protos 7 protoDigitalClock 7 aProtoDigitalClock := { _proto: protoDigitalClock, viewFlags: integer, // viewFlags constants viewBounds: boundsFrame, viewJustify: justificationFlags, increment: integer, // minutes to change on tap time: integer, // initial or current time wrapping: Boolean, // non-nil to wrap around day // boundaries midnite: Boolean, // non-nil if 0 means midnight // tomorrow Refresh: function, // update clock TimeChanged: function, // ca
C H A P T E R 7 Controls and Other Protos Refresh: TimeChanged: ... } function, function, // update clock // called when time is changed protoAMPMCluster 7 aProtoAMPMCluster := { _proto: protoAMPMCluster, viewBounds: boundsFrame, viewJustify: justificationFlags, time: integer, // specify time--required ...
C H A P T E R 7 Controls and Other Protos protoDrawer 7 aProtoDrawer := { _proto: protoDrawer, viewFlags: integer, // viewFlags constants viewBounds: boundsFrame, viewFormat: formatFlags, viewEffect: effectFlags, showSound: soundFrame,// sound when drawer opens hideSound: soundFrame,// sound when drawer closes ...
C H A P T E R 7 Controls and Other Protos protoGlance aProtoGlance := { _proto: protoGlance, viewBounds: viewJustify: viewFormat: viewFont: viewEffect: viewIdleFrequency: text: ...
C H A P T E R 7 Controls and Other Protos protoDivider 7 aProtoDivider:= { _proto: protoDivider, viewBounds: boundsFrame, viewFlags: integer, // viewFlags constants viewFont: fontFlags, // font for text viewJustify: justificationFlags, viewFormat: formatFlags, title: string, // text on divider bar titleHeight: integer, // height of divider ...
C H A P T E R Figure 8-0 Table 8-0 8 Text and Ink Input and Display 8 This chapter describes how the Newton system handles text and presents interfaces you can use to work with text in NewtonScript applications.
C H A P T E R 8 Text and Ink Input and Display When the user writes a line of text on the Newton screen, the Newton system software performs a series of operations, as follows: ■ The raw data for the input is captured as ink, which is also known as sketch ink or raw ink. ■ Raw ink is stored as a sequence of strokes or stroke data.
C H A P T E R 8 Text and Ink Input and Display Caret Insertion Writing Mode 8 Caret insertion writing mode is a text input mode that the user can enable or disable. When caret insertion mode is disabled, handwritten text is inserted into the view at the location where it is written. When caret insertion writing mode is enabled, handwritten text is inserted at the location indicated by the insertion caret, regardless of where on the screen it is drawn.
C H A P T E R 8 Text and Ink Input and Display The views and protos that you use for text are listed in Table 8-1. Table 8-1 Views and protos for text input and display View or Proto Description edit view Use the clEditView class for basic text input and display. Objects of this class can display and/or accept text and graphic data. The clEditView automatically creates child clParagraphView views for text input and display and clPolygonView views for graphic input and display.
C H A P T E R 8 Text and Ink Input and Display ■ Use one of the keyboard protos to create keyboard views in your applications. These protos include the protoKeyboard, which creates a keyboard view that floats above all other views. The keyboard protos are also described in “Keyboard Views.” The Keyboard Registry 8 You need to register any custom keyboards or keypads that you create with the Newton system’s keyboard registry.
C H A P T E R 8 Text and Ink Input and Display Compatibility 8 One of the significant advances in software functionality in the Newton 2.0 system is the capacity to process ink in most views, which includes deferred recognition and the ability to mix text and ink together in rich string. This expands the behavior provided by Newton 1.x machines, which generally process written input immediately for recognition and display the resulting word in a typeface.
C H A P T E R 8 Text and Ink Input and Display instead, they have child views that contain the individual data items. Text items are contained in child views of the class clParagraphView and graphics are contained in child views of the class clPolygonView. A view of the clEditView class includes the following features: ■ Automatic creation of clParagraphView or clPolygonView children as the user writes or draws in the view. These child views hold the data the user writes.
C H A P T E R 8 Text and Ink Input and Display Here is an example of a template defining a view of the clEditView class: editor := {... viewClass: clEditView, viewBounds: {left:0, top:0, right:200, bottom:200}, viewFlags: vVisible+vAnythingAllowed, viewFormat: vfFillWhite+vfFrameBlack+vfPen(1)+ vfLinesLtGray, viewLineSpacing: 20, // methods and other view-specific slots viewSetupFormScript: func()... ...
C H A P T E R 8 Text and Ink Input and Display Defining a Line Pattern 8 You can define a custom line pattern for drawing the horizontal lines in a paragraph view. A line pattern is an eight-byte binary data structure with the class 'pattern. To create a binary pattern data structure on the fly, use the following NewtonScript trick: myPattern := SetClass( Clone("\uAAAAAAAAAAAAAAAA"), 'pattern ); This code clones a string, which is already a binary object, and changes its class to 'pattern.
C H A P T E R 8 Text and Ink Input and Display IMPORTANT You store view templates (not view objects) in the viewChildren array of an edit view. ▲ Paragraph Views The clParagraphView class displays text or accepts text input. It includes the following features: ■ Text recognition ■ Text correction ■ Text editing, including scrubbing, selection, copying to the clipboard, pasting from the clipboard, and other gestures, including duplicating, as controlled by the setting of the viewFlags slot.
C H A P T E R 8 Text and Ink Input and Display // 8 chars of one font, 3 chars of another, 5 chars // of another styles: [8, 18434, 3, 12290, 5, 1060865], ...} Paragraph views are normally lined to convey to the user that the view accepts text input. To add the lined paper effect to paragraph views, see “Creating the Lined Paper Effect in a Text View” (page 8-8).
C H A P T E R 8 Text and Ink Input and Display Once a lightweight paragraph view has been instantiated, you cannot dynamically change the view flags to make it an editable view, or add multistyled text by providing a styles slot, since this type of view object doesn’t support these features. If you need this functionality for an existing lightweight paragraph view, you’ll have to copy the text out of it into an editable paragraph view.
C H A P T E R 8 Text and Ink Input and Display The slots of protoRichInputLine are described in “protoRichInputLine” (page 7-19) in Newton Programmer’s Reference. protoLabelInputLine 8 This proto defines a view that features a label, accepts any kind of input, and is left-justified. The protoLabelInputLine can optionally include a picker. When the protoLabelInputLine does include a picker, the user selects a choice from the picker.
C H A P T E R 8 Text and Ink Input and Display IMPORTANT You can programmatically access the value of the text slot for the protoLabelInputLine with the expression entryLine.text. If you update the text slot programmatically, you need to call the SetValue function to ensure that the view is updated. Below is an example: SetValue(entryLine, 'text, "new text")] ▲ The following is an example of a template using protoLabelInputLine: labelLine := {...
C H A P T E R 8 Text and Ink Input and Display Recognition menu. The view configuration is defined by the view flags and the (optional) recognition configuration (recConfig) frame of the view. The Recognition menu is shown in Figure 8-3. Figure 8-3 The Recognition menu When the viewFlags input flags and the recConfig frame of the view are set to accept both text and ink, the Recognition menu choices control what kind of data is inserted into the paragraph view.
C H A P T E R 8 Text and Ink Input and Display Note The view flags are described in “Views” (page 3-1). The recognition view flags are described in “Recognition” (page 9-1). ◆ Although raw ink is intended mostly for drawing, the user can still write with raw ink by choosing “Sketches” from the Recognition menu. The recognizer automatically segments raw ink into ink words. The raw ink can subsequently be recognized, using deferred recognition.
C H A P T E R 8 Text and Ink Input and Display You can modify the size at which ink words are displayed in two ways: by changing the scaling percentage or the font size. For example, suppose that you draw an ink word and the system calculates its font size, as written, at 36 point. If your ink text scaling is set to 50 percent, the ink word is displayed at half of the written size, which makes its font size 18 point.
C H A P T E R 8 Text and Ink Input and Display The constants you can use in font specifications are shown in “Font Constants for Packed Font Integer Specifications” (page 7-4) in Newton Programmer’s Reference. The Font Frame 8 A font frame has the following format: {family: familyName, face: faceNumber, size: pointSize} For familyName, you can specify a symbol corresponding to one of the available built-in fonts, which are shown in Table 8-3.
C H A P T E R 8 Text and Ink Input and Display Note Apple recommending using the normal, bold, and underline font styles. The other styles do not necessarily display well on Newton screens. ◆ For pointSize, use an integer that specifies the point size value. The Packed Integer Font Specification 8 You can specify a font in one 30-bit integer. A packed integer font specification uses the lower 10 bits for the font family, the middle 10 bits for the font size, and the upper 10 bits for the font style.
C H A P T E R 8 Text and Ink Input and Display Table 8-5 Built-in font constants (continued) Constant Font frame Integer value ROM_fontsystem12underline {family:'espy, face:4, size:12} 4206592 ROM_fontsystem14 {family:'espy, face:0, size:14} 14336 ROM_fontsystem14bold {family:'espy, face:1, size:14} 1062912 ROM_fontsystem14underline {family:'espy, face:4, size:14} 4208640 ROM_fontsystem18 {family:'espy, face:0, size:18} 18432 ROM_fontsystem18bold {family:'espy, face:1, size:18} 10670
C H A P T E R 8 Text and Ink Input and Display Table 8-5 Built-in font constants (continued) Constant Font frame Integer value editFont10 {family:'handwriting, face:0, size:10} 10243 editFont12 {family:'handwriting, face:0, size:12} 12291 editFont18 {family:'handwriting, face:0, size:18} 18435 The integers in Table 8-5 are derived by packing font family, face, and size information into a single integer value. Each NewtonScript integer is 30 bits in length.
C H A P T E R 8 Text and Ink Input and Display Table 8-6 Font packing constants (continued) Constant Value Description tsItalic 2097152 Italic font tsUnderline 4194304 Underlined normal font tsOutline 8388608 Outline font tsSuperScript 134217728 Superscript font tsSubScript 268435456 Subscript font Note that the “Casual” font uses the symbol 'handwriting for its font family.
C H A P T E R 8 Text and Ink Input and Display Important Rich String Considerations 8 Although the Newton system software allows you to use rich strings anywhere that plain strings are used, there are certain considerations to be aware of when using rich strings. These include: ■ Do not use functions that are not rich-string-aware. These include the Length, SetLength, BinaryMunger, and StuffXXX functions. ■ Use the StrLen function to find the length of a string.
C H A P T E R 8 Text and Ink Input and Display view’s 'text and 'styles slots are generated and placed in the context frame of the view. When SetValue is called with a string parameter that is a rich string, it is automatically decoded into a text and style pair. The result is stored in the view frame of the paragraph view. Rich String Functions 8 You can use the rich string functions to convert and work with rich strings.
C H A P T E R 8 Text and Ink Input and Display Text and Styles 8 Within a paragraph view, text is represented in two slots: the 'text slot and the 'styles slot. The 'text slot contains the sequence of text characters in the paragraph, including an instance of the kParaInkChar placeholder character (0xF701) for each ink word. The 'styles slot specifies how each text run is displayed in the paragraph. A text run is a sequence of characters that are all displayed with the same font specification.
C H A P T E R 8 Text and Ink Input and Display Setting the Caret Insertion Point 8 When you application starts up, you might want to establish the insertion point for keyboard entry in caret insertion writing mode. There are three functions that you can use for this purpose: ■ to establish the insertion point in an input field, use the SetKeyView function, which is described in “SetKeyView” (page 7-43) in Newton Programmer’s Reference.
C H A P T E R 8 Text and Ink Input and Display To use the numeric keyboard, which is shown in Figure 8-7, use the symbol 'numericKeyboard. Figure 8-7 The built-in numeric keyboard To use the phone keyboard, which is shown in Figure 8-8, use the symbol 'phoneKeyboard. Figure 8-8 The built-in phone keyboard To use the time and date keyboard, which is shown in Figure 8-9, use the symbol 'dateKeyboard.
C H A P T E R 8 Text and Ink Input and Display If you want to open one of these keyboards programmatically, use code like the following to send it the Open message: Getroot().alphaKeyboard:Open() The keystrokes entered by the user are sent to the current key receiver view. There can be only one key receiver at a time, and only views of the classes clParagraphView and clEditView can be key receiver views.
C H A P T E R 8 Text and Ink Input and Display Figure 8-10 An example of a protoKeyboard This proto enables the caret (if it is not already visible) in the key-receiving view while the keyboard is displayed. Characters corresponding to tapped keys are inserted in the key-receiving view at the insertion bar location. The caret is disabled when the keyboard view is closed. This proto is used in conjunction with protoKeypad to implement a floating keyboard.
C H A P T E R 8 Text and Ink Input and Display protoSmallKeyboardButton 8 This proto is used to include a small keyboard button in a view. Tapping the button causes the on-screen keyboard to appear. If the keyboard is already displayed, a picker listing available keyboard types is displayed. The user can tap one to open that keyboard. Figure 8-12 shows an example of the small keyboard button.
C H A P T E R 8 Text and Ink Input and Display The Key Definitions Array 8 Each keyboard view contains a key definitions array, which determines the layout of the individual keys in the keyboard. The key definitions array is an array of rows. Each row is an array of values that looks like this: row0 := [ rowHeight, rowMaxKeyHeight, key0Legend, key0result, key0Descriptor, key1Legend, key1result, key1Descriptor, key2Legend, key2result, key2Descriptor, ...
C H A P T E R 8 Text and Ink Input and Display row1 := "4",4, "5",5, "6",6, [ keyVUnit, keyVUnit, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite ]; row2 := "7",7, "8",8, "9",9, [ keyVUnit, keyVUnit, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite, keyHUnit+keyVUnit+keyFramed+2*keyInsetUnit+keyAutoHilite ]; row3
C H A P T E R 8 Text and Ink Input and Display ■ An array. An element of the array is selected and treated as one of the above data types. The index of the array element is determined by the value of the keyArrayIndex slot (which can be changed dynamically). Note that arrays of arrays are not allowed here, but an array can include any combination of other data types. The Key Result 8 The key result is the value returned when the key is pressed.
C H A P T E R 8 Text and Ink Input and Display Figure 8-14 35 7A 78 F1 esc Keyboard codes 63 76 F2 F3 60 61 F4 F5 F6 62 64 F7 65 6D 67 6F F8 F9 F10 F11 F12 ~ 32 ! 12 @ 13 # 14 $ 15 % 17 ^ 16 & 1A 1C ( 19 ) 1D 1B + 18 caps lock 33 = delete 30 0C 0D 0E 0F 11 10 20 22 1F 23 { 21 } 1E 2A ] Q W E R T Y U I O P [ : 24 39 00 01 02 03 05 04 26 28 25 29 " 27 A S D F G H J K L ; return shift 07 08 09 0B 2D 2E 2B 2F .
C H A P T E R 8 Text and Ink Input and Display Table 8-8 Key descriptor constants (continued) keyFramed Specify the thickness of the frame around the key. Multiply this constant by the number of pixels that you want to use for the frame thickness, from 0-3. keyRoundingUnit Specify the roundedness of the frame corners. Multiply this constant by the number of pixels that you want to use for the corner radius, from 0-15, zero being square.
C H A P T E R 8 Text and Ink Input and Display Key dimensions are specified by summing a combination of horizontal and vertical key unit constants within the keyDescriptor. For example, to specify a key that is 2 3/4 units wide by 1 1/2 units high, specify these constants for keyDescriptor: keyHUnit*2 + keyHQuarter*3 + keyVUnit + keyVHalf Using the Keyboard Registry 8 If your application includes its own keyboard, you need to register it with the system keyboard registry.
C H A P T E R 8 Text and Ink Input and Display Each view path must specify the actual view that accepts the input. An example of a suitable path is shown here: 'myInputLine, 'myLabelInputLine.entryLine When the user tabs through this list, it loops from end to beginning and, with reverse-tabbing, from beginning to end. You can use the _tabParent slot to inform the system that you want tabbing in a view restricted to that view. Each view in which _tabParent is non-nil defines a tabbing context.
C H A P T E R 8 Text and Ink Input and Display ■ a view descended from protoInputLine with the vApplication flag set in the viewFlags slot The Caret Pop-up Menu 8 Normally, when the user taps the insertion caret, the system-provided Punctuation pop-up Menu opens. However, you can override this with a pop-up menu of your own creation. When the user taps the insertion caret, the system starts searching for a slot named _caretPopup.
C H A P T E R 8 Text and Ink Input and Display Summary of Text 8 Text Constants and Data Structures 8 Text Flags 8 vWidthIsParentWidth vNoSpaces vWidthGrowsWithText vFixedTextStyle vFixedInkTextSTyle vExpectingNumbers (1 (1 (1 (1 (1 (1 << << << << << << 0) 1) 2) 3) 4) 9) Font Family Constants for Use in Frames 8 'espy 'geneva 'newYork 'handwriting Font Face Constants for Use in Frames kFaceNormal kFaceBold kFaceItalic kFaceUnderline kFaceOutline kFaceSuperScript kFaceSubScript 0x000 0x001 0
C H A P T E R 8 Text and Ink Input and Display ROM_fontsystem10underline ROM_fontsystem12 ROM_fontsystem12bold ROM_fontsystem12underline ROM_fontsystem14 ROM_fontsystem14bold ROM_fontsystem14underline ROM_fontsystem18 ROM_fontsystem18bold ROM_fontsystem18underline 4204544 12288 1060864 4206592 14336 1062912 4208640 18432 1067008 4212736 simpleFont9 simpleFont10 simpleFont12 simpleFont18 9218 10242 12290 18434 fancyFont9 or userFont9 fancyFont10 or userFont10 fancyFont12 or userFont12 fancyFont18 or u
C H A P T E R 8 Text and Ink Input and Display Font Face Constants for Packed Integer Font Specifications tsPlain tsBold tsItalic tsUnderline tsOutline tsSuperScript tsSubScript 0 1048576 2097152 4194304 8388608 134217728 268435456 Keyboard Registration Constants kKbdUsesKeyCodes kKbdTracksCaret kKbdforInput 8 1 2 4 Key Descriptor Constants keySpacer keyAutoHilite keyInsetUnit keyFramed keyRoundingUnit keyLeftOpen keyTopOpen keyRightOpen keyBottomOpen keyHUnit keyHHalf keyHQuarter keyHEighth keyVUnit
C H A P T E R 8 Text and Ink Input and Display Keyboard Modifier Keys kIsSoftKeyboard kCommandModifier kShiftModifier kCapsLockModifier kOptionsModifier kControlModifier 8 (1 (1 (1 (1 (1 (1 << << << << << << 24) 25) 26) 27) 28) 29) Views 8 clEditView 8 aClEditView:= { viewBounds: viewFlags: viewFormat: viewLineSpacing: viewLinePattern: boundsFrame, constant, formatFlags, integer, integer, view:EditAddWordScript(form, bounds) NotesText(childArray) ...
C H A P T E R 8 Text and Ink Input and Display clKeyboardView aClEditView:= { _noRepeat: viewBounds: keyDefinitions: viewFlags: viewFormat: keyArrayIndex: keyHighlightKeys: keyResultsAreKeycodes: keyReceiverView: keySound: keyPressScript: ...
C H A P T E R 8 Text and Ink Input and Display text: viewFont: viewJustify: viewFormat: viewTransferMode: viewLineSpacing: viewLinePattern: memory: string, constant, constant, constant, constant, integer, binary, symbol, viewChangedScript: ...
C H A P T E R 8 Text and Ink Input and Display labelFont: labelCommands: curLabelCommand: indent: viewLineSpacing: viewLinePattern: constant, array, integer, integer, integer, binary, textSetup: updateText: textChanged: setLabelText: setLabelCommands: labelClick: labelActionScript: ... } function, function, function, function, function, function, function, // strings for list // 8-byte pattern protoKeyboard 8 aprotoKeyboard:= { _proto : protoKeyboard, saveBounds: boundsFrame, freeze: Boolean, ...
C H A P T E R 8 Text and Ink Input and Display protoKeyboardButton 8 aprotoKeyboardButton:= { _proto : protoKeyboardButton, viewFlags: constant, viewBounds: boundsFrame, viewJustify: constant, defaultKeyboard symbol, ... } protoSmallKeyboardButton 8 aprotoSmallKeyboardButton:= { _proto : protoSmallKeyboardButton, viewFlags: constant, viewBounds: boundsFrame, viewJustify: constant, current: symbol, ...
C H A P T E R 8 Text and Ink Input and Display protoPhoneKeyboard 8 aprotoPhoneKeyboard:= { _proto : protoPhoneKeyboard, viewBounds: boundsFrame, viewJustify: constant, ... } protoDateKeyboard 8 aprotoDateKeyboard:= { _proto : protoDateKeyboard, viewBounds: boundsFrame, viewJustify: constant, ... } Text and Ink Display Functions and Methods 8 This section summarizes the functions and methods you can use to work with text and ink in your applications.
C H A P T E R 8 Text and Ink Input and Display Font Attribute Functions and Methods 8 FontAscent(fontSpec) FontDescent(fontSpec) FontHeight(fontSpec) FontLeading(fontSpec) GetFontFace(fontSpec) GetFontFamilyNum(fontSpec) GetFontFamilySym(fontSpec) GetFontSize(fontSpec) MakeCompactFont(family, size, face) SetFontFace(fontSpec, newFace) SetFontFamily(fontSpec, newFamily) SetFontParms (fontSpec, whichParms) SetFontSize(fontSpec, newSize) Rich String Functions and Methods 8 DecodeRichString(richString,
C H A P T E R 8 Text and Ink Input and Display Keyboard Functions and Methods 8 This section summarizes the functions and methods that you can use to work with keyboards in your applications.
C H A P T E R 8 Text and Ink Input and Display Input Event Functions and Methods 8 This section summarizes the functions and methods that you can use to work with input events in your applications.
C H A P T E R Figure 9-0 Listing 1-0 Table 9-0 9 Recognition 9 This chapter and Chapter 10, “Recognition: Advanced Topics,” describe the use of the Newton recognition system. The recognition system accepts written input from views and returns text, ink text, graphical objects, or sketch ink to them. This chapter describes how to use view flags to enable the recognition of text, shapes and gestures in views.
C H A P T E R 9 Recognition Although no recognizers are associated with clicks and strokes, they do pass through the recognition system, allowing your view to respond to them by means of optional ViewClickScript and ViewStrokeScript methods that you supply as necessary. The ViewClickScript method of a view that accepts pen input takes application-specific action when the pen contacts or leaves the surface of the screen within the view’s boundaries.
C H A P T E R 9 Recognition Classifying Strokes 9 Recognition is an iterative process that compares raw input strokes with various system-defined models to identify the best matches for further processing. When the user writes or draws in an edit view or paragraph view that accepts user input, the system ■ notifies the view that a pen event occurred within its boundaries. ■ provides user feedback, in the form of electronic ink drawn on the screen as the pen moves across its surface.
C H A P T E R 9 Recognition multiple stroke units into meaningful groups. For example, certain letters (such as an uppercase E) might be composed of multiple strokes. The process of grouping input strokes is influenced by the user preference settings for handwriting style and letter styles. The recognizer that claimed one or more stroke units returns to the view one or more interpretations of the strokes. The gesture and shape recognizers return only one interpretation to the view.
C H A P T E R 9 Recognition Figure 9-1 Recognizers create units from input strokes Pen on tablet Stroke units ABC Recognizers Shape unit Text Shapes Word unit Ink text Gesture unit Ink 9 When the recognition system returns a shape unit to the view, the shape is displayed as the clPolygonView child view of a clEditView view. The shape unit contains a single, cleaned-up version of the original strokes.
C H A P T E R 9 Recognition Text 9 When the recognition system returns a word unit to a view based on the clParagraphView or clEditView classes, the view displays or uses the best interpretation of the original input strokes. Paragraph views display words directly; edit views create a clParagraphView child automatically to display text that the recognition system returns.
C H A P T E R 9 Recognition recognizer’s letter-by-letter option may produce different results than using the printed recognizer (which always provides letter-by-letter recognition.) Options for both recognizers are described throughout this chapter and in Chapter 10, “Recognition: Advanced Topics.” Unrecognized Strokes 9 If the input strokes are not recognized, the system encapsulates them in an object known as a stroke bundle.
C H A P T E R 9 Recognition clParagraphView view child. Ink text automatically wraps to the paragraph boundaries, just as recognized text does. Ink text is also usually reduced in size when it is drawn, according to the user preference specified by the Ink Text Scaling item in the Text Editing preferences slip. Sketch ink, on the other hand, is treated as a graphic: it is inserted into the view as a clPolygonView view child.
C H A P T E R 9 Recognition Figure 9-2 Recognition-related view flags vAddressField vNameField vCapsRequired 1 1 0 0 24 vClickable vStrokesAllowed vGesturesAllowed vAnythingAllowed 1 0 1 0 1 1 0 0 20 1 0 1 0 1 0 1 0 15 1 0 1 0 vSingleUnit 1 0 1 0 1 1 0 0 10 5 0 vNothingAllowed vCustomDictionaries vTimeField vDateField vPhoneField Reserved for system use vCharsAllowed vNumbersAllowed vLettersAllowed vPunctuationAllowed vShapesAllowed View Flags 9 The system supplies a number of cons
C H A P T E R 9 Recognition multiple bits in the input mask to produce a particular behavior. You can use a recConfig frame to set individual bits in the input mask, allowing you to control aspects of recognition behavior that view flags do not. Some features of the recognition system require the use of a recConfig frame.
C H A P T E R 9 Recognition Recognition Failure 9 Recognition may fail when the handwritten input is too sloppy for the system to make a good match against its internal handwriting model, when the view is not configured correctly for the intended input, or (in the case of dictionary-based recognition only) when none of the interpretations of the input strokes match a dictionary entry. In such cases, the recognition system may return sketch ink or ink text.
C H A P T E R 9 Recognition IMPORTANT An excessively large user dictionary can slow the system when performing searches that are not related to your application. It is therefore recommended that applications do not add items to the user dictionary at all. ▲ The system supports a total of about 1,000 items in the RAM-based user dictionary (also known as the review dictionary). Note that this number may change in future Newton devices.
C H A P T E R 9 Recognition user to make individual decisions about each word in the list, this slip does not permit selection. Although the Recently Written Words slip asks the user whether to add words to the Personal Word List, the words have already been added to both the user dictionary and the auto-add dictionary by the time they are displayed in this slip if the cursive recognizer is in use.
C H A P T E R 9 Recognition ■ the expansions of words that match entries in the expansion dictionary. ■ a graphical representation of the original input strokes as ink. ■ buttons for the soft keyboard and text-corrector views. ■ a Try Letters button when the cursive recognizer is active. Figure 9-3 Text-corrector picker The words in this list are one example of correction information stored by the system as it recognizes words.
C H A P T E R 9 Recognition This section describes only those user preferences for which the system provides a NewtonScript interface. It does not provide a comprehensive summary of the user interface to recognition, which may vary on different Newton devices. For a description of the user interface to a particular Newton device, see the user manual for that device.
C H A P T E R 9 Recognition Figure 9-4 Handwriting Recognition preferences letterSetSelection letterSpaceCursiveOption Options Button Checking the “Configure for guest user” checkbox causes the system to ■ save all current recognition system settings. ■ save the owner’s learning data. ■ temporarily reset all recognition system preferences to their default values. ■ learn the guest user’s writing style as misrecognized words are corrected if the cursive recognizer is in use.
C H A P T E R 9 Recognition can always add new words to the user dictionary programmatically, regardless of which recognizer is enabled. To display or edit the personal word list, the user taps the book icon on the soft keyboard. Figure 9-5 Text Editing Settings slip The system provides two versions of the Fine Tuning slip, one for each of the cursive and printed text recognizers, as shown in Figure 9-6.
C H A P T E R 9 Recognition Figure 9-7 Handwriting Settings slip letterInFieldsOption lettersCursiveOption learningEnabledOption When the “Learn my handwriting” checkbox is selected, the system sets the value of the learningEnabledOption slot in its user configuration data to true. When this slot holds the value true, the system modifies its internal handwriting model as the user corrects misrecognized words when the cursive recognizer is enabled.
C H A P T E R 9 Recognition displays a picker from which the user can choose recognition behaviors that you specify. When this picker is collapsed, the appearance of the button indicates the current recognition settings for the view or views that it controls. Figure 9-8 shows the appearance of typical protoRecToggle view when it is collapsed and when it is expanded to display the pick list of recognizers it can enable.
C H A P T E R 9 Recognition recognition takes place. The Entry Flags area of the NTK screen specifies the view flags for this dynamically created child view separately from the view flags for the container view in which it appears. When the system creates the child view, it copies the Entry Flags bits into the child view’s viewFlags slot. For simplicity’s sake, this chapter refers to all recognition-oriented flags as “view flags.
C H A P T E R 9 Recognition cursive letter styles in the system’s handwriting model are enabled, and the system disables unused letter styles over time as the user corrects misrecognized words. The default settings of the cursive recognizer in version 2.0 enable this recognizer’s letter-by-letter recognition option.
C H A P T E R 9 Recognition recognition behavior by setting view flags or providing a recConfig frame. Specifically, clEditView views create clParagraphView or clPolygonView child views automatically as required to display output from the recognition system. To use other kinds of views for recognition, you may need to provide viewXxxScript methods that create these child views and respond in other ways to recognition system events.
C H A P T E R 9 Recognition Obtaining Optimum Recognition Performance 9 To obtain the most accurate results from the recognition system, you must define as precisely as possible the type of input that the view is to recognize. Aside from potentially introducing errors, enabling superfluous recognizers may slow the recognition system’s performance.
C H A P T E R 9 Recognition this regard. If necessary, you can provide a ViewWordScript or ViewChangedScript method that validates the recognizer’s output; this method can be especially useful when working with the printed recognizer. Accepting Pen Input 9 When setting up any view, you must specify whether it accepts pen input at all. If you set the vNothingAllowed flag (or turn off all recognition-oriented flags), the view does not accept pen input.
C H A P T E R 9 Recognition You can solve this problem by setting the top view’s vClickable flag without providing a ViewClickScript method. (The top view need not handle the taps, only prevent them from being passed on to the other view.) Recognizing Shapes 9 The vShapesAllowed flag enables the recognition of geometric shapes such as circles, straight lines, polygons, and so on. Do not set this flag for views that handle text input only.
C H A P T E R 9 Recognition Double Taps” beginning on page 10-41. See also “ViewGestureScript” (page 8-71) in Newton Programmer’s Reference. Combining View Flags 9 Generally, you must combine multiple view flags to produce useful recognition behavior. For example, most views that accept user input set the vClickable flag to enable pen input and the vGesturesAllowed flag to enable recognition of standard gestures such scrubbing and inserting spaces.
C H A P T E R 9 Recognition When troubleshooting recognition errors, remember that view flags may enable multiple dictionaries and that the sets of dictionaries enabled by various flags may overlap. As a general rule, the fastest and most accurate recognition occurs when the fewest recognizers and dictionaries necessary to successfully analyze the input are enabled. Enabling unnecessary recognizers and dictionaries may decrease the speed and accuracy with which recognition is performed.
C H A P T E R 9 Recognition the cursive recognizer’s letter-by-letter option may be different from those returned by the printed recognizer for the same input data. Although the printed recognizer can always return non-dictionary words, it does make extensive use of the dictionaries available to the view for recognition. Users may improve the printed recognizer’s accuracy for problematic non-dictionary words by adding them to the user dictionary.
C H A P T E R 9 Recognition The vNoSpaces flag must appear in an evaluate slot named textFlags that you create in the view. The vSingleUnit flag appears in the view’s viewFlags slot, as usual. Forcing Capitalization 9 The vCapsRequired flag directs the system to capitalize the first letter of each word returned by the recognizer before displaying the text in the view.
C H A P T E R 9 Recognition or typing them. To prevent invalid input by these means, you can implement a ViewChangedScript method that validates its view’s input. Using the vAnythingAllowed Mask 9 The vAnythingAllowed mask can be used only with views based on the clEditView class. When used by itself, this mask sets all of the bits in the view’s input mask, potentially enabling all of the system-supplied recognizers and dictionaries.
C H A P T E R 9 Recognition Summary 9 Constants 9 Text Recognition View Flags 9 Constant vCharsAllowed Value Description 1 << 12 Enables default text recognizer and default dictionary set. or 0x01000 vLettersAllowed 1 << 14 Enables letter-by-letter text recognition. or 0x04000 vAddressField 1 << 21 or Enables recognizers and dictionaries suitable for the input of address data in the current locale.
C H A P T E R 9 Recognition Non-Text Recognition View Flags Constant vNothingAllowed 9 Value Description 0x00000000 The view accepts no handwritten or keyboard input. or 0x0000 vAnythingAllowed 65535 << 9 or Recognize any input. Use only for views based on the clEditView class. 0x01FFFE00 vClickable 1 << 9 or 0x0200 vStrokesAllowed 1 << 10 or 0x0400 vGesturesAllowed Accept stroke input and send the ViewStrokeScript message at the end of each stroke.
C H A P T E R 9 Recognition View Flags Enabling Lexical Dictionaries Constant vNumbersAllowed Value Description 1 << 13 Enables recognition of numbers, monetary values (for example, $12.25), decimal points, and mathematical signs (+ and –). or 0x02000 vPhoneField 1 << 18 or 0x040000 vDateField 9 1 << 19 or Enables recognition of phone numbers. Note that the set of lexical dictionaries enabled by this flag varies with the text recognizer currently in use.
C H A P T E R 9 Recognition 9-34 Slot name Notes doTextRecognition true enables text recognition unconditionally. doShapeRecognition true enables shape recognition unconditionally. doInkWordRecognition true causes text recognizer to return ink text rather than sketch ink.
C H A P T E R Figure 10-0 Listing 2-0 Table 10-0 1 0 Recognition: Advanced Topics 10 This chapter describes advanced uses of the Newton recognition system. If you are developing an application that supports ink text, implements specialized recognition system behavior, or provides unusual input views, you’ll need to understand one or more topics presented here. This chapter describes ■ the use of recConfig frames.
C H A P T E R 1 0 Recognition: Advanced Topics applications to change these system-wide settings. Instead, individual views can customize their own recognition behavior by using a recConfig frame or recToggle view to override these inherited values locally. In practice, most views’ recognition behavior is defined by a combination of inherited and overridden values.
C H A P T E R 1 0 Recognition: Advanced Topics On the other hand, if the view does not supply a recConfig frame, the recognition system builds one based on the set of view flags enabled for that view, the contents of its dictionaries slot (if present) and any recognition-related user preferences that may apply. Thus, every view that performs recognition is eventually associated with a recConfig frame that the system uses to perform setup tasks when the view is opened.
C H A P T E R 1 0 Recognition: Advanced Topics ■ values specified by an optional recConfig frame, which may override values inherited from user configuration data, override values specified by a recToggle view, or supply additional values. ProtoCharEdit Views 10 The protoCharEdit system prototype provides a comb-style entry view (or comb view) that allows the user to edit individual characters in words easily.
C H A P T E R 1 0 Recognition: Advanced Topics A formatted comb view utilizes a template you define which specifies characteristics of the view’s behavior or appearance. A comb view’s template may specify an initial value for the string that the view displays, the editing characteristics for each position in the comb view, and filters that restrict the values recognized in each of these positions.
C H A P T E R 1 0 Recognition: Advanced Topics The user can enter unrecognized ink by enabling ink text or sketch ink. In this mode, strokes appear as ink. To convert the ink to text, the user double-taps the ink word; the user can cause multiple words to be recognized by selecting them beforehand and then double-tapping the selection. The recognition system responds by inverting the ink word or selection, as shown in Figure 10-2, and returning the recognized text, which replaces the selection.
C H A P T E R 1 0 Recognition: Advanced Topics Compatibility Information 10 The ReadDomainOptions function is obsolete. It has been replaced by the ReadCursiveOptions function. The AddToUserDictionary function is obsolete. It has been replaced by the AddWord method of the review dictionary. Two new dictionary constants, kMoneyOnlyDictionary and kNumbersOnlyDictionary, provide access to new lexical dictionaries used for recognizing monetary and numeric values, respectively.
C H A P T E R 1 0 Recognition: Advanced Topics ■ using protoRecToggle views to specify recognition behavior ■ defining single-letter input areas within a view ■ accessing text correction information ■ using custom dictionaries for recognition ■ manipulating the review dictionary (includes the user dictionary, expand dictionary, and auto-add dictionary) ■ using protoCharEdit views for correcting text ■ using stroke bundles Using recConfig Frames 10 This section describes how to use a recCon
C H A P T E R 1 0 Recognition: Advanced Topics Creating a recConfig Frame 10 For any view that is to use a recConfig frame, you must supply a recConfig slot, usually by defining it in your view’s template. The frame in your view’s recConfig slot must be modifiable; that is, it must be RAM-based. When your view template supplies a recConfig frame, the view system builds a RAM-based recConfig frame along with the view—you need not do anything more to cause the view to use the recConfig frame.
C H A P T E R 1 0 Recognition: Advanced Topics exact complement of slots and values required is determined by the recognition features your recConfig frame is intended to supply; for more information, including complete descriptions of the system-supplied recConfig frames, see “System-Supplied recConfig Frames” (page 8-18) in Newton Programmer’s Reference. Once you’ve created a RAM-based recConfig frame, you must cause the recognition system to use it.
C H A P T E R 1 0 Recognition: Advanced Topics Sketch ink, like shapes, is displayed only in views based on the clEditView class. As a rule of thumb, consider sketch ink and ink text to be mutually exclusive when configuring recognition in views; for best results, configure your input view to recognize only one of these two data types. Views based on the clEditView class handle sketch ink and ink text automatically.
C H A P T E R 1 0 Recognition: Advanced Topics Table 10-1 Recognition failure in paragraph or edit view controlled by recToggle Recognizer enabled by recToggle view Returns on failure Text Ink text Ink text Ink text (does not fail) Shapes Sketch ink, smoothed Sketch ink Nothing (occurs rarely) As an alternative to using a recConfig frame to provide support for ink text, you can set your clParagraphView view’s vAnythingAllowed mask.
C H A P T E R 1 0 Recognition: Advanced Topics Manipulating Dictionaries 10 You can control the view’s use of dictionaries by including in your recConfig frame the dictionaries, rcSingleLetters, or inhibitSymbolsDictionary slots as appropriate. These slots are described in “protoRecConfig” (page 8-36) in Newton Programmer’s Reference.
C H A P T E R 1 0 Recognition: Advanced Topics To obtain the best performance and to conserve available memory, create your rcBaseInfo frame by cloning the frame provided by the ROM_canonicalBaseInfo constant. Store your frame in a slot named rcBaseInfo in your input view’s recConfig frame. For a detailed description of the rcBaseInfo frame, see “Data Structures Used in recConfig Frames” (page 8-24) in Newton Programmer’s Reference.
C H A P T E R 1 0 Recognition: Advanced Topics If you provide a grid in which the user is to write characters or words, you need to use an rcGridInfo frame to define the grid to the text recognizer. For example, the protoCharEdit system prototype uses an rcGridInfo frame internally to define the input areas (cells) in the comb view it provides. The recognizer uses the information in an rcGridInfo frame to make charactersegmentation decisions.
C H A P T E R 1 0 Recognition: Advanced Topics // indent from left of view to first letter constant kBoxIndent := 4; // width of a single box in the grid constant kCellWidth := 24; // create editable recConfig frame and set initial values myView.ViewSetupDoneScript := func() begin // prebuild RAM copy that we can change recConfig := PrepRecConfig(recConfig); // set these same flags in myView.viewFlags recConfig.
C H A P T E R 1 0 Recognition: Advanced Topics The PurgeAreaCache function causes the recognition system to adopt the settings that the recConfig frame specifies. This function is explained in more detail in the next section, “Changing Recognition Behavior Dynamically.” Normally, you need not call the PurgeAreaCache function when specifying a recConfig frame as part of a view’s template. However, you must call this function to change a recConfig frame at run time.
C H A P T E R 1 0 Recognition: Advanced Topics ▲ WA R N I N G The SetValue function may not be appropriate for setting the entryFlags slot in views that do not have a viewFlags slot. In these kinds of views, set the value of the entryFlags slot directly and then call the PurgeAreaCache function to invalidate the area cache. If you have changed values in the system’s user configuration data, call the ReadCursiveOptions function instead of the PurgeAreaCache function.
C H A P T E R 1 0 Recognition: Advanced Topics Using protoRecToggle Views 10 A protoRecToggle view changes the recognition behavior of views by overriding values inherited from the system’s user configuration data. Note that values in the view’s recConfig frame override settings specified by the protoRecToggle view. The protoRecToggle view is usually used with clEditView views that set the vAnythingAllowed mask or clParagraphView views that support ink text.
C H A P T E R 1 0 Recognition: Advanced Topics Configuring Recognizers and Dictionaries for recToggle Views 10 Regardless of whether you use a recConfig frame or view flags to specify your view’s recognition behavior, the view must be capable of enabling recognizers and dictionaries appropriate for each choice in the recToggle picker.
C H A P T E R 1 0 Recognition: Advanced Topics Figure 10-5 One recToggle controls all views Input Strokes recognized as recognized as recognized as appBase myRecToggle Figure 10-6 Each recToggle view controls a single input view Input Strokes recognized as recToggle1 recognized as recToggle2 recognized as recToggle3 appBase Using Advanced Topics in Recognition 10-21
C H A P T E R 1 0 Recognition: Advanced Topics When the view receives input, it uses parent inheritance to find configuration information. If a _recogSettings slot exists in the view’s _parent chain, the view uses the value of this slot, along with values supplied by an optional recConfig frame and values inherited from the system’s user configuration data. The recToggle view’s ViewSetupFormScript method uses the value of the _recogSettings slot to set the state of the recToggle view.
C H A P T E R 1 0 Recognition: Advanced Topics Avoid including inappropriate items in the recToggle popup, such as an ink text item for a view that does not support ink text. It is your responsibility to ensure that the _recogPopup array includes only symbols representing valid choices for the view that the recToggle configures. Accessing Correction Information 10 As words are recognized, the system saves correction information that includes ■ the stroke bundle.
C H A P T E R 1 0 Recognition: Advanced Topics The wordInfo frame provides methods that you can use to manipulate its contents; for more information, see “WordInfo Methods” (page 8-62) in Newton Programmer’s Reference. The alternate interpretations of a recognized word are provided as wordInterp frames based on the protoWordInterp system prototype. An array of wordInterp frames resides in the wordInfo frame’s words slot.
C H A P T E R 1 0 Recognition: Advanced Topics application’s NTK project; they might be supplied by the user in an input line view; they might even arrive as serial data. Because dictionary items can originate from a number of sources, the example here presumes that you know how to store your word strings and pass them, one at a time, to the AddWordToDictionary function. This function adds its argument to the specified custom dictionary.
C H A P T E R 1 0 Recognition: Advanced Topics symbol 'custom as its argument, which specifies that the new dictionary is for this application’s use only. Note Although the token returned by the NewDictionary function currently evaluates to an integer in the NTK Inspector, the type of value returned by this function may change on future Newton devices. Do not rely on the NewDictionary function returning an integer.
C H A P T E R 1 0 Recognition: Advanced Topics This approach works well for small dictionaries; for most large dictionaries, however, it is far more efficient to populate the dictionary from saved soup data. You should store custom dictionary data in a soup so that it is safely stored and persistent across soft resets. IMPORTANT Do not use the AddWordToDictionary global function to add words to the review dictionary; instead, use the appropriate review dictionary methods.
C H A P T E R 1 0 Recognition: Advanced Topics // store the dictionary data dictData := {data:theObj}; mySoup:AddXmit(dictData, nil); Restoring Dictionary Data From a Soup 10 To use the dictionary, your application needs to retrieve the dictionary data object from the soup and use the global function SetDictionaryData to install the data in an empty dictionary.
C H A P T E R 1 0 Recognition: Advanced Topics In addition to setting the view’s vCustomDictionaries flag, you need to create a dictionaries slot in either the view or its recConfig frame. The dictionaries slot stores a single dictionary identifier or an array of dictionary identifiers. You need to install the custom dictionary in this slot using code similar to the following example.
C H A P T E R 1 0 Recognition: Advanced Topics Removing Your RAM-Based Custom Dictionary 10 It is recommended that you remove your custom dictionary when it is no longer needed, such as when your application is removed. The DisposeDictionary function removes a specified RAM-based dictionary. The DisposeDictionary function accepts one argument, the dictionary identifier returned by NewDictionary.
C H A P T E R 1 0 Recognition: Advanced Topics Do not use the global functions AddWordToDictionary and RemoveWordFromDictionary to make changes to the review dictionary; instead, use the appropriate review dictionary methods. The dictionaries themselves are stored as entries in the system soup. This section describes how to manipulate these dictionaries programmatically.
C H A P T E R 1 0 Recognition: Advanced Topics Note Future versions of the system are not guaranteed to have the autoAdd slot. You must verify that the returned value is non-nil before using it. ◆ Adding Words to the User Dictionary 10 The following code fragment uses the AddWord method of the reviewDict object to add words to the user dictionary. After adding one or more words, you must call the SaveUserDictionary function to make your changes to the user dictionary’s system soup entry persistent.
C H A P T E R 1 0 Recognition: Advanced Topics The RemoveWord method returns true if the word was removed successfully and returns nil if the word was not removed. This method returns nil and does not remove the specified word if there are differences in case between the word in the dictionary and the word passed as the argument to the RemoveWord method. This method also returns nil when the word to be removed is not present in the review dictionary.
C H A P T E R 1 0 Recognition: Advanced Topics Removing Words From the Expand Dictionary 10 Normally, words are added to both the expand dictionary and the user dictionary simultaneously. As a result, words removed from the expand dictionary generally must also be removed from the user dictionary. The following code fragment uses the RemoveWord method to remove a word from both the expand and the user dictionaries.
C H A P T E R 1 0 Recognition: Advanced Topics Usually, you do not need to load the auto-add dictionary into RAM yourself—the system does so automatically whenever the Personal Word List slip is opened or the system is reset. However, the system provides the LoadAutoAddDictionary function for your convenience.
C H A P T E R 1 0 Recognition: Advanced Topics Removing Words From the Auto-Add Dictionary 10 The RemoveAutoAdd function deletes a specified word from both the user and auto-add dictionaries. This function returns true if the word was removed and returns nil if the word was not removed. This method does not remove the word if it is not present in the auto-add dictionary or if there are case inconsistencies between the argument to this function and the word actually found in the dictionary.
C H A P T E R 1 0 Recognition: Advanced Topics Manipulating Text in protoCharEdit Views 10 The default view provided by the protoCharEdit proto is an unformatted comb view (see page 10-4). You can provide an optional template that customizes this view’s appearance and behavior. The template itself is a frame residing in the view’s template slot. This frame may provide the following slots and methods: ■ The template’s filter slot defines a set of permissible input values.
C H A P T E R 1 0 Recognition: Advanced Topics You may also need to know the boundaries of the word in the text slot when working with certain protoCharEdit methods and functions. The protoCharEdit view’s wordLeft and wordRight slots provide indexes into the text string that you can use to determine the boundaries of a substring suitable for external display or for use as an argument to these routines. The wordLeft slot contains the index of the first externally-displayed character in the text slot.
C H A P T E R 1 0 Recognition: Advanced Topics The cells in this example template use filters defined by the format and filters slots to restrict input to valid values. The format slot specifies the valid input for each position in the comb view. Each character in the format string is an index into the filters array.
C H A P T E R 1 0 Recognition: Advanced Topics Customized Processing of Input Strokes 10 Setting the vStrokesAllowed flag provides the view with a means of intercepting raw input data for application-specific processing. If this flag is set, strokes are passed one at a time as the argument to the view’s ViewStrokeScript method. Your ViewStrokeScript method can then process the strokes in any manner that is appropriate.
C H A P T E R 1 0 Recognition: Advanced Topics Customized Processing of Double Taps 10 To process double taps reliably, your view’s ViewGestureScript method can test for the presence of the aeDoubleTap gesture. The gesture recognizer measures time between pen events reliably even when the main NewtonScript thread is busy. The recognition system considers a second tap to be part of a double tap when it occurs within a specified amount of time and distance relative to the first tap.
C H A P T E R 1 0 Recognition: Advanced Topics Note Normally, slot values in the system’s user configuration data are set by the user from various preference slips. It is strongly recommended that you do not change any user preferences without first obtaining confirmation from the user.
C H A P T E R 1 0 Recognition: Advanced Topics GetKeyView().viewInkWordScript := func(strokeBundle) begin // convert the stroke bundle into an ink word local inkPoly := CompressStrokes(strokeBundle); local inkWord := inkPoly.ink; local textSlot := "\uF701"; local stylesSlot := [1, inkWord]; local root := GetRoot(); // create a rich string with the ink word in it local appendString := MakeRichString(textSlot, stylesSlot); // append the rich string to myRichString if root.myRichString then root.
C H A P T E R 1 0 Recognition: Advanced Topics Summary of Advanced Topics in Recognition 10 See also “Summary” beginning on page 9-31 in Chapter 9, “Recognition.” Constants 10 See also Chapter 9, “Recognition,” which includes the following summaries: “Text Recognition View Flags” on page 9-31; “Non-Text Recognition View Flags” on page 9-32; and “View Flags Enabling Lexical Dictionaries” on page 9-33.
C H A P T E R 1 0 Recognition: Advanced Topics Lexical Dictionaries 10 Dictionary ID Constant Value Contents kLocalDateDictionary 110 Date formats. kLocalNumberDictionary1 113 Currency and numeric formats. kLocalPhoneDictionary 112 Phone number formats. kLocalTimeDictionary 111 Time formats. kMoneyOnlyDictionary1 118 Currency values and formats. kNumbersOnlyDictionary1 117 Numeric values and formats. kPostalCodeDictionary 116 Postal code formats.
C H A P T E R 1 0 Recognition: Advanced Topics System-Supplied RecConfig Frames // recognize ink or text ROM_rcInkOrText := { // allow user to enable text recog from recToggle allowTextRecognition: true, // default // return ink text when text recognizer disabled doInkWordRecognition: true, // default …} // recognize according to user prefs ROM_rcPrefsConfig := { // allow user to enable text recog from recToggle allowTextRecognition: true, // default // allow user to enable shape recog from recToggle all
C H A P T E R 1 0 Recognition: Advanced Topics // use custom dictionaries only inputMask: vCustomDictionaries, // default // dictionaries to use for recognition dictionaries: kSymbolsDictionary, // default // don’t enable symbols dictionary twice inhibitSymbolsDictionary: true // default …} // recognize letter-by-letter instead of w/ dictionaries ROM_rcTryLettersConfig := { // do not change value of this slot _proto: ROM_rcDefaultConfig, // default //interpret all input strokes as a single word letterSpa
C H A P T E R 1 0 Recognition: Advanced Topics // Positive offset (in pixels) from base // to the top of an uppercase “X” bigHeight: int, // Positive offset (in pixels) from base // to the bottom of a lowercase “g” descent: int, …} // use w/ rcBaseInfo to define grids of input cells rcGridInfo := {// all coordinates are global (screen) coordinates // coord of left edge of upper-left box in grid boxLeft: int, // coord of right edge of upper-left box in grid boxRight: int, // distance in pixels from one bo
C H A P T E R 1 0 Recognition: Advanced Topics System-Supplied ProtoCharEdit Templates 10 GetLocale().phoneFilter // phone number template GetLocale().dateFilter // date template GetLocale().
C H A P T E R 1 0 Recognition: Advanced Topics // dictionaries to use when vCustomDictionaries is set // single values need not reside in an array dictionaries: [dictId1, dictID2, … dictIdN], // optional baseline info rcGridInfo: frame, // optional single-letter input view info rcSingleLetters: frame, // true disables symbols dictionary inhibitSymbolsDictionary: Boolean, …} protoRecToggle 10 aRecToggleView := { // current setting of recToggle view // this slot may be provided by _parent chain _recogSe
C H A P T E R 1 0 Recognition: Advanced Topics // height of cells in pixels cellHeight: int, // system-provided default is 50 // recConfig frame specifying this view’s recog behavior recConfig: frame, // system provides default // specifies appearance & behavior of formatted comb view template: frame, // optional protoCharEdit template // string displayed when view opens; arg to SetupString method text: string, // optional // index of leftmost non-space character in comb view wordLeft: int, // system-pro
C H A P T E R 1 0 Recognition: Advanced Topics protoCharEdit Templates 10 ROM_numberFilter // general-purpose numeric template GetLocale().timeFilter // time template GetLocale().dateFilter// date template GetLocale().
C H A P T E R 1 0 Recognition: Advanced Topics ProtoWordInfo 10 aWordInfoFrame := { // ID of view that owns this data; returned by GetViewID id: int, // first char’s offset into clParagraphView view Start: int, // last char’s offset into clParagraphView view Stop: int, flags: forSystemUseOnly, // do not use this slot unitID: forSystemUseOnly, // do not use this slot // array of wordInterp frames; see page 10-53 words: [wordInterp1, wordInterp2, … wordInterpN] // stroke data from original input strokes:
C H A P T E R 1 0 Recognition: Advanced Topics Additional Recognition Functions and Methods 10 Dictionary Functions 10 AddWordToDictionary(dictionary, wordString) DeleteWordFromDictionary(dictID,word) DisposeDictionary(dictionary) GetDictionaryData(dictionary) GetRandomWord(minLength, maxLength) LookupWordInDictionary(dictID,word) NewDictionary(dictionaryKind) SaveUserDictionary() SetDictionaryData(dictionary, binaryObject) User Dictionary Functions and Methods 10 AddAutoAdd(word) RemoveAutoAdd(wo
C H A P T E R 1 0 Recognition: Advanced Topics Deferred Recognition Functions 10 Recognize(strokes, config, doGroup) RecognizePara(para, start, end, hilite, config) RecognizePoly(poly, hilite, config) Application-Defined Methods 10 view:ViewClickScript(stroke) view:ViewStrokeScript(stroke) view:ViewGestureScript(stroke, gesture) view:ViewWordScript(stroke) CorrectInfo Functions 10 GetCorrectInfo() // return correctInfo frame // return view identifier for use w/ correctInfo methods GetViewID(view)
C H A P T E R Figure 11-0 Table 11-0 1 1 Data Storage and Retrieval 11 The Newton operating system supplies a suite of objects that interact with each other to provide data storage and retrieval services. This chapter describes the use of these objects—stores, soups, cursors, and entries—to save and retrieve data. If you are developing an application that saves data, retrieves data, or provides preexisting data, you should familiarize yourself with the contents of this chapter.
C H A P T E R 1 1 Data Storage and Retrieval Introduction to Data Storage Objects 11 Newton devices represent data as objects. The NewtonScript programming language provides four basic object types that applications can use to represent data: Immediate A small, immutable object such as a character, integer or Boolean value. Binary Raw binary data. Array A collection of object references accessed from a numerical index. Frame A collection of object references accessed by name.
C H A P T E R 1 1 Data Storage and Retrieval lookup, message-passing, and inheritance in NewtonScript, see The NewtonScript Programming Language. Other than the requirement that data must reside in a slot, frames don’t impose any structure on their data. In practical use, though, the slots in a frame tend to be related in some way, usually holding related data and methods which operate on that data. In this way, the frame exemplifies the classic object-oriented programming definition of an “object.
C H A P T E R 1 1 Data Storage and Retrieval different from soups that are not part of a union. Unless specifically noted otherwise, anything said about soups in this text applies equally to union soups. Figure 11-1 Stores, soups and union soups Internal Store aSoup External Store aSoup Union Soup {aSlot:"some string data", ...} {theNum:121088, ...} {data: , ...} {myFn:, ...
C H A P T E R 1 1 Data Storage and Retrieval the query specification or query spec. The query spec describes the kind of information the query returns. The order in which soups return data items is imposed by an index you define for a specified soup. If you’ve ever used an array, you are already familiar with the concept of an index. Each element of the array is associated with a unique numeric value called a key.
C H A P T E R 1 1 Data Storage and Retrieval applications might require notification include creating soups; deleting soups; and adding, removing, or changing individual soup entries. The soup change notification mechanism is discussed in more detail in “Using Soup Change Notification” beginning on page 11-63.
C H A P T E R 1 1 Data Storage and Retrieval For information on using store objects, see “Using Stores” beginning on page 11-29. Packages 11 A package is the basic unit of downloadable Newton software: it provides a means of loading code, resources, objects, and scripts into a Newton device. Most Newton applications are shipped as packages that can be installed on a Newton device by applications such as Newton Package Installer or Newton Backup Utility.
C H A P T E R 1 1 Data Storage and Retrieval The soup definition frame specifies a name that identifies the soup to the system, a user-visible name for the soup, a symbol identifying the application that “owns” the soup, a user-visible string that describes the soup, and an array of index specification frames defining the default set of indexes with which the soup is created.
C H A P T E R 1 1 Data Storage and Retrieval You can create your own specialized indexes for any soup. You need to create an index for each slot or set of slots on which the soup will be searched frequently. It is preferable to define your indexes in the appropriate soup definition, but you can add indexes to an existing soup if necessary. An index generated against a single key value is called a single-slot index.
C H A P T E R 1 1 Data Storage and Retrieval data from a different locale. To take advantage of this behavior, the application must create an internationalized index for the soup and the query must request the alternate sorting behavior explicitly in its query spec. For more information, see “Internationalized Sorting Order for Text Queries” on page 11-45.
C H A P T E R 1 1 Data Storage and Retrieval Querying for Indexed Values 11 Queries can retrieve items according to the presence of one or more index keys and can test key values as well. A query that tests for the presence or value of an index key is called an index query. Soups that have single-slot indexes allow queries to use a single index key to select soup entries. Detailed information is provided in “Querying on Single-Slot Indexes” beginning on page 11-39.
C H A P T E R 1 1 Data Storage and Retrieval Indexes sort key values in ascending order unless the index spec frame used to create a particular index specifies descending order. Begin Keys and End Keys 11 Because index keys are sorted by value, you can improve the speed of an index query significantly by limiting the range of index key values it tests. One way to do this is to eliminate from the search any index key values that fall outside specified minimum or maximum values.
C H A P T E R 1 1 Data Storage and Retrieval exclusive forms of the same endrange selector; for example, a single query spec cannot specify both a beginKey value and a beginExclKey value. Another important point to understand is that there is only one beginKey or beginExclKey value, and only one endKey or endExclKey value associated with any query and the cursor it returns.
C H A P T E R 1 1 Data Storage and Retrieval cursor is positioned on the next valid entry in index key order. Similarly, if a valid entry is not found at the key value specified for an endKey or endExclKey value, the cursor is positioned on the previous valid entry in index key order. (The cursor is never positioned beyond the endKey value or before the beginKey value.
C H A P T E R 1 1 Data Storage and Retrieval key values, indexValidTest functions are fast and efficient because index key values are always kept in memory. Another kind of customized test, the validTest function, works like the indexValidTest function but tests the soup entry itself rather than its associated index key value.
C H A P T E R 1 1 Data Storage and Retrieval unless this behavior is requested explicitly, the words "blackSmith" and "Smithsonian" would also be found by this query. A text query is slower than its words query counterpart. Text queries do not require significantly more heap space than other kinds of queries. For more information about performing text queries, see “Querying for Text” beginning on page 11-43.
C H A P T E R 1 1 Data Storage and Retrieval Figure 11-5 Indexed entries Select subrange of valid entries Cursor presents discontiguous index key values contiguously 1 2 3 4 5 6 7 8 9 subrange of index key values 2 3 4 5 6 7 beginKey Eliminate more entries Valid entries in black Valid entries as presented by cursor endExclKey indexValidTest: func (key) begin (key MOD 2 = 0) end 4 2 2 Entries 6 4 6 11 An entry is a special kind of frame that resides in a soup.
C H A P T E R 1 1 Data Storage and Retrieval All frames are compressed automatically when they are stored as soup entries and all soup entries are decompressed when they are referenced. The automatic compression and decompression of soup data reduces the amount of storage space and run-time memory required by Newton applications. If you add a frame that references another entry, the referenced entry is copied as a frame into the new soup entry that is created.
C H A P T E R 1 1 Data Storage and Retrieval The most important factor to consider with respect to the kind of data is whether the data is static or dynamic. You must use soups to store dynamic data, but a number of options are available for storing static data. You will probably find that certain structures lend themselves more naturally than others to working with your particular data set. Especially for large data sets, space-efficiency may influence your choice of one data structure over another.
C H A P T E R 1 1 Data Storage and Retrieval ■ Although the user might enter data dynamically, there might be a large initial set of data your application needs to provide. Again, it’s more efficient to supply this as package data rather than as soup data. ■ You can supply multiple static data sets as separate packages to allow the user to load some subset of that data. For example, a travel guide application might keep data for individual countries in separate packages.
C H A P T E R 1 1 Data Storage and Retrieval Soup Compatibility Information 11 This section contains compatibility information regarding ■ the new soup format introduced with version 2.0 of the Newton operating system ■ obsolete soup functions and methods ■ the new soup change notification mechanism introduced in version 2.0 of the Newton operating system ■ soup information frame changes ■ null union soups on Newton 1.x devices New Soup Format 11 Because 2.
C H A P T E R 1 1 Data Storage and Retrieval The following soup methods and functions are obsolete: SetupCardSoups() // use RegUnionSoup instead RegisterCardSoup(soupName,indexArray, appSymbol,appObject) // useRegUnionSoup instead UnRegisterCardSoup(soupName)// use UnRegUnionSoup instead BroadcastSoupChange(soupNameString) // use -xmit methods or // XmitSoupChange fn instead UnionSoupIsNull(unionSoup)// no null uSoups from GetUnionSoupAlways GetUnionSoup(soupNameString)// use GetUnionSoupAlways instead s
C H A P T E R 1 1 Data Storage and Retrieval Null Union Soups 11 Under unusual circumstances a 1.x application may encounter a union soup that doesn’t contain any member soups. A soup in this state is referred to as a null union soup. Queries on a null union soup fail. Attempts to add entries to a missing member soup also fail if a soup definition for that soup has not been registered. Null union soups should not normally occur with 1.x applications and cannot occur with applications that use the 2.
C H A P T E R 1 1 Data Storage and Retrieval Query Global Function Is Obsolete 11 Queries are now performed by the Query method of soups or union soups; however, the Query global function still exists for compatibility with applications using version 1.x of the Newton application programming interface. The Query method accepts the same query specification frame argument that the Query global function did; however, version 2.0 query specs provide additional features that 1.x queries do not.
C H A P T E R 1 1 Data Storage and Retrieval Heap Space Requirements of Words and Text Queries 11 On systems prior to version 2.0, words and text queries generally require more memory than index queries, because each entry to be tested must first be read into the NewtonScript heap. System software version 2.
C H A P T E R 1 1 Data Storage and Retrieval This section presumes understanding of the material in “About Data Storage on Newton Devices” beginning on page 11-1. Most applications store data as frames that reside in soup entries. You can create a frame by simply defining it and saving it in a variable, a constant, or a slot in another frame. For example, the following code fragment defines a frame containing the aSlot and otherSlot slots. The frame itself is stored in the myFrame variable.
C H A P T E R 1 1 Data Storage and Retrieval When creating soups from within your application (form) part’s InstallScript function, remember that this function calls the EnsureInternal function on all values it uses. Thus, instead of passing references such as partFrame.theForm.myMainSoupDef to the RegUnionSoup function, paste a local copy of your soup definition into your application part’s InstallScript function for its use.
C H A P T E R 1 1 Data Storage and Retrieval // get from myUSoup all entries having an aSlot slot local myCursor := myUSoup:Query({indexPath: 'aSlot}); The Query method returns a cursor object that iterates over the set of soup entries satisfying the query specification passed as its argument. You can send messages to the cursor to change its position and to retrieve specified entries, as shown in the following example.
C H A P T E R 1 1 Data Storage and Retrieval You can use the EntryUndoChangesXmit function to undo the changes to the soup entry if you have not yet written the cached entry back to the soup. Because this function throws away the contents of the entry cache, referencing a slot in the entry after calling the EntryUndoChangesXmit function causes entry data to be read into the cache again. Most applications unregister their soup definitions when they are closed or removed.
C H A P T E R 1 1 Data Storage and Retrieval Referencing Stores 11 The GetStores global function returns an array of references to all currently available stores. You can send the messages described in this section to any of the store objects in this array. local allStores := GetStores(); ▲ WA R N I N G Do not modify the array that the GetStores function returns.
C H A P T E R 1 1 Data Storage and Retrieval for such stores. Do not use the global function IsReadOnly to test store objects; use only the IsReadOnly store method for this purpose. Getting or Setting the Default Store 11 The default store is that store designated by the user as the one on which new data items are created. Normally, applications using union soups do not need to get or set the default store.
C H A P T E R 1 1 Data Storage and Retrieval method retrieves the value of a specified slot in the store information frame. Its corollary, the SetInfo store method, writes the value of a specified slot in this frame. Using Soups 11 This section discusses the functions and methods used to work with soup objects. Individual entries in soups and union soups are manipulated by means of queries, cursors, and entry functions, as described in subsequent sections of this chapter.
C H A P T E R 1 1 Data Storage and Retrieval Registering and Unregistering Soup Definitions 11 The RegUnionSoup global function registers a soup definition with the system and returns a union soup object to which you can send messages. Once the soup definition is registered, various union soup methods create the union’s member soups as needed to save entries. A corollary function, UnRegUnionSoup, unregisters a specified soup definition.
C H A P T E R 1 1 Data Storage and Retrieval indexes: [{structure: 'slot, path: 'aSlot, type: 'string}] }; // register soup or retrieve already-registered soup local myUsoup := RegUnionSoup('|myApp:mySig|, mySoupDef); You can unregister a soup definition whenever you no longer need to create the soup it defines. If your application is the only one that uses your soup, you need only ensure that its definition is registered while the application is actually open.
C H A P T E R 1 1 Data Storage and Retrieval Adding Entries to Soups 11 This section describes how to add a frame to a union soup or a specified member soup in a union. For information on creating union soups, see “Registering and Unregistering Soup Definitions” on page 11-33. For information on retrieving union soups, see “Retrieving Existing Soups” on page 11-34. You can use either of the AddToDefaultStoreXmit or AddToStoreXmit methods to save frames as soup entries.
C H A P T E R 1 1 Data Storage and Retrieval After creating the new soup entry, these methods transmit a soup change notification message. To suppress the soup change notification message that -Xmit functions and methods transmit, pass nil as the value of their changeSym argument.
C H A P T E R 1 1 Data Storage and Retrieval ▲ WA R N I N G Each soup has only one tags index; if you add a tags index to a soup that already has one, it replaces the original tags index. For more information, see the description of the AddIndexXmit method (page 9-42) in Newton Programmer’s Reference. ▲ Removing Soups 11 When the user scrubs your application’s icon in the Extras Drawer, the system sends a DeletionScript message to your application.
C H A P T E R 1 1 Data Storage and Retrieval This approach provides the following benefits: ■ It prevents your application from inadvertently damaging another application’s data. ■ It helps your application avoid name conflicts with other applications’ slots. ■ It prevents soups from becoming cluttered with excessive numbers of entries. ■ It facilitates removal of your application’s data.
C H A P T E R 1 1 Data Storage and Retrieval ■ the use of internationalized sorting order ■ queries on multiple-slot indexes Querying Multiple Soups 11 Soups having the same name can be associated logically by a union soup object. To retrieve entries from all the available soups in a union, just send the Query message to the union soup object. You must query differently named soups separately, however.
C H A P T E R 1 1 Data Storage and Retrieval particular slot, the soup must be indexed on that slot. For example, the following example of a query returns a cursor to all soup entries that have a name slot. The cursor sorts the entries according to the value of this slot. As first returned by the query, the cursor points to the first entry in index order.
C H A P T E R 1 1 Data Storage and Retrieval at or before the position that would be occupied by 27 in the index is the last entry in the range over which the cursor iterates. To conduct the same query while excluding the endrange values, specify a beginExclKey value instead of a beginKey value, and specify an endExclKey value instead of an endKey value, as shown in the following code fragment: // mySoup is indexed on the 'number slot // return entries for which (11 > entry.
C H A P T E R 1 1 Data Storage and Retrieval The query passes the entire entry to the validTest method, rather than just the value of the indexed slot. The next code example reads the entry’s aSlot and otherSlot slots in order to compare their values: // select entries for which aSlot > otherSlot local myCursor := mySoup:Query({endKey: aKeyValue, validTest: func (entry) begin entry.aSlot > entry.
C H A P T E R 1 1 Data Storage and Retrieval set operator to select entries marked with only the 'flower and 'tall tags; this query does not select entries missing either tag, nor does it select entries marked with additional tags: local myCurs := mySoup:Query({indexPath:'name, tagSpec: {equal: ['tall, 'flower]}}); Like the equal set operator, the all set operator specifies a set of tags that entries must have to be selected; however, the all set operator does not exclude entries marked with additional
C H A P T E R 1 1 Data Storage and Retrieval This query finds entries containing the words "Bob", "Bobby", and so forth, but not words such as "JoeBob". Text queries are not case sensitive—even though the original query spec is all lower case, this query finds entries such as "Bob" or "BOB". Because the words slot contains an array, it can be used to search for multiple string beginnings.
C H A P T E R 1 1 Data Storage and Retrieval following code fragment illustrates a query that returns entries having strings that contain the substring "Bob": // find strings containing the substring "Bob" local myCursor := mySoup:Query({text: "bob"}); This query finds entries containing words such as "JoeBob", as well as those containing words such as "bob" and "Bobby".
C H A P T E R 1 1 Data Storage and Retrieval internationalized index: cursor methods such as Next and Prev return entries in the internationally-indexed order. Queries on Descending Indexes 11 Even though queries and cursors based on descending order indexes work just like normal queries and cursors, their behavior can seem confusing if you forget that it is a function of index order.
C H A P T E R 1 1 Data Storage and Retrieval Sending the Reset message to the cursor positions it at the first valid entry in index order. In this case, the first entry is "noun" because the entries are sorted in descending alphabetical order. The GoToKey cursor method steps through the set of valid entries in index order until it finds the first entry having a specified key value. If the specified key value is not found, this method returns the next valid entry found after the specified index position.
C H A P T E R 1 1 Data Storage and Retrieval A multiple-slot query can be performed only on a soup that has a multiple-slot index generated against the same set of keys in the same order as the query spec. For information on creating an index, see “Registering and Unregistering Soup Definitions” beginning on page 11-33 and “Adding an Index to an Existing Soup” beginning on page 11-36.
C H A P T E R 1 1 Data Storage and Retrieval A multiple-slot index solves this problem by sorting entries according to multiple key values. The key values are extracted from up to six index paths specified by the path array of the index specification frame.
C H A P T E R 1 1 Data Storage and Retrieval Instead of using single values for the indexPath, beginKey, beginExclKey, endKey, and endExclKey slots in the query spec, the Query method accepts arrays of keys or values as these arguments when it works with a soup having a multiple-slot index. The first key in the array is the primary key; subsequent lowerorder keys, if they are present, are the secondary key, tertiary key, and so on, up to a total of six keys per array.
C H A P T E R 1 1 Data Storage and Retrieval This time around, the query again skips over the "Bates" entry in the process of positioning the cursor at index value "P". However, because no entry holds a primary index key value of "P", the cursor stops at the next valid entry in index order. Further, because an identical index value was not found for the primary key specification, the secondary and tertiary key selectors have no effect at all.
C H A P T E R 1 1 Data Storage and Retrieval ▲ WA R N I N G Index keys are limited to a total of 39 unicode characters (80 bytes, 2 of which are used internally) per soup entry. Keys that exceed this limit may be truncated when passed to an indexValidTest function. This 80-byte limit applies to the entire key space allocated for an entry, not for individual keys.
C H A P T E R 1 1 Data Storage and Retrieval mySoup:MakeKey(["12345678901234567890", 3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"], ['name.first, 'cardType, 'name.last] ) returns the key value ["12345678901234567890", 3, "ABCDEFGHIJKLMNO"] The next example illustrates the truncation of subkeys when the total key size is greater than 80 bytes.
C H A P T E R 1 1 Data Storage and Retrieval ■ getting the number of entries in cursor data ■ getting an index key from the cursor ■ copying the cursor Getting a Cursor 11 Cursor objects are returned by the Query method. For more information, see “Using Queries” beginning on page 11-38. Testing Validity of the Cursor 11 When a storage card is inserted or a soup is created, union soups include new soups in the union automatically as is appropriate.
C H A P T E R 1 1 Data Storage and Retrieval Moving the Cursor 11 This section describes various ways to position the cursor within the range of entries it references. Sometimes the following discussion refers to the “first” entry in a cursor. As you know, the order imposed on cursor data is defined by the soup index used by the query that generated the cursor.
C H A P T E R 1 1 Data Storage and Retrieval You can use the Move method to move the cursor multiple positions. For example, instead of coding incremental cursor movement as in the following example, for i := 1 to 5 do myCursor:Next(); you can obtain faster results by using the Move method. The following code fragment depicts a typical call to this method. After positioning the cursor, the Move method returns the current entry.
C H A P T E R 1 1 Data Storage and Retrieval Note that if the query used to generate the cursor specifies a beginKey value, the CountEntries method starts counting at the first valid entry having an index key value equal to or greater than the beginKey value. Similarly, if the query that generated the cursor used an endKey value, the CountEntries method stops counting at the last valid entry having an index key value equal to or less than the endKey value.
C H A P T E R 1 1 Data Storage and Retrieval Saving Frames as Soup Entries 11 To save a frame as a soup entry, pass the frame to either of the union soup methods AddToDefaultStoreXmit or AddToStoreXmit, or pass it to the AddXmit soup method. Each of these methods transforms the frame presented as its argument into a soup entry, returns the entry, and transmits a change notification message.
C H A P T E R 1 1 Data Storage and Retrieval No more than 32 KB of text (total of all strings, keeping in mind that one character is 2 bytes) can reside in any soup entry. Another practical limitation is that there must be space in the NewtonScript heap to hold the entire soup entry. You should also be aware that Newton Backup Utility and Newton Connection Kit do not support entries larger than 32K. Keeping these limitations in mind, you can put any slots you need into your soup entries.
C H A P T E R 1 1 Data Storage and Retrieval When the frame is constructed from the entry, it is cached in memory. At this point, you can add, modify, and delete slots just as you would in any other frame; however, the changes do not persist until the EntryChangeXmit function is called for that particular entry. The EntryChangeXmit function writes the cached entry frame back to the soup, replacing the original entry with the changed one.
C H A P T E R 1 1 Data Storage and Retrieval Copying Entries 11 The EntryCopyXmit global function and the CopyEntriesXmit soup method enable you to copy entries from one soup to another and transmit appropriate change notifications. The following code fragment uses the CopyEntriesXmit soup method to copy all the entries from a specified source soup into a specified destination soup. Note that this method is defined only for soups, not for union soups.
C H A P T E R 1 1 Data Storage and Retrieval Note The EntryCopyXmit method copies the cached entry—not the original soup entry—into the destination soup. ◆ Sharing Entry Data 11 Shared soups and shared entries need to be in a well-documented format to allow other applications to use them. For an example of how to document the structure of your soup entries, refer to Chapter 19, “Built-in Applications and System Data.
C H A P T E R 1 1 Data Storage and Retrieval In contrast, the EntryUndoChanges function clears the entry cache without writing the cached entry to the soup. This function makes references to the entry point to the original, unmodified entry residing in the soup, instead of the cached entry.
C H A P T E R 1 1 Data Storage and Retrieval ■ control how and when notifications are sent The first part of this section describes how to register and unregister a callback function for execution in response to changes in a particular soup. The next part describes the various notifications that may be sent. The last part of this section describes how applications send soup change notifications.
C H A P T E R 1 1 Data Storage and Retrieval ▲ WA R N I N G Any callback function registered by the RegSoupChange function must not call either of the RegSoupChange or UnRegSoupChange functions. ▲ The second argument to the RegSoupChange function can be any unique symbol that identifies the callback to be registered. If your application registers only one callback function, you can just use your application symbol as the callback identifier (ID).
C H A P T E R 1 1 Data Storage and Retrieval Your callback function must take any action that is appropriate to respond to the change. Most applications have no need to respond to soup changes unless they are open, which is why it is recommended that you register your callbacks when your application opens and unregister them when it closes.
C H A P T E R 1 1 Data Storage and Retrieval changeSym parameter, the change notification is not sent, but the function or method does everything else its description specifies. Sometimes it may not be not desirable to send notifications immediately after making each change to a soup; for example, when changing a large number of soup entries, you might want to wait until after you’ve finished making all the changes to transmit notification messages.
C H A P T E R 1 1 Data Storage and Retrieval Summary of Data Storage 11 This section summarizes data structures, functions, objects and methods used for data storage on Newton devices.
C H A P T E R 1 1 Data Storage and Retrieval Multiple-Slot Index Specification Frame 11 { // index keys may be multiple slot values structure: 'multiSlot, // must use this value // up to six path expressions specifying indexed slots path:[pathExpr1, pathExpr2, … , pathExpr6], // data type found in each indexed slot type:[sym1, sym2, … sym6] // optional. 'ascending or 'descending order: [sym1, sym2, … sym6 ] // optional.
C H A P T E R 1 1 Data Storage and Retrieval // maximum index key value examined by this query // for all entries, (entry.indexPath ≤ endKey) endKey: keyValue, // optional // excluded upper boundary of key range examined by query // for all entries, (beginExclKey < entry.
C H A P T E R 1 1 Data Storage and Retrieval // optional tags query spec frame; see page 11-71 tagSpec: {equal:[t1, t2, …tN], all:[t1, t2, …tN], any:[t1, t2, …tN],none:[t1, t2, …tN]}, // when non-nil, match entire string in 'words slot entireWords: Boolean, // optional // string(s) to match w/ word beginnings in entries words: string|[str1, str2, … , strN], // optional // string to match w/ any substring in entries text: string, // optional } Tags Query Specification Frame 11 // this frame resides in
C H A P T E R 1 1 Data Storage and Retrieval store:IsValid() SetDefaultStore(newDefaultStore) store:SetInfo(slotSymbol,value) store:TotalSize() store:UsedSize() Soups These functions and methods allow you to work with soup-level data such as frames, soup indexes, soup information frames, and soup signatures.
C H A P T E R 1 1 Data Storage and Retrieval soupOrUsoup:GetSize() uSoup:GetSoupList() soup:GetStore() GetUnionSoupAlways(soupNameString) soup:MakeKey(string, indexPath) IsSoupEntry(object) soup:IsValid() soup:RemoveAllEntriesXmit(changeSym) soup:RemoveFromStoreXmit(changeSym) soupOrUsoup:RemoveIndexXmit(indexPath, changeSym) soup:SetInfoXmit(slotSymbol, value, changeSym) soup:SetName(soupNameString) Cursors 11 These functions and methods work with the cursor object returned by the Query method.
C H A P T E R 1 1 Data Storage and Retrieval EntryIsResident(entry) EntryModTime(entry) EntryMoveXmit(entry, newSoup, changeSym) EntryRemoveFromSoupXmit(entry, changeSym) EntryReplaceXmit(original, replacement, changeSym) EntrySize(entry) EntrySoup(entry) EntryStore(entry) EntryTextSize(entry) EntryUndoChangesXmit(entry, changeSym) EntryUniqueId(entry) FrameDirty(frame) IsSameEntry(entryOralias1, entryOralias2) Data Backup and Restore Functions These functions are intended for use by special-purpose dat
C H A P T E R Figure 12-0 Table 12-0 1 2 Special-Purpose Objects for Data Storage and Retrieval 12 This chapter describes the use of special-purpose objects to augment or replace the behavior of the system-supplied store, soup, cursor, and entry objects.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Virtual Binary Objects 12 The size of any NewtonScript object is limited by the amount of memory available in the NewtonScript heap. As a result, you cannot create binary objects larger than the amount of available NewtonScript heap space. For similar reasons, the amount of data that can be stored in a single soup entry is limited as well. (See “Saving Frames as Soup Entries” beginning on page 11-58 for details.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Normal binary objects encapsulate their data and reside entirely in the NewtonScript heap; thus, creating one of these objects or reading any of its data requires an amount of heap space sufficient to hold all its data. Therefore, the size of a normal binary object is limited by the amount of NewtonScript heap space available at the time it is created.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Table 12-1 Parts and type identifiers Part Type Description Application form Application. Book book Book created by Newton Book Maker or Newton Press. Auto part auto Background application/extension. Store part soup Read-only soup. Dictionary dict Custom dictionary for Newton recognition subsystem. Font font Additional font.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval in a local soup. Your mock entry could reside in a mock soup, which, in turn, could reside on a mock store. The mock entry counterparts to the system-supplied EntryXxx functions are implemented as the methods of a NewtonScript frame known as the mock entry’s handler. You supply this frame, which implements these methods as well as any it requires for its own purposes.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval // create new mock entry w/ no cached frame local m := NewMockEntry(myHandler, nil); // referencing m doesn’t create cached frame local x := m; // either statement could invoke myHandler:EntryAccess() local a := x.foo; local b := m.foo; To almost all of the system, the mock entry appears to be a normal soup entry; for example: ■ m.foo evaluates to 'bar ■ ClassOf(m) is 'frame ■ m.baz := 42 adds a slot to the handler.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Using Special-Purpose Data Storage Objects 12 This section describes how to use entry aliases, virtual binary objects (VBOs), store parts, and mock entries. This section presumes understanding of the conceptual material presented in preceding sections. Using Entry Aliases 12 This section describes how to create entry aliases, how to save them, and how to resolve them.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval You can use the IsSameEntry function to compare entries and aliases to each other; this function returns true for any two aliases or references to the same entry.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval The NewVBO and NewCompressedVBO store methods create virtual binary objects. Both methods require that you specify the class of the binary object to be created, as well as the store on which VBO data is to reside.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval A VBO becomes permanent only when it is written to a soup entry, and its associated binary data always resides on the same store as the entry. Thus, when creating a VBO, it’s usually best to specify that it use the same store as the soup entry into which you’ll save the VBO. If you try to put the same VBO in two different soup entries, a duplicate VBO is created, even if both entries reside on the same store.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval The following code fragment adds sound sample data to an empty VBO and demonstrates the use of the EntryUndoChanges function to undo those changes: // create a temporary soup mySoup := RegUnionSoup('|foo:myApp:mySig|, {name: "foo:myApp:mySig", indexes: '[]}) ; // get a soup entry that is a sound anEntry := mySoup:AddToDefaultStoreXmit('{sndFrameType: nil, samples:nil, samplingRate:nil, dataType:nil, compressionType: nil, userName: n
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval // decide to go back to the original EntryUndoChanges(anEntry); PlaySound(anEntry); // clean up foreach store in GetStores() do begin mySoup := store:GetSoup("foo:myApp:mySig") ; if mySoup then mySoup:RemoveFromStoreXmit(nil); end ; UnregUnionSoup("foo:myApp:mySig", '|foo:myApp:mySig|); VBOs and String Data 12 In most cases, you should avoid using the & and && string-concatenation operators with VBO-based strings.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Creating a Store Part 12 To create a store part, take the following steps using Newton Toolkit version 1.5 or greater: ■ Create a new project. ■ Select the Store Part radio button in the Output Settings dialog box. NTK disables all other settings in this dialog box when the Store Part option is selected. ■ Configure the Package Settings dialog box as you normally would.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Getting the Store Part 12 Store parts (also known as package stores) are made available by the GetPackageStore function. Package stores do not appear in the GetStores result array, which is reserved for normal store objects. The GetPackageStore function retrieves the store by name, so each package store must be given a unique name when it is built.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Implementing the EntryAccess Method 12 Each of your mock entry handler frames must supply an EntryAccess method that creates a cached frame containing the mock entry’s data, installs the cached frame in the mock entry, and returns the cached frame. This method is called when the system attempts to access a cached frame that is not present. The system passes the mock entry to your EntryAccess method when it is invoked.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Testing the Validity of a Mock Entry 12 The IsMockEntry global function returns the value true for objects that are valid mock entries. You can use this function to distinguish between mock entry objects and other objects such as cache frames or soup entries. Note that the IsSoupEntry function returns true for both mock entries and normal soup entries.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Summary of Special-Purpose Data Storage Objects 12 This section summarizes data structures, objects, methods and global functions used by Newton devices for specialized data storage purposes.
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval SafeFreezePackage(pkgRef) SafeMovePackage(pkgRef, destStore) SafeRemovePackage(pkgRef) store:SuckPackageFromBinary(binary, paramFrame) store:SuckPackageFromEndpoint(endPoint, paramFrame) ThawPackage(pkgRef) Store Parts (Package Stores) 12 GetPackageStore(name) GetPackageStores() Entry Aliases 12 IsEntryAlias(object) MakeEntryAlias(entry) ResolveEntryAlias(alias) IsSameEntry(entryOralias1, entryOralias2) Virtual Binary Objects
C H A P T E R 1 2 Special-Purpose Objects for Data Storage and Retrieval Application-Defined Mock Entry Handler Methods 12 handler:EntryAccess(mockEntry) handler:EntryChange(mockEntry) handler:EntryChangeWithModTime(mockEntry) handler:EntryCopy(mockEntry, newSoup) handler:EntryModTime(mockEntry) handler:EntryMove(mockEntry, newSoup) handler:EntryRemoveFromSoup(mockEntry) handler:EntryReplace(original, replacement) handler:EntryReplaceWithModTime(original, replacement) handler:EntrySize(mockEntry) handl
C H A P T E R Figure 13-0 Table 13-0 1 3 Drawing and Graphics 13 This chapter describes how to draw graphical objects such as lines and rectangles in Newton applications. You should read this chapter if you are attempting to draw complex or primitive graphical objects in a view. Before reading this chapter, you should be familiar with the information in Chapter 3, “Views.
C H A P T E R 1 3 Drawing and Graphics Note that for all of the functions described in this chapter: ■ The coordinates you specify are interpreted as local to the view in which the object is drawn. ■ The origin of the coordinate plane (0,0) is the upper-left corner of the view in which the object is drawn. ■ Positive values are towards the right or the bottom of the screen from the origin. For additional information on the Newton coordinate system see “Coordinate System” (page 3-6).
C H A P T E R 1 3 Drawing and Graphics Figure 13-1 A line drawn with different bit patterns and pen sizes A rectangle can be defined by two points—its top-left and bottom-right corners, as shown in Figure 13-2, or by four boundaries—its upper, left, bottom, and right sides. Rectangles are used to define active areas on the screen, to assign coordinate systems to graphic entities, and to specify the locations and sizes for various graphics operations.
C H A P T E R 1 3 Drawing and Graphics Drawing also provides functions that allow you to perform a variety of mathematical calculations on rectangles—changing their sizes, shifting them around, and so on. An oval is a circular or elliptical shape defined by the bounding rectangle that encloses it. If the bounding rectangle is a square (that is, has equal width and height), the oval is a circle, as shown in Figure 13-3.
C H A P T E R 1 3 Drawing and Graphics A rounded rectangle is a rectangle with rounded corners. The figure is defined by the rectangle itself, along with the width and height of the ovals forming the corners (called the diameters of curvature), as shown in Figure 13-5. The corner width and corner height are limited to the width and height of the rectangle itself; if they are larger, the rounded rectangle becomes an oval.
C H A P T E R 1 3 Drawing and Graphics Figure 13-6 A polygon A region is an arbitrary area or set of areas, the outline of which is one or more closed loops. One of drawing’s most powerful capabilities is the ability to work with regions of arbitrary size, shape, and complexity. You define a region by drawing its boundary with drawing functions. The boundary can be any set of lines and shapes (even including other regions) forming one or more closed loops.
C H A P T E R 1 3 Drawing and Graphics can draw something that was defined in another program, with great flexibility and without having to know any details about what’s being drawn. Figure 13-8 shows an example of a picture containing a rectangle, an oval, and a triangle. Figure 13-8 A simple picture Manipulating Shapes 13 In addition to drawing shapes, you can perform operations on them.
C H A P T E R 1 3 Drawing and Graphics Drawing Compatibility 13 The following new functionality has been added for Newton OS 2.0. For complete details on the new drawing functions, see the “Drawing and Graphics Reference” in the Newton Programmer’s Reference. New Functions 13 The following functions have been added: ■ GetShapeInfo—returns a frame containing slots of interest for the shape.
C H A P T E R 1 3 Drawing and Graphics Changes to View Classes 13 The icon slot of a view of the clPictureView class can now contain a graphic shape, in addition to bitmap or picture objects. Using the Drawing Interface 13 This section describes how to use the drawing interface to perform specific tasks. See “Drawing and Graphics Reference” (page 10-1) in the Newton Programmer’s Reference for descriptions of the functions and methods discussed in this section.
C H A P T E R 1 3 Drawing and Graphics If you want to redraw a view explicitly at any particular time, you need to send it the Dirty message. This message causes the system to add that view to the area of the screen that it updates in the next event loop cycle. To make the update area redraw before the next event loop cycle, you must call the RefreshViews function after sending the Dirty message.
C H A P T E R 1 3 Drawing and Graphics For example, you might nest arrays to create the hierarchy of shapes and styles depicted in Figure 13-9. Figure 13-9 Example of nested shape arrays Start Style Shape 1 Style 2 Shape 3a Shape 2a Style 3 Shape 2b Shape 3b If the nested shape array depicted in Figure 13-9 were passed to the DrawShape function, the results summarized in Table 13-1 would occur.
C H A P T E R 1 3 Drawing and Graphics Default Transfer Mode 13 The default transfer mode is actually a split state: bitmaps and text are drawn with a modeOR transfer mode, but other items (geometric shapes, pens, and fill patterns) are drawn with a modeCOPY transfer mode. However, when you actually specify a transfer mode (with a non-nil value in the transferMode slot of the style frame), all drawing uses the specified mode.
C H A P T E R 1 3 Drawing and Graphics If the style frame includes a clipping slot, the drawing of all shapes affected by this style frame is clipped according to the value of the clipping slot. If the value of the clipping slot is nil or if the clipping slot is not supplied, the clipping behavior of the destination view is used. If the clipping slot contains a region shape, that region is used as the clipping boundary for drawing operations affected by this style frame.
C H A P T E R 1 3 Drawing and Graphics Using Drawing View Classes and Protos 13 Four view classes and three protos, which you can use to create your own templates, are built into the system. The view classes include: ■ clPolygonView —displays polygons or ink, or accepts graphic or ink input. ■ clPictureView—displays a bitmap or picture object shape. ■ clEditView—edits views that can accept both text and graphic user input. ■ clRemoteView—displays a scaled image of another view.
C H A P T E R 1 3 Drawing and Graphics Displaying Bitmaps, Pictures, and Graphics Shapes 13 You can use a view of the clPictureView class to display a bitmap, picture, or graphic shape (polygon). The icon slot in this view can contain a bitmap, a picture object, or a graphic shape. Displaying Pictures in a clEditView 13 Use the clEditView view class to display and accept text and graphic data in a view.
C H A P T E R 1 3 Drawing and Graphics viewFormat: nil, ViewSetupFormScript: func() begin // aView is the view to be scaled self.stepchildren := [aView]; end, ...}; Translating Data Shapes 13 You can use the global functions PointsToArray and ArrayToPoints to translate points data between a polygon shape ('polygonShape) and a NewtonScript array. Finding Points Within a Shape 13 Use the HitShape function to determine whether a pen event occurred within the boundaries of the shape.
C H A P T E R 1 3 Drawing and Graphics Using Bitmaps 13 You can dynamically create and destroy bitmaps, draw into them, and perform operations on them such as rotating, flipping, and sizing. This flexible treatment of bitmaps allows you to use them as offscreen buffers and for storage of documents such as fax pages. You can create and use bitmap images with the drawing bitmap functions. To create a bitmap you first allocate a bitmap that will contain the drawing with the MakeBitmap function.
C H A P T E R 1 3 Drawing and Graphics Making CopyBits Scale Its Output Bitmap 13 CopyBits uses the bounds of the bitmap passed to it to scale the bitmap that it draws; so, by changing the bounds of the bitmap passed to CopyBits, you can make this method scale the bitmap it draws. If you want to scale the output bitmap without changing the bounds of the original, call ScaleShape on a clone of the original bitmap and pass the modified clone bitmap to the CopyBits method.
C H A P T E R 1 3 Drawing and Graphics Figure 13-10 Example of ViewIntoBitmap method (0, 0) (10, 10) destBitmap destRect (0, 0) srcRect (50, 100) view to capture Rotating or Flipping a Bitmap 13 Use the MungeBitmap function (page 10-22) to perform various bitmap operations such as rotating or flipping the bitmap. These operations are destructive to the bitmap passed as an argument to this function; the bitmap is modified in place and the modified bitmap shape is returned.
C H A P T E R 1 3 Drawing and Graphics Importing Macintosh PICT Resources 13 The following information applies to the Mac OS version of NTK; the Windows version differs. See the Newton Toolkit User’s Guide for details. A Macintosh PICT resource can be imported into the Newton in two ways: as a bitmap or as a picture object. A Macintosh PICT resource is stored much more compactly on the Newton as a picture object; however, it may be slower to draw than a bitmap.
C H A P T E R 1 3 Drawing and Graphics You can also use MakePict: myText := MakePict([{penpattern: 0, font: ...}, rect, {font: ...}, txtshape], {font: ...}); You can set the font in locations with MakePict. In this case the font gets “encapsulated” into the PICT. If the {penpattern} frame was not present in the picture shape, any of the above places should suffice to set the font.
C H A P T E R 1 3 Drawing and Graphics Notice that there are two types of pictures: bitmaps (a frame with bits, a bounds, and mask slots) and Format 1 PICTs (binary objects of class picture).
C H A P T E R 1 3 Drawing and Graphics Summary of Drawing 13 Data Structure 13 Style Frame 13 aStyle := { transferMode : constant, // transfer mode for the pen penSize : integer, // size of the pen in pixels penPattern : constant, // the pen pattern fillPattern : constant, // the fill pattern font : string, // font to use for drawing text justification : symbol, // alignment of text clipping : shape, region, or array of shapes, // specifies clipping transform : array, // offsets or scales the shape
C H A P T E R 1 3 Drawing and Graphics clRemoteView 13 clRemoteView := { stepChildren : int, // specifies a single view viewBounds: int, // size and location of the view viewFlags : const, // controls the recognition behavior of the view viewFormat : const, // controls appearance of the view Protos 13 protoImageView 13 aProtoImageView := { _proto: ProtoImageView, Image : shape, Annotations : array, scalingInfo : frame, viewBounds : boundsFrame, viewJustify: justificationFlags, viewFormat : formatF
C H A P T E R 1 3 Drawing and Graphics myImageView:ScrollBy : function, // scrolls an image myImageView:ZoomBy : function, // makes an image larger or smaller myImageView:ZoomTo : function, // changes the size of the image myImageView:CanZoomBy : function, // changes the size of the image myImageView:ZoomToBox : function, // resizes the image ...
C H A P T E R 1 3 Drawing and Graphics trackWhileScrolling : integer, // tracks the grey box ...
C H A P T E R 1 3 Drawing and Graphics IsPtInRect(x, y, bounds) FitToBox(sourceBox, boundingBox, justify) OffsetRect(rect, deltaX, deltaY) SectRect(rect1, rect2) UnionRect(rect1, rect2) RectsOverlap(rect1, rect2) Utility Functions 13 view:DoDrawing(drawMethodSym,parameters) view:CopyBits(picture, x, y, mode) DrawXBitmap(bounds,picture,index,mode) view:LockScreen(lock) IsPrimShape(shape) PointsToArray(polygonShape) ArrayToPoints(pointsArray) Summary of Drawing 13-27
C H A P T E R Figure 14-0 Table 14-0 1 4 Sound 14 This chapter describes how to use sound in your application and how to manipulate Newton sound frames to produce pitch shifting and other effects. You should read this chapter if you are attempting to use sound in an application.
C H A P T E R 1 4 Sound All operations on sound frames are created by sending messages to a sound channel that encapsulates the sound frame and the methods that operate on it. Sound channels can play sampled sounds starting from any point within the data. For more advanced uses of sound you can open a sound channel which allows multiple channels to play simultaneously, or multiple sounds to be queued in a single channel. You use a sound channel by sending messages to a sound channel frame.
C H A P T E R 1 4 Sound For example, to play a sound in ROM when the view opens, place its name in the view’s showSound slot. In fact, all ROM_soundName constants are pointers to Newton sound frames stored in ROM. Instead of using one of these constants; however, you can store a Newton sound frame in a slot, causing the sound stored in that frame to play in accompaniment to the event associated with that slot. The next section describes the format of a Newton sound frame.
C H A P T E R 1 4 Sound Using Sound 14 This section describes how to use sound to perform specific tasks. See Newton Toolkit User’s Guide for descriptions of the functions and methods discussed in this section. Creating and Using Custom Sound Frames 14 The following information applies to the Mac OS version of NTK. The Windows version differs; see the Newton Toolkit User’s Guide for details.
C H A P T E R 1 4 Sound Creating Sound Frames Procedurally 14 To create a sound frame, you usually need to create a copy of the sound frame you wish to modify. Because you cannot modify sound frames in ROM, you must copy the sound frame in order to modify the binary sample data. Cloning the original version of a sound frame you want to modify also allows you to reset values to their original state and provides a means of recovering the original sound frame easily if an operation fails.
C H A P T E R 1 4 Sound Creating a Sound Channel for Playback 14 You create a sound channel by sending it the Open function. The code that creates a sound channel for playback might look like the following example: mySndChn := {_proto:protoSoundChannel}; mySndChn:Open(); Playing Sounds 14 Once you create the sound channel, you can use any of the following methods to control the sound. Schedule—queues the sound for play. Start—starts playing the sounds in the order that they were scheduled.
C H A P T E R 1 4 Sound Synchronous and Asynchronous Sound 14 When a sound is played asynchronously, the playback can be intermixed with other tasks because the system does not wait for the sound to finish before beginning another task (such as updating the user interface, allowing user feedback; for example with buttons, or playing a subsequent sound). When playback must be allowed to complete, use the PlaySoundSync, PlaySoundAtVolume, or PlaySoundIrregardless to guarantee uninterrupted playback.
C H A P T E R 1 4 Sound clipped off with each new call to the PlaySoundSync function. In fact, it’s likely that you won’t hear twenty sounds in the asynchronous playback demo; the calls occur faster than the Newton sound chip can respond. About the Sound Chip 14 The Newton sound chip requires about 50 milliseconds to load a sound and begin playing it. It also requires about 50 milliseconds to clear its registers and ready itself for the next call after playback completes.
C H A P T E R 1 4 Sound Pitch Shifting 14 In general, you can set the value of a sound frame’s samplingRate slot to any float value less than that specified by the kFloat22kRate constant. However, this usually results in poor sound quality. What generally works best is to take an 11 kHz sound and play it at some higher rate. Of course, 22 kHz sound resources cannot be played at any higher sampling rate.
C H A P T E R 1 4 Sound For an example that uses output from a view based on the protoKeypad prototype, see the Newton DTS sample code on this topic. Manipulating Sample Data 14 This section describes how to use the utility functions ExtractByte and StuffByte to manipulate individual bytes in sound sample data. Because of performance considerations, you’ll want to manipulate sample data on the Newton only when it’s absolutely necessary.
C H A P T E R 1 4 Sound Summary of Sound 14 Data Structures 14 SndFrame Structure 14 mySndFrame := { _proto: mySndFrame, sndFrameType : symbol, // specifies format samples : frame, // contains sampled binary data samplingRate : integer /floating point, // specifies playback rate compressionType : integer, // indicates no compression dataType : integer, // indicates size of sample in bits start : integer, // index of first sample to play count : integer, // number of samples to play loops : integer,
C H A P T E R 1 4 Sound Functions and Methods 14 view:Dial(numberString,where) GetVolume() PlaySoundSync(soundFrameRef) RawDial(number, where) SetVolume(volume) PlaySoundAtVolume(soundFrameRef, volume) PlaySoundIrregardless(soundFrameRef) PlaySoundIrregardlessAtVolume(soundFrameRef, volume) PlaySoundEffect(soundFrameRef, volume, type) Clicker() Sound Resources ROM_alarmWakeup // alarm sound ROM_click // click sound ROM_crumple // paper crumpling sound ROM_drawerClose // drawer closing sound ROM_drawer
C H A P T E R Figure 15-0 Table 15-0 1 5 Filing 15 This chapter describes how your application can support the Filing service. This service allows the user to ■ associate data items with folders displayed by the user interface ■ create, edit, or delete folders at will ■ specify the store on which a soup entry is to reside when it is filed Before reading this chapter, you should understand the use of views to image data, as explained in Chapter 3, “Views.
C H A P T E R 1 5 Filing Your application must provide a target view that can manipulate the target. The target view is usually the same view that images the target data. Although the application base view is often an appropriate target view, it may not be under all circumstances. For example, each of these common situations has specialized targeting needs: ■ Most applications allow the user to file and move multiple data items from within an overview view.
C H A P T E R 1 5 Filing When the user taps the protoFilingButton view, it displays the Filing slip shown in Figure 15-2.
C H A P T E R 1 5 Filing Filing and other system services display user messages containing a string that is the user-visible name of your application. For example, this string is used to complete the text displayed when the user creates a local folder. You need to create in your application’s base view an appName slot that holds this string. Figure 15-3 depicts the text displayed when the user creates a folder that is local to the Notepad application.
C H A P T E R 1 5 Filing When no external store is available or the value of the doCardRouting slot is nil, the system displays the simplified version of the Filing slip shown in Figure 15-4. Figure 15-4 Filing slip without external store appObjectFileThisIn string This simplified version of the Filing slip does not include the buttons that allow the user to choose a store.
C H A P T E R 1 5 Filing When the user taps the File button, the system ■ invokes the GetTargetInfo method to discover the target and the target view ■ sends the FileThis message to the target view Your target view must supply a FileThis method that performs any tasks necessary to file the target, such as the following: ■ moving its soup entry to a different store ■ redrawing the current view ■ setting the target’s labels slot to its new value ■ performing any additional tasks that are appropr
C H A P T E R 1 5 Filing The protoClockFolderTab is a variation on protoNewFolderTab that displays the current time as its title text. Do not attempt to replace this text; if you want to display your own title text in a folder tab view, use a protoNewFolderTab view rather than a protoClockFolderTab view. Figure 15-7 depicts a typical protoClockFolderTab view.
C H A P T E R 1 5 Filing on the internal store, the external store or both; that is, the user can specify a stores filter in addition to a labels filter. Figure 15-8 shows the folder tab picker in a view based on the protoClockFolderTab proto. Figure 15-8 Choosing a filing filter To display items according to the user’s choice of store, your target view must supply a storesFilter slot.
C H A P T E R 1 5 Filing Filing Compatibility Information 15 Version 2.0 of the Newton operating system supports earlier versions of the Filing interface completely—no code modifications are required for older filing code to continue working under the version 2.0 operating system. However, it is strongly suggested that you update your application to the version 2.0 Filing interface to take advantage of new features and to remain compatible with future versions of the Newton operating system.
C H A P T E R 1 5 Filing The new slots appObjectFileThisIn and appObjectFileThisOn support localization of your application’s Filing messages into languages having masculine and feminine nouns. The DefaultFolderChanged function is obsolete. Do not use this function. The target and targetView slots are superseded by your override of the GetTargetInfo method. However, if you do not override the system-supplied GetTargetInfo method, you must include these slots in your application’s base view.
C H A P T E R 1 5 Filing ■ Create a storesFilter slot in your application’s target view ■ Implement the FileThis and NewFilingFilter methods. ■ Add a filing button view and a folder tab view to your application. ■ Register a callback function with the folder change notification mechanism.
C H A P T E R 1 5 Filing Creating the appAll Slot 15 You must create in your application’s base view an appAll slot containing a string of the form "All Items" where Items is the plural for the items to be filed, such as cards, notes, and so on. For example, when the user taps the folder tab view in the built-in Notes application, the last item in the picker is “All Notes.
C H A P T E R 1 5 Filing Specifying the Target 15 The GetTargetInfo method identifies the current target and target view to the system. Depending on your needs, you can use the default version of this method or override it. If you use the default version, your application’s base view must supply target and targetView slots that you update whenever the target or target view changes.
C H A P T E R 1 5 Filing Creating the labelsFilter slot 15 Your application’s target view must supply a labelsFilter slot. This slot holds a value indicating the current filing filter selected by the user in the picker displayed by the folder tab view. This slot can store either a symbol indicating the currently displayed filing category or the value nil (which specifies that the Unfiled category is currently displayed). The system sets the value of the labelsFilter slot for you.
C H A P T E R 1 5 Filing declare your folder tab view to the application’s base view. The system sets the folder tab view’s bounds for you at run time, positioning the folder tab relative to its parent, near the top of the screen. Customizing Folder Tab Views 15 The protoNewFolderTab proto supplies a child view named title that images a string that you may supply optionally.
C H A P T E R 1 5 Filing The arguments to the FileThis method supply all the information necessary to file a soup entry, including the item to file (the target), the category under which to file it (the value to which you set the target’s labels slot), and the store on which to file it. If the value of the labelsChanged parameter to the FileThis method is true, your FileThis method must use the value of the newLabels parameter to update the value of the target’s labels slot.
C H A P T E R 1 5 Filing perform any other actions that are appropriate, such as redrawing views affected by the change in filing filter. The symbol passed as the sole argument to your NewFilingFilter method specifies which of the storesFilter or labelsFilter slots changed in value. This argument does not specify the slot’s new value, however. Your NewFilingFilter method must use the current value of the specified slot to retrieve those soup entries that fall into the new filing category.
C H A P T E R 1 5 Filing // now redraw views affected by the change // NOTE: You could keep track of the original // labelsFilter and storesFilter to see // whether you need to actually do work. end Using the Folder Change Notification Service 15 You can use the RegFolderChanged global function to register callback functions that are executed when the user adds, removes, or edits folders.
C H A P T E R 1 5 Filing Using Local or Global Folders Only 15 To suppress the display of either local or global folders in the Filing slip and the folder tab views, you can set the values of optional localFoldersOnly and globalFoldersOnly slots that you supply in your application’s base view. Note that the use of local or global folders only is intended to be an application design decision that is made once, rather than a user preference that can change.
C H A P T E R 1 5 Filing Summary 15 This section summarizes the data structures, protos, functions, and methods used by the Filing service.
C H A P T E R 1 5 Filing Filing Protos 15 protoFilingButton 15 myFilingButtonView := // do not override ViewClickScript; use ButtonClickScript instead { _parent:{ // MyAppBaseView _parent: {…}, // root view _proto: {…}, // myAppBaseViewTemplate …}, _proto: {// myFilingButtonTemplate // set your own viewBounds in NTK view editor viewBounds: {left: 10, top: 250, right: 27, bottom: 263}, _proto: {// protoFilingButton _proto: {…}, // protoPictureButton // your ButtonClickScript must call inherited Button
C H A P T E R 1 5 Filing protoClockFolderTab 15 myClockFolderTabView := { {_parent: myAppBaseView, // see page 15-20 _proto: { protoClockFolderTab, // your folder tab’s viewSetupFormScript must // call inherited:?viewSetupFormScript() viewSetupFormScript: , …}, // do not attempt to alter the time display text …} Filing Functions and Methods 15 view:GetTargetInfo(reason) // override for multiple targets view:MoveTarget (target, destStore) // move target between stores RegFolderC
C H A P T E R Figure 16-0 Table 16-0 1 6 Find 16 This chapter describes how your application can support finding text, dates, or your own data types in its data. If you want users to be able to use the system’s Find service to locate data in your application, you should be familiar with the material discussed in this chapter. Before reading this chapter, you should understand the concept of the target of an action, explained in Chapter 15, “Filing.
C H A P T E R 1 6 Find Figure 16-1 The system-supplied Find slip The system-supplied Find slip contains an input line that specifies a search string, several buttons indicate the scope of the search, and a Look For picker (pop-up menu) that specifies the kind of search to perform. By choosing from the Look For picker (pop-up menu) you may specify whether the search string is a text item or a date, as shown in Figure 16-2.
C H A P T E R 1 6 Find Searching for data in the current application only is called a Local find operation. Figure 16-3 depicts a Local find in the Notepad application. Figure 16-3 A local Find operation The Everywhere and Selected buttons specify that the system perform searches in applications other than the currently active one. Applications must register with the Find service to participate in such searches.
C H A P T E R 1 6 Find In addition, an application can support searches of multiple data sets. For example, a personal finance program might allow you to search the check ledger, the account list, and the credit charges list as separate searches, even though all the data resides in a single application. For more information on how to implement this in your application see “Adding Application Data Sets to Selected Finds” beginning on page 16-19.
C H A P T E R 1 6 Find Figure 16-6 The Find overview The user can tap items in the Find overview to display them. As items are displayed, a status message at the top of the Find slip indicates which item is displayed and whether there are more results to display. Figure 16-7 depicts this status message. Figure 16-7 Find status message When more than one item is found, the status message indicates that there are more items to display.
C H A P T E R 1 6 Find Compatibility Information 16 The current version of the Find service opens in the text or date find mode last used. The Find slip in versions of Newton System Software prior to 2.0 always opened in text find mode, regardless of the mode last used. Find now performs “date equal” finds, and returns control to the user more quickly than previous versions did.
C H A P T E R 1 6 Find The only significant difference between a date find and a text find is that a different search method locates the items that are returned. To support text searches, you must supply a Find method. To support searching by date, you must supply a DateFind method. You can support any of these search methods independently of one another; for example, you can implement the Find method without implementing the DateFind method.
C H A P T E R 1 6 Find ROM_CompatibleFinder proto, the string to display for each found item is contained in the title slot of each of the items in the items array in your finder. When the user taps scroll buttons to scroll through this list of found items, the system keeps track of the user’s place in the array of found items. Figure 16-8 depicts the strings from both the title slot and the FindSoupExcerpt method as they are used in a typical Find overview.
C H A P T E R 1 6 Find Figure 16-9 The ShowFoundItem method displays the view of an overview item The Find overview provides Routing and Filing buttons. If you are using the ROM_SoupFinder the system will file, move, and delete your entries in the overview of found items. In such an occurrence, the soup-change notification mechanism notifies your application. (The soup-change notification mechanism is described in Chapter 11, “Data Storage and Retrieval.
C H A P T E R 1 6 Find The most important difference between Local finds and other kinds of find operations is that when the system invokes your search method as part of a Global or Selected find, your application may not be open. Therefore, you must test to see that the application soup is available before searching it. The system informs your search method of the scope of the search through the scope parameter.
C H A P T E R 1 6 Find ■ Employ multiple data sets from one application in a Selected find by adding the method AppFindTargets, and one or both of the search methods FindTargeted and DateFindTargeted. ■ Replace the system-supplied Find slip with one of your own by supplying a CustomFind method in your application’s base view. This method will be called when the user taps Find and your application is frontmost. The sections immediately following describe these tasks in detail.
C H A P T E R 1 6 Find The full complement of slots in the finder frame resulting from your searches varies according to the finder proto it’s based on. A finder frame based on the ROM_SoupFinder proto returns a finder containing a cursor with which to retrieve found items from the application soup. A finder frame based on the ROM_CompatibleFinder proto results in a frame containing an array of the actual found items.
C H A P T E R 1 6 Find Table 16-1 Overview of ROM_SoupFinder methods Method Description Override? Reset Resets cursor to first found entry. In general you should use ReSync to reset a finder. No ZeroOneOrMore Returns 0 if no found entries, 1 for one found entry, or other number for more. No ShowEntry Causes the finding application to display entry, which is passed to it as an argument. Does not close the Find overview. No SelectItem Marks the item, passed in as an argument, as selected.
C H A P T E R 1 6 Find If your application does not store data as soup entries, you can use the ROM_CompatibleFinder proto as the framework from which to create your finder frame. Although ROM_CompatibleFinder provides most of the services that ROM_SoupFinder does, it does not respond to messages sent by the system when the user files, deletes, or moves items in the Find overview. The following methods have the same definitions in the ROM_CompatibleFinder as they have in the ROM_SoupFinder.
C H A P T E R 1 6 Find Although the implementation of a search method is for the most part application specific, some general requirements apply to all search methods. This section describes these requirements and advises you of potential problems your search methods may need to handle. Your search method must be able to search for data in internal RAM as well as in RAM or ROM on a PCMCIA card.
C H A P T E R 1 6 Find Using Your Own Text-Searching Method 16 The following code example illustrates the kinds of tasks you must perform when the StandardFind method is not used. (However, it is strongly suggested that you use the StandardFind method to implement your Find routine, if possible.) This example searches for text in soup-based application data using the ROM_SoupFinder proto: // This routine MUST be named Find; it is called by // the system when the user chooses Find. MyApplicationBase.
C H A P T E R 1 6 Find Finding Text With a ROM_CompatibleFinder 16 The following example shows how to use the ROM_CompatibleFinder proto to search for text in application data that is not soup based. The sample code immediately following doesn’t contain code that actually searches application data, because the implementation of such a search would be specific to the data type used to store the application data. MyAppplicationBase.
C H A P T E R 1 6 Find // We may also add slots here... }; // Append myFinder frame to system’s results array AddArraySlot(results, myFinder); end; Implementing the DateFind Method 16 Date-based searches have a lot in common with their text-based counterparts; in fact the only significant difference between these two operations is the search criteria. Rather than matching a text string, the DateFind method tests items against a time value according to the value of the findType parameter.
C H A P T E R 1 6 Find querySpecFrame := { dateBefore : { indexPath : 'timeStamp, endKey: findTime, }, dateAfter : { indexPath : 'timeStamp, beginKey: findTime, }, dateOn : { indexPath : 'timeStamp, beginKey: kOneDay * (findTime div kOneDay) , endKey: kOneDay + kOneDay * (findTime div kOneDay) , } }; local querySpec := querySpecFrame.(findType); // Get the cursor. myCursor := mySoup:Query(querySpec); // Set up finder frame and add it to the results // array.
C H A P T E R 1 6 Find limit a Find operation to certain data sets of an application. For example, a personal finance program may have a check ledger, an account list, and a credit card charges list. Another example is an online sales catalog program that could allow users to separately search different catalogs.
C H A P T E R 1 6 Find Note Applications implementing these methods must also implement the usual Find and DateFind methods since a find operation may be dispatched as other than a Selected find. ◆ Returning Search Results 16 After constructing the finder frame, your search method needs to append it to the system-supplied results array. Each element in this array is a finder frame.
C H A P T E R 1 6 Find Your FindSoupExcerpt method may also extract extra information if the finder frame has been set up to hold additional data. For example, if the date associated with each found item was saved, you could use this information to build more descriptive titles for overview items. The following example shows the implementation of a simple FindSoupExcerpt method: myApplication.FindSoupExcerpt:= func(entry, myFinder) begin //We simply return the string in our entry’s name slot entry.
C H A P T E R 1 6 Find In the body of this method, you need to do whatever is necessary to display the soup entry myEntry. Typically, you first send a Close message to the Overview and then open the view that displays the entry. The following code fragment shows the implementation of a typical ShowFoundItem method. // For use with ROM_SoupFinder proto myApplication.
C H A P T E R 1 6 Find begin myApp:Open(); myApp:ShowFoundItem (items[index], self); end; end, .... } Replacing the Built-in Find Slip 16 Applications can replace the system-supplied Find slip with a customized version, which is called when the application is frontmost. To implement a custom Find slip that displays in your application, include a method named CustomFind in the application’s base view.
C H A P T E R 1 6 Find The following code fragment shows how to use the statusView parameter to display a progress message to the user: MyAppplicationBase.Find:= func(what, results, scope, statusView) begin if statusView then statusView:SetMessage("Searching in" & GetAppName(kAppSymbol)& $/u2026); ...
C H A P T E R 1 6 Find Summary 16 Finder Protos 16 mySoupFinder:= { // Use to find soup entries.
C H A P T E R 1 6 Find myCompatibleFinder:= {// Use to find data stored in // non-soup data structures. //Override most to fit your data. _proto: ROM_CompatibleFinder, owner:self, // Required. View that gets ShowFoundItem // message;usually your app's base view. title: "My Application",// Displayed in Find overview; // usually inherited from owner. findType:'text// Can also be 'dateBefore, //'dateOn, or 'dateAfter. findWords:[textOrDate]// Text or date to find.
C H A P T E R 1 6 Find Functions and Methods 16 RegFindApps(appSymbol) //registers app. for global & //selected finds UnRegFindApps(appSymbol) //unregs.
C H A P T E R Figure 17-0 Table 17-0 1 7 Additional System Services 17 This chapter discusses system services not covered elsewhere in this book. The topics covered in this chapter are ■ Providing the capability to undo and redo user actions. ■ Using idler objects to perform periodic operations. ■ Using the notification service to respond to soup, folder, or user configuration change messages.
C H A P T E R 1 7 Additional System Services a function object to redo the original function or method. Thus tapping the Undo button twice completes an undo/redo cycle. Undo Compatibility 17 The user interface standards for version 2.0 of the Newton operating system call for the user’s second tap on the Undo button to provide a Redo rather than a second level of Undo. Your undo action must create an undo action for itself to implement this interface.
C H A P T E R 1 7 Additional System Services Online Help 17 Your application can provide a protoInfoButton view that displays customized online help to the user (or a newtInfoButton if working in the NewtApp framework). Help can also be displayed from the Intelligent Assistant. For a complete description of how to create a help book and integrate it with your application, see version 2.0 of the Book Maker User’s Guide. For a description of the protoInfoButton, see Chapter 7, “Controls and Other Protos.
C H A P T E R 1 7 Additional System Services Figure 17-2 Alarm slip with Snooze button Periodic Alarms 17 The periodic alarm service sends messages to your application at a specified time. This can be used, for example, by an email client application to periodically log on to a server to check for incoming messages. The interface to the periodic alarm service is the system-supplied protoPeriodicAlarmEditor, shown in Figure 17-3.
C H A P T E R 1 7 Additional System Services Alarms Compatibility 17 All alarm information described here is new to the Newton 2.0 system. Alarm functionality for 1.x devices is provided by the NTK platform file. See the platform file release notes for the 1.x platform for important compatibility information. Progress Indicators 17 This section describes the automatic busy cursor, the notification icon, and the status slip, which you can use to provide feedback to the user during lengthy operations.
C H A P T E R 1 7 Additional System Services Status Slips With Progress Indicators 17 For complex operations requiring more user feedback than the automatic busy cursor offers, you can provide a status slip. You can use the DoProgress function to call the function that implements that operation. The DoProgress function displays a status slip with graphical progress indicators and informative messages. Figure 17-6 depicts a typical progress slip displayed by the DoProgress global function.
C H A P T E R 1 7 Additional System Services Power Registry 17 The Power Registry implements a cooperative model for powering the Newton on and off. When power is turned on or off, this service ■ notifies registered applications of the impending change in power status ■ allows applications to temporarily halt the shutdown process ■ executes registered callback functions The Power Registry model is based on the registration of callback functions to execute when the Newton is powered on or off.
C H A P T E R 1 7 Additional System Services Using Undo Actions 17 The following code example shows how to provide undo capability in a view. Imagine you have a view that uses cards. The view has a particular method, DeleteCard, that it uses to delete a card. Within the DeleteCard method, you call the AddUndoAction method, passing as its arguments the name of the card deleted and a different method that will add the card (thereby undoing the delete operation).
C H A P T E R 1 7 Additional System Services Avoiding Undo-Related “Bad Package” Errors 17 The AddUndoAction method saves the current context (self) so that later it can send the “redo” message (the argument to the methodName parameter of the AddUndoAction method) to the appropriate object. As a result, it is possible that references to your application can stay in the system inside the Undo mechanism’s data structures after the application has been removed.
C H A P T E R 1 7 Additional System Services Note Do not install idler objects having idle time intervals of less than 100 milliseconds.
C H A P T E R 1 7 Additional System Services Using Alerts and Alarms 17 This section describes the use of functions and methods that provide alerts and alarms, and the protoPeriodicAlarmEditor. Using the Notify Method to Display User Alerts 17 The Notify method offers a simple way to display a message to the user. This method takes three arguments. The first specifies which type of alert is displayed; some alerts beep, some only log their notice instead of displaying it, and so on.
C H A P T E R 1 7 Additional System Services The following code example adds an alarm set to execute in five minutes: AddAlarm("Alarm1:MyApp:MySig", Time()+5, ["Title String","Message String"], nil, nil); The first argument is the alarm key (which this function call returns). The second is when the alarm is to execute. The third is an array of strings to use as arguments to the AlarmUser function that displays the alarm slip.
C H A P T E R 1 7 Additional System Services The following code example removes all alarms an application has scheduled for the next five minutes: foreach alarmKey in GetAppAlarmKeys(":MyApp:MySig") do if not (GetAlarm(alarmKey).time > Time() + 5) then RemoveAlarm (alarmKey); Removing Installed Alarms 17 The functions RemoveAlarm and RemoveAppAlarms remove a particular alarm and all of an application’s alarms, respectively.
C H A P T E R 1 7 Additional System Services In any case, debugging your callback function is difficult because any exceptions it raises are caught and ignored by the alarm mechanism. Thus, you need to debug your callback functions thoroughly before passing them to the AddAlarm function. Since your application may not be open, or even installed when its alarm executes, your code needs to handle these eventualities appropriately.
C H A P T E R 1 7 Additional System Services 2. Define another method in your application’s base view named PeriodicAlarm. This method is called whenever the alarm “goes off.” This method is passed a single parameter, alarm, that contains information about the present alarm. For information on the alarm parameter, see PeriodicAlarm in Newton Programmer’s Reference. 3. Create a view that is based on protoPeriodicAlarmEditor.
C H A P T E R 1 7 Additional System Services To add an action to the notify icon and display it, call the AddAction method as in the following example: myFunc := func() GetRoot():SysBeep(); theAct := GetRoot().notifyIcon:AddAction("Beep", myFunc, nil); You can remove an action by calling the KillAction method—for example, if your task in progress completes while the protoStatusTemplate view is hidden, you should close the status view and remove the action from the notify icon's menu.
C H A P T E R 1 7 Additional System Services performing the myFunc function, pass it as the value of the workFunc parameter to the DoProgress function, as illustrated in the following code fragment: // options and data are accessible from workFunc because // the workFunc "closes over" this context myOpts := { wFnData:"Confabulating", closebox:nil, icon: kMyIcon, statusText: kAppName, gauge: 10, titleText:"One moment, please."}; workFunc := func (theContextView) begin for x := 1 to 10 do begin myOpts.
C H A P T E R 1 7 Additional System Services The code above shows the two ways in which your code can respond when the user cancels the operation. If the user taps the Stop button an exception is thrown by SetStatus. You may catch this exception and perform any clean-up necessary. (In the code above the all-inclusive |evt.ex| onexception clause catches this exception.) You must, however, rethrow this exception so the system can perform its own cleanup, otherwise the Newton device appears to hang.
C H A P T E R 1 7 Additional System Services 2. Open the status slip. There are three parts to this process: ■ Instantiate your status view by passing its template to the BuildContext function. ■ Initialize the status slip by passing the template’s setup frame to the status slip’s ViewSet method. ■ Invoke the status slip’s Open method to display the slip. 3.
C H A P T E R 1 7 Additional System Services Figure 17-8 Built-in status view configurations statusText icon progress statusText icon titleText primary primary vStatus closeBox vProgress closeBox vGauge closeBox vBarber closeBox statusText statusText icon icon gauge titleText titleText primary primary vStatusTitle closeBox statusText statusText icon icon barber secondary titleText primary primary vConfirm closeBox If you want to use a system-supplied template, you can simply
C H A P T E R 1 7 Additional System Services includes an InitialSetup frame initializes this view automatically before it opens.
C H A P T E R 1 7 Additional System Services initialSetup: // used to initialize view automatically { name: 'vMyBarber, appSymbol: kAppSymbol, values: { icon: kDummyActionIcon, statusText: "Computing IsHalting…", closeBox: func() begin base:Hide(); //close the status view //add an action to the Notify Icon, this allows //the user to reopen the status view, which is //necessary to allow the user to cancel the //operation...
C H A P T E R 1 7 Additional System Services And be sure to include this in your application’s ViewQuitScript to get rid of the notify icon’s action: if theNotifyIconAction then begin GetRoot().
C H A P T E R 1 7 Additional System Services Because the ViewSet method rebuilds and updates all the status slip’s child views, you’ll obtain better performance by calling UpdateIndicator rather than ViewSet when you just need to update the gauge view. The UpdateIndicator method rebuilds and updates only the gauge, barber pole, and progress sheet views.
C H A P T E R 1 7 Additional System Services Registering Login Screen Functions 17 If you want a power-on function that brings up some sort of visible component, you should register that function as login function. These functions are only called after the login screen has been displayed and the password entered (if the user has installed a password). Note that future Newton devices may not support the login screen. In this case the login functions will still be executed.
C H A P T E R 1 7 Additional System Services communications endpoint, it can return the 'holdYourHorses symbol to delay shutdown. After completing the task for which you delayed shutdown, you must call the PowerOffResume function as soon as possible to resume the poweroff sequence. Returning nil in response to the 'powerOff symbol allows the power-off sequence to continue. Your callback function must return the value nil in response to any symbols other than those described here.
C H A P T E R 1 7 Additional System Services Summary of Additional System Services 17 This section summarizes the services documented in this chapter.
C H A P T E R 1 7 Additional System Services Functions and Methods 17 myApp:AlarmsEnabled() //call PeriodicAlarms? myApp:PeriodicAlarms(alarm) //called when periodic alarm //triggers AddAlarm(alarmKey,time,argsArray,callBackFn,callBackParams) //adds //an alarm AlarmUser(title, message) //brings up slip RemoveAlarm(alarmKey) //removes alarms GetAlarm(alarmKey) //gets an alarm GetAppAlarmKeys(alarmKeySuffix) //gets an app’s alarm keys RemoveAppAlarms(alarmKeySuffix) //removes an app’s alarms view:Notify(
C H A P T E R 1 7 Additional System Services Power Registry 17 Functions and Methods 17 BatteryCount() //returns battery count BatteryStatus(which) //returns info about battery RegPowerOff(callbackID,callBackFn) //registers a power-off //callback fn. UnRegPowerOff(callBackID) //unregisters a power-off //callback fn. PowerOffResume(appSymbol) //resumes power-off sequence RegPowerOn(callbackID,callBackFn) //registers a power-on //callback fn.
C H A P T E R Figure 18-0 Table 18-0 1 8 Intelligent Assistant 18 The Intelligent Assistant is a system service that attempts to complete actions specified by the user’s written input. You can think of the Assistant as an alternate interface to Newton applications and services. The Assistant can use the built-in applications to complete predefined tasks such as calling, faxing, printing, scheduling, and so on. You can also program the Assistant to execute any task that your application performs.
C H A P T E R 1 8 Intelligent Assistant templates may be supplied by the system or by your application. Some systemsupplied templates make use of lexical dictionaries, which are also supplied by the system. For more information about lexical dictionaries, see Chapter 9, “Recognition.” Depending on the amount of information that parsing the input string provides, the Assistant either attempts to complete a task or prompts the user to supply additional information.
C H A P T E R 1 8 Intelligent Assistant Figure 18-1 Assist slip When prompted by the Assist slip, the user must provide additional information on its input line or choose an action from the Please picker. The top portion of the Please picker displays all of the actions currently registered with the Assistant. The Please picker is shown in Figure 18-2.
C H A P T E R 1 8 Intelligent Assistant To allow the user to repeat recent actions easily, the bottom portion of the Please picker displays the eight strings most recently passed to the Assistant. Thus, the string "ring Maurice" appears here, even though the action of placing a phone call is represented only by the verb "call" in the top portion of the picker.
C H A P T E R 1 8 Intelligent Assistant Programmer’s Overview 18 This section describes how the templates, frames and methods used by the Assistant interact to provide services to the user. You can think of any user operation as a set of one or more actions to complete. A single action is represented to the Assistant by an action template. You can use action templates supplied by the system and you can also define your own action templates. Some actions require data or objects on which to operate.
C H A P T E R 1 8 Intelligent Assistant Your task template designates one action template as its primary action. The primary action is the one that the Assistant associates with a specified verb in its input string. The primary action is represented by an action template that resides in the task template’s primary_act slot. Because task templates do not provide lexicons, the designation of a primary action provides the Assistant with a way to associate a verb in the input string with a task template.
C H A P T E R 1 8 Intelligent Assistant Figure 18-4 Simplified overview of the Assistant’s matching process Parse raw input Call For Bob Lexical matching & tokenization Action Template call_act := { isa: 'action, value: "call action", Lexicon: ["yo", "call", "phone", "ring"], …} Because "for" is not matched, it is added to the noisewords array. If a target is not found in the original parse, your PostParse method can try to extract it from the task frame or the appropiate soup.
C H A P T E R 1 8 Intelligent Assistant You define the PostParse method in your task template. Your PostParse method must perform any actions required to complete the primary task. The PostParse method usually acts as a dispatching method that executes the subtasks comprising the primary action. In doing so, the PostParse method may validate data and retrieve information that the Assistant was unable to find on its own.
C H A P T E R 1 8 Intelligent Assistant "555-1234" as having the format of a telephone number. Based on that information, the Assistant creates a task frame from the built-in call_act template and displays a call slip to prompt the user for additional information. When no action template is matched, or more than one is matched, the Assistant compares the number of matched target templates for each task with the total number of targets for that task.
C H A P T E R 1 8 Intelligent Assistant The Signature and PreConditions Slots 18 Your task template must define two slots, called signature and preConditions, which store arrays of templates and symbols, respectively. The signature slot holds action templates and target templates that must be matched to complete the primary action. The preConditions slot specifies the names of slots that the Assistant creates in the task frame as templates in the signature slot are matched.
C H A P T E R 1 8 Intelligent Assistant The Assistant creates a slot in the task frame only when a template is matched. For example, if the when_obj template is not matched, the when slot is not created. If any frame represented in the signature array is not present (that is, if its lexicon was not matched) the Assistant may still call your PostParse method if it can match an action frame with your task template’s primary action.
C H A P T E R 1 8 Intelligent Assistant value "Bob Anderson", that element of the phrases array stores the entire string "Bob Anderson", as the following code fragment shows: // input string is "call bob anderson" {… phrases: ["bob anderson", "call"], …} Note that strings may appear in the phrases array in a different order than they did in the original input to the Assistant.
C H A P T E R 1 8 Intelligent Assistant Resolving Template-Matching Conflicts 18 Template matching conflicts may arise when a template’s lexicon includes a word that appears in the lexicon of another registered template. This section describes the means by which the Assistant attempts to resolve such conflicts. When a verb matches more than one action template, the Assistant must choose the appropriate action template.
C H A P T E R 1 8 Intelligent Assistant If you specify the 'dyna_user_action symbol as the first element of your task template’s signature slot, any target that distinguishes one template from another enables the Assistant to select the correct template.
C H A P T E R 1 8 Intelligent Assistant Using the Assistant 18 This section describes how to make an application behavior available through the Assistant, as well as how to display online help from the Assistant. This material presumes understanding of the conceptual material provided in previous section. Making Behavior Available From the Assistant 18 You need to take the following steps to make an application behavior available through the Assistant: 1.
C H A P T E R 1 8 Intelligent Assistant 5. Define the words or phrases this template is to match as an array of strings in its lexicon slot. If you place the name of a system-supplied template in your template’s isa slot, your template inherits its lexicon from the system-supplied template. You should be aware, however that isa slot values other than the symbols 'dyna_user_action and 'dyna_user_obj may interfere with the system’s ability to match your template successfully.
C H A P T E R 1 8 Intelligent Assistant Based on the definition above, you can derive a my_other_action template that holds the value 'my_action in its isa slot, as in the following example: my_other_action := { // name of this action value: "my other action", // subclass of 'dyna_user_action isa: 'my_action, // words matching this action lexicon: ["leap", "lunge"] } You can take a similar approach to define your own target object types by placing the 'dyna_user_obj symbol in your target template’s isa
C H A P T E R 1 8 Intelligent Assistant Sample PostParse Method 18 The following code fragment is an example of a PostParse method that tests for the existence of the value slot and accesses its content: PostParse: func() begin local thePhraseText; // self is the task frame if hasSlot(self, 'value) then thePhraseText := self.
C H A P T E R 1 8 Intelligent Assistant preConditions array is related to the first element of the signature array, the second element of the preConditions array is related to the second element of the signature array, and so on. For more information, see the section “The Signature and PreConditions Slots” (page 18-10). 9. Place the value nil in the score slot. This slot is used internally by the Assistant. Sample Task Template 18 The following code fragment is an example of a task template.
C H A P T E R 1 8 Intelligent Assistant 2. Define an action template for opening the appropriate help book. The global functions ShowManual and OpenHelpTo open the system-supplied help book. The OpenHelpBook and OpenHelpBookTo functions open a help book that you supply. The ShowManual function is described in “Utility Functions” (page 26-1). All of these functions are described in version 1.1 of the Newton Book Maker User’s Guide . 3.
C H A P T E R 1 8 Intelligent Assistant Summary 18 Data Structures 18 Task Frame 18 // Returned by ParseUtter function { // original user input phrase origphrase: ["str1", "str2", … "strN"], // strings that matched registered templates phrases: ["aStr1", "aStr2", … "aStrN"], // strings that did not match registered templates noisewords: ["noiseStr1", "noiseStr2", … "noiseStrN"], // Aliases to soup entries that were matched // You must use GetMatchedEntries fn to retrieve entries: [alias1, alias2, …
C H A P T E R 1 8 Intelligent Assistant // Optional. View template that defines task slip taskslip : myTaskSlipView, // internal use only - always put nil in this slot score: nil, // your additional slots and methods …} Action Template 18 // defines action words to Assistant my_act := { // string may be replaced in lexical parse value: string , //Required. // object type that this template creates // must use this value or one descended from it isa: 'dyna_user_action, // Required.
C H A P T E R 1 8 Intelligent Assistant System-Supplied Action Templates 18 // base your action templates on this generic action dyna_user_action:= { // this template has no lexicon …} // Action template for dialing the telephone call_act:= { // Words or phrases to match with this template // lexicon: ["call", "phone", "ring","dial"], …} // Action template for using the Find service.
C H A P T E R 1 8 Intelligent Assistant // Action template for creating To Do items remind_act := { lexicon: ["remember", "remind", "remind me", "to do", "todo", "don't forget to", "don't let me forget to"], …} // Action template for sending electronic mail mail_act := { lexicon: ["mail", "send", "email"], …} // Action template for scheduling meetings // and events in the Dates application schedule_act := { lexicon: ["schedule"], …} // Action template for scheduling meetings // and events in the Dates ap
C H A P T E R 1 8 Intelligent Assistant // Action template for scheduling lunch in Dates app lunch_act := { isa: 'meal_act, usualTime:"12:00 pm", lexicon: ["lunch"], …} // Action template for scheduling dinner in Dates app dinner_act := { isa: 'meal_act, usualTime:"7:00 pm", lexicon: ["dinner"], …} Special Events 18 birthday := { isa: 'special_event_act, Lexicon: ["birthday","bday","b-day"], …} anniversary := { isa: 'special_event_act, Lexicon: ["anniversary"], …} holiday := { isa: 'special_event_act,
C H A P T E R 1 8 Intelligent Assistant System-Supplied Target Templates 18 Places 18 // list of system-supplied where_obj target templates // system uses lexical dictionaries to match these // templates so they do not provide lexicons address, city, region, country, postal_code, phone,parsed_phone, phone_tag, faxPhone, homePhone, workPhone, carPhone, mobilePhone, beeper, places, company, city, county, state, country, town, province Times 18 // list of system supplied when_obj frames // system uses
C H A P T E R 1 8 Intelligent Assistant People 18 person := { // generic person template isa: 'who_obj, value: nil // system use only …} title := { // "owner", "manager", and so on isa: 'who_obj, …} affiliate:= { // "friend", "brother", "sister", and so on isa: 'person, …} group := { // "Engineering", "Marketing", and so on isa: 'person, …} custom := { // customized 'person template isa: 'person, …} Miscellaneous 18 salutationPrefix := { ISA: 'parser_obj, Lexicon: ["dear", "to", "attention", "attn",
C H A P T E R 1 8 Intelligent Assistant Developer-Supplied Functions and Methods taskFrame:PostParse() // called after input is parsed Application Base View Slots viewHelpTopic 18-28 Summary 18 // topic in help book 18
C H A P T E R Figure 19-0 Table 19-0 1 9 Built-in Applications and System Data 19 This chapter describes the interfaces to the built-in applications. It also describes the soup formats used by the built-in applications and the soup format of the System soup. You should read the appropriate section of this chapter if your application needs to interact with any of the built-in applications, receive faxes, use auxiliary buttons, or access system data.
C H A P T E R 1 9 Built-in Applications and System Data IMPORTANT Soup formats are subject to change. Applications that rely on soup formats risk incompatibility with future versions of Newton software. To avoid future compatibility problems with soup format changes, you should use the methods provided by the built-in applications (if any exist) or the global functions GetSysEntryData and SetSysEntryData to get or change entries in any of the built-in soups.
C H A P T E R 1 9 Built-in Applications and System Data Figure 19-1 Names application Card and All Info views Names Compatibility 19 All the Names methods, variables, and constants are new in this version. The 'group, 'owner, and 'worksite types are new. The 'person and 'company types include many new slots. The Names application converts incoming soup entries that contain 1.x data into soup entries that conform to the 2.0 data format.
C H A P T E R 1 9 Built-in Applications and System Data Using the Names Application 19 This section describes ■ adding a new type of card to the Names application ■ adding a new data item to a card ■ adding a new card layout style ■ using the Names methods ■ using the Names soup ■ using two protos with pickers for personae and emporia Adding a New Type of Card 19 The New button on the Names status bar creates its picker by looking at the registered dataDefs for the Names application.
C H A P T E R 1 9 Built-in Applications and System Data Here is an example of an infoFrame for a Names viewDef defining a view that has two fields, Make and Model: infoFrame:{checkPaths: '[carMake, carModel], checkPrefix: '[true, [pathExpr: carInfo]], stringData: nil, format: "^?0Make: ^0\n||^?1Model: ^1||" } When chosen from the Add picker the first time, this view initially fills in the carMake and carModel slots in the soup entry with the user’s entries.
C H A P T E R 1 9 Built-in Applications and System Data The bizCardIcon slot contains an icon representing the new layout, to be shown in the Card Style view, where the user can change the type of card layout to use for a particular card. This icon should be 38x23 since this is the size of the built-in icons. Adding New Layouts to the Names Application 19 The Show picker allows the user to chose from the two built-in layouts: Card and All Info.
C H A P T E R 1 9 Built-in Applications and System Data ■ get information from Names soup entries ■ for credit/phone card information (BcCreditCards) ■ for custom fields information (BcCustomFields) ■ for e-mail address information (BcEmailAddress) ■ for e-mail network information (BcEmailNetwork) ■ for phone number information (BcPhoneNumber) These functions and methods are all described in Newton Programmer’s Reference.
C H A P T E R 1 9 Built-in Applications and System Data The diamond appears only if there is more than one owner card; otherwise you see just a name without a diamond. Tapping the name produces a picker showing the names of all owner cards stored by the Names application in this Newton device. protoEmporiumPopup 19 This proto is used for a picker that lets the user maintain and switch between different information relevant to various locations where she may be.
C H A P T E R 1 9 Built-in Applications and System Data Figure 19-2 Dates application Day and Day’s Agenda views Meetings and events can repeat. That is, they can recur on one or more days in addition to the original meeting or event date. The application is called Dates, because that is what the user sees, but in programming the term “calendar” is used interchangeably and appears in the code.
C H A P T E R 1 9 Built-in Applications and System Data ■ In addition to changes in the programmatic interface, the 2.0 version has extensive changes in the user interface. ■ In system software version 1.x, the Dates application allowed notes (text and graphics) to be written without an associated meeting marker. In system software 2.0, such notes, previously called annotations, cannot be written. Annotations imported via Newton Connection Kit from a 1.x system are still visible and editable, however.
C H A P T E R 1 9 Built-in Applications and System Data Adding Meetings or Events 19 You can programmatically add meetings and events by using the AddAppointment and AddEvent methods. You should use these methods rather than adding entries in the Dates soups directly. Here are some examples of adding meetings. Note that the parameters to AddAppointment are (mtgText, mtgStartDate, mtgDuration, repeatPeriod, repeatInfo). ■ To schedule a one-hour lunch appointment: GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data Deleting Meetings and Events 19 The Dates application provides three methods for deleting meetings or events: DeleteAppointment, DeleteRepeatingEntry, and DeleteEvent. These three methods all take the same parameters, as in DeleteAppointment(mtgTextOrFrame,mtgStartDate,deleteOneOnly).
C H A P T E R 1 9 Built-in Applications and System Data ■ To delete a single instance of the repeating event created in “Adding Meetings or Events”: GetRoot().calendar:DeleteEvent ("George's birthday", StringToDate("2/22/95"), true); ■ To delete the whole series of George’s birthdays by passing in a meeting frame for a repeating meeting: GetRoot().calendar:DeleteEvent ( GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data [StringToDate("6/1/95 12:00am"), StringToDate ("6/30/95 11:59pm")], nil, nil); ■ To find the unique meeting in the month of June with the word “lunch” in the title or the notes, and handle the possibility of an exception being thrown if this criterion is not unique: try GetRoot().calendar:FindExactlyOneAppointment (nil, '["lunch"], [StringToDate("6/1/95 12:00am"), StringToDate("6/30/95 11:59pm")], nil); onexception |evt.
C H A P T E R 1 9 Built-in Applications and System Data ■ To move a meeting half an hour earlier and give it a different (90 minute) duration: GetRoot().calendar:MoveAppointment( "lunch with Ellen", StringToDate("6/30/95 12:00pm"), StringToDate("6/30/95 11:30am"), 90); MoveOnlyOneAppointment works just like MoveAppointment except that if it finds a nonexception instance of a repeating meeting or event that fits the criteria, it moves only that instance.
C H A P T E R 1 9 Built-in Applications and System Data ■ Get or set the meeting icon type with GetMeetingIconType and SetMeetingIconType. The remainder of this section presents sample code that uses these methods. You may wish to look at the summary section at the end of this chapter to see what the parameters to these methods are. // useful abbreviations cal := GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data // get the notes of the last meeting. If there are no // meeting notes, GetMeetingNotes returns nil meetingNotes := cal:GetMeetingNotes(mtgName, appDueDate); // add a paragraph to these notes, then set the meeting // notes to this new array. Note, how care is taken // not to overwrite any existing notes.
C H A P T E R 1 9 Built-in Applications and System Data and a frame containing the definition of the new meeting type. This frame has the following slots; see “RegMeetingType” (page 16-48) in Newton Programmer’s Reference for full details: Slot description item icon NewMeeting smallIcon OpenMeeting memory Required. A string that is the meeting type name to appear in the New picker. Required. The icon shown in the New picker. It should be no larger than 24x15 pixels. Required.
C H A P T E R 1 9 Built-in Applications and System Data Examples of Creating New Meeting Types 19 The following example code registers a new meeting type for a monthly meeting: GetRoot().calendar:RegMeetingType ( '|MonthlyMeeting:MySig|, { item: "Monthly Meeting", icon: myIcon, smallicon: mySmallIcon, NewMeeting: func(date, parentBox) begin local appt:= GetRoot().calendar :AddAppointment ("",date, 60, 'monthly, nil); appt.
C H A P T E R 1 9 Built-in Applications and System Data local slip := BuildContext( {_proto: protoFloater viewFlags:vClickable + vFloating + vApplication + vClipping, viewJustify:0, viewBounds:SetBounds ( parentBox.left+40, parentBox.top+40, parentBox.right-40, parentBox.
C H A P T E R 1 9 Built-in Applications and System Data ■ OpenMeetingSlip opens the meeting slip for a specific meeting or event. ■ RegInfoItem adds and UnRegInfoItem or deletes an item in the Info picker in the base view of the Dates application. This example shows how to add a command that displays the next day’s To Do List to the Info button: GetRoot().calendar:RegInfoItem('|NextDayToDo:MyApp|, { item: "Next Day's To Do", doAction: func() begin local cal := GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data Using the Dates Soups 19 The Dates application stores meeting and event information and notes in the following soups: Soup (name string) Description ROM_CalendarSoupName Entries are meeting frames for nonrepeating meetings.
C H A P T E R 1 9 Built-in Applications and System Data Figure 19-3 The To Do List application To Do List Compatibility 19 Version 2.0 reads and converts all 1.x To Do List soups. It does not reproduce styling of text, because 2.0 doesn’t support styling. It does not allow shapes and sketches in a task, so shapes and sketches are thrown away. Because the internal structure of the 2.0 To Do List soup is completely different from that of the 1.x version, when you transmit a 2.0 soup to a 1.
C H A P T E R 1 9 Built-in Applications and System Data Also, note that some of these methods only work when the To Do List is open. You can ensure the To Do List is open by calling the Dates method DisplayDate passing in 'toDoList for the format parameter as in the following code: //open Dates and make it show today’s To Do List GetRoot().calendar:Open(); GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data GetToDoItemsForThisDate returns an array of tasks. Tasks are elements of the array stored in the topics slot of a day’s soup entry. For the structure of these frames, see “To Do List Soup Format” (page 16-77) in Newton Programmer’s Reference. The following code example obtains today’s tasks: todaysTasksArray := GetRoot().calendar:GetToDo(): GetToDoItemsForThisDate(time()); GetToDoEntry returns an array of soup entries for a specific day.
C H A P T E R 1 9 Built-in Applications and System Data begin theTask := todaysTasksArray[i]; theIndex := i; end; //and mark it as done GetRoot().calendar:GetToDo(): SetDone(theIndex,theTask,true,nil,nil); The third parameter to SetDone determines whether a task is checked off; passing nil unchecks it. Miscellaneous To Do List Methods 19 The To Do List also provides the following methods: ■ GetTaskShapes and GetToDoShapes return the shapes necessary to draw tasks, which are used for printing.
C H A P T E R 1 9 Built-in Applications and System Data of slots in a soup entry. If you don’t use these functions to get and set entry slots in the built-in soups, your application may break under future versions of system software. Time Zones 19 This section describes the Time Zones API. The Time Zones application is shown in Figure 19-4.
C H A P T E R 1 9 Built-in Applications and System Data Using the Time Zone Application 19 The application program interface provides functions for retrieving information about cities and countries, a method to add a city to a Newton device’s list of cities, and a method to set the home city. To call a Time Zones method, you need a reference to the application. To obtain this reference, use the following code: GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data though that the list of cities and countries is not necessarily the same on your Newton device and the user of your application. Your application should also check string names for cities and countries entered by the user. The GetCountryEntry function performs an additional search based on the class of the string passed in. This is done in order to take into account the language of the ROM used; the symbols are all in English.
C H A P T E R 1 9 Built-in Applications and System Data areaCode: "503", region:"OR", airport:"PDX"} Using Longitude and Latitude Values 19 To calculate the latitude or longitude of a location, create and use the following function: CalcLngLat := func(dgrs, min, secs, westOrSouth) begin local loc; loc := dgrs / 180 + min / (180 * 60) + secs / (180 * 60 * 60); loc := rinttol(loc * 0x10000000); if westOrSouth then loc := 0x20000000 - loc; loc; end; The built-in utility functions LatitudeToString and Lo
C H A P T E R 1 9 Built-in Applications and System Data Figure 19-6 Notes note and Checklist views About the Notes Application 19 Notes is a simple application based on NewtApp that allows the user to create new stationery, scroll up and down, route and file notes, and scan an overview. The Notes API is limited to a few methods which allow you to create new notes. The Notes application can be extended by adding auxiliary buttons, as described in “Auxiliary Buttons” beginning on page 19-36.
C H A P T E R 1 9 Built-in Applications and System Data Using the Notes Application 19 This section describes the methods that add new notes, and the Notes soup format. To obtain a reference to the Notes application in order to send it messages, use the following code: GetRoot().paperroll Note that future Newton devices may not include the Notes application. You should therefore check for the existence of the Notes application before trying to access it.
C H A P T E R 1 9 Built-in Applications and System Data points :ArrayToPoints ([11, // a rectangle 5, //how many points 0,0, //first point 0,25, //second 150,25,//third 150,0,//fourth 0,0]),//back home viewBounds : {top:0, left:0, right:100, bottom:100}} ]; //Add the note to the Notes application notes:NewNote ( theNote, true, nil); This creates the note shown in Figure 19-7.
C H A P T E R 1 9 Built-in Applications and System Data Detailed information on the data structures that support these stationeries is provided in “Notes Soup Format” (page 16-82) in Newton Programmer’s Reference. A list of these frames is available in the Summary; see “Notes Soup” (page 19-53). To avoid future compatibility problems with soup format changes, you should use the global functions GetSysEntryData and SetSysEntryData to make change entries in any of the built-in soups.
C H A P T E R 1 9 Built-in Applications and System Data body within the In/Out Box soup entry, where a user can view it. Applications may be passed an In/Out Box soup entry as part of the putting away process. For more information on handling items coming from the In/Out Box, see “Receiving Data” beginning on page 21-31 in Newton Programmer’s Guide. The structure of the body frame is described in “Fax Soup Entries Reference” (page 16-94) in Newton Programmer’s Reference.
C H A P T E R 1 9 Built-in Applications and System Data Prefs and Formulas Compatibility 19 The functions RegPrefs, UnRegPrefs, RegFormulas, and UnRegFormulas are new to the 2.0 system. Using the Prefs and Formulas Interfaces 19 This section describes how to add panels to the Prefs and Formulas rolls. Adding a Prefs Roll Item 19 The RegPrefs function adds a panel to the Prefs rolls. This roll is not intended for application-specific preferences, but rather for system-wide preferences.
C H A P T E R 1 9 Built-in Applications and System Data Figure 19-9 The Notes application with and without an auxiliary button Using Auxiliary Buttons 19 You can add buttons to the status bars or other locations in the Notes and Names applications. Your application may also use this mechanism to allow itself to be extended. RegAuxButton and UnRegAuxButton are the functions that add and remove a button from the auxiliary button registry; they are called by button providers.
C H A P T E R 1 9 Built-in Applications and System Data Any application that adds buttons to another application should provide a preference that allows the user to enable or disable the display of the source application buttons in the destination application. The user may want to suppress buttons because the buttons from several source applications may be too many to fit in a single destination application.
C H A P T E R 1 9 Built-in Applications and System Data This section also covers creating a cursor that iterates over icons in the Extras Drawer, and a number of functions that manipulate the entries these cursors iterate over. With these functions you can programmatically open an icon (which has the same effect as a user tapping the icon), and get information about the package the icon represents. In addition, the Newton 2.
C H A P T E R 1 9 Built-in Applications and System Data Using Extras Drawer Cursors 19 The Extras Drawer method GetPartCursor creates a cursor that can iterate over parts (icons) in the Extras Drawer. You can create a cursor that iterates over parts in a specific store, a particular folder of the Extras Drawer, a particular package, or a combination of these criteria. This cursor is a normal soup cursor, as described in Chapter 11, “Data Storage and Retrieval.
C H A P T E R 1 9 Built-in Applications and System Data InstallScript := func (partFrame) begin local ed := GetRoot().
C H A P T E R 1 9 Built-in Applications and System Data Creating a Script Icon 19 Installation of a script icon is basically the same as that for a soup icon. The two main differences are that the symbol 'scriptEntry is passed in for the iconType parameter of AddExtraIcon, and the paramFrame argument contains different slots. However, with a script icon it is not important to keep this icon in the internal store.
C H A P T E R 1 9 Built-in Applications and System Data InstallScript := func(partFrame, removeFrame) begin local mySlip := GetLayout("MySlip.t") ; // install the slip DefGlobalVar (kMyConfigSlipSym, BuildContext(mySlip)); local ed := GetRoot().extrasDrawer; //Figure out which store our package is in. This code //will work for a form part, as long as the argument //to ObjectPkgRef is a reference type (i.e., a // pointer).
C H A P T E R 1 9 Built-in Applications and System Data 2. Add a frame called soupervisor to your application’s base view. Note that this means you cannot add a soupervisor frame to an autopart unless GetRoot.(kAppSymbol) exists. This frame must have a slot called type. The possible values for the type slot are 'moveOnly Allows a user to move all soup entries to a different store. 'fileOnly Allows a user to file all soup entries to a different folder.
C H A P T E R 1 9 Built-in Applications and System Data Functions for Accessing User Configuration Data 19 The global functions GetUserConfig and SetUserConfig get and set the values of user configuration variables in the system soup. These variables, see “User Configuration Variables” (page 16-101) in Newton Programmer’s Reference. A list of these variables is available in the Summary; see 19 “User Configuration Variables.
C H A P T E R 1 9 Built-in Applications and System Data Summary 19 Constants and Variables 19 Names Card Layouts 19 Constant Value kSquiggle 0 kPlain 1 kSeparate 2 kCross 3 Dates Variables 19 firstDayOfWeek useWeekNumber Dates Constants for the Day of the Week 19-46 Constant Value kSunday 0x00000800 kMonday 0x00000400 kTuesday 0x00000200 kWednesday 0x00000100 kThursday 0x00000080 kFriday 0x00000040 kSaturday 0x00000020 kEveryday 0x00000FE0 Summary 19
C H A P T E R 1 9 Built-in Applications and System Data Dates Constants for repeatType Constant Value kDayOfWeek 0 kWeekInMonth 1 kDateInMonth 2 kDateInYear 3 kPeriod 4 kNever 5 kWeekInYear 7 Other Date Constants Constant Value kForever 0x1FFFFFFF kMaxyear 2919 kYearMissing 2920 Dates Constants for the Weeks in a Month Constant Value kFirstWeek 0x00000010 kSecondWeek 0x00000008 kThirdWeek 0x00000004 kFourthWeek 0x00000002 kLastWeek 0x00000001 kEveryWeek 0x0000001F Us
C H A P T E R 1 9 Built-in Applications and System Data currentCountry currentEmporium currentPersona currentPrinter dialingPrefix doAutoAdd doInkWordRecognition doTextRecognition doShapeRecognition emailPassword faxPhone homePhone leftHanded learningEnabledOption lettersCursiveOption letterInFieldsOption letterSetSelection letterSpaceCursiveOption location mailAccount mailNetwork mailPhone name paperSize paperSizes phone signature speedCursiveOption timeoutCursiveOption userFont Protos 19 protoPerson
C H A P T E R 1 9 Built-in Applications and System Data protoEmporiumPopup 19 myEmporiumPopup := { _proto: protoEmporiumPopup, SetUpText: function,// returns string to display as current // emporium JamIt: function, // calls SetUpText and updates screen ...
C H A P T E R 1 9 Built-in Applications and System Data cardType: integer, name: frame, names: array, company: stringOrRichString, title: stringOrRichString, companies: array, address: stringOrRichString, address2: stringOrRichString, addresses: array, city: stringOrRichString, region: stringOrRichString, postal_code: stringOrRichString, country: stringOrRichString, phones: array, email: stringOrRichString, emailAddrs: array, emailPassword: nil, pagers: array, bday: integerOrStringOrRichString, bdayEvent
C H A P T E R 1 9 Built-in Applications and System Data phones: array, email: stringOrRichString, emailAddrs: array, emailPassword: string, pagers: array, bday: integerOrStringOrRichString, bdayEvent: entryAlias, anniversary: integerOrStringOrRichString, anniversaryEvent: entryAlias, notes: array, sorton: string, owner: frame, ...
C H A P T E R 1 9 Built-in Applications and System Data email: stringOrRichString, emailAddrs: array, notes: array, sorton: string, ...
C H A P T E R 1 9 Built-in Applications and System Data version: integer, viewBounds: frame, exceptions: array, ...} Notes Frames 19 aNotesFrame := { notes: array, repeatingMeetingAlias: entryAlias, ...} To Do List Soup 19 aToDoListEntry := { class: symbol, needsSort: Boolean, date: integer, topics: array, ...} Notes Soup 19 aNotesEntry := { viewStationery: symbol, class: symbol, height: integer, timeStamp: integer, labels: symbol, data: array, topics: array, ...
C H A P T E R 1 9 Built-in Applications and System Data cardfile:BcCreditCards(inEntry, inWhich) // returns the // credit card information cardfile:BcCustomFields(inEntry, inWhich) // returns custom // field information cardfile:BcEmailAddress(entry, which) // returns e-mail // information cardfile:BcEmailNetwork(entry, type)// returns e-mail // network information cardfile:BcPhoneNumbers(inEntry, inWhich) // returns an // array of phone numbers cardfile:OpenTo(entry, nil) // opens Names to a card cardfi
C H A P T E R 1 9 Built-in Applications and System Data calendar:GetMeetingIconType(mtgTextOFrame, mtgStartDate) // returns the type of icon of a meeting or event GetCalendarMeetingType() // returns an array of meeting // types registered with Dates (platform file func) GetCalendarMeetingTypeInfo(typeSymbol ) // returns // information about a meeting type registered with // Dates (platform file function) calendar:GetMeetingInvitees(mtgText, mtgStartDate) // returns // list of invitees calendar:GetMeeting
C H A P T E R 1 9 Built-in Applications and System Data calendar:SetMeetingNotes(mtgText, mtgStartDate, notes) // sets notes for specified meeting or event calendar:SetRepeatingEntryStopDate(mtgText, mtgStartDate, mtgStopDate) // sets last date for specified repeating // meeting or event calendar:UnRegInfoItem(symbol) // removes item from info // picker calendar:UnRegMeetingType(symbol) // removes meeting type // from New picker To Do List Methods toDoFrame:CreateToDoItem(date, richString, reminder, fre
C H A P T E R 1 9 Built-in Applications and System Data Time Zone Functions 19 GetCityEntry(name) // returns information about the // specified city GetCountryEntry(name) // returns information about the // specified country worldClock:SetLocation(whichCity) // sets the current city worldClock:NewCity(newCity, nil, makeHome) // adds a city Notes Methods 19 paperroll:MakeTextNote(string, addIt) // adds a text note to // Notes soup paperroll:NewNote(note, goto, store) // adds a note to // Notes soup
C H A P T E R 1 9 Built-in Applications and System Data Extras Drawer Functions and Methods 19 extrasDrawer:AddExtraIcon(iconType, paramFrame, pkgName, store) // adds an icon (platform file function) extrasDrawer:GetExtraIcons(iconType, pkgName, store) // returns array of icons added with AddExtraIcon extrasDrawer:GetPartCursor(packageName, store, folderSym) // returns cursor that iterates over parts (icons) // (platform file function) extrasDrawer:GetPartEntryData(entry) // returns information // abou
C H A P T E R Figure 20-0 Table 20-0 2 0 Localizing Newton Applications 20 This chapter discusses how to support multiple languages and use locale-specific user preferences to customize the way an application handles numbers, dates, and times. This chapter also discusses how locale settings affect the set of dictionaries the system uses for handwriting recognition. The recognition information in this chapter assumes a basic understanding of handwriting recognition issues.
C H A P T E R 2 0 Localizing Newton Applications Figure 20-1 The Locale settings in Preferences The most important of these settings is the Country pop-up menu. Every Newton device contains a number of frames for tailoring the system’s responses to match the conventions of a specified location. These frames are called locale bundles. At any time, one and only one of these locale bundles is active; that is called the active locale bundle.
C H A P T E R 2 0 Localizing Newton Applications ■ Displaying the text. This uses the date, time, and number formatting attributes of the active locale bundle. The recognition lexical dictionaries need to be, and are, most tolerant. Because the formats specified in these dictionaries are more loosely defined, you can actually combine the different formats being used in different countries. These dictionaries accept constructs such as “77/34/56”, a string that doesn't make much sense.
C H A P T E R 2 0 Localizing Newton Applications Defining a Localization Frame 20 You define the alternative language frames with the SetLocalizationFrame function in a text file included in the project. Here is an example: SetLocalizationFrame({ Swedish: { find: { searchFor: "Söker efter ^0…", // "Searching for ^0…" . . .}}, French: { find: { searchFor: "Recherche dans ^0…",// "Searching for ^0…" . . .
C H A P T E R 2 0 Localizing Newton Applications ■ A frames path the compiler uses to find the alternative object when the Language setting in the Project Settings dialog box is for anything other than English. You should avoid having reserved words in the path—refer to Appendix A of The NewtonScript Programming Language for a complete list of reserved words in NewtonScript.
C H A P T E R 2 0 Localizing Newton Applications Measuring String Widths at Compile Time 20 When the size of a screen element depends on the size of associated text, you can use the MeasureString function to determine, at compile time, how big to make the screen element. If you want to determine the size at runtime, use StrFontWidth. You could establish the width of the search message, for example, by using MeasureString and LocObj together. MeasureString(LocObj("What is your name?", 'find.
C H A P T E R 2 0 Localizing Newton Applications For example: activeLocale:=GetLocale(); Once you’ve obtained a bundle, you can examine it to see how your application should interpret user input or display output. See “Contents of a Locale Bundle” (page 17-1) in Newton Programmer’s Reference for information on the slots of a locale bundle. Changing Locale Settings 20 You cannot change settings in the active locale bundle.
C H A P T E R 2 0 Localizing Newton Applications In the preceding code example the myLocaleBundle frame is based on the U.S. locale bundle. It gives a new title and localeSym value, as it must, but implements no functional changes to the locale.
C H A P T E R 2 0 Localizing Newton Applications The RemoveLocale function accepts as its argument a symbol specifying the locale bundle it is to remove. The following code shows how to pass the locale bundle’s symbol to this function: RemoveLocale('|myLocaleBundle:PIEDTS|); Changing the Active Locale 20 The SetLocale function searches for a specified locale bundle and makes that bundle the active locale bundle.
C H A P T E R 2 0 Localizing Newton Applications //save the current locale setting previousLocale:=GetLocale().localeSym; //install myLocaleBundle as the active locale bundle SetLocale('|myLocaleBundle:PIEDTS|); //reset the previous locale setting SetLocale(previousLocale); //remove your locale RemoveLocale('|myLocaleBundle:PIEDTS|); Localized Output 20 Your application should employ locale-specific user preferences to customize its handling of numbers, dates, and times.
C H A P T E R 2 0 Localizing Newton Applications Functions that Use the Locale Setting To Determine Format 20 These functions are quite simple. You pass in a system clock value or a string, and the function uses the date and time format information in the current locale bundle to produce a string or a system clock value.
C H A P T E R 2 0 Localizing Newton Applications To use one of these values, access the appropriate slot by dereferencing ROM_dateTimeStrSpecs with a dot operator, as in the following example: LongDateStr(Time(),ROM_datetimestrspecs.longDateStrSpec); Using these predefined format specifications also saves the trouble of defining them at compile time and initializing slots with the compile-time variables at run time.
C H A P T E R 2 0 Localizing Newton Applications // get the current time theTime:= Time(); // pass the time and the format to LongDateStr LongDateStr(theTime,kmyDateSpec); This example is deliberately verbose for purposes of illustrating how to build a format specification array.
C H A P T E R 2 0 Localizing Newton Applications Summary of Localization Functions 20 This section categorizes the date, time, locale, and utility functions in this chapter according to task. Compile-Time Functions 20 These functions allow you to build an application for various language environments.
C H A P T E R 2 0 Localizing Newton Applications StringToTime(timeString) TimeStr(time, timeStrSpec) Date Frame Functions 20 These functions convert system clock values to or from date frames. A system clock value is an integer giving the number of minutes since midnight, January 1, 1904 or the number of seconds since midnight, January 1, 1993; a date frame has slots with day, date, year, and so on. See Table 17-8 (page 17-27) in Newton Programmer’s Reference for details of a date frame.
C H A P T E R Figure 21-0 Table 21-0 2 1 Routing Interface 21 This chapter describes the Routing interface in Newton system software. The Routing interface allows applications to send, receive, and perform other operations on data, such as deleting or duplicating. The Routing interface provides a common user interface mechanism that all applications should use to provide routing services. You should read this chapter if your application needs to provide routing services to the user.
C H A P T E R 2 1 Routing Interface user can switch between the In Box and the Out Box by tapping radio buttons in the application. When open, the In/Out Box displays either the In Box, containing incoming items, or the Out Box, containing outgoing items. The user can choose to sort items in both the boxes in various ways, such as by date, transport type, or status. A transport is a type of communication service such as fax, e-mail, or beam.
C H A P T E R 2 1 Routing Interface In Box receives such an item, it is automatically transferred from the In Box to the application, without user intervention. For example, incoming stock quotes from a wireless modem could be automatically transferred to a stock tracking application. The In Box itself also supports routing certain items. For example, you can read incoming e-mail, reply to it, print it, or fax it directly from within the In Box.
C H A P T E R 2 1 Routing Interface In the user interface of your application, the Action button should be positioned differently, depending on how your application displays individual items. If your application can have more than one selectable item on the screen at a time (like Notes), the Action button should be attached to the top of the view it will act on. For example, each note in the Notes application has its own Action button, which applies just to that note.
C H A P T E R 2 1 Routing Interface 3. Using the list of formats, the system builds a list of transports that can handle at least one of the data types supported by any of the formats. The matching transports are shown on the Action picker. Application-defined actions such as delete or duplicate are also added to the picker. 4.
C H A P T E R 2 1 Routing Interface which transports show up in the Action picker. The system builds a list of all routing formats registered under the symbol matching the class of the object being routed. This list contains all the formats that can be used with that class of object. Remember that the class of a frame object is simply the value of the class slot in the frame.
C H A P T E R 2 1 Routing Interface Figure 21-4 Format picker in routing slip Format Picker The built-in applications and transports support routing of the basic data types listed in Table 21-1. Other data types may be defined by applications, but only those transports aware of them can use them. If you do create a custom data type, you must append your developer signature to make it unique.
C H A P T E R 2 1 Routing Interface You must register all routing formats that you define with the system, usually in your application part InstallScript function. Registration is discussed in the section “Registering Routing Formats” beginning on page 21-16. Current Format 21 The routing system maintains a “current format,” which is the last routing format used by your application for a specific transport, or the first routing format available otherwise.
C H A P T E R 2 1 Routing Interface ■ send items programmatically ■ receive items ■ allow items to be viewed in the In/Out Box Providing Transport-Based Routing Actions 21 Here’s a summary of the minimum things you need to do to support routing by the Action button in an application: ■ Include the Action button in your application (or in individual views) by adding a view based on the protoActionButton proto.
C H A P T E R 2 1 Routing Interface Getting and Verifying the Target Object 21 When the user first taps the Action button, but before a choice is made from the picker, the Routing interface sends the Action button view the GetTargetInfo message, passing the symbol 'routing as a parameter. The purpose of this message is to get the target object to be routed and the target view in which it resides. Usually, these items are stored in slots named target and targetView in your application.
C H A P T E R 2 1 Routing Interface The VerifyRoutingInfo method is passed two parameters, the target information frame obtained by GetTargetInfo, and the partially initialized item frame obtained from NewItem. The VerifyRoutingInfo method allows you a chance to verify or change the target item before the routing slip is opened. Normally you would return the same target frame that was passed in, possibly modified. To cancel the routing operation, you can return nil from this method.
C H A P T E R 2 1 Routing Interface If your application does not have a lastFormats slot, or if a matching format is not found (the format was unregistered), the first format found becomes the current format. It is your responsibility to save the lastFormats frame to a soup if you want to maintain it, since this information is cleared on a system reset or if your application is uninstalled. Supplying the Target Object 21 Next, the Routing interface sends the SetupItem message to the current format.
C H A P T E R 2 1 Routing Interface Storing an Alias to the Target Object 21 When there is a single target object, if there is not enough storage space, or the target object is larger than a specified size, you can specify that an alias to the target object, rather than the target object itself, be stored in the item.body slot. This can be a soup entry alias or you can implement your own alias handling.
C H A P T E R 2 1 Routing Interface override the routing format methods that handle the alias operations: TargetSize, MakeBodyAlias, and ResolveBody. The TargetSize method must determine the size of the target object passed to it. The default method does this for soup entries, but you must override it and do it yourself for other kinds of objects.
C H A P T E R 2 1 Routing Interface If your GetTargetInfo method returns a multiple-item target object by using the function CreateTargetCursor, you can set the class of that target object to 'newtOverview to enable this special behavior. You’d do this using code like this: CreateTargetCursor('newtOverview, myItemArray); There is a limitation to using the 'newtOverview data class, which is that this data class handles data types of 'view, 'frame, and 'text only.
C H A P T E R 2 1 Routing Interface If you need to read the body slot within the fields frame, note that it might contain an alias. In order to access it you must get the format and send it the ResolveBody message, like this: theFormat := GetCurrentFormat(fields); resolvedBodySlot := theFormat:ResolveBody(fields); The ResolveBody method returns the data in the body slot whether or not it is referenced by an alias, so you can always use it.
C H A P T E R 2 1 Routing Interface RegisterViewDef. Nor should you use DefConst, or any other method that directly references the routing format. This is because the entire InstallScript function is passed to EnsureInternal (for application parts). Your routing format layouts would be copied into the NewtonScript heap, wasting precious memory. Instead, you should use an indirect method to reference your routing format layouts.
C H A P T E R 2 1 Routing Interface Creating a Print Format 21 You create a print format by using protoPrintFormat. This proto is required for routing formats with a 'view data type, such as views that you would print or fax. This proto format is actually a view template, which displays the target object visually. The data to be displayed is laid out as child views of the protoPrintFormat view.
C H A P T E R 2 1 Routing Interface in portrait mode ('portrait) or horizontally in landscape mode ('landscape). The default value of the orientation slot is 'portrait. Your format should always use relative view justification and/or check the actual bounds of the print format by using the LocalBox view method. Note that you cannot change the orientation between a series of pages being printed by a single print format.
C H A P T E R 2 1 Routing Interface Then the print format view is closed. Note that the ViewShowScript and ViewDrawScript messages are not sent to the view. This takes a lot of time for the transport to determine the number of pages, so if you can, override the CountPages method with one of your own. 3. The transport instantiates the print format view and sends it the ViewSetupFormScript message.
C H A P T E R 2 1 Routing Interface The PrintNextPageScript method should construct the view for the next page of data so that the message self:Dirty() shows the view. Typically, you do this by keeping track of what data has been routed so far. When the format receives this message, you select a new set of child views representing the next page of data to send. Then you call the view method RedoChildren, which closes and then reopens the child views.
C H A P T E R 2 1 Routing Interface // which takes targetInfoFrame.target and makes an // alias, if appropriate end, TextScript: func(item,target) begin . . . end, ... }; Note that one application can have multiple frame formats. You would simply supply a different SetupItem method for the different formats (as well as unique symbol and title slots), to construct the item frame differently.
C H A P T E R 2 1 Routing Interface Your application can provide internal application-defined actions, such as deleting and duplicating, that do not use the Out Box and a transport to perform the routing operation. These routing actions appear at the bottom of the Action picker. You define these routing actions by providing a slot named routeScripts in your application. The Action button searches its own context for the first routeScripts slot that it finds.
C H A P T E R 2 1 Routing Interface Performing the Routing Action 21 The important slot in each frame in the routeScripts array is the RouteScript slot. This slot contains either a symbol identifying a method, or a function directly, that is called if the user chooses this action from the Action picker. This function is where you perform the routing action.
C H A P T E R 2 1 Routing Interface cursors, refer to Chapter 11, “Data Storage and Retrieval.” Note that only these three cursor methods are supported for use with cursors returned by GetTargetCursor. Note that GetTargetCursor works with any kind of target data, whether or not it’s a cursor. So you don’t need to call TargetIsCursor to check before calling GetTargetCursor.
C H A P T E R 2 1 Routing Interface Sending Items Programmatically 21 Your application can send an item programmatically, using a specific transport or transport group, without any user intervention. The Action button is not used in this case. This is done using the global function Send. Here is an example of how to use the Send function: myItem := { toRef: [nameRefObject, ...], // array of fax name refs title: "The Subject", // title of item body: {class: kMyDataSym, // fax data frame myData: ...
C H A P T E R 2 1 Routing Interface The following frame shows a summary of the slots you can include in the item frame. Note that some of the slots shown are specific to a particular transport, and you should include them only if you are sending to that transport. Also, don’t include any additional slots in the item frame unless they are specific to a particular transport.
C H A P T E R 2 1 Routing Interface entry and even some of the slots from the soup entry. Note that you must use name references; you cannot specify soup entries directly. To create a name reference object, use name reference data definitions registered with the system in the data definition registry. There are built-in name reference data definitions for e-mail ('|nameRef.email|), fax ('|nameRef.fax|), and call ('|nameRef.phone|) information associated with names from the Names file.
C H A P T E R 2 1 Routing Interface data. That variable holds the printer selected by the user as the current printer. You can use this function to obtain the current printer for the item: item.printer := GetUserConfig('currentPrinter); If you want to provide a way for the user to select a different printer, you can use the printer chooser proto, protoPrinterChooserButton. This proto changes the setting of the current printer in the system; it actually changes the currentPrinter variable.
C H A P T E R 2 1 Routing Interface // get an entry from the Names soup to use for the recipient curs:=GetUnionSoupAlways(ROM_CardfileSoupName):Query(nil); if curs:Entry() then begin // set the toRef slot in the item frame class := '|nameRef.phone|; // transport addressing class nameRef := GetDataDefs(class):MakeNameRef(anEntry, class); item.
C H A P T E R 2 1 Routing Interface Receiving Data 21 Incoming data arrives first as an entry in the In Box. If there is a public view definition registered for the class of the entry, the item may then be viewed directly in the In Box. IMPORTANT Generally, the body slot of every received item must have a meaningful class. (This is not strictly required if the item has an appSymbol slot.) If body contains a frame, its class slot identifies its data class.
C H A P T E R 2 1 Routing Interface Data” (page 21-34). If a matching application is found in the registry, the appSymbol slot of the item is set to the value of the appSymbol slot in the matching application. If no matching applications are found in the registry, the item may have a pre-existing appSymbol slot, which determines the application to which it belongs. If no matching application is located in the registry and the item has no existing appSymbol slot, it cannot be put away automatically.
C H A P T E R 2 1 Routing Interface Manually Putting Away Items 21 If an item is not put away automatically, it resides in the In Box until the user chooses to put it away manually by tapping the Put Away button. When the user taps the Put Away button, the In Box displays a slip showing to which application the item will be put away. This application is the one that matches the appSymbol slot in the item. The In Box sends the PutAwayScript message to the base view of that application.
C H A P T E R 2 1 Routing Interface Registering to Receive Foreign Data 21 To receive data from a different application or from a non-Newton source, your application must register its interest in such data with the In Box application registry. To do this, use the RegInboxApp function. If your application is no longer interested in foreign data, or is being uninstalled, you can unregister to receive foreign data by using the UnRegInboxApp function.
C H A P T E R 2 1 Routing Interface not provide a view definition, and there are no other view definitions available for that data class, the In/Out Box displays a generic blank view for the item. Items formatted with the 'view data type do not need a separate view definition because the In/Out Box itself provides a page preview view for these items.
C H A P T E R 2 1 Routing Interface access addressing or other information in the entry besides the actual data being routed, look at the frame in the fields slot. However, use of the fields slot is for special cases only and is generally discouraged. This is because it works only in the In/Out Box, and so ties your stationery to it.
C H A P T E R 2 1 Routing Interface Summary of the Routing Interface Constants ROM_RouteDeleteIcon ROM_RouteDuplicateIcon 21 21 // bitmap for delete icon // bitmap for duplicate icon Data Structures 21 Item Frame 21 itemFrame := { appSymbol: symbol, // appSymbol of sender destAppSymbol: symbol, // receiving app, if different body: frame, // the data to send title: string, // item title, e-mail subject toRef: array, // array of name refs for recipients cc: array, // array of name refs for copied re
C H A P T E R 2 1 Routing Interface RouteScripts Array Element 21 RouteScriptsArrayElement := { title: string, // string name of picker item icon: bitmap object, // icon for picker item appSymbol: symbol, // used if defined in a view def RouteScript: symbol or function,// function called if this // action is chosen GetTitle: function, // supplied instead of title slot ... } Protos 21 protoActionButton 21 aProtoActionButton := { _proto: protoActionButton, viewBounds : boundsFrame, ...
C H A P T E R 2 1 Routing Interface TextScript: function, TargetSize: function, MakeBodyAlias: function, ResolveBody: function, // // // // gets text data determines target size makes an alias resolves alias body slot // for protoPrintFormat variant only dataTypes: ['view], // print formats support view data usesCursors: Boolean, // handles multiple items on a page? orientation: symbol, // 'portrait or 'orientation margins: boundsFrame, // inset from edges pageWidth: integer, // width of view pageHeig
C H A P T E R 2 1 Routing Interface GetItemTransport(item) view:GetRouteScripts(targetInfoFrame) RegAppClasses(appSymbol, dataClasses) RegInboxApp(appSymbol, test) TransportNotify(transportSym, message, paramArray) UnRegAppClasses(appSymbol) UnRegInboxApp(appSymbol) UnRegTheseAppClasses(appSymbol, dataClasses) Application-Defined Methods app:AutoPutAway(item) app:PutAwayScript(item) app:ItemCompletionScript(item) app:VerifyRoutingInfo(targetInfo, item) 21-40 Summary of the Routing Interface 21
C H A P T E R Figure 22-0 Table 22-0 2 2 Transport Interface 22 This chapter describes the Transport interface in Newton system software. The Transport interface lets you provide additional communication services to the system. You should read this chapter if you are writing a low-level communication tool or special endpoint that you want to make available as a transport for applications to use.
C H A P T E R 2 2 Transport Interface transports that might be installed in the system at any time. An application need not know anything about the transports available. Likewise, transports can be removed from the system without any effect on applications.
C H A P T E R 2 2 Transport Interface destAppSymbol body title remote connect error currentFormat hidden covert state About Transports Optional. A symbol identifying the application to receive the item, if it is different from the sending application. Applications that send data should set this slot to identify the receiving application, if it is different from the sending one.
C H A P T E R 2 2 Transport Interface completionScript needsResolve A Boolean; if true, the transport sends the ItemCompletionScript message to the application when the item’s state changes or when errors occur. For more details on this mechanism, see the section “Completion and Logging” beginning on page 22-16. A Boolean that is set to true if the body slot contains an alias, rather than the actual data. This means that the format method ResolveBody must be called before the item is sent.
C H A P T E R 2 2 Transport Interface Using the Transport Interface 22 This section describes how to use the Transport interface to perform these specific tasks: ■ create a new transport object ■ create a routing information template, for use by the In/Out Box ■ control the built-in status template, if you need to provide status information to the user ■ create a routing slip template, if your transport sends data ■ create a transport preferences template, if your transport has userconfigurabl
C H A P T E R 2 2 Transport Interface Here is an example of installing a transport in the part InstallScript function: InstallScript := func(partFrame,removeFrame) begin RegTransport(kAppSym, partFrame.partData.(kAppSym)); // assumes that partData.(kAppSym) holds the transport end; When your transport is removed, use the UnRegTransport function to unregister the transport from the system.
C H A P T E R 2 2 Transport Interface The default setting of the addressingClass slot is the symbol '|nameRef.email| For more information about how to use name references for addressing information, see the section “Creating a Name Reference” beginning on page 21-27. For more on name references in general, see “Name References” (page 5-1) in Newton Programmer’s Reference. Grouping Transports 22 Two or more transports can be grouped together in the Action picker under a single action.
C H A P T E R 2 2 Transport Interface the routing slip is not closed. If TransportChanged returns nil, then the transport is changed and operations continue normally. You can use the function GetGroupTransport to determine the name of the current (last-used for sending by the user) transport in a group. Note that when you install a grouped transport, it becomes the current transport for that group.
C H A P T E R 2 2 Transport Interface After sending an item (successfully or unsuccessfully), you must call ItemCompleted to inform the In/Out Box. If there was an error, the ItemCompleted method informs the In/Out Box that an item was not sent. ItemCompleted uses HandleError to inform the user of an error. If you want to perform your own error notification, you can override the HandleError method.
C H A P T E R 2 2 Transport Interface Some transports may ignore the ReceiveRequest message, since they receive data continuously. Others may use this message as a trigger to initiate a connection. You can choose to comply with or ignore any request to receive, depending on the communication resources available and their status. If you choose to comply, the ReceiveRequest method should establish a connection and begin receiving by whatever means the transport uses to communicate.
C H A P T E R 2 2 Transport Interface After downloading all the remote data, you must refresh the In Box view, so the items are updated. To do so, send the Refresh message to the application identified by the ownerApp slot in the transport, like this: ownerApp:Refresh(); Note In Newton OS version 2.0, the ownerApp slot in the transport must first be set up by using the NTK platform file function kSetupOwnerAppFunc in the transport InstallScript method.
C H A P T E R 2 2 Transport Interface Handling Requests When the Transport Is Active 22 While the transport is actively sending or receiving data in the background, the user might request another send or receive operation from the In/Out Box. One way to handle such requests is to queue them up and append them to the current communication transaction or to start another connection when the transport is finished.
C H A P T E R 2 2 Transport Interface // SendRequest method func (newRequest) begin if status <> 'idle then // check if I’m active // wait for idle and then call SendRequest again :QueueRequest('SendRequest, newRequest); else // do a normal send here end, Canceling an Operation 22 The system sends the CancelRequest message to the transport when the user cancels the current transaction or for other reasons, such as when the system wants to turn off. This method must be defined by all transports.
C H A P T E R 2 2 Transport Interface for the item. This allows the transport an opportunity to add its own slots to the item frame. Most transports will want to add a fromRef slot to the item frame. This slot must contain a name reference that identifies the sender. This information is usually extracted from the sender’s current owner card, or persona. You shouldn’t just use the value of GetUserConfig('currentPersona) because it is simply an alias to a names file entry.
C H A P T E R 2 2 Transport Interface e-mail address to the sender’s internet address. Here’s an example of code that sets the appropriate e-mail address in the fromRef object: owner:=ResolveEntryAlias(GetUserConfig('currentPersona)); if owner and GetRoot().cardfile then begin addrs := GetRoot().cardfile:BcEmailAddress(owner, ['|string.email.
C H A P T E R 2 2 Transport Interface if dataDef then begin item.fromRef := dataDef:MakeNameRef(persona, addressingClass); // add other slots or extract routing info here end; item; end; During a receive operation, the transport itself must invoke the NewFromItem method to get a new In/Out Box item frame. This method copies most slots from the received item to the new In/Out Box item frame.
C H A P T E R 2 2 Transport Interface Storing Transport Preferences and Configuration Information 22 Transports can store user-configurable preferences and other configuration information. Typically, you store several chunks of data that correspond to individual preferences or other kinds of configuration information that you want to save for your transport. You must use the transport methods GetConfig and SetConfig to retrieve and set configuration information for your transport.
C H A P T E R 2 2 Transport Interface to the Action picker in an application. Here is an example of a return value that adds two items to the picker: [ {title: "Reply", // name of action icon: ROM_RouteReply, // picker icon // called if action selected RouteScript: func(target, targetView) begin ... end, }, {title: "Forward", // name of action icon: ROM_RouteForward, // picker icon // called if action selected RouteScript: func(target, targetView) begin ...
C H A P T E R 2 2 Transport Interface Application Messages 22 Applications can send messages directly to a single transport or to all transports by using the TransportNotify global function. This mechanism serves as a general way for applications to communicate with transports. Here is an example of using this function: TransportNotify('_all,'AppOpened,[appSymbol]) The In/Out Box uses this mechanism to send three different messages to transports: AppOpened, AppClosed, and AppInFront.
C H A P T E R 2 2 Transport Interface Error Handling 22 The default exception handling method implemented by protoTransport is HandleThrow, which catches and handles exceptions resulting from any supplied transport methods such as SendRequest and ReceiveRequest. You must provide your own exception handler for any methods that you define, or you can pass them to HandleThrow, as follows: try begin ... // do something Throw(); onException |evt.
C H A P T E R 2 2 Transport Interface Providing a Status Template 22 A status template for a transport is based on the proto protoStatusTemplate. The status template displays status information to the user. A transport should generally display a status view whenever it is sent the ReceiveRequest or SendRequest messages. You probably won’t need to create your own status template.
C H A P T E R 2 2 Transport Interface Figure 22-1 Status view subtypes vStatus vProgress vStatusTitle vGauge vConfirm vBarber Each child view included in a subtype has one important value that controls the appearance of that child element.
C H A P T E R 2 2 Transport Interface Using this set of predefined status templates gives all transports a similar user interface and matches the use of other status views throughout the system. For more detailed information on protoStatusTemplate and the predefined subtypes, refer to Chapter 17, “Additional System Services.” Controlling the Status View 22 Your transport should display a status view to the user whenever it is engaged in a lengthy activity such as sending or receiving data.
C H A P T E R 2 2 Transport Interface // vStatus subtype :SetStatusDialog('Connecting, 'vStatus, "Looking for host..."); // vStatusTitle subtype :SetStatusDialog('Connecting, 'vStatusTitle, {statusText: "Connecting to host...", titleText: "Data set 4"}); // vConfirm subtype :SetStatusDialog('Confirming, 'vConfirm, {statusText: "The host has a new data set for you. Do you want to receive it now?", secondary:{text:"Receive Data Set", script: func() ... }, primary:{text:"Disconnect Now", script: func() ...
C H A P T E R 2 2 Transport Interface The vBarber subtype shows a barber pole-like image, but it doesn’t animate automatically. To make it appear to move, use the UpdateIndicator method in a ViewIdleScript method, as shown here: // create the initial vBarber status view :SetStatusDialog('Sending, 'vBarber, {statusText: "Sending data set...", titleText:"Data set 1", barber:true}); ... // set up the status view data frame statusDialog.barberValueFrame:={name:'vBarber,values:{barber:true}}; ...
C H A P T E R 2 2 Transport Interface Figure 22-2 Routing information view Tap transport icon next to Routing information view is In your transport object, store a reference to your routing information template in the transportInfoForm slot. To add your own information to the routing information view, you can supply a BuildText method. From BuildText, call the AddText method for each additional line of text you want to add below the existing elements.
C H A P T E R 2 2 Transport Interface Store a reference to your routing slip template in the routingSlip slot in your transport object. Use the protoFullRouteSlip template, described in the following section, to create a routing slip. One additional proto for use in routing slips is described in the section “Using protoAddressPicker” (page 22-31). Using protoFullRouteSlip 22 This routing slip proto already includes most of the elements required in a routing slip.
C H A P T E R 2 2 Transport Interface the item is updated. The format picker also sends the SetupItem message to the format itself. If the format contains an auxForm slot, the view specified in the auxForm slot opens when the format is selected. The sender pop-up child view allows the sender of the item to select a different owner persona or worksite from a picker, which might affect how the owner’s name and address appear and how the item is sent.
C H A P T E R 2 2 Transport Interface The name of the current transport appears in the upper-right corner of the protoFullRouteSlip view. If that transport belongs to a group, the transport name is actually a picker, from which the user can choose any of the other transports in the group. The picker is displayed only if there is more than one transport that belongs to the group.
C H A P T E R 2 2 Transport Interface Positioning Elements in the Lower Portion of the Routing Slip 22 The height of the lower portion of the routing slip is controlled by the bottomIndent slot. Placing your own user interface elements in this portion of the routing slip is complicated by the fact that the format picker may or may not be inserted by the system. It is included only if there is more than one format for the item.
C H A P T E R 2 2 Transport Interface information at that time. For example, if a user queued several fax items from home but didn’t send them until she got to work, the area code information for telephone numbers might need to be changed. Using protoAddressPicker 22 This proto consists of a labeled field that you can use in the routing slip to allow the user to choose the recipient(s) of the item being sent.
C H A P T E R 2 2 Transport Interface Figure 22-6 Address picker with remembered names The Intelligent Assistant also interacts with the address picker. If the user invokes a routing action such as “fax Bob” with the Intelligent Assistant, the Intelligent Assistant sets up the address picker with a list of alternatives from the Names file, as shown in Figure 22-7. Figure 22-7 Address picker set up by Intelligent Assistant The protoAddressPicker uses name references to refer to individual names.
C H A P T E R 2 2 Transport Interface Most transports can use the built-in name reference data and view definitions to handle and display name references. For example, one place you might need to use these is if you need to build a string representing the address or addresses chosen in the protoAddressPicker. The selected slot of the protoAddressPicker contains an array of name references for the names selected by the user in the picker.
C H A P T E R 2 2 Transport Interface ■ default folders for new and read or sent items ■ show/hide status and progress dialogs The protoTransportPrefs proto provides a dialog containing the preferences items shown in Figure 22-9.
C H A P T E R 2 2 Transport Interface For example, the built-in Print transport uses the protoTransportPrefs proto for its preferences view. Since the ReceiveRequest method does not exist in the Print transport, the In Box preference element is not displayed, as shown in Figure 22-10. Figure 22-10 Print preferences The Info button is included in the protoTransportPrefs template so you can give the user access to About and Help views for the transport.
C H A P T E R 2 2 Transport Interface Summary of the Transport Interface Constants 22 22 ROM_RouteMailIcon // bitmap for mail group icon ROM_RoutePrintIcon // bitmap for print group icon ROM_RouteFaxIcon // bitmap for fax group icon ROM_RouteBeamIcon // bitmap for beam group icon ROM_RouteReply // bitmap for reply action icon ROM_RouteForward // bitmap for forward action icon ROM_RouteAddSender // bitmap for add sender to Names icon ROM_RoutePasteText // bitmap for copy text to Notes icon Protos 22
C H A P T E R 2 2 Transport Interface AppInFront: function, // notifies transport of change in app frontmost status AppOpened: function, // notifies transport of app opening CancelRequest: function, // cancels in-progress operation CanPutAway: function, // put away hook for transport CheckOutbox: function, // invokes SendRequest operation CloseStatusDialog: function, // closes status dialog ConnectionDetect: function, // force send now or later GetConfig: function, // returns a prefs value GetDefaultOwne
C H A P T E R 2 2 Transport Interface TranslateError: function, // returns a string translation VerifyRoutingInfo: function, // called on send of multiple // item target that is being split ...
C H A P T E R 2 2 Transport Interface protoAddressPicker 22 anAddressPicker := { _proto: protoAddressPicker, // address picker viewBounds: boundsFrame, // location and size text: string, // picker label otherText: string, // last item (pops up people picker) selected: array, // name refs to be initially selected alternatives: array, // name refs to be shown in picker class: symbol, // name ref data def class _picker: viewTemplate, // picker for other addresses ...
C H A P T E R Figure 23-0 Table 23-0 2 3 Endpoint Interface 23 This chapter describes the basic Endpoint interface in Newton system software. The Endpoint interface allows you to perform real-time communication using any of the communication tools available in the system. The Endpoint interface is well suited for communication needs such as database access and terminal emulation.
C H A P T E R 2 3 Endpoint Interface The endpoint object created from this proto encapsulates and maintains the details of the specific connection. It allows you to control the underlying communication tool to perform your communication tasks. The Endpoint interface uses an asynchronous, state-driven communications model. In asynchronous operation, communication requests are queued, and control is returned to your application after each request is made but before it is completed.
C H A P T E R 2 3 Endpoint Interface This kind of asynchronous operation lends itself nicely to creating state-machine based code, where each part of the communication process is a state that is invoked by calling an endpoint method. The CompletionScript method of each state invokes the next state, and the state machine automatically progresses from one state to the next in a predefined fashion. Synchronous Operation 23 Many endpoint methods can be called synchronously as well as asynchronously.
C H A P T E R 2 3 Endpoint Interface If the input operation terminates normally—that is, the InputScript method is called—the system automatically reposts the input spec for you to receive additional input. Of course, you can alter this process if you want to. Data Forms 23 All NewtonScript data needs to be transformed whenever it is sent to or received from a foreign environment.
C H A P T E R 2 3 Endpoint Interface The different types of data forms and the defaults are described in more detail in “Data Form Symbols” (Table 20-1 on page 20-2) in Newton Programmer’s Reference. Only a subset of data form values is applicable for any particular operation. Table 23-1 enumerates the data forms and their applicability to output specs, input specs, and endpoint option frames.
C H A P T E R 2 3 Endpoint Interface placeholder or default values, which the system fills in when the data is received. For more information, see the section “Specifying the Data Form and Target” beginning on page 23-13. The data types that can be used in the typelist array are identified by these symbols: 'long, 'ulong, 'short, 'byte, 'char, 'unicodechar, 'boolean, 'struct, and 'array. They are described in detail in “Data Type Symbols” (Table 20-2 on page 20-3) in Newton Programmer’s Reference.
C H A P T E R 2 3 Endpoint Interface Endpoint Options 23 You configure the communication tool underlying an endpoint object by setting endpoint options. An endpoint option is specified in an endpoint option frame that is passed in an array as an argument to one of the endpoint methods. Options select the communication tool to use, control its configuration and operation, and return result code information from each endpoint method call.
C H A P T E R 2 3 Endpoint Interface ■ Multiple communication sessions. The system now supports multiple simultaneous communication sessions. In other words, you can have more than one active endpoint at a time.
C H A P T E R 2 3 Endpoint Interface All option data you set gets packed together into one block of data. Each option within this block must be long-word aligned for the communication tools. So, when using the 'template data form, you need to use the 'struct type (at the beginning of the typelist array) to guarantee that the option is long-word aligned and padded.
C H A P T E R 2 3 Endpoint Interface 'long, 'long ] } }; When you set endpoint options, the cloned option frame is returned to you so that you can check the result codes for individual options. If you set options with an asynchronous method call, the cloned option frame is returned as a parameter to the CompletionScript callback method. If you set options with a synchronous method call, the cloned option frame is returned as the value of the synchronous method itself.
C H A P T E R 2 3 Endpoint Interface When you are finished with an endpoint, you must unbind it using the UnBind method, then dispose of it using the Dispose method. Establishing a Connection 23 After instantiating and binding an endpoint, you establish a connection. There are two ways you can create a connection. One way is to call the Connect method. If the physical connection is serial, for instance, you don't even need to specify an address as an option.
C H A P T E R 2 3 Endpoint Interface Receiving Data Using Input Specs 23 The most common way to receive data is to use input specs. An input spec is a frame that defines what kind of data you are looking for, termination conditions that control when the input should be stopped, and callback methods to notify you when input is stopped or other conditions occur. An input spec consists of many pieces.
C H A P T E R 2 3 Endpoint Interface Table 23-2 Input spec slot applicability termination slot discard After slot* filter slot partial Frequency and partial Script slots† Data form target slot 'char na (not applicable) determined automatically na OK na 'number na determined automatically na OK na 'string na OK OK OK OK 'bytes na OK OK OK OK 'binary data and offset all slots except na na na slots only endSequence 'template typelist and arglist slots only determined
C H A P T E R 2 3 Endpoint Interface If you specify the form 'template or 'binary, you also must specify a target slot in the input spec. The target slot is a frame used to define additional information pertaining to the data form. If your input form is 'template, then you must set the arglist and typelist slots in the target frame. The arglist array contains placeholder data, which is filled in with actual data when it is received, and the typelist array contains the template’s array of types.
C H A P T E R 2 3 Endpoint Interface termination sequence, or an array of items, any one of which will cause the input to terminate. A termination sequence can be a single character, a string, a number, or an array of bytes. If you don't want to look for a termination sequence, don't define this slot. For the 'binary data form, you cannot use the endSequence slot to specify a termination condition.
C H A P T E R 2 3 Endpoint Interface Specifying Flags for Receiving 23 For certain communication tools, it may be necessary to use special protocol flags when receiving data. You do this by specifying one or more flag constants in the rcvFlags slot in the input spec. You can use such flags only if the communication tool supports them. For example, some of the built-in communication tools, such as the infrared and AppleTalk tools, support only framed receiving (packetized data).
C H A P T E R 2 3 Endpoint Interface slot in the input spec. The filter slot is a frame containing two slots, byteProxy and sevenBit, which allow you to perform two different kinds of processing. The byteProxy slot allows you to identify one or more characters or bytes in the input stream to be replaced by zero or one characters. You may, for instance, replace null characters (0x00) with spaces (0x20). Note that if your input data form is set to 'string, you are encouraged to use this slot.
C H A P T E R 2 3 Endpoint Interface Handling Normal Termination of Input 23 The InputScript message is sent to the input spec frame when one of the termination conditions is met. You define the InputScript method in the input spec frame. The received data is passed as a parameter to the InputScript method. Another parameter describes the specific condition that caused the input to terminate, in case you had specified more than one in the input spec.
C H A P T E R 2 3 Endpoint Interface Handling Unexpected Completion 23 The CompletionScript message is sent to the input spec frame when the input spec completes unexpectedly—for example, because of a time-out expiring or a Cancel message. If you do not specify a CompletionScript method in your input spec frame, an exception is forwarded to the endpoint ExceptionHandler method.
C H A P T E R 2 3 Endpoint Interface IMPORTANT Do not call the Input or Partial methods in a polling loop to look for incoming data. The Newton communications architecture requires a return to the main event loop in order to process incoming data from the endpoint’s underlying communication tool. These methods are included as an alternate way of retrieving data from the incoming data buffer, not as a way to implement synchronous data receives.
C H A P T E R 2 3 Endpoint Interface within the binary object at which to stream data. For more information on receiving binary data and using the target frame, see the section “Specifying the Data Form and Target” beginning on page 23-13. For sending data, the data is expected to be a binary object and is interpreted as a raw byte stream. That is, the data is not converted and is passed directly to the communication tool. This is the default data form for sending binary objects.
C H A P T E R 2 3 Endpoint Interface The cancellation itself can be invoked asynchronously or synchronously, and is handled differently in the system depending on how it’s done. The details are explained in the following subsections.
C H A P T E R 2 3 Endpoint Interface Next, the Cancel (or Disconnect) method returns, and any pending synchronous request is canceled by throwing an exception that contains error code –16005. Or, if the cancellation was invoked as the result of a time-out expiration, then whatever method timed out throws an exception containing error code –16005.
C H A P T E R 2 3 Endpoint Interface an option succeeds without errors, the result slot is set to nil. For more general information on setting options, see the section “Endpoint Options” beginning on page 23-7. Power-Off Handling 23 During send and receive operations, you may want to protect against the system powering off so that the connection is not broken. The system can power-off unexpectedly as a result of the user inadvertently turning off the power or as a result of a low battery.
C H A P T E R 2 3 Endpoint Interface Summary of the Endpoint Interface 23 Constants and Symbols 23 Data Form Symbols 23 'char 'number 'string 'bytes 'binary 'template 'frame Data Type Symbols 23 'long 'ulong 'short 'byte 'char 'unicodechar 'boolean 'struct 'array Option Opcode Constants opSetNegotiate 256 opSetRequired 512 opGetDefault 768 opGetCurrent 1024 Summary of the Endpoint Interface 23 23-25
C H A P T E R 2 3 Endpoint Interface Endpoint State Constants kUninit 0 kUnbnd 1 kIdle 2 kOutCon 3 kInCon 4 kDataXfer 5 kOutRel 6 kInRel 7 kInFlux 8 kOutLstn 9 Other Endpoint Constants kNoTimeout 0 kEOP 0 kMore 1 kPacket 2 23 Data Structures 23 Option Frame 23 myOption := { type: symbol, // option type label: string, // 4-char option identifier opCode: integer, // an opCode constant form: 'template, // default form for options result: nil, // set by the system on return d
C H A P T E R 2 3 Endpoint Interface Callback Spec Frame 23 myCallbackSpec := { async: Boolean, // asynch request? reqTimeout: integer, // time-out period, or 0 CompletionScript: // called when request is done func(endpoint, options, result)...
C H A P T E R 2 3 Endpoint Interface filter: { // used to filter incoming data byteProxy: [{ // an array of frames byte: char, // char or byte to replace proxy: char // replacement char or byte, or nil }, ...], sevenBit: Boolean // strip high-order bit }, rcvOptions: [], // array of options, or a single frame partialFrequency: integer,// freq, in milliseconds, to call // PartialScript InputScript: // called when input is terminated func(endpoint, data, terminator, options)...
C H A P T E R 2 3 Endpoint Interface Input: // returns data from input buffer and clears it func() ..., Partial: // returns data from input buffer func() ..., FlushInput: // flushes whole input buffer func() ..., FlushPartial: // flushes input buffer previously read func() ..., Cancel: // cancels operations func(callbackSpec) ..., Option: // sets & gets options func(options, callbackSpec) ..., ExceptionHandler: // called on exceptions func(error) ...
C H A P T E R 2 3 Endpoint Interface Functions and Methods 23 Utility Functions 23 MakeAppleTalkOption(NBPaddressString) MakeModemOption() MakePhoneOption(phoneString) Translate(data, translator, store, progressScript) 23-30 Summary of the Endpoint Interface
C H A P T E R Figure 24-0 Table 24-0 2 4 Built-in Communications Tools24 This chapter describes the built-in communications tools provided in Newton system software 2.0. The following tools are built into the system: ■ Serial ■ Modem ■ Infrared ■ AppleTalk These communications tools are accessed and used through the Endpoint interface. This chapter provides an introduction to each tool and the options that you use with each.
C H A P T E R 2 4 Built-in Communications Tools The following is an example of how to create an endpoint that uses the standard asynchronous serial tool: myAsyncEP := {_proto:protoBasicEndpoint}; myOptions := [ { label: kCMSAsyncSerial, type: 'service, opCode: opSetRequired } ]; returnedOptions:= myAsyncEP:Instantiate(myAsyncEP, myOptions); Table 24-1 summarizes the standard serial options.
C H A P T E R 2 4 Built-in Communications Tools Table 24-1 Summary of serial options (continued) Label Value Use when Description kCMOSerialBreak "sbrk" After connecting Sends a break. kCMOSerialDiscard "sdsc" After connecting Discards data in input and/or output buffer. kCMOSerialEventEnables "sevt" Any time Configures the serial tool to complete an endpoint event on particular state changes.
C H A P T E R 2 4 Built-in Communications Tools Serial Tool with MNP Compression 24 The asynchronous serial communications tool with MNP compression works just like a standard asynchronous serial endpoint, except that it uses MNP data compression.
C H A P T E R 2 4 Built-in Communications Tools An endpoint can include kPacket, kEOP, and kMore flags to control the sending and receiving of framed (packetized) data with the framed asynchronous serial tool. For more information on these flags, see “Sending Data” (page 23-11).
C H A P T E R 2 4 Built-in Communications Tools both that character and an additional DLE character are sent; conversely, two consecutive DLE characters on input are turned into a single DLE data byte. The packet is framed at the end by the 2-character DLE-ETX trailer. Finally, a 2-character frame check sequence is appended.
C H A P T E R 2 4 Built-in Communications Tools Table 24-4 Summary of modem options Label Value Use When Description kCMOModemPrefs "mpre" Any time Configures the modem controller. kCMOModemProfile "mpro" Any time Override modem setup selected in preferences. Use when instatiating. kCMOModemECType "mecp" Any time Specifies the type of error control protocol to be used in the modem connection. kCMOModemDialing "mdo" Any time Controls the parameters associated with dialing.
C H A P T E R 2 4 Built-in Communications Tools Infrared Tool 24 You use the infrared (IR) communications tool to perform half-duplex infrared communications. Since the infrared tool does not support full-duplex communications, you cannot activate an input specification and expect to output data. The infrared tool supports packetized data, which means that an endpoint can include kPacket, kEOP, and kMore flags to control sending and receiving framed (packetized) data.
C H A P T E R 2 4 Built-in Communications Tools The infrared tool uses the Sharp Infrared protocol. Because of the characteristics of this protocol, Apple recommends setting sendFlags to kPacket and to kEOP every time you send data. For more information on sendFlags see, “Sending Data” (page 23-11). If you don’t set sendFlags as recommended above, the tool only sends data after it queues 512 bytes of data, which means that input scripts do not terminate as you might expect.
C H A P T E R 2 4 Built-in Communications Tools } } ]; results := myATalkEP:Instantiate(myATalkEP, myOptions); The AppleTalk tool options are summarized in Table 24-6. These options are described in detail in “Options for the AppleTalk Tool” (page 21-71) in Newton Programmer’s Reference. Table 24-6 Summary of AppleTalk options Label Value Use When Description kCMARouteLabel “rout” When connecting or listening Sets an AppleTalk NBP address.
C H A P T E R 2 4 Built-in Communications Tools claiming its resources passively and will allow another tool to claim it. If this value is nil, the communications tool is claiming its resources actively and will not allow another tool to claim it. ■ The resource-passive state option (kCMOPassiveState) has a Boolean value that specifies whether or not the current state of the communications tool supports releasing resources.
C H A P T E R 2 4 Built-in Communications Tools The following example shows how to instruct a communications tool to allow its resources to be claimed by another tool. For instance, you might send this option with an arglist value of true if you are listening for an incoming connection. The default for all tools is to be in an active state.
C H A P T E R 2 4 Built-in Communications Tools Table 24-8 AppleTalk functions Function Description OpenAppleTalk Opens the AppleTalk drivers. CloseAppleTalk Closes the AppleTalk drivers. AppleTalkOpenCount Returns the open count for the AppleTalk drivers. HaveZones Returns true if a connection exists and zones are available. Returns nil if there are no zones. GetMyZone Returns a string naming the current AppleTalk zone.
C H A P T E R 2 4 Built-in Communications Tools Figure 24-2 NetChooser view while searching When the search has been completed, the NetChooser fills in the available choices and allows the user to make a selection, as shown in Figure 24-3. Figure 24-3 NetChooser view displaying printers After the user has made a selection, the system calls a method that you provide named NetworkChooserDone. The system fills in the parameters to this method with the name of the selection and zone chosen by the user.
C H A P T E R 2 4 Built-in Communications Tools The following is an example that shows the use of this function: ChooserSample := { // open network connection openNetworkScript: func() begin GetRoot().
C H A P T E R 2 4 Built-in Communications Tools Summary 24 Built-in Communications Tool Service Option Labels kCMSAsyncSerial kCMSMNPID kCMSModemID kCMSSlowIR kCMSFramedAsyncSerial kCMSAppleTalkID "aser" "mnps" "mods" "slir" "fser" "atlk" Options 24 Asynchronous Serial Tool Options 24 kCMOSerialHWChipLoc kCMOSerialChipSpec kCMOSerialCircuitControl kCMOSerialBuffers kCMOSerialIOParms kCMOSerialBitRate kCMOOutputFlowControlParms kCMOInputFlowControlParms kCMOSerialBreak kCMOSerialDiscard kCMOSerialE
C H A P T E R 2 4 Built-in Communications Tools Framed Serial Tool Options kCMOFramingParms kCMOFramedAsyncStats 24 "fram" "frst" Modem Options kCMOModemPrefs kCMOModemProfile kCMOModemECType kCMOModemDialing kCMOModemConnectType kCMOModemConnectSpeed kCMOModemFaxCapabilities kCMOModemFaxEnabledCaps kCMOModemVoiceSupport kCMOMNPSpeedNegotiation kCMOMNPCompression kCMOMNPStatistics 24 "mpre" "mpro" "mecp" "mdo" "mcto" "mspd" "mfax" "mfec" "mvso" "mnpn" "mnpc" "mnps" Infrared Tool Options kCMOSlowIRCon
C H A P T E R 2 4 Built-in Communications Tools Constants 24 Serial Chip Location Option Constants 24 kHWLocExternalSerial kHWLocBuiltInIR kHWLocBuiltInModem kHWLocPCMCIASlot1 kHWLocPCMCIASlot2 "extr" "infr" "mdem" "slt1" "slt2" Serial Chip Specification Option Constants 24-18 kSerCap_Parity_Space kSerCap_Parity_Mark kSerCap_Parity_Odd kSerCap_Parity_Even 0x00000001 0x00000002 0x00000004 0x00000008 kSerCap_DataBits_5 kSerCap_DataBits_6 kSerCap_DataBits_7 kSerCap_DataBits_8 kSerCap_DataBits_All
C H A P T E R 2 4 Built-in Communications Tools Serial Circuit Control Option Constants kSerOutDTR kSerOutRTS 0x01 0x02 kSerInDSR kSerInDCD kSerInRI kSerInCTS kSerInBreak 0x02 0x08 0x10 0x20 0x80 Serial Configuration Option Constants k1StopBits k1pt5StopBits k2StopBits 0 1 2 kNoParity kOddParity kEvenParity 0 1 2 k5DataBits k6DataBits k7DataBits k8DataBits 5 6 7 8 kExternalClock k300bps k600bps k1200bps k2400bps k4800bps k7200bps k9600bps k12000bps k14400bps k19200bps k38400bps k57600bps k11520
C H A P T E R 2 4 Built-in Communications Tools Serial Event Configuration Option Constants kSerialEventBreakStartedMask kSerialEventBreakEndedMask kSerialEventDCDNegatedMask kSerialEventDCDAssertedMask kSerialEventHSKiNegatedMask kSerialEventHSKiAssertedMask kSerialEventExtClkDetectEnableMask 0x00000001 0x00000002 0x00000004 0x00000008 0x00000010 0x00000020 0x00000040 Serial External Clock Divide Option Constants kSerClk_Default kSerClk_DivideBy_1 kSerClk_DivideBy_16 kSerClk_DivideBy_32 kSerClk_Divide
C H A P T E R 2 4 Built-in Communications Tools kV17_12Mod kV17st_12Mod kV17_14Mod kV17st_14Mod 0x00000200 0x00000400 0x00000800 0x00001000 MNP Compression Option Constants kMNPCompressionNone kMNPCompressionMNP5 kMNPCompressionV42bis 24 0x00000001 0x00000002 0x00000008 Infrared Protocol Type Option Constants kUsingNegotiateIR kUsingSharpIR kUsingNewton1 kUsingNewton2 0 1 2 4 kUsing9600 kUsing19200 kUsing38400 1 2 4 24 Functions and Methods 24 AppleTalk Driver Functions 24 OpenAppleTalk() C
C H A P T E R 2 4 Built-in Communications Tools NetChooser Function NetChooser:OpenNetChooser(zone, lookupName, startSelection, who, connText, headerText, lookforText) 24-22 Summary 24
C H A P T E R Figure 25-0 Table 25-0 2 5 Modem Setup Service 25 This chapter contains information about the modem setup capability in Newton system software. You need to read this chapter if you want to define a modem setup package for your application. The built-in modem communications tool uses these packages for communicating with modems. For more information about the built-in modem communications tool, see “Built-in Communications Tools” (page 24-1).
C H A P T E R 2 5 Modem Setup Service Modem setup packages can be supplied by modem manufacturers, or can be created by other developers. A modem setup package can contain four parts: ■ General information. The beginning of a modem setup package specifies general information about the modem corresponding to the package—for example, the modem’s name and version number. ■ A modem tool preferences option. The part of the package that contains specifications that configure the modem controller.
C H A P T E R 2 5 Modem Setup Service Figure 25-1 Modem preferences view The Modem Setup Process 25 All communication applications that use a modem endpoint make use of the modem setup service. The current modem setup is automatically invoked when an application calls the modem endpoint’s Instantiate method. Note If the modem endpoint option list includes the modem profile option (kCMOModemProfile), the modem setup is not invoked.
C H A P T E R 2 5 Modem Setup Service 4. The modem endpoint is reconfigured with pass-through mode disabled, and control is returned to the client application, which can proceed with its Bind and Connect calls. “Defining a Modem Setup” (page 25-5) describes how to define a modem setup. Modem Communication Tool Requirements 25 The Newton modem communication tool expects certain characteristics from a modem. These characteristics are described here.
C H A P T E R 2 5 Modem Setup Service Note The modem tool has been upgraded to support the Class 2 and Class 2.0 FAX protocols in release 2.1 of the Newton System Software. This upgrade is also available in the German version of release 2.0 of the Newton System Software. To enable the use of these protocols, you must define the fax profile in your modem setup.
C H A P T E R 2 5 Modem Setup Service about the modem preferences option, see “Modem Preferences Option” (page 21-34) in Newton Programmer’s Reference. Setting the Modem Profile Option 25 This modem profile option describes the modem characteristics, to be used by the modem controller.
C H A P T E R 2 5 Modem Setup Service Table 25-1 Summary of configuration string usage Configuration string When used kConfigStrNoEC The default configuration used for data connections when kDirectConnectOnly is nil. Also used for FAX connections. See “The No Error Control Configuration String” (page 22-7) in Newton Programmer’s Reference for an example. kConfigStrECOnly Used for data connections that require error correction. This configuration string is used only if requested by an application.
C H A P T E R 2 5 Modem Setup Service Note You can only set the service class (use the kServiceClass constant) for versions of the software that support the Class 2 fax protocol. Newton System Software version 2.1 and the German version of Newton System Software version 2.0 support the Class 2 fax protocol. ◆ For detailed descriptions of these constants, see “Fax Profile Constants” (page 22-10) in Newton Programmer’s Reference.
C H A P T E R 2 5 Modem Setup Service Summary of the Modem Setup Service 25 Constants 25 Constants for Modem Setup General Information 25 kModemName kVersion kOrganization Constants for Modem Setup Preferences 25 kIdModem kUseHardwareCD kUseConfigString kUseDialOptions kHangUpAtDisconnect Constants for the Modem Setup Profile 25 kSupportsEC kSupportsLCS kDirectConnectOnly kXonnectSpeeds kXommandTimeout kMaxCharsPerLine kInterCmdDelay kModemIDString kConfigStrNoEC kConfigStrECOnly kConfigStrEC
C H A P T E R 2 5 Modem Setup Service Fax Speed Constants 25 kV21Ch2Mod kv27Ter24Mod kV27Ter48Mod kV29_72Mod kV17_72Mod kV17st_72Mod kV29_96Mod kV17_96Mod kV17st_96Mod kV17_12Mod kV17st_12Mod kV17st_14Mod Fax Class Constants kModemFaxClass0 kModemFaxClass1 kModemFaxClass2 kModemFaxClass2_0 25-10 Summary of the Modem Setup Service 25
C H A P T E R Figure 26-0 Table 26-0 2 6 Utility Functions 26 This chapter provides a listing of a number of utility functions documented in the “Utility Functions Reference” in the Newton Programmer’s Reference.
C H A P T E R 2 6 Utility Functions Table 26-1 Summary of copying functions Function name Recurs Follows magic pointers Ensures object is internal Copies object Clone — — — yes DeepClone yes yes — yes EnsureInternal yes — yes as needed TotalClone yes — yes yes Compatibility 26 This section describes the changes to the utility functions for Newton System Software 2.0. New Functions 26 The following new functions have been added for this release.
C H A P T E R 2 6 Utility Functions New String Functions 26 The following new string functions have been added. CharPos LatitudeToString LongitudeToString StrExactCompare StrFilled (existed in 1.0 but now documented) StrTokenize StyledStrTruncate SubstituteChars New Array Functions 26 The following new array functions have been added.
C H A P T E R 2 6 Utility Functions New Integer Math Functions 26 The following new functions related to integer math have been added. GetRandomState SetRandomState New Financial Functions 26 The following new functions that perform operations related to the currency exchange rate have been added. GetExchangeRate SetExchangeRate GetUpdatedExchangeRates New Exception Handling Functions 26 The following new exception handling function has been added.
C H A P T E R 2 6 Utility Functions New Data Stuffing Functions 26 The following new data stuffing functions have been added. StuffCString StuffPString New Functions to Get and Set Globals 26 The following new functions that get, set, and check for the existence of global variables and functions have been added. GetGlobalFn GetGlobalVar GlobalFnExists GlobalVarExists DefGlobalFn DefGlobalVar UnDefGlobalFn UnDefGlobalVar New Debugging Functions 26 The following debugging functions have been added.
C H A P T E R 2 6 Utility Functions GetMemorySlot MakePhone MakeDisplayPhone ParsePhone PowerOff Translate Enhanced Functions 26 The following string function has been enhanced in Newton 2.0. ParamStr has been enhanced to support conditional substitution. Obsolete Functions 26 Some utility functions previously documented in the Newton Programmer’s Guide are obsolete, but are still supported for compatibility with older applications.
C H A P T E R 2 6 Utility Functions Summary of Functions and Methods Object System Functions 26 26 ClassOf(object) Clone(object) DeepClone(object) EnsureInternal(obj) GetFunctionArgCount(function) GetSlot(frame, slotSymbol) GetVariable(frame, slotSymbol) HasSlot(frame, slotSymbol) HasVariable(frame, slotSymbol) Intern( string ) IsArray(obj) IsBinary(obj) IsCharacter(obj) IsFrame(obj) IsFunction(obj) IsImmediate(obj) IsInstance(obj, class) IsInteger(obj) IsNumber(obj) IsReadOnly(obj) IsReal(obj) IsStrin
C H A P T E R 2 6 Utility Functions String Functions BeginsWith( string, substr ) Capitalize( string ) CapitalizeWords( string ) CharPos(str, char, startpos) Downcase( string ) EndsWith( string, substr ) EvalStringer( frame, array ) FindStringInArray( array, string ) FindStringInFrame( frame, stringArray, path ) FormattedNumberStr(number, formatString) IsAlphaNumeric(char) IsWhiteSpace(char) LatitudeToString(latitude) LongitudeToString(longitude) NumberStr( number ) ParamStr( baseString, paramStrArray )
C H A P T E R 2 6 Utility Functions Bitwise Functions 26 Band(a, b) Bor(a, b) Bxor(a, b) Bnot(a) Array Functions 26 AddArraySlot (array, value) Array( size, initialValue ) ArrayInsert(array, element, position) ArrayMunger( dstArray, dstStart, dstCount, srcArray, srcStart, srcCount ) ArrayRemoveCount( array, startIndex, count ) InsertionSort(array, test, key) Length (array) LFetch(array, item, start, test, key) LSearch(array, item, start, test, key) NewWeakArray(length) SetAdd (array,value,uniqueOnly
C H A P T E R 2 6 Utility Functions BMerge(array1, array2, test, key, uniqueOnly) BSearchLeft(array, item, test, key) BSearchRight(array, item, test, key) Integer Math Functions 26 Abs(x) Ceiling(x) Floor(x) GetRandomState() Max( a, b ) Min( a, b ) Real(x) Random (low, high) SetRandomSeed (seedNumber) SetRandomState(randomState) Floating Point Math Functions Acos(x) Acosh(x) Asin(x) Asinh(x) Atan(x) Atan2(x,y) Atanh(x) CopySign(x,y) Cos(x) Cosh(x) Erf(x) Erfc(x) Exp(x) Expm1(x) Fabs(x) FDim(x,y) FMax
C H A P T E R 2 6 Utility Functions IsFinite(x) IsNaN(x) IsNormal(x) LessEqualOrGreater(x, y) LessOrGreater(x, y) LGamma(x) Log(x) Logb(x) Log1p(x) Log10(x) NearbyInt(x) NextAfterD(x,y) Pow(x,y) RandomX(x) Remainder(x,y) RemQuo(x,y) Rint(x) RintToL(x) Round(x) Scalb(x, k) SignBit(x) Signum(x) Sin(x) Sinh(x) Sqrt(x) Tan(x) Tanh(x) Trunc(x) Unordered(x, y) UnorderedGreaterOrEqual(x, y) UnorderedLessOrEqual(x, y) UnorderedOrEqual(x, y) UnorderedOrGreater(x, y) UnorderedOrLess(x, y) FeClearExcept(excepts) Fe
C H A P T E R 2 6 Utility Functions FeTestExcept(excepts) FeUpdateEnv(envObj) Financial Functions 26 Annuity(r, n) Compound(r, n) GetExchangeRate(country1, country2) SetExchangeRate(country1, country2, rate) GetUpdatedExchangeRates() Exception Functions 26 Throw(name, data) Rethrow() CurrentException() RethrowWithUserMessage(userTitle,userMessage,override) Message Sending Functions 26 Apply(function, parameterArray) IsHalting(functionObject, args) Perform(frame, message, parameterArray) PerformI
C H A P T E R 2 6 Utility Functions Data Extraction Functions 26 ExtractByte(data, offset) ExtractBytes(data, offset, length, class) ExtractChar(data, offset) ExtractLong(data, offset) ExtractXLong(data, offset) ExtractWord(data, offset) ExtractCString(data, offset) ExtractPString(data, offset) ExtractUniChar(data, offset) Data Stuffing Functions 26 StuffByte(obj, offset, toInsert) StuffChar(obj, offset, toInsert) StuffCString(obj, offset, aString) StuffLong(obj, offset, toInsert) StuffPString(obj,
C H A P T E R 2 6 Utility Functions Stats() StrHexDump(object, spaceInterval) TrueSize(object, filter) ViewAutopsy(functionSpec) Miscellaneous Functions AddMemoryItem(memSymbol, value) AddMemoryItemUnique(memorySlot, value, testFunc) Backlight() BacklightStatus(state) BinEqual(a, b) BinaryMunger( dst, dstStart, dstCount, src, srcStart, srcCount ) Chr(integer) Compile(string) Gestalt(selector) GetAppName(appSymbol) GetAppParams( ) GetAppPrefs(appSymbol, defaultFrame) GetMemoryItems(memSymbol) GetMemorySl
A P P E N D I X Figure 27-0 Table 27-0 The Inside Story on Declare A This appendix describes the technical details of the declare mechanism. Knowing these technical details is not necessary to understanding what declaring a view means; they are provided primarily for completeness and to help you when you are debugging. You shouldn’t write code that depends on these details. For a basic discussion of the declare mechanism, see the section “View Instantiation” beginning on page 3-26.
A P P E N D I X Note Protos built into the system use an analogous slot called allocateContext, that holds the same thing as stepAllocateContext. The allocateContext slot is for declared children from the viewChildren array and the stepAllocateContext slot is for declared children from the stepChildren array. ◆ Also, as a result of the declare operation, NTK creates a slot in the Display template called preallocatedContext. This slot holds a symbol that is the name of the template, in this case 'Display.
A P P E N D I X Figure A-1 Declare example Templates (compile time) Calculator { Display: nil stepAllocateContext: ['Display, Display] . .} As a result of the declare, two slots are added to the Calculator template. The Display slot will eventually hold the address of the Display view. Views (run time) Calculator { _proto: Display: Display . .
Glossary Action button The small envelope button used in applications to invoke routing functions. When tapped, it displays a picker listing routing actions available for the current item. alias An object that consists of a reference to another object. An alias saves space, since the alias object is small, and can be used to reference very large objects. Resolving an alias refers to retrieving the object that the alias references. See also entry alias.
G L O S S A RY cursor An object returned by the Query method. The cursor contains methods that iterate over a set of soup entries meeting the criteria specified in the query. The addition or deletion of entries matching the query specification is automatically reflected in the set of entries referenced by the cursor, even if the changes occur after the original query was made. data definition A frame containing slots that define a particular type of data and the methods that operate on it.
G L O S S A RY flag A value that is set either on or off to enable a feature. Typically, flag values are single bits, though they can be groups of bits or a whole byte. home city The emporium the system uses to modify dialing information, time zone, and so on. It is usually the user’s home, but the user may set it to another city when traveling. font spec A structure used to store information about a font, including the font family, style, and point size.
G L O S S A RY item frame The frame that encapsulates a routed (sent or received) object and that is stored in the In/Out Box soup. NewtonScript heap An area of RAM used by the system for dynamically allocated objects, including NewtonScript objects. lexical dictionary A list of valid grammars, each specifying the format of an entity to be recognized, such as a date, time, phone number or currency value. See also enumerated dictionary and grammar.
G L O S S A RY part A unit of software—either code or data— held in a part frame. The format of the part is identified by a four-character identifier called its type or its part code. part frame The top-level frame that holds an application, book, or auto part. PCMCIA Personal Computer Memory Card International Association. This acronym is used to describe the memory cards used by the Newton PDA. Newton memory cards follow the PCMCIA standards.
G L O S S A RY template slot. For example, a field for entering phone numbers might restrict acceptable user input to numerals. rich string A string object that contains imbedded ink words. Rich strings create a compact representation for strings that contain ink words and can be used with most of the string-processing functions provided in the system software. See also rich string format. rich string format The internal representation used for rich strings.
G L O S S A RY target The object being acted upon. Sometimes the target consists of multiple items, for example, when multiple items are selected from an overview for sending. template A frame that contains the data description of an object (usually a view). A template is intended to be instantiated at run time. See also proto. text run A sequence of characters that are all displayed with the same font specification.
Index A accessing query results 11-16 accessing tasks in the To Do List application 19-24 Action button 21-3 accessing routing actions from 21-3 adding to user interface 21-4 minimum actions for including 21-9 placement of 21-4 action button GL-1 action frames 18-5 Action picker choosing a transport from 21-6 including a separator line in 21-23 types of routing actions 21-4 action template 18-5 AddAction 17-16 AddAlarm 17-11 AddAlarmInSeconds 17-11 AddAppointment, Dates method 19-11 AddArraySlot function 16
I N D E X application components overview 1-15 application data class registry 21-33 application-defined routing actions 21-23 application extensions 5-1 application name in appName slot 15-4 user-visible 15-4 application soup 16-10 appName slot 15-4, 15-10, 16-10 creating 15-11, 16-11 appObjectFileThisIn slot 15-4, 15-5, 15-10 creating 15-12 appObjectFileThisOn slot 15-4, 15-10 creating 15-12 appObjectUnfiled slot 15-10 creating 15-12 arc 13-4, GL-1 arglist array in endpoint options 23-5 array GL-1 assist
I N D E X C calendar versus the term Dates 19-9 Calendar Notes soup 19-22 Calendar soup 19-22 callback functions 15-3 registering 15-11 registering for folder changes 15-8 callback spec GL-1 defining 23-2 calling 18-3 Call transport opening routing slip for 21-29 cancelling endpoint requests 23-21 asynchronously 23-21 synchronously 23-22 cancelling task slip 18-4 CancelRequest 22-13 CanPutAway 22-18 card GL-1 card-based application 4-6 cardfile versus the term Names 19-2 caret insertion writing mode 8-3, 8
I N D E X completion CompletionScript 23-18 handling unexpected in endpoints 23-18 compressed images storing 13-18 configuration string usage 25-7 confirm 18-4 confirming task slip 18-4 conflict-resolution mechanism 18-16 constant GL-1 controlling clipping 13-12 controlling recognition in views 9-8 controls compatibility 7-1 protos 7-2 to 7-15 coordinate system 3-6 copying functions summary of 26-2 correcting intelligent assistant input 18-4 countries obtaining information about a city or country 19-28 cou
I N D E X dateKeyboard 8-27 Dates compatibility information 19-9 versus the term calendar 19-9 Dates application 19-8 adding meetings or events 19-11 controlling display features 19-21 creating new meeting types 19-17 deleting meetings or events 19-12 finding meetings or events 19-13 getting and setting information for meetings or events 19-15 getting a reference to 19-10 list of methods 19-54 moving meetings or events 19-14 soup format 19-52 soups 19-22 date search description 16-2 declareSelf slot 3-24 d
I N D E X endpoint (continued) input form 23-13 input spec 23-12 input target 23-13 input time-out 23-16 instantiating 23-10 linking to application 23-24 protoBasicEndpoint 23-1 protos 23-28 protoStreamingEndpoint 23-20 rcvOptions slot 23-17 setting options 23-8 summary of 23-25 terminating 23-10 using 23-8 endpoint interface overview 1-14 endpoint option GL-2 endpoint options setting 23-10 specifying 23-8 EnsureVisibleTopic, To Do List method 19-26 entries 11-4 entries slot 18-11 entry GL-2 entry alias GL
I N D E X filter options 23-16 use of byteProxy slot with 23-16 use of filter slot with 23-16 Find global 16-3 local 16-3 overview 1-10 Find, targeted 16-19 FindAppointment, Dates method 19-13 finder GL-2 finder frame 16-11 finder proto choosing 16-11 ROM_CompatibleFinder 16-7 soupFinder 16-7 FindExactlyOneAppointment, Dates method 19-13 finding 18-3 finding meetings or events in the Dates application 19-13 Find method 16-7, 16-10, 16-28 returning results 16-21 Find overview filing, deleting, moving items
I N D E X fonts (continued) specifying for a view 3-24 style numbers 8-18 font spec 8-3, GL-3 font specification 8-17 packed integer format 8-19 font styles 8-18, 8-25 constraining in view 8-17 forceNewEntry slot 4-16 format picker in routing slip 22-27 formatting endpoint data 23-13 Formulas roll 19-35, 19-57 compatibility information 19-36 frame 3-2, 11-2, GL-2, GL-3 framed asynchronous serial tool 24-4 frame functions and methods 26-7 frame routing format creating 21-21 frame types 18-16 free-form entry
I N D E X functions and methods (continued) ItemCompleted 22-16 KillAction 17-16 LastVisibleTopic, To Do List method 19-26 LaunchPartEntry, Extras Drawer method 19-40 LocObj 20-1 to 20-5 MakeRichString 8-24 MakeTextNote, Notes method 19-32 MeasureString 20-6 NewCity, Time Zones method 19-29 NewItem 22-13 NewNote, Notes method 19-32 NextToDoDate, To Do List method 19-25 NormalizeAddress 22-9 Notify 17-3, 17-11 OpenKeyPadFor 8-36 OpenMeetingSlip, Dates method 19-21 OpenTo, Names method 19-6 PeriodicAlarm 17-
I N D E X GetCityEntry 19-28 GetCountryEntry 19-28 GetDefaultFormat 21-11 GetDefs 5-8 GetExtraIcons, Extras Drawer method 19-41 GetMeetingIconType, Dates method 19-16 GetMeetingInvitees, Dates method 19-15 GetMeetingLocation, Dates method 19-15 GetMeetingNotes, Dates method 19-15 GetPartCursor, Extras Drawer method 19-40 GetPartEntryData, Extras Drawer method 19-40 GetRichString 8-24 GetRouteScripts 21-23 GetSelectedDates, Dates method 19-20 GetTargetCursor 21-24 GetTargetInfo 18-20, 21-10 GetTargetInfo me
I N D E X In/Out Box 1-13, GL-3 extending the user interface 22-17 input termination of in endpoints 23-17 use of InputScript message for 23-17 input buffer for endpoints removing data from 23-18 input data forms for endpoints 23-12 input events handling 8-38 input line protos 8-4, 8-12 input spec 23-12, GL-3 components of 23-12 data filter 23-16 data termination 23-14 flushing input 23-18 input form 23-13 input target 23-13 input time-out 23-16 receive options 23-17 setting up 23-18 slot applicability 23-
I N D E X keys alarm 17-12 KillAction 17-16 L labelsChanged parameter 15-16 labels filter 15-8 labelsFilter slot 15-8, 15-10 creating 15-14 labels slot 15-1, 15-6, 15-10 creating 15-11 lastFormats slot 21-12 LastVisibleTopic, To Do List method 19-26 latitude values 19-30 LaunchPartEntry, Extras Drawer method 19-40 laying out multiple child views 3-43 learningEnabledOption, user configuration variable 19-48 leftHanded, user configuration variable 19-48 letterInFieldsOption, user configuration variable 19-4
I N D E X modem setup (continued) process 25-3 profile constants 25-9 profile option 25-6, 25-7 user interface 25-2 modem setup package 25-1 modem setup service 25-1 about 25-1 required modem characteristics 25-1 user interface 25-1 modem tool preferences option 25-2 profile option 25-2 requirements 25-4 moving meetings or events in the Dates application 19-14 N name, user configuration variable 19-48 name reference 22-4, GL-4 creating 21-27 example of 21-28 Names compatibility information 19-3 versus the
I N D E X Notes application (continued) list of methods 19-57 soup 19-33 soup format 19-53 versus term paperroll 19-31 Notes stationery 19-30, 19-33 notifications 17-2, 17-10 Notify 17-3, 17-11 notify icon adding action to 17-16 numericKeyboard 8-27 O object GL-4 object storage system overview 1-5 object system functions and methods 26-7 obtaining information about a city or country in Time Zones application 19-28 online help 17-10, 18-3 'onlyCardRouting symbol 15-5 OpenKeyPadFor 8-36 OpenMeetingSlip, Dat
I N D E X periodic alarms 17-4, 17-14 persistent storage 1-3 persona GL-5 persona popup proto 19-7 phone, user configuration variable 19-48 phoneKeyboard 8-27 phrases slot 18-11 picker GL-5 pickers 6-1 about 6-1 compatibility 6-2 date 6-17 location 6-17 map 6-8 number 6-21 time 6-17 PickItems array specifying 6-37 PICT swapping during run-time 13-21 picture GL-5 pictures 13-6 setting a default 13-21 storing compressed 13-18 pitch shifting 14-9 pixel 3-6 playing event related sounds 14-3 playing sound globa
I N D E X protoFolderTab proto 15-9 protoFrameFormat 21-21 protoFullRouteSlip 22-27 protoInputLine 8-12, 8-13, 8-14 protoKeyboard 8-28 protoKeyboardButton 8-28, 8-29 protoKeypad 8-28, 8-29 protoLabelInputLine 8-13 protoListPicker using 6-26 protoNewFolderTab 15-6, 15-9 protoNewFolderTab view 15-11 protoNumericKeyboard 8-28, 8-30 protoPeriodicAlarmEditor 17-4, 17-14 protoPersonaPopup 19-7 protoPhoneKeyboard 8-28, 8-30 protoPrinterChooserButton 21-29 protoPrintFormat 21-18 protoRoutingFormat 21-22 proto slot
I N D E X receiving large objects 23-20 recognition flags vAddressField 9-31 vAnythingAllowed 9-32 vCapsRequired 9-31 vClickable 9-32 vCustomDictionaries 9-31 vDateField 9-33 vGesturesAllowed 9-32 vLettersAllowed 9-31 vNameField 9-31 vNoSpaces 9-32 vNothingAllowed 9-32 vNumbersAllowed 9-31, 9-33 vPhoneField 9-33 vPunctuationAllowed 9-31 vShapesAllowed 9-32 vSingleUnit 9-32 vStrokesAllowed 9-32 vTimeField 9-33 recognition functions 10-54 recognition menu 8-14 recognition system overview 1-7 recognized text
I N D E X RouteScript 21-24 example of 21-25 routeScripts slot 21-22, 21-23, 21-24 defining a method identified by 21-24 routing about 21-1 application-specific 21-22 compatibility 21-8 current format 21-8 data types 21-7 dataTypes slot 21-5 formats 21-5 handling multiple items 21-14, 21-24 in box 21-1 lastFormats slot 21-12 out box 21-1, 21-3 programmatic sending 21-26 protoActionButton 21-4 protoFrameFormat 21-21 protoPrinterChooserButton 21-29 protoPrintFormat 21-18 protoRoutingFormat 21-22 providing tr
I N D E X scrolling controlling in In/Out Box view def 21-36 speeding up 3-46 scrollRect 7-3 scrollUpSound 14-2 search method 16-7 search methods 16-6, 16-10 examples 16-16 implementing 16-15 returning results of 16-21 scope parameter to 16-10 StandardFind 16-15 Selected button 16-2, 16-3 selected Finds 16-9 targeted find 16-19 selection hits testing for 8-38 self GL-6 Send 21-26 send button in routing slip 22-28 sending data with endpoints 23-11 sending large objects 23-20 SendRequest 22-8 serial options
I N D E X sound (continued) synchronous 14-7 waiting for completion 14-7 sound channel characteristics of 14-2 creating for playback 14-6 deleting 14-6 using 14-5 sound chip 14-8 sound frame cloning 14-5 creating 14-5 setting sampling rate 14-9 sounds event related 14-2 for predefined events 14-2 in ROM 14-2 sound slots hideSound 14-2 scrollDownSound 14-2 scrollUpSound 14-2 showSound 14-2 sound structures sound frame 14-3 sound result frame 14-3 sound techniques advanced 14-8 soup 11-3, GL-6 affected by sy
I N D E X synonyms 18-3 system data 19-44 list of functions 19-58 system messages in automatic views 8-8 system resets 2-7 system services 16-1, 17-1 alarms 17-3 automatic busy cursor 17-5 filing 15-1 idling 17-2, 17-9 notify icon 17-5 online help 17-3 power registry 17-7 status slips 17-6 undo 17-1, 17-8 user alerts 17-3 system soup storing application preferences 19-45 T tabbing order 8-36 tags 15-1 target GL-7 getting and verifying for routing 21-10 of filing 15-1 of routing 21-3 specifying for filing
I N D E X Time Zones application 19-27 adding a city 19-29 compatibility information 19-27 getting a refernce to 19-28 list of functions and methods 19-57 obtaining information about a city or country 19-28 TitleClickScript method 15-7 defining 15-15 title slot 16-7, 16-10 and Find overview 16-7 creating 16-11 todo items 18-3 To Do List application 19-22 accessing tasks 19-24 checking-off tasks 19-25 compatibility information 19-23 creating and removing tasks 19-24 getting a reference to 19-23 list of meth
I N D E X UnRegFolderChanged function 15-3, 15-10, 15-18 UnRegFormulas 19-36 UnRegInboxApp 21-34 UnRegInfoItem, Dates method 19-21 unregistering the task template 18-19 UnregisterOpenKeyboard 8-36 UnRegLogin 17-25 UnRegPowerOff 17-26 UnRegPowerOn 17-24 UnRegTheseAppClasses 21-33 UnRegTransport 22-6 UnRegUserConfigChange 19-45 user alert 17-3, 17-11 user configuration data 19-45 user configuration variables address 19-47 cityZip 19-47 company 19-47 country 19-47 countrySlot 19-47 currentAreaCode 19-47 curre
I N D E X view (continued) creating 3-28 custom fill pattern 3-21 custom frame pattern 3-21 declareSelf slot 3-24 declaring 3-27 defining characteristics of 3-8 dependencies between 3-43 dirtying 3-33 displaying 3-33 finding bounds 3-39 hiding 3-33 highlighting 3-42 idler for 17-2, 17-9 laying out multiple children 3-43 limiting text in 3-17 memory usage 3-45 modal 3-38 optimizing performance 3-44 origin offset 3-20 pop-up views 3-37 redrawing 3-44, 13-10 root 3-6, GL-6 screen-relative bounds 3-12 showing
I N D E X viewFlags (continued) vApplication 3-47 vCalculateBounds 3-47 vCapsRequired 9-31 vClickable 3-47, 9-32 vClipping 3-47 vCustomDictionaries 9-31 vDateField 9-33 vFixedInkTextStyle 8-17 vFixedTextStyle 8-17 vFloating 3-47 vGesturesAllowed 9-32 vLettersAllowed 9-31 vNameField 9-31 vNoFlags 3-47 vNoScripts 3-47 vNoSpaces 9-32 vNothingAllowed 9-32 vNumbersAllowed 9-31, 9-33 vPhoneField 9-33 vPunctuationAllowed 9-31 vReadOnly 3-47 vShapesAllowed 9-32 vSingleUnit 9-32 vStrokesAllowed 9-32 vTimeField 9-33
T H E A P P L E P U B L I S H I N G S Y S T E M 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.