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)
예제 #2
0
def getValueForKey(prefsDict, key):
    need2repr = ['brailleEOLIndicator', 'brailleContractionTable',
                 'brailleRequiredStateString', 'enabledBrailledTextAttributes',
                 'enabledSpokenTextAttributes', 'speechRequiredStateString',
                 'speechServerFactory', 'presentDateFormat',
                 'presentTimeFormat']

    value = None
    if key in prefsDict:
        if type(prefsDict[key]) is str:
            if key in need2repr:
                value = "\'%s\'" % prefsDict[key]
            elif key  == 'voices':
                key = getVoiceKey(key)
                value = prefsDict[key]
            else:
                try:
                    value = getattr(settings, prefsDict[key])
                except:
                    debug.println(debug.LEVEL_SEVERE,
                                  "Something went wront with key: " % key)
                    debug.printStack(debug.LEVEL_FINEST)
        else:
            value = prefsDict[key]
    return value
예제 #3
0
    def load(self, keymap, handlers):
        """ Takes the keymappings and tries to find a matching named
           function in handlers.
           keymap is a list of lists, each list contains 5 elements
           If addUnbound is set to true, then at the end of loading all the
           keybindings, any remaining functions will be unbound.
        """


        for i in keymap:
            keysymstring = i[0]
            modifierMask = i[1]
            modifiers = i[2]
            handler = i[3]
            try:
                clickCount = i[4]
            except:
                clickCount = 1

            if handlers.has_key(handler):
                # add the keybinding
                self.add(KeyBinding( \
                  keysymstring, modifierMask, modifiers, \
                    handlers[handler], clickCount))
            else:
                debug.println(debug.LEVEL_WARNING, \
                  "WARNING: could not find %s handler to associate " \
                  "with keybinding." % handler)
예제 #4
0
    def skipObjectEvent(self, event):
        """Gives us, and scripts, the ability to decide an event isn't
        worth taking the time to process under the current circumstances.

        Arguments:
        - event: the Event

        Returns True if we shouldn't bother processing this object event.
        """

        cachedEvent, eventTime = self.eventCache.get(event.type, [None, 0])
        if not cachedEvent or cachedEvent == event:
            return False

        focus    = ["focus:", "object:state-changed:focused"]
        typing   = ["object:text-changed:insert", "object:text-changed:delete"]
        arrowing = ["object:text-caret-moved", "object:text-selection-changed",
                    "object:selection-changed"]

        skip = False
        if (event.type in arrowing or event.type in typing) \
           and event.source == cachedEvent.source:
            skip = True
            reason = "more recent event of the same type in the same object"
        elif event.type in focus and event.source != cachedEvent.source \
             and event.detail1 == cachedEvent.detail1:
            skip = True
            reason = "more recent event of the same type in a different object"

        if skip:
            debug.println(debug.LEVEL_FINE,
                          "script.skipObjectEvent: skipped due to %s" \
                          % reason)

        return skip
예제 #5
0
    def _isSimpleObject(self, obj):
        """Returns True if the given object has 'simple' contents, such as text
        without embedded objects or a single embedded object without text."""

        if not obj:
            return False

        try:
            children = [child for child in obj]
        except (LookupError, RuntimeError):
            debug.println(debug.LEVEL_FINE, 'Dead Accessible in %s' % obj)
            return False

        children = filter(lambda x: x.getRole() != pyatspi.ROLE_LINK, children)
        if len(children) > 1:
            return False

        try:
            text = obj.queryText()
        except NotImplementedError:
            return True

        string = text.getText(0, -1).decode('UTF-8').strip()
        if string.find(self._script.EMBEDDED_OBJECT_CHARACTER) > -1:
            return len(string) == 1

        return True
예제 #6
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()
    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
예제 #8
0
def getLongBrailleForRoleName(obj, role=None):
    """Returns the localized name of the given Accessible object; the name is
    a long string suitable for a Braille display.  If a localized name cannot
    be discovered, this will return the string as defined by the at-spi.

    Arguments:
    - obj: an Accessible object

    Returns a string containing the localized name of the object suitable for
    a Braille display.
    """

    role = _adjustRole(obj, role or obj.getRole())

    # If the enum is not in the dictionary, check by name.
    role_entry = \
        rolenames.get(role) or rolenames.get(obj.getRoleName())
    if role_entry:
        return role_entry.brailleLong
    else:
        debug.println(debug.LEVEL_WARNING, "No rolename for %s" % repr(role))
        localizedRoleName = obj.getLocalizedRoleName()
        if localizedRoleName and len(localizedRoleName):
            return localizedRoleName
        else:
            return repr(role)
예제 #9
0
def _speak(text, acss, interrupt):
    """Speaks the individual string using the given ACSS."""

    if settings.speakMultiCaseStringsAsWords:
        text = _processMultiCaseString(text)
    if orca_state.activeScript and orca_state.usePronunciationDictionary:
        text = orca_state.activeScript.utilities.adjustForPronunciation(text)
    if settings.speakMultiCaseStringsAsWords:
        text = _processMultiCaseString(text)

    logLine = "SPEECH OUTPUT: '" + text + "'"
    extraDebug = ""
    if acss in settings.voices.values():
        for key in settings.voices:
            if acss == settings.voices[key]:
                if key != settings.DEFAULT_VOICE:
                    extraDebug = " voice=%s" % key
                break

    try:
        extraDebug = extraDebug.encode("UTF-8")
    except UnicodeDecodeError:
        pass

    debug.println(debug.LEVEL_INFO, logLine + extraDebug)
    log.info(logLine + extraDebug)

    if _speechserver:
        voice = ACSS(settings.voices.get(settings.DEFAULT_VOICE))
        try:
            voice.update(acss)
        except:
            pass
        _speechserver.speak(text, __resolveACSS(voice), interrupt)
예제 #10
0
def speak(text, 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
    """

    # We will not interrupt a key echo in progress.
    #
    if orca_state.lastKeyEchoTime:
        interrupt = interrupt \
            and ((time.time() - orca_state.lastKeyEchoTime) > 0.5)

    if settings.silenceSpeech:
        return

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

    if _speechserver:
        _speechserver.speak(text, __resolveACSS(acss), interrupt)
예제 #11
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)
예제 #12
0
def speakUtterances(utterances, acss=None, interrupt=True):
    """Speaks the given list of utterances immediately.

    Arguments:
    - list:      list of strings 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.
    - interrupt: if True, stop any speech currently in progress.
    """

    # We will not interrupt a key echo in progress.
    #
    if orca_state.lastKeyEchoTime:
        interrupt = interrupt \
            and ((time.time() - orca_state.lastKeyEchoTime) > 0.5)

    if settings.silenceSpeech:
        return

    for utterance in utterances:
        debug.println(debug.LEVEL_INFO,
                      "SPEECH OUTPUT: '" + utterance + "'")
        log.info("speakUtterances utterance='%s'" % utterance)

    if _speechserver:
        _speechserver.speakUtterances(utterances,
                                       __resolveACSS(acss),
                                       interrupt)
예제 #13
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.")
    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)
    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)
예제 #16
0
    def _createScript(self, app, obj=None):
        """For the given application, create a new script instance."""

        moduleName = self.getModuleName(app)
        script = self._newNamedScript(app, moduleName)
        if script:
            return script

        objToolkit = self._toolkitForObject(obj)
        script = self._newNamedScript(app, objToolkit)
        if script:
            return script

        try:
            toolkitName = getattr(app, "toolkitName", None)
        except (LookupError, RuntimeError):
            msg = "Error getting toolkitName for: %s" % app
            debug.println(debug.LEVEL_FINE, msg)
        else:
            if app and toolkitName:
                script = self._newNamedScript(app, toolkitName)

        if not script:
            script = self.getDefaultScript(app)
            debug.println(debug.LEVEL_FINE, "Default script created")

        return script
예제 #17
0
    def speakKeyEvent(self, event):
        """Speaks a key event immediately.

        Arguments:
        - event: the input_event.KeyboardEvent.
        """
        if event.isPrintableKey() \
           and event.event_string.decode("UTF-8").isupper():
            voice = ACSS(settings.voices[settings.UPPERCASE_VOICE])
        else:
            voice = ACSS(settings.voices[settings.DEFAULT_VOICE])

        event_string = event.getKeyName()
        if orca_state.activeScript and orca_state.usePronunciationDictionary:
            event_string = orca_state.activeScript.\
                utilities.adjustForPronunciation(event_string)

        lockingStateString = event.getLockingStateString()
        event_string = "%s %s" % (event_string, lockingStateString)

        logLine = "SPEECH OUTPUT: '" + event_string +"'"
        debug.println(debug.LEVEL_INFO, logLine)
        log.info(logLine)

        self.speak(event_string, acss=voice)
예제 #18
0
def _showNotificationMessage(index):
    global indexNotificationMessages
    if not _messagesPresent():
        return

    if index < 1:
        index = 1
        # Translators: This is a brief message presented to the user when
        # when the top of a list of notifications is reached.
        #
        msg = C_("notification", "Top")
        _showMessage(msg)
    elif index > size():
        index = size()
        # Translators: This is a brief message presented to the user when
        # when the bottom of a list of notifications is reached.
        #
        msg = C_("notification", "Bottom")
        _showMessage(msg)

    indexNotificationMessages = index
    index = size() - index
    debug.println(debug.LEVEL_FINEST, \
                   "_showNotificationMessage (queue length: %s, index: %s)"\
                   % (size(), index))
    if index >= 0 and index < size():
        msg = notificationMessages[index]
        _showMessage(msg)
    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)
예제 #20
0
    def getModuleName(self, app):
        """Returns the module name of the script to use for application app."""

        try:
            appAndNameExist = app != None and app.name != ''
        except (LookupError, RuntimeError):
            appAndNameExist = False
            debug.println(debug.LEVEL_SEVERE,
                          "getModuleName: %s no longer exists" % app)

        if not appAndNameExist:
            return None

        # Many python apps have an accessible name which ends in '.py'.
        # Sometimes OOo has 'soffice.bin' as its name.
        name = app.name.split('.')[0]
        altNames = self._appNames.keys()

        names = filter(lambda n: n.lower() == name.lower(), altNames)
        if names:
            name = self._appNames.get(names[0])
        else:
            for nameList in (self._appModules, self._toolkitModules):
                names = filter(lambda n: n.lower() == name.lower(), nameList)
                if names:
                    name = names[0]
                    break

        debug.println(debug.LEVEL_FINEST, "mapped %s to %s" % (app.name, name))

        return name
예제 #21
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))
    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
예제 #23
0
    def processObjectEvent(self, event):
        """Processes all AT-SPI object events of interest to this
        script.  The interest in events is specified via the
        'listeners' field that was defined during the construction of
        this script.

        Note that this script may be passed events it doesn't care
        about, so it needs to react accordingly.

        Arguments:
        - event: the Event
        """

        if not event.source:
            msg = 'script.processObjectEvent: event.source went away'
            debug.println(debug.LEVEL_FINE, msg)
            return

        try:
            role = event.source.getRole()
        except (LookupError, RuntimeError):
            msg = 'script.processObjectEvent: Error getting role'
            debug.println(debug.LEVEL_FINE, msg)
            return

        # Check to see if we really want to process this event.
        #
        processEvent = (orca_state.activeScript == self \
                        or self.presentIfInactive)
        if role == pyatspi.ROLE_PROGRESS_BAR \
           and not processEvent \
           and settings.progressBarVerbosity == settings.PROGRESS_BAR_ALL:
            processEvent = True

        if not processEvent:
            return

        if self.skipObjectEvent(event):
            return

        # Clear the generator cache for each event.
        #
        self.generatorCache = {}

        # This calls the first listener it finds whose key *begins with* or is
        # the same as the event.type.  The reason we do this is that the event
        # type in the listeners dictionary may not be as specific as the event
        # type we received (e.g., the listeners dictionary might contain the
        # key "object:state-changed:" and the event.type might be
        # "object:state-changed:focused".  [[[TODO: WDW - the order of the
        # keys is *not* deterministic, and is not guaranteed to be related
        # to the order in which they were added.  So...we need to do something
        # different here.  Logged as bugzilla bug 319781.]]]
        #
        for key in self.listeners.keys():
            if event.type.startswith(key):
                self.listeners[key](event)
 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)
예제 #25
0
def _dbusCallbackError(funcName, error):
    """Log D-Bus errors

    Arguments:
    - funcName: The name of the gsmag function that made the D-Bus call.
    - error: The error that D-Bus returned.
    """
    logLine = funcName + " failed: " + str(error)
    debug.println(debug.LEVEL_WARNING, logLine)
 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)
예제 #27
0
def increaseSpeechPitch(script=None, inputEvent=None):
    if _speechserver:
        _speechserver.increaseSpeechPitch()
    else:
        logLine = "SPEECH OUTPUT: 'higher'"
        debug.println(debug.LEVEL_INFO, logLine)
        log.info(logLine)

    return True
예제 #28
0
def increaseSpeechRate(script=None, inputEvent=None):
    if _speechserver:
        _speechserver.increaseSpeechRate()
    else:
        debug.println(debug.LEVEL_INFO,
                      "SPEECH OUTPUT: 'faster'")
        log.info("increaseSpeechRate")

    return True
예제 #29
0
def decreaseSpeechRate(script=None, inputEvent=None):
    if _speechserver:
        _speechserver.decreaseSpeechRate()
    else:
        logLine = "SPEECH OUTPUT: 'slower'"
        debug.println(debug.LEVEL_INFO, logLine)
        log.info(logLine)

    return True
예제 #30
0
def decreaseSpeechPitch(script=None, inputEvent=None):
    if _speechserver:
        _speechserver.decreaseSpeechPitch()
    else:
        debug.println(debug.LEVEL_INFO,
                      "SPEECH OUTPUT: 'lower'")
        log.info("decreaseSpeechPitch")

    return True
예제 #31
0
 def on_connect(self):
     self.send({
         'pseudo':
         self._controlers['adventure'].get_pseudo(),
         'pos':
         self._controlers['perso'].get_pos(),
         'key':
         self._connection_key,
         'avatar':
         os.path.basename(self._controlers['perso'].get_skin_path())
     })
     debug.println("[NETWORK] Connexion")
예제 #32
0
def setLocusOfFocus(event, obj, notifyPresentationManager=True):
    """Sets the locus of focus (i.e., the object with visual focus) and
    notifies the current presentation manager of the change.

    Arguments:
    - event: if not None, the Event that caused this to happen
    - obj: the Accessible with the new locus of focus.
    - notifyPresentationManager: if True, propagate this event
    """

    if obj == orca_state.locusOfFocus:
        return

    oldLocusOfFocus = orca_state.locusOfFocus
    if oldLocusOfFocus and not oldLocusOfFocus.valid:
        oldLocusOfFocus = None

    orca_state.locusOfFocus = obj
    if orca_state.locusOfFocus and not orca_state.locusOfFocus.valid:
        orca_state.locusOfFocus = None

    if orca_state.locusOfFocus:
        appname = ""
        if not orca_state.locusOfFocus.app:
            appname = "None"
        else:
            appname = "'" + orca_state.locusOfFocus.app.name + "'"

        debug.println(debug.LEVEL_FINE,
                      "LOCUS OF FOCUS: app=%s name='%s' role='%s'" \
                      % (appname,
                         orca_state.locusOfFocus.name,
                         orca_state.locusOfFocus.role))

        if event:
            debug.println(debug.LEVEL_FINE,
                          "                event='%s'" % event.type)
        else:
            debug.println(debug.LEVEL_FINE, "                event=None")
    else:
        if event:
            debug.println(debug.LEVEL_FINE,
                          "LOCUS OF FOCUS: None event='%s'" % event.type)
        else:
            debug.println(debug.LEVEL_FINE, "LOCUS OF FOCUS: None event=None")

    if notifyPresentationManager and _currentPresentationManager >= 0:
        _PRESENTATION_MANAGERS[_currentPresentationManager].\
            locusOfFocusChanged(event,
                                oldLocusOfFocus,
                                orca_state.locusOfFocus)
예제 #33
0
 def _send_command(self, command, *args, **kwargs):
     if hasattr(speechd, 'SSIPCommunicationError'):
         try:
             return command(*args, **kwargs)
         except speechd.SSIPCommunicationError:
             debug.println(
                 debug.LEVEL_CONFIGURATION,
                 "Speech Dispatcher connection lost. "
                 "Trying to reconnect.")
             self.reset()
             return command(*args, **kwargs)
     else:
         # It is not possible tho catch the error with older SD versions.
         return command(*args, **kwargs)
예제 #34
0
    def __init__(self, app):
        """Creates a script for the given application, if necessary.
        This method should not be called by anyone except the
        focus_tracking_presenter.

        Arguments:
        - app: the Python Accessible application to create a script for
        """
        self.app = app

        if app:
            self.name = self.app.name
        else:
            self.name = "default"

        self.name += " (module=" + self.__module__ + ")"

        self.listeners = self.getListeners()

        # By default, handle events for non-active applications.
        #
        self.presentIfInactive = True

        self.inputEventHandlers = {}
        self.pointOfReference = {}
        self.setupInputEventHandlers()
        self.keyBindings = self.getKeyBindings()
        self.brailleBindings = self.getBrailleBindings()
        self.app_pronunciation_dict = self.getPronunciations()

        self.brailleGenerator = self.getBrailleGenerator()
        self.speechGenerator = self.getSpeechGenerator()
        self.whereAmI = self.getWhereAmI()
        self.bookmarks = self.getBookmarks()
        self.voices = settings.voices

        self.flatReviewContextClass = flat_review.Context

        self.findCommandRun = False

        # Assists with dealing with CORBA COMM_FAILURES.  A failure doesn't
        # always mean an object disappeared - there just might be a network
        # glitch.  So, on COMM_FAILURES, we might retry a few times before
        # giving up on an object.  This might need to be overridden by the
        # script.  See bug #397787.
        #
        self.commFailureWaitTime = settings.commFailureWaitTime
        self.commFailureAttemptLimit = settings.commFailureAttemptLimit

        debug.println(debug.LEVEL_FINE, "NEW SCRIPT: %s" % self.name)
예제 #35
0
 def do_POST(self):
     contentLength = self.headers.getheader('content-length')
     if contentLength:
         contentLength = int(contentLength)
         inputBody = self.rfile.read(contentLength)
         debug.println(debug.LEVEL_FINEST,
                       "httpserver._HTTPRequestHandler received %s" \
                       % inputBody)
         if inputBody.startswith("speak:"):
             speech.speak(inputBody[6:])
             self.send_response(200, 'OK')
         elif inputBody == "stop":
             speech.stop()
             self.send_response(200, 'OK')
         elif inputBody == "isSpeaking":
             self.send_response(200, 'OK')
             self.send_header("Content-type", "text/html")
             self.end_headers()
             self.wfile.write("%s" % speech.isSpeaking())
         elif inputBody.startswith("log:"):
             import logging
             logFile = inputBody[4:]
             for logger in ['braille', 'speech']:
                 log = logging.getLogger(logger)
                 formatter = logging.Formatter('%(name)s.%(message)s')
                 try:
                     loggingFileHandlers[logger].close()
                     log.removeHandler(loggingFileHandlers[logger])
                 except:
                     pass
                 if logFile and len(logFile):
                     loggingFileHandlers[logger] = logging.FileHandler(
                         '%s.%s' % (logFile, logger), 'w')
                     loggingFileHandlers[logger].setFormatter(formatter)
                     log.addHandler(loggingFileHandlers[logger])
                 log.setLevel(logging.INFO)
             self.send_response(200, 'OK')
         elif inputBody.startswith("debug:"):
             split = inputBody.split(':')
             debug.debugLevel = int(split[1])
             if debug.debugFile:
                 debug.debugFile.close()
                 debug.debugFile = None
             if (len(split) == 3) and (len(split[2])):
                 debug.debugFile = open('%s.debug' % split[2], 'w', 0)
             self.send_response(200, 'OK')
     else:
         debug.println(debug.LEVEL_FINEST,
                       "httpserver._HTTPRequestHandler received no data")
예제 #36
0
def panToOffset(offset):
    """Automatically pan left or right to make sure the current offset is
    showing."""

    while offset < _viewport[0]:
        debug.println(debug.LEVEL_FINEST,
                      "braille.panToOffset (left) %d" % offset)
        if not panLeft():
            break

    while offset >= (_viewport[0] + _displaySize[0]):
        debug.println(debug.LEVEL_FINEST,
                      "braille.panToOffset (right) %d" % offset)
        if not panRight():
            break
예제 #37
0
def __setROI(rect):
    """Sets the region of interest.

    Arguments:
    - rect: A GNOME.Magnifier.RectBounds object.
    """

    global _roi

    debug.println(debug.LEVEL_ALL, "mag.py:__setROI: (%d, %d), (%d, %d)" \
                  % (rect.x1, rect.y1, rect.x2, rect.y2))

    _roi = rect

    _zoomer.setROI(_roi)
    _zoomer.markDirty(_roi)  # [[[TODO: WDW - for some reason, this seems
예제 #38
0
def _isLockingKey(event_string):
    """Return an indication of whether this is a locking key.

    Arguments:
    - event: the event string

    Returns True if this is a locking key.
    """

    lockingKeys = ["Caps_Lock", "Num_Lock", "Scroll_Lock"]

    reply = event_string in lockingKeys \
            and not event_string in settings.orcaModifierKeys
    debug.println(debug.LEVEL_FINEST,
                  "orca._echoLockingKey: returning: %s" % reply)
    return reply
예제 #39
0
def _isActionKey(event_string):
    """Return an indication of whether this is an action key.

    Arguments:
    - event: the event string

    Returns True if this is an action key.
    """

    actionKeys = [
        "Return", "Escape", "Tab", "BackSpace", "Delete", "Page_Up",
        "Page_Down", "Home", "End"
    ]

    reply = event_string in actionKeys
    debug.println(debug.LEVEL_FINEST,
                  "orca._echoActionKey: returning: %s" % reply)
    return reply
예제 #40
0
    def sayAll(self, utteranceIterator, progressCallback):
        """Iterates through the given utteranceIterator, speaking
        each utterance one at a time.  Subclasses may postpone
        getting a new element until the current element has been
        spoken.

        Arguments:
        - utteranceIterator: iterator/generator whose next() function
                             returns a [SayAllContext, acss] tuple
        - progressCallback:  called as speech progress is made - has a
                             signature of (SayAllContext, type), where
                             type is one of PROGRESS, INTERRUPTED, or
                             COMPLETED.
        """
        for [context, acss] in utteranceIterator:
            debug.println(debug.LEVEL_INFO,
                          "SPEECH OUTPUT: '" + context.utterance + "'")
            log.info("sayAll utterance='%s'" % context.utterance)
            self.speak(context.utterance, acss)
예제 #41
0
def shutdownOnSignal(signum, frame):
    global exitCount

    debug.println(debug.LEVEL_ALL,
                  "Shutting down and exiting due to signal = %d" \
                  % signum)

    debug.println(debug.LEVEL_ALL, "Current stack is:")
    debug.printStack(debug.LEVEL_ALL)

    # Well...we'll try to exit nicely, but if we keep getting called,
    # something bad is happening, so just quit.
    #
    if exitCount:
        abort(signum)
    else:
        exitCount += 1

    # Try to do a graceful shutdown if we can.
    #
    if settings.timeoutCallback and (settings.timeoutTime > 0):
        signal.signal(signal.SIGALRM, settings.timeoutCallback)
        signal.alarm(settings.timeoutTime)

    try:
        if _initialized:
            shutdown()
        else:
            # We always want to try to shutdown speech since the
            # speech servers are very persistent about living.
            #
            speech.shutdown()
            shutdown()
        cleanExit = True
    except:
        cleanExit = False

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

    if not cleanExit:
        abort(signum)
예제 #42
0
    def _cleanupCache(self):
        """Looks for defunct accessible objects in the cache and removes them.
        """

        objectsRemoved = 0
        for obj in atspi.Accessible._cache.values():
            try:
                if obj.state.count(atspi.Accessibility.STATE_DEFUNCT):
                    atspi.Accessible.deleteAccessible(obj)
                    objectsRemoved += 1
                else:
                    # Try to force a COMM_FAILURE
                    #
                    obj.toString()
            except CORBA.COMM_FAILURE:
                atspi.Accessible.deleteAccessible(obj)
                objectsRemoved += 1

        debug.println(debug.LEVEL_FINEST,
                      "_cleanupCache: %d objects removed." % objectsRemoved)
예제 #43
0
    def sayAll(self, utteranceIterator, progressCallback):
        """Iterates through the given utteranceIterator, speaking
        each utterance one at a time.

        Arguments:
        - utteranceIterator: iterator/generator whose next() function
                             returns a new string to be spoken
        - progressCallback:  called as progress is made
        """
        try:
            [context, acss] = utteranceIterator.next()
            debug.println(debug.LEVEL_INFO,
                          "SPEECH OUTPUT: '" + context.utterance + "'")
            log.info("sayAll utterance='%s'" % context.utterance)
            self.__sayAll = _SayAll(utteranceIterator,
                                    context,
                                    self.__speak(context.utterance, acss),
                                    progressCallback)
        except StopIteration:
            pass
예제 #44
0
def _isPrintableKey(event_string):
    """Return an indication of whether this is an alphanumeric or
       punctuation key.

    Arguments:
    - event: the event string

    Returns True if this is an alphanumeric or punctuation key.
    """

    if event_string == "space":
        reply = True
    else:
        unicodeString = event_string.decode("UTF-8")
        reply = (len(unicodeString) == 1) \
                and (unicodeString.isalnum() or unicodeString.isspace()
                or unicodedata.category(unicodeString)[0] in ('P', 'S'))
    debug.println(debug.LEVEL_FINEST,
                  "orca._echoPrintableKey: returning: %s" % reply)
    return reply
예제 #45
0
def _isModifierKey(event_string):
    """Return an indication of whether this is a modifier key.

    Arguments:
    - event: the event string

    Returns True if this is a modifier key
    """

    # [[[TODO:richb - the Fn key on my laptop doesn't seem to generate an
    #    event.]]]

    modifierKeys = [ 'Alt_L', 'Alt_R', 'Control_L', 'Control_R', \
                     'Shift_L', 'Shift_R', 'Meta_L', 'Meta_R' ]
    modifierKeys.extend(settings.orcaModifierKeys)

    reply = event_string in modifierKeys
    debug.println(debug.LEVEL_FINEST,
                  "orca._echoModifierKey: returning: %s" % reply)
    return reply
예제 #46
0
def generateMouseEvent(x, y, eventName):
    """Synthesize a mouse event at a specific screen coordinate.
    Most AT clients should use the #AccessibleAction interface when
    tempted to generate mouse events, rather than this method.

    Event names: b1p = button 1 press; b2r = button 2 release;
                 b3c = button 3 click; b2d = button 2 double-click;
                 abs = absolute motion; rel = relative motion.

    Arguments:
    - x: the x screen coordinate
    - y: the y screen coordinate
    - eventName: the event name string (as described above)
    """

    debug.println(debug.LEVEL_FINER,
                  "SYNTHESIZING MOUSE EVENT: (%d, %d) %s"\
                  % (x, y, eventName))

    d = atspi.Registry().registry.getDeviceEventController()
    d.generateMouseEvent(x, y, eventName)
예제 #47
0
def _isFunctionKey(event_string):
    """Return an indication of whether this is a function key.

    Arguments:
    - event: the event string

    Returns True if this is a function key.
    """

    # [[[TODO:richb - what should be done about the function keys on the left
    #    side of my Sun keyboard and the other keys (like Scroll Lock), which
    #    generate "Fn" key events?]]]

    functionKeys = [
        "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11",
        "F12"
    ]

    reply = event_string in functionKeys
    debug.println(debug.LEVEL_FINEST,
                  "orca._echoFunctionKey: returning: %s" % reply)
    return reply
예제 #48
0
def getLongBrailleForRoleName(obj):
    """Returns the localized name of the given Accessible object; the name is
    a long string suitable for a Braille display.  If a localized name cannot
    be discovered, this will return the string as defined by the at-spi.

    Arguments:
    - obj: an Accessible object

    Returns a string containing the localized name of the object suitable for
    a Braille display.
    """

    name = obj.role
    if rolenames.has_key(name):
        return rolenames[name].brailleLong
    else:
        debug.println(debug.LEVEL_WARNING, "No rolename for %s" % name)
        localizedRoleName = obj.localizedRoleName
        if localizedRoleName and len(localizedRoleName):
            return localizedRoleName
        else:
            return name
예제 #49
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)
예제 #50
0
파일: game.py 프로젝트: SuperFola/UnamedPy
    def prepare(self):
        debug.println("[GAME] Démarrage")
        self.__start_at__ = time.time()

        # Variables ayant besoin d'être rechargées avant le lancement du jeu (en cas de lancement multiple du jeu)
        self.continuer = 1
        yield 1

        self.renderer_manager.clear_all()
        yield 1
        self.renderer_manager.ban_renderer(RENDER_COMBAT, RENDER_INVENTAIRE,
                                           RENDER_CREATURES, RENDER_POKEDEX,
                                           RENDER_CARTE, RENDER_MENU_IN_GAME,
                                           RENDER_BOUTIQUE, RENDER_SAVE,
                                           RENDER_PC)
        yield 1

        self.personnage.set_carte_mgr(self.carte_mgr)
        yield 1

        self.mini_map.load()
        yield 1

        self.pc_mgr.add_equipe(self.equipe_mgr)
        yield 1
        self.equipe_mgr.add_pc(self.pc_mgr)
        yield 1

        self.musics_player.load()
        yield 1

        for i in self.load():
            yield i

        ree.init_joystick()
        yield 1
        if ree.count_joysticks() > 0:
            joystick = ree.create_joystick()
            joystick.init()
            self.joystick = JoystickController(joystick)
            debug.println("[GAME] Un joystick a été trouvé")

        ree.set_key_repeat(200, 100)
        yield 1
        if self.joystick:
            self.joystick.set_repeat(40)

        self.musics_player.create_random_playlist()
        yield 1

        self.musics_player.select(self.musics_player.get_rdm_playlist().pop())
        yield 1

        if not os.path.exists(os.path.join("..", "saves")):
            os.mkdir(os.path.join("..", "saves"))

        debug.println("[GAME] Démarré en %3.4f sec" %
                      (time.time() - self.__start_at__))
예제 #51
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()
예제 #52
0
def getScriptModuleName(app):
    """Returns the module name of the script to use for a given
    application.  Any script mapping set via the setScriptMapping
    method is searched first, with the ultimate fallback being the
    name of the application itself.

    Arguments:
    - app: the application to find a script module name for
    """

    if not app.name:
        return None

    for mapping in _scriptMappings:
        regExpression = mapping[0]
        moduleName = mapping[1]
        if regExpression.match(app.name):
            debug.println(
                debug.LEVEL_FINEST,
                "Script mapping for %s is %s" % (app.name, moduleName))
            return moduleName

    return app.name
예제 #53
0
    def general_load(self):
        for i in glob(os.path.join("..", "assets", "tiles", "*")):
            # chargement automatique des tiles, leur nom déterminent si elles sont bloquantes ou non
            # chargement d'une tile simple
            if os.path.isfile(i):
                self.images[os.path.split(i)[1][:-4]] = ree.load_image(i)
                self.lassets.append(os.path.split(i)[1][:-4])
            # chargement d'une animation
            elif os.path.isdir(i):
                self.images[i.split(
                    os.sep)[-1]] = BaseMultipleSpritesAnimator(i)
                self.lassets.append(i.split(os.sep)[-1])

        self._load_animators()
        self._load_tiles_rects()

        with open(os.path.join("..", "assets", "configuration", "tiles.umd"),
                  "r") as file:
            self.specials_blocs = eval(file.read())

        self.loaded = True

        debug.println("[CARTE] Chargement global terminé")
예제 #54
0
 def load(self):
     if not path.exists(self.path):
         self.create()
         debug.println("[ULoader] Chargement terminé")
     else:
         debug.println("[ULoader] Note :", sep='', end=' ')
         with open(self.path, 'rb') as rlast_job_done:
             debug.println(pickle.Unpickler(rlast_job_done).load())
         self.create()
예제 #55
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)
예제 #56
0
 def clic(self, xp: int, yp: int):
     real_y = (yp - INVENT_Y_ITEM) // INVENT_ESP_ITEM
     if INVENT_X_ITEM <= xp <= INVENT_MAX_X_ITEM and 0 <= real_y < len(self.objets[self.cur_categorie]):
         self.selected_item = real_y
     else:
         if INVENT_BTN_JETER_Y <= yp <= INVENT_BTN_JETER_Y + INVENT_SIZE_BTN_Y and \
                 INVENT_BTN_JETER_X <= xp <= INVENT_BTN_JETER_X + INVENT_SIZE_BTN_X:
             # DEMANDER CONFIRMATION AVANT !
             debug.println("[INVENTAIRE] besoin de confirmation")
             self.jeter(self.selected_item)
         elif INVENT_BTN_JETERTT_Y <= yp <= INVENT_BTN_JETERTT_Y + INVENT_SIZE_BTN_Y and \
                 INVENT_BTN_JETERTT_X <= xp <= INVENT_BTN_JETERTT_X + INVENT_SIZE_BTN_X:
             # DEMANDER CONFIRMATION AVANT !
             debug.println("[INVENTAIRE] besoin de confirmation")
             self.jeter_tout(self.selected_item)
         elif INVENT_BTN_USE_Y <= yp <= INVENT_BTN_USE_Y + INVENT_SIZE_BTN_Y and \
                 INVENT_BTN_USE_X <= xp <= INVENT_BTN_USE_X + INVENT_SIZE_BTN_X:
             self.utiliser(self.selected_item)
         elif INVENT_BTN_PREVIOUS <= xp <= INVENT_BTN_PREVIOUS + INVENT_BTN_PAGES_SX and \
                 INVENT_BTN_PAGES <= yp <= INVENT_BTN_PAGES + INVENT_BTN_PAGES_SY:
             self.previous()
         elif INVENT_BTN_NEXT <= xp <= INVENT_BTN_NEXT + INVENT_BTN_PAGES_SX and \
                 INVENT_BTN_PAGES <= yp <= INVENT_BTN_PAGES + INVENT_BTN_PAGES_SY:
             self.next()
예제 #57
0
    def loadAppSettings(self, script):
        """Load the users application specific settings for an app.

        Arguments:
        - script: the current active script.
        """

        app = script.app
        settingsPackages = settings.settingsPackages
        moduleName = settings.getScriptModuleName(app)
        module = None

        if moduleName and len(moduleName):
            for package in settingsPackages:
                if len(package):
                    name = package + "." + moduleName
                else:
                    name = moduleName
                try:
                    debug.println(debug.LEVEL_FINEST,
                                  "Looking for settings at %s.py..." % name)
                    if not self._knownAppSettings.has_key(name):
                        self._knownAppSettings[name] = \
                            __import__(name, globals(), locals(), [''])
                    reload(self._knownAppSettings[name])
                    debug.println(debug.LEVEL_FINEST, "...found %s.py" % name)

                    # Setup the user's application specific key bindings.
                    # (if any).
                    #
                    if hasattr(self._knownAppSettings[name],
                               "overrideAppKeyBindings"):
                        script.overrideAppKeyBindings = \
                            self._knownAppSettings[name].overrideAppKeyBindings
                        script.keyBindings = \
                         self._knownAppSettings[name].overrideAppKeyBindings( \
                            script, script.keyBindings)

                    # Setup the user's application specific pronunciations
                    # (if any).
                    #
                    if hasattr(self._knownAppSettings[name],
                               "overridePronunciations"):
                        script.overridePronunciations = \
                            self._knownAppSettings[name].overridePronunciations
                        script.app_pronunciation_dict = \
                         self._knownAppSettings[name].overridePronunciations( \
                            script, script.app_pronunciation_dict)

                    break
                except ImportError:
                    debug.println(debug.LEVEL_FINEST,
                                  "...could not find %s.py" % name)
예제 #58
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)
예제 #59
0
 def _debug(self, msg):
     """ Convenience method for printing debug messages
     """
     debug.println(self.debugLevel, "J2SE-access-bridge.py: " + msg)
예제 #60
0
파일: gui.py 프로젝트: SuperFola/UnamedPy
 def set_color(self, color: str):
     try:
         self.image = ree.load_image(os.path.join("..", "assets", "gui", "bulle_{}.png".format(color)))
     except OSError:
         debug.println("[GUI] La couleur demandée n'est pas trouvable pour la gui bulle ('{}')".format(color))