1#!/usr/bin/python
2"""
3This script is a daemon that will open the ReadMe file in the root of any
4(removable) volume that is inserted while this script is running.
5
6The script is part of an article at MAcDevCenter:
7    http://www.macdevcenter.com/pub/a/mac/2003/01/31/pyobjc_one.html
8
9Usage:
10    python autoreadme.py
11"""
12import sys
13import os
14import re
15
16from AppKit import *
17from Foundation import *
18from PyObjCTools import AppHelper
19
20
21readTheseFiles = re.compile('(.*read\s*me.*|.*release.*note.*|^about.*)', re.I)
22
23class NotificationHandler(NSObject):
24    """
25    Class that handles the mount notifications
26    """
27
28    def handleMountNotification_(self, aNotification):
29
30        # Find the path to the just inserted volume
31        path = aNotification.userInfo()['NSDevicePath']
32
33        for aFile in os.listdir(path):
34            if readTheseFiles.match(aFile):
35                # Found a readme file, try to open it using the Workspace API
36
37                fullPath = os.path.join(path, aFile)
38                success, app, None = workspace.getInfoForFile_application_type_(
39                        fullPath)
40                if not success:
41                    NSLog("Failed to find application to open file %s",
42                        fullPath)
43                    return
44                workspace.openFile_withApplication_(fullPath, app)
45
46# Create an instance of our notification handler, and ask the workspace
47# notification center to tell us when a new volume is mounted.
48workspace = NSWorkspace.sharedWorkspace()
49notificationCenter = workspace.notificationCenter()
50notificationHandler = NotificationHandler.new()
51notificationCenter.addObserver_selector_name_object_(
52    notificationHandler,
53    "handleMountNotification:",
54    NSWorkspaceDidMountNotification,
55    None)
56
57NSLog("Listening for mount notifications....")
58AppHelper.runConsoleEventLoop()
59