Automation with AppleScript Cocoa

KosmicTask Help

Automation with AppleScript Cocoa

Automation with AppleScript Cocoa

We began our series of automation examples with an AppleScript example. KosmicTask also provides support for scripting tasks in AppleScriptObjC which provides a bridge between AppleScript and Cocoa.

An AppleScriptCocoa task can perform all the functions of a regular AppleScript task including returning AppleScript objects as results. However AppleScriptCocoa tasks can interact with the Cocoa framework as demonstrated in this AppleScriptObjC implementation of our Pages task:

-- KosmicTask controller
property taskController : class "KosmicTaskController"

script KosmicTask
  property parent : class "NSObject"
  property NSTask : class "NSTask"

  on KosmicTask(pagesDocFilePath)
      -- we need a path to save our RTF document file into.
      -- the easy way is simply to append .rtf to our existing file path
      set rtfDocFilePath to pagesDocFilePath & ".rtf"

      -- save our pages document as RTF
      tell application "Pages"
        set myDoc to open pagesDocFilePath
        save myDoc as "SLDocumentTypeRichText" in rtfDocFilePath
        close myDoc saving no
      end tell

      -- get result file path
      set resultFile to (taskController's resultFileWithName_("result.html")) as string

      -- build our command
      set theArgs to {"-convert", "html", "-output", resultFile, rtfDocFilePath}

      -- run task
      set theTask to NSTask's launchedTaskWithLaunchPath_arguments_("/usr/bin/textutil", theArgs)
      theTask's waitUntilExit()

      -- return file result
      return {kosmicFile:resultFile, kosmicInfo:"file returned"}

    on error errorMessage number errorNumber
      return {kosmicError:errorMessage}
    end try
  end KosmicTask
end script

When comparing the above example to the original AppleScript implementation the points to note are:

  • The KosmicTaskController object is declared as a script property.
  • The AppleScript script object itself is a subclass of Cocoa's NSObject.
  • The temporary file path is retrieved directly from the task controller rather than from the KosmicTask application.
  • The textutil program is launched using an instance of the Cocoa NSTask object rather than the AppleScript do shell script command. This is an implementation detail that has the same effect in either case.