def _getTutorialForMenu(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a menu.

        Arguments:
        - obj: the menu
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is a tip for the user, how to navigate menues.
        mainMenuMsg = _("To navigate, press left or right arrow. " \
                       "To move through items press up or down arrow.")

        # Translators: this is a tip for the user, how to
        # navigate into sub menues.
        subMenuMsg = _("To enter sub menu, press right arrow.")

        # Checking if we are a submenu,
        # we can't rely on our parent being just a menu.
        if obj.parent.name != "" and obj.parent.__class__ == obj.__class__:
            if (self.lastTutorial != [subMenuMsg]) or forceTutorial:
                utterances.append(subMenuMsg)
        else:
            if (self.lastTutorial != [mainMenuMsg]) or forceTutorial:
                utterances.append(mainMenuMsg)

        self._debugGenerator("_getTutorialForMenu",
                             obj,
                             alreadyFocused,
                             utterances)
        return utterances
def speakKeyEvent(event_string, type):
    """Speaks a key event immediately.

    Arguments:
    - event_string: string representing the key event as defined by
                    input_event.KeyboardEvent.
    - type:         key event type as one of orca.KeyEventType constants.

    """
    if settings.silenceSpeech:
        return

    if _speechserver:
        _speechserver.speakKeyEvent(event_string, type)
    else:
        # Check to see if there are localized words to be spoken for
        # this key event.
        #
        event_string = keynames.getKeyName(event_string)

        if type == orca.KeyEventType.LOCKING_LOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("on")
        elif type == orca.KeyEventType.LOCKING_UNLOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("off")

        debug.println(debug.LEVEL_INFO, "SPEECH OUTPUT: '" + event_string +"'")
        log.info("speakKeyEvent utterance='%s'" % event_string)
    def speakKeyEvent(self, event_string, type):
        """Speaks a key event immediately.

        Arguments:
        - event_string: string representing the key event as defined by
                        input_event.KeyboardEvent.
        - type:         key event type as one of orca.KeyEventType constants.

        """
        if type == orca.KeyEventType.PRINTABLE and \
               event_string.decode("UTF-8").isupper():
            voice = settings.voices[settings.UPPERCASE_VOICE]
        else:
            voice = settings.voices[settings.DEFAULT_VOICE]

        # Check to see if there are localized words to be spoken for
        # this key event.
        #
        event_string = keynames.getKeyName(event_string)

        if type == orca.KeyEventType.LOCKING_LOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("on")
        elif type == orca.KeyEventType.LOCKING_UNLOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("off")

        debug.println(debug.LEVEL_INFO, "SPEECH OUTPUT: '" + event_string +"'")
        log.info("speakKeyEvent utterance='%s'" % event_string)

        self.speak(event_string, acss=voice)
Exemple #4
0
def speakKeyEvent(event_string, type):
    """Speaks a key event immediately.

    Arguments:
    - event_string: string representing the key event as defined by
                    input_event.KeyboardEvent.
    - type:         key event type as one of orca.KeyEventType constants.

    """
    if settings.silenceSpeech:
        return

    if _speechserver:
        _speechserver.speakKeyEvent(event_string, type)
    else:
        # Check to see if there are localized words to be spoken for
        # this key event.
        #
        event_string = keynames.getKeyName(event_string)

        if type == orca.KeyEventType.LOCKING_LOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("on")
        elif type == orca.KeyEventType.LOCKING_UNLOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("off")

        debug.println(debug.LEVEL_INFO,
                      "SPEECH OUTPUT: '" + event_string + "'")
        log.info("speakKeyEvent utterance='%s'" % event_string)
    def __init__(self):
        """Initialize the Orca profile configuration GUI."""

        Gtk.Dialog.__init__(self)

        # Translators: Profiles in Orca make it possible for users to
        # quickly switch amongst a group of pre-defined settings (e.g.
        # an 'English' profile for reading text written in English using
        # an English-language speech synthesizer and braille rules, and
        # a similar 'Spanish' profile for reading Spanish text. The
        # following string is the title of a dialog in which users can
        # save a newly-defined profile.
        #
        self.set_title(_("Save Profile As"))
        self.set_has_resize_grip(False)

        self.add_button("gtk-cancel", Gtk.ResponseType.CANCEL)
        self.add_button("gtk-save", Gtk.ResponseType.ACCEPT)

        grid = Gtk.Grid()
        grid.set_property("margin", 12)
        grid.set_row_spacing(10)
        grid.set_column_spacing(10)

        # Right now the content area is a GtkBox. We'll need to update
        # this once GtkBox is fully deprecated.
        contentArea = self.get_content_area()
        contentArea.pack_start(grid, True, True, 0)

        self.profileEntry = Gtk.Entry()
        self.profileEntry.set_property("hexpand", True)
        self.profileEntry.set_activates_default(True)
        grid.attach(self.profileEntry, 1, 0, 1, 1)

        # Translators: Profiles in Orca make it possible for users to
        # quickly switch amongst a group of pre-defined settings (e.g.
        # an 'English' profile for reading text written in English using
        # an English-language speech synthesizer and braille rules, and
        # a similar 'Spanish' profile for reading Spanish text. The
        # following string is the label for a text entry in which the user
        # enters the name of a new settings profile being saved via the
        # 'Save Profile As' dialog.
        #
        label = Gtk.Label(_("_Profile Name:"))
        label.set_use_underline(True)
        label.set_mnemonic_widget(self.profileEntry)
        grid.attach(label, 0, 0, 1, 1)

        defaultButton = self.get_widget_for_response(Gtk.ResponseType.ACCEPT)
        defaultButton.set_property("can-default", True)
        defaultButton.set_property("has-default", True)

        self.connect("response", self.onResponse)
        self.connect("destroy", self.onDestroy)

        self.searchString = None
        self.profileString = None
        self.prefsDialog = None
 def _change_default_speech_rate(self, decrease=False):
     acss = settings.voices[settings.DEFAULT_VOICE]
     delta = settings.speechRateDelta * (decrease and -1 or +1)
     rate = acss[ACSS.RATE]
     acss[ACSS.RATE] = max(0, min(99, rate + delta))
     debug.println(debug.LEVEL_CONFIGURATION,
                   "Speech rate is now %d" % rate)
     # Translators: This string announces speech rate change.
     self.speak(decrease and _("slower.") or _("faster."), acss=acss)
 def _change_default_speech_pitch(self, decrease=False):
     acss = settings.voices[settings.DEFAULT_VOICE]
     delta = settings.speechPitchDelta * (decrease and -1 or +1)
     pitch = acss[ACSS.AVERAGE_PITCH]
     acss[ACSS.AVERAGE_PITCH] = max(0, min(9, pitch + delta))
     debug.println(debug.LEVEL_CONFIGURATION,
                   "Speech pitch is now %d" % pitch)
     # Translators: This string announces speech pitch change.
     self.speak(decrease and _("lower.") or _("higher."), acss=acss)
Exemple #8
0
 def _change_default_speech_rate(self, decrease=False):
     acss = settings.voices[settings.DEFAULT_VOICE]
     delta = settings.speechRateDelta * (decrease and -1 or +1)
     rate = acss[ACSS.RATE]
     acss[ACSS.RATE] = max(0, min(99, rate + delta))
     debug.println(debug.LEVEL_CONFIGURATION,
                   "Speech rate is now %d" % rate)
     # Translators: This string announces speech rate change.
     self.speak(decrease and _("slower.") or _("faster."), acss=acss)
Exemple #9
0
 def _change_default_speech_pitch(self, decrease=False):
     acss = settings.voices[settings.DEFAULT_VOICE]
     delta = settings.speechPitchDelta * (decrease and -1 or +1)
     pitch = acss[ACSS.AVERAGE_PITCH]
     acss[ACSS.AVERAGE_PITCH] = max(0, min(9, pitch + delta))
     debug.println(debug.LEVEL_CONFIGURATION,
                   "Speech pitch is now %d" % pitch)
     # Translators: This string announces speech pitch change.
     self.speak(decrease and _("lower.") or _("higher."), acss=acss)
Exemple #10
0
    def bookmarkCurrentWhereAmI(self, inputEvent):
        """ Report "Where am I" information for this bookmark relative to the 
        current pointer location."""
        try:
            context = self._bookmarkToContext( \
                          self._bookmarks[inputEvent.hw_code])
        except KeyError:
            self._script.systemBeep()
            return   

        obj = context.getCurrentAccessible()    
        cur_obj = orca_state.locusOfFocus

        # Are they the same object?
        if self._script.utilities.isSameObject(cur_obj, obj):
            # Translators: this announces that the current object is the same
            # object pointed to by the bookmark.
            #
            self._script.presentMessage(_('bookmark is current object'))
            return
        # Are their parents the same?
        elif self._script.utilities.isSameObject(cur_obj.parent, obj.parent):
            # Translators: this announces that the current object's parent and 
            # the parent of the object pointed to by the bookmark are the same.
            #
            self._script.presentMessage(
                _('bookmark and current object have same parent'))
            return

        # Do they share a common ancestor?
        # bookmark's ancestors
        bookmark_ancestors = []
        p = obj.parent
        while p:
            bookmark_ancestors.append(p)
            p = p.parent
        # look at current object's ancestors to compare to bookmark's ancestors
        p = cur_obj.parent
        while p:
            if bookmark_ancestors.count(p) > 0:
                rolename = p.getLocalizedRoleName()
                # Translators: this announces that the bookmark and the current
                # object share a common ancestor
                #
                self._script.presentMessage(_('shared ancestor %s') % rolename)
                return
            p = p.parent

        # Translators: This announces that a comparison between the bookmark
        # and the current object can not be determined.
        #
        self._script.presentMessage(_('comparison unknown'))
    def __init__(self):
        Gtk.MessageDialog.__init__(self)
        self.set_property('message-type', Gtk.MessageType.QUESTION)

        self.set_property('text', _('Quit Orca?'))
        self.format_secondary_text(
            _('This will stop all speech and braille output.'))

        self.add_button('gtk-cancel', Gtk.ResponseType.CANCEL)
        self.add_button('gtk-quit', Gtk.ResponseType.ACCEPT)

        self.connect('response', self.onResponse)
        self.connect('destroy', self.onDestroy)
 def saveBookmarks(self, inputEvent):
     """ Save the bookmarks for this script. """        
     try:
         self._saveBookmarksToDisk(self._bookmarks)
         # Translators: this announces that a bookmark has been saved to 
         # disk
         #
         speech.speak(_('bookmarks saved'))
     except IOError:
         # Translators: this announces that a bookmark could not be saved to 
         # disk
         #
         speech.speak(_('bookmarks could not be saved'))
Exemple #13
0
 def saveBookmarks(self, inputEvent):
     """ Save the bookmarks for this script. """
     try:
         self._saveBookmarksToDisk(self._bookmarks)
         # Translators: this announces that a bookmark has been saved to
         # disk
         #
         speech.speak(_('bookmarks saved'))
     except IOError:
         # Translators: this announces that a bookmark could not be saved to
         # disk
         #
         speech.speak(_('bookmarks could not be saved'))
def shutdown(script=None, inputEvent=None):
    """Exits Orca.  Unregisters any event listeners and cleans up.  Also
    quits the bonobo main loop and resets the initialized state to False.

    Returns True if the shutdown procedure ran or False if this module
    was never initialized.
    """

    global _initialized

    if not _initialized:
        return False

    # Try to say goodbye, but be defensive if something has hung.
    #
    if settings.timeoutCallback and (settings.timeoutTime > 0):
        signal.signal(signal.SIGALRM, settings.timeoutCallback)
        signal.alarm(settings.timeoutTime)

    # Translators: this is what Orca speaks and brailles when it quits.
    #
    speech.speak(_("Goodbye."))
    braille.displayMessage(_("Goodbye."))

    # Deregister our event listeners
    #
    registry = atspi.Registry()
    registry.deregisterEventListener(_onChildrenChanged,
                                     "object:children-changed:")
    registry.deregisterEventListener(_onMouseButton,
                                     "mouse:button")

    if _currentPresentationManager >= 0:
        _PRESENTATION_MANAGERS[_currentPresentationManager].deactivate()

    # Shutdown all the other support.
    #
    if settings.enableSpeech:
        speech.shutdown()
    if settings.enableBraille:
        braille.shutdown();
    if settings.enableMagnifier:
        mag.shutdown();

    registry.stop()

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

    _initialized = False
    return True
    def _populateKeyBindings(self, clearModel=True):
        """Fills the TreeView with the list of Orca keybindings. The
        application specific ones are prepended to the list.

        Arguments:        
        - clearModel: if True, initially clear out the key bindings model. 
        """

        if clearModel:
            self.keyBindingsModel.clear()

        # Get the key bindings for the application script.
        #
        self.appKeyBindings = appScript.getKeyBindings()
        self.appKeyBindings = appScript.overrideAppKeyBindings(appScript, self.appKeyBindings)

        # Get the key bindings for the default script.
        #
        defScript = _scriptManager.getDefaultScript()
        self.defKeyBindings = defScript.getKeyBindings()

        iterApp = self._createNode(applicationName)
        iterOrca = self._createNode(_("Orca"))

        # Translators: this refers to commands that do not currently have
        # an associated key binding.
        #
        iterUnbound = self._createNode(_("Unbound"))

        # Find the key bindings that are in the application script but
        # not in the default script.
        #
        for kb in self.appKeyBindings.keyBindings:
            if not self.defKeyBindings.hasKeyBinding(kb, "description"):
                node = iterApp
            elif kb.keysymstring:
                node = iterOrca
            else:
                node = iterUnbound
            if not self._addAlternateKeyBinding(kb):
                handl = appScript.getInputEventHandlerKey(kb.handler)
                self._insertRow(handl, kb, node)

        if not self.keyBindingsModel.iter_has_child(iterApp):
            self.keyBindingsModel.remove(iterApp)

        # Call the parent class to add braille bindings and finish
        # setting up the tree view.
        #
        self.kbindings = self.appKeyBindings
        orca_gui_prefs.OrcaSetupGUI._populateKeyBindings(self, False)
Exemple #16
0
def shutdown(script=None, inputEvent=None):
    """Exits Orca.  Unregisters any event listeners and cleans up.  Also
    quits the bonobo main loop and resets the initialized state to False.

    Returns True if the shutdown procedure ran or False if this module
    was never initialized.
    """

    global _initialized

    if not _initialized:
        return False

    # Try to say goodbye, but be defensive if something has hung.
    #
    if settings.timeoutCallback and (settings.timeoutTime > 0):
        signal.signal(signal.SIGALRM, settings.timeoutCallback)
        signal.alarm(settings.timeoutTime)

    # Translators: this is what Orca speaks and brailles when it quits.
    #
    speech.speak(_("Goodbye."))
    braille.displayMessage(_("Goodbye."))

    # Deregister our event listeners
    #
    registry = atspi.Registry()
    registry.deregisterEventListener(_onChildrenChanged,
                                     "object:children-changed:")
    registry.deregisterEventListener(_onMouseButton, "mouse:button")

    if _currentPresentationManager >= 0:
        _PRESENTATION_MANAGERS[_currentPresentationManager].deactivate()

    # Shutdown all the other support.
    #
    if settings.enableSpeech:
        speech.shutdown()
    if settings.enableBraille:
        braille.shutdown()
    if settings.enableMagnifier:
        mag.shutdown()

    registry.stop()

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

    _initialized = False
    return True
Exemple #17
0
    def bookmarkCurrentWhereAmI(self, inputEvent):
        """ Report "Where am I" information for this bookmark relative to the 
        current pointer location."""
        try:
            context = self._bookmarkToContext(
                self._bookmarks[inputEvent.hw_code])
        except KeyError:
            self._script.systemBeep()
            return

        obj = context.getCurrentAccessible()
        cur_obj = orca_state.locusOfFocus

        # Are they the same object?
        if self._script.isSameObject(cur_obj, obj):
            # Translators: this announces that the current object is the same
            # object pointed to by the bookmark.
            #
            speech.speak(_('bookmark is current object'))
            return
        # Are their parents the same?
        elif self._script.isSameObject(cur_obj.parent, obj.parent):
            # Translators: this announces that the current object's parent and
            # the parent of the object pointed to by the bookmark are the same.
            #
            speech.speak(_('bookmark and current object have same parent'))
            return

        # Do they share a common ancestor?
        # bookmark's ancestors
        bookmark_ancestors = []
        p = obj.parent
        while p:
            bookmark_ancestors.append(p)
            p = p.parent
        # look at current object's ancestors to compare to bookmark's ancestors
        p = cur_obj.parent
        while p:
            if bookmark_ancestors.count(p) > 0:
                # Translators: this announces that the bookmark and the current
                # object share a common ancestor
                #
                speech.speak(_('shared ancestor %s') % p.role)
                return
            p = p.parent

        # Translators: This announces that a comparison between the bookmark
        # and the current object can not be determined.
        #
        speech.speak(_('comparison unknown'))
Exemple #18
0
def showPreferencesUI():
    global applicationName, appScript

    # There must be an application with focus for this to work.
    #
    if not orca_state.locusOfFocus or not orca_state.locusOfFocus.getApplication():
        message = _("No application has focus.")
        braille.displayMessage(message)
        speech.speak(message)
        return

    appScript = orca_state.activeScript

    # The name of the application that currently has focus.
    #
    applicationName = orca_state.activeScript.app.name
    if not orca_state.appOS and not orca_state.orcaOS:
        # Translators: Orca Preferences in this case, is a configuration GUI
        # for allowing users to set application specific settings from within
        # Orca for the application that currently has focus.
        #
        line = _("Starting Orca Preferences for %s.") % applicationName
        appScript.presentMessage(line)

        prefsDict = orca_prefs.readPreferences()
        orca_state.prefsUIFile = os.path.join(
            orca_platform.prefix, orca_platform.datadirname, orca_platform.package, "ui", "orca-setup.ui"
        )

        orca_state.appOS = OrcaSetupGUI(orca_state.prefsUIFile, "orcaSetupWindow", prefsDict)
        orca_state.appOS.initAppGUIState(appScript)

        orca_state.appOS.init()
    else:
        if not orca_state.orcaWD:
            orca_state.orcaWarningDialogUIFile = os.path.join(
                orca_platform.prefix,
                orca_platform.datadirname,
                orca_platform.package,
                "ui",
                "orca-preferences-warning.ui",
            )
            orca_state.orcaWD = WarningDialogGUI(orca_state.orcaWarningDialogUIFile, "orcaPrefsWarningDialog")
            warningDialog = orca_state.orcaWD.getPrefsWarningDialog()
            warningDialog.realize()
            warningDialog.show()
        return

    orca_state.appOS.showGUI()
    def _getSpeechForLabel(self, obj, already_focused):
        """Get the speech for a label.

        Arguments:
        - obj: the label
        - already_focused: False if object just received focus

        Returns a list of utterances to be spoken for the object.
        """

        utterances=[]
        if (not already_focused):
            utterances = self._getDefaultSpeech(obj, already_focused)

        obj.was_selected = False
        if obj.state.count(Accessibility.STATE_EXPANDED) != 0:
            # Translators: this represents the state of a node in a tree.
            # 'expanded' means the children are showing.
            # 'collapsed' means the children are not showing.
            #
            utterances.append(_("expanded"))
        elif obj.state.count(Accessibility.STATE_EXPANDED) == 0 and \
                obj.state.count(Accessibility.STATE_EXPANDABLE) != 0:
            # Translators: this represents the state of a node in a tree.
            # 'expanded' means the children are showing.
            # 'collapsed' means the children are not showing.
            #
            utterances.append(_("collapsed"))
        elif obj.state.count(Accessibility.STATE_SELECTED) != 0:
            # Translators: this represents the state of a node in a tree
            # or list.
            #
            # ONLY TRANSLATE THE PART AFTER THE PIPE CHARACTER |
            utterances.append(Q_("listitem|selected"))
            obj.was_selected = True
        elif obj.state.count(Accessibility.STATE_SELECTED) == 0 and \
                obj.state.count(Accessibility.STATE_SELECTABLE) != 0:
            # Translators: this represents the state of a node in a tree
            # or list.
            #
            # ONLY TRANSLATE THE PART AFTER THE PIPE CHARACTER |
            utterances.append(Q_("listitem|unselected"))

        self._debugGenerator("_getSpeechForLabel",
                             obj,
                             already_focused,
                             utterances)

        return utterances
    def _getTutorialForPushButton(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a push button

        Arguments:
        - obj: the push button
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is the tutorial string for activating a push button.
        msg = _("To activate press space.")

        if (not alreadyFocused and self.lastTutorial != [msg]) \
           or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForPushButton",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForPageTab(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a page tab.

        Arguments:
        - obj: the page tab
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of tutorial utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is the tutorial string for landing
        # on a page tab, we are informing the
        # user how to navigate these.
        msg = _("Use left and right to view other tabs.")

        if (self.lastTutorial != [msg]) or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForPageTabList",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForText(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a text object.

        Arguments:
        - obj: the text component
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of tutorial utterances to be spoken for the object.
        """
        utterances = []
        # Translators: This is the tutorial string for when landing
        # on text fields.
        msg = _("Type in text.")

        if (not alreadyFocused or forceTutorial) and \
           not self._script.utilities.isReadOnlyTextArea(obj):
            utterances.append(msg)

        self._debugGenerator("_getTutorialForText",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForList(self, obj, alreadyFocused, forceTutorial):
        """Get the  tutorial string for a list.

        Arguments:
        - obj: the list
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of tutorial utterances to be spoken for the object.
        """

        utterances = []

        # Translators: this is the tutorial string when navigating lists.
        msg = _("Use up and down to select an item.")

        if (not alreadyFocused and self.lastTutorial != [msg]) \
           or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForList",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForSpinButton(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a spin button.  If the object already has
        focus, then no tutorial is given.

        Arguments:
        - obj: the spin button
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is the tutorial string for when landing
        # on a spin button.
        msg = _("Use up or down arrow to select value." \
              " Or type in the desired numerical value.")

        if (not alreadyFocused and self.lastTutorial != [msg]) \
           or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForSpinButton",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForFrame(self, obj, alreadyFocused, forceTutorial):
        """Get the  tutorial string for a frame.

        Arguments:
        - obj: the frame
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of tutorial utterances to be spoken for the object.
        """

        utterances = []
        name = self._script.utilities.displayedText(obj)
        if not name and obj.description:
            name = obj.description

        # Translators: If this application has more than one unfocused alert or
        # dialog window, inform user of how to refocus these.
        childWindowsMsg = _("Press alt+f6 to give focus to child windows.")

        # If this application has more than one unfocused alert or
        # dialog window, tell user how to give them focus.
        alertAndDialogCount = \
                    self._script.utilities.unfocusedAlertAndDialogCount(obj)
        if alertAndDialogCount > 0:
            utterances.append(childWindowsMsg)

        self._debugGenerator("_getTutorialForFrame",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def _getTutorialForComboBox(self, obj, alreadyFocused, forceTutorial):
        """Get the  tutorial string for a combobox.

        Arguments:
        - obj: the combo box
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of tutorial utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is a tip for the user on how to interact
        # with a combobox.
        msg = _("Press space to expand, and use up and down to select an item.")

        if (not alreadyFocused and self.lastTutorial != [msg]) \
           or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForComboBox",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
 def getFactoryName():
     """Returns a localized name describing this factory."""
     # Translators: this refers to the speech synthesis services
     # provided by the separate emacspeak utility available at
     # http://emacspeak.sourceforge.net/.
     #
     return _("Emacspeak Speech Services")
Exemple #28
0
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_title(_("Orca Screen Reader"))
        self.set_has_resize_grip(False)

        grid = Gtk.Grid()
        grid.set_border_width(5)
        self.add(grid)

        preferencesButton = Gtk.Button.new_from_stock("gtk-preferences")
        preferencesButton.connect("clicked", orca.showPreferencesGUI)
        grid.attach(preferencesButton, 0, 0, 1, 1)

        quitButton = Gtk.Button.new_from_stock("gtk-quit")
        quitButton.connect("clicked", orca.quitOrca)
        grid.attach(quitButton, 1, 0, 1, 1)

        self.aboutDialog = None
        aboutButton = Gtk.Button.new_from_stock("gtk-about")
        aboutButton.connect("clicked", self.aboutButtonClicked)
        grid.attach(aboutButton, 2, 0, 1, 1)

        helpButton = Gtk.Button.new_from_stock("gtk-help")
        helpButton.connect("clicked", orca.helpForOrca)
        grid.attach(helpButton, 3, 0, 1, 1)

        accelGroup = Gtk.AccelGroup()
        (keyVal, modMask) = Gtk.accelerator_parse("F1")
        helpButton.add_accelerator("clicked", accelGroup, keyVal, modMask, 0)
        self.add_accel_group(accelGroup)

        self.connect("destroy", self.onDestroy)
Exemple #29
0
    def toggleMessageHistories(self, script, inputEvent):
        """ Toggle whether we provide chat room specific message histories.

        Arguments:
        - script: the script associated with this event
        - inputEvent: if not None, the input event that caused this action.
        """

        line = _("Provide chat room specific message histories.")
        roomHistories = _settingsManager.getSetting("chatRoomHistories")
        _settingsManager.setSetting("chatRoomHistories", not roomHistories)
        if roomHistories:
            line = _("Do not provide chat room specific message histories.")
        self._script.presentMessage(line)

        return True
Exemple #30
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)
Exemple #31
0
    def utterMessage(self, chatRoomName, message, focused=True):
        """ Speak/braille a chat room message.

        Arguments:
        - chatRoomName: name of the chat room this message came from
        - message: the chat room message
        - focused: whether or not the current chatroom has focus. Defaults
          to True so that we can use this method to present chat history
          as well as incoming messages.
        """

        # Only speak/braille the new message if it matches how the user
        # wants chat messages spoken.
        #
        verbosity = self._script.getSettings().chatMessageVerbosity
        if orca_state.activeScript.name != self._script.name and verbosity == settings.CHAT_SPEAK_ALL_IF_FOCUSED:
            return
        elif not focused and verbosity == settings.CHAT_SPEAK_FOCUSED_CHANNEL:
            return

        text = ""
        if _settingsManager.getSetting("chatSpeakRoomName") and chatRoomName:
            text = _("Message from chat room %s") % chatRoomName
        text = self._script.utilities.appendString(text, message)

        if len(text.strip()):
            speech.speak(text)
        self._script.displayBrailleMessage(text)
Exemple #32
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)
Exemple #33
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)
Exemple #34
0
    def toggleBuddyTyping(self, script, inputEvent):
        """ Toggle whether we announce when our buddies are typing a message.

        Arguments:
        - script: the script associated with this event
        - inputEvent: if not None, the input event that caused this action.
        """

        line = _("announce when your buddies are typing.")
        announceTyping = _settingsManager.getSetting("chatAnnounceBuddyTyping")
        _settingsManager.setSetting("chatAnnounceBuddyTyping", not announceTyping)
        if announceTyping:
            line = _("Do not announce when your buddies are typing.")
        self._script.presentMessage(line)

        return True
Exemple #35
0
 def getFactoryName():
     """Returns a localized name describing this factory."""
     # Translators: this refers to the speech synthesis services
     # provided by the separate emacspeak utility available at
     # http://emacspeak.sourceforge.net/.
     #
     return _("Emacspeak Speech Services")
    def _getTutorialForSlider(self, obj, alreadyFocused, forceTutorial):
        """Get the tutorial string for a slider.  If the object already has
        focus, then no tutorial is given.

        Arguments:
        - obj: the slider
        - alreadyFocused: False if object just received focus
        - forceTutorial: used for when whereAmI really needs the tutorial string

        Returns a list of utterances to be spoken for the object.
        """

        utterances = []
        # Translators: this is the tutorial string for when landing
        # on a slider.
        msg = _("To decrease press left arrow, to increase press right arrow." \
          " To go to minimum press home, and for maximum press end.")

        if (not alreadyFocused and self.lastTutorial != [msg]) \
           or forceTutorial:
            utterances.append(msg)

        self._debugGenerator("_getTutorialForSlider",
                             obj,
                             alreadyFocused,
                             utterances)

        return utterances
    def localize_widget(self, obj):
        """Force the localization of the label/title of GtkBuilder objects

        Arguments:
        - obj: the GtkBuilder object whose label or title should be localized
        """

        # TODO - JD: This is a workaround for a GtkBuilder bug which prevents
        # the strings displayed by widgets from being translated. See bgo bug
        # 589362.
        #
        try:
            useMarkup = obj.get_use_markup()
            useUnderline = obj.get_use_underline()
        except:
            useMarkup = False
            useUnderline = False

        if isinstance(obj, Gtk.Frame):
            # For some reason, if we localize the frame, which has a label
            # but does not (itself) support use_markup, we get unmarked
            # labels which are not bold but which do have <b></b>. If we
            # skip the frames, the labels get processed as expected. And
            # there was much rejoicing. Yea.
            #
            return

        try:
            title = obj.get_title()
            if title and len(title):
                obj.set_title(_(title))
        except:
            try:
                text = obj.get_label()
            except:
                return False

            if text and len(text):
                if useMarkup:
                    obj.set_markup(_(text))
                else:
                    obj.set_label(_(text))

        if useUnderline:
            obj.set_use_underline(True)

        return True
Exemple #38
0
    def _getSpeechForLabel(self, obj, already_focused):
        """Get the speech for a label.

        Arguments:
        - obj: the label
        - already_focused: False if object just received focus

        Returns a list of utterances to be spoken for the object.
        """

        utterances = []
        if (not already_focused):
            utterances = self._getDefaultSpeech(obj, already_focused)

        obj.was_selected = False
        if obj.state.count(Accessibility.STATE_EXPANDED) != 0:
            # Translators: this represents the state of a node in a tree.
            # 'expanded' means the children are showing.
            # 'collapsed' means the children are not showing.
            #
            utterances.append(_("expanded"))
        elif obj.state.count(Accessibility.STATE_EXPANDED) == 0 and \
                obj.state.count(Accessibility.STATE_EXPANDABLE) != 0:
            # Translators: this represents the state of a node in a tree.
            # 'expanded' means the children are showing.
            # 'collapsed' means the children are not showing.
            #
            utterances.append(_("collapsed"))
        elif obj.state.count(Accessibility.STATE_SELECTED) != 0:
            # Translators: this represents the state of a node in a tree
            # or list.
            #
            # ONLY TRANSLATE THE PART AFTER THE PIPE CHARACTER |
            utterances.append(Q_("listitem|selected"))
            obj.was_selected = True
        elif obj.state.count(Accessibility.STATE_SELECTED) == 0 and \
                obj.state.count(Accessibility.STATE_SELECTABLE) != 0:
            # Translators: this represents the state of a node in a tree
            # or list.
            #
            # ONLY TRANSLATE THE PART AFTER THE PIPE CHARACTER |
            utterances.append(Q_("listitem|unselected"))

        self._debugGenerator("_getSpeechForLabel", obj, already_focused,
                             utterances)

        return utterances
Exemple #39
0
def _toggleSilenceSpeech(script=None, inputEvent=None):
    """Toggle the silencing of speech.

    Returns True to indicate the input event has been consumed.
    """
    speech.stop()
    if settings.silenceSpeech:
        settings.silenceSpeech = False
        # Translators: this is a spoken prompt letting the user know
        # that speech synthesis has been turned back on.
        #
        speech.speak(_("Speech enabled."))
    else:
        # Translators: this is a spoken prompt letting the user know
        # that speech synthesis has been temporarily turned off.
        #
        speech.speak(_("Speech disabled."))
        settings.silenceSpeech = True
    return True
Exemple #40
0
def showPreferencesUI():
    """Uses the console to query the user for Orca preferences."""

    prefsDict = {}

    if not setupSpeech(prefsDict):
        prefsDict["enableSpeech"] = False
        prefsDict["enableEchoByWord"] = False
        prefsDict["enableKeyEcho"] = False

    # Translators: this is prompting for whether the user wants to use a
    # refreshable braille display (an external hardware device) or not.
    #
    answer = sayAndPrint(_("Enable Braille?  Enter y or n: "), True, True,
                         speechServerChoice, speechVoiceChoice)
    prefsDict["enableBraille"] = checkYes(answer)

    # Translators: the braille monitor is a graphical display on the screen
    # that is used for debugging and demoing purposes.  It presents what
    # would be (or is being) shown on the external refreshable braille
    # display.
    #
    answer = sayAndPrint(_("Enable Braille Monitor?  Enter y or n: "), True,
                         True, speechServerChoice, speechVoiceChoice)
    prefsDict["enableBrailleMonitor"] = checkYes(answer)

    logoutNeeded = orca_prefs.writePreferences(prefsDict)
    if logoutNeeded:
        sayAndPrint(
            _("Accessibility support for GNOME has just been enabled."),
            logoutNeeded, False, speechServerChoice, speechVoiceChoice)
        sayAndPrint(
            _("You need to log out and log back in for the change to take effect."
              ), False, False, speechServerChoice, speechVoiceChoice)

        if desktopRunning:
            answer = sayAndPrint(
                _("Do you want to logout now?  Enter y or n: "), False, True,
                speechServerChoice, speechVoiceChoice)
            if checkYes(answer):
                sayAndPrint(_("Setup complete. Logging out now."), False,
                            False, speechServerChoice, speechVoiceChoice)
                time.sleep(2)

                import bonobo
                import gobject

                gobject.threads_init()
                gobject.idle_add(logoutUser)
                bonobo.main()

    answer = sayAndPrint(_("Setup complete.  Press Return to continue."),
                         not logoutNeeded, True, speechServerChoice,
                         speechVoiceChoice)

    for [factory, servers] in workingFactories:
        factory.SpeechServer.shutdownActiveServers()
Exemple #41
0
def getModifierNames(mods):
    """Gets the modifier names of a numeric modifier mask as a human
    consumable string.
    """

    text = ""
    if mods & (1 << settings.MODIFIER_ORCA):
        text += _("Orca") + "+"
    #if mods & (1 << atspi.Accessibility.MODIFIER_NUMLOCK):
    #    text += _("Num_Lock") + "+"
    if mods & 128:
        # Translators: this is presented in a GUI to represent the
        # "right alt" modifier.
        #
        text += _("Alt_R") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_META3):
        # Translators: this is presented in a GUI to represent the
        # "super" modifier.
        #
        text += _("Super") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_META2):
        # Translators: this is presented in a GUI to represent the
        # "meta 2" modifier.
        #
        text += _("Meta2") + "+"
    #if mods & (1 << atspi.Accessibility.MODIFIER_META):
    #    text += _("Meta") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_ALT):
        # Translators: this is presented in a GUI to represent the
        # "left alt" modifier.
        #
        text += _("Alt_L") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_CONTROL):
        # Translators: this is presented in a GUI to represent the
        # "control" modifier.
        #
        text += _("Ctrl") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_SHIFTLOCK):
        # Translators: this is presented in a GUI to represent the
        # "caps lock" modifier.
        #
        text += _("Caps_Lock") + "+"
    if mods & (1 << atspi.Accessibility.MODIFIER_SHIFT):
        # Translators: this is presented in a GUI to represent the
        # "shift " modifier.
        #
        text += _("Shift") + "+"
    return text
Exemple #42
0
    def startingPointChanged(self, widget):
        """Signal handler for the "toggled" signal for the
           currentLocationRadioButton or topRadioButton GtkRadioButton
           widgets. The user has toggled the starting point for the search.

        Arguments:
        - widget: the component that generated the signal.
        """

        if widget.get_active():
            if widget.get_label() == _("C_urrent location"):
                self.startAtTop = False
            else:
                self.startAtTop = True
Exemple #43
0
    def _showGUI(self):
        """Show the app-specific Orca configuration GUI window. This 
        assumes that the GUI has already been created.
        """

        # Adjust the title of the app-specific Orca Preferences dialog to
        # include the name of the application.
        #
        self.app = orca_state.locusOfFocus.app
        self.applicationName = self.app.name
        title = _("Orca Preferences for %s") % self.applicationName
        self.orcaSetupWindow.set_title(title)

        orca_gui_prefs.orcaSetupGUI._showGUI(self)
Exemple #44
0
    def addBookmark(self, inputEvent):
        """ Add an in-page accessible object bookmark for this key. """
        context = self._script.getFlatReviewContext()
        self._bookmarks[inputEvent.hw_code] = self._contextToBookmark(context)

        # Translators: this announces that a bookmark has been entered.
        # Orca allows users to tell it to remember a particular spot in an
        # application window and provides keystrokes for the user to jump to
        # those spots.  These spots are known as 'bookmarks'.
        #
        utterances = [_('bookmark entered')]
        utterances.extend(self._script.speechGenerator.getSpeech( \
                          context.getCurrentAccessible(), False))
        speech.speakUtterances(utterances)
Exemple #45
0
def showPreferencesUI():
    global applicationName, appScript, OS

    # There must be an application with focus for this to work.
    #
    if not orca_state.locusOfFocus or not orca_state.locusOfFocus.app:
        message = _("No application has focus.")
        braille.displayMessage(message)
        speech.speak(message)
        return

    appScript = orca_state.activeScript

    # The name of the application that currently has focus.
    #
    applicationName = orca_state.locusOfFocus.app.name

    # Translators: Orca Preferences in this case, is a configuration GUI
    # for allowing users to set application specific settings from within
    # Orca for the application that currently has focus.
    #
    line = _("Starting Orca Preferences for %s. This may take a while.") % \
           applicationName
    braille.displayMessage(line)
    speech.speak(line)

    removeGeneralPane = False
    if not OS:
        gladeFile = os.path.join(platform.prefix, platform.datadirname,
                                 platform.package, "glade", "orca-setup.glade")
        OS = orcaSetupGUI(gladeFile, "orcaSetupWindow")
        removeGeneralPane = True

    OS._init()
    if removeGeneralPane:
        OS._initAppGUIState(appScript)
    OS._showGUI()
Exemple #46
0
    def __init__(self, id):
        self._id = id
        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.
        #
        self._default_voice_name = _("%s default voice") % id

        try:
            self._init()
        except Exception, e:
            debug.println(
                debug.LEVEL_WARNING,
                "Speech Dispatcher service failed to connect: %s" % e)
Exemple #47
0
    def speakKeyEvent(self, event_string, type):
        """Speaks a key event immediately.

        Arguments:
        - event_string: string representing the key event as defined by
                        input_event.KeyboardEvent.
        - type:         key event type as one of orca.KeyEventType constants.

        """
        if type == orca.KeyEventType.PRINTABLE and \
               event_string.decode("UTF-8").isupper():
            voice = settings.voices[settings.UPPERCASE_VOICE]
        else:
            voice = settings.voices[settings.DEFAULT_VOICE]

        # Check to see if there are localized words to be spoken for
        # this key event.
        #
        event_string = keynames.getKeyName(event_string)

        if type == orca.KeyEventType.LOCKING_LOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("on")
        elif type == orca.KeyEventType.LOCKING_UNLOCKED:
            # Translators: this represents the state of a locking modifier
            # key (e.g., Caps Lock)
            #
            event_string += " " + _("off")

        debug.println(debug.LEVEL_INFO,
                      "SPEECH OUTPUT: '" + event_string + "'")
        log.info("speakKeyEvent utterance='%s'" % event_string)

        self.speak(event_string, acss=voice)
Exemple #48
0
def _onChildrenChanged(e):
    """Tracks children-changed events on the desktop to determine when
    apps start and stop.

    Arguments:
    - e: at-spi event from the at-api registry
    """

    registry = atspi.Registry()
    if e.source == registry.desktop:

        # If the desktop is empty, the user has logged out-- shutdown Orca
        #
        try:
            if registry.desktop.childCount == 0:
                speech.speak(_("Goodbye."))
                shutdown()
                return
        except:  # could be a CORBA.COMM_FAILURE
            debug.printException(debug.LEVEL_FINEST)
            shutdown()
            return
Exemple #49
0
def _processKeyCaptured(event):
    """Called when a new key event arrives and orca_state.capturingKeys=True.
    (used for key bindings redefinition)
    """

    if event.type == 0:
        if _isModifierKey(event.event_string) \
               or event.event_string == "Return":
            pass
        elif event.event_string == "Escape":
            orca_state.capturingKeys = False
        else:
            # Translators: this is a spoken prompt letting the user know
            # Orca has recorded a new key combination (e.g., Alt+Ctrl+g)
            # based upon their input.
            #
            speech.speak(_("Key captured: %s. Press enter to confirm.") \
                         % str(event.event_string))
            orca_state.lastCapturedKey = event
    else:
        pass
    return False
Exemple #50
0
    def _dequeueEvent(self):
        """Handles all events destined for scripts.  Called by the GTK
        idle thread.
        """

        rerun = True

        if settings.debugEventQueue:
            debug.println(debug.LEVEL_ALL,
                          "Entering focus_tracking_presenter._dequeueEvent" \
                          + " %d" % self._dequeueEventCount)
            self._dequeueEventCount += 1

        try:
            event = self._eventQueue.get_nowait()

            if isinstance(event, input_event.KeyboardEvent):
                if event.type == atspi.Accessibility.KEY_PRESSED_EVENT:
                    debug.println(debug.LEVEL_ALL,
                                  "DEQUEUED KEYPRESS '%s' (%d) <----------" \
                                  % (event.event_string, event.hw_code))
                    pressRelease = "PRESS"
                elif event.type == atspi.Accessibility.KEY_RELEASED_EVENT:
                    debug.println(debug.LEVEL_ALL,
                                  "DEQUEUED KEYRELEASE '%s' (%d) <----------" \
                                  % (event.event_string, event.hw_code))
                    pressRelease = "RELEASE"
                debug.println(debug.eventDebugLevel,
                              "\nvvvvv PROCESS KEY %s EVENT %s vvvvv"\
                              % (pressRelease, event.event_string))
                self._processKeyboardEvent(event)
                debug.println(debug.eventDebugLevel,
                              "\n^^^^^ PROCESS KEY %s EVENT %s ^^^^^"\
                              % (pressRelease, event.event_string))
            elif isinstance(event, input_event.BrailleEvent):
                debug.println(debug.LEVEL_ALL,
                              "DEQUEUED BRAILLE COMMAND %d <----------" \
                              % event.event)
                debug.println(debug.eventDebugLevel,
                              "\nvvvvv PROCESS BRAILLE EVENT %d vvvvv"\
                              % event.event)
                self._processBrailleEvent(event)
                debug.println(debug.eventDebugLevel,
                              "\n^^^^^ PROCESS BRAILLE EVENT %d ^^^^^"\
                              % event.event)
            else:
                if (not debug.eventDebugFilter) \
                    or (debug.eventDebugFilter \
                        and debug.eventDebugFilter.match(event.type)):
                    debug.println(debug.LEVEL_ALL,
                                  "DEQUEUED EVENT %s <----------" \
                                  % event.type)
                    debug.println(debug.eventDebugLevel,
                                  "\nvvvvv PROCESS OBJECT EVENT %s vvvvv" \
                                  % event.type)
                self._processObjectEvent(event)
                if (not debug.eventDebugFilter) \
                    or (debug.eventDebugFilter \
                        and debug.eventDebugFilter.match(event.type)):
                    debug.println(debug.eventDebugLevel,
                                  "^^^^^ PROCESS OBJECT EVENT %s ^^^^^\n" \
                                  % event.type)

            # [[[TODO: HACK - it would seem logical to only do this if we
            # discover the queue is empty, but this inroduces a hang for
            # some reason if done inside an acquire/release block for a
            # lock.  So...we do it here.]]]
            #
            noFocus = (not orca_state.activeScript) \
                      or ((not orca_state.locusOfFocus) \
                          and (self.noFocusTimestamp \
                               != orca_state.noFocusTimestamp))

            self._gidleLock.acquire()
            if self._eventQueue.empty():
                if noFocus:
                    if settings.gilSleepTime:
                        time.sleep(settings.gilSleepTime)
                    # Translators: this is intended to be a short phrase to
                    # speak and braille to tell the user that no component
                    # has keyboard focus.
                    #
                    message = _("No focus")
                    if settings.brailleVerbosityLevel == \
                        settings.VERBOSITY_LEVEL_VERBOSE:
                        braille.displayMessage(message)
                    if settings.speechVerbosityLevel == \
                        settings.VERBOSITY_LEVEL_VERBOSE:
                        speech.speak(message)
                    self.noFocusTimestamp = orca_state.noFocusTimestamp
                self._gidleId = 0
                rerun = False  # destroy and don't call again
            self._gidleLock.release()
        except Queue.Empty:
            debug.println(debug.LEVEL_SEVERE,
                          "focus_tracking_presenter:_dequeueEvent: " \
                          + " the event queue is empty!")
        except:
            debug.printException(debug.LEVEL_SEVERE)

        if settings.debugEventQueue:
            self._dequeueEventCount -= 1
            debug.println(debug.LEVEL_ALL,
                          "Leaving focus_tracking_presenter._dequeueEvent" \
                          + " %d" % self._dequeueEventCount)

        return rerun
Exemple #51
0
 def getFactoryName():
     # Translators: this is the name of a speech synthesis system
     # called "Speech Dispatcher".
     #
     return _("Speech Dispatcher")
Exemple #52
0
class SpeechServer(speechserver.SpeechServer):
    # See the parent class for documentation.

    _active_servers = {}

    DEFAULT_SERVER_ID = 'default'

    # Translators: "Default Synthesizer" will appear in the list of available
    # speech engines as a special item.  It refers to the default engine
    # configured within the speech subsystem.  Apart from this item, the user
    # will have a chance to select a particular speech engine by its real
    # name, such as Festival, IBMTTS, etc.
    #
    _SERVER_NAMES = {DEFAULT_SERVER_ID: _("Default Synthesizer")}

    KEY_NAMES = {
        '_': 'underscore',
        'space': 'space',
        '"': 'double-quote',
    }

    def getFactoryName():
        # Translators: this is the name of a speech synthesis system
        # called "Speech Dispatcher".
        #
        return _("Speech Dispatcher")

    getFactoryName = staticmethod(getFactoryName)

    def getSpeechServers():
        default = SpeechServer._getSpeechServer(SpeechServer.DEFAULT_SERVER_ID)
        servers = [default]
        for module in default.list_output_modules():
            servers.append(SpeechServer._getSpeechServer(module))
        return servers

    getSpeechServers = staticmethod(getSpeechServers)

    def _getSpeechServer(cls, id):
        """Return an active server for given id.

        Attempt to create the server if it doesn't exist yet.  Returns None
        when it is not possible to create the server.
        
        """
        if not cls._active_servers.has_key(id):
            cls(id)
        # Don't return the instance, unless it is succesfully added
        # to `_active_Servers'.
        return cls._active_servers.get(id)

    _getSpeechServer = classmethod(_getSpeechServer)

    def getSpeechServer(info=None):
        if info is not None:
            id = info[1]
        else:
            id = SpeechServer.DEFAULT_SERVER_ID
        return SpeechServer._getSpeechServer(id)

    getSpeechServer = staticmethod(getSpeechServer)

    def shutdownActiveServers():
        for server in SpeechServer._active_servers.values():
            server.shutdown()

    shutdownActiveServers = staticmethod(shutdownActiveServers)

    # *** Instance methods ***

    def __init__(self, id):
        self._id = id
        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.
        #
        self._default_voice_name = _("%s default voice") % id

        try:
            self._init()
        except Exception, e:
            debug.println(
                debug.LEVEL_WARNING,
                "Speech Dispatcher service failed to connect: %s" % e)
        else:
Exemple #53
0
    def __addVerbalizedPunctuation(self, oldText):
        """Depending upon the users verbalized punctuation setting,
        adjust punctuation symbols in the given text to their pronounced
        equivalents. The pronounced text will either replace the
        punctuation symbol or be inserted before it. In the latter case,
        this is to retain spoken prosity.

        If we are moving around by single characters, then always speak
        the punctuation. We try to detect this by looking for just a
        single character being spoken.

        Arguments:
        - oldText:      text to be parsed for punctuation.

        Returns a text string with the punctuation symbols adjusted accordingly.
        """

        # Translators: we replace the ellipses (both manual and UTF-8)
        # with a spoken string.  The extra space you see at the beginning
        # is because we need the speech synthesis engine to speak the
        # new string well.  For example, "Open..." turns into
        # "Open dot dot dot".
        #
        oldText = oldText.replace("...", _(" dot dot dot"), 1)
        oldText = oldText.replace("\342\200\246",  _(" dot dot dot"), 1)
        oldText = oldText.decode("UTF-8")

        ## Don't speak newlines unless the user is moving through text
        ## using a right or left arrow key.
        ##
        removeNewLines = True
        if orca_state.lastInputEvent and \
               orca_state.lastInputEvent.__dict__.has_key("event_string"):
            lastKey = orca_state.lastInputEvent.event_string
            if lastKey == "Left" or lastKey == "Right":
                removeNewLines = False

        if removeNewLines:
            oldText = oldText.replace("\n", "", 1)

        # Used to keep a list of character offsets into the new text string,
        # once it has been converted to use verbalized punctuation, one for 
        # each character in the original string.
        #
        self.textCharIndices = []
        style = settings.verbalizePunctuationStyle
        newText = ''
        for i in range(0, len(oldText)):
            self.textCharIndices.append(len(newText))
            try:
                level, action = \
                    punctuation_settings.getPunctuationInfo(oldText[i])

                # Special case for punctuation in text like filenames or URL's:
                #
                isPrev = isNext = isSpecial = False
                if i > 0:
                    isPrev = not (oldText[i - 1] in string.whitespace)
                if i < (len(oldText) - 1):
                    isNext = not (oldText[i + 1] in string.whitespace)

                # If this is a period and there is a non-space character
                # on either side of it, then always speak it.
                #
                isSpecial = isPrev and isNext and (oldText[i] == ".")

                # If this is a dash and the users punctuation level is not
                # NONE and the previous character is a white space character,
                # and the next character is a dollar sign or a digit, then
                # always speak it. See bug #392939.
                #
                prevCharMatches = nextCharMatches = False
                if orca_state.activeScript:
                    currencySymbols = \
                        orca_state.activeScript.getUnicodeCurrencySymbols()
                if i == 0:
                    prevCharMatches = True
                if i > 0:
                    prevCharMatches = (oldText[i - 1] in string.whitespace)
                if i < (len(oldText) - 1):
                    nextCharMatches = (oldText[i + 1] in string.digits or \
                                       oldText[i + 1] in currencySymbols)

                if oldText[i] == "-" and \
                   style != settings.PUNCTUATION_STYLE_NONE and \
                   prevCharMatches and nextCharMatches:
                    if isPrev:
                        newText += " "
                    # Translators: this is to be sent to a speech synthesis
                    # engine to prefix a negative number (e.g., "-56" turns
                    # into "minus 56".  We cannot always be sure of the type
                    # of the number (floating point, integer, mixed with other
                    # odd characters, etc.), so we need to unfortunately
                    # build up the utterance in this manner.
                    #
                    newText += _("minus")
                elif (len(oldText) == 1) or isSpecial or (style <= level):
                    if isPrev:
                        newText += " "
                    newText += chnames.getCharacterName(oldText[i])
                    if (action == punctuation_settings.PUNCTUATION_INSERT) \
                        and not isNext:
                        newText += oldText[i].encode("UTF-8")
                    if isNext:
                        newText += " "
                else:
                    newText += oldText[i].encode("UTF-8")
            except:
                if (len(oldText) == 1):
                    newText += chnames.getCharacterName(oldText[i])
                else:
                    newText += oldText[i].encode("UTF-8")

        return newText
Exemple #54
0
CMD_RESTARTSPEECH     = 0x44
CMD_MAX               = 0x44

BRL_FLG_REPEAT_INITIAL= 0x800000
BRL_FLG_REPEAT_DELAY  = 0x400000

# Common names for most used BrlTTY commands, to be shown in the GUI:
# ATM, the ones used in default.py are:
#
command_name = {}

# Translators: this is a command for a button on a refreshable braille
# display (an external hardware device used by people who are blind).
# When pressing the button, the display scrolls to the left.
#
command_name[CMD_FWINLT]   = _("Line Left")

# Translators: this is a command for a button on a refreshable braille
# display (an external hardware device used by people who are blind).
# When pressing the button, the display scrolls to the right.
#
command_name[CMD_FWINRT]   = _("Line Right")

# Translators: this is a command for a button on a refreshable braille
# display (an external hardware device used by people who are blind).
# When pressing the button, the display scrolls up.
#
command_name[CMD_LNUP]     = _("Line Up")

# Translators: this is a command for a button on a refreshable braille
# display (an external hardware device used by people who are blind).
Exemple #55
0
# a : alpha, b : bravo, c : charlie,
#
# And so on.  The complete set should consist of all the letters from
# the alphabet for your language paired with the common
# military/phonetic word(s) used to describe that letter.
#
# The Wikipedia entry
# http://en.wikipedia.org/wiki/NATO_phonetic_alphabet has a few
# interesting tidbits about local conventions in the sections
# "Additions in German, Danish and Norwegian" and "Variants".
#
__phonlist = _("a : alpha, b : bravo, c : charlie, "
               "d : delta, e : echo, f : foxtrot, "
               "g : golf, h : hotel, i : india, "
               "j : juliet, k : kilo, l : lima, "
               "m : mike, n : november, o : oscar, "
               "p : papa, q : quebec, r : romeo, "
               "s : sierra, t : tango, u : uniform, "
               "v : victor, w : whiskey, x : xray, "
               "y : yankee, z : zulu")

__phonnames = {}

for __pair in __phonlist.split(','):
    __w = __pair.split(':')
    __phonnames[__w[0].strip()] = __w[1].strip()


def getPhoneticName(character):
    """Given a character, return its phonetic name, which is typically
    the 'military' term used for the character.
Exemple #56
0
 def getFactoryName():
     """Returns a localized name describing this factory."""
     return _("GNOME Speech Services")
Exemple #57
0
        self.speech = speech


# [[[TODO: WDW - the AT-SPI also has getLocalizedRoleName, which might a
# more appropriate thing to use, as it covers the situation where an app
# has developed a brand new component with a brand new role. Logged as
# buzilla bug 319780.]]]
#
rolenames = {}

rolenames[ROLE_INVALID] = Rolename(\
    ROLE_INVALID,
    # Translators: short braille for the rolename of an invalid GUI object.
    # We strive to keep it under three characters to preserve real estate.
    #
    _("???"),
    # Translators: long braille for the rolename of an invalid object.
    # We typically make these 'camel' case.
    #
    _("Invalid"),
    # Translators: spoken words for the rolename of an invalid object.
    #
    _("invalid"))

rolenames[ROLE_ACCEL_LABEL] = Rolename(
    ROLE_ACCEL_LABEL,
    # Translators: short braille for an accelerator (what you see in a menu).
    # We strive to keep it under three characters to preserve real estate.
    #
    _("acc"),
    # Translators: long braille for an accelerator (what you see in a menu).