« | Home | »

When Open Does Not Return An Object Reference

There is a long standing bug in Cocoa Scripting, the technology Apple provides to developers to help make their applications scriptable, where the Open, Move and Copy commands do not return a reference to the newly created or moved object. This makes scripting these applications difficult.

I frequently get requests from Script Debugger customers for help solving this problem. I see people resorting to UI Scripting and many other techniques to address this problem.

The code below shows one way of working around the problem of the Open command not returning a reference to the newly opened document. I use the Preview application in my code, but this technique works equally well with other applications which fail to return a document reference from their Open commands. This technique fails is the file is already open.

set theFile to choose file — pick a file to open

tell application “Preview”

   set theOldOpenFiles to path of documents — sample the existing open documents

   open theFile — no new document reference returned – sigh

   set theOpenFiles to path of documents — sample the new list of open documents

end tell

—   Find the item in the list of new open documents that is not present in the old list of 

—   open documents.

set theNewFiles to finddifference of theOpenFiles against theOldOpenFiles

tell application “Preview”

   —  recover the reference to the newly opened document

   set theOpenedDocument to first document where path is (item 1 of theNewFiles)


   tell theOpenedDocument

      —  your code targetting the newly opened document goes here…

      set theDocumentName to name

   end tell

end tell

to finddifference of listA against listB

   —  This handler computes the ‘difference’ between the contents of two lists

   local newList


   set newList to {}

   repeat with a in listA

      set a to contents of a — dereference implicit loop reference

      if {a} is not in listB then set end of newList to a

   end repeat


end finddifference

About this entry