newton technology journal: volume 1, number 5
TRANSCRIPT
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
1/32
Inside This Issue
Newton 2.0:Whatsthe Big
Idea?by Joseph Ansanelli & the Newton PlatformMarketing Team, Apple Computer, Inc.
Alot hashappened since Apple brought theindustrysfirst personal digital assistant (PDA) to
market in 1993. Manycompanieshave entered
the market, and some competitorshave already
fallen bythe wayside. Technologyhasadvanced.
Improvementshave been made on manyfronts
software, communicationscapabilities, and
servicesoptionshave grown more sophisticated
and useful. Today, though the world isless
inclined to viewPDAsasa panacea for all
technological and businessproblems, there are
manycustomerswho are championing the
usefulnessof PDAs.
Most important, the Newton PDA platform
continuesto gain momentum in the market.
With the advent of Applessecond-generation
PDA software platform Newton 2.0 more and
more companiesand individualswill have
reasonsto make Newton their platform of
choice. With a significant number of
improvements all derived from customer
feedback Newton 2.0offersa great solution for
keeping professionalsorganized and helpingthem communicate, while providing more robust
integration with personal computers. At the
same time, we created a richer platform and
more toolsfor software development.
Themarket and customers for mobiledevices
On the front linesof the businessworld, life is
continued on page 26 continued on page 29
Volume I, Number 5 November 1995
gygyNewton TechnoloJ O U R N A L
Technical Overviewof Newton 2.0:
The DeveloperPerspectiveby Christopher Bey, Apple Computer, Inc.
Version 2.0of the Newton System Softwarebringsmanychangesto all areas. Some
programming interfaceshave been extended;
othershave been completelyreplaced with new
interfaces; and still other interfacesare brand
givesnew. Thisarticle a brief overviewof what is
newand what haschanged in Newton 2.0,
focusing on those programming interfacesthat
you will be most interested in asa developer.
NEWTAPPNewtApp isa newapplication framework
designed to help you build a complete, full-
featured Newton application more quickly. The
NewtApp framework consistsof a collection of
protosthat are designed to be used together in a
layered hierarchy. The NewtApp framework
linkstogether soup-based data with the display
and editing of that data in an application. For
manytypesof applications, using the NewtApp
framework can significantlyreduce development
time because the protosautomaticallymanagemanyroutine programming tasks. For example,
some of the tasksthe protossupport include
filing, finding, routing, scrolling, displaying an
overview, and soup management.
The NewtApp framework isnot suited for all
Newton applications. If your application stores
data asindividual entriesin a soup, displaysthat
Newton Directions New Technology
Newton Directions
Newton 2.0: Whatsthe Big Idea? 1
New Technology
Technical Overviewof Newton 2.0:
The Developer Perspective 1
NewtonScript Techniques
Ensuring Newton 2.0Compatibility 3
NewtonScript Techniques
Converting Newton 1.x Appsto
Newton 2.0 6
Communications Technology
Newton 2.0CommunicationsOverview:Peeling the Onion 11
New Technology
Newton 2.0User Interface
Making the Best Better 17
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
2/32
November 1995 Newton Technology Journal
2
Newton 2.0 Out of InfancyLetscut to the chase here. What exactlyisso great about Newton 2.0and whyshould I
care? The answer is: lots. Lotsthat we think
you asdeveloperswill love and even more
that we think Newton platform customerswilllove. Thatsprobablythe most important part
about the whole 2.0launch. We havent
developed Newton 2.0just because we
wanted to. We developed it because it isa
powerful technologythat solvesreal customer
problems, and thatsthe reason were all in
business to solve customer problemsand
meet unfulfilled needs(and hopefullymake a
profit doing it!).
So, here we are announcing a major new
release of the Newton operating system; but
first, we have a little historyto get past. We
think Newton 2.0isjam packed with so many
improvements, historymayjust be forgotten.
But letstake a minute to look at that history
and evaluate exactlywhyit wasimportant for
the platformsevolution.
In 1993, Apple and Sharp launched their
first productsin the newPDA category
the Apple MessagePad and the Sharp
ExpertPad based on ApplesNewton OS.
Technologyenthusiastseagerlybought
them up, hoping to realize the promise of a
brand newtechnology. Theywanted to be
among the first to communicate wirelessly,
to enter data via handwriting input, and to
organize their liveson a computer smallenough to fit into their pockets. The press,
too, thrilled at the promise of a revolution
in technology, grabbed at the devicesand
began their evaluation.
Reactionswere not exactlywhat Apple had
hoped for. Almost immediately, the press
panned the Newton OS based primarilyon
one feature alone handwriting recognition.
But, a reallypositive thing, perhapsthe most
important thing of all, happend in response
to those lessthan stellar reactions.
Customersand developerstogether have
been evaluating the technology, realizing its
capabilitiesand potential, and creating real
world solutionsthat harnessthe platforms
power to handle real customer problemsin a
cost-effective, time-saving way. Some of thesesolutionshave been technologyexperiments
and some have been hard-core, positive ROI
productsfor businessprofessionalsand
vertical market customers. And theyall
resulted in some major accomplishments.
Theygot people thinking about the
possibilities. Theygot people doing real
thingswith PDAs. And theyhelped the
Newton Systemsteam at Apple learn to listen
long and hard to customer needswhile
continuing to refine the technologyand
improve on it for itsnext stage in life.
What technologysavvyfolksrealized, at the
time the Newton OS waslaunched, isthat new
technologyisnever born fullymature. Like
most life forms, technologymust also go
through manylife stages. In infancy, itsmere
existence isa miracle. It growsinto the
crawling yearswhen functionalitybeginsto
provide some freedom of movement with
exploration of anything it can get into. It
finallygetsto itsfeet and toddlesalong until
adolescence, when the growth rate is
phenomenal. Onlythen doesthe technology
enter a mature stage that could satisfythe
needsof itsusers. Newton devices, like most
life forms, have needed some time to growupin order to reach their potential. Theresno
doubt that the technologyisincredible and
hasbeen since introduction. But the Newton
operating system isnowwell on itsway
through the toddler yearsand into
adolescence. Itspotential isbeing realized, its
Published by Apple Computer,Inc.
Lee DePalma D orsey Managing Editor
GerryKane Coordinating Editor,Technical Content
Gabriel 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, Bruce Thompson
Contributors
Joseph Ansanelli, Christopher Bey, Garth Lewis,
Julie McKeehan,N eil Rhodes, Bill Worzel
Produced by Xplain CorporationN eil T icktin Publisher
John Kawakami Editor ial Assistant
Judith C haplin Art Director
1995 Apple Computer, Inc.,1 Infinite Loop,Cupertino,C A95014,408-996-1010. A ll rightsreserved.
Apple, the Apple logo, APD A, AppleDesign, AppleLink,AppleShare, Apple SuperDrive, AppleTalk, HyperCard,LaserWriter, Light Bulb Logo,Mac, MacApp,M acintosh,M acintoshQ uadra, M PW, N ewton, N ewton Toolkit, N ewtonScript,Performa, Q uickT ime, StyleW riter 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 uickD raw, SNA ps, StarCore, and Sound M anager aretrademarks, and AC O T isa service mark of Apple Computer, Inc.Motorola and Marco are registered trademarksof Motorola,Inc.N uBus is a trademark of Texas Instruments. PowerPC is atrademark of International BusinessMachinesC orporation, usedunder license therefrom. Windows is a trademark of M icrosoftCorporation and SoftW indowsisa trademark used under licenseby Insignia from Microsoft Corporation. UN IX is a registeredtrademark of U N IX System Laboratories, Inc. CompuServe,Pocket Q uicken byIntuit,C IS Retriever byBlackLabs,PowerFormsbySestra, Inc.,ACT! bySymantec, Berlitz,and all other trademarksare 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 bythe respective vendor or supplier.Apple assumesnoresponsibility with regard to the selection, performance, or use of
the products listed in this publication. A ll 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 ofmerchantability and fitnessfor a particular purpose.
gygyNewton TechnoloJ O U R N A L
Volume I, Number 5 November 1995
Letter From the Editorby Lee DePalma Dorsey, Apple Computer, Inc.
Editors Note
continued on page 10
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
3/32
Thisarticle providesguidelinesto help you ensure that your applicationsare compatible not onlywith current Newton devices, but also with future
devicesthat Licenseesmaycreate, and with Newton 2.0. Failure to follow
these guidelinesmaycause your application to break in the future.
UNDOCUMENTEDGLOBALFUNCTIONSDont use undocumented global functions. Documented functionswill
continue to exhibit their documented behavior. Undocumented functions
mayact differentlyin the future, or maynot exist. Here are some examples
of undocumented functionsto avoid:CreateAppSoup
(use the platformfile function RegisterCardSoup instead)SetupCardSoups
(use the platformfile function RegisterCardSoup instead)MakeSymbol
(use the documented global function Intern)GetAllFolders
Test by:Compile your application with NTK 1.6which will warn about callsto
undocumented global functions.
UNDOCUMENTEDGLOBALVARIABLESDont use undocumented global variables. Documented global variableswill
continue to contain their documented value. Undocumented global
variablesmayact differentlyin the future, or maynot exist. Here are some
examplesof undocumented global variablesto avoid:
cardSoups(use the platformfile function RegisterCardSoup instead)
extras
UNDOCUMENTEDSLOTSINFRAMESOnlyuse documented slots. Manyprotosand other objectsuse some slots
internally, in addition to the onestheydocument. Onlythe documented
slotsare supported; othersmaybe removed or changed. Here are some
examplesof undocumented slotsin objects:
cursor.currentpaperRoll.dataSoupGetRoot().dockerChooserGetRoot().keyboardChicken
UNDOCUMENTEDMAGICPOINTERSDont use undocumented magicpointers(defined in the platformsfile as@
numbers). These magicpointersindirectlypoint to actual objectsin the
Newton. If you use undocumented ones, theycould point to different
objectsin future devicesor system software.
SOUPSStore 0 is internal; all others are unspecified
The onlystore that you can count on isthatGetStores()[0] isthe internal store. Dont relyon the length of theGetStores() arrayor on the relative positionsof storesin that array(other than that the first is
the internal store). Future Newton devicesmight support more than one
PCMCIA slot, might support partitioning a large storage card into multiple
stores, or might support virtual stores(for example, a remote volume
appearing asa store).
Manyapplicationsthat support the action button contain code that callsGetStores() to determine the title of the card action item in thepicker. ThisisOK, but unnecessary. Instead, have your entryfor the card
action in your routing frame referenceROM_cardaction. Forinstance:
myRoutingFrame := {print: ,card: ROM_cardAction,
}
Test by:
Use the List command in NTK to search your project for callsto
GetStores(). Examine howyou use the result. Do you assume thatthe length will be no more than two?Do you assume that the second entry
will be the external store?
UNIONSOUPSUse the RegisterCardSoup/UnregisterCardSoup platformfilefunctions
At one point in time, shortlyafter the Newton wasreleased, developers
were told to add aRegisterCardSoup andUnRegisterCardSoup slot to their base template with code inRegisterCardSoupwhich calledCreateAppSoup and
SetupCardSoups. Later, platform file functionswith the same nameswere created, and developerswere told to use those instead. The platform
file functionsare guaranteed to do the right thing, even on future system
software, whereasdirect callstoCreateAppSoup and
SetupCardSoups arent supported.
Test by:
Use the List command in NTK to search your project for
CreateAppSoup orSetupCardSoups.Or, run your application with the Compatibilityapp (available in the
Llama Lounge area on eWorld) which will print to the Inspector if your
application callsCreateAppSouporSetupCardSoups.
Newton Technology Journal November 1995
3
Ensuring Newton 2.0 Compatibilityby Neil Rhodes & Julie McKeehan, Calliope Enterprises, Inc.
NewtonScript Techniques
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
4/32
soupChanged could be called more often
BroadcastSoupChange iscalled for your soup bythe system
when a store containing your soup isinserted or removed. In the future, it
maybe called bythe system when a soup iscreated, when a soup isdeleted,
or in anyother caseswhere a soup ismodified.
Test by:Run your application with the Compatibilityapp which will call
soupChanged from withinUnRegisterCardSoup and eachtime an entryisadded to a soup. Make sure your application works
correctly.
Constituent soups dont necessarily exist on all stores
For example, a store which isread-onlywont have a soup created on it.
In the future, constituent soupsmight onlybe created on the default store as
needed; if no entriesare added on a particular store, the soup wouldnt exist.
Therefore, dont write code like:
defaultStore:GetSoup("myUnionSoup"):Add();
Instead use:GetUnionSoup("myUnionSoup"):AddToDefaultStore();
The first code snippet maynot work since the constituent soup maynot
yet have been created.
unionSoup:AddToDefaultStore may throwan exception
AddToDefaultStore isdocumented to throwan exception incase of an error; it maystart doing so.
Test by:
Run your application with the Compatibilityapp which will cause
AddToDefaultStore to throwan exception on a store full error.Check the Simulate store full checkbox which simulatesa full store
(EntryChange andAddToDefaultStorewill simulate storefull).
Dont use unionSoup:Add
AlthoughAdd isdocumented to work for union soups, dont use it (whywould you want an entryto be added to an unspecified store, anyway?).
Test by:
Run your application with the Compatibilityapp which will print to the
inspector ifunionSoup:Add iscalled.
VIEWSYSTEMHandle any screen size
Make sure to handle screen sizesusingGetAppParams. Thescreen could be larger or smaller in one or both dimensionsthan currently
shipping products. For example, licenseesmight make unitswhich are
wider than theyare tall. If you have a minimum size and screen istoo small,
put up a slip stating the case. If you have a maximum size, use it (dont
blindlymake your app the size of the screen if it doesnt make sense).
Test by:
An application which simulatesdifferent screen sizesmaybe released
shortly; test with it.
Dont rely on the order of viewQuitScript messages
TheviewQuitScriptmessage issent first to the viewwhich isClosed. The order in which descendantsreceive theviewQuitScript isundefined and maychange. If you need to
guarantee the order in which messagesare sent, have your top-levelviewQuitScript send itsown message (maybemyViewQuitScript) recursivelyto descendants.
Test by:
Look at yourviewQuitScriptmethodseverywhere but in yourbase template. Do you send messagesto your descendantsor accessslots
from your descendants?What about your ancestors?
STRINGSUse only documented stringfunctions to manipulate strings
useStrLen to find out the length of a string useStrMunger to perform operationsthat change the length of a
string.//e.g. append "abc" to the end of astring
StrMunger(str,StrLen(str),nil,"abc",0,nil);
//e.g. delete 4 character fromthe end of astringStrMunger(str,StrLen(str)-4,nil,"",0,nil);
Do not use the following functionson strings:
Length (except to get the size of the binaryobject which maybe unrelated to the lengthof the string)
SetLengthBinaryMungeranyof theStuffXXX functions
Do not use undocumented string functions.
Do not put nullsinside strings.
e.g. string[10] := $\u00 as aquick wayto truncateastringto 10 chars.
Test by:Run your application in conjunction with the Compatibili tyapplication
which will print to the Inspector if functionsother than those documented
for stringsare called on a string. Note that the Compatibilityapplication
wont catch callstoLength.
USEPLATFORMFILEFUNCTIONS
When an API isprovided, use it.
Use RegFindApps and UnRegFindApps instead of modifying
findApps globalThe findAppsglobal variable isdocumented to contain an arrayof
symbolsof applicationswhich support global find. However, rather than
directlyaccessing thisarray, use the platform file functions
RegFindApps andUnRegFindApps.
Test by:
Use the List command from NTK to search forfindApps.
November 1995 Newton Technology Journal
4
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
5/32
Dont access the userConfiguration global directly
Instead, use the platform file functionsGetUserConfig,
SetUserconfig, FlushUserConfig.
Test by:
UsetheList command from NTK to search foruserConfiguration.
Dont send any messages to the IOBox app
Instead, use theSend platform file function.
Test by:
Use the List command from NTK to search forGetRoot().outBox.
UNDO/REDOFromwithin your undo action, call AddUndoAction
In Newton 1.x, the user interface supportstwo levelsof undo. Newton
2.0providesan Undo/Redo facilityinstead. In order to specifythe redo
action to Newton 2.0, your code needsto callAddUndoActionwhenthe user choosesUndo. Thus, you need to callAddUndoAction from
within the call which isexecuting an undo action.On 1.x systems, callstoAddUndoActionwhile an undo action is
being executed are ignored; on Newton 2.0, the same call would register a
redo action.
For example, here iscode handling deleting an item
MyDelete := func(item)begin
EntryRemoveFromSoup(item);AddUndoAction('MyUndoDelete, [item]);
end;
// here is the code to undo the deleteMyUndoDelete := func(item)begin
mySoup:AddToDefaultStore(item);
// Newton 1.x ignores this call
// Newton 2.0 treats it as aRedo of the deleteAddUndoAction('MyRedoDelete, [item]);end;
// here is the code to redo the deleteMyRedoDelete := func(item)begin
EntryRemoveFromSoup(item);AddUndoAction('MyUndoDelete, [item]);
end;
ROUTINGUse the slip symbols 'printslip, 'mailslip, 'faxslip, 'beamslip only inyour routingframe
Dont tryto accessGetRoot().printSlip, for instance. Inaddition, dont check those symbolsfrom yourSetupRoutingSlipmethod.
Test by:
Use the List command from NTK to search for each of the four symbols.
Make sure theyappear onlyasthe contentsof therouteSlip slotwithin your routing frame.
Dont rely on category symbols, 'printcategory, 'faxcategory,'beamcategory, 'mailcategory
Dont check for these symbolsfrom your SetupRoutingSlip method, for
instance.
Test by:
Use the List command from NTK to search for each of the four symbols.
Use only the 'body slot for your data in the fields frame
The bodyslot should be used for anydata you wish to preserve until
printing/faxing time. If you are beaming or mailing, the bodyslot will be
overridden with the target.
Test by:
Check yourSetupRoutingSlipmethod to see whether youwrite to anything other thanfields.body.
Dont read the iobox soup
The format of itemsin the iobox maychange.
Newton Technology Journal November 1995
5
NTJ
If you have an idea for an article youd like to write for Newton TechnologyJournal,
send it via Internet to:
piesysop@ applelink.apple.com or AppleLink: PIESYSOP
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
6/32
November 1995 Newton Technology Journal
6
INTRODUCTIONThisarticle tellsyou howto convert your existing Newton application to
take advantage of featuresof Newton 2.0. (Note that much of thismaterial
will not make sense if youre not alreadyfamiliar with creating an application
within the 1.0Newton operating system.) Well cover three typesof changes
you need to make: getting your 1.0application working in the 2.0world;
redoing your existing 1.0code to take advantage of enhanced existing
features; and adding support for new2.0features.
In the section that dealswith existing features, well cover soup changes
first. Newton 2.0givesyou increased control of soup information, aswell asoffering you the abilityto speed up your queriesand entrydisplays. Next,
well look at Filing and Find changesand then move on to the newwaythat
routing ishandled. For most of these topicswell provide you with source
code examples.
In the section that dealswith newfeatures, well point out the new
methodsor changesthat you might want to implement within your
application. Asyou can imagine, thisisa grab bag of topics, and isnot
covered in anyparticular order. Thissection isnot a comprehensive
treatment of the newfeatures; rather, we cover some of the more important
ones. Notice, for example, that one of the most important aspectsof the
Newton 2.0, NewtApp, isnot even discussed. Thisisbecause NewtApp is
better suited for applicationswritten from scratch.
MAKINGYOUR1.0 APPLICATION2.0 COMPATIBLEThe most basicupgradesinvolve both using NTK 1.6and making minor
changesto ensure compatibility. Reviewthe following stepsasyou upgrade
your application.
Check your existingapplication
The first step you need to take isto make sure that your existing
application workscorrectlyunder Newton 2.0. If it doesnt, then you should
work through the changesdescribed in Newton Compatibility elsewhere in
thisissue.
Build with NTK 1.6
Although it isnot necessaryto use NTK 1.6to build Newton 2.0
applications, it isdesirable, and since youll be making changesto yourapplication anyway, you mayaswell modifyit to use NTK 1.6.
Open your NTK 1.0project within NTK 1.6, then build and download it.
Run it through the standard set of pacesto verifythat the application works.
Use the Newton 2.0 platformfile
From the Project Settingsdialog, select the Newton 2.0platform file
rather than the MessagePad platform file. Rebuild and download and then
verifythat your application works.
Remove NTK 1.0 build order
From within the Project Settingsdialog, uncheckNTK 1.0 build order. By
doing this, NTK will no longer add pt_filenameslotsto the base template
for user protos. Now, change all of your code that referencespt_filename.
For example, if you have code that lookslike this:
GetRoot().(kAppSymbol).pt_filename
change it to:
GetLayout("filename")
Nowbuild your application. You will most likelyfind that the order in
which filesare built needsto be changed. In such a case, NTK will notifyyou
that the order iswrong with the following error message:
The filefilenamehasnot been processed yet
Note that a file referenced byGetLayoutmust be built before the call toGetLayout.
To change the order in which your filesare built, you will use the Process
Earlier or ProcessLater menu items. You can do thiswhile viewing the
project windowin NTK 1.6.
TAKINGADVANTAGEOFENHANCEDNEWTON2.0 FEATURESMany1.0featureshave been modified in the newsystem. Indeed, changes
have been made in virtuallyeveryfeature. Some featureshave been so
completelyoverhauled that theybear little resemble to their earlier versions;
an example of thisisrouting. Other featureshave been pepped up or have
been given increased capabilities, but operate prettymuch astheydid in the
past; Find isa perfect example of this.
Data storage
Manychangeshave been made to the waydata storage ishandled in the
Newton 2.0world. Some of the changesare fairlysimple, such ashowyou
register your soups; other changesinvolve implementing a whole newset of
calls, such asthe newsoup notification routines.
Soup registrationInstead of using RegisterCardSoup and UnRegisterCardSoup, you will use
RegUnionSoup and UnRegUnionSoup.
Note that these newroutinestake soup definition framesthat provide
information about the soup, itsindexes, a user-visible name, and so on.
Soup change notification
In the 1.0system, soup change notification wasfairlyrudimentary. You
would be notified that a soup had changed, but receive no information
Converting Newton 1.x Appsto Newton 2.0by Neil Rhodes & Julie McKeehan, Calliope Enterprises, Inc.
NewtonScript Techniques
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
7/32
about what had changed. In the Newton 2.0world the situation isimproved,
and the granularityfor notification ismuch finer. You can be notified about a
wide varietyof events, such as: an entryhasbeen added, an entryhasbeen
modified, a soup hasentered the union soup.
To use thisnewform of notification you must:
Call the auto-xmit routineswhen you change anyaspect of a soup
Register for the newtype of notificationYou will no longer add your application symbol to the soupNotifyarray,
but instead will call RegSoupChange and UnRegSoupChange. Also, you will
use the newQuerysoup method instead of the old standard Queryglobal
function.
Thus, your old querycode that looked like this:
Query(soup, )
Will nowlook like this:
soup:Query()
Tags for folders
The slowfolder displayin the 1.0system hasbeen fixed with theintroduction of tags. Thus, if your application supportsfiling, it isessential
that you use tagsto speed up you displayswhen the user isswitching
folders.
Add a tagindex to your soup
In your soup definition frame, add an index to the indexesarray. It
should look like this:
indexes: [,{structure:'slot, path: 'labels, type: 'tags, tags:[]}
]
Note that the tagsarraycan be empty. Asentriesare added to the soup,
the arraywill be updated automatically.
Use tagindex when doingyour initial queryIn your initial query, use the tagSpecslot of the queryspecto specifythe
folder. You also need to remove anycode in the validTest that wasused to
find entriesin a folder. Heresa before-and-after example:
soup:Query({type: 'index,indexPath: validTest: func(e) begin
return labelsFilter = '_all or e.labels = labelsFilterend,
});
Here isthe wayyour newcode should look:
if labelsFilter '_all thenmyCursor := soup:Query({type: 'index,
indexPath: tagSpec: [labelsFilter],})
elsemyCursor := soup:Query({type: 'index,
indexPath: });
Call query fromyour FilingChanged method
You will also need to call your newqueryfrom within your FilingChanged
method to avoid the slowdisplayspeed of 1.0. Here isan example of how
your newmethod will look:
app.FilingChanged = func()begin
if labelsFilter '_all thenmyCursor := soup:Query({type: 'index,
indexPath: tagSpec: [labelsFilter],
})else
myCursor := soup:Query({type: 'index,
indexPath: });// redisplay
end
Modify your tags when the user changes or deletes a folder
You must also update the tagsif a folder isdeleted or changed. You
neednt worryabout updating the tagswhen adding a folder, because the
tagsare automaticallyadded the first time an entrythat containsthe newtag
isadded.
Here iscode that handlesthe updating:
app.FolderChanged = func(soupName, oldFolder, newFolder)begin
//do nothingif afolder was addedif oldFolder then begin
// iterate through updatingeach entrylocal s := GetUnionSoup(kSoupName);local cursor := s:Query({type: 'index,
tagSpec: [oldFolder]});local e := cursor:Entry();while e do begin
e.labels := newFolder;EntryChangeXMit(e, kAppSymbol);e := cursor:Next();
end;
// update tagsif newFolder = nil then // afolder was deleted
s:RemoveTags([oldFolder])else // afolder was modified
s:ModifyTag(oldFolder, newFolder);end;
end
ENTRY
ALIASES
In the old 1.0world, you had to go through a bit of contortion when you
wanted to uniquelyidentifya soup entry. To create such a reference you had
to store a combination of entryunique ID, soup ID, and store ID. In
Newton 2.0, thingsare much simpler. Now, you create an entryalias. You
can then use it to uniquelyreference an entryand to retrieve that
corresponding entry.
The newcallsthat accomplish thisare MakeEntryAliasand
ResolveEntryAlias. You will use these anywhere you need to save references
to entries. For example, to save the currently-displayed entry, your code
should look like this:
app.viewQuitScript := func()begin
local currentEntryAlias := MakeEntryAlias(myCursor:Entry();// save currentEntryAlias in with other application preferences
);
Now, to open the application at the last-displayed entry, all you have to
do isthis:
app.viewSetupFormScript := func()begin
local currentEntryAlias;// initialize currentEntryAlias fromsavedpreferences
Newton Technology Journal November 1995
7
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
8/32
local currentEntry := ResolveEntryAlias(currentEntryAlias);if currentEntry then
myCursor:Goto(currentEntry);
end;
NEWQUERYSPECSYou will no longer be using startKeyand endTest in your queryspecs.
Instead, you will use beginKeyor beginExclKeyasa replacement for startKey.Likewise, you will use endKeyor endExclKeyinstead of an endTest.
There isalso the nice little addition of beingable to use an indexValidTest
instead of avalidTest if your validitytestingdependsonlyon the value of the slot
beingindexed. Thiswill speed cursor operationsup (because onlythe index
value isused, the entryitself doesnt need to be read to determine validity).
MULTI-SLOTINDEXESIn the Newton 1.x, you could index on onlyone slot. Thisisa thing of the
past in Newton 2.0, which providesmulti-slot indexes. Heresan example of
an index that sortsfirst bylast name and then byfirst name:
soup:AddIndex({structure: 'multiSlot,path:['lastName, 'firstName],type:['string, 'string]});
Heresan example of a querythat will use our newmulti-slot index:
soup:Query({type: 'index, indexPath: ['lastName, 'firstName]});
There are some other featuresthat you can set up in your indexesas
well. These include:
Specifying the sort order (ascending or descending) of keys
Counting the number of entriesin a cursor (cursor:CountEntries)
Resetting to the end of the cursor ( cursor:ResetToEnd)
Having string indexesbe case and/or diacritical sensitive
FINDANDFILINGManyof the changesthat have been made to Find and Filing in Newton 2.0
are similar, so theywill be covered together. Some changesare simple, such
ashowyou register with the system; other changesinvolve the addition of
newmethods.
Find registration
Use the platform file functionsRegFindApp and UnRegFindApp instead of
manipulating the findAppsarraydirectly(these platform file functionswork
in 1.x aswell asNewton 2.0).
Filingregistration
Instead of adding to the soupNotifyarray, use RegFolderChanged and
UnRegFolderChanged.
Find date equal
Within Newton 2.0there isa user interface for findingan entrywith a
particular date. Asa result, you need to support findingparticular dates. Here
issample code for DateFind that supportsfindingdatesbefore, datesequal,
and datesafter (it assumesentriesare indexed on thetimestamp slot):
app.DateFind := func(findTime, findType, results, scope,statusForm)begin
constant kMinutesPerDay := 1440;
if statusForm thenstatusForm:SetStatus("Searching in" &&
kAppName & $\u2026);
local theSoup := GetUnionSoup("Notes");if theSoup then begin
local queryFrame := {type: 'index,indexPath: 'timestamp,
};if findType = 'dateBefore thenqueryFrame.endExclKey := findTime;
else if findType = 'dateOn then beginqueryFrame.beginKey := findTime;queryFrame.endExclKey := findTime + kMinutesPerDay;
endelse // dateAfter
queryFrame.beginExclKey := findTime;local theCursor;
theCursor := theSoup:Query(queryFrame);if theCursor:Entry() then
AddArraySlot(results,{_proto :soupFinder,
owner: GetRoot().(kAppSymbol),title: kAppName,cursor: theCursor,findType: findType,findTime: findTime,
});end;end
Filter by storeThe folder tab can nowfilter not just byfolder but also bystore. If a
storesFilter slot existsin the parent inheritance chain of the folder tab, then
storesaswell asfoldersare shown in the folder tab. The value of the
storesFilter slot isnil if all storesshould be displayed. Otherwise, the slot is
set to a store object. When the user changesa store in the folder tab, the
FilingChanged method will be called.
Note that yourQuery callsshould take into account the currentstoresFilter ( just asit takesinto account the value of the currentlabelsFilter).
CARDROUTINGThe Newton 2.0user interface haschanged the location of card routing.
Moving to and from cardsisnowin the folder slip rather than in the action
picker. Bydefault, thisfeature isdisabled in the newsystem.
If you support card routing in your application, you should remove the
corresponding card slot from the routing frame. Next, you should add a
doCardRouting slot (with a value of true) to your application base template.
If your application doesnt support folders, but doessupport card routing,
you will also need to add a protoFolderButton to your statusbar and set the
value of doCardRouting in your base template to 'onlyCardRouting.
ROUTING
Manyof the changesin the newsystem make routing much easier toimplement. Changeshave been made in both the registration processand
in howvariousrouting actionsare implemented. Thus, you will need to add
newcode aswell asclean up your old code.
Remove the old 1.x routingregistration
An important first step isto fix the wayin which registration ishandled.
Start byremoving the code in your InstallScript that installsa routing frame in
the routing global and that callsBuildContext to add a viewto the root view.
November 1995 Newton Technology Journal
8
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
9/32
Likewise, get rid of the code in your RemoveScript that removesthe
routing frame from the routing global and the corresponding viewfrom the
root view.
Addingroute actions
To support actions( like duplicate and delete), add a routeScript slot to
your base template (actually, from anyancestor of the protoActionButton).The value of thisslot isan arrayof frames. Each frame containsthe following
slots:
title:routeScript: func(target, targetView)icon:
USINGSTATIONERYFORROUTINGIn Newton 2.0, routing ishandled bythe use of viewstationery. Thus, the
itemsthat appear in the routing button depend entirelyon the type of the
data that iscurrentlybeing viewed (theclass slot of the current target).Thus, within thisnewsystem you need to handle some newtasks: setting
the targetsclassslot and stationeryregistration.
Settingthe class of targetFirst, you should make sure that the target hasa classslot that specifiesthe kind of data in thisitem. For instance, a check-writing application might
have checkswith a classslot of '| check:MySignature| and depositswith a
classslot of '| deposit:MySignature| . It iseasiest to set thisclassslot when
entriesare created.
Stationery registration
To handle stationeryregistration you will be installing one data def for
each kind of data. For example, in a checkbook application, you would
install one data def for '| check:MySignature| and another one for
'| deposit:MySignature| . Typicallyyou will do thisinstallation in your
InstallScript and remove each data def in your RemoveScript.
Heresan example of registering:
RegDataDef(kCheckDataDefSymbol, {_proto: newtStationery,symbol: kCheckDataDefSymbol,superSymbol: kAppSymbol,name: "Check",version: 1
});
HandlingroutingYoull have to do some further conversion to handle print formatsin your
project. You will create a print format data viewbyadding a title slot ( the
same title that appearsin the format picker) and a symbol slot (containing a
symbol unique to your data view) to your templatesthat proto from
protoPrintFormat.If your application supportssending frames( like Beam and Mail) , then
you will also need to create a targetFrameFormat data view:
{_proto: targetFrameFormat,title: "my title",symbol: |target::check:MySignature|, //unique for the dataview
}
If your application supportsa text representation ( like Mail) , then you
need to add a textScript slot to your data def which will be used to create
text from the target.
Handlingthe In/Out box
In order for your application to displayyour data in the In/Out box, you
should create a data view. To do thisyou need to do several things:
1. Create a layout file with templatesthat can displayyour data (note that
methodsin these templatescan referencetarget, an inherited slotwhich will contain the target frame).
2. In the topmost template add the following slotsto make the template aviewer data view:
title: "Check Viewer",symbol: kCheckViewerDataViewSymbol,// unique for dataviewtype: viewer,
3. Install all your data viewsin your InstallScript with callsto RegDataView:
RegDataView(|check:MySignature|, myDataView);
4. Unregister your data viewsin your RemoveScript with callsto
UnRegDataView:
UnRegDataView(|check:MySignature|,kCheckViewerDataViewSymbol);
PRINTINGMULTIPLEITEMSUSINGCURSORSA newfeature of Newton 2.0allowsusersto handle routing tasksfrom theoverview. For instance, theycan select multiple itemsand print or fax them.
Note that, bydefault, each entryin the cursor isadded separatelyto the
Out Box. For view-type formats( printing/faxing) there isalso a wayto have
just the entryin the Out Box (for instance, if you want to print multiple
itemson one page). See the Newton ProgrammersGuide for more details.
ADDINGNEWTON2.0 FEATURESTOYOURAPPLICATIONThere are some important Newton 2.0featuresthat you should add to your
application, even if you dont take advantage of all the newpossibilities. You
might think of thisasthe must have list. These featuresare:
Supporting screen rotation
Rich text
Another feature that you should consider adding dependson the type of
application you have. If it makessense for your application, you mayalso
want to add support for being a Backdrop app (Backdrop appsare discussed
later in thissection).
HANDLINGSCREENROTATIONIn order for your application to run while the screen isrotated, it must have
a ReOrientToScreen method in itsbase view. Thismethod getscalled after
the screen isrotated.
Note that if your app viewusesviewjustification (or if it calls
GetAppParamsfrom the viewSetupFormScript) , changesto the screen size
can be handled bya call to SyncView. Therefore, the ReOrientToScreen
method can often be assimple as:
app.ReOrientToScreen := func():SyncView();
end;
You will also need to consider the layout of your viewswhen your application
isin arotated state. Obviously, thiswill varyfrom application to application.
Some applicationswill need to change howtheir viewsare laid out extensively,
while otherswill adapt to the neworientation without much tweaking.
Newton Technology Journal November 1995
9
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
10/32
November 1995 Newton Technology Journal
10
RICHTEXTRich text isnewto Newton 2.0. Rich text istext that isnot recognized but
remainsin ink form. The format of rich text islike a string, but with ink
wordsembedded ( the kInkChar character specifiesthat a particular
character isactuallyan ink word).
Note that these ink wordsare stored at the end of the string. Thus, there
maybe data in a string after the end of the last character.
Comparingnon-rich and rich text
Your application should support rich text everywhere it makessense. Dont
skimp here: the more placesyour application offersrich text, the more useful it
will be to the user. For example, in a check-writingapplication, you might need
to recognize onlythe amount (to keep track of a runningtotal) and the check
number (to check for duplicatesand to sort bycheck number). Since other
fieldsneed not be recognized (payee and memo, for example), theyshould
allowrich text. Another example isthe built-in Namesapplication. It allows
rich text for the last name but asksfor a letter to use for sorting.
protoRichInputLine and protoRichLabelInputLine
These protoswork much like protoInputLine and protoLabelInputLine.To obtain the rich text in the proto, use the method GetRichString(). Note
that you should not read directlyfrom the text slot.
Allowingrich text in other views
Bydefault, paragraph viewsand edit viewsdont support rich text. In
order to enable rich text, add a recConfig slot to the view. A predefined
configuration frame (suitable for recConfig) that will allowtext or ink is
ROM_rcInkOrText. To obtain the rich text, use MakeRichString, passing the
value of the text slot and the value of the stylesslot.
BECOMINGABACKDROPAPPIn order for an application to become the Backdrop application, it should:
be full-screen (otherwise, there will be blank partson the screen outside
of the application).
be able to rotate to landscape mode although thisisnot an absolute
requirement.
be prepared to never close. For example, it would be important when theuser changessome datato call EntryChange bymeansof awatchdogtimer
rather than waitinguntil the user closesthe application or scrollsto another
piece of data(the user mayleave thisdataopen for hoursor days!).
NEWTON2.0 TOPICSNOTCOVEREDThere are a number of other featuresthat we are not covering here but you
should consider adding to your application. These featuresinclude:
Extending your app with stationery
DILs
NCK
Communications
Extending Built-in appsusing stationery
SUMMARYIn thisarticle we covered the three different typesof changesyou need to
make to an application to bring it into the Newton 2.0world. The easiest
and most crucial changessimplyinvolve ensuring that it will run asis on a
Newton 2.0machine. Next, we discussed some of the modificationsto
existing Newton featuresthat you will want to take advantage of in your
code. Asmanyof the changesinvolve significant speed increasesfor the
user, theyare well worth your time and attention. Last of all we covered
some of the newfeaturesthat you will want to add to your application.
If you implement everything that we discussed here, you will be well on
your wayto having a good transition application from the 1.x to the Newton
2.0world.
NTJ
functionalityisgrowing and maturing, and customersare employing it in ways
that will further enhance itsevolution, and itsbusinesspromise over time.
Were thrilled to be able to bring you all of the latest newson the Newton
2.0OS in thisissue of the Newton TechnologyJournal. Our cover storieswill
introduce you to all of the newfeaturesbuilt into Newton 2.0, from amarketing and businessperspective aswell asa technical one. Weve
covered the critical issuesaround moving an application from 1.x to 2.0and
gaining compatibilitywith your existing 1.x applications. Weve also included
an article on the newcommunicationsfeaturesin Newton 2.0. Future issues
of thispublication will cover additional areasof 2.0, including programming
in-depth, and will run featureson whatever we find to be development
trouble spots although we hope there will be none!
So, with thisissue of NTJand the recent Newton Development
Conference, we are proud to bring you the Newton 2.0operating system.
Weve worked long and hard on it and were proud of the growth and
changesour infant hasgone through. We listened to customersand
developer feedback, and weve delivered on the next generation of the
platform. It isprobablynot yet a fullygrown adult, but an adolescent full of
power, capabilities, flexibility, and the agilityof youth. With thisgeneration ofthe Newton OS, userswill more easilyand more powerfullyorganize data,
communicate, and integrate with their desktop PCs. And itsyour Newton
2.0applicationsthat will help them do it. The Newton platform has
graduated from high school. Well look forward to seeing the newsolutions
that harnessitsabilitiesand help launch it into a world of possibilitiesfor
mobile professionalsand the vertical markets.
continued from page 2
Newton 2.0 Out of Infancy
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
11/32
Newton Technology Journal November 1995
11
INTRODUCTIONNewton 2.0isdesigned with communicationsintegrated throughout thesystem software. In anyNewton application the user will use similar interfaces
to dend information regardlessof the medium he or she isusingto send the
information. The general ideais, whatever you can see, you can send.
From a programming point of view, presenting a unified communication
interface appearscomplicated. Fortunately, the Newtonscommunications
architecture isdesigned in a layered way, and there isa great deal of built-in
communicationssoftware that we can use, so that, unlessyour
requirementsare fairlyunusual, little newprogramming needsto be done.Figure 1showsthe different layersin the Newton 2.0system. Most of the
layersare in the NewtonScript level, but the communication toolsare written
in C+ + . Within the NewtonScript layer there are five main piecesto the
system which are accessed from four separate APIs. We will look at these
layersone byone.
Figure 1: Newton Communications Layers
ROUTING
Newton 2.0communicationsare built around a store-and-forward model,
with target data stored in the In/Out Boxes. Store-and-forward describes
howmessagesare routed (directed) to a distant communicationsobject orfrom such an object to a Newton application through an intermediate
holding area (the In/Out Boxes). Target data isanypiece of information that
isrouted in or out of the Newton.
The In/Out Boxesare a single application that providesa user interface to
viewand manage messages, which are stored internallyasa soup. Figure 2
showswhat the In/Out Boxesmight look like when there are messages
pending. Note that at anytime the user can switch between In Box and Out
Box with the radio buttonsat the top of the view.
Figure 2
Routing isusuallytriggered byadding the protoActionButton to a view.
The protoActionButton, when tapped, displaysa picker showing available
actions(transportsand routeScripts.) asillustrated in Figure 3. Some
applicationswill have one protoActionButton in the statusbar; otherswill
have one in each of several views. The Namesapplication, for example, hasa
single Action button, since normallyonlyone name at a time isviewed. The
Notesapplication hasan Action button attached to each note, since there
maybe manynoteson the screen at anygiven time.
Figure 3
Each target object that isrouted must have a classslot identifying the typeof data associated with thiskind of object. Normallyeach application will
supplyitsown classof data for routing, such as'Note or 'Form or the like.
Thisclassisused bythe system to look up (in the ViewDefinition Registry)
the list of routing formatsthat maybe used to route the data. From these
routing formats, the system createsa list of communicationsmethods(faxing,
printing, beaming, etc.) that can route the target data. (These
communicationsmethods, or transports, are discussed in more detail in the
following section.) The net result isthat when the user tapsthe Action button
Communication ToolsSerial Modem MNP IR ATalkFax
Comm Tool DDK
Application
I/O Box
Endpoint Interface
Transports
Transport API
Routing API
Comm Scripting API
Newton 2.0 CommunicationsOverview: Peeling the Onionby Bill Worzel, Arroyo Software, [email protected]
Communications Technology
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
12/32
a list of destinationsappear which are possible for the target data.
Figure 4showshowthisisstitched together. An application, usuallyin
the InstallScript, will install into the ViewDefinition Registryone or more
formatsnamed for the classesof data it will route. These formatswill consist
of one or more dataTypesthat describe what form the target data can take
when routed. The system usesthisto search a list of installed transports;
when it findsa transport that supportsone of the dataTypes, it addsthetransport name to the list to be displayed in the Action Button.
In Figure 4, the application hasinstalled into the ViewDefinition Registry
a frame, | forms:PIEDTS| , which supportstwo routingTypesof 'viewsand
two of 'frames. At least one of the typesissupported byeach of the built-in
transportsfor printing, faxing, beaming, and mailing, so these optionsappear
in the Action button. Note that it doesnt pick up the transport whose
dataType is'binary.
Figure 4
When the user selectsa transport from the Action button, a routing slip is
displayed and all formatsin which the data can be displayed appear in the
format picker, asshown in Figure 5. Formatsare ViewDefinitionsthat
describe howthe target data should be organized before sending it to the
appropriate destination. When printing, for example, there maybe several
formats letter, memo, two-column, etc. that describe howthe target data
will be printed or faxed.
Figure 5
When the user selectsa format for the target data and sendsit off, the
appropriate transport isthen messaged with information about the target
data, and it isplaced the target data the Out Box for further disposition.
TRANSPORTSThe simplest definition of a transport issomething that routesyour data.
But a clearer definition isthat a transport isa globallyavailable service
offered to applicationsfor sending or receiving data. Because of the global
nature of transports, it isnot necessary, or even likely, for an individual
application to define a transport.
The built-in transportsinclude printing, faxing, mailing, and beaming, but
one might imagine additional transportssuch asmessaging (point-to-point,
real-time message passing), scanning, and even compressing, or archiving
data. Thus, while transportsare usuallyassociated with hardware (printers,
mail servers, and scanners, for example) theyare not limited to hardware,
and a service maybe offered that altersthe data being routed without
sending it to anyoutside hardware.
Transportsare built asauto-load packages; which meansthat theydo
not appear in the ExtrasDrawer. Instead, a transportsInstallScript registers
the transport with the system bycalling the function RegTransport. As
described in the routing section above, if appropriate target data isrouted,
the transport maythen appear in the Action Button picker in an application
when the user tapsthe button.
Because most transportshave communicationscode that will be used to
send or receive the target data, theywill typicallyhave communication
endpoint code that communicateswith the destination.
Transportsusuallywork with an application through the In/Out Box
application. Figure 6showsthe interactionsbetween the NewtonScript
application, the In/Out Box, and a transport during a send request.
Figure 6
In/Out Box Transport(User routes item(s)to I/O Box)
SendRequest,
cause:submit
(User sends item(s)preivously routed toI/O Box)
SendRequest,cause:user
(Transportsends data todestination)
ItemCompleted
(Out Boxremoves itemfrom display)
ItemRequest
targetData:={.
class:|forms:PIEDTS|..
.}
Routed Object
|forms:PIEDTS|:{viewFormat:{dataTypes:view...},faxFormat:{dataTypes:view...},frameFormat:{dataTypes:frame...},frameAndFormat:{dataTypes:[text,frame]...},};
format2:{...}
format3:{...}
Routing Formats in View Definition Registry
[printTransport:{dataType:[view]...},faxTransport:{dataTypes:[view,text
]...},beamTransport:[dataTypes:frame
]...},mailTransport:[dataTypes:text,`frame
]..},compressTransport:[dataTypes:binary
]]
Installed Transports
November 1995 Newton Technology Journal
12
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
13/32
In particular, a transport receivesa SendRequest whenever an item is
routed to the Out Box. The request sent to the transport hasa cause slot
that describeswhythe transport wasnotified. In the case of target data that
isheld in the Out Box, the cause slot will have a value of 'submit, indicating
that it isposted but should not be sent yet. If the cause is'user or 'item,
then the transport should send the target data.
In either case, after processingaSendRequest message, the transport shouldcall ItemRequest to see if there are anyfurther itemsposted in the Out Box.
A request to receive data, isalittle more complicated. In the simplest case,
when the user selectsatransport from the Receive button list in the In Box, the
selected transport issent aReceiveRequest message. The transport will connect
to the remote source, get anypendingdata, and add it to the In Box list.
In a slightlymore complex situation, the transport maysimplyget a
description of what isavailable at the source (for example, the title of an
email message) and post it to the In Box. In thiscase, the transport must
add a remote slot to the request and set it to true. Thisflagsthe item so that
the In Box knowsthat the bodyof the data hasnot arrived. The user may
later select the item from the In Box and ask to see it, at which point the In
Box will send the transport another ReceiveRequest message, but with the
cause slot set to 'remote. The transport will then be responsible for gettingthe bodyof the data so the In Box can displayit.
Aswith sending a message, the transport should then check for other
pending receive requestsbycalling ItemRequest.
Note that ItemRequest isdefined in protoTransport, so the transport
sendsitself a message for the purpose of getting information from the
system in thiscase, the next item to be transported.
Asmentioned above, the main proto used to create a transport is
protoTransport. protoTransport ispowerful and in manycasessurprisingly
little code other than the actual endpoint code needsto be written. Thisis
because the defaultstypicallydo the right thing to provide an interface and
default behavior for the transport.
In particular, taskssuch asdisplaying the statusof a routing request,
logging of routed items, error handling, power-off handling, and general user
interfacesare handled well bythe defaultsif the transport simplysetsor
updatesa fewslotswhen appropriate. Onlythe actual service code (such as
communications) will be different between transports.
The keymethodsand variablesthat are usuallyimplemented in a
transport are asfollows:
status // used to displaythe status of arouting// request sent to atransport, set usingthe// method: SetStatusDialog
actionTitle // title that appears in the transports// routingslip
appSymbol // the transports symbol, used to match the// transport with the itembeingtransported
icon // icon that appears in the transports// routingslip
SendRequest // message sent to the transport from// the In/Out Box datawhen itemposted// or requested to send out
ReceiveRequest // message sent fromthe In/Out box to// receive or to complete receipt of// items previouslyreceived in summary// form
CancelRequest // method to stop transport of dataNewItem // message fromthe In/Out Box to create an
// itemfor displayin the In/Out Box, usually// overriden byatransport to add transport// specific information about an item
ItemRequest // message sent bythe transport to self// to request next itempendingin a// send/receive action
ItemCompleted //message sent bythe transport to
// self to notifythe systemitem// transport action (send/receive) has// finished
In addition to these methodsand slots, there are manyother features
that maybe added to a transport to augment or override user interface
featurescontrolling the displayand format of data being transported or the
action of the transport.The DTS sample ArchiveTransport showsa minimallyimplemented
transport that providesa global, frame-based transport for archiving frame
information in an archive soup.
ENDPOINTSEndpointsare the primaryAPI for programming communicationson the
Newton in NewtonScript. Theyprovide a virtual pipeline for all
communications. Endpointsare designed to hide the specificsof a particular
communicationsmedia asmuch aspossible, and once connected, present a
genericbyte-stream model for input and output.
Endpoint code to receive data from an AppleTalk network can be
identical to code to receive data through a modem, which can be identical to
code to receive data over a serial line, etc. Thingssuch aspacketization which occursin anynetwork protocol are hidden from the endpoint user
during sending and receiving, asare flowcontrol, error recovery, etc.
The onlyexceptionsto thisrule occur when there are specifichardware
limitationsthat cannot be hidden bythe endpoint API. For example, IR
beaming isa half-duplex protocol (that is, it can send or receive, but not
both at the same time) while serial, AppleTalk, or modem communications
are all full-duplex (that is, theycan send and receive at the same time).
Of course, while sending and receiving are media-independent, the
connection processisnecessarilytied to the media being used. So, for
example, with AppleTalk it isnecessaryto specifynetwork addresses; for
modem communications, a phone number; for serial communications,
speed, parity, stop bits; and so on.
Figure7showsthelifecycleof an endpoint. An endpoint isinitiallydefined as
aframein an application that isbased on theprotoBasicEndpoint proto. Thishas
several slotsdescribingthesettingsof theendpoint and methodsthat maybe
called bythesystem duringthecourseof itsexistence. However, thisframeisnot
an endpoint. That is, it describeswhat an endpoint might look like, but it isnot a
NewtonScript object. To createsuch an object it must first beinstantiated. Note
that sincetheobjectsused most often in theNewton OSareviews, and sincethe
viewsystem automaticallyinstantiatestheviewobject when it isopened, we
usuallydont seemuch instantiation codein apps. But with an endpoint, because
it isindependent of theviewsystem, wemust explicitlyinstantiateit to createan
endpoint object.
Figure 7
Life Cycle of an Endpoint
EP:Instantiate()
EP:Bind()EP:Connect()EP:Output.()/SetInputSpec()EP:Disconnect()EP:Unbind()EP:Dispose()
Note: EP isa fictitousreference to a NewtonScript frame
which isbased on protoBasicEndpoint
Newton Technology Journal November 1995
13
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
14/32
Once the endpoint isconnected, it should be bound to a particular
address, node, etc., depending on the media. An AppleTalk endpoint, for
example, isbound to a node on the network. Thisisdone bysending the
endpoint the Bind() message.
After binding the endpoint, the Connect message issent to connect to
the particular media being used. For a remote service that isaccessed
through a modem endpoint, the endpoint would dial the service andestablish the physical connection (but not protocol itemssuch aslogging on,
supplying passwords, etc.; these are part of an ongoing dialog that the
application and the service must engage in once connection isestablished).
The endpoint method Listen() maybe used to establish a connection
instead of the Connect() method. In thiscase the endpoint isconnected
and readyto listen to an offer bythe communicationsmedia. Based on
the the particular situation with the remote media, an application mayeither
reject the connection bysending the Disconnect( ) message to the endpoint,
or accept it with the Accept() message.
After connecting, the endpoint isreadyto send and receive data.
Sending isfairlystraightforward and isdone byusing the methodsOutput()
and OutputFrame().. The latter method isused to send Newton framesto
other entitiesthat understand thisdata format, the former isused to send allother kindsof data. Such callsmaybe made either synchronouslyor
asynchronously.
Receiving data isa little more complex. Incoming data isbuffered bythe
system belowthe application endpoint level. An application must set up a
description of situationsto trigger processing of incoming data. This
description isin the form of an inputSpec. For example, an inputSpeccould
be created which looked for the string login:, or it could be set to trigger
when 200characterswere received, or after 100milliseconds. To some
extent it can be set to notifythe endpoint of incoming data after a
combination of these events(e.g., after the string login: isseen or after 100
milliseconds, whichever comesfirst) .
When an inputSpecinput condition ismet, an appropriate message is
sent to the endpoint. Thismessage differsdepending on the cause of the
trigger; for example, a PartialScript message will be sent if the condition
causing the event isa 100-millisecond wait, while an InputScript message will
be sent if a specified string hasbeen received or character limit reached.
At anygiven time, the endpoint will have onlyone inputSpecactive. By
default, the active inputSpecwill remain active until told otherwise.
InputSpecsare activated bysending the message SetInputSpec() to the
endpoint with a reference to an inputSpecframe.
Bychaining inputSpecstogether, a communicationsstate machine of
arbitrarycomplexitycan be created. For example, before connecting to a
service, an application might call SetInputSpec() with an inputSpecthat
looksfor the string login:. Once that string isseen, the InputSpec()
method within the inputSpecmight call InputScript ( ) to activate an
inputSpecthat looksfor the string password:. When thisstring arrives, the
InputScript code might call SetInputSpecto activate an inputSpecthattriggersevery100charactersor when a carriage return character isreceived.
In thisway, endpointscan be used to build a communicationsprotocol
based on expected behavior of the service.
Endpointsdeal with different formsof data well. Since the Newton uses
Unicode (16-bit) character representations, and since most systemsstill use
ASCII, character stringssent or received through endpointswill do a Unicode-
to-ASCII and ASCII-to-Unicode translation bydefault. Thisdefault maybe
overidden byadding an encoding slot to the endpoint with a system constant
describing a translation table to be used for all character data.
At aslightlyhigher level adataform maybeused to convert incomingor
outgoingdataasappropriate. Figure8showsalist of thedataformsthat can be
used to format incomingor outgoingdata. Theseformscontrol howthedatawill
betreated with, for example, 'char and 'stringformsgoingthrough translation
tablemappings, with 'number beinginterpreted asaNewton 30-bit integer.
Data Form Description'char Default value for sending characters, does
ASCI I-to-Unicode or other translationsbased
on encoding slot.
'number Convertsto or from 30-bit integer.'string Default for sending and receiving strings,
Unicode-to-ASCI I conversion isdone unless
overridden bythe encoding slot. Termination
character isadded to the string.
'bytes A stream of single-byte values. No translation isdone onthe values.
'binary Used to receive or send rawbinary data.
'template Used to exchange data with a service that expectsC-typestructures.
'frame The data isexpected to be a frame. For output, the frameisflattened into a stream of bytesprior to being sent; for
input, the byte stream isunflattened and returned asa
frame. Particularlyuseful when beaming or
communicating with a desktop machine using DILs(DILs
are descibed below).
Figure 8
Perhapsthe most intriguing of these data formsisthe 'template form,
which can be used to map a seriesof data valuesinto different formatsin the
same waya C-structure describeshowto read successive valuesin memory.
Thisisalso used to describe endpoint options the state settingsfor the
endpoint when creating or modifying the endpoint object.
When an application isdone sending and receiving data and wishesto
tear down the endpoint, there are messagesthat maybe sent to an endpoint
to break down the state built up during the processof connecting and
communicationg with the media.
The first step isto terminate anyoutstanding inputSpecsbysending a
Cancel message followed bya SetInputSpec() message with a nil inputSpec.
Thisterminatesthe current inputSpecand establishesthe fact that no more
input will be accepted.
Then, the connection isbroken bycalling the Disconnect( ) method.
Next, the Unbind() message issent to break the addressassociation
between the endpoint and the media.
Finally, a Dispose() message issent to destroythe endpoint object. Notethat the endpoint maybe left instantiated or disconnected if it isanticipated
that it maybe reconnected later in the life of the application.
LOW-LEVELCOMMUNICATIONSTOOLSBelowthe NewtonScript level there are built-in system toolsthat provide
basiccommunicationsfunctionality. When an endpoint isinstantiated, one
of the thingsthat must be defined isthe type of the endpoint. This
definition causesthe endpoint to be connected to one of the existing low-
November 1995 Newton Technology Journal
14
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
15/32
level toolsthat are written in C+ + and run in a separate task thread.
While the detailsof these toolsare beyond the scope of thisarticle, at
some point Apple will release the necessaryprogramming interfacesand
toolsto support the development of third-partycommunicationstools.
DILS
Not shown in the diagram in Figure 1, but still important to Newtoncommunicationsprogramming, are a set of librariescalled the Desktop
Integration Libraries, or DILs. The first and most important thingabout DILsis
that theydont run on the Newton. The DILsare librariesfor Macintosh and
Windowsdevelopment environments, and are used to create appswhich can
establish a communicationslink between Newtonsand desktop machines.
Figure 9showsthisrelationship. Essentially, endpoint code on the
Newton, whether hooked directlyto an application or via a transport, sends
data from the Newton to a desktop machine. On the desktop machine, an
application that usesthe DILssendsand receivesdata which isthen
displayed on the desktop machine. Currently, DILsare available for MacOS
and Windowsplatforms.
All of the DILsare librarieswritten for C. On the MacOS platform, there
are MPW, Think C, and MetroWerkslibraries. On the Windowsplatform,DILsare implemented asa DLL and therefore should be independent of
particular C language implementations.
Figure 9
The DILs main feature isthat theyabstract the connection to the Newton
to a virtual pipe for bytes, and theyprovide control over thingssuch as
ASCII-to-Unicode conversionsand Newton data structuresand typessuch as
framesand 30-bit integers.
Asshown in Figure 10, there are three DILswhich build off of one another:
CDILs, FDILs, and PDILs. CDILsprovidesbasicconnectivityto a Newton. To
use FDILsand PDILs, you must use CDILsto establish a connection. FDILs
provide a relativelysimple wayto map NewtonScript framesto C structures
and also provide a mechanism to handle data that wasadded dynamicallyto
the frame. PDILsprovide an easymechanism for synchronizingdata between a
Newton application and a desktop application. AsI write this, PDILsare not yet
available, but will be available in the future.
Figure 10
CDILSCDILs essentiallyhave the following phases: initialization, connection, reading
or writing, disconnecting (sound familiar?). The idea isto create and open a
virtual pipe to the Newton and then communicate using some predetermined
protocol bysending and receiving messagesor data down the pipe.
The CDInitCDIL function must be called before anything can be done
with CDILs. On Windowsmachines, the routine CDSetAppplication must becalled next. There isno equivalent call on the Macintosh. Next, the routine
CDCreateCDILObject() iscalled to create a CDIL pipe. CDCreateCDILObject
returnsa pointer to a pipe; thispointer must be used for all subsequent calls
involving that pipe.
CDPipeInit initializesa pipe object so that it isopen for business. In
particular, it definesthe communicationsoptions, including the media details
such asconnection type (serial, AppleTalk, etc.) and relevant media options
(speed of connection, dataBits, modem type, etc.).
Next, the pipe waitsfor the connection from the Newton using the
function CDPipeListen. When the Newton contactsthe desktop machine,
the application using the CDIL mayaccept the connection bycalling
CDPipeAccept. At anytime in thisprocessthe desktop application can
cancel an attempted connection bycalling CDPipeAbort.Once a connection isestablished and working, data can be sent and
received using the routinesCDPipeRead and CDPipeWrite. Aswith most
CDIL routines, these callsmaybe made either synchronouslyor
asynchronouslywith a callback routine. (MacOS programmer note:
callbacksare not executed at interrupt time, so theyare not subject to the
restrictionsplaced on code running at interrupt time.)
From thispoint on, the desktop application and the Newton application
will probablyengage in an application-specificprotocol where there will be a
predictable exchange of messagesand data via the CDILsvirtual pipeline.
When the decision ismade to terminate the connection, the routine
CDPipeDisconnect maybe called. Once thisfunction hascompleted, the
connection hasbeen broken and both sidesmust reestablish the connection
before anymore data can be sent or received.
Finally, when the desktop application iscompletelyfinished with the
pipe, it must call the functionsCDDisposeDILObject to tear down the pipe
and CDDisposeCDIL to clear the CDIL environment.
FDILFDIL, or Frame Desktop Integration Library(also called HLFDIL for High
Level FDIL), isused to support transferring NewtonScript objectsto and
from the desktop in an orderlyfashion. A CDIL connection must be
established, and isused to transfer frames.
Before FDIL callscan be made to move information to or from the
Newton, the FDIL routine FDInitFDIL() must be called to initialize the library.
The simplest use of an FDIL isto map NewtonScript framesinto C
variables. If the frame shown in Figure 11isgoing to be uploaded to a
desktop machine, the desktop application can use FDILsto map thisframeinto the C structure shown in the figure.
aFrame:={ slot1:'b,slot2: { slot1:24,
slot2:{slot1:16,slot2:$c}
}slot3: "TROUT"}
struct {char slot1[5]; // whatever symbol lengthstruct slot2 {
PPPPPDDDDDIIIII LLLLL (((((PPPPPrrrrroooootttttooooocccccooooolllll DDDDDIIIII LLLLL)))))
FFFFFDDDDDIIIII LLLLL (((((FFFFFrrrrraaaaammmmmeeeeesssss DDDDDIIIII LLLLL)))))
CCCCCDDDDDIIIII LLLLL(((((CCCCCooooommmmmmmmmmuuuuunnnnniiiii cccccaaaaatttttiiiii ooooonnnnn DDDDDIIIII LLLLL)))))
Newton
(Endpoint Code)
Desktop Machine(Windows or
Mac OS)
(Application builtusing DIL code)
Newton Technology Journal November 1995
15
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
16/32
November 1995 Newton Technology Journal
16
long subslot1;char subslot2;
};char slot3[32]; // whatever max strlen
}
Figure 11
To build the mapping between the NewtonScript frame and the C structure,make repeated callsto FDbindSlot. These callsmatch a Newton slot name
(or an arrayobject) to a C variable or buffer. Part of the call isa maximum
size to ensure that the capture of the NewtonScript object doesnot overflow
the memoryreserved for the C variable.
In thisexample, there would be repeated callsto FDbindSlot, each of
which would specifya slot name for an element in the frame and the address
of the C variable or in thiscase structure member. Once thisisdone, the
data can be transferred bycalling FDget. When the Newton sendsthe frame
data (presumablybycalling OutputFrame ) to the desktop, the FDIL will
move the data into the appropriate locationson the desktop machine.
If data were to be sent to the Newton, the desktop application would call
FDput to send the data at the addressesspecified bythe FDbindSlot callsto
the Newton in a flattened frame format that the Newton can understand. Inthiscase, on the Newton side it would be expected that an inputSpecwould
have been established which expected a data form of 'frame.
Thisisthe easiest and most efficient wayto move data to and from the
Newton, but since NewtonScript framescan change dynamically, there needs
to be a wayto get information from the Newton which the desktop
application maynot have known about when the initial binding took place,
or newinformation created after binding. Thisisdone bytransferring data
to the desktop machine into a dynamictree structure that can be parsed by
the desktop machine. Thisdata iscalled unbound data.
Asbefore, a CDIL connection must be established; then, a call to FDget will
transfer anydata. If anyof the data transferred isbound, it will be put in the
appropriate location. Otherwise, it will go into dynamicallyallocated memory.
To get the unbound data, the routine FDGetUnboundList returnsa pointer
to a tree. Thistree isorganized with a branch for each element in the
structure on the Newton. The list structure isan arrayof elements, each of
which in turn maybe a list of elementsif the particular branch hassub-
elements. For example, if the Newton frame shown in Figure 11were brought
into the desktop machine in an unbound form, there would be three
branches(one for each element). Branch two would have two sub-branches,
and branch two of branch two would have two branches.
Using thisstructure, you can write code to parse and use the unbound
data. After the desktop application isdone with the unbound data, it should
be disposed of bycalling FDGetUnboundList.
Examplesof CDIL and FDIL usage can be seen in the DTS sample
SoupDrink, which transfersthe contentsof anysoup on the Newton to the
desktop or sendsframesfrom the desktop to the Newton.
NTJ
NTJ
Newton
CommunicationsA Point of Viewby Eileen Tso, Apple Computer, Inc.
Asthe CommunicationsEvangelist for the Newton platform,whenever I discussthe 2.0operating system and its
improvementsbeyond the 1.x communicationsstory, I am
proud to hear myself tout that our operating system usesan
extensible architecture which allowsfor advanced
communicationscapabilitiesand features.
I hope youll notice that we have moved toward a truly
modular system. Our architecture islayered, and providesaccessto built-in toolsthat nowexist for you. The I/O box,
transports, and endpointsof 2.0are just a glimpse of howwe
plan to continue moving our commsarchitecture forward,
enabling you to write more powerful applications as
explained in the accompanying article.
To be fair, and ensure that we maintain a realisticlevel of
expectation, we must acknowledge that itsimperative for us
to continue thisforward momentum. A lot of you are
probablyanxiouslyawaiting the release of our DDKs( driver
development kits), and those are on their way. Bythe same
token, a lot of you would also probablyappreciate a TCP/IP
stack for your commssolutions. Be assured, a TCP/IP stack is
also on itsway. Other issues, such asmemoryrestrictionsand
more than one PC Card slot are, asyoure well aware,
hardware-dependent. And with the emergence of our 2.0
operating system, I think well all be watching for new
hardware devicesfrom Apple and our licenseeswhich will
enable usto reallytake advantage of the newcommunications
functionalityin 2.0.
I think youll agree that weve made significant stridesin
our communicationsstory, and Im onlythe first to saythat
there are still issuesto conquer. But aswe continue to take
these stepsforward, I hope youll agree that we reallyare
moving in the right direction. Asyour first point of contact for
communications-related development, please dont hesitate to
let me knowif you think otherwise!
Our objective isto make it easier for you to help ustocomplete our communicationsstory, and I feel verystrongly
that were making improvementstowardsthat goal. We learned
a great deal aswe encouraged development of comms
solutionsfor our 1.x product, and based on those insights, Im
proud to saythe 2.0realm hasbrilliant possibilities!
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
17/32
Newton Technology Journal November 1995
17
If anysingle idea served asthe guiding principle in the development of theNewton 2.0user interface, it wasthis: listen to the customer. The feedback
from Newton 1.x users, developers, analystsand the pressfueled every
phase of the re-design. Leveraging two yearsof feedback, from our own user
studiesand from the field, the Newton team set out to enhance an already
acclaimed UI and to addresswhatever shortcomingsexisted. Despite greatly
expanding functionality, the team strove to maintain the simplicitythat isthe
essence of Newtonsdesign. In short, the goal wasto keep the best and fix
the rest.
Thisoverviewexamineswhat haschanged in the newuser interface,what prompted the changes, and howthose changeshave been received by
users. It will not touch on everyUI change in Newton 2.0. Instead, it
highlightssome of the more important changesand givessome of the
rationale behind them.
Central to the user complaintsabout Newton 1.x were problems
surrounding data entry. Recognition received itsshare of criticism, but other
areasalso frustrated users: difficultywriting in fieldsand expandos, lack of
readability, problemswith correction, memoryproblems(especiallywhen
using ink) , a sense of UI inconsistencybetween applications. In short, there
wasa perceived lack of precision and predictabilitywhen it came to getting
information into the MessagePad.
Therefore, an overarching goal of Newton 2.0wastoease data entry,
manipulation and viewing. Handwriting recognition, still an emerging
technologywhen Newton launched in July1993, hasmade big stridesover
the past year and a half. So too hasthe effort to find alternativesto
recognition. The pervasive use of pickers, a newdefault font, greater
support of electronicink, and the introduction of remote writing all serve
to help usersget data into their Newton devices, and to make it useful once
itsthere.
Another overarching goal in the redesign processhasbeen toestablish
greater consistency, in both look and functionality. System fonts, styles, and
slip layoutsall conform to a single style, therebymaximizing readabilityand
ease of use. Functionality, too, hasbeen generalized throughout the system:
New and Show buttonshave been generalized throughout applications,
keyboard and recognition buttonsare ubiquitous, routing and filing are
supported in nearlyall areas( including the ExtrasDrawer).
RECOGNIZETHIS!Perhapsthe most widelyheard comment during user testsof Newton 2.0has
been howmuch recognition hasimproved. Experienced usersperceive
enhanced recognition performance using both printed and cursive
handwriting styles; newusersare impressed byhowmuch better recognition
isthan theyexpected. Better accuracyisevident acrossthe board: text and
numbers, dictionaryand non-dictionarywords, and punctuation.
Improvementsstem in part from better algorithms, larger dictionaries
(roughly90,000wordsat presstime), lessconstrained recognition in fields,
and an expanded character set.
Still, even with the improvementsin recognition performance, studies
showthat there will continue to be a subset of userswho do not have success
with recognition (because of handwriting idiosyncrasiesor other inhibitors).
For those users, Newton 2.0featuresa number of recognition alternatives.
In termsof user interface elementsto control recognition, the
recognition popup hasevolved from a three-button toggle to a popup
(fig. 1). Thisdesign hasmanyadvantagesincluding clarityand extensibility,
aswell asproviding accessto handwriting preferences. While the popup
addsa tap in most cases, usage patternssuggest that userstend to leave therecognition control in a particular setting. (The need for momentaryletter-
by-letter setting waseliminated byadvancesin recognition.)
Fig. 1 screen shot of rec pop
Another keyimprovement isthe addition of remote writing. Thisfeature,
manifested bythe caret ( fig. 2) which indicateswhere a word isplaced,
solvesthe problem of unpredictabilityof word placement in Newton 1.x.
With the caret, there isno ambiguityor guesswork involved. The user can
write wherever it iscomfortable to write and knowwith certaintywhere the
recognized text will appear. Editing, too, ismade easier. For example, if you
want to replace a word in the middle of a paragraph, all you do isselect the
word and then write anywhere on the screen and the word isreplaced. InNewton 1.x, the task of scrubbing, inserting space, and rewriting wasoften
daunting to users. Usersare extremelykeen on thisfeature: I love the fact
that you knowwhere the insertion point is! It makesediting and work
addition so much easier, not to mention the punctuation marks.
Newton 2.0 User Interface Making the Best Betterby Garth Lewis, Apple Computer, Inc.
New Technology
-
7/28/2019 Newton Technology Journal: Volume 1, Number 5
18/32
Fig. 2 screen shot of caret
The corrector popup (fig. 3) hasalso been enhanced. Thanksto
recognition refinements, if a word ismisrecognized, the alternate word list is
much more likelyto contain the correct word. In addition, a newletter-by-
letter correction tool providesthe user a larger writing area in which tooverwrite letters, correct segmentation problems, and so on. Research
showsthat manyNewton 1.x usersrelied on the keyboard to correct
misrecognized words. In Newton 2.0, overwriting isthe first line of defense
and the newcorrector isa welcome fallback. Asone user said, The
corrector ismuch preferred to the old method of just getting the keyboard,
because previously, I would often have to use the arrowkeysa lot to get to
the character I wanted to correct. Thismakesit easier. The newcorrector
isespeciallyuseful when using smaller fonts(which makesoverwriting more
difficult) . I t also offersaccessvia popupsto letter alternates. The new
corrector can also be used for bulk correction. In thisscenario, the user
leavesthe corrector ope