def _initHelpAgent( self ): # TO DO: need to check ASDictionary is version 0.9.0 or later try: apppath = aem.findapp.byid(self._kHelpAgentID) asdictionaryisrunning = aem.Application.processexistsforpath( apppath) self._helpAgent = aem.Application(apppath) if not asdictionaryisrunning: # hide ASDictionary after launching it # TO DO: something less kludgy aem.Application( aem.findapp.byid('com.apple.systemevents')).event( 'coresetd', { '----': aem.app.elements('prcs').byname( 'ASDictionary').property('pvis'), 'data': False }).send() sleep( 1 ) # KLUDGE: need a short delay here to workaround ASDictionary 0.9.0's event handling glitches # TO DO: delete after ASDictionary is fixed return True except aem.findapp.ApplicationNotFoundError: print >> sys.stderr, "No help available: ASDictionary application not found." except aem.CantLaunchApplicationError: print >> sys.stderr, "No help available: can't launch ASDictionary application." return False
def _inithelpagent(self): try: apppath = aem.findapp.byid(self.kHelpAgentBundleID) asdictionaryisrunning = aem.Application.processexistsforpath( apppath) self._helpagent = aem.Application(apppath) if not asdictionaryisrunning: # tell System Events hide ASDictionary after it's launched (kludgy, but does the job) aem.Application( aem.findapp.byid('com.apple.systemevents')).event( 'coresetd', { '----': aem.app.elements('prcs').byname( 'ASDictionary').property('pvis'), 'data': False }).send() self._helpagent.event( 'AppSHelp', { 'Cons': self.constructor, 'Iden': self.identifier, 'Styl': 'py-appscript', 'Flag': '-h', 'aRef': None, 'CNam': '' }).send() return True except aem.findapp.ApplicationNotFoundError: self._write( "No help available: ASDictionary application not found.") except aem.CantLaunchApplicationError: self._write( "No help available: can't launch ASDictionary application.") return False
def test_by_aem_app(self): a = appscript.app(aemapp=aem.Application('/Applications/TextEdit.app')) self.assertEqual(appscript.reference.Application, a.__class__) self.assertEqual(appscript.reference.Reference, a.name.__class__) self.assertEqual( "app(aemapp=aem.Application('/Applications/TextEdit.app'))", str(a))
def _target(klass): if not klass._rubyapp: klass._rubyproc = Popen( [klass._findrubyinterpreter(), klass._findrubyrenderer()]) klass._rubyapp = aem.Application(pid=klass._rubyproc.pid) return klass._rubyapp
def getaetedata(appname): if _osaxpathsbyname.has_key(appname.lower()): return getappterminology(_osaxpathsbyname[appname.lower()]) elif appname.startswith('eppc://'): return terminology.aetedataforapp(aem.Application(url=appname)) else: return getappterminology(aem.findapp.byname(appname))
def help(constructor, identity, style, flags, aemreference, commandname=''): id = (constructor, identity, style) if id not in _cache: if constructor == 'path': appobj = appscript.app(identity) elif constructor == 'pid': appobj = appscript.app(pid=identity) elif constructor == 'url': appobj = appscript.app(url=identity) elif constructor == 'aemapp': appobj = appscript.app(aemapp=aem.Application(desc=identity)) elif constructor == 'current': appobj = appscript.app() else: raise RuntimeError, 'Unknown constructor: %r' % constructor output = StringIO() helpobj = Help(appobj, style, output) _cache[id] = (appobj, helpobj, output) ref, helpobj, output = _cache[id] output.truncate(0) if aemreference is not None: ref = ref.AS_newreference(aemreference) if commandname: ref = getattr(ref, commandname) helpobj.help(flags, ref) s = output.getvalue() if NSUserDefaults.standardUserDefaults().boolForKey_(u'enableLineWrap'): res = [] textwrapper = textwrap.TextWrapper(width=NSUserDefaults.standardUserDefaults().integerForKey_(u'lineWrap'), subsequent_indent=' ' * 12) for line in s.split('\n'): res.append(textwrapper.fill(line)) s = u'\n'.join(res) return s
def test_6(self): sa = osax.OSAX( 'Standardadditions', aemapp=aem.Application("/System/Library/CoreServices/Finder.app/")) self.assertEqual(65, sa.ASCII_number('A')) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def _inithelpagent(self): try: apppath = aem.findapp.byid(self.kHelpAgentBundleID) self._helpagent = aem.Application(apppath, hide=True) return True except aem.findapp.ApplicationNotFoundError: self._write("No help available: ASDictionary application not found.") except aem.CantLaunchApplicationError: self._write("No help available: can't launch ASDictionary application.") return False
def test_6(self): sa = osax.OSAX( 'Standardadditions', aemapp=aem.Application("/System/Library/CoreServices/Finder.app/")) sa.activate() self.assertEqual({ osax.k.button_returned: '', osax.k.gave_up: True }, sa.display_dialog('test', giving_up_after=1)) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def makeappglue(appname, prefix, outdir, aetes=None): """ appname : str -- application name or path prefix : str -- ObjC classnam prefix, e.g. 'TE' outdir : str -- path to glue folder aetes : list of AEDesc | None -- if None, get aetes from specified application, otherwise use supplied list of aetes """ if aetes is None: appname = aem.findapp.byname(appname) aetes = _terminologytablebuilder.aetesforapp(aem.Application(appname)) builder = ClassBuilder(_terminologytablebuilder.tablesforaetes(aetes)) builder.render(ImplementationRenderer(appname, prefix, outdir))
def renderCommand(apppath, addressdesc, eventcode, targetref, directparam, paramsdict, resulttype, modeflags, timeout, appdata): global _appData # kludge; TO DO: eventformatter should pass aem objects to each renderer module _appData = appdata if not _formattercache.has_key((addressdesc.type, addressdesc.data)): typebycode, typebyname, referencebycode, referencebyname = \ _terminology.tablesforapp(aem.Application(desc=addressdesc)) _formattercache[(addressdesc.type, addressdesc.data)] = typebycode, referencebycode typebycode, referencebycode = _formattercache[(addressdesc.type, addressdesc.data)] appname = os.path.splitext(os.path.basename(apppath))[0] f = _Formatter(typebycode, referencebycode) appvar = 'app(%s)' % f.format(appname) if targetref and not isinstance(targetref, appscript.Application): f = _Formatter(typebycode, referencebycode, appvar) target = f.format(targetref) else: target = appvar try: commandname, paramnamebycode = referencebycode[kCommand + eventcode][1] except KeyError: raise UntranslatedKeywordError('event', eventcode, 'Ruby') args = [] f = _Formatter(typebycode, referencebycode, appvar, kNested) if directparam is not kNoParam: args.append(f.format(directparam)) for k, v in paramsdict.items(): try: args.append(':%s => %s' % (paramnamebycode[k], f.format(v))) except KeyError: raise UntranslatedKeywordError('parameter', k, 'Ruby') if resulttype: args.append(':result_type => %s' % f.format(resulttype)) if timeout != -1: args.append(':timeout => %i' % (timeout / 60)) if modeflags & 3 == aem.kae.kAENoReply: args.append(':wait_reply => false') if args: args = '(%s)' % ', '.join(args) else: args = '' return '%s.%s%s' % (target, commandname, args)
def _findosax(osaxname): """ locate a scripting addition by name """ se = aem.Application(aem.findapp.byid('com.apple.systemevents')) for domaincode in ['flds', 'fldl', 'fldu']: osax = aem.app.property(domaincode).property('$scr').elements( 'file').byfilter( aem.its.property('pnam').eq(osaxname).OR( aem.its.property('pnam').eq('%s.osax' % osaxname))).byindex(1) if se.event('coredoex', { '----': osax }).send(): # domain has ScriptingAdditions folder return se.event('coregetd', {'----': osax.property('posx')}).send() raise RuntimeError("Scripting addition %r not found." % osaxname)
def _initcaches(): _se = aem.Application(aem.findapp.byid('com.apple.systemevents')) for domaincode in [b'flds', b'fldl', b'fldu']: osaxen = aem.app.property(domaincode).property(b'$scr').elements(b'file').byfilter( aem.its.property(b'asty').eq('osax').OR(aem.its.property(b'extn').eq('osax'))) if _se.event(b'coredoex', {b'----': osaxen.property(b'pnam')}).send(): # domain has ScriptingAdditions folder names = _se.event(b'coregetd', {b'----': osaxen.property(b'pnam')}).send() paths = _se.event(b'coregetd', {b'----': osaxen.property(b'posx')}).send() for name, path in zip(names, paths): if name.lower().endswith('.osax'): # remove name extension, if any name = name[:-5] if name.lower() not in _osaxcache: _osaxnames.append(name) _osaxcache[name.lower()] = [path, None] _osaxnames.sort()
def _inithelpagent(self): try: apppath = aem.findapp.byid(self.kHelpAgentBundleID) asdictionaryisrunning = aem.Application.processexistsforpath( apppath) self._helpagent = aem.Application(apppath) if not asdictionaryisrunning: # tell System Events hide ASDictionary after it's launched (kludgy, but does the job) aem.Application( aem.findapp.byid('com.apple.systemevents')).event( 'coresetd', { '----': aem.app.elements('prcs').byname( 'ASDictionary').property('pvis'), 'data': False }).send() # KLUDGE: need to workaround problem where newly launched ASDictionary starts # to handle incoming events before custom event handlers have been installed) for _ in range(25): try: self._helpagent.event( 'AppSHelp', { 'Cons': self.constructor, 'Iden': self.identifier, 'Styl': 'py-appscript', 'Flag': '-h', 'aRef': None, 'CNam': '' }).send() except aem.EventError, e: if int(e) == -1708: sleep(0.2) else: raise return True
import AppKit from PyObjCTools import NibClassBuilder, AppHelper import osascript, aem import eventformatter NibClassBuilder.extractClasses("MainMenu") NibClassBuilder.extractClasses("ASTranslateDocument") _ci = osascript.Interpreter() _rendererscript = AppKit.NSBundle.mainBundle().pathForResource_ofType_('rubyrenderer', 'rb') _rubyproc = Popen(['ruby', _rendererscript]) _rubyapp = aem.Application(pid=_rubyproc.pid) ####### class ASApplicationDelegate(NibClassBuilder.AutoBaseClass): def applicationWillTerminate_(self, notification): try: _rubyapp.event('aevtquit').send() except: pass class ASTranslateDocument(NibClassBuilder.AutoBaseClass): # (NSDocument) # Outlets:
def unpackapplicationbydesc(self, desc): return app(aemapp=aem.Application(desc=desc))
def __init__(self, *args, **kargs): self._realApp = _aem.Application(*args, **kargs) self._repr = 'Application(%s)' % _fmt(args, kargs)
import appscript from appscript import terminology from aem.ae import getappterminology from osaterminology.dom import aeteparser, osadictionary from osaterminology.renderers import htmldoc, quickdoc from osaterminology.makeidentifier import getconverter import aem from aemreceive import * import appscriptsupport ####### _osaxpathsbyname = {} #_se = app(id='com.apple.systemevents') _se = aem.Application(aem.findapp.byid('com.apple.systemevents')) #for domain in [_se.system_domain, _se.local_domain, _se.user_domain]: for domain in ['flds', 'fldl', 'fldu']: # osaxen = domain.scripting_additions_folder.files[ # (its.file_type == 'osax').OR(its.name_extension == 'osax')] osaxen = aem.app.property(domain).property('$scr').elements( 'file').byfilter( aem.its.property('asty').eq('osax').OR( aem.its.property('extn').eq('osax'))) # for name, path in zip(osaxen.name(), osaxen.POSIX_path()): if _se.event('coredoex', { '----': osaxen.property('pnam') }).send(): # domain has ScriptingAdditions folder names = _se.event('coregetd', {'----': osaxen.property('pnam')}).send() paths = _se.event('coregetd', {'----': osaxen.property('posx')}).send() for name, path in zip(names, paths):
def renderCommand(apppath, addressdesc, eventcode, targetref, directparam, paramsdict, resulttype, modeflags, timeout, appdata): global _appData _appData = appdata try: if not _formatterCache.has_key((addressdesc.type, addressdesc.data)): typebycode, typebyname, referencebycode, referencebyname = \ _terminology.tablesforapp(aem.Application(desc=addressdesc)) _formatterCache[(addressdesc.type, addressdesc.data)] = typebycode, referencebycode typebycode, referencebycode = _formatterCache[(addressdesc.type, addressdesc.data)] appname = os.path.splitext(os.path.basename(apppath))[0] appvar = _convert(appname.lower()) prefix = makeprefix(appname) s = '// To create glue: osaglue -o %sGlue -p %s %s\n\n' % ( prefix, prefix, appname) f = _Formatter(typebycode, referencebycode, '', '') s += '%sApplication *%s = [%sApplication applicationWithName: %s];\n\n' % ( prefix, appvar, prefix, f.format(appname) ) # TO DO: use bundle ID if available commandname, paramnamebycode = referencebycode[kCommand + eventcode][1] if directparam is not None: f = _Formatter(typebycode, referencebycode, appvar, prefix) directparam = f.format(directparam) params = [] for k, v in paramsdict.items(): f = _Formatter(typebycode, referencebycode, appvar, prefix) params.append('%s: %s' % (paramnamebycode[k], f.format(v))) if targetref and not isinstance(targetref, appscript.Application): f = _Formatter(typebycode, referencebycode, appvar, prefix) s += '%sReference *ref = %s;\n\n' % (prefix, f.format(targetref)) target = 'ref' else: target = appvar if params or resulttype or modeflags != 0x1043 or timeout != -1: if eventcode == 'coresetd': # unlike py-appscript, objc-appscript doesn't special-case 'set' command's 'to' param, # so put it back in params list params = ['to: %s' % directparam] + params directparam = None classprefix = commandname[0].upper() + commandname[1:] if directparam: tmp = '[%s %s: %s]' % (target, commandname, directparam) else: tmp = '[%s %s]' % (target, commandname) for param in params: tmp = '[%s %s]' % (tmp, param) # args if resulttype: code = _codecs.unpack(appdata.pack(resulttype)).code tmp = '[%s requestedType: [ASConstant %s]]' % ( tmp, typebycode[code]) # .AS_name if timeout != -1: tmp = '[%s timeout: %i]' % (tmp, timeout / 60) if modeflags & 3 == aem.kae.kAENoReply: tmp = '[%s ignoreReply]' % tmp s += '%s%sCommand *cmd = %s;\n\n' % (prefix, classprefix, tmp) target = 'cmd' elif eventcode == 'coresetd': return s + 'id result = [%s setItem: %s];\n' % (target, directparam) elif eventcode == 'coregetd': return s + 'id result = [%s getItem];\n' % target else: target = '[%s %s]' % (target, commandname) s += 'id result = [%s send];\n' % target return s except Exception, e: import traceback return '%s\n\n%s' % (e, traceback.format_exc())
#!/usr/bin/python import types, datetime, os.path, re import aem, appscript from appscript import mactypes from osaterminology import makeidentifier from osaterminology.tables.tablebuilder import * ####### _formatterCache = {} _self = aem.Application() _codecs = aem.Codecs() _convert = makeidentifier.getconverter('objc-appscript') _terminology = TerminologyTableBuilder('objc-appscript') ###################################################################### # PRIVATE ###################################################################### class _Formatter: def __init__(self, typebycode, referencebycode, appvar, prefix, indent=''): self._referencebycode = referencebycode self._typebycode = typebycode self._prefix = prefix self._indent = indent self._valueFormatters = { types.NoneType: self.formatNone,
def _unpackApplicationByDesc(desc, codecs): return app(aemapp=aem.Application(desc=desc))
#!/usr/local/bin/python3.0 import aem # Get name of application "TextEdit" textedit = aem.Application('/Applications/TextEdit.app') print(textedit.event(b'coregetd', {b'----': aem.app.property(b'pnam')}).send()) # Get list of items in home folder as mactype.Alias objects: finder = aem.Application(aem.findapp.byname('Finder')) print( finder.event( b'coregetd', { b'----': aem.app.property(b'home').elements(b'cobj'), aem.kae.keyAERequestedType: aem.AEType(aem.kae.typeAlias), }).send())