Esempio n. 1
0
    def showGUI(self):
        """Show the splash screen dialog."""

        imageFile = os.path.join(orca_platform.prefix,
                    orca_platform.datadirname,
                    orca_platform.package,
                    "gfx",
                    "orca-splash.png")

        image = Gtk.Image()
        image.set_from_file(imageFile)

        self.add(image)

        try:
            self.realize()
        except:
            debug.printException(debug.LEVEL_FINEST)

        self.set_transient_for(None)
        self.grab_focus()
        self.show_all()

        GObject.timeout_add(3000, self.hideGUI)

        while Gtk.events_pending():
            Gtk.main_iteration()

        return self
Esempio n. 2
0
    def run(self):
        """Try to start an HTTP server on settings.httpServerPort.
        If this fails, retry settings.maxHttpServerRetries times,
        each time incrementing the server port number by 1. If we
        are still unable to start a server, just fail gracefully.
        """

        portNo = settings.httpServerPort
        connected = False
        while not connected and \
            (portNo < settings.httpServerPort + settings.maxHttpServerRetries):
            try:
                httpd = BaseHTTPServer.HTTPServer(('', portNo),
                                                  _HTTPRequestHandler)
                connected = True
            except:
                if portNo == settings.httpServerPort:
                    debug.printException(debug.LEVEL_WARNING)
                debug.println(
                    debug.LEVEL_WARNING,
                    "httpserver._HTTPRequestThread unable to start server on port %d"
                    % portNo)
                portNo += 1

        if not connected:
            debug.println(
                debug.LEVEL_WARNING,
                "httpserver._HTTPRequestThread server startup failed.")
        else:
            httpd.serve_forever()
Esempio n. 3
0
    def queueText(self, text="", acss=None):
        """Adds the text to the queue.

        Arguments:
        - text: text to be spoken
        - acss: acss.ACSS instance; if None,
                the default voice settings will be used.
                Otherwise, the acss settings will be
                used to augment/override the default
                voice settings.

        Output is produced by the next call to speak.
        """
        if not settings.enableSpeech:
            return

        # A command to send to the speech server queueing text
        cmd = "q { %s }\n"
        if acss:
            try:
                code = self.getvoice(acss)
                cmd = "q {%s %%s %s}\n" % (code[0], code[1])
            except:
                debug.printException(debug.LEVEL_WARNING)

        # Split text into chunks and each chunk queue separately
        for chunk in (t.group() for t in self._speechChunk.finditer(text)):
            self._output.write(cmd % self._quoteSpecialChars(chunk))
Esempio n. 4
0
    def run(self):
        """Try to start an HTTP server on settings.httpServerPort.
        If this fails, retry settings.maxHttpServerRetries times,
        each time incrementing the server port number by 1. If we
        are still unable to start a server, just fail gracefully.
        """

        portNo = settings.httpServerPort
        connected = False
        while not connected and \
            (portNo < settings.httpServerPort + settings.maxHttpServerRetries):
            try:
                httpd = BaseHTTPServer.HTTPServer(('', portNo),
                                                  _HTTPRequestHandler)
                connected = True
            except:
                if portNo == settings.httpServerPort:
                    debug.printException(debug.LEVEL_WARNING)
                debug.println(debug.LEVEL_WARNING,
                    "httpserver._HTTPRequestThread unable to start server " \
                    "on port %d" % portNo)
                portNo += 1

        if not connected:
            debug.println(debug.LEVEL_WARNING,
                    "httpserver._HTTPRequestThread server startup failed.")
        else:
            httpd.serve_forever()
Esempio n. 5
0
    def getSpeechServers():
        """Gets available speech servers as a list.  The caller
        is responsible for calling the shutdown() method of each
        speech server returned.
        """

        haveNewServers = False
        try:
            serversConf = file(os.path.join(SpeechServer.location, '.servers'))
        except:
            return SpeechServer.__activeServers.values()
        for name in serversConf:
            name = name.strip()
            if name == '' or name[0] == '#':
                continue
            if name not in SpeechServer.__activeServers:
                try:
                    SpeechServer.__activeServers[name] = SpeechServer(name)
                    haveNewServers = True
                except:
                    debug.printException(debug.LEVEL_WARNING)
        serversConf.close()

        # Check whether some servers have died and remove those from the list
        if haveNewServers:
            from time import sleep
            sleep(1)
        for server in SpeechServer.__activeServers.values():
            if not server.process or server.process.poll() is not None:
                server.shutdown()

        return SpeechServer.__activeServers.values()
Esempio n. 6
0
    def reclaimScripts(self):
        """Compares the list of known scripts to the list of known apps,
        deleting any scripts as necessary.
        """

        from pyatspi import Registry

        try:
            desktop = Registry.getDesktop(0)
        except:
            debug.printException(debug.LEVEL_FINEST)
            return

        appList = self.appScripts.keys()
        appList = filter(lambda a: a!= None and a not in desktop, appList)
        for app in appList:
            appScript = self.appScripts.pop(app)
            _eventManager.deregisterScriptListeners(appScript)
            del appScript

            try:
                toolkitScripts = self.toolkitScripts.pop(app)
            except KeyError:
                pass
            else:
                for toolkitScript in toolkitScripts.values():
                    _eventManager.deregisterScriptListeners(toolkitScript)
                    del toolkitScript

            del app
Esempio n. 7
0
    def processInputEvent(self, script, inputEvent):
        """Processes an input event.  If settings.learnModeEnabled is True,
        this will merely report the description of the input event to braille
        and speech.  If settings.learnModeEnabled is False, this will call the
        function bound to this InputEventHandler instance, passing the
        inputEvent as the sole argument to the function.

        This function is expected to return True if it consumes the
        event; otherwise it is expected to return False.

        Arguments:
        - script:     the script (if any) associated with this event
        - inputEvent: the input event to pass to the function bound
                      to this InputEventHandler instance.
        """

        consumed = False

        if settings.learnModeEnabled and self._learnModeEnabled:
            if self._description:
                # These imports are here to eliminate circular imports.
                #
                import braille
                import speech
                braille.displayMessage(self._description)
                speech.speak(self._description)
                consumed = True
        else:
            try:
                consumed = self._function(script, inputEvent)
            except:
                debug.printException(debug.LEVEL_SEVERE)

        return consumed
Esempio n. 8
0
    def _markModified(self):
        """ Mark as modified the user application specific custom key bindings:
        """

        global appScript

        try:
            appScript.setupInputEventHandlers()
            keyBinds = keybindings.KeyBindings()
            keyBinds = appScript.overrideAppKeyBindings(appScript, keyBinds)
            keyBind = keybindings.KeyBinding(None, None, None, None)
            treeModel = self.keyBindingsModel

            myiter = treeModel.get_iter_first()
            while myiter != None:
                iterChild = treeModel.iter_children(myiter)
                while iterChild != None:
                    descrip = treeModel.get_value(iterChild,
                                                  orca_gui_prefs.DESCRIP)
                    keyBind.handler = input_event.InputEventHandler(
                        None, descrip)
                    if keyBinds.hasKeyBinding(keyBind,
                                              typeOfSearch="description"):
                        treeModel.set_value(iterChild, orca_gui_prefs.MODIF,
                                            True)
                    iterChild = treeModel.iter_next(iterChild)
                myiter = treeModel.iter_next(myiter)
        except:
            debug.printException(debug.LEVEL_SEVERE)
Esempio n. 9
0
def _processBrailleEvent(command):
    """Called whenever a  key is pressed on the Braille display.

    Arguments:
    - command: the BrlAPI command for the key that was pressed.

    Returns True if the event was consumed; otherwise False
    """

    # [[[TODO: WDW - probably should add braille bindings to this module.]]]

    consumed = False

    # Braille key presses always interrupt speech.
    #
    speech.stop()

    event = BrailleEvent(command)
    orca_state.lastInputEvent = event

    try:
        consumed = _PRESENTATION_MANAGERS[_currentPresentationManager].\
                   processBrailleEvent(event)
    except:
        debug.printException(debug.LEVEL_SEVERE)

    if (not consumed) and settings.learnModeEnabled:
        consumed = True

    return consumed
Esempio n. 10
0
def init():

    if _speechserver:
        return

    try:
        moduleName = settings.speechServerFactory
        _initSpeechServer(moduleName,
                          settings.speechServerInfo)
    except:
        moduleNames = settings.speechFactoryModules
        for moduleName in moduleNames:
            if moduleName != settings.speechServerFactory:
                try:
                    _initSpeechServer(moduleName, None)
                    if _speechserver:
                        break
                except:
                    debug.printException(debug.LEVEL_SEVERE)

    if _speechserver:
        debug.println(debug.LEVEL_CONFIGURATION,
                      "Using speech server factory: %s" % moduleName)
    else:
        debug.println(debug.LEVEL_CONFIGURATION, "Speech not available.")
Esempio n. 11
0
    def increaseSpeechRate(self, step=5):
        """Increases the speech rate.

        [[[TODO: WDW - this is a hack for now.  Need to take min/max
        values in account, plus also need to take into account that
        different engines provide different rate ranges.]]]
        """

        voices = settings.voices
        acss = voices[settings.DEFAULT_VOICE]
        speaker = self.__getSpeaker(acss)

        rateDelta = settings.speechRateDelta

        try:
            rate = min(100, self.__getRate(speaker) + rateDelta)
            acss[ACSS.RATE] = rate
            self.__setRate(speaker, rate)
            debug.println(debug.LEVEL_CONFIGURATION,
                          "speech.increaseSpeechRate: rate is now " \
                          " %d" % rate)
            # Translators: this is a short string saying that the speech
            # synthesis engine is now speaking at a faster rate (words
            # per minute).
            #
            self.speak(_("faster."))
        except:
            debug.printException(debug.LEVEL_SEVERE)
Esempio n. 12
0
    def decreaseSpeechPitch(self, step=0.5):
        """Decreases the speech pitch for the default voice.

        Arguments:
        - step: the pitch step decrement.
        """

        # [[[TODO: WDW - this is a hack for now.  Need to take min/max
        # values in account, plus also need to take into account that
        # different engines provide different rate ranges.]]]

        voices = settings.voices
        acss = voices[settings.DEFAULT_VOICE]
        speaker = self.__getSpeaker(acss)

        pitchDelta = settings.speechPitchDelta

        try:
            pitch = max(1, self.__getPitch(speaker) - pitchDelta)
            acss[ACSS.AVERAGE_PITCH] = pitch
            self.__setPitch(speaker, pitch)
            debug.println(debug.LEVEL_CONFIGURATION,
                          "speech.decreaseSpeechPitch: pitch is now " \
                          " %d" % pitch)
            # Translators: this is a short string saying that the speech
            # synthesis engine is now speaking in a lower pitch.
            #
            self.speak(_("lower."))
        except:
            debug.printException(debug.LEVEL_SEVERE)
Esempio n. 13
0
    def reset(self, text=None, acss=None):
        """Resets the speech engine."""

        # We might get into a vicious loop of resetting speech, so
        # we will abort if we see this happening.
        #
        if (time.time() - self.__lastResetTime) < 20:
            debug.println(debug.LEVEL_SEVERE,
                          "Something looks wrong with speech.  Aborting.")
            debug.printStack(debug.LEVEL_ALL)
            os._exit(50)
        else:
            self.__lastResetTime = time.time()

        speakers = self.__speakers
        self.shutdown()

        servers = bonobo.activation.query(
            "repo_ids.has('IDL:GNOME/Speech/SynthesisDriver:0.3')")

        for server in servers:
            if server.iid == self.__iid:
                try:
                    self.__driver = self.__activateDriver(self.__iid)
                    self.__speakers = {}
                    for name in speakers.keys():
                        self.__getSpeaker(speakers[name])
                    if text:
                        self.speak(text, acss)
                    break
                except:
                    debug.printException(debug.LEVEL_SEVERE)
                    self.__driver = None
                    pass
Esempio n. 14
0
    def decreaseSpeechRate(self, step=5):
        """Decreases the rate of speech for the given ACSS.  If
        acssName is None, the rate decrease will be applied to all
        known ACSSs.

        [[[TODO: WDW - this is a hack for now.  Need to take min/max
        values in account, plus also need to take into account that
        different engines provide different rate ranges.]]]

        Arguments:
        -acssName: the ACSS whose speech rate should be decreased
        """

        voices = settings.voices
        acss = voices[settings.DEFAULT_VOICE]
        speaker = self.__getSpeaker(acss)

        rateDelta = settings.speechRateDelta

        try:
            rate = max(1, self.__getRate(speaker) - rateDelta)
            acss[ACSS.RATE] = rate
            self.__setRate(speaker, rate)
            debug.println(debug.LEVEL_CONFIGURATION,
                          "speech.decreaseSpeechRate: rate is now " \
                          " %d" % rate)
            # Translators: this is a short string saying that the speech
            # synthesis engine is now speaking at a slower rate (words
            # per minute).
            #
            self.speak(_("slower."))
        except:
            debug.printException(debug.LEVEL_SEVERE)
    def _markModified(self):
        """ Mark as modified the user application specific custom key bindings:
        """

        global appScript

        try:
            appScript.setupInputEventHandlers()
            keyBinds = keybindings.KeyBindings()
            keyBinds = appScript.overrideAppKeyBindings(appScript, keyBinds)
            keyBind = keybindings.KeyBinding(None, None, None, None)
            treeModel = self.keyBindingsModel

            myiter = treeModel.get_iter_first()
            while myiter != None:
                iterChild = treeModel.iter_children(myiter)
                while iterChild != None:
                    descrip = treeModel.get_value(iterChild, 
                                                  orca_gui_prefs.DESCRIP)
                    keyBind.handler = input_event.InputEventHandler(None,
                                                                    descrip)
                    if keyBinds.hasKeyBinding(keyBind,
                                              typeOfSearch="description"):
                        treeModel.set_value(iterChild, 
                                            orca_gui_prefs.MODIF, True)
                    iterChild = treeModel.iter_next(iterChild)
                myiter = treeModel.iter_next(myiter)
        except:
            debug.printException(debug.LEVEL_SEVERE)
Esempio n. 16
0
    def _processInputEvent(self, event):
        """Processes the given input event based on the keybinding from the
        currently-active script.

        Arguments:
        - event: an instance of BrailleEvent or a KeyboardEvent
        """

        if not orca_state.activeScript:
            return

        if isinstance(event, input_event.KeyboardEvent):
            function = orca_state.activeScript.processKeyboardEvent
            data = "'%s' (%d)" % (event.event_string, event.hw_code)
        elif isinstance(event, input_event.BrailleEvent):
            function = orca_state.activeScript.processBrailleEvent
            data = "'%s'" % repr(event.event)
        else:
            return

        eType = str(event.type).upper()
        debug.println(debug.eventDebugLevel, "\nvvvvv PROCESS %s %s vvvvv" % (eType, data))
        try:
            function(event)
        except:
            debug.printException(debug.LEVEL_WARNING)
            debug.printStack(debug.LEVEL_WARNING)
        debug.println(debug.eventDebugLevel, "^^^^^ PROCESS %s %s ^^^^^\n" % (eType, data))
Esempio n. 17
0
def shutdown():
    """Shuts down the magnifier module.
    Returns True if the shutdown procedure was run or False if this
    module has not been initialized.
    """

    global _initialized
    global _magnifier

    if not _magnifierAvailable:
        return False

    if not _initialized:
        return False

    atspi.Registry().deregisterEventListener(__onMouseEvent, "mouse:abs")

    # Someone might have killed the magnifier on us.  They shouldn't
    # have done so, but we need to be able to recover if they did.
    # See http://bugzilla.gnome.org/show_bug.cgi?id=375396.
    #
    try:
        _magnifier.clearAllZoomRegions()
        _magnifier.dispose()
    except:
        debug.printException(debug.LEVEL_WARNING)

    _magnifier = None

    _initialized = False

    return True
Esempio n. 18
0
    def processInputEvent(self, script, inputEvent):
        """Processes an input event.  If settings.learnModeEnabled is True,
        this will merely report the description of the input event to braille
        and speech.  If settings.learnModeEnabled is False, this will call the
        function bound to this InputEventHandler instance, passing the
        inputEvent as the sole argument to the function.

        This function is expected to return True if it consumes the
        event; otherwise it is expected to return False.

        Arguments:
        - script:     the script (if any) associated with this event
        - inputEvent: the input event to pass to the function bound
                      to this InputEventHandler instance.
        """

        consumed = False

        if settings.learnModeEnabled and self._learnModeEnabled:
            if self.description:
                script.presentMessage(self.description)
                consumed = True
        else:
            try:
                consumed = self.function(script, inputEvent)
            except:
                debug.printException(debug.LEVEL_SEVERE)

        return consumed
Esempio n. 19
0
def _processBrailleEvent(command):
    """Called whenever a  key is pressed on the Braille display.

    Arguments:
    - command: the BrlAPI command for the key that was pressed.

    Returns True if the event was consumed; otherwise False
    """

    # [[[TODO: WDW - probably should add braille bindings to this module.]]]

    consumed = False

    # Braille key presses always interrupt speech.
    #
    speech.stop()

    event = BrailleEvent(command)
    orca_state.lastInputEvent = event

    try:
        consumed = _PRESENTATION_MANAGERS[_currentPresentationManager].\
                   processBrailleEvent(event)
    except:
        debug.printException(debug.LEVEL_SEVERE)

    if (not consumed) and settings.learnModeEnabled:
        consumed = True

    return consumed
Esempio n. 20
0
def shutdown():
    """Shuts down the magnifier module.
    Returns True if the shutdown procedure was run or False if this
    module has not been initialized.
    """

    global _initialized
    global _magnifier

    if not _magnifierAvailable:
        return False

    if not _initialized:
        return False

    atspi.Registry().deregisterEventListener(__onMouseEvent,"mouse:abs")

    # Someone might have killed the magnifier on us.  They shouldn't
    # have done so, but we need to be able to recover if they did.
    # See http://bugzilla.gnome.org/show_bug.cgi?id=375396.
    #
    try:
        _magnifier.clearAllZoomRegions()
        _magnifier.dispose()
    except:
        debug.printException(debug.LEVEL_WARNING)

    _magnifier = None

    _initialized = False

    return True
Esempio n. 21
0
    def __speak(self, text=None, acss=None, interrupt=True):
        """Speaks all queued text immediately.  If text is not None,
        it is added to the queue before speaking.

        Arguments:
        - text:      optional text to add to the queue before speaking
        - acss:      acss.ACSS instance; if None,
                     the default voice settings will be used.
                     Otherwise, the acss settings will be
                     used to augment/override the default
                     voice settings.
        - interrupt: if True, stops any speech in progress before
                     speaking the text

        Returns an id of the thing being spoken or -1 if nothing is to
        be spoken.
        """

        # If the user has speech turned off, just return.
        #
        if not settings.enableSpeech:
            return -1

        speaker = self.__getSpeaker(acss)
        if acss and not acss.has_key(ACSS.RATE):
            voices = settings.voices
            defaultACSS = voices[settings.DEFAULT_VOICE]
            if defaultACSS.has_key(ACSS.RATE):
                self.__setRate(speaker, defaultACSS[ACSS.RATE])

        if not text:
            if interrupt:
                speech.stop()
            return -1

        text = self.__addVerbalizedPunctuation(text)
        if orca_state.activeScript and orca_state.usePronunciationDictionary:
            text = orca_state.activeScript.adjustForPronunciation(text)

        try:
            # [[[TODO: WDW - back this stop out for now.  The problem is
            # that we end up clipping too much speech, especially in the
            # case where we want to speak the contents of a popup before
            # speaking the object with focus.]]]
            #
            #if interrupt:
            #    speaker.stop()
            self.__lastText = [text, acss]
            self.__isSpeaking = True
            return speaker.say(text)
        except:
            # On failure, remember what we said, reset our connection to the
            # speech synthesis driver, and try to say it again.
            #
            debug.printException(debug.LEVEL_SEVERE)
            debug.println(debug.LEVEL_SEVERE, "Restarting speech...")
            self.reset()
            return -1
    def __init__(self, serverId):
        super(SpeechServer, self).__init__()
        self._id = serverId
        self._client = None
        self._current_voice_properties = {}
        self._acss_manipulators = (
            (ACSS.RATE, self._set_rate),
            (ACSS.AVERAGE_PITCH, self._set_pitch),
            (ACSS.GAIN, self._set_volume),
            (ACSS.FAMILY, self._set_family),
            )
        if not _speechd_available:
            debug.println(debug.LEVEL_WARNING,
                          "Speech Dispatcher interface not installed.")
            return
        if not _speechd_version_ok:
            debug.println(debug.LEVEL_WARNING,
                        "Speech Dispatcher version 0.6.2 or later is required.")
            return
        # The following constants must be initialized in runtime since they
        # depend on the speechd module being available.
        self._PUNCTUATION_MODE_MAP = {
            settings.PUNCTUATION_STYLE_ALL:  speechd.PunctuationMode.ALL,
            settings.PUNCTUATION_STYLE_MOST: speechd.PunctuationMode.SOME,
            settings.PUNCTUATION_STYLE_SOME: speechd.PunctuationMode.SOME,
            settings.PUNCTUATION_STYLE_NONE: speechd.PunctuationMode.NONE,
            }
        self._CALLBACK_TYPE_MAP = {
            speechd.CallbackType.BEGIN: speechserver.SayAllContext.PROGRESS,
            speechd.CallbackType.CANCEL: speechserver.SayAllContext.INTERRUPTED,
            speechd.CallbackType.END: speechserver.SayAllContext.COMPLETED,
           #speechd.CallbackType.INDEX_MARK:speechserver.SayAllContext.PROGRESS,
            }
        # Translators: This string will appear in the list of
        # available voices for the current speech engine.  %s will be
        # replaced by the name of the current speech engine, such as
        # "Festival default voice" or "IBMTTS default voice".  It
        # refers to the default voice configured for given speech
        # engine within the speech subsystem.  Apart from this item,
        # the list will contain the names of all available "real"
        # voices provided by the speech engine.
        #
        try:
            serverId = serverId.encode("UTF-8")
        except UnicodeDecodeError:
            pass

        self._default_voice_name = _("%s default voice") % serverId
        
        try:
            self._init()
        except:
            debug.println(debug.LEVEL_WARNING,
                          "Speech Dispatcher service failed to connect:")
            debug.printException(debug.LEVEL_WARNING)
        else:
            SpeechServer._active_servers[serverId] = self
 def getSpeechServer(info=['outloud','outloud']):
     """Gets a given SpeechServer based upon the info.
     See SpeechServer.getInfo() for more info.
     """
     if SpeechServer.__activeServers.has_key(info[0]):
         return SpeechServer.__activeServers[info[0]]
     else:
         try:
             return SpeechServer(info[0])
         except:
             debug.printException(debug.LEVEL_SEVERE)
         return None
Esempio n. 24
0
    def _processBrailleEvent(self, brailleEvent):
        """Called whenever a cursor key is pressed on the Braille display.

        Arguments:
        - brailleEvent: an instance of input_event.BrailleEvent
        """
        if orca_state.activeScript:
            try:
                orca_state.activeScript.processBrailleEvent(brailleEvent)
            except:
                debug.printException(debug.LEVEL_WARNING)
                debug.printStack(debug.LEVEL_WARNING)
Esempio n. 25
0
def _showFindGUI(script=None, inputEvent=None):
    """Displays the user interace to perform an Orca Find.

    Returns True to indicate the input event has been consumed.
    """

    try:
        module = __import__(settings.findModule, globals(), locals(), [''])
        module.showFindUI()
    except:
        debug.printException(debug.LEVEL_SEVERE)
        pass
Esempio n. 26
0
 def getSpeechServer(info=['outloud', 'outloud']):
     """Gets a given SpeechServer based upon the info.
     See SpeechServer.getInfo() for more info.
     """
     if SpeechServer.__activeServers.has_key(info[0]):
         return SpeechServer.__activeServers[info[0]]
     else:
         try:
             return SpeechServer(info[0])
         except:
             debug.printException(debug.LEVEL_SEVERE)
         return None
    def _processBrailleEvent(self, brailleEvent):
        """Called whenever a cursor key is pressed on the Braille display.

        Arguments:
        - brailleEvent: an instance of input_event.BrailleEvent
        """
        if orca_state.activeScript:
            try:
                orca_state.activeScript.processBrailleEvent(brailleEvent)
            except:
                debug.printException(debug.LEVEL_WARNING)
                debug.printStack(debug.LEVEL_WARNING)
    def _processKeyboardEvent(self, keyboardEvent):
        """Processes the given keyboard event based on the keybinding from the
        currently active script.

        Arguments:
        - keyboardEvent: an instance of input_event.KeyboardEvent
        """
        if orca_state.activeScript:
            try:
                orca_state.activeScript.processKeyboardEvent(keyboardEvent)
            except:
                debug.printException(debug.LEVEL_WARNING)
                debug.printStack(debug.LEVEL_WARNING)
Esempio n. 29
0
    def _processKeyboardEvent(self, keyboardEvent):
        """Processes the given keyboard event based on the keybinding from the
        currently active script.

        Arguments:
        - keyboardEvent: an instance of input_event.KeyboardEvent
        """
        if orca_state.activeScript:
            try:
                orca_state.activeScript.processKeyboardEvent(keyboardEvent)
            except:
                debug.printException(debug.LEVEL_WARNING)
                debug.printStack(debug.LEVEL_WARNING)
Esempio n. 30
0
def _processBrailleEvent(command):
    """Handles BrlTTY command events.  This passes commands on to Orca for
    processing.  If Orca does not handle them (as indicated by a return value
    of false from the callback passed to init, it will attempt to handle the
    command itself - either by panning the viewport or passing cursor routing
    keys to the Regions for handling.

    Arguments:
    - command: the BrlAPI command for the key that was pressed.
    """

    _printBrailleEvent(debug.LEVEL_FINE, command)

    # [[[TODO: WDW - DaveM suspects the Alva driver is sending us a
    # repeat flag.  So...let's kill a couple birds here until BrlTTY
    # 3.8 fixes the problem: we'll disable autorepeat and we'll also
    # strip out the autorepeat flag if this is the first press of a
    # button.]]]
    #
    if command & BRL_FLG_REPEAT_INITIAL:
        command &= ~(BRL_FLG_REPEAT_INITIAL | BRL_FLG_REPEAT_DELAY)
    elif command & BRL_FLG_REPEAT_DELAY:
        return True

    consumed = False

    if settings.timeoutCallback and (settings.timeoutTime > 0):
        signal.signal(signal.SIGALRM, settings.timeoutCallback)
        signal.alarm(settings.timeoutTime)

    if _callback:
        try:
            # Like key event handlers, a return value of True means
            # the command was consumed.
            #
            consumed = _callback(command)
        except:
            debug.printException(debug.LEVEL_WARNING)
            consumed = False

    if (command >= 0x100) and (command < (0x100 + _displaySize[0])):
        if len(_lines) > 0:
            cursor = (command - 0x100) + _viewport[0]
            lineNum = _viewport[1]
            _lines[lineNum].processRoutingKey(cursor)
            consumed = True

    if settings.timeoutCallback and (settings.timeoutTime > 0):
        signal.alarm(0)

    return consumed
Esempio n. 31
0
def init():
    """Creates an HTTP server that listens for speak commands from a
    separate port defined by settings.httpServerPort.  We run this
    as a daemon so it will die automatically when orca dies."""

    global _httpRequestThread

    if settings.httpServerPort and (not _httpRequestThread):
        try:
            _httpRequestThread = _HTTPRequestThread()
            _httpRequestThread.setDaemon(True)
            _httpRequestThread.start()
        except:
            debug.printException(debug.LEVEL_WARNING)
Esempio n. 32
0
def init():
    """Creates an HTTP server that listens for speak commands from a
    separate port defined by settings.httpServerPort.  We run this
    as a daemon so it will die automatically when orca dies."""

    global _httpRequestThread

    if settings.httpServerPort and (not _httpRequestThread):
        try:
            _httpRequestThread = _HTTPRequestThread()
            _httpRequestThread.setDaemon(True)
            _httpRequestThread.start()
        except:
            debug.printException(debug.LEVEL_WARNING)
Esempio n. 33
0
    def getSpeechServer(info=None):
        """Gets a given SpeechServer based upon the info.
        See SpeechServer.getInfo() for more info.
        """

        if info and SpeechServer.__activeServers.has_key(info[1]):
            return SpeechServer.__activeServers[info[1]]

        server = None

        gservers = bonobo.activation.query(
            "repo_ids.has('IDL:GNOME/Speech/SynthesisDriver:0.3')")

        if len(gservers) == 0:
            return None

        gserver = None

        # All this logic is to attempt to fall back to a working
        # driver if the desired one cannot be found or is not
        # not working.
        #
        if not info:
            gserver = gservers[0]
        else:
            for s in gservers:
                if s.iid == info[1]:
                    gserver = s
                    break

        if not gserver:
            return None

        server = None
        try:
            server = SpeechServer.__createServer(gserver.iid)
        except:
            debug.printException(debug.LEVEL_WARNING)

        if not server:
            for s in gservers:
                try:
                    server = SpeechServer.__createServer(s.iid)
                    if server:
                        break
                except:
                    debug.printException(debug.LEVEL_WARNING)

        return server
Esempio n. 34
0
def _showFindGUI(script=None, inputEvent=None):
    """Displays the user interace to perform an Orca Find.

    Returns True to indicate the input event has been consumed.
    """

    try:
        module = __import__(settings.findModule,
                            globals(),
                            locals(),
                            [''])
        module.showFindUI()
    except:
        debug.printException(debug.LEVEL_SEVERE)
        pass
Esempio n. 35
0
    def _getScriptForEvent(event):
        """Returns the script associated with event."""

        if event.type.startswith("mouse:"):
            return orca_state.activeScript

        script = None
        try:
            app = event.host_application or event.source.getApplication()
        except:
            debug.printException(debug.LEVEL_WARNING)
        else:
            script = _scriptManager.getScript(app, event.source)

        return script
Esempio n. 36
0
    def getVoiceFamilies(self):
        """Returns a list of speechserver.VoiceFamily instances
        representing all the voice families known by the speech server.
        """

        families = []
        try:
            for voice in self.getvoicelist():
                props = {speechserver.VoiceFamily.NAME: voice}
                families.append(speechserver.VoiceFamily(props))
        except:
            debug.printException(debug.LEVEL_SEVERE)
            pass

        return families
Esempio n. 37
0
    def _verifyFormatting(self):

        # Verify the formatting strings are OK.  This is only
        # for verification and does not effect the function of
        # Orca at all.

        # Populate the entire globals with empty arrays
        # for the results of all the legal method names.
        #
        globalsDict = {}
        for key in self._methodsDict.keys():
            globalsDict[key] = []
        self._addGlobals(globalsDict)

        for roleKey in self._script.formatting[self._mode]:
            for key in ["focused", "unfocused"]:
                try:
                    evalString = \
                        self._script.formatting[self._mode][roleKey][key]
                except:
                    continue
                else:
                    if not evalString:
                        # It's legal to have an empty string.
                        #
                        continue
                    while True:
                        try:
                            eval(evalString, globalsDict)
                            break
                        except NameError:
                            info = _formatExceptionInfo()
                            arg = info[1][0]
                            arg = arg.replace("name '", "")
                            arg = arg.replace("' is not defined", "")
                            if not self._methodsDict.has_key(arg):
                                debug.printException(debug.LEVEL_SEVERE)
                                debug.println(
                                    debug.LEVEL_SEVERE,
                                    "Unable to find function for '%s'\n" % arg)
                            globalsDict[arg] = []
                        except:
                            debug.printException(debug.LEVEL_SEVERE)
                            debug.println(
                                debug.LEVEL_SEVERE,
                                "While processing '%s' '%s' '%s' '%s'" \
                                % (roleKey, key, evalString, globalsDict))
                            break
Esempio n. 38
0
def _showPreferencesConsole(script=None, inputEvent=None):
    """Displays the user interace to configure Orca and set up
    user preferences via a command line interface.

    Returns True to indicate the input event has been consumed.
    """

    try:
        module = __import__(settings.consolePreferencesModule, globals(),
                            locals(), [''])
        module.showPreferencesUI()
    except:
        debug.printException(debug.LEVEL_SEVERE)
        pass

    return True
Esempio n. 39
0
    def getVoiceFamilies(self):
        """Returns a list of speechserver.VoiceFamily instances
        representing all the voice families known by the speech server.
        """

        families = []
        try:
            for voice in self.getvoicelist():
                props = {
                    speechserver.VoiceFamily.NAME   : voice
                }
                families.append(speechserver.VoiceFamily(props))
        except:
            debug.printException(debug.LEVEL_SEVERE)

        return families
Esempio n. 40
0
    def consumeKeyboardEvent(self, script, keyboardEvent):
        """Attempts to consume the given keyboard event.  If these
        keybindings have a handler for the given keyboardEvent, it is
        assumed the event will always be consumed.
        """

        consumed = False
        handler = self.getInputHandler(keyboardEvent)
        if handler:
            consumed = True
            if keyboardEvent.type == atspi.Accessibility.KEY_PRESSED_EVENT:
                try:
                    handler.processInputEvent(script, keyboardEvent)
                except:
                    debug.printException(debug.LEVEL_SEVERE)

        return consumed
Esempio n. 41
0
def _showAppPreferencesGUI(script=None, inputEvent=None):
    """Displays the user interace to configure the settings for a
    specific applications within Orca and set up those app-specific
    user preferences using a GUI.

    Returns True to indicate the input event has been consumed.
    """

    try:
        module = __import__(settings.appGuiPreferencesModule, globals(),
                            locals(), [''])
        module.showPreferencesUI()
    except:
        debug.printException(debug.LEVEL_SEVERE)
        pass

    return True
    def consumeKeyboardEvent(self, script, keyboardEvent):
        """Attempts to consume the given keyboard event.  If these
        keybindings have a handler for the given keyboardEvent, it is
        assumed the event will always be consumed.
        """

        consumed = False
        handler = self.getInputHandler(keyboardEvent)
        if handler:
            consumed = True
            if keyboardEvent.type == atspi.Accessibility.KEY_PRESSED_EVENT:
                try:
                    handler.processInputEvent(script, keyboardEvent)
                except:
                    debug.printException(debug.LEVEL_SEVERE)

        return consumed
Esempio n. 43
0
def getSpeechServerFactories():
    """Imports all known SpeechServer factory modules.  Returns a list
    of modules that implement the getSpeechServers method, which
    returns a list of speechserver.SpeechServer instances.
    """

    factories = []

    moduleNames = settings.speechFactoryModules
    for moduleName in moduleNames:
        try:
            module = __import__(moduleName, globals(), locals(), [''])
            factories.append(module)
        except:
            debug.printException(debug.LEVEL_OFF)

    return factories
Esempio n. 44
0
def init():

    global _speechserver

    if _speechserver:
        return

    # First, find the factory module to use.  We will
    # allow the user to give their own factory module,
    # thus we look first in the global name space, and
    # then we look in the orca namespace.
    #
    moduleName = settings.speechServerFactory

    if moduleName:
        debug.println(debug.LEVEL_CONFIGURATION,
                      "Using speech server factory: %s" % moduleName)
    else:
        debug.println(debug.LEVEL_CONFIGURATION,
                      "Speech not available.")
        return

    factory = None
    try:
        factory =  __import__(moduleName,
                              globals(),
                              locals(),
                              [''])
    except:
        try:
            moduleName = moduleName.replace("orca.","",1)
            factory =  __import__(moduleName,
                                  globals(),
                                  locals(),
                                  [''])
        except:
            debug.printException(debug.LEVEL_SEVERE)

    # Now, get the speech server we care about.
    #
    speechServerInfo = settings.speechServerInfo
    if speechServerInfo:
        _speechserver = factory.SpeechServer.getSpeechServer(speechServerInfo)
    else:
        _speechserver = factory.SpeechServer.getSpeechServer()
Esempio n. 45
0
def _showMainWindowGUI(script=None, inputEvent=None):
    """Displays the Orca main window.

    Returns True to indicate the input event has been consumed.
    """

    try:
        module = __import__(settings.mainWindowModule, globals(), locals(),
                            [''])
        if settings.showMainWindow:
            module.showMainUI()
        else:
            module.hideMainUI()
    except:
        debug.printException(debug.LEVEL_SEVERE)
        pass

    return True
Esempio n. 46
0
    def _writeAppKeyBindingsMap(self, prefs, appName, appScript, treeModel):
        """Write to an application specific configuration file 'prefs', the
        key bindings passed in the model treeModel.

        Arguments:
        - prefs: file handle for application preferences.
        - appName: the application these preferences are for.
        - appScript: the application script.
        - treeModel: key bindings treemodel.
        """

        self._writeKeyBindingsPreamble(prefs)
        try:
            self._iterateKeyBindings(prefs, treeModel)
        except:
            debug.println(debug.LEVEL_FINEST, "FAILURE: _iterateKeyBindings")
            debug.printException(debug.LEVEL_FINEST)
        self._writeAppKeyBindingsPostamble(prefs, appName, appScript)
Esempio n. 47
0
    def _showGUI(self):
        """Show the Orca quit GUI dialog. This assumes that the GUI has 
        already been created.
        """

        # Set the current time on the quit GUI dialog so that it'll
        # get focus. set_user_time is a new call in pygtk 2.9.2 or later.
        # It's surronded by a try/except block here so that if it's not found,
        # then we can fail gracefully.
        #
        try:
            self.quitDialog.realize()
            self.quitDialog.window.set_user_time(\
                orca_state.lastInputEventTimestamp)
        except AttributeError:
            debug.printException(debug.LEVEL_FINEST)

        self.quitDialog.show()
Esempio n. 48
0
def quitOrca(script=None, inputEvent=None):
    """Quit Orca. Check if the user wants to confirm this action.
    If so, show the confirmation GUI otherwise just shutdown.

    Returns True to indicate the input event has been consumed.
    """

    if settings.quitOrcaNoConfirmation:
        shutdown()
    else:
        try:
            module = __import__(settings.quitModule, globals(), locals(), [''])
            module.showQuitUI()
        except:
            debug.printException(debug.LEVEL_SEVERE)
            pass

    return True
Esempio n. 49
0
def test():
    import speechserver
    factories = getSpeechServerFactories()
    for factory in factories:
        print factory.__name__
        servers = factory.SpeechServer.getSpeechServers()
        for server in servers:
            try:
                print "    ", server.getInfo()
                for family in server.getVoiceFamilies():
                    name = family[speechserver.VoiceFamily.NAME]
                    print "      ", name
                    acss = ACSS({ACSS.FAMILY: family})
                    server.speak(name, acss)
                    server.speak("testing")
                server.shutdown()
            except:
                debug.printException(debug.LEVEL_OFF)
                pass
Esempio n. 50
0
    def getSpeechServers():
        """Gets available speech servers as a list.  The caller
        is responsible for calling the shutdown() method of each
        speech server returned.
        """

        # Get a list of all the drivers on the system and find out how many
        # of them work.
        #
        knownServers = bonobo.activation.query(
            "repo_ids.has('IDL:GNOME/Speech/SynthesisDriver:0.3')")

        for server in knownServers:
            if not SpeechServer.__activeServers.has_key(server.iid):
                try:
                    SpeechServer.__createServer(server.iid)
                except:
                    debug.printException(debug.LEVEL_WARNING)

        return SpeechServer.__activeServers.values()
Esempio n. 51
0
    def _showGUI(self):
        """Show the Orca Find dialog. This assumes that the GUI has
        already been created.
        """

        # Set the current time on the Find GUI dialog so that it'll
        # get focus. set_user_time is a new call in pygtk 2.9.2 or later.
        # It's surronded by a try/except block here so that if it's not found,
        # then we can fail gracefully.
        #
        try:
            self.findDialog.realize()
            self.findDialog.window.set_user_time(\
                orca_state.lastInputEventTimestamp)
        except AttributeError:
            debug.printException(debug.LEVEL_FINEST)

        self.findDialog.show()

        # Populate the dialog box from the previous searchQuery, should
        # one exist.  Note:  This is necessary because we are destroying
        # the dialog (rather than merely hiding it) before performing the
        # search.

        try:
            self.searchForEntry.set_text(\
                orca_state.searchQuery.searchString)
            self.searchForEntry.select_region(
                0, len(self.searchForEntry.get_text()))
            if orca_state.searchQuery.startAtTop:
                self.topRadioButton.set_active(True)
            self.matchCaseCheckbox.set_active(\
                orca_state.searchQuery.caseSensitive)
            self.matchEntireWordCheckbox.set_active(\
                orca_state.searchQuery.matchEntireWord)
            self.wrapAroundCheckbox.set_active(\
                orca_state.searchQuery.windowWrap)
            self.searchBackwardsCheckbox.set_active(\
                orca_state.searchQuery.searchBackwards)
        except:
            pass
Esempio n. 52
0
    def _reclaimScripts(self):
        """Compares the list of known scripts to the list of known apps,
        deleting any scripts as necessary.
        """

        # Sometimes the desktop can become unavailable.  This happens
        # often when synaptic is used to load new modules (see the bug
        # report http://bugzilla.gnome.org/show_bug.cgi?id=342022).
        # So...if this happens, we'll just move along.  The next
        # successful call to _reclaimScripts will reclaim anything we
        # didn't reclaim this time.
        #
        try:
            apps = []
            desktop = self.registry.desktop
            for i in range(0, desktop.childCount):
                try:
                    acc = desktop.getChildAtIndex(i)
                    app = atspi.Accessible.makeAccessible(acc)
                    if app:
                        apps.insert(0, app)
                except:
                    pass

            for app in self._knownScripts.keys():
                if apps.count(app) == 0:
                    script = self._knownScripts[app]
                    self._deregisterEventListeners(script)

                    # Provide a bunch of hints to the garbage collector
                    # that we just don't care about this stuff any longer.
                    # Note the "app.app = None" - that helps remove a
                    # cycle of the application referring to itself.
                    #
                    del self._knownScripts[app]
                    app.app = None
                    del app
                    del script
        except:
            debug.printException(debug.LEVEL_FINEST)
Esempio n. 53
0
    def processRoutingKey(self, offset):
        """Processes a cursor routing key press on this Component.  The offset
        is 0-based, where 0 represents the leftmost character of string
        associated with this region.  Note that the zeroeth character may have
        been scrolled off the display."""

        actions = self.accessible.action
        if actions:
            actions.doAction(0)
        else:

            # [[[WDW - HACK to do a mouse button 1 click if we have
            # to.  For example, page tabs don't have any actions but
            # we want to be able to select them with the cursor
            # routing key.]]]
            #
            debug.println(debug.LEVEL_FINEST,
                          "braille.Component.processRoutingKey: no action")
            try:
                eventsynthesizer.clickObject(self.accessible, 1)
            except:
                debug.printException(debug.LEVEL_SEVERE)