PageRenderTime 102ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/plat-mac/aetools.py

https://bitbucket.org/dac_io/pypy
Python | 363 lines | 352 code | 0 blank | 11 comment | 1 complexity | 06566220c7fd13975b19271692f1c1d8 MD5 | raw file
  1. """Tools for use in AppleEvent clients and servers.
  2. pack(x) converts a Python object to an AEDesc object
  3. unpack(desc) does the reverse
  4. packevent(event, parameters, attributes) sets params and attrs in an AEAppleEvent record
  5. unpackevent(event) returns the parameters and attributes from an AEAppleEvent record
  6. Plus... Lots of classes and routines that help representing AE objects,
  7. ranges, conditionals, logicals, etc., so you can write, e.g.:
  8. x = Character(1, Document("foobar"))
  9. and pack(x) will create an AE object reference equivalent to AppleScript's
  10. character 1 of document "foobar"
  11. Some of the stuff that appears to be exported from this module comes from other
  12. files: the pack stuff from aepack, the objects from aetypes.
  13. """
  14. from warnings import warnpy3k
  15. warnpy3k("In 3.x, the aetools module is removed.", stacklevel=2)
  16. from types import *
  17. from Carbon import AE
  18. from Carbon import Evt
  19. from Carbon import AppleEvents
  20. import MacOS
  21. import sys
  22. import time
  23. from aetypes import *
  24. from aepack import packkey, pack, unpack, coerce, AEDescType
  25. Error = 'aetools.Error'
  26. # Amount of time to wait for program to be launched
  27. LAUNCH_MAX_WAIT_TIME=10
  28. # Special code to unpack an AppleEvent (which is *not* a disguised record!)
  29. # Note by Jack: No??!? If I read the docs correctly it *is*....
  30. aekeywords = [
  31. 'tran',
  32. 'rtid',
  33. 'evcl',
  34. 'evid',
  35. 'addr',
  36. 'optk',
  37. 'timo',
  38. 'inte', # this attribute is read only - will be set in AESend
  39. 'esrc', # this attribute is read only
  40. 'miss', # this attribute is read only
  41. 'from' # new in 1.0.1
  42. ]
  43. def missed(ae):
  44. try:
  45. desc = ae.AEGetAttributeDesc('miss', 'keyw')
  46. except AE.Error, msg:
  47. return None
  48. return desc.data
  49. def unpackevent(ae, formodulename=""):
  50. parameters = {}
  51. try:
  52. dirobj = ae.AEGetParamDesc('----', '****')
  53. except AE.Error:
  54. pass
  55. else:
  56. parameters['----'] = unpack(dirobj, formodulename)
  57. del dirobj
  58. # Workaround for what I feel is a bug in OSX 10.2: 'errn' won't show up in missed...
  59. try:
  60. dirobj = ae.AEGetParamDesc('errn', '****')
  61. except AE.Error:
  62. pass
  63. else:
  64. parameters['errn'] = unpack(dirobj, formodulename)
  65. del dirobj
  66. while 1:
  67. key = missed(ae)
  68. if not key: break
  69. parameters[key] = unpack(ae.AEGetParamDesc(key, '****'), formodulename)
  70. attributes = {}
  71. for key in aekeywords:
  72. try:
  73. desc = ae.AEGetAttributeDesc(key, '****')
  74. except (AE.Error, MacOS.Error), msg:
  75. if msg[0] != -1701 and msg[0] != -1704:
  76. raise
  77. continue
  78. attributes[key] = unpack(desc, formodulename)
  79. return parameters, attributes
  80. def packevent(ae, parameters = {}, attributes = {}):
  81. for key, value in parameters.items():
  82. packkey(ae, key, value)
  83. for key, value in attributes.items():
  84. ae.AEPutAttributeDesc(key, pack(value))
  85. #
  86. # Support routine for automatically generated Suite interfaces
  87. # These routines are also useable for the reverse function.
  88. #
  89. def keysubst(arguments, keydict):
  90. """Replace long name keys by their 4-char counterparts, and check"""
  91. ok = keydict.values()
  92. for k in arguments.keys():
  93. if k in keydict:
  94. v = arguments[k]
  95. del arguments[k]
  96. arguments[keydict[k]] = v
  97. elif k != '----' and k not in ok:
  98. raise TypeError, 'Unknown keyword argument: %s'%k
  99. def enumsubst(arguments, key, edict):
  100. """Substitute a single enum keyword argument, if it occurs"""
  101. if key not in arguments or edict is None:
  102. return
  103. v = arguments[key]
  104. ok = edict.values()
  105. if v in edict:
  106. arguments[key] = Enum(edict[v])
  107. elif not v in ok:
  108. raise TypeError, 'Unknown enumerator: %s'%v
  109. def decodeerror(arguments):
  110. """Create the 'best' argument for a raise MacOS.Error"""
  111. errn = arguments['errn']
  112. err_a1 = errn
  113. if 'errs' in arguments:
  114. err_a2 = arguments['errs']
  115. else:
  116. err_a2 = MacOS.GetErrorString(errn)
  117. if 'erob' in arguments:
  118. err_a3 = arguments['erob']
  119. else:
  120. err_a3 = None
  121. return (err_a1, err_a2, err_a3)
  122. class TalkTo:
  123. """An AE connection to an application"""
  124. _signature = None # Can be overridden by subclasses
  125. _moduleName = None # Can be overridden by subclasses
  126. _elemdict = {} # Can be overridden by subclasses
  127. _propdict = {} # Can be overridden by subclasses
  128. __eventloop_initialized = 0
  129. def __ensure_WMAvailable(klass):
  130. if klass.__eventloop_initialized: return 1
  131. if not MacOS.WMAvailable(): return 0
  132. # Workaround for a but in MacOSX 10.2: we must have an event
  133. # loop before we can call AESend.
  134. Evt.WaitNextEvent(0,0)
  135. return 1
  136. __ensure_WMAvailable = classmethod(__ensure_WMAvailable)
  137. def __init__(self, signature=None, start=0, timeout=0):
  138. """Create a communication channel with a particular application.
  139. Addressing the application is done by specifying either a
  140. 4-byte signature, an AEDesc or an object that will __aepack__
  141. to an AEDesc.
  142. """
  143. self.target_signature = None
  144. if signature is None:
  145. signature = self._signature
  146. if type(signature) == AEDescType:
  147. self.target = signature
  148. elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
  149. self.target = signature.__aepack__()
  150. elif type(signature) == StringType and len(signature) == 4:
  151. self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
  152. self.target_signature = signature
  153. else:
  154. raise TypeError, "signature should be 4-char string or AEDesc"
  155. self.send_flags = AppleEvents.kAEWaitReply
  156. self.send_priority = AppleEvents.kAENormalPriority
  157. if timeout:
  158. self.send_timeout = timeout
  159. else:
  160. self.send_timeout = AppleEvents.kAEDefaultTimeout
  161. if start:
  162. self._start()
  163. def _start(self):
  164. """Start the application, if it is not running yet"""
  165. try:
  166. self.send('ascr', 'noop')
  167. except AE.Error:
  168. _launch(self.target_signature)
  169. for i in range(LAUNCH_MAX_WAIT_TIME):
  170. try:
  171. self.send('ascr', 'noop')
  172. except AE.Error:
  173. pass
  174. else:
  175. break
  176. time.sleep(1)
  177. def start(self):
  178. """Deprecated, used _start()"""
  179. self._start()
  180. def newevent(self, code, subcode, parameters = {}, attributes = {}):
  181. """Create a complete structure for an apple event"""
  182. event = AE.AECreateAppleEvent(code, subcode, self.target,
  183. AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
  184. packevent(event, parameters, attributes)
  185. return event
  186. def sendevent(self, event):
  187. """Send a pre-created appleevent, await the reply and unpack it"""
  188. if not self.__ensure_WMAvailable():
  189. raise RuntimeError, "No window manager access, cannot send AppleEvent"
  190. reply = event.AESend(self.send_flags, self.send_priority,
  191. self.send_timeout)
  192. parameters, attributes = unpackevent(reply, self._moduleName)
  193. return reply, parameters, attributes
  194. def send(self, code, subcode, parameters = {}, attributes = {}):
  195. """Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
  196. return self.sendevent(self.newevent(code, subcode, parameters, attributes))
  197. #
  198. # The following events are somehow "standard" and don't seem to appear in any
  199. # suite...
  200. #
  201. def activate(self):
  202. """Send 'activate' command"""
  203. self.send('misc', 'actv')
  204. def _get(self, _object, asfile=None, _attributes={}):
  205. """_get: get data from an object
  206. Required argument: the object
  207. Keyword argument _attributes: AppleEvent attribute dictionary
  208. Returns: the data
  209. """
  210. _code = 'core'
  211. _subcode = 'getd'
  212. _arguments = {'----':_object}
  213. if asfile:
  214. _arguments['rtyp'] = mktype(asfile)
  215. _reply, _arguments, _attributes = self.send(_code, _subcode,
  216. _arguments, _attributes)
  217. if 'errn' in _arguments:
  218. raise Error, decodeerror(_arguments)
  219. if '----' in _arguments:
  220. return _arguments['----']
  221. if asfile:
  222. item.__class__ = asfile
  223. return item
  224. get = _get
  225. _argmap_set = {
  226. 'to' : 'data',
  227. }
  228. def _set(self, _object, _attributes={}, **_arguments):
  229. """set: Set an object's data.
  230. Required argument: the object for the command
  231. Keyword argument to: The new value.
  232. Keyword argument _attributes: AppleEvent attribute dictionary
  233. """
  234. _code = 'core'
  235. _subcode = 'setd'
  236. keysubst(_arguments, self._argmap_set)
  237. _arguments['----'] = _object
  238. _reply, _arguments, _attributes = self.send(_code, _subcode,
  239. _arguments, _attributes)
  240. if _arguments.get('errn', 0):
  241. raise Error, decodeerror(_arguments)
  242. # XXXX Optionally decode result
  243. if '----' in _arguments:
  244. return _arguments['----']
  245. set = _set
  246. # Magic glue to allow suite-generated classes to function somewhat
  247. # like the "application" class in OSA.
  248. def __getattr__(self, name):
  249. if name in self._elemdict:
  250. cls = self._elemdict[name]
  251. return DelayedComponentItem(cls, None)
  252. if name in self._propdict:
  253. cls = self._propdict[name]
  254. return cls()
  255. raise AttributeError, name
  256. # Tiny Finder class, for local use only
  257. class _miniFinder(TalkTo):
  258. def open(self, _object, _attributes={}, **_arguments):
  259. """open: Open the specified object(s)
  260. Required argument: list of objects to open
  261. Keyword argument _attributes: AppleEvent attribute dictionary
  262. """
  263. _code = 'aevt'
  264. _subcode = 'odoc'
  265. if _arguments: raise TypeError, 'No optional args expected'
  266. _arguments['----'] = _object
  267. _reply, _arguments, _attributes = self.send(_code, _subcode,
  268. _arguments, _attributes)
  269. if 'errn' in _arguments:
  270. raise Error, decodeerror(_arguments)
  271. # XXXX Optionally decode result
  272. if '----' in _arguments:
  273. return _arguments['----']
  274. #pass
  275. _finder = _miniFinder('MACS')
  276. def _launch(appfile):
  277. """Open a file thru the finder. Specify file by name or fsspec"""
  278. _finder.open(_application_file(('ID ', appfile)))
  279. class _application_file(ComponentItem):
  280. """application file - An application's file on disk"""
  281. want = 'appf'
  282. _application_file._propdict = {
  283. }
  284. _application_file._elemdict = {
  285. }
  286. # Test program
  287. # XXXX Should test more, really...
  288. def test():
  289. target = AE.AECreateDesc('sign', 'quil')
  290. ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
  291. print unpackevent(ae)
  292. raw_input(":")
  293. ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
  294. obj = Character(2, Word(1, Document(1)))
  295. print obj
  296. print repr(obj)
  297. packevent(ae, {'----': obj})
  298. params, attrs = unpackevent(ae)
  299. print params['----']
  300. raw_input(":")
  301. if __name__ == '__main__':
  302. test()
  303. sys.exit(1)