NewtonTechnology ®
J
O
U
R
N
A
L
Vol ume II, Number 4
August 1996
New ewtonScr tonScript ipt Techniques Techniques
InsideT his Iss Issue NewtonScript Techniques slimPicker: ker: A Slimme limmer listPicker Proto
1
Real Real World New N ewton ton Practic Practicum/powerPen: Four-Year Student Student Software Teamsfor Ne Newton 1
Desktop C ommunication ommunication Techniques M inini-Meta Data: A Anothe notherr wayto get get information to your PC
7
Newton Communications Newton Programming: Communication ionsOv sOverview
14
slimPic Picker: A Practicum/pow um/power Slimmer lilistPic tPicker Pen: FourFour-Year Proto Student Soft oftware Teamsfor Newton T by Jeremy Wyld and and Maur Maur i ce Sharp, har p, Apple Apple Computer, omputer, Inc. In c.
he Newton 2.0 OS OS providesman esmanynew prototy prototypesfor developersto lopersto use. O ne of the popular onesisprotoListPicker. I t was desi gned to to provi provide de a generalize neralized frame framework and and interfac interface for presenting enting lis li stsof ts of choices choicesto the user. Unfort Unfortuna unately, protoListPicker also tri triesto esto do everything thi ng for the the developer. veloper. The result is i sa complex API, API , and overhead in in space and time ti me that is isnot necessaryi ary i n a lot lot of cases. This hisartic arti cle presentsa slimme li mmer pic pi cker.
THE DATAIS THEPICKER (LISTPICKER) C ommunications ommunicationsTechnology Technology Newton Programming: DI LsO verview
19
Reall World Rea World New Newton
Most of the overhead from lis li stPic tPi cker is i sdue to the waythat aythat it handlesdata. ndlesdata. The purpose of lis li stPic tPi cker is i sto dis display playlis li stsof tsof data data that the the user can select items itemsfr from. om. The data itemsca temscan be elementsi tsin an array rray, soup entries entries, or a mix mi x of both. To make the developers’ li fe easier, lis li stPic tPi cker requires requiress some understanding tanding of what the data data isand how how i t is isformatted. This iswhere the pickerD pickerDef ef and nameRef structur tructures es comefrom. from. A nameRef is isa generic ri c data wrapper. I t can be used to wrap an array rrayelement element or a soup entry. All of the relevant data slots lotsare part of the top top leve level frame of the the nameRef so that that lis li stPic tPicker doesnot need to modifythe modify the actual data referenced bythe nameRef. Thepic pickerDef kerDef i sthe code object responsible for creating ti ng and managing managing nameRefs. conti nued on page 3
by Jeffr Jeffr ey C. Schli chl i mmer, Washington ashin gton State ta te Uni Uni versity versi ty
New computer science graduatesfr tesfrom om most universitiesare ti esare not ready readyto to go to work work in modern softw oftware companies nies. Ass Assoftwa oftware professionalsare ls are quic uick to point poi nt out, these studentshav tudents have onlylearned only learned howto write wri te 300line li ne programsbythems programsbythemselvesfrom elvesfrom scratch. These programs programswe were classassignmentsthat gnmentsthat focused on elegancerather than effici effi ciencyor ncyor maintaina ntainabili bility ty. The specific fi cations ationsc cameout of thin thin ai air, the code waspoorly tested, the the interfac nterface wasa simple command line, line, and there wasnever anyuser’s er’smanual. The studentsdi tudentsdid d not learn howto reuse existing existing code or howto work in teams( ms( that would be cheating) heating).. They heydid did not learn howto trad tradee-off featuresand deadli deadlineswi neswith th customers. Enough batteri ttering ng of the current univers university system. That type of education ation providesbas providesbasic knowledge of data struc tructures turesand and algorithms algori thms essential ential for engineering eeri ng softw oftware. O ur idea ideais to suppleme upplement nt the the traditi traditional, fundamental coursework ork with a fourfour-year practical curri curric culum mode modeling li ngthe activit ti vitiiesof a software oftware company. From the univers university’s ty’ s point point of view view, entering ri ng freshmen are enrolled nrolled in a four-year, softwa oftware engineeri engineering ng course nt ed Softwar oftwa r e Pr acti cum called Team-Ori ente . conti nued on page 6
2
NewtonTechnology ®
J
O
U
R
N
Volume II, Number 4
A
Editor’s Note
L
August 1996
… … … … … … … … … … … … … … … … … … … …
Published by Apple Comp Computer,Inc. uter,Inc.
Letter From theEditor by LeeDors Dor sey and and Jenni fer Dunvan Dunvan
Jennifer D unvan • M anaging Editor Coordinating ing Editor,Technical Editor,Technical Content G erryK ane • Coordinat Coordinating ng Editor, Editor, DTS and G abriel A costa-Lopez osta-Lopez • Coordinati Training rai ning Content Technical Peer Review Board J. C hristopher Bell, Bell, Bob Ebert, Ebert, D avid Fedor, Fedor, Ryan Robertson, Ro bertson, Jim Schram, Schram, M aurice Sharp, Bruce Thomps T hompson Contributors Ryan Roberts Ro bertson, Jeffrey effreyC C . Schlimmer, JeremyW eremyW yld and M aurice Sharp,
… … … … … … … … … … … … … … … … … … … …
Produced by Xplain Corporation N eilT icktin icktin • Publisher Assistant tant John Kawakami K awakami • Editorial Assis Assistant tant M att N euburg • Editorial Assis enior Art Director Judith udit h Chaplin C haplin • Senior … … … … … … … … … … … … … … … … … … … …
© 1996 1996 A pple C omputer,Inc.,1 omputer,Inc.,1 Infinite Infinite Loop,C uperti upertino,C no,C A 950 95014, 14,408408-996-1010 1010.. A ll rightsreserved. rightsreserved. Apple, Apple, the the Apple Apple log logo, APD A, AppleDes AppleDesign, ign, AppleL AppleLin ink, k, Apple AppleShare, re, Apple Apple SuperDrive perDrive,, Apple AppleTalk Talk,, Hype HyperCard, rCard, LaserWriter, erW riter,Light Light Bulb Logo,M Logo, M ac, ac, M acA pp,M pp, M acintos acintosh, h,M M acintos acintoshh Q uadra dra, MPW, N ewton wton,, N ewton wton Tool Toolkit, k it, N ewton tonScript, ript, Perf Performa orma,, Q uickT ime, Sty StyleW leW riter riter and WorldSc WorldScript are tradema trademarks rks of Appl A pple C omputer omputer,, Inc., Inc., registere isteredd in i n the U.S. and and other other countries ountries. AO C E, A ppleSc eScript, A ppleSea eSearc rch, h, C olorSy olorSync, deve develo lop, p, eWorld eWorld,, Finde inderr, O pen penD oc, oc, Powe Powerr M acintos intosh, Q uickD raw raw, SNA • ps, Star StarCore, Core, and and Soun Soundd Manag Manager are are trademarks,and trademarks,and AC O T isa is a service mark of A pple C omputer, Inc. M otorola and and M arco arco are registered istered trademarks trademarksof of M otorola, Inc. N uBus uBus is a trade tradema mark rk of Texas Texas Instrume trument ntss. Power PowerPC PC is a trademark trademark of International International Busines Business M achines hines C orporation, used under under licen licensse therefrom. therefrom. W indowsis indows is a trademark trademark of Micros M icrosoft C orporati orpo ration on and and SoftWi SoftW indowsi dows is a trademark used under under licens ense by Insignia ignia from from Micros M icrosoft Corporation. U N IX is a reg registere isteredd tradema trademark rk of U N IX System Laboratorie Laboratoriess, Inc. Inc. C ompuSe ompuServe, rve, Pocket Pocket Q uicken uicken byI byIntuit, ntuit,CC IS Retriever byBlackLabs byBlackLabs, PowerForms PowerForms bySestra, Inc.,AC Inc.,A C T ! bySymantec bySymantec, Berlitz,an Berlitz, andd all other trademarks trademarks are the property propert y of their respective owners. M ention ention of produc products in this this publica publication tion is for informational informational purposes purposes only and constit utes neither an an endorse endorsement ment nor a recommendati recommendation.A n. A ll product speci pecificationsand ns and descriptio nswere supplied by the respective vendor or supplier. A pple assumesno umes no responsibili i lity with regard to the selec selectio n, performance, performance, or use use of the produc products listed in this public publication. ation. A ll unders understanding tandingss, agreements agreements, or warrantiestake st ake place directlybetween the vendors and and prospective users. Limitation of liability: A pple makes no warrantieswi s with respec respectt to the t he contentsof ontents of productsli products listed in this publication or o r ooff the completeness or accu accuracyof racyof this publication. A pple specifically ifically disc disclaims all warranties warranties, express or implied, inclu including ding, but but not limited limited to, the implied implied warran warranties ties of merchantabi merchantability and fitness for a parti part icular ular purpos purpo se.
heysaythat aythat all good thingsmus thi ngsmust Theys eventuallyc ntually come to an end. I saythat aythat all good thingsmus thi ngsmust eventuallyevolve ntually evolve i nto better thing things. And so it it is i swith the Newt Newton on Technol echnology ogy Jour nal nal. Like everything rythi ng and everyone at Apple Apple Computer, we are in the the processof evaluating luati ng programs programs, projec proj ects, ts, and organiza nizations ti onsand and designing them to be better, more effic efficient and, above all else, signifi gnifi cant in in contri contri buting buti ng to the success of Apple’sk le’skeyt eytec echnologiesand hnologiesand partners rtners. Thisi his i sgreat newsfor Apple’ Apple’sdeveloper loper communi ommunity tyan and d the the projec proj ects, programs and public publi cations ati onsthat that feed the successof this thiscommunity nity. I t isespeciallygoo ally good d new news for New Newton developers, who are findi fi nding ng renewed commitment ommitment and excitement around the Newton platform asa technolog hnology y criti ri tic cal to Apple’sfuture Apple’s future success. I t is i saswe have alwaysknown it it should hould be. So, in the vein of mak makinggood good thing things better, the New Newton SystemsGroup temsG roup is is dedic dedicating ating more resourcesto ourcesto developer loper information, ti on, educ education, and support. upport. Along with this thiscomesnewpeople omesnewpeople with fresh ideas about improvement and expansion. While hile we continually onti nuallyrece receive feedback that the Newton Techni echni cal Journal Jour nal isa valuable piec piece of your developer support portfol portfoliio, we are looking looki ngto improv i mprove e it and grow growiit into a public bli cation ation that servesyour specific fi c needs. With th thiisgoal in i n mind, nd, it i t iswith iswith great excitement and expectation tati on for for such continue ontinued growth tha that I passthe edi editorial tori al reinsover reinsover to to a newmanaging editor, editor, who will bring bring to the public publication ation fresh idea ideas, newenthusias enthusiasm and aclosetie ti e to New Newton ton traini trai ning ng and educationa ational programs. All these thingscombi thingscombined will undoubtedly result in abetter, more effic efficient suite uite of developer education ation products, i ncluding ludi ng
NTJ an expanded NTJ . So, without without further ado, let me welcome Jennifer ennifer Dunvan D unvanasthe asthe echnology ogy ManagingEditor Editor of the theNewton Technol Journal our nal .
conti nued nu ed on page 22
August 1996
Newton Technol ology ogy Journa Journal
3 continued conti nued from fr om page page 1
slimP limPiicker: A Sli Slim mmer lilistPic tPicker Proto Thepic pickerDef kerDef and nameRef structure providesf provi desflexi lexibi bilility ty, but data that i sonlyarray only arraybas based or only onlysoup based paysthe overhead for representing enting the mixed mixed array/soup data. Everyli Everyline ne of data dis displayed in in the lis li stPic tPi cker requ requiresa resa nameRef structure which which requiresheap space. Each nameRef created requiress resseveral leve levelsof ls of function function callsto alls to the the pic pickerDef kerD ef objec object. Each accessto a nameRef requiress resseveral leve levelsof lsof functionsca ti onscalllls s. This hisistrue even for a simple accesssuch ascomparis arison. Caching the data in the the nameRef cansometimesavoi ometimesavoid d the calli alling overhead, but it i t costsheap ts heap space. The pic pickerDef/name kerDef/nameRef abstraction traction doesprovide provi de some benefits nefits. I n addi addi tion ti on to the obvi obvious ousmi mixi xing ng of arrayand soup items items, it also enab enables lis li stPic tPi cker to render the individua ndivi dual data dis displayli playli neswith littl li ttle e developer intervention. ntion. I t als also makesfi makesfililing ng easy. O n the downsi de, de, the the representati entation on isquit is quite e brittl ri ttle. e. The seeming minglys ly simple tas task of using an icon asthe firs first item item i n therendered ered line li ne of data isac is actuallyve tually very rydi diffi ffic cult to implement. A hidde hidden n cost is i sthe complexity omplexityof learning to use lis listPic tPi cker. ker. To create a simple pic picker that that dis di splaysdeveloper data requires requires unders understandi tanding ng protoLi stPi cker, the pic pickerDef kerDef object ( such as protoName protoNameRefDataDef RefDataDef)) and the nameRef wrapper. I t also requires learni learning howthese three entiti ntitiesi esintera nteract. There here isno is no clear deli deline neation ation of data manipulati ulation on and displayc playcharacteris teri stic ti cs. A good example of this thi sissingle selection, ti on, which i sa charac haracteris teri stic ti c of the pickerDef not the lis li stPic tPi cker. Another hidden hidden cost is i sthe “cursor” used bythe lis li stPic tPi cker. I n order to handle both both array- and soup-based data, the li li stPi tPicker must implement a ps pseudo-cursor that that can wrap both both ty typesof pesof data. Unfortunately, the deta detai lsof lsof the implementation tation are hidden. This hismeans that that i t isvery verydiff diffiicult to to use lis li stPic tPi cker on data that that is i srepresented ented acrossmult rossmultii ple ple soups. I f you are dis di splaying lis listsof ts of names, or if i f your data can be both array and soup based, li l istPi cker provi providesa desa nice niceproto proto for you to use. However, for most developers, all theywa theywant is i sto dis di splays play soup-based datain a lis li st. Enter slimPi li mPic cker... ker...
four goals. Most of the overhead of lis li stPic tPi cker is i sin the pic pickerDef/nameRef call chains, asis asi smost of the complexity omplexityand and brittl brittlen enes essof impleme mplementati ntation. on. The rest of thi this ssection ti on givess essome examplesof xamplesof how the goals effected the design and implemen implementation. tati on.
Y OU DATA, ME PICKER (SLIMPICKER) When we set out to to design slimPi li mPicker cker, weset four goals( goals( well five, fi ve, see below) low) : 1. Provi Provide the lis li stPic tPicker look look and and feel. 2. Minimiz nimi ze space and and time time costs. 3. Make it it eas easyfor the develope developerr to unders understand and and use. 4. Allowthe Allow the developer to customize tomize it with minima minimal effort. O rigi ri ginally nally, we had a fift fifth h goal of kee keeping pingthe same API asli aslistPic tPi cker. We hoped that a developer could jus j ust substitut ti tute e slimPi li mPicker cker for lis listPic tPi cker and everything rything would work. work. However, we dropped that requirement requirement after after finding fi nding that supporting upporting the API required verys ry si milar milar overhead to lis li stPic tPi cker. M ost of the the overhead camefrom an iterator that could work with with both soup cursor and arr array ays. O nce we dropped the requirement for for supporti pporting the API, API , we also dropped the pickerDef and nameRef structures. This hiscontributest ontri butesto o all
Newton Technol ology ogy Journa Journal
August 1996
4 Look andFeel The look and feel waseasyto do. We examined lis listPic tPi cker to to see which indivi ndividual dual elementsw ts were used in i tscon ts construc truction. ti on. We had the source code, but you could do a si milar milar thi thing ng using DV in in the i nspector. We used the same elementsi tsin slimPi li mPic cker with with onlyone only one notable exception: epti on: i nstead of using a protoStaticText for the selection election counter, we drawit. This hissavesa bit bit of time ti me and space ( though not muc much). h) . The main part of slimPicker li mPicker isi i simplem mplemented ented using a protoO protoOve vervi rview ew because it it can be used with either ei ther array array-or soup-based data. I t requi requiresa resa cursor (or ( or curs cursor-like) li ke) object for itera iterating ti ng over over the data data. The other nice feature of protoO vervi verview ewisthat it it handles handlesthe the selection ti on check boxes. The downside is isthat there there isno is no supported wayt wayto o cache the shapesus hapesused for eac each data dis displayli playline ne.. This hisresultsi ults in a time ti me pen penalty alty everyti methe displa display ylis li st of data data linesis linesi srebuilt. uilt. Unfortuna Unfortunately, this thi s occ occursan ursany y time ti me you update update the vis visual ual dis di splayli playlis st ( that is i s, scrolli rolling ng and and the RefreshPicker ca call) . Luckily, sli slimPic mPicker ker doesthi doesthis sfaster than lis li stPic tPi cker. I f slimP limPiicker were bui built into i nto ROM RO M, we could overc overcome this thisdiffi diffic culty ultyby by using undocumented features. However, wedid di d not use these features features because theyare theyare likely li kelyto to changein future New Newton OS O S devic vices.
SpaceandTim ime The main performance gainsc nscome from making the developers responsible for their their data. There isno pickerDef kerDef or nameRef structure tructure to provi provide de ageneric neric data wrapper. I nstead there is isa well defined defi ned interface between slimPi li mPic cker and the data. The developersare velopersare responsible for rendering rendering the shape that is isa line li ne of data. Theyare heyare also responsible for providi provi ding ng the curs cursor structure used byprot byprotoO oOverview verview, handling verifi cation, creating ti ng new newi tems tems( i ncluding any any edi edi ting ti ng slips li ps) and maintai aintaini ning ng a lis list of the the current selections lections. Note Note that elimi elimina nating ti ngthe pickerDef kerDef also elimi li mina natesthe testhe popup and valida li dation ti on overhe overhead. ad. I n lis li stPic tPi cker, the onlyw ly wayto determineif a given item in a column column requiresa quiresa popup popup character is i sto build build the popup. popup. That meanseach line li ne of data bui built byli bylistPic tPi cker requiresa call to Make M akePopup in in the pickerDef. I n slimPi limPicker, if i f apopup isrequired, the developer renders the popchar into to the displayli playli ne for that that data. Theyalso need to detect if a hit to that line li ne isin thepopable item item, pop the correct pic pi cker and handle the result. ult. Although Although it seemsli mslike ke wehave added more work for the the developer, it i sactually tuallyeasier to implement a simple soup-based slimPi li mPic cker than an equi equiva valent lent lis li stPic tPi cker. ker. I n essence, wespeeded up sli mPicker mPi cker and reduc reduced the the space by removing removing the data abstrac traction ti on layer. This hisdoesi doesi ncrease the work a developer must do, but it i t also removesmost of the overhead aswell as reducing the complexity omplexityof the proto.
EasytoUnder rs standandUse I n addi additition on to elimi eli mina nating ti ng the pi pickerDef/nameRef/li Ref/lis stPic tPicker interactions ti ons, we also reduced the overall number of slotsand slots and methods that a developer needsto needsto learn. Asan Asanexample, all of the lis li stPic tPi cker “suppress” settingsare etti ngsare now in one bi bi t fi field calllled ed visibleChildrenFlags. Another Another good exa example is isaddi adding ng new newitems. I n lis li stPic tPi cker you had to enable the New Newbutton button and then provide provide several methodsi methods i n your pic pickerDef. I n additi ddition, on, the the callbac allbacksfor adding the newitem are sent ent to
August 1996
the pickerDef pickerDef context, ontext, not to the the lis listPic tPi cker. I n slimPic limPicker ker,, you enable the New button tton and provide provide one method called CreateNewItem. O n the downside, sli slimPi mPic cker will wil l not do any any work such asbring asbri ngi ng up a slip li p or calling alli ng back when the slip li p is isdis dismis missed. I nstead, CreateNewItem i s called when the New button is i spushed. Everything thi ng else i sup to you. The chang hange that providesthe providesthe most flexibi flexibilility tyiisletting letti ng you render a line li neof data. You provide provi de an Abstract method method that is isgiven the data item and abounding bounding box and returnsa returns a shape that repres representsthe entsthe data item. That hat meansy nsyou can put anything thing in that shape hape that is i srequi required, including ludi ng i consand columns. I n lis listPic tPi cker, adding adding an icon wasdiffi asdi ffic cult at best. I n slimPi li mPic cker, jus j ust add it to the shapefor your data line. li ne. slimPicke limPickerr also provi providesan desan AlphaCharacter call that letsyou return the character used for sorti orting a partic parti cular item item of data. I n lis li stPic tPi cker you would have have to provide provi de at lea least one method method ( possi bly two) and set up the column descripti cription. on. I f the firs first dis di splayed column of data data wasnot the the one used for sorti ng, ng, there are additi dditiona onall methods and slotstha lots thatt must be provi provi ded. ded. Thisme his mean ansthing thingslike li ke dis displaying iconsin onsi n the firs first column column isve is very rydif diffific cult. For slimPicker li mPicker, you can dis di splay what you wi sh, and control ontrol tthe he order with with AlphaCharacter. A downside of slimPi li mPic cker is i sthat the developer is i sresponsible for tracking selection. ti on. The dev develope eloperr needsto dsto provide provi de theIsSelected and SelectItem methods methodsthat that do the right ri ght thing thing. Each change in selected state will requi require an update in in the vis visual dis displayof play of the the data lines li nes, whic hich meansredoi ansredoing ng the childr hildren en of the overview rvi ew( that is i s, a call to RefreshPicker ). Single select is i srelatively relati velyea easyto implemen i mplement, use asingle slot to repres represent the selected item item and refres refresh the picker picker. Your SelectItem method will will replac replace the value of the the slot lot and your IsSelected method will onlyreturn onlyreturn true if if the entry trypassed in in matche matchesthe one in the the slot. lot. The rest ishandled byslimPi li mPic cker. ker.
EasytoCustomize ze Even Even though though single ngle selection ti on isprovi is provided ded byli bylis stPic tPi cker (through ( through the pic pickerDef!) kerDef!) , it i t providesa nice exa example of how hows slimPicker li mPicker isea iseasyto customiz tomi ze. I t als also pointsout points out that, once again, elimi elimina nating ti ng the pic pickerDef/name kerD ef/nameRef repres representation ti on wasa good decision. Perhapsthe bigg biggest area of customiz tomi zation ation in in slimPi li mPic cker is i sthe abi abilility ty to change nge the data typesand typesand representati entation on on the fly. I n lis li stPic tPicker it i t is is not pos possible to change the pickerDef pi ckerDef or modifythe fy the cursor that t hat access the data. The onlyw ly wayto ayto do that is isto close and open the lis listPic tPi cker. ker. With slimPi li mPicker you have complete control over how the data iis s accessed ( cursor) and howit is i srepresented ented (Abstract) . All tha that is required isa call to RefreshPicker, and and everythi rything ng wi ll update. Another example isfi is fililing ng. To add fili fi li ng you jus just add the support you normallyw normally would in in an applic ppli cation. ation. That is i s, activa ti vate te the folder tab ( set the appropriate flag in visibleChildrenFlags) , then then provide provide the standard system API for fili fi ling ng (appAll, NewFilingFilter, etc.) . When the fi fi lter lter changes, you can change your cursor and call RefreshPicker.
SIXO IX OF ONE, A DOZENOF ENOFANOTHER This hissection ti on givesyou some comparis ri sonsbetwe onsbetween lis li stPi cker and slimPi li mPic cker. To be candid, andid, the tes testsare ts are stacked in favor of slimPi li mPic cker. Theyare heyare based on simple mple soup-based view viewing.
Newton Technol ology ogy Journa Journal
5 All All the the testswe ts were performed performed on the sameMessagePad. MP 120, running runningNewton OS O S 2.0 and having 79 entriesi entriesin n Names. The lis li stPic tPi ckerbased FAX pic pi cker wasopened wasopened from faxing faxi ng anote and choosing “O ther Names” from from the Namepic picker. Heap space wasmeas asmeasured before before and after the pic picker wasopened asopened using HeapShowin the accurate setti tting with no timed ti med updates. Timing ming started when hen the picker inc including ludi ng “O ther Names” wasclos asclosed and stopped topped when the FAX pic picker was opened. For the the lis li stPi tPicker based People ople picker picker, weused the PeoplePi oplePic cker-1 sample from from Newton Deve Developer Technica hni cal Support Support.. Heap usage was measured usi ng Hea HeapShow. Timing ming started tarted after fter the pen wasrelea asreleased on the icon i con in the the extrasdr trasdraw awer and ended when the people pi pic cker appeared and and w wasr asrea eadyfor dyfor input. TheslimPi li mPic cker measurementsw urementswere done on the protoSli protoSlimFaxPickerxPi cker-1 and protoSli protoSlimPeoplePi mPeoplePickercker-1 code samples. These will be on Newton Developer CD CD # 10 and on the web at
Thiss his slot isrequ i srequired. red. The iterator for the the data dis displayed bythe bythe slimPi li mPic cker. Can be either either a soup cursor or a developer-defined defined object that implements i mplementsthe the methods methodsrequir required ed bythe bythe cursor slot of protoO verview. See theNewton ProgrammersGui ersG uide de or Newton Developer Technic hnical Support Q& Q & A for moreinformation ti on on the the protoO verview cursor structure.
folderTabTitle The text to put into the protoFolderTab. rTab. Thisi his i sused to ide identi ntify fythe the slimP limPiicker that isope is open. Thedefault fault isNI sNI L (i(i.e., no title) title).. You can use SetValue to to change the value value at runti runtime. me.
reviewSelections
http://dev.info.apple.com/newton/techinfo/slimPicker.html.
Heap Used i n bytes Time to O pen i n seconds
listPicker 9300 8496 5 3
FAX picker People picker FAX picker People picker
slimPicker 3856 2740 3 2
Asy Asyou can seefrom the the table, slimPi li mPic cker is i smore effic ffi cient than lis li stPic tPi cker in in all cases. For heap heap usage this thisi snot really surpris urpri sing: ng: lis li stPi tPicker hasthe hasthe overhead of nameRefs, a more complex omplex selection election tracking tracki ng,, extra cursorsan ors and d a pic pi ckerDef. And slimPicke limPickerr also has hasminima mini mal extra extra informa information. ti on. Timeto open open isa is a bit differe different. Both lis listPic tPicker and and slimPicker li mPicker use protoO vervi verview ew, but lis li stPic tPi cker also hasto construct the soup/array iterator and the nameRefs. I n additi ddition, on, each data accesshasthe hasthe overhead of calli alling through through the picke pickerDef rDef object. slimPi li mPic cker can just iterate over the vi vis sible data and call Abstract on each entry. There is veryli verylitt ttle le housekeeping ping overhead. Unfortuna Unfortunately, slimPicke limPickerr isstil isstilll fairly fairlys slow to launc launch. A quick profile profi le of slimPicker limPicker showsthat about about 10% of the opening time ti me iss is spent pent in i n the Abstract method method of protoOve protoOvervi rview ew. The other major piec pi ece isproba isprobably soup access. This hismeansthere nsthere is isno effective ti ve wayto speed up the code. The usual idea idea of caching i snot useful si nce the slow lownessispart of the opening process. I f the slownesswasi n scrolli crolling, caching might might makess kes sense, but of coursethat would inc i ncrease the memoryfoot memoryfootpri print. nt. O ne measure that is isharder to estima ti mate is isthe sizeof the objec object. We can get a good measure of slimPi li mPic cker byei by either ther look lookiing at the the sizeof the the package on the desktop, or byus by using TrueSi zeon the Mes M essagePad. There is isno similar milar wayto find fi nd the size of lis li stPic tPi cker. ker.
If true, the slimPicker li mPicker will onlydi only dis splaythe selec elected items. I f NIL, NI L, all items i tems wi ll be dis displayed. Corres Correspondsto pondsto the “Selected Only O nly” checkbox in the the user interfac interface of theslimPi li mPic cker. Thedefault is NIL. NI L. You can use SetValue to to change the value value at runti runtime. me.
viewLineSpacing An intege integer representing enting the height of each line li ne of data in in the slimPi li mPic cker. This hisvalue must be at least the height of the checkbox. The default is is 14. visibleChildrenFlags Bit Bit flagsiden flagsi dentify ti fying whic hich child hild view viewsare to be vis visible. The valuesare:
Constant
Value
Shows/Hides
vNewButton
(1< < 0)
New New butto tton fo for ad addingnew data
(1< ( 1< (1< (1< ( 1< (1<
Scroll rolle ersfo rsfor scrollin rolling g the the list AZTabsfor alph lphabetica tical na navigation Folder ta tab for fil filin ing g Selection tion Onlyc Onlycheckbo kbox Clos Close box for for clo clos singthe the slimPic limPicker ker Cou Count of of selected items
items
vScrollers vAZTabs vFolderTab vSelectionOnly vCloseBox vCounter
< < < < < <
1) 2) 3) 4) 5) 6)
The default isall viewsvisible.
Methods slimPicker:Abstract(entry, slimPicker:Abstract(entry, bounds)
API Thiss his section ti on pres presentsthe tsthe API to slimPicker li mPicker. O f cours course, you you will have all of the the source code so you could modify modi fyany anything. thi ng. But jus j ust in i n case this this codeshowsup in i n ROM RO M someday, stic ti ck to to the API. API.
Slots
Thismethod isrequired. Returns Returnsthe the shape hape that representsthe entsthe given entryi entry in the slimPicker li mPicker. The shape must not be larger than bounds. This hisiswhere the developer rendersan rendersan indivi ndividual dual line li ne of data. The returned shape must be onethat DrawShape can use.
cursor continued conti nued on page page 22 22
Newton Technol ology ogy Journa Journal
August 1996
6 continued conti nued from fr om page page 1
Prac Practicum/powerPen: rPen: FourFour-Year Student Softw Software Tea Teamsfor msfor Newton From the student’s tudent’spoint point of view vi ew, theyhav theyhave joi joined ned asoftware company called powerP ati on of fundamental and practic ti cal works orks power Pen . The combination well because students tudentsbecome highly highlymoti motivated. vated. For example, ple, theywa they want to learn in in their their Englis Engli sh course because theyw theywant to write ri te effective ti ve marketing rketi ngmaterial ri al or a clear user’s er’ smanual. Theywant to understand compilers ompilersbec because theyw theywant to add an authori uthoring language to their thei r appli applic cation. ation. To be more speci fic fi c, Practic ti cum isroug is roughly hlydi divi vide ded d into into two stages. I n the firs fi rst tw two years, student teamss msstudyac tudy activi ti vititiest esthat hat surround urround programming in i n a software compa company ny, i.e., marketing rketi ng,, testing, ti ng, projec proj ect management, user documentation, umentati on, and technica hni cal support. upport. Freshmen and sophomoresc ophomorescan tackle tthes hese topicsbefore topi csbefore theybecome theybecomeeffective ti ve programmers. Each semester the team of studentss nts studiesa tudi esa text text or two on the topic topi c and completesa completesa related projec project for for a regional softw oftware company, sometimesunder ometimesunder nondis nondisclosure. I n return, the company provideswri provi deswritt tten en feedback on the student work. ork . ( We havefound that students tudentstak take e construc tructive ti ve criti ri tic cism from future employersmuc ersmuch more serious eriouslythan ly than from professors.) The goal of this thi sfirs fi rst stag stage is isto develop develop basi c ski lllls si n various ri ouss softw oftware development tasks. We want them to “walk i n the shoes” of othersthat others that theyw theywi ll be worki orking with when when they become softwa oftware developers developers. I n the second stage of Prac Practic ti cum, studentsare tudents are reorganized nized into into product product groupsto groupsto build build and support commerc commerci al-quality li tyappli applic cations ations. Studentsi ntsin these product groupsdes groups design, gn, program, market, and and support either either a new version of an exis xisting ti ng applic application ation or an ini inititial al vers versi on of a new new applic application. ation. This hisprocessi ncludesthe ludesthe follow following steps: a user survey, amarketi rketing requirements uirementsdocu document (oft ( often en done in conjunc conjunctition on with a freshman team) team),, a desi gn speci fic fi cation, ation, a program, testing ti ng (w (with a freshman team), m) , a user’s er’smanual ( with a sophomore team), team) , and a product releas release. The goal of thi this ssecond stage isto build build experi experien enc ce while hile developi developing ng complete, high hi gh-quality li ty appli cations ti ons. We want them to see the whole softwa oftware proce processi n action, ti on, and occasionally, make mistakesbefore mistakesbefore jobsare jobsare ridi ri ding ng on thei thei r deci sions. After a year’s r’ sexperienc ri ence, we found that studentshad ntshad trouble applying themselvesto their their indus i ndustry tryprojec proj ectsi tsin the firs fi rst tw two yearsbe rs because we did did not have a common technologybas hnology base. Someof the studentsk tudents knewonly newonly Windowsprogramming (an ( and had PCs) , some onlyM onlyMac. To remedythis edythi s, we adopted Newton asour asour common technologywith hnologywith the the help of Apple in in early rly1994. Apple Apple donated aMessagePad for each of our studentsand tudents and helped uss usset up a seniorenior-level coursein mobile mobile computing computi ng that focu focuses on Newton programming. programming. The univers universitypurcha ty purchased several Macsto host the Newton Toolk Toolkit and alloca allocated space for a development lopment lab. Students in Practic ti cum/powerPentake the mobile mobi le computing computi ng courseand gain ain common, essential ti al skills llsfor building ding modern, graphic phical user-interface applica appli cations ti ons. Newton hasturned hasturned out to be an excellent ellent choice hoicebecause of the the huge potential potenti al in in the hand-held market market and the ease of developing developi ng NewtonScript ri pt applic appli cations ations. I t hasalso helped that the the Newton developer community ommunityiissmall andcooperative. rati ve. O ur freshmen and sophomore teams have been able to do Newton marketing, marketing, testing, ti ng, and documentation tati on projec proj ectsfor tsfor Newton companies ompanies. Theyhave heyhavealso volunteered olunteered at Newton
August 1996
conferencesand had summer interns internships hipsw with New Newton companies companies. Our first fi rst team started tarted in in 1992 with 10fres freshmen. A second team followed followed the next year, and a third third in i n 1995. Currently Currently17 17studentsare tudents are involved in in Practic ti cum/powerPen: 5 seniors rs, 6 juni juniors ors, and 6 freshmen. Like Like manycompanies nies, we experienc ri ence regular turnover, turnover, los losing about 50% of the the new studentsi tudents in the firs fi rst year and another 25% of the the overall group upon graduati graduation. on. The studentsare tudentsare currently urrently supporti ng si x Newton applic appli cations ationsan and d developi developing ng a seventh. Each appli applic cation ation is is available in in at least one of six forei foreign gn languages. Theyhave heyhaveover 500 regis registered usersi ers in 25countri ountries. Our most signific fi cant marketing marketing channel is i sthe Interne Internet, and in in specific fic the Worldorld-Wide Web. We host a series eri esof of pageswi pageswith th the the most current current version of each applic application. ation. We dis distribute tri bute applic ppli cationsf ationsfor or free free because wewant to haveasmanyus asmanyusersas ersaspos possible. These pageslis li st known known defects, feature reque requests, source code, functional functional specs, and other development informati information. on. Wemake our development infor informati mation on and source freelyava freely available lable because we want to help others othersunders understand how we are doing doing development – including ludi ng other studentsnot tudentsnot at our univers universi ty. For applic appli cations ationsw wi th a signific fi cant content market, rket, the the pages also lis li st content weandothershav othershave developed (e.g. (e.g.,, plug-in dic dictiona ti onaries ri es for hangManor decksof cardsfor rdsfor flas flashCard). hCard) . Where possible, the pages lis li st relatedapplic li cationscomm ationscommerciallyav allyavailablefrom fromNew Newton companies nies. Practic ti cum/pow um/powerPen erPen also also providesan provi desan excellent excellent opportuni opportunity tyto to study and refi refine the softwa oftware development pr proces ocess. Two areasin areasi n which hich we hope to contribute ontri bute are localiza li zation ti on and and des design methods methods. I n localiza locali zation, ti on, wehavedevis devised techniquesf hniquesfor or managing the userinterface string tri ngs sof a New Newton applic appli cation ation so it i t can be be easi lyc ly converted rted from from one human language to another. Our latest effortsma efforts make it it possible for a non-programmer (but ( but language expert) to specify stri tri ngs byfi byfilllliing out out a Web form, subm submi tting tti ng it, and receiving eivi ng a compiled ompiled Newton applic ppli cation ation correctlyloca tly localiz li zed. This hisrepresents entsa a dramatic ti c savingsc gscompared to Apple’ Apple’s smarketing marketi ng estimatesof ti matesof US$ US$10-25K to convert a Newton applic appli cation ation into into each new language. We are invi invititing ng our interna internationa ti onal usersto ersto test this thi ssystem. I t will will leveragetheir experti se and provide provi de addi addititiona onall internationa ti onall accessto Newton applic appli cations ations. I n design methodswe methodswehaveadapted a functional ti onal speci fica fi cation ti on technique nique for event-driven dri ven programming in in general and Newton programming programming in i n speci fic fi c. Based on a table structure, thi this sspecific fi cation ation type i seasyto code agai nst and provides provi desa a ready-made test plan. plan. O ur i niti nitial al attempts attemptsw with this thi smethodologyare methodologyare also availab ailable on our Web pages( under flashCard). hCard) . Asan Asan educationa ational proj projec ect, Practic ti cum/powerPen relieson reli eson indus i ndustry try support in i n three major ways. First, First, New Newton companies niesc can help by making maki ng a tax-deductible ti ble donation donation to purchase newhardware. With Apple’ Apple’s shelp we have recently ntlyupgraded most of the the studentsto tudents to New Newton 2.0 OS OS but we will fall short when newfres ewfreshmenjoin oin Practic ti cum/powerPen next fall. Second, companiescan hire our studentsfor tudentsfor inter internships hipsor or upon graduation. ti on. Besidesthe desthe benefit fi t of personal experienc experience and growth, returning returning studentsshare their expertis erti se. Third, hird, companiesca niescan propose and evaluate marketing marketi ng, testing ti ng, or user documentation ti on NTJ
Newton Technol ology ogy Journa Journal
7 Des esktop ktop Communicati C ommunication on Tech Techniques niques
Mini-MetaData: Anot Another wayto get informationto your PC by Ryan yan Rober obertson, Appl Apple Computer, omputer, Inc. Inc.
hisartic article describe ri bes sthe development of a pai pair of applic appli cationst ationstha hatt This export data from from a Newton devic device to a desktop computer. There are two appli applic cations ations: one that that runson runson a Newton de devi vic ce and one that runs runs on a desktop computer. Theyare desi gned to allow allow a developer to register register data defini definititions onss so that soup soup informati i nformation on can be be transferred between the New Newton ton device deviceand the desktop top computer. ( M inini-MetaD etaData isa is a Newton DT DTS sample that should be availab ailable by presstime. ti me. You can find find the M inini-MetaData source code on AppleLink AppleLi nk and the Newton WWWSite, Site, http://dev.info.apple.com/newton/newtondev.html. The next New Newton Develope eveloper CD will also contain this thi ssample.)
For ins i nstance, you will be able to export your Name Namesfile fi le to a tabdelimi delimited ted format that that could be rea read into i nto a database or a spreadsheet. The desktop applic application ation wi ll take the inc incoming omingdata and dump it into a text file. fi le. I t should also be designed gned so that it it will will eas easi lyport ly port to to other platforms platforms. This hismeansthat nsthat the user interfac terface code will be separated from the implementation ntation code. This hisimplementation ntation only dealsw ls with text text data, so the FDI Lsare Lsare not needed. needed. I ’ ll begi n this thisdis di scussion bydescribi ri bing ng the protocol used for trans transferri ferring data between the New Newton device deviceand the desktop computer. After that, I ’ll go into more detail of some of of the major design deci sionsfor onsfor both both the Newton applic appli cation ation and the desktop appli applic cation.
Y OU ARE THE CONNECTION With all the additi additionsto onsto the Newton 2.0 OS, it mayseem like li ke exporti ng data data to your desktop computer computer hasbeen hasbeen overlook overlooked: ed: i t hasnot: hasnot: the i ntenti ntention on i sfor appli applic cation ation developerst developersto o incorporate incorporate the Desktop I nteg ntegration Libra Librari ries( es( DI Ls) i nto thei thei r existi xisting ng applications ti ons. This approach wi ll allow a user to direc di rectl tly y connec onnect to to their their New Newton devic device using their favori favorite te des desktop appli applic cation. Before the DI Lsbe Lsbec came avai lable, the user wasrequired required to to use a second applic appli cation ati on calllled ed Newton Connec Connection ti on Ki Ki t to to transfer their Newton devi devi ce’sda e’s data ta to a more generi eneric c format format that could then be used bydes bydesktop applic appli cations ations. The Desktop I ntegration ration Libraries Librariesare are a set of platformplatform-i ndependent C librari li brariesand esand API sthat can be easi lyi ly i ncorporated into an existi existing ng appli applic cation. ation. Theyprovide heyprovi de all the necessarys arysupport to connect to to your your Newton Newton and to trans transfer data data between aNewton device devi ceand a desktop top computer. There arecurrentlytwo tly two typesof DI Ls: the thecommunication tion DI Ls( CDI CDI Ls) , and theframe DILs( DI Ls( FDILs FDI Ls) . Thecommunication tion DILsare DI Lsare usedto open a connection ti on with the Newton and to read and write ri te bytesof tesof data. The frame DI DI Lslet Lslet you read and write write other other Newton data types, such asframes asframes and arr arrays. The two largest advanta advantage ges to using the DI DI Lsare: Lsare: 1) The DI Lsab Lsabstract all unde underly rlyiing transport detail details sinto an easyto use API. API . 2) Your code will run on on MacO S™ and Window ndows™ with veryli veryli ttle modification. The implementation implementation of the Newton applic application ation des describe ri bed in i n this this artic arti cle is i sintended to be asgeneri neric c and extens extensible aspossible and allowsa developer to to register register information nformation about about how to forma formatt data before before it it is i ssent ent to the the desktop compute computer. r. Bydoi By doing ng this thi s, the Newton applica appli cation ti on can export data from manydi fferent soupsus psusing many differe different nt formats( ts ( this thisformat format will be explained below in further further detail) tail) .
Newton Technol ology ogy Journa Journal
Y , DO TALK BACK AKITY Y AK The protocol used for sending ding and receiving eivi ng data data is isfairly fairlys simple. Firs First I wi ll dis discussthe Newton Newton si side of the the protocol. At varioust vari oustiimes mesduring during the connection, ti on, the Newton will will send oneof three three things thi ngs: a command code, a stri tring length, or or a stri tring. The command codeshave been purpos purposefully efully selected aslarg aslarge numberss numbersso asto avoid oi d conflic onfli ct with with the string tri ng leng length. Table 1 summ ummari ariz zesthe esthe command codessent from from the New Newton duri during the protocol. Table abl e 1. Command ommand CodesUsed by the Newton Newton Protocol Prot ocol
Commandcode name Commandcodevalue
Description ription
kNewtonC onCancelle lled
Sent when the the user
0x0FFF FFF
pressesthe esthe “Cancel” button on the Newton.
kNewtonFinished
0x0FFE
Sent when all of the
data hasbeen trans transferred to to the desktop applic appli cation. ati on.
Command codesare odesare onlys only sent when the user is i scanceling eli ng the operation ti on or the export export hascompleted. hascompleted. The rest of the the protocol protocol on the Newton Newton side consi stsof ts of sending stri trings ngs to the the desktop computer. I n our protocol, the length of the stri ng i ssent ent firs fi rst to let let the desktop appli applic cation ation know howlarge large the rec receiving eivi ng buffer needsto dsto be. Byus By using this thi stechnique, we guarantee uarantee that there wi ll be no ambigui ambiguity tyast asto o whether the rec received eived data is isa command code or a stri tring length. Here isthe C func function ti on that readsdata readsdata from the CDI L pipe pipe on the desktop. top. I t returns returnsa a value indi indic cating ati ng whether the read wasa asa success, a failure, a cancel, or whether the Newton iis sreadyto readyto dis disconnect.
long ReadBuffer( LPSTR bufferPtr, long* length ) { Bool Boolea eann eom eom; Comm CommEr Errr anE anErr; rr; August 1996
8 lo n g
c om m an d ;
local numEntries := ep.fCursor:CountEntries(); ep.fCursor:CountEntries(); ep:Parent().fStatusView:GoGoGadgetGauge( numEntries, kSendingDataString );
// read thefirst first four bytes, this this will il l either either beacommandcodeor astri astring nglength length
*length = 4; anErr = CDPipeRead( gOurPipe, &command, length, &eom, 0, 0, kPipeTimeout, 0, 0 ); if (anErr) { return kReadError; }
ep:DoEvent( 'OutputData, nil ); end else if data = kAckCommand then
ep:DoEvent( 'OutputData, nil ); else begin // Therewasanerror, sodisconne disconnect GetRoot():Notify( kNotifyAlert, kAppName, kProtocolErrorString ); ep:DoEvent( 'Cancel, nil ); ep:DoEvent( 'Disconnect, nil ); end;
// interpret interpretthecommandcodeandactonit. it. Ifthedatawa datawasnotacom a commandcode, // then it is astring a stringleng length, so read in the string
if (command == kNewtonCancelled) return kNewtonCancelled; else if (command == kNewtonFinished) return kNewtonFinished; else if (command) { *length = command;
nil; end,
// resize resize thebuffer to the size of the stringplus string plus one for the null character.
if ( realloc( bufferPtr, command+1 ) ) { anErr = CDPipeRead( gOurPipe, bufferPtr, length, &eom, 0, 0, kPipeTimeout, 0, 0 ); if (anErr) return kReadError;
// ack command was received, //output the next line line
}
CompletionScript: func( ep, options, result ) begin ep:DoEvent( 'Disconnect, nil ); end,
} // ReadBuffe uffer
I f an unknown command code is isreceived eived on the Newton devic device, the Newton applica appli cation ti on si gnalsa ls a cancel and dis di sconnects. An unknown unknown command code isli is likely kelyto to be caused bya communic nicationserror. ationserror. I f the protocol protocol were more robust, the Newton could try tryto to res resync wi th the the desktop machine hine and start sending ending data agai n
The desktop PC PC side of the the protocol consi stsof ts of four four command codeswhich are summarize ummarized in in Table 2.
PROTOCOLOF COLOFTH THE W ILD O nce the connection ction hasbee hasbeen establi shed, kHelloCommand issent
}
}
Null terminate thestring string bufferPtr[(*length)] = (char)0;// Null return kReadSuccess;
return kReadError;
Table abl e 2. Comman ommand d CodesUsed by the Des Desktop top PCProt Protocol
Command codename
Command codevalue
Descrip iptio ion
kHelloCommand
0x0FFD
Sent when the the connection ti on
has been been establis tablished. This histellsthe tells the Newton Newton applic application ation to start the the protocol.
kGoCommand
0x0FFC
kAckCommand
0x0FFB
Sent when the desktop top applic ppli cation is i sreadyto dyto start recei ving ving the export data. Sent after the desktop has successfully fullyrecei received ved a li ne of
data.
kErrorCommand
0x0FF9
Sent if i f there isan is anerror
during the connecti on. Because most of the data trans transfer consi stsof ts of the the Newton device device sending ending data to the the desktop machine, the Newton applica appli cation ti on uses onlyone onlyone input speci fic fi cation ation for the entire ntire protocol. protocol.
{ f or m :
from the desktop PC to to the Newton device. Seeing eing the kHelloCommand, the Newton applic appli cation ation will send the name of the appli applic cation ation for verifi ri fic cation ation purposes. This hisname ischec hecked on the desktop PC to to make sure the connection ti on is iswith the Mi Mi nini-MetaD etaData applic application ation and and not not wi th the Newton’s Newton’sbuil builtt-ii n Connection ti on applic application ation or with the Toolkit App. The next step is isfor the the Newton applic appli cation ation to send the name of the file file that that data will be exported exported to. O nce thedesktop PC receivest receivesthi his s name, the standard save dialog dialog will be opened with that that file fi le name asthe asthe default. When the user fini fi nis shesselecting lecting the target file, fi le, the desktop appli applic cation ation wi ll send end kGoCommand indi ndi cating ti ng i t is i sreadyto begi n recei ving ving data. At this thispoi point, nt, the Newton appli applic cation beginssen nssendi ding ng data data in in the follow following pairs pairs: a string tri ng length followe followed bythe bythe string tri ng.. When the desktop successfully fullyreceivesan eivesand writes ri testhi this sstri ng to the file, file, it will will send an kAckCommand to the Newton to si si gnal tha that i t is i sreadyfor dyfor more data. Finally, the Newton appli cation ti on sendskNewtonFinished when it it has hasfini fi nis shed transferring ferri ng data. I t then then dis disconnects. I f the the desktop encountered ountered an an error during duri ng theprotocol, i t will will send end kErrorCommand to the New Newton and dis disconnect. Here isan is an example xample of the protoco protocoll in action: ti on:
' nu m be r ,
InputScript: func( ep, data, termination, options ) begin if data = kHelloCommand then begin // Hell Hello command was received, // start theprotocol. protocol.
ep:DoEvent( 'StartProtocol, nil ); end else if data = kGoCommand then begin
// go command was received. // Initialize and output the first line
ep._parent.fStatusView:StopBarber(); August 1996
Newton Technol ology ogy Journa Journal
9 Fi gur e 2. The The Mini -Me -MetaData taDat a Us User I nte nt er face fa ce
The NTK NT K Projec Proj ect for the the Newton applic application ation consistsof tsof 10files fi les, 4 of whic hich are layout files fi les.
Fi gure gur e 1. Newton-Desktop kt op Communi ommun i cati cati on Protocol Protocol Fi gure 3. 3. The NTK NTK Pr oject Wi ndow for the Mini Min i -MetaData -MetaData Applicati Appli cati on
Now that you understand the protocol, letsdi lets dive ve into into the codeon the New Newton.
NEWTON SIDE UP
The important files fi lesto to look at are: Endpoint.t, Endpoint. t, StatusView.t, ProtocolFSM, and Ma Main.t. The hi erarchyof the Newton appli applic cation ation is isi llllus ustrated in in Figure 4.
To extend the mini mini-meta data applic appli cation, ation, you will add a format frameto a global regi regis stry try. Theformat frame includess ludessuch informati formation on aswhich soup to send data from, from, what the the querys uery speci fica fi cation ti on is is, and how to create reate a formatted string tri ng from a soup entry. This hisregi stryw try will be dis di scussed in in more detail detai l below below. The Newton applic application handles handlesthe the format format informati i nformation on and providesa provi desa simple interfac interface for selecting ti ng whic hich format to use. To keep the implemen implementation tati on asgeneric ri c aspossible, a form of meta data was created. Using Using this thi smeta data, a developer can have a maximum maximum amount of control over the format of outgoi outgoing ng informati nformation on without expli explic citly tly having having to know k now much infor informati mation on about the Newton storag torage or communica communicati onss ons systems. Here is isa screen shot of what the Newton interfac interface looks lookslike. li ke.
Fi gure ur e 4. Hie Hi er archy ar chy of the Mini MetaData Appli Appli cati on
GOGOGADGETSTATUSVIEW I t isvery i sveryiimportant to give give the user feedback during during the connec onnection. ti on. Newton 2.0 O S providesa terri terrifific cproto, protoStatusTemplate , for conveying statusi tatus informati nformation on to a user. StatusView View.t contains ontainsthe the template for the statusvi tatusview ewthat is isused during duri ng the connection. ti on. O ne of the beauti autiesof esof usingprotoStatusView isthat it hasmultiple personaliti onalities es. Among other things thi ngs, a vi ewbased on protoStatus protoStatusView View can be asingle line line of text, a barber pole, pole, or a gauge. During uri ng our connection ti on wewill use all three three of thes these. The barber pole pole element is i sused during ri ng the connection ti on phase. The barber pole pole waschosen because the time ti me it it takes takesto to connect is i snot a known value, and a simple liline of text text doesn’t necessarily arilygi give the the user the impression that a lengthyopera thyoperation ti on istaki is taking ng place. During uring the connection ti on phase, the the user mayforge mayforget to to si gnal a “w “ wait ait for for connection” ti on”
Newton Technol ology ogy Journa Journal
August 1996
10 event on the desktop whic which leavesthe Newton waiting ti ng until unti l the the connect reque request ti timesout. mesout. The gauge element is i sused while hile data is isbeing being sent. Because we knowthe number of items itemsthat that will be sent, a determini termi nis stic ti cinterface element is i sa more appropriate ppropri ate choic hoice here. The simple statusvi tatus view ewi sused for dis di sconnecting. ti ng. A barber pole was not used because the dis disconnect operati on is usually ually veryfas veryfast. The dis di sconnect operation operati on will will also complete successfully fullyrega regardles rdlessof whether the desktop computer is isdis di sconnecting. cting. The statusvi tatusview ewtemplate hasthree hasthreemain methodsof thodsof interes interest. They are: GoGoGadgetBarberPole, GoGoGadgetGauge, and GoGoGadgetSimpleStatus. Each of these methodsw ethodswill set up the statustemplate tatus template with the correc orrect informati i nformation on and open it it if i f necessary. There here are also lso some additi dditiona onal methods methodsfor for updating ti ng the text, text, the gauge, and the barber pol pole e once the view vi ew hasalready asalreadybee been opened.
BACKTO CKTOTH THE BASICS T he mi mi nini-meta data applica appli cation ti on usesprotoBasicEndpoint asthe prototy protot ype for the connec onnection ti on endpoint. ndpoint. Usi Usi ng protoEndpoint i s not recommended, and is actually tually impossi ble to use in a “2.0 “2.0 only” appli applic cation. ation. T his his new new endpoi endpoint nt proto i s much more reliab reli able le and and functi functional onal than protoEndpoint . Endpoint. Endpoint.tt conta containsthe templa template te for our endpoint. endpoint. I n additi on to the standard endpoint ndpoint methods, there is isone other method of iinteres nterest: OutputLine. OutputLine callsa alls a helper function function to format format a soup entryi entry into an output stri ng ( this thi smethod wi ll be dis discussed in more detail detail later). later) . I t then outputs outputsthat that string tri ng and upda updatest testhe he statusview tatusvi ew. Here isthe is the defi definiti nition on of Outpu OutputLine tLine:
func() begin local entry := fCursor:Entry(); // if if there is anentry, thenoutput the next line line of data. Otherwise, // outputkNewtonFinishe kNewtonFinishedanddisconnect.
if entry then begin fData := :CreateStringFromEntry( entry, fMetaDataFrame ); fCursor:Next(); // Output the length of thedatathe tathen output thedata. If either // output fail failss then post a‘cance a‘cancel event.
:Output( StrLen(fData), nil, {asy {asynnc: tru true, f or m : ' n um b er , CompletionScript: func( ep, ep, options, options, result) result) begin if NOT result then ep:Output( ep.fData, nil, {async: true, form: 'string, Completion CompletionScrip Script: t: func( ep, options, result) begin if NOT result then begin ep._parent.fStatusView:UpdateGauge(); ep.fData := ""; end else ep:DoEvent( 'Cancel, nil ); end, } ); else ep:DoEvent( 'Cancel, nil ); end, } ); end else begin // Output Output kNewtonFini kNewtonFinished shed command and disconnect disconnect when theOutput completes.
:Output( kNewtonFinished, nil, {async: true, form: 'number, CompletionScript: func( ep, options, result )
August 1996
end;
begin ep._parent.fStatusView:FinishGauge(); ep:DoEvent( 'Disconnect, nil ); end; } ); );
end
HOLY FINITE STATE MACHIN INESBATMAN! Using a determini determinis stic ti c fini fi nitete-state machine hine for communications ationsw was covered in depth depth in in theApril April 1996 issueof NTJ( NT J( volume IIII , issue2) . This applic appli cation ation leveragesoff esoff of the the sample code produced for that arti article. The file file of intere i nterest i sProtocolFSM whic hich has hasthe layout of all the states and events eventsnee needed for our applic appli cation. ation. There here are threeeven eventsw ts worth pointi pointing ng out. The firs fi rst event is isthe ‘Create’ Create’ event in in the Genes enesisstate. This hiseven eventt setsup the endpoi endpoint, nt, the the statusvi tatus view ew, and regi stersa power off func function. ti on. Anyinit Anyi nitiializ li zations ti ons needed for the connection ti on should be done here. Next we have the ‘Connec ‘Connect Success’ event in i n the the ‘Connec ‘Connect’ state. This hisevent setsthe etsthe input input specific fi cation ation for our protocol, and and als also o has has the defini definitition on of our inpu input spe spec cific fication ti on in in thefInputSpecification instance variable. variable. This hisevent is isperformed performed once there hasbeen a successful connecti on with with the the desktop top computer. Finalllly y, we have the ‘O utputData utputData’ even eventt i n the ‘Conne ‘ Connec cted’ state. Thisevent simplycallsthe endpoint’sOutputLine method described cribed above. ove. So whyi hyi sthis thi sevent event of interest to us? Another Another possi ble implementation ntation for outputting outputti ng data would would have been to call the the OutputLine method method direc directly tlyfrom the input nput specific fi cation. ation. Doing oing this this would ould remove an event from from the state machine, and make the the code more centrali entraliz zed. However, byplac byplacing the OutputLine method in i n an event, canceling elingfunctiona ti onality li tyiisprovided provided for free. When hen the fini finite te state machine hine receivesa eivesa cancel event, all posted communications ationsreques requests wi ll be canceled, eled, i ncluding luding the input speci fic fi cation. ation. Byus Byusing the fini finite te state machine hine sample, the code is ismore understandable, and more modular. This histype of modularity lari typrovi providesan desan almost complete separation eparation between the the interf interfac ace code and the the communicationscode. ationscode. Having this thi sseparation rati on will make future revis visions easier. All All communic ommunications ationsc code on the Newton si de i sasynchronous. This his deci sion wasmade because synchronousc hronous commsare ommsare generally rallyevil. evil. When you post a synchronous commsreques commsrequest on the the Newton, an addi addititiona onal task is i screated reated – tha that’t’s sNewton ling lingo o for a new new thread. This his addsneedlessoverhead to to the the system, and can potentially potenti ally reveal some interesting ti ng problems. For ins i nstance, you may may be outputting outputti ng lots lotsof data i n aloop loop using synchronous hronousoutput output reque requests. Each time ti me through through the loop a newtask will be created, which which isa rather expensive operation. rati on. The newtask will take up system memory, and will will not release control ontrol unti untill i t retu returnst rnsto o the main even event loop loop (w ( which doesnot happe happen unti untill you are fini finis shed with your output loop) loop) . Asa As a consequence, the the Newton will will eventuallyrun ntually run out of system memoryand memory and come crashing hing to itsk ts knees nees. Another drawbac back of usi ng synchronouscommsis hronouscommsi sthat the user losescon losescontrol trol of their their Newton while while the commsrequest iswaiti aiting to complete.
GRAND CENTRAL O ur main main layout file file ismain.t. n.t. This hisfile file containsthe nsthe code for selecting ti nga format, and creating reati ng an output stri ng from a soup entry.
Newton Technol ology ogy Journa Journal
11 The importan mportantt function ti on to look at is i sCreateStringFromEntry. This hismethod method isc is called repeate repeatedly dlyduri during ng the protocol. I t is ispassed a soup entry entryand will will return a stri ng repres representati entation on of tha thatt entry entry by using the format frame. I t itera i teratesover tesover the field arrayin theformat frame, buildi building ng a string tri ng from the the elementsof that array.
func( entry, metaFrame ) begin local line, lineItem, result; line := foreach foreach lineItem lineItem in metaFrame metaFrame.fiel .fields ds collect collect begin // build buil d the itemstringfromthe itemstring fromthe metadataframe.
// if if lineI lineItemi temiss apath expression, the resolveit and return the value
if ClassOf( lineItem ) = 'pathExpr OR ClassOf( lineItem ) = 'symbol then begin if entry.(lineItem) then entry.(lineItem) & metaFrame.itemSeparator; metaFrame.itemSeparator; else metaFrame.emptySpace & metaFrame.itemSeparator; metaFrame.itemSeparator; end else if IsFunction(lineItem.format) AND HasSlot( lineItem, 'pathExpr ) then begin // if we have aform aformat function then then pass in the the value found using // the pathExpr slot slot to the function.
result := call lineItem.format with ( entry.(lineItem.pathExpr) entry.(lineItem.pathExpr) ); if result then result & metaFrame.itemSeparator; metaFrame.itemSeparator; else metaFrame.emptySpace & metaFrame.itemSeparator; metaFrame.itemSeparator; end else if lineItem.format = 'quotedString AND HasSlot( lineItem, 'pathExpr ) then begin // if i f form format is ‘quotedString, tthen hen quotethe value found using // the pathExpr slot.
result := result; if result then $" & result & $" & metaFrame.itemSeparator; else metaFrame.emptySpace & metaFrame.itemSeparator; metaFrame.itemSeparator; end else if lineItem.format = 'quoteIfExists AND HasSlot( lineItem, 'pathExpr ) AND entry.(lineItem.pathExpr) entry.(lineItem.pathExpr) then begin
Protocol. Protocol.c c because theyc they contain ontain file file accessrouti routinesthat nesthat are speci fic fi c to one platform. platform. WhyInitializePipe isnot in Protocol.c isnot as obvious obvious: the underlying underlying transport opti options onsare are speci fied fi ed slightly li ghtly differentl differently ydepending ding on whether you are running running on Mac MacO S or on Windo Windows ws.
OSEVENT HANDLIN ING Theinterface code is in the I nterface.c file file if if you are using MacO S and is intheI NTERF NTERFAC.C AC. C file fi le if if you are using Windows. These files filesc contain ontain all the standard tandard event handli handli ng code and and should probab probaby look pretty pretty familia mili ar. I n additi ddition on to the above menti mentione oned d func functions ti ons ( CreateNOpenFile, WriteToFile, UpdateNCloseFile, and InitializePipe) , the Mac MacO S code containsone ontains one other function ti on of interest: SetupPortMenu. This hisfunction ti on correctlyc tly createsa reatesa lis li st of the portsav ports avail ailab able on the given mac machine hine.. For ins i nstance, most Mac M acintosh’s h’s have a printer pri nter and amodem port. However, if i f the user is isrunni ng on a Duo there is isoneprinter/mod printer/modem port. port.
PROTOCOL.C This hisfile fi le containsall tainsall the code necessaryto aryto handle the protocol protocol and the vari various ouss statesof tatesof the connection. ti on. I t also contains ontainsthe the code to handle handle error reporting reporti ng to the user. M ost of the functionsand ti onsand procedures eduresiin this thi sfile fi le are easyto understand. However, there there are a couple of areas that warrant further further dis di scussi on. The procedure that handles handlesmos most of the protocol is i sDoProtocol(), and is isdefined as asfollow follows:
// if if format is is ‘quoteIfExists ‘quoteIfExists thenquote if the value found using // the pathExpr slot exists
$" & entry.(lineItem.pathExpr) & $" & metaFrame.itemSeparator; end else metaFrame.emptySpace metaFrame.emptySpace & metaFrame.itemSeparator; metaFrame.itemSeparator; end; // retu return astring a stringwith with the proper line line separator
return Stringer( line ) & metaFrame.lineSeparator; end
DON’T FORGET THEDESKTOP Asdi As dis scussed earli earlier er, the desktop applic appli cation ation usesthe esthe DI Lsto Lsto trans transfer data between the Newton devic device and the output file. fi le. The requiremen uirements of this thi sappli applic cation ation were simple enough that that onlythe onlythe CDI CDI Lsw Lswere needed. To help in in the effort ffort to to create crossplatform platform code, the projec proj ect is is broken broken into two C files files. There isa is a file file for the main OS OS event handling ndling code and afile fi le for the the protocol code. Theyare Interfac Interface.c and Protoc Protocol.c ol. c. The event code and the dialog code isnot is not cros crossplatform because much of that code is specific fi c to either either platform. platform. The protocol protocol code is iscross rossplatform platform and consi stsof ts of the the code to open the connection ti on with the Newton, handle the protocol, protocol, and close the connec connection. ti on. There here are four functionsi ti onsin n Interfac I nterface.c that that are not not used for handli handling ng O S events. Theyare CreateNOpenFile, WriteToFile, UpdateNCloseFile, and InitializePipe. Thefirs first three are not in in
Newton Technol ology ogy Journa Journal
August 1996
12 void DoProtocol() { StandardFi StandardFileRep leReply ly fileReply fileReply;; s ho r t fi l eR e f = 0; l on g le n gt h ; c ha r *b u ff e r Pt r = NU L L ; l on g fB u ff e r Re s ul t ; l on g an E rr ; // prea prealloca ll ocate abuffer abuffer that we think will will be largeenough for most data. // This This buffer will il l be resized as datais tais received.
if ( !(bufferPtr = malloc( 256 )) ) { ConductErrorDialog( kNoMemoryString ); return; }
// Send kHell kHelloCommand to the Newton
fBufferResult = WriteCommand( kHelloCommand ); if (fBufferResult == kWriteError) Fail(FailWrite); // Make sure the we have connected to the Mini-MetaDataapp taapp on the Newton
fBufferResult = ReadBuffer( bufferPtr, &length ); switch (fBufferResult) { case kReadSuccess: if ( strcmp( kHeloResponse, bufferPtr ) ) { Fail(FailWrongApp); } break; case kNewtonCancelled: Fail(NewtonCancelled); case kReadError: Fail(FailRead); }
// Readthefilena filenametosavetheincom incomingdatato ing datato
fBufferResult = ReadBuffer( bufferPtr, &length ); switch (fBufferResult) { case kNewtonCancelled: Fail(NewtonCancelled) case kReadError: Fail(FailRead); }
// createandopen thefile, file, then start dumpingdatai ping datainto nto it.
anErr = CreateNOpenFile( bufferPtr, &fileReply, &fileRef ); if ( anErr == noErr ) { fBufferResult = WriteCommand( kGoCommand ); if (fBufferResult == kWriteError) { UpdateNCloseFile( fileRef, &fileReply ); Fail(FailWrite); } // Loop until until there there is either an error, rror, or until unti l the the Newton sends acancel // command or afi afini nished shed command
while( true ) { CDIdle( gOurPipe ); fBufferResult = ReadBuffer( bufferPtr, &length ); switch (fBufferResult) { case kReadSuccess: anErr = WriteToFile( fileRef, &length, bufferPtr ); // if if there wasan error writing writingto to the file, file, close the file, file, display // an error and return.
if (anErr) { Fail(FailWriteFile); }
// send an kAckCommand, if if there was an error then handle it. it.
fBufferResult = WriteCommand( kAckCommand ); if (fBufferResult == kWriteError) { UpdateNCloseFile( fileRef, &fileReply ); Fail(FailWrite); } break; case kNewtonCancelled: UpdateNCloseFile( fileRef, &fileReply ); Fail(NewtonCancelled); case kNewtonFinished: ConductErrorDialog( kDownloadWasSuccessful ); UpdateNCloseFile( fileRef, &fileReply ); free( bufferPtr );
August 1996
}
}
}
bufferPtr = NULL; return; case kReadError: UpdateNCloseFile( fileRef, &fileReply ); Fail(FailRead);
WriteCommand( kErrorCommand ); free( bufferPtr ); bufferPtr = NULL; return; // Thes These are the Goto locations that are jumped to usingthe using the Fail() il () macro.
FailWrite: WriteCommand( kErrorCommand ); ConductErrorDialog( ConductErrorDialog( kBufferWriteErrorString kBufferWriteErrorString ); free( bufferPtr ); bufferPtr = NULL; return; FailRead: WriteCommand( kErrorCommand ); ConductErrorDialog( ConductErrorDialog( kBufferReadErrorString kBufferReadErrorString ); free( bufferPtr ); bufferPtr = NULL; return;
NewtonCancelled: ConductErrorDialog( ConductErrorDialog( kNewtonCancelledString kNewtonCancelledString ); free( bufferPtr ); bufferPtr = NULL; return; FailWriteFile: ConductErrorDialog( kFileWriteErrorString ); WriteCommand( kErrorCommand ); UpdateNCloseFile( fileRef, &fileReply ); free( bufferPtr ); bufferPtr = NULL; return; FailWrongApp: ConductErrorDialog( kWrongAppString ); free( bufferPtr ); bufferPtr = NULL; return; } // HandleProtoc rotocol
ReadBuffer and WriteCommand are helper func functions ti onsus used to read to and write rite from theCDI CDI L pipe pipe.. Thereturn value is ischecked to make sure there were no errors rrorsiin the protocol. I f an error occurred, i t is isassumed that there is isa problem with the connection, ti on, and the connection ti on is aborted. orted. I n an effort to retain retain some amount of synchronici nchroni city, ty, kErrorCommand issent after an error has occurred. There is a good chance that the thekErrorCommand maynot be sent because the origi ori ginal nal error wasa communica ommunications ti onserro error. r. Amore robust protocol protocol would examine mine the error value and take appropriate appropri ate action ti on based onthat value. I t maybe maybe possible to recover from from the error rror and continue onti nue receivi eiving ng data. REGISTERINGTHE NGTHEMETADATA To extend the mini mini--meta data applic appli cation, ation, you will add aformat fram frame to a global regi stry try. The symbol for thisr thisreg egistryi try is '|MiniMetaDataRegistry:DTS|. Here isanexample of howyou add a format format frame:
local registry; if GlobalVarExists( '|MiniMetaDataRegistry:DTS| ) then registry = GetGlobalVar( '|MiniMetaDataRegistry:DTS| ); else registry := DefGlobalVar(
Newton Technol ology ogy Journa Journal
13 EnsureInternal('|MiniMetaDatRegistry:DTS|), EnsureInternal([]) ); AddArraySlot( registry, myFormatFrame );
itemSeparator: ",", lineSeparator: unicodeCR, emptySpace: " ", fields: ['name.first, 'name.last, {format: 'quotedString, pathexpr: 'city}]}
Here is ishow you would remov remove your format format from the the registry try:
if GlobalVarExists( '|MiniMetaDataRegistry:DTS| ) then begin local registry = GetGlobalVar( '|MiniMetaDataRegistry:DTS| ); local pos := LSearch( registry, myFormatSym, 0, '|=|, 'symbol ); if pos then RemoveSlot( registry, pos ); end;
Each MetaData MetaData frame framemust have the followi following slots lots: titl ti tle, e, symbol, fields fields, either either GetS G etSoupNameor soupName, and either either GetQ G etQuer uerySpec or querySpec. I t mayopti mayoptionallyhav onally have alineS li neSeparator slot, lot, emptySpace slot, lot, and an itemSe itemSeparator slot. Here is isa more inin-depth descripti ri ption on of each slot: lot:
title Here are some examplesof plesof what a forma format frame framemigh might look look like: li ke:
{title: "Names File - First, Last", symbol: '|Format1:DTS|, soupName: "Names", lineSeparator: unicodeCR, itemSeparator: ",", emptySpace: " ", fields: ['name.first, 'name.last]} {title: "Names File - First, Last, Address, Phone", symbol: '|Format2:DTS|, soupName: "Names", fileName: "Names Export", fields: ['name.first, 'name.last, {format: func(s) if s then CapitalizeWords(s) else nil, pathexpr: 'address}, [pathexpr: 'phones, 0]]} {title: "Names File - First, Last, City", symbol: '|Format3:DTS|, soupName: "Names",
The nameof thisparti thispartic cular ular meta data frame frame. Thisi his isthe name that will will appear to the user in i n the li st of installed talled meta data frames.
Symbol This hisi sa uni unique quesymbol used to iden identify ti fythi this spartic particular meta data frame. I f you regis register two two meta data frameswi frameswith th the the same symbol, the second one that is isinstalled will overwrit overwrite e the firs fi rst one. Append your developer eloper si gnature ture to the symbol.
soupName The nameof the soup to export data from, or nil. nil.
GetSoupName I f you cannot know knowthe name of the soup at compile time, time, specify thi s slot instead of the soupName slot. lot. GetSoupName will hold a function ti on
NTJ
I f you have have an idea dea for an arti rticle you’d like like to write ri te for Newton ton Technology hnologyJ Journal, send it vi via I nternet to: NEWTONDEV@ NDEV@ apple pplelilink. nk.a apple pple.c .com om or AppleLi leLin nk: NEWTO NDEV NDEV
Newton Technol ology ogy Journa Journal
August 1996
14 Newton Communica Communications tions
NewtonProg Programming: CommunicationsOvervie rview Newton Devel oper Tr aini ai ni ng
operati ng system is isdesigned with communic nications ati onsasan asan The Newton operating integral part of the the system. The pervasive approac pproach is isthat whatever you can see in a Newton applic appli cation, ati on, you can send. Part of of thi this s approach is isthe notion notion that, asmuch asposs aspossible, the user wi will have have a verys verysi milar milar experienc experi ence in in sending data regardlessof the the medium dium used to send send i t. From a programming programming point point of view viewthing thi ngsare not not quite quite so simple but the archi architec tecture is i sdesigned gned in in a layered wayso that litt li ttle le program programming ming isreq is requir uired ed unles nlessthe situati tuation on is isfairly fairlyunus unusual. I n other words, there is isa great reat deal of built built-in commu communi nic cationssoftw ationssoftware in the the Newton which which can be used to provide provi de basic communica ommunications ti ons functiona ti onality li tyfor for almost any anyprogram. Figure 1 showsthe howsthe various variouslay layerscompri erscompris sing the Newton communic unications ationss system and the programmi programming interf i nterfac acesus esused to accessthese elements. The rest of this thi sarticle arti cle givesbri esbrief ef descripti ri ptions onsof of these APIs API saswell asprovidi asproviding ng referen referencesto more details tailsab about them.
appli applic cation ation programmi ramming ng interfac nterface (API (API)) isused to specifyw fy whic hich data i s bei bei ng “routed”, routed”, what form it takesan kesand d howi t should appea appear ( for example, pri print format) . The Newton 2.0 OS OS usesa storetore-and-forward model for this thiskind of communic nicationsan ationsand the In/O In/Out ut boxesare where here i ncoming oming or outgoing outgoing data i sstored tored i n the routing routi ng model. model. Built into the system is is In/OutBoxApplic icationandTransportAPI. Built the In/O I n/Out ut Box applic application ation whi whic ch managesthe esthe soupsused oupsused to store tore incoming oming and outgoing tgoing data. T his hisappli applic cation ation communi ommunic cateswith ateswith one of several Transports ports, which consi st of of code provided provi ded to move the data to or from the appropri ppropriate destinati ti nation on or source. While hile there are several built built--in transports portsin the system, NewtonScript ri pt programm programmers maywrite maywri te their thei r own transport to provi provide de system-wide data management. Endpoin int API andEndpoin int System. TheEndp Endpoint oint API isa NewtonSc tonScript ri pt interface for performing direc di rect communic nicationswit ationswith h the outsi de world. orld. Applic Appli cationspr ationsprogra ogrammersma rs may yadd add endpoint codeto their their programsto programsto communic nicate directly tlywi th an external source or destina ti nation. ti on. An example of this thi smigh mightt be endpoint endpoint code whic hich communicatesdirec atesdi rectly tlywith a GPS device on demand. Transports ports have endpoint endpoint code to move the data theyrece theyreceive out to an external destinati ti nation on or to rec receive eive data from anexternal source pri or to to passing it to the I n/Out n/Out Box Application. tion. Low-le level Communic icationTo Tools ls. These toolsare toolsare implemented in C+ + and actuallyc llycommu ommunica nicate with the the C+ + interfac rfacesto the hardware drivers dri vers. While hile these interfacesare not yet available, theyw theywill be publis publi shed in the future. Each of the APIs API swill be describe ri bed d in in more deta detaiil in i n the rema remai nder of thisarticle.
ROUTING
Fi gure ur e 1: 1: Newton Communi Communi cati ons Layers
The follow following isa brief ri ef descripti ri ption on of the item items sshown in in Figure 1 and their APIs API s. Routing API isthe simplest ANewtonScrip iptappli licationusing the Routing wayfor applic application ation programme programmersto rsto provi provide de communi ommunic cationssu ationssupport from a Newton devi ce. Anyappli Anyapplic cation ation writt ri tten en in NewtonScript ri pt can use communic munications ationsmodules moduleswh whi ch havebeen i nstalled talled asTrans asTransports ports. I n Newton 2.0 O S, this thi sincludesthe ludesthe builtbuilt-in transportsfor ports for beam beamiing, ng, fax faxiing, ng, mailing li ng, and printi pri nting ng. To use the avail availab able le transports, the Routing Routi ng
August 1996
The Newton O S is isprovidesa providesa store-and-forward model for communicationsand ationsand usesthe esthe In/O I n/Out ut Boxesast Boxesasthe he place where target reandforw rwardmeansth data iss isstored. Thetermstore meansthat at messagesare agesare routed (di ( direc rected) to a dis distant communicationsdevi ationsdevic ce or from such a device to a Newton applic appli cation ation through an intermedi intermediate holdi holding ng area ( theI n/Out n/Out Boxes) . Target data isanypiec piece of information w whi hic ch is isbeing routed in in or out of the the Newton. The In/O In/Out ut Boxesare actuallya tually a single appli applic cation ation whic hich provides the storage in the the form of a soup, the functiona ti onality li tyof of sending and
Newton Technol ology ogy Journa Journal
15
recei ving ving messages, and the interfac terface that letsthe lets the user look look at pending pending messageand dis disposeof them them ashe ashe or she desires. Figure Figure 2 shows what the In/O In/Out ut Boxesmi Boxesmight ght look like li ke when there are messages pending ding. Note that at any anytitime me the user canswitch from In In Box to Out O ut Box and vi ce versavia via the radio radio buttonsat buttons at the top of the vi view ew.
actions ti onsasi asillllus ustrated in Figure 3. Some appli applic cationswi ationswillll have one Action Action button button in i n the the statusba tatus bar, r, othe others rsw will have one one in in each of sev severa eral view views. The Namesapplic Namesappli cation ation is an example of a single Action ti on button because normallyonly normally onlyone one name at atime ti me isview viewed. The Notes Notes applic appli cation ati on hasan Action Acti on button button attached to each note si nce there may be manynoteso anynoteson n the screen at anygi anygiven ven time. time. The Action ti on button is i screated reated on screen by addi adding the prototype protoActionButton to the the desired view vi ew.
Fi gure gur e 3. The Acti Acti on Button Button Popup
Fi gure 2. 2. The In/Out In /Out Box User Inter In terfa face ce
Routing Routi ng i s usualllly ytrigg tri ggered ered byus byusing the Action ti on button button that is is dis displayed in the view viewfrom which something omething will be routed. The Action Action button button is isdis di splay played in in the view view asa asa pop-up which showsavailabl howsavailable e user
Newton Technol ology ogy Journa Journal
Each targ target obj objec ect which is isrouted routed must have a meaningful class. For frames, this thi smeansthat nsthat the the frame must have a classslot whic hich identifi ti fiest esthe he type type of of data associated ated with this thi skind of object. Normally Normally, each appli applic cation ation wi ll supplyi upply i tsow ts own n classof data for routi ng, ng, such as '|myData:MYSIG|. This hisclassisused bythe bythe system to look up i n the Data View Registry trythe lis li st of routing routi ng frame frames swhic hich may maybe us used to route route data of a speci fic fi c class. From these routing routi ng frames frames, a lis li st of transportsor ports or communi ommunic cation ation methods( for example, faxing faxing, pri pri nting nting, beaming) ming) whi ch can route route the target data are supplied uppli ed to the Action Acti on button. The net res result of this thi si sthat when hen the user tapson the Action Action button a lis li st of the destina ti nationsappea ti onsappear which are appropriate appropriate for the target data. Figure gure 4 showshow this thi si sall interc interconnected. An applic application, ation, usualllly yin its itsII nstallScript, ri pt, will put oneor more frame framesnamed for the classesof esof data whic hich it it will route route into into the Data Data View Vi ewRegistry. These Frameswill rameswill consi st of of one or more Routi Routing Frameswhich describe ri be what format the target data can take when it is i srouted. routed. The system usesthi esthis s to search the lis li st of i nstalled talled transportsan ports and, d, when it finds fi ndsa a transport which hich supports upportsone of the routi ngTypes, addsthe addsthe trans transport port name to the lis li st to to be display displayed in the the Action ti on button. So in the example shown in in Figure 4, the applic appli cation ation hasi nstalled talled a frame|forms:MYSIG| in theView ViewDefiniti Definition on Reg Registryw try whic hich supports supports data dataTypesof 'view view, 'frame and 'text. 'text. These are used to choose the transportsfor ports for pri printing nti ng,, faxing, beam beamiing and mai ling li ng so these appear in in the Acti Action on button the user has haspressed. Note Note that it it doesn’ t pic pi ck up the compresstrans transport port whose dataType is is 'binary binary. When the user selectsa ts a transport from from the Action Acti on button, an appropri appropriate ate routing routi ng slip li p is isdis displayed and and all all formatsthat formatsthat in in whic hich the data can be displayed are dis displayed in in the format format pic pi cker asshown in in Figure 5. Formats ormatsdes describe cribe howthe target data should be organized organi zed before sending ending i t onward to the appropri appropriate destinati ti nation. on. For example, when printi printing ng, there might might be several formats formatss such aslet asletter, ter, memo, two-column, and so on, which describe cribe how the targ target data will will be
August 1996
16 printed. When the user hass hasselected a format format for the target data data and sent it it off, the appropri ate transport i sthen messaged wi th informati i nformation on about about the target data and the data isplac is placed in the Out Box for further dispos disposition. ti on.
Fi gure gur e 5. The For mat Picker Pi cker
TRANSPORTS
Fi gure gur e 4. 4. The Routi out i ng System ystem
August 1996
The simplest defini definitition on of a transport is i s– somethi omething ng to which data can be routed. But a more useful defini fi nitition on isthat is that a transport is i sa globalllly yavail availab able service offered to applic applicationsf ationsfor or sending nding or receivi eiving ng data data.. Because of the global nature of tran trans sports, it i t is i snot necessary, or even likely li kely, for an indivi di vidual dual applic ppli cation ation to define define a transport. The bui bui lt-i lt-in trans transportsi portsi nclude printi printing ng, faxi faxing, mai ling li ng, and beaming ming,, but one mi might ima imagine gine additi additional onal trans transports portssuch as messaging, scanning, nning, compressi ng, archi ving, ving, or encrypting. rypti ng. Thus, while hile ttrans ransportsare ports are usuall ually y associ ociated wi th hardwa hardware ( printers printers, mail servers, and scanners, for example) this thi si snot necessarily arilythe the case (e.g. (e.g.,, compressing, archivi archiving, ng, encrypti ng), ng) , si nce a servic ervice maybe offered that altersthe alters the data being routed without sending it to t o anyouts nyoutsi de hardware. Transports portsare usuall ually ybuilt built asauto-load parts rts; theyappe theyappear in the Extensionsfolde onsfolderr of the ExtrasDraw ExtrasD rawer. A transport’s port’ sI nstallScript ri pt registers registersiit with with the the system byc bycalling alli ng the global function function RegTransport(). Asdes Asdescribe ri bed d earlier arlier in the routing routing dis discussion, if i f appropriate appropriate target data is isrouted, the the transport’ sname name wi ll appear in in the action ti on lis li st in i n an applic ppli cation ation when the user tapsthe tapsthe Acti Action on button. Because most trans transports portshave communic ommunications ationsc code that will will be used to send or rec receive eive the target data, they theywi will ty typic pi cally also inc include endpoi endpoint nt code that that communi ommunic cateswith ateswith the destina ti natition. on.
Newton Technol ology ogy Journa Journal
17 Transportsus ports usualllly ywork wi th an an applic ppli cation ation via the I n/Out n/O ut Box appli applic cation. ation. When an appli applic cation ation routesdata out to a transport, the transport provi desa routing routi ng slip li p and i snotifi noti fied ed when the routed data reachesthe hesthe O ut Box. When itemsare temsare sent, the the tran transport will will get the data from the the Out Out Box and do whatever is i snecessaryto ary to send the data, setting etti ng statusi tatus information nformation at appropriate appropri ate stagesduring duri ng the tran trans sfer. fer. I n the case of a request to to receive data, the the sequence is isjust slightly sli ghtly more compli omplicated. I n the simples mplest case, when the user selectsa electsa trans transport from from the Receive eive button utton lis li st in i n the In In Box, the selected trans transport is i ssent a reque request to receive eive data. The trans transport will will then then connect to the the remote source, get anypending anypendi ng data, and add it to to the I n Box Box lis list. There i salso an option opti on for a trans transport to to get get informati information on about the data data being routed from the the remote remote source and post this thisinformation nformation into the I n Box wi thout thout actually tuallyg getting etting the data. Thisi his i suseful in in a situation tuati on such asa mai l trans transport where the user often often wantsto antsto simply ply get the ti ti tles tlesof of pending pending messagess esso he or she maychoose whi ch messagesthey estheyw want to to download to to the the Newton devic device. The main proto proto used to create a transport isprotoTransport. The powerful thi thing ng about protoTransport i sthat in i n many many cases, surpris urpri si ngly nglylilitt ttle le code other other tha than n the actual endpoint endpoint code must be written. ri tten. This hisi sbecause the transport defaultsty ults typi pic cally “do the rig ri ght thing thi ng” to provide provi de an interface and and behavi havior or for the transport. O nly those featuress turesspecific fi c to the transport ( for example, archive hive name for an archive rchive transport) port) must be added to the the standard interfac i nterface.
Newton Technol ology ogy Journa Journal
Transports portswhi which can send data also have their thei r own routi routi ng sli ps based on the the prototype prototypeprotoFullRouteSlip. Thisallowsusersto provide provi de transportport-speci fic fi c options opti onss such asaddres asaddressesi n a partic parti cular format, and so on. I n partic particular, such thingsas thingsasdi dis splayi ng the statusof tatus of a routi ng request, logging of routed routed items items, error handli handling ng, power power--off handling handli ng,, and general user interface interfacesare handled well bythe by the defaults ultsif the transport si mplys mply setsor etsor updatesa tesa few slots lotswhen appropriate. appropriate. O nly the actual servic rvi ce code (s ( such ascommuni cations ations) will differ differ from from one transport to another.
ENDPOINTS
Endpoints Endpointsare are the prima primaryNew ry NewtonScript ri pt API for programming programming communic nicationson ationson the Newton devic vice. They heyprovide provide a “virtual virtual pipeli pipeline ne”” for all communic nications ations. They heyare designed to hide hide mos most of the specific fi csof a partic parti cular communications ationsmedi media and, onc once connected, endpoi endpoint nt input i nput and output code i susuall ually ythe same ame regardles rdlessof the media media being used. Endpoint Endpoint code to rec receive eive data from from an AppleTalk network can be identica dentical to to code to receive eive data through through amodem, whic which can be identic dentical to code to rec receive eive data over a serial eri al line, li ne, and so on. Such thing thi ngs saspacketi aspacketiz zation – which occursin ursi n anynetwork twork protocol – are hidden hidden from the endpoint user during duri ng sendi ending ng and receiving eivi ng,, asare operations operationss such asfl asflow ow control, ontrol , error rec recovery, ry, and so on. The only onlyex exc ceptionst eptionsto o this thi srule occur when when there there are speci fic fi c hardw hardware are limi limitati tationst onstha hatt push through the endpoint dpoint API . For exa example, I R beaming ming isa is a half-duplex lf-duplex protocol ( it can onlybe onlybe in send end mode or receive mode, not both at the same time) time) while hile serial, erial, AppleTalk, alk, or modem communications ationsare are all fullfull-duplex (they ( theyc can be in in send and receive modeat the sametime) ti me).. O f course, while while sending and recei ving ving are purposefully full ymediai ndependen pendent,t, the conne connection ti on processi snec necessarily arilytitied ed to the the media dia being being used. So, for example, with AppleTalk i t is i snecessaryto ary to speci fy network addresses; for modem communica ommunications ti ons, a phone number; for for serial eri al communic ommunications ations, speed, parity pari ty, stop top bits; bits; and so on. Figure gure 6showsthe life life cycle of an endpoint. ndpoint. An endpoint endpoint is i si niti nitially ally defi define ned asa frame proto’ed from from protoBasicEndpoint . Theframe hasseveral slots lots describi ri bing ng the settingsof etti ngsof the t he endpoint endpoint and methods that maybe may be called alled bythe bythe system during duri ng the course of its i tsexi exis stence. However, such a frame isnot is not an endpoi endpoint. nt. T hat hat is i s, it describe ri bes swhat hat an endpoi ndpoint nt might might look like, li ke, but it it is i snot aNewtonScript ri pt object. To create such an objec object, i t must fi rst be ins instantiated. tantiated. Note Note that that s siince most obj objec ectsi ts in the New Newton O S are view vi ews, and si nce the view vi ew system automati automatic callyi ally i nstantiatesa tantiatesa view viewobjec object when it it is i sopened, we usuall ually y
August 1996
18 don don’ t see this thi sstep. But si nce an endpoi endpoint nt is isindepend ndependent ent of the view view system, we must explic expli ci tly tly i nstantiate tantiate it it to to create an endpoint ndpoint objec obj ect.
Fi gure ur e 6. Li fe Cycle of an Endpoin Endpoint t
O nce instantiated, tantiated, an endpoi endpoint nt is isopened bysending nding the Open() message to it. it. This histiest ti esthe he endpoi endpoint nt to a lowlow-level communications ti ons tool tool i n the system and spawnsa new task at that lowe lower level. level. O nce the endpoint i sconnected, i t mayne mayneed ed to be bound to a particu parti cular mediamedi a-dependent address, node, and so on. An Apple AppleTalk endpoint, for exam example, is i sbound to anode node on on the network. twork. Thisi his is done by by sending the endpoi endpoint nt the Bind() message. Note Note that some protocols( protocols ( such asseri asserial al commun communi cations ations) do not have a requi required red bindi binding ng phas phase but it i t is i sstill ti ll necessaryto aryto call Bind() ( and later, Unbind()).
After binding binding the endpoi ndpoint, nt, the Connect() message i s sent to to connect to to the parti cular media media bei ng used. For a remote service ervi ce that i saccessed through a modem endpoint, ndpoi nt, the endpoint endpoint would dial dial the service ervi ce and establis tabli sh the physi cal connection. ti on. Note Note that the endpoint ndpoi nt doesnot doesnot handle handle protoc protocol items i temss such aslogging logging on, supplying passwords, and so on; these are part of an ongoing ongoing dialog dialog that the t he applic appli cation ati on and the servic ervi ce must engage in once connection ti on is is establi tabli shed. The endpo endpoiint methodListen() maybe maybe used to establis tabli sh a connection ti on ins instead of the Connect() method method if if the endpoint is is i nstantiated tantiated and readyto dyto li li sten to an “offer” “offer” bythe bythe remote source. ource. Based on the parti partic cular situation tuation wi with the the communi ommunic cationsmedi ationsmedia, a, an appli applic cation ation may mayeither either reject the connection ti on bys bysendi ending ng the Disconnect() message to the endpoint, endpoint, or accept it i t with with the the Accept() message. ( Note Note that si nce infrared frared connections ti onshave have one side sending ending and the other side receivi ng, in i n this thi scase the passive si de connectsby ts byc calling alli ngListen() i nstead of Connect().) After fter connecting, ti ng, the endpoint endpoint is i sreadyto readyto send and recei ve data. Sending nding i sfairl fairly y straigh trai ghtfor tforw ward and isdone is done byus byusing the method method Output(). When sending data, information nformati on about the form of the data ( such asthat it it is i sa stri ng, a New NewtonScript ri pt frame, and so on) i susualllly y sent. This hisgives givesthe the system a descripti cription on of how the data should be formatted asit asi t is isbei being sent. ent. O utput maybe may be made either synchronouslyor hronously or asynchronouslywi hronouslywith asynchronousca hronous calllls srequiri requiring ng that a callback method be speci fied. fi ed. Receiving i ngdataisa litt li ttle le more complex. I ncoming omingdataisbuffered by the system below the applic application ation endpoint poi nt leve level. An applic appli cation ation must set up a descripti ri ption on of when hen it it wantsto ntsto get get inc i ncoming oming data. data. This his des descripti ri ption on is isin the formof an inputSpec . For example, an inputSpec could be created whic hich looked for the string tri ng “login:” login:”,, or it it could be set to to tri trigger when 200 characterswe ters were received. To some extent, extent, it can be set to notify noti fythe the endpoint of inc i ncoming oming data after a
NTJ
To send comments comments or to make reque requestsfor tsfor artic arti clesi lesin New Newton TechnologyJ hnologyJournal, send mail via vi a the Inte Internet to: NEWTONDEV NDEV@ @ appleli lelink.ap nk.apple.com .com
August 1996
Newton Technol ology ogy Journa Journal
19 Communicati ommunications onsTech Technology nology
NewtonProgramming: DILsOv LsOvervie rview Newton Devel oper Tr aini ai ni ng
important new new additi ddition on to New Newton communi municationspr ationsprogra ogramming An important isa set of librariescalled theDesktop ktop Inte Integ gration Librariesor D DII Ls. The firs fi rst and most i mportant mportant thing thi ng to unde unders rstand tand about about DI DI Lsi Lsi sthat they have nothing nothi ng to do with wi th prog pr ogrr amming ammin g communi communicati cations ons on the Ne Newton device . I nstead, theyare they are used to create a communic ommunications ationslilink nk between Newton devicesanddesktop machines hines. I n other words, ttheyare heyare an aid for writi ri ting ng code for a desktop machine hine whic hich wi ll communicate with a Newton. Figure gure 1 showsthis thi srelations relati onship. hip. Essentially entially, endpoi endpoint nt code code on the Newton, whether part of an appli applic cation ation or in i n a transport, transfersdata fersdata between a Newton devic device and a desktop machine. hine. O n the desktop mac machine hine,, an applic ppli cation ation whi whi ch usesa DI D I L sendsand receivesda eivesdata ta which isha is handled bya desktop ktop appli applic cation. ti on. Currently CurrentlyD DI Lsare ava avai lable lable for the Mac M acO S and for Windows-based machines hines.
connectivi ctivity tyto to a Newton device deviceand must be used to establis tabli sh a connection ti on before you canuse theFDI L and PDI PDI L. The FramesDIL esDI L (FDI (FDIL) L) providesa providesa relativelysi ti velysimple wayto map NewtonScript ript fram framesto C structuresand ructures and also provides provi desa a mechanis nism to handle handle data which which was added dynamic micallyto allyto the frame. TheProtocol DI L (PD (PDII L) providesan providesaneasy mechanis hanism for synchronizi hroni zing ng data between a Newton applic appli cation ation and a desktop applic pplication. At the time timeof writi ri ting ng, the PDI PDI L isnot isnot yet available lable but will be available in in the future. All of the the DI Lsare libra li brariesw rieswritten ritten orig originallyi lly in C+ + but but calllled ed using a C-like C-like syntax wi th a “mag “magi c cooki ook ie” obj objec ect token token passed into into the the calls. On theMacO S side, de, the there re are MPWan MPW and Metrowerksl rksliibraries ri es. On the Windowsside, DI D I Lsare Lsare implemented implemented asDLLsan LLsand so should be independent of parti parti cular C lang language impleme plementations ntati ons.
CDIL The CDI CD I L essenti entially allyha has sthe follow following phases: ini i nititiali aliz zation, ation, connec onnecting ti ng,, reading ding or wri writiting ng, and and disc disconnec onnecting ti ng. This hisi s purposefullyverysimi efullyverysimilar lar to the the normal endpoi endpoint nt life life cycle. The idea dea is to create and open avirt virtual ual pipe pipe to the the Newton device deviceand then communica ommunicate using some user-defined defined protocol protocol bys bysending ending and recei ving ving messagesor esor data down the pi pipe. pe. Figure Figure 3 showsthe howsthe normal order of callsi allsin us using the CDI L.
Fi gure gur e 1: DILs DI Lsand an d Newton Newton Devices
The main advantage that DI DI Lsprovi Lsprovide de isthat they theymake it it easier to write ri te code for a desktop machine hine whic hich communic unicateswith ateswith a New Newton devi device. I n parti cular, theyabstract the the Newton conne connection ti on to a virtual virtual pipe pi pe for bytesan tesand d provide provide control over such thing things sasASCI I -toUnicode nicode conversions rsionsand and Newton ton data structures tructuresand and typess pessuch as frame framesand 30-bit bit integers.
Fi gure ur e 2: Hie Hi er archical ar chical Str uctur e of of DILs
Ass Asshown in in Figure 2 there are three DI Lsw Lswhic hich build on one another: CDI L, FDIL FDI L andPDIL. PDI L. The Commu Communication tionsD sDII L (CDI (CDI L) provide providesbasic
Newton Technol ology ogy Journa Journal
CDInitCDIL() CDSetAppplication() // Windows only CDCreateCDILObject() CDPipeInit() CDPipeListen() CDPipeRead()/CDPipeWrite() CDPipeDisconnet() CDDisposeDILObject() CDDisposeCDIL() Fi gure gur e 3: CDIL Call al ls
The The CDInitCDIL() routi routine must be called lled before anything thi ng else can be done with the CDI CD I L. O n Windowsmac machinesthe hinesthe routine routine CDSetAppplication() must be called next. There isno equivalent quivalent to this thi scall on the MacO S. Next, the routi routine neCDCreateCDILObject() i scalled to create a CDI CDI L pipe. I t returns returnsa pointer pointer to a pipe whic hich mus must be us used for all subsequent calllls swhich involve involve that pipe. pi pe. CDPipeInit() initializesthe pipe so that it is“open for business.” I n particular, i t setsthe comm commun uniicationsopti ti onsoptionsi onsinc ncluding the media media detailssuch asmedia type ( for example, serial, erial, Apple AppleTalk, lk , and so on), on) , and relevant media edia options opti ons(( for example, speed of connection, ti on, data bits bits, modem type, and so on). on) . Next, the pipe pipe us usesthe CDPipeListen() call to wait for a
August 1996
20 connection ction from the Newton device device. When the Newton device devicecontacts the desktop machine, hine, the the applica appli cation ti on using the CDI CDI L mayaccept the connection ction onceCDPipeListen()) return returns sbycalli bycalli ng CDPipeAccept(). This hisallowsa connection ti on to be be canceled if, for example, the applic appli cation ation decidesthat desthat the actual connect rate wastoo slow. At anyti anytime me in this thisprocess, tthe he desktop applic appli cation ation can cancel an attempted connection ti on byc bycalling alli ngCDPipeAbort(). O nce a connection ti on is isestablis tabli shed and worki ork ing, strea treamsof msof bytesca tes can be sent and received using the routi routinesCDPipeRead() and CDPipeWrite(). Asw Aswith most CDI CD I L routine routines, these callsma allsmayeithe eitherr be made synchronouslyor hronously or asynchronouslywi hronously with a callbac allback routi routine. From this thi spoint point on, the desktop applic application ation and the New Newton applic appli cation ati on can engage in in an appli ppli cationati on-speci fic fi c protocol protocol where there will be an predic predi ctable exchange of messagesand data via via the CDI CD I L’ s virtua virtual pipe pi peliline ne. When the decision is ismadeto terminate termi nate the connection, ti on, the the routi routine CDPipeDisconnect() should be called. O nce this thi sroutine routi ne has completed, ompleted, connection ction hasbeen broken roken and both sidesmus desmust rereestablis tabli sh the the connection ti on before before data can again be sent or received. Finally lly, whenthe desktop applic application ation is completelyfi ompletelyfini nis shed with the pipe pipe,, it must call the routinesCDDisposeDILObject() to tea tear down the pseudo-objec obj ect and CDDisposeCDIL() to close theCDI CD I L environme vironment. O n the MacO S, CDDisposeCDIL() clos losesthe esthe CommunicationsToolbox ationsToolbox tool tool whic hich wasopened, and on a Windows machine hine it closesthe appropriate propri ate driver driver. There are several other additi additional onal CDI CDI L callsw alls whic hich maybe of use to the desktop programmer. These fall into i nto four categories tegories: encryption, rypti on, utili utilitities es, status, and and mis mi scellaneous ellaneous. There are two encryption rypti on routi routines nes: CDEncryptFunction() and CDDecryptFunction(). These passcallbac llback routi routinesuse nesused to the CDI CDI L. These callback routine routi nesarecalled bythe CDI L libra libraryat ry at the appropriate appropri ate time ti me to encrypt or decrypt data passi ng through through the pipe. pipe. There here is isno attempt bythe bythe CDI CDI L to packetize keti zedata and so, if i f the programmer is isusi ng aunit-ori unit-oriented ented encryption ryption scheme (for (for example, cipher block block chaining), ning) , i t is i sup to the applic pplication to buffer buffer the i ncoming oming or outgoing outgoi ng data until unti l there there isenou is enough gh data to encrypt or decrypt the block. block. T he utili utility tyrouti routine nes si nclude such thingsasCDFlush() whic hich is is used to flus flush the contentsof contentsof the pipe pipe in in a given di direction, ti on, CDIdle() whic hi ch is i sused to call completion ompleti on routi routinespas nespassed into i nto asynchronous callsaswe alls aswellll aschecking on and and updating ti ng the statusof tatusof the pipe, pi pe, and CDPipeAbort() whic hich aborts abortsan any transactionsi ti onsin n a given direc direction ti on which hich are pending. pending. T he statusrouti tatusroutine nes sreturn information nformation about the pipe. pipe. CDBytesInPipe() returnsthe returnsthe number of bytesc tescurrentlyw urrently waiti aiting in a given direction ti on in a partic rti cular pipe. CDConnectionName() returns the the name set by CDPipeInit(), CDGetConfigStr() returnsthe medi medi a configu onfi gurati ration on stri ng pas passed into i nto CDPipeInit(), and CDGetPortStr() whic hich returnsthe returnsthe nam name of the port the the pipe is is conne onnected to (for ( for exa example, “COM CO M 2” or “M “Modem”) . CDGetPipeState() and CDSetPipeState() get and return the the current state of the pipe. pipe. Figure 3 showsa lis li st of the the possible statesof tatesof a pipe.
kCDIL_Startup kCDIL_Listening kCDIL_ConnectPending kCDIL_Connected kCDIL_Busy kCDIL_Aborting kCDIL_Disconnected kCDIL_Userstate Fi gure gur e 3: CDI CDIL L Pi pe States ta tes
kCDIL_Unitialized kCDIL_InvalidConnection August 1996
Newton Technol ology ogy Journa Journal
21 The last of the utili utilityc ty classfunctionsi ti onsis sCDGetTimeout() whi whi ch returnsthe returnsthe amou amount nt of time ti me in milli mi llis secondsbefore ondsbefore a read or write ri te call call will will time out. Fi nall nally y, the mis mi scellaneousc ouscategoryi ory i ncludestw ludestwo routi routine nes swhic hich may be useful: eful: CDPad() and CDSetPadState(). CDPad() padst padsthe he write ri te buffer so that it i san even multi ltiple of a value passed in in asa parameter. This hisi suseful for some packetiz keti zed protocolsor protocolsor if i f a unitnit-orien ori ented ted encryption rypti on scheme is isbeing being used. CDSetPadState() turnsthe padding speci fied fi ed byCDPad() on or off.
FDIL TheFDI L (als ( also sometime ti mescalled HLFDIL LFDI L for Hig Hi gh Level FDI L) isused to support the the transfer of NewtonScript ri pt objec obj ects( ts ( framesand arrays) to the desktop. A CDI CD I L connection ti on must be establis tabli shed before FDI Lsc Lscan be used in in order to provide provide the underlying derlying pipeli pipeline ne for FDI FDI L tran transfers. Before FDI L callsc allscan be made to move informa formation ti on to or from the the Newton device , the FDI L routine routineFDInitFDIL() must be called to to initialize the library. The most common use of the FDI L is i sto map NewtonScript ri pt fram frames into C structures tructures. I f the frame frame shown in in Figure gure 4 is isgoing going to be uploaded to a desktop machine, hine, the the desktop appli cation ation can use FDI Ls to map thisframe into the fromNewt C structure shown in the figure. fi gure.
aNewtFrame:={ slot1:'b, slot2: {slot3:24, slot4:{ slot5:16, Fi gure ur e 6: Unbound Data in i n slotDefin slotDefinii tions ti ons slot6:$c} }
slot7: "TROUT"}; struct fromNewt {
long subsubslot5; char subsubslot6;
}
}; // slot4 }; // slot2 strlen char slot7[32]; // or maxstrlen Fi gure ur e 4: 4: Mapping Mappi ng a NewtonS NewtonScri pt Frame to a C Str u ct
To build build the mapping mapping between the NewtonScript ri pt frame and the C structure, an FDI L obj object is isfirs first crea created bycall bycalliingthe FDI L routine routine FDCreateObject(). This hisobject ac actsasthe tsasthe central entral linkag li nkage e for all all itemsin temsi n the frame or arraybei rraybeing sent or received. To map the slots lotsi n a frame or elementsi ntsin an arrayrepeated rrayrepeated callsto alls to FDbindSlot() are made. These callsmatc alls match a Newton slot name (or (or an arrayobj rrayobjec ect) to a C variable ri able or buffer. I n the case shown, there would be repeated callsto alls to FDbindSlot() each of which which would ould specify pecifya a slot lot nameof an element in in the frame, the the addres addressof a memory memoryloca location ti on the slot value wi will be copied opied into, into, and and the FDI L object whi whic ch keepsall psall of the frame mapping ppings. Once thisbi this binding nding in completed, the data can betrans transferred with with a single call to to FDget(). Whenthe Newton sendsthe frame data ( presumablyby ly byca calli lling Output() ) to the desktop, the FDI L will move thedata into the the locationson ti onson the desktop machine hine specified fi ed in the bind calllls s. The FDI L object crea created ted keepstrac keepstrack of all bindi binding ngspreviouslyma ly made de so tha thatt when FDget() iscalled, the FDIL FDI L knowswhere each piec piece of inc incoming oming data should be put in i n the desktop machine’ hine’s memory. I f data is isbeing sent from the the desktop machine hine to the Newton devic device, the desktop applic application ation would would call FDput() to send the data at the addressess esspeci fied fi ed bythe bythe FDbindSlot() callsto alls to the Newton devic device in aflattene flattened frame format whic hich the Newton OS O S can understand. I n this thi scase, on on the Newton side it it would be expected that an inputSpec inputSpec would have been establi tablished which which expected a data data form form of 'frame. FDget() and FDput() maybe maybe called asynchronous nchronously. I f an asynchronouscall of these routine routinesismade, it i t is i simportant to remember that the memoryto ory to whic which the data is isbound must still still be available when the completion ompletion routine routineiscalled. I n partic articular, memorys ry should not be allocated using local variab variabless lessince the stack of the subroutine ubrouti ne making maki ng an asynchronousget hronous get or put call wi willll dis disappear when the program program exits xitsthe the subrouti ubroutine ne and, on the the MacOS, it i t is i salso necessaryto ary to avoid avoi d using referenc referencesto esto unlocked handles handless si nce heap compaction ti on could cause memoryblock mory blocks sto move. The stepsfor tepsfor creating creating bound framesare framesare shown in in Figure ure 5. Fi gure gure 5: FDIL Cookbook For Boun Bound d Data Data
char slot1[5];
// symbols bols to str
struct slot2 { long subslot3; struct subslot4 {
Newton Technol ology ogy Journa Journal
1. I f not previouslyope lyopened, ope open CDI L pipeline. 2. Alloca Allocate memoryon ory on desktop for framevalues. 3. Initialize FDIL. 4. Create theFDIL FDI L objectsfor each frame frame or or array object.
NTJ
August 1996
22 continued conti nued from fr om page page 2
Lette tter From theEditor Editor ow, what hat an introduction! ti on! W
I t will will no doubt doubt be an enormous enormous challenge to continue continue the traditi tradi tion on of servic rvi ce and technical excellenc ellence Newton Technical echni cal that Lee hasestablis tabli shed wi th the the production ti on of the theNewton Journal . So with both enthusiasm and trepidati trepidation on I accept the Newton Techni echni cal Jour nal to challeng llenge of managing and growing growing the Newton be an outstanding tandi ng infor informa mationa ti onal and technic hnical reference for Newton developers. Asfor Asfor me, I have spent the past year in the Newton SystemsGroup temsG roup mana managing New Newton developer traini trai ning ng. M ycurrent major projec proj ectsare tsare the development of an on-line li ne communication ation course (exc ( excerptsof erpts of whic hich are included in i n this thi si ssue) ue) , the conversion of the Newton
Essentials enti alsCour Cours se to a self-paced on-li ne version, and the preparation preparati on of new technologi hnologiestrai estraini ning ng. Prior Pri or to joi joini ning ng the Newton Sy Systems Group, I wasat Borlan Borland Interna I nternationa ti onal asan asan engineeri neering ng manager in i n the C+ + deve developer loper support upport group group.. I am commi tted to provi providing Newton developersall the informati information on theyneed to write ri te great great appli applic cations ations, whether hether it i t be in in the form of trai traini ning ng, technical journa j ournals, documentation, ntation, on-line li ne information, nformation, or support. I’d I’ d like like to start byi byinviti nviting you, the the Newton develope developer, r, to communicate your idea i deas, interests, and requestsvi ts via a email. Several Newton Techni cal Jour nal ispublished, a months monthsbefor before e each issue of Newton core team of representativesfr ti vesfrom om DTS, DT S, engineering ri ng, marketi rketi ng, NTJ soluti olutionsrelati onsrelations ons, and traini training ng meet and and discusspossible topic topi csto
continued conti nued from fr om page page 5
slimPi limPic cker: A Sli Slimm mmer lilistPic tPicker Proto slimPicker:AlphaCharacter(entry)
Returnsa Returnsa character repres representing enting the index index value for the given given entry ntry. The character will will be used to set the the appropri ppropriate tab in in the AZTabs AZTabs.
Thisme his method isreq srequired uired if theAZTabsare bsare vis visible.
slimPicker:CreateNewItem() Thisme his method isreq is required if if the New New button isvi isvis si ble. ble. The method method is iscalled whenthe user tapsthe “New “New” button. The developer developer is i sresponsible for any anywork that needsto dsto be done to add the newentry. This hisi ncludesc ludescreating reating and and opening opening any anyediti editing or data entrys entry slip, li p, adding the data to the curs cursor, or, selecting ti ng the newitem, and refreshing hing the slimPi li mPic cker ( seeRefreshPic hPicker below). low) .
slimPicker:GetHiliteShape(xcoo slimPicker:GetHiliteShape(xcoord, rd, bounds) This hismethod method isc is called to get the hilite li te box box for alis li st item. item. The deve developer loper should provide provide this thismethod method if i f tthe hey ywi sh to create a multiple multi ple column column pic pi cker. This hismethod should return something omething suitable uitable for Draw DrawShape. normali zed to bounds. xcoord isthe current x coordi nate of the pen normalize bounding ding box for the item bei being hi lited. li ted. bounds isthe boun
slimPicker:GetNumSelected() Thisme his method isreq is required if if the counter isvi isvis sible or or
UpdateSelectedText iscalled. Returns Returnsthe the number of selected items.
NTJ August 1996
Newton Technol ology ogy Journa Journal
23 Correction
Correction NTJ In NTJ Volume IIII Number 2, in i n the artic rti cle “Apple AnnouncesNew esNew MessagePad 130 wi th New Newton 2.0!” 2.0!”,, there wasan error in the des descripti ri ption on of the backli kli ght API . On page page21, a function ti on called BackLightPresent isdocumented. nted. Thisfun his func ction ti on should hould not be used. ed. Althoug Although it it exis existsi ts in the MessagePad 13 130, it will will not be present in in future future hardware that hasa backlight. li ght. The correct way to test for for the the presence of a backlight li ght is isto usethe Gestalt function ti on asfollows:
// define define this somewhere in your project project until // platformfile defines it
constant kGestalt_BackLight := '[0x02000007, [struct,boolean], 1] ;
local isBacklight := Gestalt(kGestalt_BackLight) Gestalt(kGestalt_BackLight) ; if isBacklight AND isBacklight[0] then // has abacklight
else
// has not got one
NTJ
To request infor i nforma mation ti on onor anapplic pplication ation for Apple’ Apple’s sNewton deve developer loper programs, contact Apple’ Apple’s sDeveloper eloper Support Center at 408-974-4897 or Applelink: NEWTONDEV or I nternet: NEWTONDEV@ NDEV@ apple pplelilink. nk.a apple pple.c .com om
Newton Technol ology ogy Journa Journal
August 1996
NewtonDeveloper Programs ®
Apple Developer Group
Apple Apple offersthree offersthreeprogramsfor sfor New Newton developers– lopers– the Newton AssociatesProgram, the Newton AssociatesPlusPr atesPlusProgra ogram and the New Newton Partne PartnersProgram. rsProgram. The Newton As AssociatesProgra atesProgram is isa lowc lowcost, selfelf-help development program. The Newton As AssociatesPlus atesPlusPr Program ogramprovidesfo provi desforr developers lopersw who needa limi li mited ted amount of code-level support and options options. The Newton PartnersProgram PartnersProgram isdes isdesigned for developersw eloperswho needujnli ujnlimi mited ted expert-level development. All All programsprovi programsprovide defocusedNewton development infor i nforma mation tion and dis discountson development hardware, softwa oftware, and tools– tools– all of which can reduceyour orga organiza nization’ ti on’s sdevelopment time ti meandcosts.
Newton As Associates Program This hisprogram isspeci allydes ally desi gned to provide provide lowcost, selfelf-help development rres esourcesto ourcest o Newton developers. Parti rti ci pantsga pantsgai n accessto online onli ne technic hnical informa i nformation ti on and receive monthlyma monthlymai ling li ngs of essential enti al Newton development informati information. on. Wit h the dis discountsthat ountsthat partic parti ci pantsrec ts receive on everything rything from development hardware to traini trai ning, ng, manyfi nyfind nd that their their annual fee feei srecouped in i n the firs fi rst fewmonthsof fewmonthsof membership. hip. Self-Help Technical Support Support • O nline technica hnical i nformation ti on and developer forums • Accessto Apple’stechnical Q& Q & A reference libra li brary • Use of of Apple’sThi ’s Thirdrd-PartyCompa rtyCompatibilit tibi lityTes yTest Lab Newton Developer Mailing na l –si x i ssues per year • Newton Technol ogy Jour nal • Newton Newton Developer CD –four fou r r eleases eleasesper year whic hi ch mayi mayi nclude: – Newton Sample Code – Newton ton Q & A’s – Newton System Software updates – Marketing and busi nessi nforma nformatition on • Appl Apple e Dir ections ection s –The Developer Busines Busin ess Report epor t • Newton Pl Pl atfor m News News& Information Savings on Hardware, Tools, Tools, a nd Training • Discountson development-related Apple hardware • Apple Newton development tool updates • Di scounte ounted rateson Apple’sonline servi ce • US $100Newton development traini training ng di scount
Annual feesare feesare $250.
NewtonPartners Program This hisexpert-level development support program helpsdeve helpsdevelopersc lopers create productsand ts and services ervi ces compatible ti ble with with N New ewton produc products. Newton Partners recei ve all Newton AssociatesProgram tes Program features, aswell asunlimi asunli mited ted programmi ng-level development support via vi a electronic troni c mai l, dis discounts on five fi ve additi dditiona onal N New ewton development units units, and partic partici pation in i n select marketing marketi ng opportuniti opportunities es. Wi th thi sprogram’ program’ sfocused approach to the deli delive very ry of Newton-s ton-speci fic fi c i nformation, nformati on, the Newton PartnersProgram, Partners Program, more than than ever, can help keep your proj ects on the fast trac track and reduce development development costs. Unlimited Expert Newt on Programming-level Support • O ne-to-one technical support via vi a e-mai l Apple Newton Hardware • Di scountson ountson five add addii tion ti ona al Newton development units
For Information on All Apple Developer Programs Pre-release Hardware and Software • Cons i de ration rati on a sa tes t s ite for prereleafor se Call the Developer Support Center Newton products informati nformation on or an appli applic cation. ation. Developersouts lopersoutside the United United States Market ing Activities A ctivities and Canada should hould contact thei theirr loca local • Pa rtic rti ci pa tion ti on in in sele ct Applespons oredloc marke Apple office for infor informati mation on about local al ti ng an d PR a c tivi ti viti ties es programs. All Newton Associat Associat es Program Features: Developer Support Support Center • Developer Support Center Service vi ces at lf-he (408) 974-4897 • Se lp tec hnical support Apple Computer nc.ili • New Ne wton Develope lope,rIma il i ng 1av I nfini nfi nite te Loop ,M /Stools 303-1 • S ing son hardw hardw are, , Pand trai ning
Cupert upertino, CA 95014-6299 Other • Developer Support Center Service vi ces • Developer conference i nvitations nvitations • Apple Developer veloper Unive Uni verr si ty Catal og • APDA Tools Cata Catall og
Apple Lin k: k:$15 DEVS UPPORT Annual Annu al feesare fees are 00. UPPORT