Esempio n. 1
0
    def __init__(self):
        self.preffilepath = os.path.join("Python",
                                         "Package Install Manager Prefs")
        Wapplication.Application.__init__(self, 'Pimp')
        from Carbon import AE
        from Carbon import AppleEvents
        self.defaulturl = ""

        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEOpenApplication,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEReopenApplication,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEPrintDocuments,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEQuitApplication,
                                 self.quitevent)
        if 1:
            import PyConsole
            # With -D option (OSX command line only) keep stderr, for debugging the IDE
            # itself.
            debug_stderr = None
            if len(sys.argv) >= 2 and sys.argv[1] == '-D':
                debug_stderr = sys.stderr
                del sys.argv[1]
            PyConsole.installoutput()
            if debug_stderr:
                sys.stderr = debug_stderr
        self.domenu_openstandard()
        self.mainloop()
Esempio n. 2
0
        def __init__(self):
            self.quitting = 0

            AE.AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
                                     self.__runapp)
            AE.AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
                                     self.__openfiles)
Esempio n. 3
0
 def __init__(self):
     self.quitting = 0
     if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn':
         del sys.argv[1]
     AE.AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
                              self.__runapp)
     AE.AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
                              self.__openfiles)
Esempio n. 4
0
def mac_show(bundle_id):
    target = AE.AECreateDesc(AppleEvents.typeApplicationBundleID, bundle_id)
    activateEvent = AE.AECreateAppleEvent('misc', 'actv', target,
                                          AppleEvents.kAutoGenerateReturnID,
                                          AppleEvents.kAnyTransactionID)
    activateEvent.AESend(AppleEvents.kAEWaitReply,
                         AppleEvents.kAENormalPriority,
                         AppleEvents.kAEDefaultTimeout)
Esempio n. 5
0
def test():
    target = AE.AECreateDesc('sign', 'quil')
    ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
    print unpackevent(ae)
    raw_input(":")
    ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
    obj = Character(2, Word(1, Document(1)))
    print obj
    print repr(obj)
    packevent(ae, {'----': obj})
    params, attrs = unpackevent(ae)
    print params['----']
    raw_input(":")
Esempio n. 6
0
        def __init__(self):
            self.quitting = 0

            AE.AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
                                     self.__runapp)
            AE.AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
                                     self.__openfiles)
            AE.AEInstallEventHandler(kAEInternetSuite, kAEISGetURL,
                                     self.__geturl)

            # The definition of kAEInternetSuite seems to be wrong,
            # the lines below ensures that the code will work anyway.
            AE.AEInstallEventHandler('GURL', 'GURL', self.__geturl)
def run(command):
    termAddress = AE.AECreateDesc(typeApplicationBundleID,
                                  'com.apple.Terminal')
    theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
                                     kAutoGenerateReturnID, kAnyTransactionID)
    commandDesc = AE.AECreateDesc(typeChar, command)
    theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
    try:
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
    except AE.Error as why:
        if why[0] != -600:
            raise
        os.system(START_TERMINAL)
        time.sleep(1)
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
Esempio n. 8
0
    def __init__(self, signature=None, start=0, timeout=0):
        """Create a communication channel with a particular application.

        Addressing the application is done by specifying either a
        4-byte signature, an AEDesc or an object that will __aepack__
        to an AEDesc.
        """
        self.target_signature = None
        if signature is None:
            signature = self._signature
        if type(signature) == AEDescType:
            self.target = signature
        elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
            self.target = signature.__aepack__()
        elif type(signature) == StringType and len(signature) == 4:
            self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
            self.target_signature = signature
        else:
            raise TypeError, "signature should be 4-char string or AEDesc"
        self.send_flags = AppleEvents.kAEWaitReply
        self.send_priority = AppleEvents.kAENormalPriority
        if timeout:
            self.send_timeout = timeout
        else:
            self.send_timeout = AppleEvents.kAEDefaultTimeout
        if start:
            self._start()
Esempio n. 9
0
    def newevent(self, code, subcode, parameters = {}, attributes = {}):
        """Create a complete structure for an apple event"""

        event = AE.AECreateAppleEvent(code, subcode, self.target,
                  AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
        packevent(event, parameters, attributes)
        return event
Esempio n. 10
0
def run(command):
    """Run a shell command in a new Terminal.app window."""
    termAddress = AE.AECreateDesc(typeApplSignature, TERMINAL_SIG)
    theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
                                     kAutoGenerateReturnID, kAnyTransactionID)
    commandDesc = AE.AECreateDesc(typeChar, command)
    theEvent.AEPutParamDesc(kAECommandClass, commandDesc)

    try:
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
    except AE.Error, why:
        if why[0] != -600:  # Terminal.app not yet running
            raise
        os.system(START_TERMINAL)
        time.sleep(1)
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
Esempio n. 11
0
def focuswindow(window):
    """Focuses the provided window"""
    if window is None:
        pass
    actevent = AE.AECreateAppleEvent('misc', 'actv', window,
                                     AppleEvents.kAutoGenerateReturnID,
                                     AppleEvents.kAnyTransactionID)
    actevent.AESend(AppleEvents.kAEWaitReply, AppleEvents.kAENormalPriority,
                    AppleEvents.kAEDefaultTimeout)
Esempio n. 12
0
    def __init__(self):
        if sys.platform == "darwin":
            if len(sys.argv) > 1 and sys.argv[1].startswith("-psn"):
                home = os.getenv("HOME")
                if home:
                    os.chdir(home)
        self.preffilepath = os.path.join("Python", "PythonIDE preferences")
        Wapplication.Application.__init__(self, 'Pide')
        from Carbon import AE
        from Carbon import AppleEvents

        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEOpenApplication,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEReopenApplication,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEPrintDocuments,
                                 self.ignoreevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEOpenDocuments,
                                 self.opendocsevent)
        AE.AEInstallEventHandler(AppleEvents.kCoreEventClass,
                                 AppleEvents.kAEQuitApplication,
                                 self.quitevent)
        import PyConsole, PyEdit
        Splash.wait()
        # With -D option (OSX command line only) keep stderr, for debugging the IDE
        # itself.
        debug_stderr = None
        if len(sys.argv) >= 2 and sys.argv[1] == '-D':
            debug_stderr = sys.stderr
            del sys.argv[1]
        PyConsole.installoutput()
        PyConsole.installconsole()
        if debug_stderr:
            sys.stderr = debug_stderr
        for path in sys.argv[1:]:
            if path.startswith("-p"):
                # process number added by the OS
                continue
            self.opendoc(path)
        self.mainloop()
Esempio n. 13
0
    def main(self):
        pool = NSAutoreleasePool.alloc().init()
        NSLog("editing thread started for %s" % self.path)
        NSLog("shell command: %@", EDITOR_COMMAND % {'linenum': self.linenum, 'filename': self.path.replace("'","'\"'\"'")})

        stdin = open('/dev/null','r')
        stdout = open('/dev/null','w')
        subprocess.call(EDITOR_COMMAND % {'linenum': self.linenum, 'filename': self.path.replace("'","'\"'\"'")},
                        shell=True, stdin=stdin, stdout=stdout, stderr=stdout)
        #os.system(EDITOR_COMMAND % {'linenum':self.linenum, 'filename':self.path})

        # Send the "file closed" ODB event.
        if self.odb_app:
            NSLog("sending file closed event to %s, %s" % (self.odb_app, type(self.odb_app)))

            target = AE.AECreateDesc(AppleEvents.typeApplSignature, self.odb_app[::-1])  # For strange endianness reasons, have to reverse this
            event = AE.AECreateAppleEvent(kODBEditorSuite, kAEClosedFile, target, AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)

            if self.odb_token:
                event.AEPutParamDesc(keySenderToken, pack(self.odb_token, typeWildcard))

            fsr = Carbon.File.FSPathMakeRef(self.path)[0].encode('utf-8')
            event.AEPutParamDesc(AppleEvents.keyDirectObject, pack(fsr))

            event.AESend(AppleEvents.kAENoReply, AppleEvents.kAENormalPriority, AppleEvents.kAEDefaultTimeout)

            #evt_app = NSAppleEventDescriptor.descriptorWithTypeCode_(fourcc(self.odb_app))
            #evt = NSAppleEventDescriptor.appleEventWithEventClass_eventID_targetDescriptor_returnID_transactionID_(fourcc(kODBEditorSuite),
            #                                                                                                       fourcc(kAEClosedFile),
            #                                                                                                       evt_app,
            #                                                                                                       -1, # kAutoGenerateReturnID
            #                                                                                                       0) # kAnyTransactionID
            #if self.odb_token:
            #    evt_tok = NSAppleEventDescriptor.descriptorWithDescriptorType_data_(fourcc('****'), self.odb_token)
            #    evt.setParamDescriptor_forKeyword_(evt_tok, fourcc(keySenderToken))
            #
            #fsr = objc.FSRef.from_pathname(self.path).data
            #evt_path = NSAppleEventDescriptor.descriptorWithDescriptorType_bytes_length_(fourcc('fsrf'),fsr,len(fsr))
            #evt.setParamDescriptor_forKeyword_(evt_path, fourcc('----'))

        NSLog("editing thread finished for %s" % self.path)
        del pool
Esempio n. 14
0
 def _lowlevelhandler(self, event):
     what, message, when, where, modifiers = event
     h, v = where
     if what == kHighLevelEvent:
         try:
             AE.AEProcessAppleEvent(event)
         except AE.Error, err:
             msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16)))
             print 'AE error: ', err
             print 'in', msg
             traceback.print_exc()
         return
 def __init__(self):
     self.quitting = 0
     self.ae_handlers = {}
     # Remove the funny -psn_xxx_xxx argument
     import sys
     if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn':
         del sys.argv[1]
     ehandlers = (
         (AEc.kAEOpenApplication, self.open_app),
         (AEc.kAEOpenDocuments, self.open_file),
         (AEc.kAEReopenApplication, self.reopen_app),
         (AEc.kAEQuitApplication, self.quit_app),
         (AEc.kAEApplicationDied, self.launched_app_died),
     )
     for etype, cb in ehandlers:
         AE.AEInstallEventHandler(AEc.kCoreEventClass, etype, cb)
Esempio n. 16
0
    def lowlevelhandler(self, event):
        what, message, when, where, modifiers = event
        h, v = where
        if what == kHighLevelEvent:
            msg = 'High Level Event: %r %r' % (code(message),
                                               code(h | v << 16))
            try:
                AE.AEProcessAppleEvent(event)
            except AE.Error as err:
                print 'AE error: ', err
                print 'in', msg
                traceback.print_exc()

            return
        if what == keyDown:
            c = chr(message & charCodeMask)
            if modifiers & cmdKey:
                if c == '.':
                    raise KeyboardInterrupt, 'Command-period'
                if c == 'q':
                    if hasattr(MacOS, 'OutputSeen'):
                        MacOS.OutputSeen()
                    self.quitting = 1
                    return
        elif what == mouseDown:
            partcode, window = Win.FindWindow(where)
            if partcode == inMenuBar:
                result = Menu.MenuSelect(where)
                id = result >> 16 & 65535
                item = result & 65535
                if id == self.appleid:
                    if item == 1:
                        EasyDialogs.Message(self.getabouttext())
                    elif item > 1 and hasattr(Menu, 'OpenDeskAcc'):
                        name = self.applemenu.GetMenuItemText(item)
                        Menu.OpenDeskAcc(name)
                elif id == self.quitid and item == 1:
                    if hasattr(MacOS, 'OutputSeen'):
                        MacOS.OutputSeen()
                    self.quitting = 1
                Menu.HiliteMenu(0)
                return
        if hasattr(MacOS, 'HandleEvent'):
            MacOS.HandleEvent(event)
        else:
            print 'Unhandled event:', event
Esempio n. 17
0
 def __init__(self, signature=None, start=0, timeout=0):
     self.target_signature = None
     if signature is None:
         signature = self._signature
     if type(signature) == AEDescType:
         self.target = signature
     elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
         self.target = signature.__aepack__()
     elif type(signature) == StringType and len(signature) == 4:
         self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
         self.target_signature = signature
     else:
         raise TypeError, 'signature should be 4-char string or AEDesc'
     self.send_flags = AppleEvents.kAEWaitReply
     self.send_priority = AppleEvents.kAENormalPriority
     if timeout:
         self.send_timeout = timeout
     else:
         self.send_timeout = AppleEvents.kAEDefaultTimeout
     if start:
         self._start()
     return
Esempio n. 18
0
def pack(x, forcetype=None):
    if forcetype:
        if type(x) is StringType:
            return AE.AECreateDesc(forcetype, x)
        else:
            return pack(x).AECoerceDesc(forcetype)
    if x is None:
        return AE.AECreateDesc('null', '')
    elif isinstance(x, AEDescType):
        return x
    elif isinstance(x, FSSType):
        return AE.AECreateDesc('fss ', x.data)
    elif isinstance(x, FSRefType):
        return AE.AECreateDesc('fsrf', x.data)
    elif isinstance(x, AliasType):
        return AE.AECreateDesc('alis', x.data)
    elif isinstance(x, IntType):
        return AE.AECreateDesc('long', struct.pack('l', x))
    elif isinstance(x, FloatType):
        return AE.AECreateDesc('doub', struct.pack('d', x))
    elif isinstance(x, StringType):
        return AE.AECreateDesc('TEXT', x)
    elif isinstance(x, UnicodeType):
        data = x.encode('utf16')
        if data[:2] == '\xfe\xff':
            data = data[2:]
        return AE.AECreateDesc('utxt', data)
    elif isinstance(x, ListType):
        list = AE.AECreateList('', 0)
        for item in x:
            list.AEPutDesc(0, pack(item))

        return list
    elif isinstance(x, DictionaryType):
        record = AE.AECreateList('', 1)
        for key, value in x.items():
            packkey(record, key, value)

        return record
    elif type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
        return AE.AECreateDesc('type', x.want)
    elif hasattr(x, '__aepack__'):
        return x.__aepack__()
    elif hasattr(x, 'which'):
        return AE.AECreateDesc('TEXT', x.which)
    else:
        return AE.AECreateDesc('TEXT', x.want) if hasattr(
            x, 'want') else AE.AECreateDesc('TEXT', repr(x))
Esempio n. 19
0
"""'echo' -- an AppleEvent handler which handles all events the same.
def _interact():
    AE.AEInteractWithUser(50000000)
Esempio n. 21
0
"""Tools for use in AppleEvent clients and servers.
Esempio n. 22
0
 def close(self):
     AE.AERemoveEventHandler(kCoreEventClass, kAEOpenApplication)
     AE.AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments)
     AE.AERemoveEventHandler(kAEInternetSuite, kAEISGetURL)
     AE.AERemoveEventHandler('GURL', 'GURL')
Esempio n. 23
0
 def installaehandler(self, classe, type, callback):
     AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
     self.ae_handlers[classe, type] = callback
Esempio n. 24
0
"""MiniAEFrame - A minimal AppleEvent Application framework.
Esempio n. 25
0
 def close(self):
     for classe, type in self.ae_handlers.keys():
         AE.AERemoveEventHandler(classe, type)
Esempio n. 26
0
def findwindow(bundleid):
    """Finds a window identified by the provided bundle identifier"""
    return AE.AECreateDesc(AppleEvents.typeApplicationBundleID, bundleid)
Esempio n. 27
0
def _interact():
    """Make sure the application is in the foreground"""
    AE.AEInteractWithUser(50000000)
Esempio n. 28
0
def pack(x, forcetype=None):
    """Pack a python object into an AE descriptor"""

    if forcetype:
        if type(x) is StringType:
            return AE.AECreateDesc(forcetype, x)
        else:
            return pack(x).AECoerceDesc(forcetype)

    if x is None:
        return AE.AECreateDesc('null', '')

    if isinstance(x, AEDescType):
        return x
    if isinstance(x, FSSType):
        return AE.AECreateDesc('fss ', x.data)
    if isinstance(x, FSRefType):
        return AE.AECreateDesc('fsrf', x.data)
    if isinstance(x, AliasType):
        return AE.AECreateDesc('alis', x.data)
    if isinstance(x, IntType):
        return AE.AECreateDesc('long', struct.pack('l', x))
    if isinstance(x, FloatType):
        return AE.AECreateDesc('doub', struct.pack('d', x))
    if isinstance(x, StringType):
        return AE.AECreateDesc('TEXT', x)
    if isinstance(x, UnicodeType):
        data = x.encode('utf16')
        if data[:2] == '\xfe\xff':
            data = data[2:]
        return AE.AECreateDesc('utxt', data)
    if isinstance(x, ListType):
        list = AE.AECreateList('', 0)
        for item in x:
            list.AEPutDesc(0, pack(item))
        return list
    if isinstance(x, DictionaryType):
        record = AE.AECreateList('', 1)
        for key, value in x.items():
            packkey(record, key, value)
            #record.AEPutParamDesc(key, pack(value))
        return record
    if type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
        # Note: we are getting a class object here, not an instance
        return AE.AECreateDesc('type', x.want)
    if hasattr(x, '__aepack__'):
        return x.__aepack__()
    if hasattr(x, 'which'):
        return AE.AECreateDesc('TEXT', x.which)
    if hasattr(x, 'want'):
        return AE.AECreateDesc('TEXT', x.want)
    return AE.AECreateDesc('TEXT', repr(x))  # Copout
Esempio n. 29
0
 def close(self):
     AE.AERemoveEventHandler(kCoreEventClass, kAEOpenApplication)
     AE.AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments)
Esempio n. 30
0
"""Tools for use in AppleEvent clients and servers: