1"""
2Minimal applescript support.
3
4The PyDocEventHandler handles just the event that is used to open URLs. Thanks
5to this class you can use ``open pydoc:///os.open`` from a command-line, or
6add ``pydoc:///`` to HTML files.
7"""
8from Foundation import *
9
10from Carbon.AppleEvents import kAEISGetURL, kAEInternetSuite
11import struct
12import objc
13
14def fourCharToInt(code):
15    return struct.unpack('>l', code)[0]
16
17class PyDocEventHandler (NSObject):
18    webview = objc.IBOutlet('webview')
19    urlfield = objc.IBOutlet('urlfield')
20
21    def handleEvent_withReplyEvent_(self, event, replyEvent):
22        theURL = event.descriptorForKeyword_(fourCharToInt('----'))
23
24        self.urlfield.setStringValue_(theURL.stringValue())
25        self.webview.takeStringURLFrom_(theURL)
26
27
28    def awakeFromNib(self):
29        manager = NSAppleEventManager.sharedAppleEventManager()
30
31        # Add a handler for the event GURL/GURL. One might think that
32        # Carbon.AppleEvents.kEISInternetSuite/kAEISGetURL would work,
33        # but the system headers (and hence the Python wrapper for those)
34        # are wrong.
35        manager.setEventHandler_andSelector_forEventClass_andEventID_(
36            self, 'handleEvent:withReplyEvent:',
37                fourCharToInt('GURL'),
38                fourCharToInt('GURL'))
39