예제 #1
0
def process_name_change(new_name):
    if new_name:
        settings.set_username(new_name)
        speech.speak('Pleased to meet you, ' + settings.username + '!', True)
        return True
    else:
        return False
예제 #2
0
    def processInputEvent(self, script, inputEvent):
        """Processes an input event.  If settings.learnModeEnabled is True,
        this will merely report the description of the input event to braille
        and speech.  If settings.learnModeEnabled is False, this will call the
        function bound to this InputEventHandler instance, passing the
        inputEvent as the sole argument to the function.

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

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

        consumed = False

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

        return consumed
예제 #3
0
def map_editor(map):
	quit = False
	player.x = map.get_attribute('start')[0]
	player.y = map.get_attribute('start')[1]
	yAxis = 0
	xAxis = 0
	oldTime = time.time()
	pygame.key.set_repeat(50)

	while not quit:
		time.sleep(.005) # Be kind to processors

		for e in pygame.event.get():
			if pygame.key.get_pressed()[pygame.K_UP]: yAxis = 1
			if pygame.key.get_pressed()[pygame.K_DOWN]: yAxis = -1
			if not pygame.key.get_pressed()[pygame.K_UP] and not pygame.key.get_pressed()[pygame.K_DOWN]: yAxis = 0
			if pygame.key.get_pressed()[pygame.K_RIGHT]: xAxis = 1
			if pygame.key.get_pressed()[pygame.K_LEFT]: xAxis = -1
			if not pygame.key.get_pressed()[pygame.K_RIGHT] and not pygame.key.get_pressed()[pygame.K_LEFT]: xAxis = 0

			if not xAxis == 0 or not yAxis == 0:
				if time.time() - oldTime >= player.get_attribute('walk_speed'):
					oldTime = time.time()
					if not player.collision(player.x + xAxis, player.y + yAxis, map):
						player.x += xAxis
						player.y += yAxis
						dir = 'sounds\\footsteps\\' + GameObject.TILE_TYPES[map.get_tile(player.x, player.y).get_attribute('type')]
						footstep = dir + '\\' + str(utilities.get_random(dir)) + '.wav'
						sound_pool.play_stationary(footstep)
					else:
						speech.speak('bump')

			if pygame.key.get_pressed()[pygame.K_z]: speech.speak(str(player.x) + ': ' + str(player.y))
			if pygame.key.get_pressed()[pygame.K_ESCAPE]: quit = True #mapbuilder_menu()
예제 #4
0
파일: fx.py 프로젝트: karimkohel/Kiwi
def takeNotes(intent):
    speech.speak(intent)
    note = speech.takeCommand()
    with open("notes.txt", 'a') as f:
        f.write(note)
        f.write("\n---------------------\n")
    speech.speak("Note added.")
예제 #5
0
def sayAndPrint(text,
                stop=False,
                getInput=False,
                speechServer=None,
                acss=None):
    """Prints the given text.  In addition, if the text field
    is not None, speaks the given text, optionally interrupting
    anything currently being spoken.

    Arguments:
    - text: the text to print and speak
    - stop: if True, interrupt any speech currently being spoken
    - getInput: if True, elicits raw input from the user and returns it
    - speechServer: the speech server to use
    - acss: the ACSS to use for speaking

    Returns raw input from the user if getInput is True.
    """

    if stop:
        speech.stop()
        if speechServer:
            speechServer.stop()

    if speechServer:
        speechServer.speak(text, acss)
    else:
        speech.speak(text, acss)

    if getInput:
        return raw_input(text)
    else:
        print text
예제 #6
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)
예제 #7
0
def process_schedule(verbose):
    '''Tells the user what events are planned for today from the calendar DB.'''
    event_list = calendardb.get_todays_events()
    if len(event_list) < 1:
        output_str = 'There are no events currently scheduled.'
    elif len(event_list) == 1:
        output_str = ' '.join([
            'You only have', event_list[0].event_str, 'at',
            event_list[0].start_time_str
        ]) + '.'
    elif len(event_list) == 2:
        output_str = ' '.join([
            'You have', event_list[0].event_str, 'at',
            event_list[0].start_time_str, 'and', event_list[1].event_str, 'at',
            event_list[1].start_time_str
        ]) + '.'
    else:
        # 3 or more events
        output_str = 'You have '
        for event in event_list[:-1]:
            output_str += ' '.join(
                [event.event_str, 'at', event.start_time_str]) + ', '
        output_str += ' '.join([
            'and', event_list[-1].event_str, 'at',
            event_list[-1].start_time_str
        ]) + '.'
    speech.speak(output_str, verbose)
예제 #8
0
def dialog(text):
 speak(text)
 while 1:
  for event in pygame.event.get():
   if event.type == pygame.KEYDOWN:
    if event.key == pl.K_RETURN: return
    elif event.key == pl.K_UP or event.key == pl.K_RIGHT or event.key == pl.K_DOWN or event.key == pl.K_LEFT: speak(text)
예제 #9
0
def makeJoke():
    res = requests.get('https://icanhazdadjoke.com/',
                       headers={"Accept": "application/json"})
    if res.status_code == requests.codes.ok:
        speak(str(res.json()['joke']))
    else:
        speak('oops!I ran out of jokes')
예제 #10
0
 def d(self, args):
     "Dispatches our internal queue to NVDA's speech framework."
     res = []
     res.extend(self._header)  # Add speech params
     res.extend(self._queue)  # Add queued speech
     speech.speak(res, priority=speech.priorities.SpeechPriority.NOW)
     self._queue.clear()
예제 #11
0
def process_voice(voice):
    if voice in ("female", "male"):
        settings.set_voice(voice)
        speech.speak('Okay, I will use a %s voice from now on.' % (voice),
                     True)
    else:
        speech.speak('I don\'t understand what voice you want')
예제 #12
0
    def script_navigate(self, gesture):
        r = False
        if gesture.mainKeyName in [
                "downArrow", "upArrow", "leftArrow", "rightArrow", "home"
        ]:
            r = self.mathcontent.navigate(gesture.mainKeyName)

        if not r:
            if _config.Access8MathConfig["settings"]["no_move_beep"]:
                tones.beep(100, 100)
            else:
                speech.speak([_("no move")])

        api.setReviewPosition(self.makeTextInfo(), False)
        if self.mathcontent.pointer.parent:
            if _config.Access8MathConfig["settings"][
                    "auto_generate"] and self.mathcontent.pointer.parent.role_level == A8M_PM.AUTO_GENERATE:
                speech.speak([self.mathcontent.pointer.des])
            elif _config.Access8MathConfig["settings"][
                    "dictionary_generate"] and self.mathcontent.pointer.parent.role_level == A8M_PM.DIC_GENERATE:
                speech.speak([self.mathcontent.pointer.des])
        else:
            speech.speak([self.mathcontent.pointer.des])
        speech.speak(
            translate_SpeechCommand(self.mathcontent.pointer.serialized()))
예제 #13
0
def process_name_change(new_name):
    if new_name:
        settings.set_username(new_name)
        speech.speak('Pleased to meet you, ' + settings.username + '!', True)
        return True
    else:
        return False
예제 #14
0
파일: game.py 프로젝트: ragb/sudoaudio
 def possibilities(self, event):
     l = self._board.possibilities(self._x, self._y)
     if l:
         message = " ".join(map(str, l))
         speech.speak(message)
     else:
         speech.speak(_("Nothing"))
예제 #15
0
	def speak(self, reason, mode):
		seq = self.getSpeakMessage(mode)
		if isinstance(seq, str):
			seq = [seq]
		if mode == 'Message':
			seq = [self.header.level, ', ', *seq]
		speech.speak(seq)
예제 #16
0
def sayAndPrint(text,
                stop=False,
                getInput=False,
                speechServer=None,
                voice=None):
    """Prints the given text.  In addition, if the text field
    is not None, speaks the given text, optionally interrupting
    anything currently being spoken.

    Arguments:
    - text: the text to print and speak
    - stop: if True, interrupt any speech currently being spoken
    - getInput: if True, elicits raw input from the user and returns it
    - speechServer: the speech server to use
    - voice: the ACSS to use for speaking

    Returns raw input from the user if getInput is True.
    """

    if stop:
        speech.stop()
        if speechServer:
            speechServer.stop()

    if speechServer:
        speechServer.speak(text, voice)
    else:
        speech.speak(text, voice)

    if getInput:
        return raw_input(text)
    else:
        print text
예제 #17
0
파일: files.py 프로젝트: mikemelch/hallie
def removeFile(file):
	"""remove a file"""
	if "y" in speech.question("Are you sure you want to remove " + file + "? (Y/N): "):
		speech.speak("Removing " + file + " with the 'rm' command.")
		subprocess.call(["rm", "-r", file])
	else:
		speech.speak("Okay, I won't remove " + file + ".")
예제 #18
0
파일: wirus.py 프로젝트: nibty/robot-wirus
    def autonomous(self):
        speech.speak("I am Humphrey!")

        while self.autonomous_thread_running:
            if self.autonomous_thread_pause:
                time.sleep(.1)
                self.time_of_last_stuck = time.time()
                continue

            self.start_forward()

            if config.SERVO_ON:
                servo = self.next_step()
                self.set_servo(servo)

            self.current_distance = self.get_top_distance()

            if self.object_detected(self.current_distance, servo):
                self.stop_forward()
                self.backward(config.BACKWARD_TIME)
                self.auto_turn(servo)

            elif self.is_robot_stuck():
                self.stop_forward()
                self.get_unstuck()

            speech.say_something()
예제 #19
0
def plugin_start3(plugin_dir):
    # Look for load any quests
    for f in glob.glob(r"%s\*.cfg" % plugin_dir):
        QUESTS.append(Quest.load(f, plugin_dir))
    log("ed_mission_creator started %s" % sys.path)
    speech.speak("ED mission creator started with %s quests" % len(QUESTS),
                 path=plugin_dir)
    return "v%s with %s quests from %s" % (VERSION, len(QUESTS), plugin_dir)
예제 #20
0
def speakSimilarPackages(similar, package_managers=[], package=None):
    if package_managers and package:
        speech.speak(
            "The package '" + package +
            "' is not installed with the following package managers:\n" +
            "\t\t" + "\n\t\t".join(package_managers) + "\n")
    speech.speak("But I found the following similar installed packages:\n" +
                 "\t\t" + "\n\t\t".join(similar) + "\n")
예제 #21
0
파일: install.py 프로젝트: mikemelch/hallie
def speakInstalledPackages(package, package_manager, installed, similar=[], speakSimilar=True):
    if installed:
        speech.speak("The package '" + package + "' is installed with the '" + package_manager + "' package manager.\n")
    elif speakSimilar:
        speech.speak("The package '" + package + "' is not installed with the '" + package_manager + "' package manager." +
                     ("" if similar else "\n"))
        if similar:
            speakSimilarPackages(similar)
예제 #22
0
def pullImg(sshIp=""):
    speech.speak("Enter docker image name")
    imgname = input("Enter docker image name (*req): ")

    speech.speak("enter docker image version by default it's latest")
    imgv = input("Enter docker image version (latest): ") or "latest"

    return subprocess.getoutput(f'{sshIp} sudo podman pull {imgname}:{imgv}')
예제 #23
0
	def script_navigate(self, gesture):
		modNames = gesture.modifierNames
		try:
			text = self.provider._mpNavigation.DoNavigateKeyPress(gesture.vkCode,
				"shift" in modNames, "control" in modNames, "alt" in modNames, False)
		except COMError:
			return
		speech.speak(_processMpSpeech(text, self.provider._language))
예제 #24
0
	def script_navigate(self, gesture):
		modNames = gesture.modifierNames
		try:
			text = self.provider._mpNavigation.DoNavigateKeyPress(gesture.vkCode,
				"shift" in modNames, "control" in modNames, "alt" in modNames, False)
		except COMError:
			return
		speech.speak(_processMpSpeech(text, self.provider._language))
예제 #25
0
파일: files.py 프로젝트: mikemelch/hallie
def removeFile(file):
    """remove a file"""
    if "y" in speech.question("Are you sure you want to remove " + file +
                              "? (Y/N): "):
        speech.speak("Removing " + file + " with the 'rm' command.")
        subprocess.call(["rm", "-r", file])
    else:
        speech.speak("Okay, I won't remove " + file + ".")
예제 #26
0
def process_send_email(recipient_info, verbose):
    '''Take appropriate action with the given email recipient information.'''
    if recipient_info and recipient_info.find("@") != -1:
        recipient = 'mailto:' + recipient_info  # Open default email client
    else:
        recipient = 'https://mail.google.com/mail/u/0/#compose' # Gmail
    speech.speak('Composing an email...', verbose)
    webbrowser.open(recipient)
예제 #27
0
파일: files.py 프로젝트: mikemelch/hallie
def copy(location):
	"""copy file or directory at a given location; can be pasted later"""
	copyData = settings.getDataFile()
	copyFileLocation = os.path.abspath(location)
	copy = {"copyLocation": copyFileLocation}
	dataFile = open(copyData, "wb")
	pickle.dump(copy, dataFile)
	speech.speak(location + " copied successfully!")
	speech.speak("Tip: use 'hallie paste' to paste this file.")
예제 #28
0
파일: fx.py 프로젝트: karimkohel/Kiwi
def changeVoice(intent):
    confirmed = speech.confirmCommand(intent)
    if confirmed:
        settings['voice_number'] = 0 if settings['voice_number'] == 1 else 1 # switch value of voice between 0,1
        with open('settings.json', 'w') as f:
            json.dump(settings, f)
        speech.speak("ok, done switching my voice but change will take effect after restart")
    else:
        speech.speak("you did not confirm, canceling task")
예제 #29
0
파일: files.py 프로젝트: mikemelch/hallie
def copy(location):
    """copy file or directory at a given location; can be pasted later"""
    copyData = settings.getDataFile()
    copyFileLocation = os.path.abspath(location)
    copy = {"copyLocation": copyFileLocation}
    dataFile = open(copyData, "wb")
    pickle.dump(copy, dataFile)
    speech.speak(location + " copied successfully!")
    speech.speak("Tip: use 'hallie paste' to paste this file.")
예제 #30
0
 def speakMatrix(self):
     matrix = [
         "Matrix %d" % self.matrixNumber, "Begin matrix",
         speech.BreakCommand(400)
     ]
     for i in range(1, self.matrix.rows + 1):
         matrix += self.speakRow(i)
         matrix.append(speech.BreakCommand(300))
     speech.speak(matrix + ["end matrix"])
예제 #31
0
파일: fx.py 프로젝트: karimkohel/Kiwi
def startWordProject(intent):
    speech.speak(intent)
    docName = speech.takeCommand()
    speech.speak("ok, creating document")
    doc = docx.Document()
    doc.add_paragraph(docName)
    fileName = os.path.expanduser("~/Desktop") + "\\" + docName + ".docx"
    doc.save(fileName)
    os.startfile(fileName)
예제 #32
0
def about(reg_ex):
    try:
        if reg_ex:
            topic = reg_ex.group(1)
            ny = wikipedia.page(topic)
            speak(ny.content[:500].encode('utf-8'))
    except Exception as e:
        print(e)
        speak(e)
예제 #33
0
def open(reg_ex):
    if reg_ex:
        domain = reg_ex.group(1)
        url = "https://www." + domain
        webbrowser.open(url)
        print('browser opened')
        speak("The website you have requested has been opened for you")
    else:
        pass
예제 #34
0
    def __present_item(self, text: str, isFilename: bool) -> int:
        # PRIVATE: plays or speaks the item

        if isFilename:
            return sound_pool.play_stationary(
                text)  # The index of the sound in the sound_pool
        else:
            speech.speak(text, False)
        return 0
예제 #35
0
 def l(self, args):
     "Speak a single character (or set of characters) immediately."
     res = []
     res.extend(self._header)
     if "character_scale" in self._state:
         res.append(speech.RateCommand(multiplier=self._state["character_scale"]))
     res.extend(list(speech.getSpellingSpeech("".join(args))))
     speech.cancelSpeech()  # Flush NVDA's speech queue
     speech.speak(res, priority=speech.priorities.SpeechPriority.NOW)
예제 #36
0
def messageWithLangDetection(msg):
	autoLanguageSwitching=config.conf['speech']['autoLanguageSwitching']
	if autoLanguageSwitching:
		speechSequence=[]
		speechSequence.append(LangChangeCommand(msg['lang']))
		speechSequence.append(msg['text'])
		speak(speechSequence)
		braille.handler.message(msg['text'])
	else:
		ui.message(msg['text'])
예제 #37
0
 def script_reportColumn(self, gesture):
     obj = api.getFocusObject()
     try:
         info = obj.makeTextInfo(textInfos.POSITION_CARET)
         pos = info.bookmark.startOffset
         info.expand(textInfos.UNIT_LINE)
         info.collapse()
         speech.speak(str(pos - info.bookmark.startOffset))
     except:
         pass
 def train(self):
     print("train module")
     if len(self.command) > 1:
         speak("wallah! too many files")
         print(self.command)
         Initialize(self.command, self)
     else:
         command = "start" + " " + self.command[0]
         return update_new_command(self.trigger, self.d_type, self.exe,
                                   self.name, command)
예제 #39
0
def cmd(command, name):
    proc = subprocess.Popen(command,
                            shell=True,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE)
    out, err = proc.communicate()
    if str(err).lower() == "none":
        speak(name + " started")
        return True
    else:
        return False
예제 #40
0
파일: game.py 프로젝트: ragb/sudoaudio
 def put(self, event):
     value = event.key - K_0
     ret = self._board.put(self._x, self._y, value)
     if ret:
         self._move_sound.play()
         self.speak_current()
         if self._board.is_solution():
             self._win_sound.play()
             speech.speak(_("Solution found"))
     else:
         speech.speak(_("Impossible move"))
예제 #41
0
def process_add_cal_event(event_str, verbose):
    '''Schedule a new calendar event with the user.'''
    if event_str == 'event':
        event_sentence = speech.ask_question('Okay, what is the event called?', verbose)
        day_sentence = speech.ask_question('What day will this be on?', verbose)
        time_sentence = speech.ask_question('What time will this start at?', verbose)
        cal_event = calendardb.CalendarEvent(event_sentence, day_sentence, time_sentence, '')
        calendardb.add_event(cal_event)
        feedback_sentence = 'Alright, I\'m putting down ' + str(cal_event) + '.'
        speech.speak(feedback_sentence, verbose)
    else:
        speech.speak('Sorry, I am unable to help you schedule this right now.', verbose)
예제 #42
0
파일: game.py 프로젝트: ragb/sudoaudio
 def help(self, event):
     help_string = _(
         """
     To move around the board use the arrow keys.
     To put a number on a square use numbers from 1 to 9.
     To clear a square use the 0 key. A square can only be cleared if it was blank on the original puzzle.
     To speak the current square position on the board use the p key.
     To know how many squares are still blank press b.
     To speak what possibilities exist for the current square press s.
     To quit the game press the q key.
     """
     )
     speech.speak(help_string)
예제 #43
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'))
예제 #44
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
예제 #45
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")
예제 #46
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()
예제 #47
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.generateSpeech(
             context.getCurrentAccessible()))
     speech.speak(utterances)
예제 #48
0
파일: files.py 프로젝트: mikemelch/hallie
def paste(location):
	"""paste a file or directory that has been previously copied"""
	copyData = settings.getDataFile()
	if not location:
		location = "."
	try:
		data = pickle.load(open(copyData, "rb"))
		speech.speak("Pasting " + data["copyLocation"] + " to current directory.")
	except:
		speech.fail("It doesn't look like you've copied anything yet.")
		speech.fail("Type 'hallie copy <file>' to copy a file or folder.")
		return
	process, error = subprocess.Popen(["cp", "-r", data["copyLocation"], location], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()
	if "denied" in process:
		speech.fail("Unable to paste your file successfully. This is most likely due to a permission issue. You can try to run me as sudo!")
예제 #49
0
    def whereAmI(self, obj, basicOnly):
        """Speaks information about the current object of interest, including
        the object itself, which window it is in, which application, which
        workspace, etc.

        The object of interest can vary depending upon the mode the user
        is using at the time. For example, in focus tracking mode, the
        object of interest is the object with keyboard focus. In review
        mode, the object of interest is the object currently being visited,
        whether it has keyboard focus or not.
        """
        if (not obj):
            return False
        else:
            speech.speak(self.getWhereAmI(obj, basicOnly))
            return True
예제 #50
0
def parse(verb, verb_object, alternate_noun, alternate_verb, adjective, verbose=False):
    '''Parse the command and take an action. Returns True if the command is
    understood, and False otherwise.'''
    # Print parameters for debugging purposes
    print('\tverb:           ' + verb)
    print('\tverb_object:    ' + verb_object)
    print('\talternate_verb: ' + alternate_verb)
    print('\talternate_noun: ' + alternate_noun)
    print('\tadjective:      ' + adjective)
    browse_cmd_list = ['start', 'open', 'go', 'go to', 'browse', 'browse to', 'launch', 'take to', 'show'] #Original verb only + addition verb 'show'
    email_cmd_list = ['email', 'compose', 'compose to', 'send', 'send to', "write", "write to"]
    roomfinder_cmd_list = ['find', 'where is']
    calendar_cmd_list = ['schedule', 'remind', 'remind about', 'plan']
    voice_cmd_list = ['use']

    if verb in browse_cmd_list:
        # Open an indicated web page in the default browser
        process_website(verb_object, verbose)
    elif verb in email_cmd_list:
        # Open a window to compose an email
        process_send_email(verb_object, verbose)
    elif verb in roomfinder_cmd_list:
        # Tell the user which building and floor a room is in
        process_find_room(verb_object, verbose)
    elif verb in calendar_cmd_list:
        # Schedule an event for the user
        process_add_cal_event(verb_object, verbose)
    elif verb in voice_cmd_list:
        # Change voice between male / female
        process_voice(adjective)
    # This could be a few things
    elif verb == "what is" or verb == "tell":
        if verb_object.find("weather") != -1:
            process_weather(verbose)
        elif verb_object == "schedule":
            process_schedule(verbose)
        elif verb_object == "time":
            speech.speak('It is currently ' + calendardb.get_current_time() + '.', True)
        elif verb_object == "date" or verb_object == "day":
            speech.speak('Today is ' + calendardb.get_current_date() + '.', True)
        else:
            return False
    elif verb == "is":
        if verb_object == "time":
            speech.speak('It is currently ' + calendardb.get_current_time() + '.', True)
        elif verb_object == "date" or verb_object == "day":
            speech.speak('Today is ' + calendardb.get_current_date() + '.', True)
        elif verb_object == "name":
            return process_name_change(alternate_noun)
    elif verb == "call":
        return process_name_change(alternate_noun or verb_object)
    else:
        return False
    return True
예제 #51
0
    def presentTypingStatusChange(self, event, status):
        """Presents a change in typing status for the current conversation
        if the status has indeed changed and if the user wants to hear it.

        Arguments:
        - event: the accessible Event
        - status: a string containing the status change

        Returns True if we spoke the change; False otherwise
        """

        if _settingsManager.getSetting("chatAnnounceBuddyTyping"):
            conversation = self.getConversation(event.source)
            if conversation and (status != conversation.getTypingStatus()):
                speech.speak(status)
                conversation.setTypingStatus(status)
                return True

        return False
예제 #52
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
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()
예제 #54
0
def Integrate(optional_message = None):
    import CoreNLP
    if optional_message:
        sentence = optional_message
        print "Text input provided: '" + optional_message + "'"
    else:
        greeting_str = 'Hi ' + settings.username.capitalize()
        greeting_str += '! What can I help you with?'
        speech.speak(greeting_str, True)
        (success, sentence) = speech.listen()
        if not success:
            speech.speak(sentence, True)
            exit()
    # CoreNLP is weird, need to replace some stuff to make it properly recognize short sentences
    sentence = sentence.replace("Start", "start").replace("open", "Open").replace("Please", "").replace("please", "")

    # Call NLP parsing function
    (verb, verb_object, noun2, verb2, preposition, adjective) = CoreNLP.Parse(sentence)

    # Fix some more edge cases with broken sentences
    if not verb:
        verb, verb_object = CoreNLPFail(sentence)

    # TODO: Eventually we should probably not attach the preposition to the verb (does it actually improve accuracy?)
    if preposition:
        verb = "%s %s" % (verb, preposition)
        verb_object = noun2

    if not assistantdb.parse(verb.lower(), verb_object.lower(), noun2.lower(), verb2.lower(), adjective.lower()):
        speech.speak('Sorry, I don\'t understand what you want.', True)
예제 #55
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'))
예제 #56
0
def process_schedule(verbose):
    '''Tells the user what events are planned for today from the calendar DB.'''
    event_list = calendardb.get_todays_events()
    if len(event_list) < 1:
        output_str = 'There are no events currently scheduled.'
    elif len(event_list) == 1:
        output_str = ' '.join(['You only have', event_list[0].event_str, 'at',
                               event_list[0].start_time_str]) + '.'
    elif len(event_list) == 2:
        output_str = ' '.join(['You have', event_list[0].event_str, 'at',
                               event_list[0].start_time_str, 'and',
                               event_list[1].event_str, 'at',
                               event_list[1].start_time_str]) + '.'
    else:
        # 3 or more events
        output_str = 'You have '
        for event in event_list[:-1]:
            output_str += ' '.join([event.event_str, 'at',
                                    event.start_time_str]) + ', '
        output_str += ' '.join(['and', event_list[-1].event_str, 'at',
                                event_list[-1].start_time_str]) + '.'
    speech.speak(output_str, verbose)
예제 #57
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
예제 #58
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