newton technology journal: volume 1, number 2

24
C omi ng S oon: N e wtonToolk i t 1 . 5 by T ony Es pi noza  A pple C omputer, Inc.  T he NTK Tea m lea rned alot from Newton developer sduri ng the pas t two y ears . Your feedbac k at developer conferencesand through the on- li ne forum shashelped in our effortsto bring y ou apowerful, produc ti ve NTK. You c an ex pec t NT K 1 . 5later thisSp ri ng. For now , here’sa qu ick look at s ome of the e xc iti ng n ew fea turesi n 1.5. P RODUCTIVITY  E NHANCEMENTS A NDN E WC AP AB I LI TI ES A pri marygo al for NTK ha salwa y sbee n to providea hi gh- produc ti vi tyenv ironmen t; ve rs ion1. 5fea turesimprov em en tsto s trea mline the deve lopment proces s . For starters , the brow s er i sea s ier to na viga te. The s lot lis t now respondsto s ing le clic ksins tead of double cli c ks , an d the pop- li stsfor Methods  and Attributes  have be en alpha beti c allyordered. NTK 1. 5brows ers nowena ble you to cut, copy , and pas te vi ew sand s lotswithout havi ng to open a lay out wi ndow . You can als o bui ld newkindsof pac kag es . NT K 1.0 focus ed on appli cati on pac kag es . W ith 1. 5, developersc an c hoos e from a rang e of di fferent targ et ou tput forma ts . For exa mple, y ou ca n ea s ilycreate auto, s tore, and dic tiona ryparts. Perha psthe mos t exc iti ng c ha ng e isthe ne wab ili tyto con vert a des ktop font i nto a New ton font part and inc lude i t w ith y our ap pli c ation. Tool News Comin g S o on: Ne w to n T o olkit 1 .5 1 New tonScriptTechn iques Ne w to n S c ript P e rform a n c e Tu n ing 1 Developer Group News New ton Deve loper Eveni ng Bring sNew tonCommun ity Up to Da t e 3 New tonScriptTechn iques SteppingThrough Rou t ing 5 Newton News Apple Announ c esNewNew ton Mes s ag ePad12 0, Communi ca ti ons and Sof t ware Solutions ! 1 1 Advanced Techniques A dvanced Debugging 20 Licensee Specifics Marc oSoftw areArchi tec ture, V ers ion1.0 22 continued on page 13 continued on page14  VolumeI, Number 2 A p ril 1995  g  g  N e w t o n T echn o l o   J O U R N A L ® Ne w t onS cript Performance Tuning by J ul i e M cK ee han and Neil R hodes  C al liope E nterpris e s , Inc.  T here are a numbe r of areasw ithi n the New ton s y stem that affect New ton appl ica ti on performa nc e. The more important of thes e are as are: New tonSc ri pt, the viewsy s tem, an d New ton data s torage des ign( s oups ) . T hisartic le w ill c ove r the firs t are a, New tonS c ri pt. Optimi z ing the views y s tem isdiscu s s ed i n “ Performance an d the Vi ewSystem,” byMike Eng be r i n PIE Dev elope r’ sMag a z ine. W hen y ou wa nt t o optimize the perf or manc e of New tonScri pt within y our applic ation y ou needto addres sthree import ant area s : W riting g e ne ra llyeff ic ient codein the firs t place. Know ingthe s pee dies t w ay sof d oingthing s w ithinNew tonS c ript. Us ingmemoryc orrec tly ; thisi nvo lves know ing howto mini mi ze y our us e of the frame hea p me morybymaxi mi zing the am ount of codeyou keep i n ROM an d havi ng c ode that all oca testhe correct am ount of mem oryto provide the fas tes t, most eff icient useof RAM whe n y ou do need to us e it. E FFICIENTC O DE O PTI M I ZINGTHEH O T S POTS Let usaddres seac h of thes e i s s uesin turn, s tart ing w ith s ome re s ource sf or wri tingeffic ient c ode. Tool News NewtonScript Techniques I ns ide This Is su e © 1994, A pple C omputer, Inc. and Call i ope Enterpr i s es , Inc.

Upload: pablomarx

Post on 03-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 1/24

Coming Soon:Newton Toolkit 1.5by Tony Espinoza Apple Computer, Inc. The NTK Team learned a lot from Newtondevelopersduring the past two years. Yourfeedback at developer conferencesand throughthe on-line forumshashelped in our effortstobring you a powerful, productive NTK. You canexpect NTK 1.5 later thisSpring. For now,here’sa quick look at some of the exciting newfeaturesin 1.5.

PRODUCTIVITY ENHANCEMENTSAND NEW CAPABILITIES

A primarygoal for NTK hasalwaysbeen toprovide a high-productivityenvironment;version1.5featuresimprovementsto streamlinethe development process. For starters, thebrowser iseasier to navigate. The slot list nowrespondsto single clicksinstead of double clicks,and the pop-listsfor Methods and Attributes havebeen alphabeticallyordered. NTK 1.5browsersnowenable you to cut, copy, and paste viewsandslotswithout having to open a layout window.

You can also build newkindsof packages.NTK 1.0 focused on application packages.With 1.5, developerscan choose from a range

of different target output formats. Forexample, you can easilycreate auto, store, anddictionaryparts. Perhapsthe most excitingchange isthe newabilityto convert a desktopfont into a Newton font part and include itwith your application.

Tool NewsComing Soon: Newton Toolkit 1.5 1

NewtonScript TechniquesNewtonScript Performance Tuning 1

Developer Group NewsNewton Developer EveningBringsNewton CommunityUp to Date 3

NewtonScript TechniquesStepping Through Routing 5

Newton News

Apple AnnouncesNewNewtonMessagePad 120, Communicationsand Software Solutions! 11

Advanced TechniquesAdvanced Debugging 20

Licensee SpecificsMarco Software Architecture,Version 1.0 22

continued on page 13 continued on page 14

Volume I, Number 2 April 1995

g g Newton Technolo J O U R N A L

®

NewtonScriptPerformance

Tuningby Julie McKeehan and Neil Rhodes Calliope Enterprises, Inc.

There are a number of areaswithin the Newtonsystem that affect Newton applicationperformance. The more important of these areasare: NewtonScript, the viewsystem, and Newtondata storage design (soups). Thisarticle willcover the first area, NewtonScript. Optimizingthe viewsystem isdiscussed in “Performanceand the ViewSystem,” byMike Engber in PIEDeveloper’sMagazine.

When you want to optimize the performanceof NewtonScript within your application youneed to addressthree important areas:

• Writing generallyefficient code in the firstplace.

• Knowing the speediest waysof doing thingswithin NewtonScript.

• Using memorycorrectly; thisinvolvesknowing howto minimize your use of theframe heap memorybymaximizing the

amount of code you keep in ROM andhaving code that allocatesthe correctamount of memoryto provide the fastest,most efficient use of RAM when you do needto use it.

EFFICIENT CODE –OPTIMIZINGTHE HOT SPOTS

Let usaddresseach of these issuesin turn, startingwith some resourcesfor writingefficient code.

Tool News NewtonScript TechniquesInside This Issue

© 1994, Apple Computer, Inc. and Calliope Enterprises, Inc.

Page 2: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 2/24

Apri l 1995 Newton Technology Journal

2

Newton platform newstravelsfast, andwith the recent seriesof Newtonannouncementsin the last few months,newsistraveling even faster with theplatform’slatest entrants. The newestadditionsto the Newton product familyinclude two new hardware devices– onefrom Motorola and one from Apple – and anumber of new communicationsdevices.With these new productscome an infinitenumber of wirelesscommunicationsolutionswaiting to be built bydevelopersand delivered to consumers. The messagebehind the recent Newton DeveloperEvening at MacWorld focused on themomentum that hasbeen building aroundthe platform and the opportunitiesthathave now become so clear: Newton istheleading platform in the PDA marketplace,Apple’slicenseesare deliveringdifferentiated hardware productsto helpgrow the market, and wirelessoppor-tunitiesare a growing reality. With all of these resourcesat hand, there hasneverbeen a better opportunityfor developerstostep-up to the Newton platform andbecome a part of thisnew marketdevelopment adventure.

The Newton Developer Evening pulledtogether the latest newsand successesonthe platform and offered a kaleidoscopicviewof the kindsof opportunitiesthat awaitdeveloperswith the Newton platform.Motorola, one of Apple’sNewton Licensees,showcased their newNewton device, the

Marco® WirelessCommunicator. TheMarco device differentiatesitself from

Apple’sMessagePad byfocusing on built-inwirelesscommunicationssolutions.Motorola hasopened the door fordevelopersto deliver an unlimited numberof solutionsto both consumer andcorporate marketplaces. Likewise, Applehasdelivered a number of communicationsfeaturesfor itsMessagePad and otherNewton devices. Apple’smodem set-uppackage, in conjunction with one of themanycellular-readyPCMCIA cardsavailableon the market, providesdeveloperswiththe widest arrayof wirelesscommunicationsever. The corporatemarketplace will most certainlylook toNewton devicesto deliver up-to-the-minutedata and information from serversandcentralized databasesto itsfield salesandoff-site work forces. Likewise, consumerswill embrace the technologyasit readilydeliverstheir latest stock quotes, newsande-mail straight to their fingertips, far awayfrom easyaccessto phone linesand desk-top computers. Other technologycompaniespromise you’ll be able to faxfrom the beach someday. Newton deliverson that promise today.

In addition to the Marco device fromMotorola, Apple hasalso added a newMessagePad to the product line. It offersimproved screen clarityand more memoryto the user. The MessagePad 120 delivers2MB of RAM, leaving the developer moreroom to increase their applications’capabilitiesand power. The MessagePad120 Type II PCMCIA slot nowoffersup to

… … … … … … … … … … … … … … … … … … … …

Published by Apple Computer,Inc.

Lee DePalma Dorsey• Managing Editor

G erryKane • Coordinating Editor,Technical Content

Tony Espinoza • Coordinating Editor,Technical Tools Marketing

D avid G lickman • Coordinating Editor, Business Content

G abriel Acosta-Lopez • Coordinating Editor, DTS and Training Content

Philip Ivanier • Manager, Newton Developer Relations

Technical Peer Review Board J. Christopher Bell,Bob Ebert, Jim Schram,M aurice Sharp, Steve Strong,Bruce Thompson

Contributors D avid Baum,Julie McKeehan, N eil Rhodes,

PattyTulloch

… … … … … … … … … … … … … … … … … … … …

Produced by Xplain Corporation

N eil T icktin • Publisher

Scott T Boyd • Editor

John Kawakami • Editorial Assistant

Judith Chaplin • Art Director

… … … … … … … … … … … … … … … … … … … …

© 1994 Apple Computer,Inc.,1 Infinite Loop,Cupertino,C A95014,408-996-1010. All rightsreserved.

Apple, the Apple logo, APD A, AppleDesign, AppleLink,AppleShare, Apple SuperDrive, AppleTalk, HyperCard,LaserWriter,Light Bulb Logo,Mac,MacApp,Macintosh,Macintosh

Q uadra, MPW, N ewton, N ewton Toolkit, N ewtonScript,Performa, Q uickTime, StyleWriter and WorldScript aretrademarksof Apple Computer, Inc., registered in the U.S. andother countries. AO CE, AppleScript, AppleSearch, ColorSync,develop, eWorld, Finder, O penDoc, Power Macintosh,Q uickDraw, SNA •ps, StarCore, and Sound M anager aretrademarks,and AC OT isa service mark of Apple Computer, Inc.Motorola and Marco are registered trademarksof Motorola, Inc.NuBus is a trademark of Texas Instruments. PowerPC is atrademark of International BusinessMachinesCorporation, usedunder license therefrom. Windowsis a trademark of MicrosoftCorporation and SoftWindowsisa trademark used under licenseby Insignia from Microsoft Corporation. UNIX is a registeredtrademark of UN IX System Laboratories, Inc. CompuServe,Pocket Q uicken byIntuit,CIS Retriever byBlackLabs,PowerFormsbySestra, Inc.,ACT! bySymantec,Berlitz,and all other trademarks

are the propertyof their respective owners.Mention of products in this publication is for informationalpurposes only and constitutes neither an endorsement nor arecommendation.All product specificationsand descriptionsweresupplied by the respective vendor or supplier.Apple assumesnoresponsibility with regard to the selection, performance, or use ofthe products listed in this publication. All understandings,agreements,or warrantiestake place directlybetween the vendorsand prospective users. Limitation of liability: Apple makes nowarrantieswith respect to the contentsof productslisted in thispublication or of the completenessor accuracyof thispublication.Apple specifically disclaims all warranties, express or implied,including, but not limited to, the implied warranties of

g g Newton Technolo J O U R N A L

®

Volume I, Number 2 April 1995

by Lee DePalma Dorsey, Managing Editor

Editor’s Note

continued on page 12

Apple Computer, Inc.would like to thank Xplain Corporation (the publishersof MacTech™ Magazine)

for lending their expertise in producing the Newton TechnologyJournal.

Page 3: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 3/24Newton Technology Journal April 1995

3

In the midst of hecticMacWorld schedulesand other related events,more than 400 Newton developersgathered for the Newton PlatformDeveloper Evening on January4th, 1995. Billed asan “update fromApple’sPersonal Interactive Electronic(PIE) Division and itsNewtonlicensees,” the event commenced with an addressfrom Shane Robison,VP and General Manager of the PIE division. Following Robison’stalkwere presentationson the recentlyintroduced Newton DeveloperPrograms, demonstrationsof the newMarco Communicator fromMotorola and other keywirelesscommunicationstechnologies, aswell asa recap of the PDA market for the past year.

Robison stressed the importance of the Newton developer base,emphaticallystating, “We’re here todaybecause of you!” He emphasizedthat the number of applicationsavailable for the platform continuestogrowand to contribute significantlyto the platform’slong term success.Todayworldwide there are approximately100 commercial applications,another 300 vertical in-house applicationsin use or in pilot phases, and600 shareware titles, ranging from utilitiespackagesto BookMaker-basedreference materials.

Robison stressed hiscommitmentsto investing in PIE’sDeveloperRelationsinfrastructure, listening to feedback from the developercommunity, and continuing to deliver newtools. Elaborating about tools,Robison sketched out developmentspast the current NTK, specificallymentioning the addition bythe Toolsteam of a newcompiler and profilerfunctionality, with the eventual goal of full C+ + accessfor developers.

In an overviewof the Platform Marketing goalsof the division,Robison outlined the wide varietyof Newton-based productsthat Apple

and itsNewton licenseeswill continue to produce. From intelligentorganizerslike the MessagePad 120 to the wirelesscommunicator, Marcodevice, the Newton OS will continue to offer the flexibilitynecessaryforthese newdevicesto evolve. Asthe diagram belowillustrates, the Newtonplatform isdriven bysolutions, with tools, cross-platform connectivity,and hardware productscombining to meet the demandsof thecommercial and vertical markets.

Robison concluded hisaddresswith a call to action for developers.Asmomentum for the platform buildsand PIE’scommitment todelivering more and better toolsremainsstrong, opportunitiesopenfor Newton developers.

MOTOROLA ’S MARCO WIRELESS COMMUNICATOR

With the introduction of Motorola’sMarco® WirelessCommunicator, PIE’sNewton licensee partnerscontinue to broaden theNewton platform with highlydifferentiated products. RickLane, general manager of thePersonal CommunicatorProduct organization atMotorola outlined the MarcoCommunicator and Motorola’scommitment to the Newtonplatform. The Marco device isbased on the latest Newton OS(1.3) and integratesan ARDIS two-waywirelessRF modem to deliver anintegrated solution for wide areawirelessdata communications. Userswill have accessto RadioMail services:store and forward mail, gatewayto the

Internet, sending faxes, and receiving stock quotes, news, and otherinformation. Marco WirelessCommunicator userscan also accesstheARDIS PersonalMessaging service and send or receive messageswithother PersonalMessaging usersanywhere within the ARDIS network.

For more information about the Marco Communicator anddevelopment opportunities, developerscan contact Patrick Pahl, BusinessDevelopment Manager at Motorola, at the following Internet address:Patrick_Pahl@ msmail.wes.mot.com

Newton Platform

IntelligentOrganizers

WirelessCommunicators

Apple Products Licensees

Tools andDesktop Connectivity

SolutionsCommercial, Vertical, Communications

Newton Developer EveningBringsNewton CommunityUp to Dateby David Glickman, Apple Computer

Developer Group News

continued on page 4

Page 4: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 4/24

Apri l 1995 Newton Technology Journal

4

DEVELOPER PROGRAMS

Lee Dorsey, Manager of Developer Programsin PIE, described the expansionof programsfor Newton platform developersand laid out the road mapfor these programsin 1995.

The recentlyintroduced Newton AssociatesProgram offershighqualityself-support for Newton developerswith accessto “developers-

only” Newton forumson AppleLink (at AppleLink discount rates) , theNewton monthlymailing, and hardware purchase privileges. The NewtonAssociatesProgram costs$400 per year.

The Newton PartnersProgram hasbeen revamped with newofferingsat the reduced yearlyprice of $2500. In addition to all Newton Associatesbenefits, Partner memberswill receive expert-level technical support viae-mail, opportunitiesto participate in select marketing opportunities, andadditional hardware purchasing privileges.

The Executive PartnersProgram isdesigned specificallyfor in-housecorporate developers. Thisprogram offersa designated technical leadfrom the PIE team, design and code reviews, training, development tools,and executive briefings. Thisprogram costs$25,000 per year and isavailable to a small group of corporate customers.

In outlining Developer Programsplansfor 1995, Dorseyannouncedthat support programswill be availableworldwide in the Spring of 1995. Inaddition, Developer Relationsiscreating newco-marketingopportunitiesin areassuch assolutionguides, trade showparticipation, andpressrelations.

For more information on NewtonDeveloper Programs, contact Apple’sDeveloper Support Center atDEVSUPPORT@ APPLELINK.APPLE.COMorat 408-974-4897. In addition, a fulldescription of the Newton Associatesand PartnersProgramsispublished inthe February1995 issue of the NewtonTechnologyJournal.

WIRELESS COMMUNICATIONS DEMOS

Susan Schuman, CommunicationsProduct Manager in PIE, opened thesection of communicationsdemonstrationswith an overview of theNewton Platform wirelesscommunicationsstrategy. In building uponNewton’sbuilt-in software communicationscapabilities– faxing andNewtonMail – Schuman outlined the current effortsunderwaytoprovide toolsfor the continued development of Newton-savvy

communication products.The Communicationsgroup will deliver a modem-enabler package to

the entire Newton community(developersand users) . I n conjunctionwith modem-setup packagesfor specificcellular-readyPCMCIA cards, themodem-enabler technologywill give usersaccessto a myriad of PCMCIAmodem cardsfor wirelesscellular faxing and e-mail.

In a demonstration of PIE’scommitment to opening up the Newtonplatform for newcommunicationsdevelopments, several wirelesscommunicationsdemonstrationswowed the crowd. Schuman and AviWeiss, CommunicationsEngineer in PIE, demonstrated cellular faxing

using the Motorola Cellect cellular-readyPCMCIA card. Weissalso sent apage using ExMachina’sNotifysoftware and the Cellect card.

Dayna Communicationsdemonstrated the Serial Roamer RF PacketwirelessLAN technology, using a prototype PCMCIA-based Serial Roamercard with a MessagePad. Ed Colby, President of WayfarerCommunications, demonstrated hiscompany’sclient/server technology

for “integrating Newton-based productsinto enterprise informationsystems, enabling custom application development” in the areasof dataaccess, formscompletion, and mobile communications. With a WindowsNT server asthe backbone, Wayfarer’stechnologyallowsNewton devicesto accesshost information in real time. Colbyannounced the availabilityof the Development Kit for Wayfarer’stechnologyfor February1995.

NEWTON PLATFORM MARKETINGKen Wirt, PIE’sDirector of Marketing, discussed the marketing strategyfor the Apple MessagePad familyof productsand the current state of thePDA market. The chart belowoutlinesthe two distinct marketsfor theMessagePad: individual userslooking for a complete solution for businessproductivityneeds; and vertical marketsin which large businessescreatecustom solutionsfor keyareassuch assalesforce automation, outside

plant management, and healthcare.Wirt also discussed analysts’ viewsof the projected PDA market

growth and Newton-based productswithin that industry. In general, thePDA market isprojected to increase approximately40% in 1995 over 1994figures, with an installed base estimated at 5 million unitsin 1999.Currently, Newton-based productshave a 60% market share, with aprojection to continue to lead the market in the year 2000 with a 40%

market share.In 1995, Wirt seesthe most significant growth for the Newton platform

in the vertical development area, driven bythe emerging wirelesstechnologies, continued developmentsfrom Newton licensees, and theincreased interest in forms-based technologiesfor Newton-based devices.

BRINGING THE EVENINGTOA CLOSE ...The Newton Developer Evening wrapped to a close with Wirt’s

positive market figures, a brief Q& A, and a fewhoursof mingling withPIE’sstaff over bountiful food, drinksand music. NTJ

IndividualIndividual VVerticalertical

What:What:

Who:Who:

Benefit:Benefit:

Advantage:Advantage:

Handheld device thatbegins where Organizers end

Mobile BusinessProfessionals

• Instant Access to Critical Info• Personal Productivity

• Breadth and depth of solutions• Desktop Connectivity• Communications solutions• Hardware and Software Design

Mobile client for datagathering and access

Mobile Workforce(Sales Force, Healthcare…)

• LowCost Solution• Mobility

• Better tools• Price / Performance• Communications Solutions

Page 5: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 5/24Newton Technology Journal April 1995

5

INTRODUCTION

Routing presentsa varietyof complex implementation tasks. To help clarifythese tasks, thisarticle first stepsthrough the basiccomponentsof routingand then showsthe implementation of four routing elements: beaming,printing, faxing and mailing. Bythe end of thisdiscussion, the programmershould have a clear understanding of the Newton routing architecture and of what isrequired to implement routing in an application.

THE ROUTING FRAME

Your application’srouting frame indicatesto the Newton operating systemwhich routing functionsit supports, and also ensuresthat these functionsappear in the Action Button picker. The itemsthat you find listed in a typicalrouting button usuallyinclude: Duplicate, Delete, Print, Fax, Mail, and Beam.Each of these itemsin turn correspondsto a slot in the routing frame:

routingFrame := {print: …,fax: …,zap: …,mail: …,duplicate: …,delete: …

}

Each of these routing frame slotsisitself a frame containing two or threeslotsof itsown. To give you a better idea what thislookslike, here isthesame routing frame with more of the detail filled in:

routingFrame := {print: {

title: "Print Note",routeForm: 'printSlip,formats: [kFormatSymbol],

},fax: {

title: "Fax",routeForm: 'faxSlip,formats: [kFormatSymbol],

},zap: {

title: "Beam",routeForm: 'zapSlip,

},mail: {

title: "Mail",routeForm: 'mailSlip,formats: [kFormatSymbol],

},separator: nil, // dotted line in pickerduplicate: {

title: "Duplicate",routeScript: 'DuplicateActionScript,

},delete: {

title: "Delete",routeScript: 'DeleteActionScript,

},card: ROM_cardAction,

};

The Newton operatingsystem fillsin the itemsin the action picker inpreciselythe same order that it findsthem in thisroutingframe (makingthisthe singular case in Newton programmingwhere the order, not the names, of the elementsin a frame matters). Asyou can also see in the example above, aslot with a nil value specifiesa separator line. In thiscase, the first slot found isprint . The operatingsystem then looksin the title slot or callsthefunction in the GetTitle slot of the print frame to determine what textstringto put in the Action button list. Given the above title slotsof each actionin the routingframe, you would end up with a Action button like this:

Now, starting with the print slot, here are the routing action’sslotsand theirfunctions:

print: {title: "Print Note",routeForm: 'printSlip,formats: [kFormatSymbol],

},

When the user picksthe “Print Note” item in the action button, the symbolin the routeForm slot isused to determine the slip to open. In thiscase, the routeForm slot containsa reference to the system symbolprintSlip .

The formats SlotThe last slot in the print frame isa formats slot. Thiscontainsan array

of symbolsthat specifythe formattingstylesavailable to the user. In the example,there isonlyone style, kFormatSymbol . These stylesare displayed in

the format picker that the user seeswhen selectingan appropriate routingfunction (for example, mailing, printing, faxing, and so on). Different formatpickersmayhave the same typesof formats(see Figure2) or onesthat vary:

Stepping through Routing

© 1994, Apple Computer, Inc. and Calliope Enterprises, Inc.

NewtonScript Techniques

Page 6: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 6/24

Apri l 1995 Newton Technology Journal

6

Figure 2

The Other SlotsWith the exception of the card slot, the rest of the slotsin the routing

frame are quite similar in their construction. Here isan overviewof the

contentsof each:

fax routeForm: ‘faxSlip System slip

zap routeForm: ‘zapSlip System slip

mail routeForm: ‘mailSlip System slip

delete routeScript: ‘DeleteActionScript

A method you provide

duplicate routeScript: ‘DuplicateActionScript

A method you provide

THE APPLICATIONAND ITS REQUIRED SLOTSBecause the routing frame istypicallya slot in your base viewtemplate, youwill have to ensure that the system knowsabout your routing capabilitieseven when the application isnot open. Thus, at your application’sinstallation time, itsrouting frame needsto be installed into the globalrouting frame. The following line in your InstallScript willaccomplish this:

routing.(kAppSymbol) := packageFrame.theForm.routingFrame;

Some of the routing functionsalso require the addition of certain slotstoyour application base view. These slotsare: appSymbol , target ,targetView . These are nowdescribed in turn.

appSymbolThisslot containsyour application symbol.

targetThe target slot identifiesthe frame that isbeing acted upon bytherouting action. It isup to you to maintain the contentsof thisslot.

targetViewThe targetView isused byseveral partsof the Newton system,including routing and filing. When your application registersyour routingframe, your base viewwill actuallyget routing messages, which, in somecases, include target and targetView asparameters. Generally,the value of thisslot will be your application base view. Thisviewispassed asa parameter to the routeScript methods.

IMPLEMENTING ROUTINGThissection discussesthe implementation of four routing actions: beaming,printing, faxing, and mailing. ( We assume that your application alreadysupportsduplicate, delete, and card actions.) First, you will find a checklistof itemsneeded to support each particular routing action and then you willstep through the actual implementation. Note that implementing onerouting action makesthe next easier; once you support beaming, you willhave lessto do to implement printing. Let usbegin with beaming.

ADDING BEAMINGTo add beaming support to your application, you need to complete the

following steps:

The Checklist1. Add “Beam” to the action picker.2. Add a title for itemsthat are routed to the In/Out Box.

3. Test sending and receiving an item.4. Handle putting awayan item on a receiving Newton.

1. Add Beamto the Action PickerAdd a newbeam slot to the routing frame of your application. Thisslot

should be standard from application to application, so use thiscode:

zap: {title: "Beam",routeForm: 'zapSlip,

},

If Beam isthe first routing action in the frame, then the title slot stringshould be “Beam Object” (where Object standsfor whatever isappropriatefor your application) instead of just “Beam.”

2. Add a Title for Items that are Routed to the In/Out BoxTo support titlesfor itemsin the In/Out Box you need to add a

SetupRoutingSlip method to the application base template. Hereisan example of thismethod:

func(fields)begin

fields.title := info from target && DateNTime(Time());en d

Thismethod should create a title slot with a title that isdescriptive to theuser. For instance, providing the date and information that identifiesthetarget will make it easier for the user to recognize a particular entryin theIn/Out box. The title should be no more than 44characterslong; it isusedboth in the Out Box of the sender and in the In Box of the receiver. If neces-sary, append an ellipsischaracter to handle the displayof longer strings.

3. TestingSendingand Receivingan ItemAfter implementing routing in the action picker and adding your

SetupRoutingSlip , you should be able to beam an item. To test,set the Beam preferenceson the receiving Newton to those found inFigure3. IMPORTANT: Make sure the Inspector isnot connected while thebeaming occurs.

Figure 3

Page 7: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 7/24Newton Technology Journal April 1995

7

4. Handle PuttingAway an Itemon the ReceivingNewton

To handle putting awayan item on a receiving Newton, there are severalconditionsthat you need to take into account:• A beam can be received when your application isclosed.

• A beam can be received before your application hasever been run, andthusyour soup maynot exist on the receiving Newton.

• A received item maycome from a non-existent folder.

Each of these conditionsmust be handled properlyin yourPutAway method. When a Newton receivesa beam and the userselects“Put Away” (or has“Put awaybeamsimmediately” set), thePutAway message issent to the application with a matching applicationsymbol. For a trickier approach, a sending application could modifytheappSymbol slot in the fields frame (in theSetupRoutingSlip method) and beam to a different application. Forinstance, our application could beam a name to the Namesapplication.

Nowthat you have an idea of the type of conditionsyou need to accountfor in your method, look at a sample PutAway . Remember thatPutAway isa slot in your application base view:

func(item)begin

local newEntry := item.body;local theSoup := nil;local appIsOpen := self.appSoup;

CheckThatFolderExists(newEntry);if appIsOpen then

theSoup := appIsOpen ;else begin

theSoup := call kRegisterCardSoupFunc with(kSoupName, kSoupIndexes, kAppSymbol, kAppObject);

end;

theSoup:AddToDefaultStore(newEntry);

if not appIsOpen thencall kUnRegisterCardSoupFunc with (kSoupName);BroadcastSoupChange(kSoupName);

en d

Created in the InstallScript

r out i ng:

…| MyFor mat: App: Si gnatur e|…

…| App: Si gnat ure| :…

GlobalsRoutingframe

Root view

Viewproto:par ent :

(using BuildContext)

_pr ot o:t i t l e: "aFormat"mai nFor mat :

Format Frame

Print Format

ROM_coverPageFormat

protoPrintFormat _pr ot o:pr i ntNext PageScri ptst epChi l dren: [ …]

routi ngFrame : = {pr i nt : {

t i t l e: " Pr i nt i t em" ,routeForm: ' pr i ntSl i p,f ormats: [ ' | MyFormat: App:Si gnature| ] ,

},f ax: …,beam: …,mai l : …,

}

{…

}

{…

}

Base Template Slot

Figure 4

Page 8: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 8/24

Apri l 1995 Newton Technology Journal

8

If your application usessoups, then the above method is fairly standard. Itisworth notingin thismethod that the item frame isroughlythe same asthe fields frame from SetupRoutingSlip . Also, item.bodycontainsthe target from the sendingNewton.

The CheckThatFolderExists method should onlybe used by

those applicationsthat support folders. Further, it isused to handle aparticular type of condition, which isdemonstrated bythe following case: I f Jean sendsan item from “JeansFolder” to Fred’sNewton, what folder shouldthe item appear in if Fred doesn’t have a “JeansFolder?” Answer: “Unfiled.”The CheckThatFolderExists method comparesthe labelsslot of itsargument to the list of folderson thismachine. If it findsit, it doesnothing, otherwise it setsthe labels slot value to nil .

Now, look at howthe sample PutAway code dealswith the situationin which the application isnot open on the receiving Newton. Thisapplication storesthe open soup in a slot called appSoup which it nil sout in the application’s viewQuitScript . If the application isrunning,PutAway usesthat soup. I f the application isnot running,PutAway calls kRegisterCardSoupFunc to create the soup(if necessary) on all writable stores(including the default store). Notice thatif we called kRegisterCardSoupFunc , we must callkUnregisterCardSoupFunc .

The BroadcastSoupChange function will call theapplication’s SoupChanged method, which will redisplaythe viewif the application isopen. If you wanted to be robust in your programming, itwouldn’t hurt to have an exception handler in thiscode aswell:

trytheSoup:AddToDefaultStore(…)

onException |evt.ex| do beginif not appIsOpen then

call kUnRegister…Rethrow();

end;if not appIsOpen then

call kUnRegister…

Unfortunately, AddToDefaultStore doesn’t currentlythrowanexception, so the exception handler will not execute. In the future, though,AddToDefaultStore might throwexceptionsand then thiscodewould correctlyhandle it.

ADDING PRINTINGThe Newton implementation of printing issignificantlydifferent, thougheasier, than typical desktop machines. Remember that, within the routingglobal, your application’srouting frame isstored in a slot whose symbol isour application signature. I n the routing frame, there isa formats slot

that isan array. Thisarraycontainsan entryfor each item in the formatpicker of the print slip. Also, each entryin thisarrayisa symbol. In the rootview, each of these symbolsisa slot that pointsto another view. The viewusesfor itsproto a format frame which you normallystore in your basetemplate. Thisisillustrated in Figure4.

THE CHECKLISTHere isthe entire set of stepsneeded to support printing:1. Create a print format and add it to your project.2. Create a format frame in your base template.

3. In your InstallScript , call BuildContext and create a slotin the root view.

4. In your RemoveScript , remove the slot in the root view.5. Add Print to the routing frame.6. Modify SetupRoutingSlip to save data.

7. Modify printNextPageScript in the print format.

Here we describe each of these stepsin greater detail.

1. Create a Print Format and Add it to your ProjectYou create a print format byusing the special “NewPrint Format” layout

provided byNTK. The topmost template in thislayout needsto use asitsproto a protoPrintFormat . Thistemplate not onlyhasa proto slotbut a printNextPageScript slot aswell. Bydefault,printNextPageScript onlyhandlesone page, but you can addcode to support multiple pages(see step 7).

Once you compile the application, the Print format layout issaved intothe package and isaccessible byname (for example,printFormat_nameOfLayoutFile ) at compile time (in anevaluate slot, for instance).

Create anychildren you wish to have on the printed page. TheprotoPrintFormat viewwill be sized so that it isthe size of theprintable area on the page (the page size inset bythe margins). You can use

justification with child viewsto place them in appropriate placeson thepage. For instance, you might want a header at the bottom-right of eachpage. Thiscould be done with a protoStaticText with parentrelative bottom and parent relative right justification.

2. Create a Format Frame in your Base TemplateThe next step isto add a format frame to the application base template.

Here isa typical format frame with italicsshowing the partsyou might wantto customize:

{ _proto: ROM_coverP ageFormat

title: "Bill", //text in the format pickermainFormat: printFormat_billFormat,

}

The mainFormat slot pointsto the printFormat youcreated in the last step. You’ll normallycreate thisformat frame asa slot inthe application base template. Note that you must proto toROM_coverPageFormat. In addition to providing the coverpage,ROM_coverPageFormat also setsup manyother slotsthat are required forprinting.

3. In your InstallScript, call BuildContext and Create a Slot in theRoot View

First, create a newconstant that the will refer to the application’snewprint format:

constant kFormatSymbol := '|MyPrintFormat:App:Signature|;

It ispossible for an application to have multiple print formats. Theyshould each have unique symbols. Then the InstallScript will writecode similar to the following to create a viewbased on the format frame

Page 9: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 9/24

using BuildContext :

InstallScript(partFrame)begin

local appBaseTemplate := partFrame.theForm;local formatFrame := appBaseTemplate.my Fo rm at Fr am e;GetRoot().(kFormat Symbol) := BuildContext(formatFrame);…

end;

Remember that BuildContext takesa template and createsa viewusing asitsproto that template (itsparent isthe root view). The viewisstored in the root viewin a slot with a unique symbol.

4. In your RemoveScript, Remove the Slot fromthe Root ViewHere iswhere you clean up and remove what isno longer needed.

RemoveScript(partFrame)begin

…RemoveSlot(GetRoot(), kFormatSymbol);

en d

5. Add Print to the RoutingFrameNowthat you have created the necessarylayoutsand instantiated them,

you need to add Print to the routing frame. After thisstep, “Print” will bea choice in the action picker:

print: { title: "Print it em",routeForm: 'printSlip,formats: [kForma tSymbo l],

},

6. Modify the SetupRoutingSlip to Save Data

For beaming, the target isautomaticallystored in the fields frame. Forprinting, thisisnot the case. You need to save whatever information you’llneed when you actuallyprint in the fields frame. Thisinformation maybethe target, it maybe some information from the target, or something elseentirely. Save thisinformation in the SetupRoutingSlip method:

func(fields)begin

fields.title := kAppName &&DateNTime(Time()) &&distinctive info from target;

fields.body := information needed for printing/faxing...en d

Remember that you onlywant to save thisinformation for printing; whenbeaming or mailing, do not use it. You should alwaysassign your data tothe body slot.

7. Modify printNextPageScript in the Print FormatThe printNextPageScript message will be sent to yourprotoPrintFormat at the end of each page. I f there are no morepages, it should return nil . If there are more pages, it should prepare forthe next page and return true :

printNextPageScript : func()begin

if moreToPrint then beginsend messages to children to update their datacreate new children possiblyremove children possibly

end elsereturn nil;

en d

When ViewMessages are Sent Duringthe PrintingProcess

The wayprinting worksdiffersdepending on the type of printing. ForPostScript printers, each viewon the page isconverted to a PostScriptequivalent, and the PostScript representation of the printed page issent tothe printer. For bitmap printers, the Newton imagesthe page into anoffscreen bitmap and then sendsthose bitsto the printer. Since there isnotenough memoryto hold the entire page in an offscreen bitmap, the Newtonimagesthe page in horizontal bandsfrom top to bottom. All viewsthatintersect a band are drawn, and the bitsfor that band are sent to the printer.The offscreen buffer isthen used for the next band.

The viewsinvolved in printing receive a number of different systemmessages. At the beginning of printing, the protoPrintFormatview(and all of itsdescendants) receive these messages:

• viewSetupFormScript• viewSetupChildrenScript• viewSetupDoneScript

These present good opportunitiesfor the programmer to do anyone-time initializations. At the end of each page, the protoPrintFormatreceivesa printNextPageScript message. During the processingof each band, each viewthat intersectsthe band isalso sent theviewDrawScript message.

From anyof these methods, you can accessthe fields frame (viaparent inheritance). Thus, you can accessanyinformation you saved in thefields frame in the SetupRoutingSlip method.

SupportingMore Than One Print FormatIf you want to support more that one type of print format, simplycreate

multiple print formatsand add them to your project. Then create multipleformat framesin your application base template. Build these multiple formatviewsin your InstallScript instead of just the original one. In theRemoveScript , remove the slotsyou created in theInstallScript . Your last dutyisto create special format symbolsforeach of the format framesand then add the multiple symbolsto theformats slot in the routing frame.

FaxingHere isthe good news– once you’ve implemented printing, you have

alreadygone a long waytowardssupporting faxing. To support faxing, youneed a separate entryin the routing frame, and you need to make sure yourimaging isquick enough to avoid timing out. Here isa checklist for faxing:

FaxingChecklist1. Add faxing to the routing frame.2. Verifythat your page imagesquickly.

Newton Technology Journal April 1995

9

Page 10: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 10/24

Apri l 1995 Newton Technology Journal

10

1. Add Faxingto the RoutingFrame.

fax: {title: "Fax it em",routeForm: 'faxSlip,formats: [kF ormatS ymbol],

},

Anyformat frame that supportsprinting will also support faxing. For both

faxing and printing, a format frame must use asitsprotoROM_coverPageFormat . The name of thisproto issomewhatmisleading since thisproto isalso necessaryfor printing.

2. Verify that Your Page Images Quickly.Faxing requirescareful attention because of the veryreal possibilityof

timing out in the middle of a fax. It isimperative that the actual sending of afax be speedy. Fax machineswill timeout if approximately5secondselapsewithout receiving information. Thus, once the connection hasbeen made,,,everything must proceed at a fairlybrisk pace. Further, each band mustimage quicklybecause all imaging occurswhile the fax connection exists. Asa result, you will need to do the following:

• Use the viewSetupFormScript of the printFormat forexpensive operations–before callinginherited:viewSetupFormScript() .

• Make printNextPageScript &viewDrawScript quick.• Consider using multiple viewswith height lessthan the entire page (only

viewsthat intersect a band need to be drawn).

These considerationsare especiallynecessaryif you have complicatedpagesto fax. For manyapplications, however, all that isrequired issome

testing that demonstratesthat faxing doesn’t time out. Note that you shouldtest thison either a StyleWriter printer, a real Fax machine or some othertype of rasterizing device. When printing to a PostScript printer, the page isimaged asone band, so thisdoesnot provide a good test.

MAILINGMailing involvessome additionsto the format frame to support the creationof text that will be sent.

The Checklist1. Add mail to the routing frame.2. Add a method to the application that will create text to send.3. Add a text slot to the format frame that referencesthisnewmethod.4. Support closuresbyadding an attachment slot to the format

frame.

To request information or an application on Apple’sNewton developer programs,contact Apple’sDeveloper Support Center

at 408-974-4897or Applelink: DEVSUPPORT

or Internet: devsupport@ applelink.apple.com.

NTJ

To send commentsor to make requestsfor articlesin Newton TechnologyJournal,send mail via internet to: piesysop@ applelink.apple.com

Page 11: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 11/24Newton Technology Journal April 1995

11

Apple Computer, Inc. hasannounced the newest member of theirNewton MessagePad familyof products, the MessagePad 120. Thiseasy-to-use, hand-held device providesconvenient accessto the informationyou need, no matter where you happen to be — in a meeting, at home,or on the road.

IMPROVED DESIGN AND SCREEN CLARITY

Like the MessagePad 110, the newMessagePad 120 hasa slimline design, soit fitseasilyinto the palm of your hand. The protective lid isnowremovable so that you can customize the MessagePad to fit your usagepattern and the PCMCIA card lock hasbeen moved to the side, to make itmore accessible when you have your lid attached. In addition, the newMessagePad 120 screen offersreduced shadowing and better screen clarity.

MORE INTERNAL MEMORY

One of the most significant MessagePad 120 feature enhancementsisthenew2MB internal memoryconfiguration. Thisoffersusersthree timesmore internal space than isavailable in the current MessagePad 110.Userswill be able to put more of their applicationsin internal memory,thusfreeing up their PCMCIA slotsfor add-on communicationscardsandperipherals. In addition, the total configuration cost will be significantlyreduced, asmost userswill not have to invest in extra memorycards. Thenewmemoryconfiguration offersa combination of RAM and Flashstorage, assuring that even if a user accidentallyremovesall the batteries,their data will be saved.

SUPPORTFOR HIGH-POWERED PCMCIA C ARDS

The MessagePad 120 Type II PCMCIA slot nowoffersup to 325 mA capacity,making it better suited for development of high-powered communicationscardsand peripherals. The PCMCIA slot accommodatesa range of add-onNewton software application cardsincluding: LAN-line, cellular data and faxmodem cards; paging cards; memorycards; and others.

1.3 (344311) S YSTEM SOFTWARE IMPROVEMENTS

Improvementshave been made to the current 1.3 version of systemsoftware, making it more reliable and intuitive. Some of the moresignificant enhancementsare outlined here.

• Notification windows(alarms) are no longer closed when the Newtongoesto sleep. Thiswill prevent usersfrom missing notificationsthatoccur when the Newton isunattended.

• The ‘*’ and ‘# ’ characterscan be used when dialing phone numbersfrom the call slip. For example, a user could set the dialing prefix to‘*70’ to turn off call-waiting, if their phone system allowsit.

• A recognition problem which could have caused the accuracyof handwriting recognition to graduallydegrade for some usershasbeen corrected.

• Switching to guest mode and back nowrestoresthe owner’sletterstylessettings, when the writing style isset to “Printed Only”.

• A modem-dialing problem for userswith location set to a cityin Japanhasbeen corrected. The Newton nowsendsthe correct modeminitialization string “AT%J&P1”.

• A problem that could have put the Newton into a state in which PCMCIAcardscould be recognized without a soft reset hasbeen corrected.

• The reliabilityof erasing flash PCMCIA memorycardshasbeenimproved.

NEW COMMUNICATIONS SOLUTIONS

With the MessagePad 120, you can communicate in several ways. Using anexternal modem or the PCMCIA modem, you can fax documentsanywhere, send and receive e-mail messageswith people who subscribe toservicessuch asNewtonMail, CompuServe, and other Internet services.

With a cellular phone, software, cable and a newPCMCIAFAX/modem, you can nowalso fax documents, and send and receive e-mail messageswirelessly.

You can turn your Message Pad 120 into a paging device with theoptional Apple Mobile Messaging system bundle. Thisincludesa PCMCIAPaging Card from Socket, software from ExMachina and a subscription toApple’snotification service.

NEW SOFTWARE SOLUTIONSSeveral business, information management, and reference softwarepackageshave been announced in conjunction with the introduction of

the MessagePad 120. These include:• ACT! , from Symantec, distributed byStarCore

Thisiscontact manager software that putsvital, up-to-date clientinformation at your fingertips, organizesyour schedule, automatesyour record-keeping and correspondence, and synchronizeswithyour Windowsand Macintosh desktop ACT! applications.

• Berlitz Five Language Interpreter from StarCoreThisapplication translates20,000 wordsand 15,000 phrasesbetweenEnglish, French, Spanish, Italian and German

• Newton Utili ties from StarCore

Apple AnnouncesNew Newton MessagePad 120,Communicationsand Software Solutions!by Patty Tulloch, Apple Computer, Inc.

Newton News

Page 12: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 12/24

Apri l 1995 Newton Technology Journal

12

Thispackage includesfour applicationswith unique featurestomaximize memory, manage software and help you work faster. TheShortcutsapplication allowsyou to create a customized floatingpalette of your favorite features.

• PowerForms™ from Sestra, Inc.

Thisapplication turnsyour Newton into a mobile electronicbriefcasecontaining businessand personal formsfor professionalson the go.Examplesinclude purchase orders, invoices, salesquotations, shoporders, salesrecords, employee personnel fi les, advertising analysis,and so on.

• The Newton Enhancement Pack from StarCoreThisbundle featuresthree great applicationson one 2MB PCMCIA flashcard. The applicationsare Graffiti, Newton Utilities, and Action Names.

• PocketQuicken from IntuitThisfacilitatestracking all your financeswhile you’re on the go. WithPocket Quicken, you can instantlyupdate your checking, savings,credit card, and cash accounts. You can also track businessexpensesbytrip, project, and client.

• CIS Retriever from BlackLabsThe Newton client for CompuServe, thisallowsusersto send andretrieve mail, and to read and post Forum messages. ThissoftwaresupportsCIS Xtenderswhich provide accessto stock quotes, airlineinformation, businessdatabases, and so on.

325 mA capacity, making it better suited for high-powered communi-cationscardsand peripherals.

The message that iscoming acrossabout Newton isimpossible to

ignore. With three major companiescurrentlymanufacturing andselling Newton devices, the Newton platform continuesto evolve.More Newton licenseesare gearing up to introduce even furtherdifferentiated productsto a growing customer base in 1995. Anyapplication written for the Newton platform will run on anyof theseNewton devices, allowing developersto continuallybroaden thepotential customer base for applications.

AsNewton devicesproliferate in the corporate marketplace and findtheir wayinto the handsof professionalson-the-go, the Newton

platform offersdevelopersthe opportunityfor greater salesof existingproducts, new businessmarkets, and unlimited growth potential. AsPhilip Ivanier, Manager of the Newton Developer RelationsGroup,

said, “we’re constantlyimproving the palette of paintsavailable fordevelopers.” With such a palette at your disposal, our hope isthat oneor more of you will be the developer who buildsthe next “killerapplication” or broad-based solution that becomesan essential part of everyuser’sNewton!

continued from page 2

Letter From the Editor

To request information or an application on Apple’sNewton developer programs,contact Apple’sDeveloper Support Center

at 408-974-4897or Applelink: DEVSUPPORT

or Internet: devsupport@ applelink.apple.com.

NTJ

Page 13: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 13/24

Create a variety of part types with the new Output Settings controls.

In addition to the standard files,projects now support multiple text files and parts.

NTK 1.5projectssupport layouts, resources, text files, book files, and

parts. Thismeansyour project can contain multiple text files. You can alsobuild multi-part packagesand specifybuild order to suit your needs.

A new button bar in the Inspector offers controls of the new Profiler tool and standard debugging functions.

INTRODUCING NEWTON SCRIPT PERFORMANCE TOOLS

To help developersstudythe performance of their applications, NTK 1.5featuresa newperformance profiling tool. The Profiler generatesan analysisof your functionsand system calls. Using the newInspector button bar, youcan upload resultsin the form of a table. The report includesusefulinformation such astime elapsed per function, number of timesa functionwascalled, and size of each function in memory. Thiscan often alert you tobottlenecksin your code that mayneed to be reworked or optimized.

OPTIMIZE WITHTHE NATIVE NEWTON SCRIPT COMPILER

For stand-alone code that doesnot interact with Newton subsystems(that is,soupsand views) you mayconsider optimizing to native ARM code. WhileNative NewtonScript ismuch larger than interpreted NewtonScript, it retainsportabilityand can deliver higher performance. With NTK 1.5, you can makethistrade-off on a function-by-function basis.

Newton Technology Journal April 1995

13

continued from page 1

Coming Soon: Newton Toolkit 1.5

Quickly upload statistics to analyze the performance of your functions.

continued on page 14

Function Min Max Average % Entries Size

MainLayout.TopView.CalculateDistance 500 900 600 7 98 250

MainLayout.TopView.SortNames 300 10000 900 10 515 780

ReportLayout.Report View.CompareResults 600 988 948 10 43 2500

ProjectData.FindPath.func1 477 500 490 3 2 5680

Page 14: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 14/24

Apri l 1995 Newton Technology Journal

14

However, using the Native compiler isnot a simple operation; you’ll wantto read the documentation carefully. There are manyhints, such asexplicittyping, that you must consider to ensure that compilation resultsin aperformance boost. Native NewtonScript maynot solve everyapplication’sperformance problems, but it’san important step. We are committed todelivering both high-level and low-level toolsto enable developersto fullyrecognize Newton’spotential.

BEYOND NTK 1.5Our goal isto provide great toolswith which to build great applications.Newton Toolkit 1.5will deliver greater productivityaswell aspowerful newcapabilities. We look forward to bringing you even better Newton toolsinthe future. Please send commentsand feature requeststoNTKBUGS@ NEWTON.APPLE.COM.

NTJ

Use the “native” keyword to optimize a particular function.

If you have an idea for an article you’d like to write for Newton TechnologyJournal,send it via internet to: piesysop@ applelink.apple.com

or AppleLink: PIESYSOP

Page 15: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 15/24Newton Technology Journal April 1995

15

Some Resources

There are two booksthat contain particularlygood discussionsof optimizing code. The first isdevoted solelyto optimization, while the secondcoversall aspectsof programming:

Jon Bentley, Writing Efficient Programs , Prentice Hall, 1982,ISBN 0-13-970244-X

Steve McConnell, Code Complete , Microsoft Press, 1993ISBN 1-55615-484-4

Both bookscorrectlypoint out that optimization should be done afterthe code iswritten. You measure the performance of an application,determine where the application isspending most of itstime, and thenconcentrate on optimizing those areas.

MeasuringPerformance of a Newton ApplicationFor the Newton, the onlyreal wayto measure performance isto call

Ticks() before and after a piece of code. Thisletsyou see howlong thecode took to execute. The Ticks() function, however, returnsa number in60ths of a second, To measure quick operations, you maywant to do themrepetitivelyin a loop.

The following isgenerallyuseful:

theRoutine := func(args)begin

…end;frame := {result: nil, time: nil};oldTicks := Ticks();frame.result := call theRoutine with (theArgs);frame.time := Ticks() - oldTicks;frame

To do thisfrom the Inspector, you will need to embed the timing code ina function. Thiswaythe code can include loops(the Inspector doesn’t allowloopsat the top level) .

Here’san example of executing this:

theRoutine := func()begin

local total := 0;for i := 1 to 1000 do beginend;return total;

end;frame := {result: nil, time: nil};oldTicks := Ticks();frame.results := call theRoutine with ();frame.time := Ticks() - oldTicks;frame#441AEF1 {result: 0,

Time: 8}

theRoutine := func()begin

local total := 0;for i := 1 to 1000 do begin

total := total + i;end;return total;

end;frame := {result: nil, time: nil};

oldTicks := Ticks();frame.results := call theRoutine with ();

frame.time := Ticks() - oldTicks;frame#441AEF1 {result: 500500,

Time: 14}

Notice that there are two timingshere. The first measured 1000iterationsof an emptyloop, and the second measured 1000iterationsof a loop with aninteger addition each iteration. The difference between the two is6ticks, or1/10of a second. Thus, a rough estimate of the speed of an addition of twolocal variablesis1/10000of a second.

SPEEDING UP Y OUR NEWTON SCRIPTSince NewtonScript isinterpreted byte-code (at least until NTK providesaNewtonScript compiler), the best wayto increase NewtonScript speed istouse rawNewtonScript aslittle aspossible.

Use Built-in Functions in Preference to WritingYour Own.For example, if you want to sort an array, rather than writing your own

sorting routine similar to:

call kMySortFunc(anArray)

you are better off calling the built-in Sort function. Since the built-in globalfunctionsare written in C+ + , theyrun much faster than your customNewtonScript code. Using a built-in function also hasthe advantage of reducing the size of your package.

You can see a continuation of thisidea in howyou handle certainNewtonScript functions. Some functionsthemselvestake functionsasparameters. For instance, Sort takesa function asthe second parameter.Assume you have an arrayof frames, each of which hasa height slot,and you wish to sort the framesin increasing order of height. One waytodo thisis:

Sort(myArray, func(a, b) return a.height - b.height, nil);

However, the third parameter of Sort isa symbol specifying the slot onwhich to sort. Therefore, the example can be rewritten as:

Sort(myArray, func(a, b) return a - b, ‘height);

Thisshould be slightlyquicker, since the two accessesof the height slotare nowmade in C+ + rather than in NewtonScript. A sample with 500

elementsyielded 884ticksfor the first case, 810for second).Even better, however, isto avoid NewtonScript entirely(even return

a-b ). Thiscan be done with Sort bypassing the symbol ‘ |<| asthesecond parameter:

Sort(myArray, ‘|<|, ‘height)

For the same sample, thisissubstantiallyfaster, taking only42ticks, a 20timesspeedup.

continued from page 1

NewtonScript Performance Tuning

Page 16: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 16/24

ALWAYS DECLARE Y OUR LOCAL VARIABLESThere are several reasonsfor thisrule, not just performance implications.One reason iscode readability. If you define your localsusing thekeyword, then readersof your code knowwhat are local variables, andwhat are globalsor inherited slots. Additionally, at some point,

NewtonScript mayrequire declaration of local variables, so you might aswell be prepared. The last reason for following thisrule isthat there isnogood reason not to.

Speed isthe most important factor, however, for declaring locals.When the NewtonScript compiler seesthe use of a declared localvariable, i t generatescode that accessesthe variable via a numericstackoffset. On the other hand, the code to accessvariablesnot declaredlocallyrequiresa dynamiclookup based on the variable name. Thisdynamiclookup isslower.

The situation when assigning to a variable for the first time isevenworse. If a variable isn’t declared local, the assignment requiresa lookup,starting first with a lookup asa local, then using both proto and parentinheritance, and finallyasa global. If the variable isn’t found at thispoint,the interpreter createsthe variable asa local.

The following code, called with an arrayof 1000 elements, takes66ticks:

SumArray := func(anArray)begin

total := 0;foreach elem in anArray do

total := total + elem;return total;

end;

Bysimplydeclaring the local variables, the time isreduced to 31ticks:

SumArray := func(anArray)begin

local total := 0;

foreach elem in anArray dototal := total + elem;return total;

end;

Loop Variables and Local Declarations

Loop variablesare automaticallydeclared aslocals. In the following code,the variablesin bold need not be explicitlydeclared aslocals:

for i:= 1 to 100 do…

foreach el em in array do…

foreach slotSymbol, value in frame do…

Usingforeach Correctly

It isquicker to iterate through the elementsof an arraywith foreachthan it iswith an explicit for loop. Here are two examples:

SumArray1 := func(anArray)begin

local total := 0;foreach elem in anArray do

total := total + elem;return total;

end;

SumArray2 := func(anArray)begin

local total := 0;for i := 0 to Length(anArray) - 1 do

total := total + anArray[i];return total;

end;

With foreach , you have a specialized NewtonScript construct whichthe interpreter can handle quickly. It isalso easier to use, since you can’taccidentallyget the starting or ending conditionswrong. In thiscase,SumArray1 took 18ticks, while SumArray2 took 32ticks(for a1000-element array).

Even with NewtonScript constructslike foreach , measurement isimportant. There are timeswhen using it isslower. For example:

ZeroArray1 := func(anArray)begin

foreach index, elem in anArray doanArray[index] := 0;

end;

ZeroArray2 := func(anArray)begin

for index := 0 to Length(anArray) - 1 doanArray[index] := 0;

end;

Although ZeroArray1 iseasier to read, the interpreter setsthevalue of elem (which isunused) aswell asthe value of index eachtime through the loop. Here, ZeroArray1 took 42tickswhen calledwith a 1000-element array, while ZeroArray2 took only15ticks.

Function calls are expensiveCompared to some other languages, the cost of calling a function in

NewtonScript isexpensive.The Newton can make not quite 1000function callsper second (if the

functionsdo nothing, and no lookup isnecessaryto call them). Thefollowing code took between 60and 70ticksto execute:

g := func()begin

local f := func()beginend;

Print(Ticks());for i := 1 to 1000 do

call f with ();Print(Ticks());

en d

Sending a message issomewhat more expensive, mostlydue to the costof looking up the method in the frame to which the message issent.

Cache expensive calculationsCurrently, the NewtonScript compiler doesno common sub-expression

elimination optimization. Everyexpression in your code will be evaluated.Thismeansthat if you refer to an inherited variable manytimesin a method,the lookup for that slot must occur manytimes. Consider caching the resultsof operations.

Apri l 1995 Newton Technology Journal

16

Page 17: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 17/24

For instance, instead of:

Method := func(s)begin

for i := 1 to 100 dos := s + inheritedVar;

return s;

end;use:

Method := func(s)begin

local cachedVar := inheritedVar;for i := 1 to 100 do

s := s + cachedVar;return s;

end;

The latter code avoids999variable lookups.Along similar lines, if you are accessing nested framesrepeatedly,

consider caching the result of the dot lookup. Rather than:

for i := 1 to 100 doa.b.c.d[i] := i;

use:

local arr := a.b.c.d;for i := 1 to 100 do

arr[i] := i;

The latter code took 6tickswhile the former code took 7ticks.

Eliminate loop InvariantsA common compiler optimization isto move expressionswhose

valuesdon’t change outside of a loop. At thispoint, however,NewtonScript doesn’t do thisoptimization, so you must do it yourself.For example, rather than:

for i := 1 to 100 do:Method(x + y + 53 * z, 2 * i);

use:

local value := x + y + 53 * z;for i := 1 to 100 do

:Method(value , 2 * i);

Bymaking thischange, the calculation of x + y + 53 * z isdone onlyonce, rather than 100times.

USINGAND ALLOCATING MEMORY EFFICIENTLY

Efficientlyhandling memorywithin a NewtonScript application involvesboth attention to memoryallocation and to whether you are using RAMor ROM. First, you must deal with the more simple issue of measuringyour memoryuse.

MeasuringMemory UseIn order to measure space in your program, the best bet isto call

Stats() . Thismethod returnsthe total amount of memoryavailable.Since Stats doesn’t take into account memorythat needsto be garbagecollected, however, you should alwayscall GC() first.

Here issome code to use to see howmuch memorya function takes:

theRoutine := func(args)begin

…end;frame := {result: nil, space: nil};

GC();oldSpace := Stats();frame.result := call theRoutine with (theArgs);GC();frame.space := oldSpace - Stats();frame

Here isan example of itsuse:

theRoutine := func()begin

return [1, 2, 3, 4, 5, 6, 7, 8]end;frame := {result: nil, space: nil};GC();oldSpace := Stats();frame.result := call theRoutine with ();GC();frame.space := oldSpace - Stats();frameFree: 38504, Largest: 50 61 6Free: 38472, Largest: 50568#4414C39 {result: [#4414C51],

space: 48}

The above example showsthat thiseight-element arraytakes48bytes.(See the NewtonScript Q&A for a detailed discussion of object sizes).

Efficiently AllocatingMemoryAllocating memorytakestime. In addition, it usesRAM – a veryprecious

resource on the Newton. For these reasons, it isbest to avoid allocatingmemorywhenever possible. Here are some waysto do that:

UsingConstant Frames and ArraysIf you use an arrayor frame that will not change at run time, make sure

that it isconstant. For example, there isa substantial difference between:

myFrame := {a: 3, b: 4}

and:

kMyFrame := '{a: 3, b: 4}

The former istechnicallya frame constructor that allocatesmemoryfromthe frame heap for the frame at run time. The second frame iscreated atcompile time and isstored aspart of your package. Thistrade of RAM forROM storage will alwaysbe a better programming method.

There isalso a syntax you should use for defining constant arrays:'[1, 2, 3]

You can also use DefConst to create constants:

DefConst('kMyFrame, {a: 3, b: 4 * 5});

In the current implementation of NewtonScript, stringsliteralsare constant.Therefore, the following code createsa string which isstored in the package,rather than in the frame heap:

s := "abcd";

Newton Technology Journal April 1995

17

Page 18: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 18/24Newton Technology Journal April 1995

18

SharingFrame MapsAsshown in the following diagram, framescreated with the same frame

constructor share the same frame map. The frame map containsthemapping from slot symbol to location within the frame.

To ensure that you use the same frame maps, create each frame withthe same frame constructor. For example, if you need to create a boundsframe, don’t use:

{left: 10, top: 5, right: 30, bottom: 100}

Instead, call SetBounds

SetBounds(10, 5, 30, 100)

Further, with SetBounds , the frame map of the rectangle will be in theNewton’sROM, rather than in your package. You can also use other systemfunctionsthat return rectanglessuch asRelBounds.

On a similar note, you should ensure that your frame constructorcontainsall the slotsyour frame needs, rather than adding newslotsdynamically. Adding a newslot not onlyrequiresallocating memoryfor theslot value (an unavoidable four bytes), but also requiresallocating memoryfor the frame map entry. Bymaking sure the initial frame constructorcontainsthe necessaryslots, the frame map can be in the package, ratherthan in the frame heap.

Here are two routineswhich each return a frame.The first createsall the slotsin the frame constructor: The second

createseach slot dynamically:

The first routine uses32 bytesof the frame heap, while the seconduses64 bytes. Thisfirst routine isnot just smaller, i t isalso faster. It takes17 ticksto call the first routine 100 times, while it takes32 ticksto call thesecond one 100 times.

Don’t Blindly use EnsureInternal, TotalClone, or DeepCloneRemember that NewtonScript isspecificallydesigned to share

memory. When you use EnsureInternal , TotalClone , orDeepClone , you are making copiesso that memoryisnot shared.Don’t do thisunlessyou have a good reason. Generallyspeaking, it isimportant to be aware of what these three routinesdo, and onlyusethem when necessary.

SUMMARY

It should nowbe obviousthat, byoptimizing a fewkeyareasin your code,you can both increase the responsivenessof your program and use memorymuch more efficiently. Having good optimizing techniquesin the first placecan onlyhelp. Beyond that, relyon built-in functionsrather than creatingyour own custom NewtonScript. Remember to define your locals, use theright loop for the job, and define constantswhere ever possible.

You can save memoryin your programsbypaying attention to detailssuch asframe maps. You should also never blindlyuse the cloning functionsto do something that can be handled in another way. Finally, your awarenessof howoperatorsuse memorycan help you determine when to change to amore efficient method.

{ a: 3, b: tr ue, c: $x, }

3true

$x

frame frame map

' a

' b

' c

NTJ

' a' b

' c' d

MakeFr ame : = f unc( )begi n

l ocal f rame : ={a: ni l , b: ni l ,

c: ni l , d: ni l };f r ame. a : = 1;f r ame. b : = 2;f r ame. c : = 3;f r ame. d : = 4;r et ur n f r ame;

end;

RAM Package

Frame

Frame map

' a' b

' c' d

FrameFrame map

RAM PackageMakeFr ame2 : = f unc( )begi n

l ocal f r ame : = {};f r ame. a : = 1;f r ame. b : = 2;f r ame. c : = 3;f r ame. d : = 4;r et ur n f r ame;

end;

Page 19: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 19/24

Newton Developer ProgramsApple offerstwo programsfor Newton developers—the Newton AssociatesProgram and the NewtonPartnersProgram. The Newton AssociatesProgram isa lowcost, self-help development supportprogram. The Newton PartnersProgram isdesigned for developerswho need expert-leveldevelopment support via electronicmail. Both programsprovide focused Newton developmentinformation and discountson development hardware, software, and tools—all of which can reduceyour organization’sdevelopment time and costs.

Newton PartnersProgramThisexpert-level development support program helpsdeveloperscreate productsand servicescompatible with Newton products.Newton Partnersreceive all Newton AssociatesProgram features, aswell asprogramming-level development support via electronicmail,discountson five additional Newton development units, and

participation in select marketing opportunities.With thisprogram’sfocused approach to the deliveryof Newton-specificinformation, the Newton PartnersProgram, more than ever,can help keep your projectson the fast track and reducedevelopment costs.

Expert Newton Programming-level Support• One-to-one technical support via e-mail

Apple Newton Hardware• Discountson five additional Newton development units

Pre-release Hardware and Software• Consideration asa test site for pre-release Newton products

Marketing Activities• Participation in select Apple-sponsored marketing and PR activities

All Newton Associates Program Features:• Developer Support Center Services• Self-help technical support• Newton Developer mailing• Savingson hardware, tools, and training

Newton AssociatesProgramThisprogram isspeciallydesigned to provide low-cost, self-helpdevelopment resourcesto Newton developers. Participantsgainaccessto online technical information and receive monthlymailingsof essential Newton development information. With the discountsthat participantsreceive on everything from development hardware

to training, manyfind that their annual fee isrecouped in the firstfewmonthsof membership.

Self-Help Technical Support• Online technical information and developer forums• Accessto Apple’stechnical Q&A reference library• Use of Apple’sThird-PartyCompatibilityTest Lab

Newton Developer Mailing• Newton Technology Journal •Newton Developer CD , which mayinclude:

– Newton Sample Code– Newton System Software– Newton toolsand utilities– Marketing and businessinformation

•Apple Directions—The Developer Business Report

Savings on Hardware, Tools, and Training• Discountson certain development-related Apple hardware• Apple Newton development tool updates• Discounted rateson Apple’sonline service• US $100Newton development training discount

Other• Developer Support Center Services

• Developer conference invitations•Apple Developer University Catalog •APDA Tools Catalog

For Information on All Apple DeveloperProgramsCall the Developer Support Center for information or anapplication. Developersoutside the United Statesand Canadashould contact their local Apple office for information aboutlocal programs.

Developer Support Center at (408) 974-4897Apple Computer, Inc.1Infinite Loop, M/S 303-1P

Apple Developer Group

®

Page 20: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 20/24

Apri l 1995 Newton Technology Journal

20

Advanced Debuggingby Julie McKeehan and Neil Rhodes, Calliope Enterprises, Inc.

Advanced Techniques

Thisarticle discussesseveral little-known debugging techniqueswhichshould be part of the arsenal of all Newton programmers. These techniquesinclude:• Replacing procedureson the fly• Overriding global functions• Overriding root viewmethods• Making trace work the wayyou want it to on a particular piece of code

REPLACING PROCEDURESONTHE FLY

You are probablyfamiliar with the common debug cycle on the Newton:• You compile and download• You run the application looking for an error• You then debug the error using the Inspector or ViewFrame (or a

combination of both)

When a bug isfound in a method, the straightforward approach isto fixit, and then start the whole processover again: compile, download, run theapplication, and test to make sure the fix iscorrect. The good newsaboutthisapproach isthat thiscompile/download/run cycle ismuch quicker thanon manyplatforms(e.g., Macintosh Programmer’sWorkshop). The badnews, asanyprogrammer will tell you, isthat thiscycle just never isquickenough.

A speedier approach isavailable. You can use the Inspector to replacethe method that hasthe error while still running the application. Forexample, let’ssayyou have a template named “myButton” which hasamethod named Method1 :

func(a, b, c)begin

local x := 1;local y := 1;local z := 1;

if a then beginy := y * 2;z := :Method2(a, b, c, x, y);

end;return x * y * z;

en d

Imagine that you have a problem with Method1 , and you wouldlike to print out itsparameters. You can do thisbyexecuting the following inthe Inspector:

Debug("myButton").Method1 := func(a, b, c)begin

Print(a);Print(b);Print(c);inherited:Method1(a, b, c);

en d

When you execute thismethod, it iscompiled from the Inspector andstored in the framesheap of the Newton. The Method1 slot isnowpart of the myButton view, and nowwhenever the Method1message issent to myButton , the newoverridden version willexecute instead. Since part of the newmethod isto print out theparameters, it will do so and then call the old version.

Notice that you could even completelyreplace Method1 :

Debug("myButton").Method1 := func(a, b, c)begin

local x := 3;local y := 3;local z := 5;

if a then beginBreakLoop();y := y * 2;z := :Method2(a, b, c, x, y);

end;return x * y * z;

end;

The one requirement for thistechnique to work isthat the viewto whichyou are adding a method must exist. Thus, you cannot add code to a closedview(unless, of course, it isdeclared to a viewthat isstill open).

You can use thisapproach to add code incrementallyto a view— onemethod at a time — thusmaking debugging much simpler. The onlytrickypart isremembering to copythe finished product back into your projectonce you’re satisfied that the code iscorrect. The best code in the worldwon’t help your application if it isleft sitting in the Inspector window.

OVERRIDING GLOBAL FUNCTIONS

There are timeswhen you will find it useful to replace a global function. Forexample, you maywant to knowwhen a particular function iscalled, or whatitsparametersare. Asan example of this, let’ssayyou want to find out when(or even whether) a particular application callsBroadcastSoupChange and what soup name it passeswhenit does.

Here ishowyou perform thisneat little trick. First, you create a globalfunction that referencesthe old global function (usually, you’ll want to

augment the behavior of a function, not completelyreplace it) . Rememberthat all global functionsare stored in the global variable functionsframe, which isitself a global variable. From the Inspector, execute thiscode:

functions.OldBroadcastSoupChange :=functions.BroadcastSoupChange;

Second, create a newfunction that takesthe same number of parametersand that callsthe old function:

© 1994, Apple Computer, Inc. and Calli ope Enterprises, Inc

Page 21: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 21/24

functions.BroadcastSoupChange := func(s)begin

Print("BroadcastSoupChange called with" && s);OldBroadcastSoupChange(s);

end;

OVERRIDING

ROOT

VIEW

METHODS

Another technique that can be veryuseful isbeing able to override root viewmethodsfor debugging purposes. Methodslike Notify ,FindSoupExcerpt , Open , and Close are all root viewmethodsthat at timesmight be useful to override for debugging purposes.

The technique isverysimilar to the one for replacing methodsin yourown application. Simplyadd a slot to the root viewthat overridesthemethod found in the root template. All you have to do isexecute thefollowing code from the Inspector:

GetRoot().MethodToOver ride := func(pa ra ms)begin

whatever you want to doinherited:MethodToOverride(pa ra ms);

end;

MAKING TRACE APPLY IMMEDIATELY The trace global variable controlstracing and it would probablybe veryuseful if you could preciselycontrol when it turnson and off. And asmanyprogrammershave learned, simplysetting it to true (or'functions ) for your whole program, onlycausesenormousamountsof information to be printed to the Inspector. Given thisbulkybitstream,manyprogrammerswould like to be able to set the variable to true onlyaround a particular section of code and then be able to examine onlythatoutput.

While you would like it to be, it’snot aseasyassurrounding your codewith the following:

trace := true;code to tracetrace := nil;

The reason thisdoesn’t work isthat the NewtonScript interpreter onlyoccasionallylooksat the value of the trace variable. Once you thinkthrough the logicof it, you will realize that thisisactuallya good thing; if theinterpreter checked the value on everyinstruction, the speed of the

interpreter would be severelyslowed for all Newtons. Since slowing theNewton down isnot a choice that anyone wants, the NewtonScriptinterpreter irregularlychecksthe value of thisvariable when a function iscalled (function callsare expensive enough that one check of a globalvariable hasno substantial impact) . Of course, thisdoesleave you with theproblem of howto trace around just a little bit of code.

Happilythere isa nice solution to thisproblem. To cause tracing tohappen around a particular section of code, all you have to do ismake sureto call a function immediatelyafter setting the trace variable:

trace := true;Apply(func() nil, []);code to tracetrace := nil;Apply(func() nil, []);

Simplybyexecuting an emptyfunction using Apply , we’ve causedthe interpreter to check the trace variable and start tracing before thecode of interest isexecuted. Similarly, assoon asthe code of interestcompletes, we turn tracing off.

There isone small proviso that accompaniesthistrick and that isthat youcan not depend upon it to work in the future versions. The particularmanner in which the trace global variable ischecked maywell bedifferent in the future.

SUMMARY

One or more of these techniquesmaybe of use to you in your Newtondebugging. Remember that all the techniquesthat create functionsin theframesheap are onlyfor debugging and will be lost when the Newton isreset. If you want to keep the resultsof your carefullycrafted code, thencopyit back into your project. These techniquesare veryuseful, however,when you want to quicklysee the effect of different code without expensiverecompile and download cycles.

Newton Technology Journal April 1995

21

NTJ

To send commentsor to make requestsfor articlesin Newton TechnologyJournal,send mail via internet to: piesysop@ applelink.apple.com

Page 22: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 22/24

Apri l 1995 Newton Technology Journal

22

BASIC S YSTEM ARCHITECTURE

The Marco communicationsarchitecture isshown belowin figure 1. Someof the featuresprovided for in the architecture include sharing the radioamong multiple clients, multiple mail transport services, wirelessandwireline mail applications, and several different developer APIs.

Figure 1: Marco Communications Architecture

The radio communicationssection of the architecture includesthe radiohardware, Shared Radio Tool and the WirelessManager. Together, thesecomponentsprovide all of the software required for wirelesscommunicationon a DataTAC network. The Shared Radio Tool iscompletelyresponsible formanaging the radio hardware and providestwo accesspoints. The firstaccesspoint isvia an endpoint used bythe WirelessManager, which isresponsible for providing the WirelessAPI to clientsaswell asanyuserinterfacesthat deal directlywith the radio (such asradio preferences). Moredetail on these componentsisgiven later in the article.

The mail section of the architecture providesthe software necessarytosupport multiple mail transports, bundled mail transport engines, mailedbased/savvyapplicationsand a mail editor application. The diagram containsa single component labeled "Mail Transports,” which isactuallymultiple mailtransport implementations, all of which share a common structure. In theinitial release both Radio Mail and ARDIS Personal Messaging are provided asMail Transports. The relationship between the Universal Mail Service and

individual transport servicesisdetailed later in the article.The last section includesapplicationsand servicesother than mail that

are provided bythird parties. Three different APIsare provided todevelopersand the choice of API will typicallybe based on the type of communicationsservice required.

Applicationsthat use a mail based service are layered on top of theUniversal Mail Service (UMS). Such applicationsare shown as“Mail Based"and “Mail Savvy” applicationsin the diagram. (Mail Based appsarespecificallydesigned to take advantage of the I/O box, Mail Savvyappsarethose that provide mail accessasan option to communicate data. Examples

of Mail Savvyappsare the built-in NotePad and Calendar applications). TheUMS API iscompletelycompatible with the existing Mail API in the Newton,while providing additional mechanismsto get information about currentlyavailable transportsand/or register for receiving replymail. Applicationsusing thissort of interface are the most genericsince theywill work acrossmultiple mail transports. In addition the host that issupplying the serviceand/or data needsonlybe accessible through mail. The primarydrawbackto thissort of application isthat the store and forward paradigm of mail canresult in significant delays.

Some mail transportsalso provide value added network services(RadioMail'sXMFS, for example). Applicationsthat take advantage of these servicesare "Transport Specific" applications. Since the exact nature and API of thenetwork service will varybetween transports, these applicationswill onlyrunover the transport for which theywere designed. It isdifficult to discussthepotential benefitsor drawbacksto these typesof applicationssince the valueadded network service itself will varyconsiderablyacrosstransports.

The last type of application isone that talksdirectlyto the WirelessManager ("Dedicated Host" applications). These applicationsuse theWirelessAPI to send and received data acrossthe wirelessnetwork.Applicationsof thistype must communicate with a specifichost on thewirelessnetwork (ARDIS in the US). Since the processfor getting accessof thistype ispotentiallyveryexpensive and time consuming, thistype of application ismost likelyto be used in vertical markets. Since mailtransportsuse the WirelessAPI, theycan be considered asa special kind of "Dedicated Host" application.

OVERVIEWOFTHE COMMUNICATIONS ARCHITECTURE

The radio communicationsportion of the architecture isshown in moredetail in figure 2. The major componentsare the radio hardware, the SharedRadio Tool, the WirelessManager, and the Dedicated Radio Tool. Asmentioned before, these componentswork together to provide radiocommunicationsover a DataTAC network (such asARDIS).

Figure 2: Overview Communications Architecture

Wireless Manager

Shared Radio Tool

Shared Radio Tool EndpointRadio PrefsRadio Controls Virtual Endpoints

Wireless API

Radio Hardware

Universal Mail Service

Mail Based App. Mail Savvy App.

Wireless Mail Transports

Wireless Manager

Shared Radio Tool

Radio Hardware

Wireline Mail Transports

Modem Tool

Serial Port

TransportSpecific App.Dedicated

Host App.

Marco Software Architecture, Version 1.0by Dave Baum, Motorola, Inc. Wireless Data Group

Licensee Specifics

© Copyright 1994 Motorola, Inc.

Page 23: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 23/24Newton Technology Journal April 1995

23

The radio providesthe physical communicationslayer and the channelaccessportion of the data link layer. The Shared Radio Tool (SRT) isacommunicationstool that providestwo separate interfaces. In the currentoperating system, each communicationstool mayonlybe used bya singleclient at anygiven time. To accommodate multiple radio clients, the wireless

manager hasassumed the responsibilityfor multiplexing clientsrequeststothe radio. Asa result, the Shared Radio Tool'snormal interface hasa dataformat significantlydifferent than a typical communicationstool.

SRT isa dual mode protocol engine (MDC and RDLAP) suitable for useon MFR and SFR DataTAC networks. It implementsthe portionsof the datalink layer above channel access, the network layer, and connectionmanagement functions.

The WirelessManager usesan endpoint to communicate with the SharedRadio Tool. All accessto the radio from NewtonScript ismade through thisendpoint. Internally, the WirelessManager providescomponentsfor settingthe radio preferencesand controlling the radio (on, off, etc.). Mostimportantly, the WirelessManager also implementsvirtual endpointswhichprovide the WirelessAPI for clientsto use. Multiple clientsmayinstantiatevirtual endpointssimultaneously-the WirelessManager coordinatesuse of the real endpoint among the multiple virtual endpoints.

DETAILED MAIL ARCHITECTURE

The Mail Architecture isshown in detail in Figure 3. Thisdocumentdescribeseach of the componentsbriefly; more detailed information maybefound in Universal Mail Service. Three major componentsare involved inthe sending of mail: an application, the Universal Mail Service, and a mailtransport. The application sending the mail maybe the Mail Applicationitself, a third partyapplication layered on top of mail services(mail basedapplications), or anyNewton application that supportsthe standard mailrouting service. The Universal Mail Service providesa consistent API for allmail transports. Applicationsneed not knowthe difference between theindividual mail transportssupplied bythird parties.

Figure 3: Detailed Mail Architecture

The Mail Application consistsof a mail editor and a log overview. TheMail Editor makesuse of the Mail Slip and I/O Box provided bythe UniversalMail Service. Other applicationsthat need to send or receive mail wouldalso use these interfaces. Universal Mail Service providesan extensiblelogging capability, the resultsof which are stored in a Mail Log Soup. TheLog Overviewprovidesthe user with convenient accessto the data in thissoup.

The user selectsand configuresmail transportsthrough the Mail Prefscomponent. Custom preferencesmaybe optionallysupplied bythetransport as"Extended Prefs". In addition, the transport mayoptionallysupplya registration viewthat allowsthe user to register that transport.

The Mail Slip allowsthe user to addressand submit a piece of mail. It

usesthe transports' Attributesto determine what featuresare available forthe specifictransport. In addition, custom featurescan be supported byanExtended Mail Slip optionallysupplied bythe transport.

The Universal Mail Service ownsthe Mail InBox/OutBox categoryandmakescallsto the transport’sI /O Functionsto send mail. When receivingmail, the transport should deliver it to the I/O box so that the Universal MailService can dispatch it appropriately.

Logging of mail issupported bythe Log Manager and the Mail Log Soup.The Log Manager providesconvenient functionsto the transport to supportlogging. The log ismaintained asa soup whose format will be published.

Lastly, a mail transport mayoptionallyprovide a Custom API for“Transport Specific” clients. The custom API isoften a standard used toprovide accessto several programming platforms( DOS, Windows,Macintosh, Newton).

For more information about Marco Communicator developmentopportunities, developersmaycontact Pat Pahl, BusinessDevelopmentManager at Motorola, at the following internet address:Patrick_Pahl@ msmail.wes.mot.com.

Marco WirelessCommunicator, Motorola, InfoTAC and DataTAC are all registered trademarksof

Motorola, Inc. Newton, Newton Technology, Newton Script, MessagePad, Newton Toolkit (NTK)

and NewtonMail are all registered trademarksof Apple Computer, Inc. ARDI S, ARDIS MG,

ARDIS Personal Messaging, RadioMail, SprintNet, CompuServe, AmericaOnline, and MCI Mail

are all trademarksof their respective companies.

Mail Prefs

Log Manager

I/O Box

Universal Mail Service

Mail EditorMail App.

Mail Transport

Extended Prefs

Mail Slip

Registration View

Extended Mail Slip

Attributes Custom API

Mail Log Soup

I/O Functions

Mail Apps

NTJ

If you have an ideafor an article you’d like to write for NewtonTechnologyJournal, send it via internet to:

piesysop@ applelink.apple.comor AppleLink: PIESYSOP

Page 24: Newton Technology Journal: Volume 1, Number 2

7/28/2019 Newton Technology Journal: Volume 1, Number 2

http://slidepdf.com/reader/full/newton-technology-journal-volume-1-number-2 24/24

Dear Newton Developer,

W e’d like to introduce you to StarCore, the software publishing and distribution arm

of the Personal Interactive Electronics Division at Apple Computer, Inc. As a Newton developer, you are already involved in creating products for this exciting technology.There are many ways in which we can build relationships that will benefit you and the Newton platform.

At StarCore, we are actively recruiting titles for the Newton. StarCore can provide developers with a broad range of services and opportunities. The developer creates the software, StarCore provides the packaging, manuals, testing, user studies, marketing

and end-user support.

We are anxious to talk with developers about products or concepts they would like to see published or distributed. We are particularly interested in business-oriented applications that would appeal to a mobile professional. We are also looking for products that have connectivity to Macintosh and Windows desktop applications.

Please contact us at:

StarCore Apple Computer, Inc.5 Infini te Loop, MS 305-3C Cupertino, CA 95014 Attn: StarCore