The following paper was originally published in the Proceedings of the Fifth Annual Tcl/Tk Workshop Boston, Massachusetts, July 1997

TclOSAScript - Exec for MacTcl

Jim Ingham Lucent Technologies (now at Sun Microsystems) Raymond Johnson Sun Microsystems

For more information about USENIX Association contact: 1. Phone: 510 528-8649 2. FAX: 510 548-5738 3. Email: [email protected] 4. WWW URL: http://www.usenix.org TclOSAScript-ExecforMacTcl

JimIngham LucentTechnologies (nowatSunMicrosystems) [email protected]

RaymondJohnson SunMicrosystems [email protected]

Abstract:

WedescribetheTclOSAScriptextensiontoMacTcl.TclOSAScriptprovides theabilityforMacTclscriptstorunscriptsinanyotherOSAcompatible languageonthe.SincetheOSAisthestandardmechanismfor interapplicationcommunicationontheMac,thisallowsMacTcltorunother applications,andprovidesanexeclikefacility(thougharguablyusingamuch richercommunicationmodel.)

I) AnIntroductiontotheOpen Tk95and96conferences[3,4].Therearetwo ScriptingArchitecture implementationsofthissolutionthathavebeen presented.TedBeldungwroteaextensioncalled Theusualinterapplicationcommunicationmecha- ASTcl[5]whichonlyworkedwithAppleScript,and nismforUnixbasedtoolsreliesonthesimpleex- didnotusemanyoftheadvancedfeaturestheOSA pedientofconnectingthestandardinandstan- offers.TclOSAScript,whichwasdevelopedcon- dardoutchannelsofthespawnedprocesstochan- currently,isamorecompleteimplementation.This nelsoftheparentprocess.Thecommunication istheonewewilldetailinthispaper. betweentheparentandchildprocessesthenmim- ThereisarealproblemthattheOSAaimstosolve icstheuserinteractionwiththeprocess,namely aswell–beyondthefactthattheremaywellnot typingcommandsonthecommandline.The beatextbasedcommandinterfacetotasksina “exec”commandinTcl,aswellastheopen-with- modernGUIoperatingsystem.Forwhilethecom- pipecommand,usethismechanismtogiveTclac- mand-basedformofcommunicationiseasyto cesstoprocessesinthesurroundingsystem. implement,toactuallydriveanapplicationyou Thismethod,unfortunately,isinapplicableon needtoknowtheparticularlanguagethattheap- Macintoshsystems.Macintoshapplicationsare plicationuses,beitsimplecommandlineswitches, onlyimplementedwithaGraphicalUserInterface orareallanguagesuchasTcl.Thereisnogeneric (GUI).Thereisnocommandline,andthusno waytoexposethefunctionalelementsofanappli- conceptofstandardinandstandardout.How- cationwithouttyingthemtoaparticularscripting ever,thisdoesnotmeanthereisnointerapplication language. communicationmechanism.Instead,amuchricher Thesolutionistodefinethebasicobjectsandverbs methodofscriptingexternaltasksisprovidedby thattheapplicationsupportsinalanguageneutral theOpenScriptingArchitecture(OSA)[1,2]. way.Thenthescriptinglanguagemustprovidea Thisproblem,andtheOSAsolutionpresentedhere, mechanismforqueryingouttheseelements.Fi- werefirstmentionedinpapersintheUsenixTcl/ nally,theoperatingsystemwillprovideamessag- ingsystemthatwillallowanyscriptinglanguage OneapplicationundertheMacOSsendsanApple todrivetheobjectsofthetargetapplication. Eventtoanotherapplicationbybuildingupthe AppleEventdatastructure,andthenpassingitto theAppleEventManager,whichplacestheevent a)SpecificationofVerbs&Objects–theaete intheeventqueueofthetargetapplication.The Thespecificationofobjectsisachievedwiththe targetapplicationthenhandlesthiseventbypars- AppleEventTerminologyExtension.Thisisaresource ingupitscontentsandperformingtherequired intheresourceforkoftheapplicationwhichlists task. the‘events’towhichtheapplicationresponds,and theclassesofobjectsintheapplication. c)OSAcompliantlanguages Examplesofeventsthatanapplicationmightrec- Allinterapplicationcommunicationiscarriedout, get set create ognizearethe‘ ’,‘ ’and‘ ’events, underthehood,bytheexchangeofAppleEvents. whichjustprovideaccesstotheobjectsintheap- However,thisistoolowlevelanexchangemecha- plication.Theseformpartofthe“StandardSuite” nismtobeusefultotheaverageuser. ofcommandsthatallwelldesignedOSAapplica- tionsshouldsupport.Therearealsomorespecial- ThejobofanOSAcompliantlanguage,then,isto izedverbs,suchas‘select’or‘revert’inaWord wrapamorehumansyntaxaroundtheconstruc- Processorappor‘ download’and‘ view file tionoftheAppleEventmessages.Theapproved list’intheFTPclientapplicationFetch.Events methodfordoingthisistoreadtheaeteofatarget alsotakeparameters,suchaswhichwordtoselect application,andimporttheverbsandnounsfound inawordprocessor,orwhichfiletodownloadin thereinintoitsownsyntaxinanaturalway.Done Fetch. thisway,theaetecanserveasdocumentationfor howtoscripteachlanguage,andthelanguagecan Examplesofobjectsarethewindowsofanapplica- dynamicallyappropriatenewapplicationsasthey tion,orthewordsandparagraphsinawordpro- areencountered. cessorwindow.Thereisalsoawayofspecifyinga containmenthierarchy,soeachobjectcanbecon- OfthetwomajorOSAcompliantlanguages,only tainedinotherobjects,andcancontainotherob- AppleScript[6]dynamicallyreadstheaeteofthe jects,.Finally,theobjectsmaytakequalifiers.An targetapplication.UserLandFrontier[7]hasastatic exampleofamoderatelycomplicatedobjectspeci- gluetableforeachapplicationthatrelatestheevent fier,inAppleScriptdialect,is:“ the file andobjectcodeswithcommandsintheFrontier “mactcltk-full-8.0a2” in the transfer language.Thislimitsthenumberofscriptableap- window “ftp.sunlabs.com” of the appli- plicationsthatFrontiercanactuallydrive. cation “Fetch 3.0.2””. Theaetemakestheconnectionbetweenthetext d)OSAComponents phrasewhichspecifiesanobjectorverb,andsome ThefinalpartoftheOSAarchitectureistheOSA packed4charactercodewhichwilloccurinthe component.Thisisanimplementationoftheno- compiledformoftheinterapplicationmessages.It tionthatascriptinglanguageisnotsomuchapart alsospecifiestheparametersfortheverbs(with oftheapplication,asaservicethatisprovidedto thenotionofrequiredandoptionalparameters), applications,toaidtheminexposingtheir- andthecontainmenthierarchyoftheobjects.Once tiveparts. youknowtheaeteofanapplication,youknowthe formanymessagetothatapplicationmusttake. Tclhasbeenverysuccessfulpreciselybecauseit makesiteasytobindtogetherthefunctionalele- b)TheMessagingsystem–AppleEvents mentsoftheapplicationwithouthavingto recompiletheapplication.ButtomakeuseofTcl, ThemessagingsystemintheOSAisgovernedby theapplicationmustembedaTclinterpreterwithin theAppleEventManager.AnAppleEventisa theobjectcodeoftheapplication.Thistiesthe datastructurethatdescribesaneventintermsof useoftheapplicationtoTcl;youcannotdynami- theaforementionedpacked4charactercodes.It callychoosewhichscriptinglanguageyouwantto startswiththemainverb,andthenusuallyhasa employ. directobjectwithitsqualifiers,andperhapsother parameters.AppleEventssupportnesting,sothat TheOSAgoesfurthertomaketheoperatingsys- asingleeventcansupportrecursiveevaluation temthemanagerofscriptingsolutions.Thepro- (muchlikethe[]syntaxinTcl). viderofascriptinglanguagewritessomegluecode thatregistersthescriptinglanguagewiththeoper- atingsystem.Applicationsrequestaconnectionto atedbythatcomponent.Currentlyconnections thescriptingcomponent,andthensendscriptdata tobothofthepopularOSAlanguages,AppleScript tothatcomponenttobeevaluated.Thescriptdata andUserLandFrontierhavebeentested. canevencontaintagsidentifyingitslanguage,so TclOSAScriptwillbeincludedasashareablelibrary thattheapplicationcanreceivescriptingdatain inthe8.0releaseofMacTcl.Whatfollowsisa anyoftheavailablelanguages,passittotheOSA generaldescriptionoftheTclOSAScriptextension. componentmanager,whichwillinturnrouteitto theappropriatecomponent. 1)TheOSAcommand Thisconnectioncanbeusedintwoways.Oneis ThefirststepinusinganyOSAcomponentisto toallowanapplicationtodriveotherapplications, getaconnectiontoaninstanceofthecomponent. sothatitdoesnothavetoduplicatetheirfunc- Atstartup,TclOSAScriptscansthelistofOSAcom- tionality.AgoodexampleofthisistheMicroSoft ponents,opensaconnectiontoeachonethatis InternetExplorer,whichhandsoffe-mail,FTPand found,andcreatesaTclcommandtoaccessthat NNTPrequeststotheuser’sfavoritee-mail,FTP component.SoiftheuserhasAppleScriptinstalled andUsenetclientsusingtheOSA. ontheirmachine,anAppleScriptcommandwill AdeeperuseoftheOSAisto“factor”theuser becreated.IfUserLandFrontierisrunningat interfaceelementsoftheapplicationfromitscore startup,a UserLand commandwillbecreated, functionality.Theuserinterfaceelementsdonot andsoon. directlycallthesubroutinesthatdotheworkof Thereisalsoagenericcommand, OSA,thatwill theapplication.RathertheysendAppleEventsback allowotherconnectionstobeopened,orclosed, totheapplication,whichreceivestheseevents,and andwillallowtheusertoquerythelistofcompo- thendispatchesthemtotheappropriateinternal nents.Thisisuseful,forinstance,toopenconnec- routines. tionswithotherlanguages. Theadvantageofthisisthatyoucanthen“attach” Anexampleofthisuseiscommunicationwiththe scriptstotheUIelements,whichscriptsdothe UserLandlanguage.TheUserLandOSAcompo- workofdispatchingtheAppleEvents.Thisimme- nentisinstalledonlywhiletheFrontierapplica- diatelyprovidesanarchitecturemuchlike tionisrunning.SoifyouwantedtouseFrontier, HyperCard,ortheTcl/Tkcallbacks,butwiththe youcouldopenit(byusingtheAppleScriptcom- addedbenefitthatthecallbacklanguageisleftup mand),andthenusetheOSAcommandtoopena totheuser’sdiscretion. connectiontotheUserLandcomponent... Itiscurrentlynotusefultoopenmultipleconnec- II) TclandtheOSA tionstothesamecomponent.Sincethecallsto theOSAcomponentsaresynchronous,havingsev- eralconnectionstoasingleOSAcomponentdoes TherearethreestepstofitTclintotheOSAarchi- notgainanything. tecture.ThefirstistoallowTcltousetheservices offeredbytheOSAcomponentsinstalledonthe system.ThisisthefunctionoftheTclOSAScript 2)CompilingandExecutingScripts: extensionwhichisdescribedintherestofthispa- Onceyouhaveanopencomponent,youcansend per.Thenexttwostepshavenotyetbeencom- scriptstoit,tobeexecuted.Thesimplestwayto pleted.ThefirstoftheseistoprovideaTclcom- dothisiswiththeexecutesubcommand(seefrag- mandtobuildanddispatchAppleEvents.The ment1): finalstepistoinstallTcl/TkasanOSAcom- ponentinitsownright,sothatTclwouldbe anoptioninallthemajorScriptingdevelop- AppleScript execute { mentenvironments. tell application "Fetch 3.0.2" download (url "ftp://" & ¬ "ftp.sunlabs.com" & ¬ TclOSAScript "/pub/tcl/mac/" & ¬ "mactcltk-full-8.0a2.sea.hqx") Thefirststageofthisincorporationiscom- end tell pleted.TheTclOSAScriptextensionallows } TclscriptstoconnecttoanyavailableOSA component,andsendscriptsofftobeevalu- Fragment1 set getNewFiles [AppleScript compile { tell application "Fetch 3.0.2" open (url "ftp://ftp.sunlabs.com/pub/tcl/mac") set thisWin to (transfer window “ftp.sunlabs.com”) set nfiles to (count remote item in thisWin) set retVal to {} repeat with i from 1 to nfiles if the modification date of (remote item i of thisWin) > refDate then download (remote item i of thisWin) end if end repeat end tell get retVal }] AppleScript execute {set refDate to (date "Saturday, February 1, 1997 3:19:02 PM")} button .b -text "Check for files" -command "AppleScript run $getNewFiles" pack .b -padx 6 -pady 6

Fragment2

“AppleScript execute”lineinFragment2will settherefDatevariablewhichthegetNewFiles ThiswillexecuteascriptthatusestheMacappli- scriptusesinitsexecution. cation“Fetch”togetthe8.0a2versionofmactcltk fromtheSunftpsite... Notethatalthoughthenotionofascriptcontext isapartoftheOSAspecification,itisnotoneof However,complicatedscriptscantakesometime therequiredparts.So,forinstance,UserLandFron- tocompile,soifyouwanttorunthesamescript tierdoesnotusethem.Ithasitsownmechanism overandover,youmightwanttocompilethescript forpersistence(theobjectdatabase). once,andthenrunitmanytimes.Forthispur- pose,thereisacompile/runpairofsubcommands. BecauseTclandthecodewithintheAppleScript commandsarejuststrings,wecancombinethetwo IntheexampleinFragment2,wemakeabutton languagesforevenmorepower.Asanexamplelet’s whoseactionistodownloadallthefilesinthe/ extendtheaboveexampletoalwaysusethecur- pub/tcl/macdirectorywhosedateislaterthanthe renttimeinsteadofasetdate.Thefollowingcode somereferencedate(chosenprettymuchatran- usesdoublequotestoallowTclbasedsubstitution domhere...): tooccurbeforetheAppleScript commandcom- The“AppleScript compile”commandpasses pilesthestringintoAppleScriptbytecodes. thescripttoAppleScripttocompile,andreturnsa TheexampleinFragment3willgetthecurrent scripthandleforthecompiledscript.Thishandle secondsandformatthetimeintoastringthatis AppleScript run canbepassedtothe“ ”com- acceptablefortheAppleScriptdatecommand.You mand,whichwillexecutethescript,andreturn mustbecareful,however,whendoingsuchcombi- whatevervaluethescriptreturns. nationstomakesureyoucreateavalidAppleScript command.AgoodunderstandingofTcl’squoting 3)OtherTricks conventionsisrequired. Wehavealsousedanother trickofTclOSAScript,to AppleScript execute "set refDate to (date \"[clock format \ definethevariablerefDate. [clock seconds] -format \"%A, %B %d, %Y %X %p\"]\")" AppleScriptexecutesits scriptsin“ Scriptcontexts ”, Fragment3 whicharejustnamespaces thatretainallthevariables andproceduresthataredefinedinthem.The 4)ReturnValues AppleScript commandopensadefaultcontext Oneotherissueisthereturnvaluesthatcomeback whichitusesforallscriptexecution.Sothe fromAppleScript.Supposethatwewanttoex- … set scriptRsrc [AppleScript load $scriptFile] AppleScript run $scriptRsrc … button .f2.view -text "Display Files" -command loadList

proc loadList {} { global hostName filePath refDate scriptRsrc .f1.lf.lb delete 0 end AppleScript execute -variable retList -context $scriptRsrc \ "listMoreRecent(\"$hostName\",\"$filePath\",date \"$refDate\")" eval .f1.lf.lb insert 0 $retList }

button .f2.load -text "Download" -command {getFiles}

proc getFiles {} { global hostName filePath scriptRsrc foreach index [.f1.lf.lb curselection] { set name [.f1.lf.lb get $index] AppleScript execute -context $scriptRsrc \ "getFiles(\"$hostName\",\"$filePath\",\{\"$name\"\})" } }

Fragment4 pandthefollowingexampletoquerythe/pub/tcl/ customizationforTclapplications.Forinstance,a macdirectory,andpresentalistofnewfilestothe MacTclapplicationcouldreadthescriptresources user,sothatshecanchoosewhichonestodown- outofallthefilesina“Scripts”folder,andpopu- load.Thenwecouldwriteasubroutinein latethe“Scripts”menuintheapplicationwith AppleScriptthatreturnedalistofnewfiles. them. However,thiswillbereturnedasanAppleScript Usingastoredscript,containingtwoAppleScript formattedlist,notaTclFormattedlist.Nowsome- subroutineslistMoreRecentandgetFiles,wecancre- timesyoumayneedtheAppleScriptformat(e.g. atetheapplicationshowninFigure1andFrag- topassbacktoAppleScript).Atothertimesthe ment4,whichwilldisplaythenewfilesinthegiven Tclformatismoreappropriate. directory,anddownloadtheoneschoseninthelist. IntypicalTclfashion,thewholeapplicationis60 InTclOSAScript,thereturnvalueoftheruncom- linesofTcl,and24linesofAppleScriptcode… mandistheAppleScriptformoftheresult.Then wehaveaddeda“-value”flagtotherunand executecommands.Youuseittopassthe nameofavariabletothecommand,and TclOSAScriptwillparseAppleScriptlistsup intoTcllists,andAppleScriptRecordsintoTcl arrays,andputtheresultinthatvariable.

5)LoadingScripts Finally,Tclisnotthemostconvenientsitefor developingAppleScriptcode.Ratherthan havetocutandpastefromtheScriptEditor intoTcl,TclOSAScripthasa“load”command thatwillloadscriptdatafromascriptresource (whichistheformatalltheAppleScriptde- velopmentenvironmentswriteout),eitherin theapplicationitself,oranauxiliaryfile. Thisfacilityallowsforusefulmethodsofuser Figure1 III) Futurework withthesortofsophisticatedfront-endthatcanso easilybecreatedinTcl/Tk.Withthenativelook- TheTclOSAScriptextensionisalmostcomplete. and-feelofversion8.0,thepowerofTcl/Tkwill Itwouldperhapsbeusefultoprovideanasynchro- proveasvaluableontheMacintoshasithasin nousmodeofexecution(analogoustoexec with UNIX. an &)Anothermajorenhancementwouldbeto makeeachcomponentcommandruninaseparate thread.Thenitwouldbeusefultoopenaconnec- References tionto,say,theAppleScriptcomponent,sendita long-runningscript.Thenopenanotherconnec- tionifyouhavesomeworktobedonebeforethe [1] AppleComputer firsttaskiscompleted. InsideMacintosh-InterapplicationCommunication AddisonWesleyPublishingCorporation,1993 Asidefromthesedetails,thereremaintwopartsof thecompleteincorporationofTclintotheOSA scheme.Thefirstremainingstepistoprovidea [2] DaveMark facilitytoparsetheaeteoftargetapplications,and UltimateMacProgramming aTclbasedmechanismfordispatchingAppleEvents IDGBooksWorldWideInc,1994 basedontheverbsandobjectsfoundtherein. [3] Johnson,R.andStantonS. Parsingtheaeteisrelativelystraightforward.How- “CrossPlatformSupportinTk” ever,definingaTclrepresentationforAppleEvents InProc:UsenixTcl/TkWorkshop,Toronto, willrequiremorework.Thenestingofobjectsthat Ontario,Canada,1995. isrequiredtospecifyelementsinatargetapplica- tioncanrequiretheconstructionofAppleEvents [4] Ingham,J. ofconsiderablecomplexity.Forinstance,wemight “Tcl/TkasanOpenDocScriptingPart” wanttoqueryout“Everyparagraphofthefirst InProc:UsenixTcl/TkWorkshop, windowoftheapplication“WordPerfect”whose Montery,California,1996. fontis“TimesRoman”andwhosefirstwordis [5] TedBelding “Foo””.TheequivalentTclsyntaxwillhavetobe richenoughtomirrorthat. ASTcl. ThelaststepistoprovideTclasanOSAcompo- http://www-personal.engin.umich.edu/~streak/ nent.Aproofofconceptimplementationwasdone ASTcl-1.0.sea.hqx byVinceDarley[8],butthiswaswithoutTk,and [6] DannyGoodman didnotaddressmanyissuesthatwillbefacedbya DannyGoodman’sAppleScriptHandbook fullimplementation. SecondEdition RandomHouse,1994 [7] DaveWiner IV) Summary UserLandFrontier http://www.scripting.com/frontier/ Theworkthatwehavedonesofar,the [8] VinceDarley TclOSAScriptextension,hasgivenTcltheability OSATcl totakeadvantageoftheotherapplicationsinthe http://www.fas.harvard.edu/~darley/Vince- Macintoshenvironment.Ourexamplejustused Downloads. theFTPclientprogramFetch,buttherearemany otherpowerfulscriptableapplicationsavailable, includingFileMakerPro,QuarkExpress,andboth andMSIE,tomentionjustafew.This richnessisnowavailabletothewritersofMacTcl applications. Conversely,theOSAscriptornowhasavailablethe TkGUItoolkitwhichhasprovedagreatboonin theUNIXworld.Manyoftheworkflowapplica- tionsthathavetraditionallybeenwrittenin AppleScriptandFrontiercannowbeaugmented