home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 May / maximum-cd-2010-05.iso / DiscContents / boxee-0.9.20.10711.exe / system / python / Lib / plat-mac / aetools.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-07-20  |  11.1 KB  |  374 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. '''Tools for use in AppleEvent clients and servers.
  5.  
  6. pack(x) converts a Python object to an AEDesc object
  7. unpack(desc) does the reverse
  8.  
  9. packevent(event, parameters, attributes) sets params and attrs in an AEAppleEvent record
  10. unpackevent(event) returns the parameters and attributes from an AEAppleEvent record
  11.  
  12. Plus...  Lots of classes and routines that help representing AE objects,
  13. ranges, conditionals, logicals, etc., so you can write, e.g.:
  14.  
  15.     x = Character(1, Document("foobar"))
  16.  
  17. and pack(x) will create an AE object reference equivalent to AppleScript\'s
  18.  
  19.     character 1 of document "foobar"
  20.  
  21. Some of the stuff that appears to be exported from this module comes from other
  22. files: the pack stuff from aepack, the objects from aetypes.
  23.  
  24. '''
  25. from types import *
  26. from Carbon import AE
  27. from Carbon import Evt
  28. from Carbon import AppleEvents
  29. import MacOS
  30. import sys
  31. import time
  32. from aetypes import *
  33. from aepack import packkey, pack, unpack, coerce, AEDescType
  34. Error = 'aetools.Error'
  35. LAUNCH_MAX_WAIT_TIME = 10
  36. aekeywords = [
  37.     'tran',
  38.     'rtid',
  39.     'evcl',
  40.     'evid',
  41.     'addr',
  42.     'optk',
  43.     'timo',
  44.     'inte',
  45.     'esrc',
  46.     'miss',
  47.     'from']
  48.  
  49. def missed(ae):
  50.     
  51.     try:
  52.         desc = ae.AEGetAttributeDesc('miss', 'keyw')
  53.     except AE.Error:
  54.         msg = None
  55.         return None
  56.  
  57.     return desc.data
  58.  
  59.  
  60. def unpackevent(ae, formodulename = ''):
  61.     parameters = { }
  62.     
  63.     try:
  64.         dirobj = ae.AEGetParamDesc('----', '****')
  65.     except AE.Error:
  66.         pass
  67.  
  68.     parameters['----'] = unpack(dirobj, formodulename)
  69.     del dirobj
  70.     
  71.     try:
  72.         dirobj = ae.AEGetParamDesc('errn', '****')
  73.     except AE.Error:
  74.         pass
  75.  
  76.     parameters['errn'] = unpack(dirobj, formodulename)
  77.     del dirobj
  78.     while None:
  79.         key = missed(ae)
  80.         if not key:
  81.             break
  82.         
  83.         parameters[key] = unpack(ae.AEGetParamDesc(key, '****'), formodulename)
  84.     attributes = { }
  85.     for key in aekeywords:
  86.         
  87.         try:
  88.             desc = ae.AEGetAttributeDesc(key, '****')
  89.         except (AE.Error, MacOS.Error):
  90.             msg = None
  91.             if msg[0] != -1701 and msg[0] != -1704:
  92.                 raise 
  93.                 continue
  94.             continue
  95.  
  96.         attributes[key] = unpack(desc, formodulename)
  97.     
  98.     return (parameters, attributes)
  99.  
  100.  
  101. def packevent(ae, parameters = { }, attributes = { }):
  102.     for key, value in parameters.items():
  103.         packkey(ae, key, value)
  104.     
  105.     for key, value in attributes.items():
  106.         ae.AEPutAttributeDesc(key, pack(value))
  107.     
  108.  
  109.  
  110. def keysubst(arguments, keydict):
  111.     '''Replace long name keys by their 4-char counterparts, and check'''
  112.     ok = keydict.values()
  113.     for k in arguments.keys():
  114.         if keydict.has_key(k):
  115.             v = arguments[k]
  116.             del arguments[k]
  117.             arguments[keydict[k]] = v
  118.             continue
  119.         if k != '----' and k not in ok:
  120.             raise TypeError, 'Unknown keyword argument: %s' % k
  121.             continue
  122.     
  123.  
  124.  
  125. def enumsubst(arguments, key, edict):
  126.     '''Substitute a single enum keyword argument, if it occurs'''
  127.     if not arguments.has_key(key) or edict is None:
  128.         return None
  129.     
  130.     v = arguments[key]
  131.     ok = edict.values()
  132.     if edict.has_key(v):
  133.         arguments[key] = Enum(edict[v])
  134.     elif v not in ok:
  135.         raise TypeError, 'Unknown enumerator: %s' % v
  136.     
  137.  
  138.  
  139. def decodeerror(arguments):
  140.     """Create the 'best' argument for a raise MacOS.Error"""
  141.     errn = arguments['errn']
  142.     err_a1 = errn
  143.     if arguments.has_key('errs'):
  144.         err_a2 = arguments['errs']
  145.     else:
  146.         err_a2 = MacOS.GetErrorString(errn)
  147.     if arguments.has_key('erob'):
  148.         err_a3 = arguments['erob']
  149.     else:
  150.         err_a3 = None
  151.     return (err_a1, err_a2, err_a3)
  152.  
  153.  
  154. class TalkTo:
  155.     '''An AE connection to an application'''
  156.     _signature = None
  157.     _moduleName = None
  158.     _elemdict = { }
  159.     _propdict = { }
  160.     __eventloop_initialized = 0
  161.     
  162.     def __ensure_WMAvailable(klass):
  163.         if klass._TalkTo__eventloop_initialized:
  164.             return 1
  165.         
  166.         if not MacOS.WMAvailable():
  167.             return 0
  168.         
  169.         Evt.WaitNextEvent(0, 0)
  170.         return 1
  171.  
  172.     __ensure_WMAvailable = classmethod(__ensure_WMAvailable)
  173.     
  174.     def __init__(self, signature = None, start = 0, timeout = 0):
  175.         '''Create a communication channel with a particular application.
  176.  
  177.         Addressing the application is done by specifying either a
  178.         4-byte signature, an AEDesc or an object that will __aepack__
  179.         to an AEDesc.
  180.         '''
  181.         self.target_signature = None
  182.         if signature is None:
  183.             signature = self._signature
  184.         
  185.         if type(signature) == AEDescType:
  186.             self.target = signature
  187.         elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
  188.             self.target = signature.__aepack__()
  189.         elif type(signature) == StringType and len(signature) == 4:
  190.             self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
  191.             self.target_signature = signature
  192.         else:
  193.             raise TypeError, 'signature should be 4-char string or AEDesc'
  194.         self.send_flags = AppleEvents.kAEWaitReply
  195.         self.send_priority = AppleEvents.kAENormalPriority
  196.         if timeout:
  197.             self.send_timeout = timeout
  198.         else:
  199.             self.send_timeout = AppleEvents.kAEDefaultTimeout
  200.         if start:
  201.             self._start()
  202.         
  203.  
  204.     
  205.     def _start(self):
  206.         '''Start the application, if it is not running yet'''
  207.         
  208.         try:
  209.             self.send('ascr', 'noop')
  210.         except AE.Error:
  211.             _launch(self.target_signature)
  212.             for i in range(LAUNCH_MAX_WAIT_TIME):
  213.                 
  214.                 try:
  215.                     self.send('ascr', 'noop')
  216.                 except AE.Error:
  217.                     pass
  218.  
  219.                 break
  220.                 time.sleep(1)
  221.             
  222.  
  223.  
  224.     
  225.     def start(self):
  226.         '''Deprecated, used _start()'''
  227.         self._start()
  228.  
  229.     
  230.     def newevent(self, code, subcode, parameters = { }, attributes = { }):
  231.         '''Create a complete structure for an apple event'''
  232.         event = AE.AECreateAppleEvent(code, subcode, self.target, AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
  233.         packevent(event, parameters, attributes)
  234.         return event
  235.  
  236.     
  237.     def sendevent(self, event):
  238.         '''Send a pre-created appleevent, await the reply and unpack it'''
  239.         if not self._TalkTo__ensure_WMAvailable():
  240.             raise RuntimeError, 'No window manager access, cannot send AppleEvent'
  241.         
  242.         reply = event.AESend(self.send_flags, self.send_priority, self.send_timeout)
  243.         (parameters, attributes) = unpackevent(reply, self._moduleName)
  244.         return (reply, parameters, attributes)
  245.  
  246.     
  247.     def send(self, code, subcode, parameters = { }, attributes = { }):
  248.         '''Send an appleevent given code/subcode/pars/attrs and unpack the reply'''
  249.         return self.sendevent(self.newevent(code, subcode, parameters, attributes))
  250.  
  251.     
  252.     def activate(self):
  253.         """Send 'activate' command"""
  254.         self.send('misc', 'actv')
  255.  
  256.     
  257.     def _get(self, _object, as = None, _attributes = { }):
  258.         '''_get: get data from an object
  259.         Required argument: the object
  260.         Keyword argument _attributes: AppleEvent attribute dictionary
  261.         Returns: the data
  262.         '''
  263.         _code = 'core'
  264.         _subcode = 'getd'
  265.         _arguments = {
  266.             '----': _object }
  267.         if as:
  268.             _arguments['rtyp'] = mktype(as)
  269.         
  270.         (_reply, _arguments, _attributes) = self.send(_code, _subcode, _arguments, _attributes)
  271.         if _arguments.has_key('errn'):
  272.             raise Error, decodeerror(_arguments)
  273.         
  274.         if _arguments.has_key('----'):
  275.             return _arguments['----']
  276.             if as:
  277.                 item.__class__ = as
  278.             
  279.             return item
  280.         
  281.  
  282.     get = _get
  283.     _argmap_set = {
  284.         'to': 'data' }
  285.     
  286.     def _set(self, _object, _attributes = { }, **_arguments):
  287.         """set: Set an object's data.
  288.         Required argument: the object for the command
  289.         Keyword argument to: The new value.
  290.         Keyword argument _attributes: AppleEvent attribute dictionary
  291.         """
  292.         _code = 'core'
  293.         _subcode = 'setd'
  294.         keysubst(_arguments, self._argmap_set)
  295.         _arguments['----'] = _object
  296.         (_reply, _arguments, _attributes) = self.send(_code, _subcode, _arguments, _attributes)
  297.         if _arguments.get('errn', 0):
  298.             raise Error, decodeerror(_arguments)
  299.         
  300.         if _arguments.has_key('----'):
  301.             return _arguments['----']
  302.         
  303.  
  304.     set = _set
  305.     
  306.     def __getattr__(self, name):
  307.         if self._elemdict.has_key(name):
  308.             cls = self._elemdict[name]
  309.             return DelayedComponentItem(cls, None)
  310.         
  311.         if self._propdict.has_key(name):
  312.             cls = self._propdict[name]
  313.             return cls()
  314.         
  315.         raise AttributeError, name
  316.  
  317.  
  318.  
  319. class _miniFinder(TalkTo):
  320.     
  321.     def open(self, _object, _attributes = { }, **_arguments):
  322.         '''open: Open the specified object(s)
  323.         Required argument: list of objects to open
  324.         Keyword argument _attributes: AppleEvent attribute dictionary
  325.         '''
  326.         _code = 'aevt'
  327.         _subcode = 'odoc'
  328.         if _arguments:
  329.             raise TypeError, 'No optional args expected'
  330.         
  331.         _arguments['----'] = _object
  332.         (_reply, _arguments, _attributes) = self.send(_code, _subcode, _arguments, _attributes)
  333.         if _arguments.has_key('errn'):
  334.             raise Error, decodeerror(_arguments)
  335.         
  336.         if _arguments.has_key('----'):
  337.             return _arguments['----']
  338.         
  339.  
  340.  
  341. _finder = _miniFinder('MACS')
  342.  
  343. def _launch(appfile):
  344.     '''Open a file thru the finder. Specify file by name or fsspec'''
  345.     _finder.open(_application_file(('ID  ', appfile)))
  346.  
  347.  
  348. class _application_file(ComponentItem):
  349.     """application file - An application's file on disk"""
  350.     want = 'appf'
  351.  
  352. _application_file._propdict = { }
  353. _application_file._elemdict = { }
  354.  
  355. def test():
  356.     target = AE.AECreateDesc('sign', 'quil')
  357.     ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
  358.     print unpackevent(ae)
  359.     raw_input(':')
  360.     ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
  361.     obj = Character(2, Word(1, Document(1)))
  362.     print obj
  363.     print repr(obj)
  364.     packevent(ae, {
  365.         '----': obj })
  366.     (params, attrs) = unpackevent(ae)
  367.     print params['----']
  368.     raw_input(':')
  369.  
  370. if __name__ == '__main__':
  371.     test()
  372.     sys.exit(1)
  373.  
  374.