tags:

views:

168

answers:

2

When writing an OS X Bundle application (.app), how can I get the name of the document that caused the application to be launched?

Say I've associated .abcd with MyApp, when I click on foo.abcd MyApp is launched. How can I get the foo.abcd from inside MyApp? (Command line arguments only contain the process id).

+1  A: 

In general, these are handled through Apple Events. Specifically, your application will receive an open document event. How you would handle it depends on what type of application you are writing.

If you're writing a document-based app, this is easy: the document controller receives an openDocumentWithContentsOfURL:display:error: message (or openDocumentWithContentsOfFile:display: for pre-Tiger systems), and will handle this accordingly.

For Cocoa apps that aren't document based, the application delegate will be sent an application:openFiles: message. If the delegate doesn't respond to that, it will try sending other messages until the delegate responds to one (openTempFile:, openFiles:, and openFile:, in that order).

Here's the documentation for handling Open Apple Events in Cocoa.

For Carbon apps, I can't really remember the details (been a while since I've written Carbon code), but if I recall correctly, you would install an Apple Event handler for kAEOpenDocuments events with AEInstallEventHandler(). See the documentation for more details.

htw
Thanks!However in my case it's just a shell script (Python), is there a way to get it from there?
lazy1
I'm not sure how to handle Apple Events with Python, actually. I found this though—hope it helps: http://wiki.python.org/moin/MacPython/AppleEvents
htw
A: 

It looks like you need a GUI toolkit for that, there is an example in idlelib/macosxSupport.py

def doOpenFile(*args):
    for fn in args:
        flist.open(fn)

# The command below is a hook in aquatk that is called whenever the app
# receives a file open event. The callback can have multiple arguments,
# one for every file that should be opened.
root.createcommand("::tk::mac::OpenDocument", doOpenFile)

Qt also has support for that.

lazy1