Automation with F-Script

KosmicTask Help

Automation with F-Script

Automation with F-Script Cocoa

Our previous examples have focussed on using the various Cocoa bridges support by KosmicTask. F-Script is not so much a Cocoa bridge as a Cocoa scripting language in its own right. It is written in Cocoa and its distinct syntax has been designed to allow quick and easy manipulation of Cocoa objects. If you want to create complex tasks that manipulate a lot of Cocoa objects then F-Script is a great choice.

No surprise then that we can recompose our Pages task in F-Script.

[:pagesDocFilePath |

  "load the ScriptingBridge framework"
  (NSBundle bundleWithPath:'/System/Library/Frameworks/ScriptingBridge.framework') load.

  " use the ScriptingBridge framework to access the application "
  app := SBApplication applicationWithBundleIdentifier:'com.apple.iWork.pages'.
  rtfDocFilePath := pagesDocFilePath ++ '.rtf'.

  "open pages"
  myDoc := app open:pagesDocFilePath.

  "save document"
  myDoc saveAs:'SLDocumentTypeRichText' in:rtfDocFilePath.

  "close document"
  myDoc closeSaving:(NSNumber numberWithBool:NO) savingIn:nil.

  " get our kosmicTaskController "
  taskController := KosmicTaskController.

   " form our file result path"
   " this file will be automatically deleted when the task ends."
  resultFile := taskController resultFileWithName: 'result.html'.

  " convert our file "
  args := {'-convert', 'html', '-output', resultFile, rtfDocFilePath}.
  task := NSTask launchedTaskWithLaunchPath:'/usr/bin/textutil' arguments:args.
  task waitUntilExit.

  " return result dictionary "
  #{'kosmicFile' -> resultFile}.
]

F-Script executes blocks as opposed to functions. In the example our task block is defined by the enclosing square braces [ ... ]. This outermost block accepts a single argument - pagesDocFilePath. As in our other examples we start by loading the ScriptingBridge framework except this time we use the Cocoa NSBundle class as the loader.

The KosmicTaskController object is also referenced in order to obtain our result file path. F-Script implements a shorthand literal notation for arrays and dictionaries. F-script functions return the value of the last statement evaluated in the enclosing block. In this case it's the literal dictionary returning our result file.