1"""argvemulator - create sys.argv from OSA events. Used by applets that 2want unix-style arguments. 3""" 4 5from warnings import warnpy3k 6warnpy3k("In 3.x, the argvemulator module is removed.", stacklevel=2) 7 8import sys 9import traceback 10from Carbon import AE 11from Carbon.AppleEvents import * 12from Carbon import Evt 13from Carbon import File 14from Carbon.Events import * 15import aetools 16 17class ArgvCollector: 18 19 """A minimal FrameWork.Application-like class""" 20 21 def __init__(self): 22 self.quitting = 0 23 # Remove the funny -psn_xxx_xxx argument 24 if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn': 25 del sys.argv[1] 26 27 AE.AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, self.__runapp) 28 AE.AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, self.__openfiles) 29 30 def close(self): 31 AE.AERemoveEventHandler(kCoreEventClass, kAEOpenApplication) 32 AE.AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments) 33 34 def mainloop(self, mask = highLevelEventMask, timeout = 1*60): 35 # Note: this is not the right way to run an event loop in OSX or even 36 # "recent" versions of MacOS9. This is however code that has proven 37 # itself. 38 stoptime = Evt.TickCount() + timeout 39 while not self.quitting and Evt.TickCount() < stoptime: 40 self._dooneevent(mask, timeout) 41 42 if not self.quitting: 43 print "argvemulator: timeout waiting for arguments" 44 45 self.close() 46 47 def _dooneevent(self, mask = highLevelEventMask, timeout = 1*60): 48 got, event = Evt.WaitNextEvent(mask, timeout) 49 if got: 50 self._lowlevelhandler(event) 51 52 def _lowlevelhandler(self, event): 53 what, message, when, where, modifiers = event 54 h, v = where 55 if what == kHighLevelEvent: 56 try: 57 AE.AEProcessAppleEvent(event) 58 except AE.Error, err: 59 msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) 60 print 'AE error: ', err 61 print 'in', msg 62 traceback.print_exc() 63 return 64 else: 65 print "Unhandled event:", event 66 67 68 def _quit(self): 69 self.quitting = 1 70 71 def __runapp(self, requestevent, replyevent): 72 self._quit() 73 74 def __openfiles(self, requestevent, replyevent): 75 try: 76 listdesc = requestevent.AEGetParamDesc(keyDirectObject, typeAEList) 77 for i in range(listdesc.AECountItems()): 78 aliasdesc = listdesc.AEGetNthDesc(i+1, typeAlias)[1] 79 alias = File.Alias(rawdata=aliasdesc.data) 80 fsref = alias.FSResolveAlias(None)[0] 81 pathname = fsref.as_pathname() 82 sys.argv.append(pathname) 83 except Exception, e: 84 print "argvemulator.py warning: can't unpack an open document event" 85 import traceback 86 traceback.print_exc() 87 88 self._quit() 89 90if __name__ == '__main__': 91 ArgvCollector().mainloop() 92 print "sys.argv=", sys.argv 93