def fillAndFindWordFile(self, text):
        """get the file/buffer self.emacsPythonFile in the front
        
        """
        open(self.wordFile, 'w').write(text)
	natqh.waitForWindowTitle ('Microsoft Word')
	print "found Microsoft Word"
        while 1:
            action('<<fileopen>>')
            if natqh.waitForWindowTitle ('Open') == 1:
                print "got window title open"
                progInfo = natqh.getProgInfo()
                if progInfo[2] == 'child':
                    break
                else:
                    print "not a child"

	print "open file"
        natqh.Wait()
        keystroke(self.wordFile)
        natqh.Wait()
        keystroke('{enter}')
        natqh.Wait()
	if natqh.waitForWindowTitle ('File conversion'):
            keystroke('{alt+w}')
            natqh.Wait()
	    keystroke ('{enter}')
	keystroke('{ctrl+alt+n}') #Switch Word to draft mode
 def gotResults_copy(self,words,fullResults):
     global sourceHandle, nsHandle
     modInfo = natlink.getCurrentModule()
     if natut.matchWindow(modInfo, self.startProgram, self.startProgram):
         self.DisplayMessage('Do not use "'+self.fullText+'" in '+self.startProgram)
         return 
     # get Handle of this window:
     sourceHandle = modInfo[2]
     
     ##  If "edit all" is said, first select whole document
     if (self.hasCommon(words, ['all'])):
         action('<<selectall>>')
         natqh.Wait(0.2)
     if (self.hasCommon(words, ['messages'])):
         natqh.switchToWindowWithTitle('messages from python macros')
         action('<<selectall>>')
         natqh.Wait(0.2)
     # copy and goto NatSpeak
     #  clear clipboard, copy and goto DragonPad
     natqh.saveClipboard()
     if (self.hasCommon(words, ['copy'])):
         action('<<copy>>')
     elif (self.hasCommon(words, ['cut'])):
         action('<<cut>>')
     else:
         print 'no copy or cut in words: %s'% words
         return
     natqh.rememberWindow()
     if self.startEditProgram():
         if natqh.getClipboard():
                 keystroke('{Ctrl+ExtEnd}{Enter}{Ctrl+v}')
         natqh.returnToWindow(20,0.2, winHandle=sourceHandle)
     natqh.restoreClipboard()
示例#3
0
    def gotResults(self, words, fullResults):

        # step 5, in got results collect the number:
        # only necessary in this grammar for collecting the choose command
        if not self.hadPick:
            return
        self.collectNumber()
        if not self.number:
            print 'collected no number'
            return
        self.getInputcontrol()
        command = self.number
        commandparts = []
        if self.navOption:
            if not self.navOption.startswith(":"):
                command += ":"
            command += self.navOption
        if command.find(';') >= 0:
            print 'command: %s' % command
            commandparts = command.split(';')
            command = commandparts.pop(0)
            print 'command: %s, commandparts: %s' % (command, commandparts)
        self.doOption(command)
        for additional in commandparts:
            natqh.Wait(visiblePause)
            keystroke(additional)
示例#4
0
    def goto_task_winkey(self, number):
        """switch to task with number, via the windows key"""
        ##    print 'action: goto task: %s'% number
        prog, title, topchild, windowHandle = natqh.getProgInfo()
        if prog == 'explorer' and not title:
            keystroke('{esc}')
            natqh.shortWait()
        try:
            count = int(number)
        except ValueError:
            print 'goto_task_winkey, invalid number: %s' % number
            return
        if not count:
            print 'goto_task_winkey, invalid number: %s' % number
            return
        elif count == 10:
            count = 0
        elif count > 10:
            print 'goto_task_winkey, pass on to "TASK %s", number > 9' % count
            return action('TASK %s' % count)

        self.doWinKey('b')
        actions.do_VW()
        self.doWinKey(str(number))
        print 'self.winkeyDown: %s' % self.winkeyDown
 def testKeystroke(self):
     """test in foreground window do some keystrokes with marks functions
     
     """
     log("test keystroke in the foreground window")
     keystroke("{shift+exthome}")
     keystroke("{ctrl+x}")
示例#6
0
 def gotResults_date(self,words,fullResults):
     day = self.getNumberFromSpoken(words[1])
     if len(words) > 2:
         month = self.getFromInifile(words[2], 'month')
     else:
         month = 12
     keystroke('%s-%s{tab}'% (day, month))
示例#7
0
    def gotResults_cancelnumbers(self,words,fullResults):
        """also stops loading the page when not finished"""
##        print 'cancel numbers, doing: %s'% Escape
        if mode == 'hah':
            keystroke(Escape[mode])
        else:
            keystroke(getNumbers[mode])
示例#8
0
 def goto_task_winkey(self, number):
     """switch to task with number, via the windows key"""
 ##    print 'action: goto task: %s'% number
     prog, title, topchild, windowHandle = natqh.getProgInfo()
     if prog == 'explorer' and not title:
         keystroke('{esc}')
         natqh.shortWait()
     try:
         count = int(number)
     except ValueError:
         print 'goto_task_winkey, invalid number: %s'% number
         return
     if not count:
         print 'goto_task_winkey, invalid number: %s'% number
         return
     elif count == 10:
         count=0
     elif count > 10:
         print 'goto_task_winkey, pass on to "TASK %s", number > 9'% count
         return action('TASK %s'% count)
     
     self.doWinKey('b')
     actions.do_VW()
     self.doWinKey(str(number))
     print 'self.winkeyDown: %s'% self.winkeyDown
示例#9
0
    def gotResults_iconswitch(self, words, fullResults):
        """go to specified icon in system tray (by number, or relative number)

        followed by an iconaction, like close or shortcut menu
        """
##        print 'icon switch, words: %s'% words
        direction = self.directionicon
        character = self.hasCommon(words, ICAlphabet)
        actions = self.ini.get('iconaction')
        act = self.hasCommon(words, actions)
        counts = self.getNumbersFromSpoken(words, self.iconCounts)
        if counts:
            count = int(counts[0])
        else:
            count = 0
        hasMousePos = 0
        if direction:
            count = count or 1
            print '_general, iconswitch: relative count: %s'% count
            keystroke("{%s %s}"% (direction, count))

        else:
            if count:
                gotit = self.getIconNumber(count)
            elif character:
                print 'get icon with letter: %s'% character[0]
                gotit = self.getIconLetter(character[0])
            else:
                print '_general, iconswitch: no count or letter, should not come here'
                return
        # wait a little
        if act:
            action('W')
            self.doIconAction(act)
    def gotResults_dgndictation(self, words, fullResults):
        #self.text = ' '.join(map(natqh.stripSpokenForm, words))
        # try with the improved nsformat function
        if self.gotPassword:
            print 'gotPassword, analyse password: %s' % words
            text = nsformat.formatPassword(words)
            keystroke(text)
            self.gotPassword = 0
            print 'reset gotPassword, ', self.gotPassword
        if self.gotVariable:
            print 'do variable trick %s on %s' % (self.gotVariable, words)
            vartrick = self.gotVariable
            funcName = 'format_%s' % vartrick
            # print 'funcName: %s'% funcName
            try:
                func = getattr(self, funcName)
                # print 'func: %s'% func
            except AttributeError:
                print 'no formatfunction for variable trick: %s' % vartrick
                return

            result = func(words)
            #
            keystroke(" " + result)
            return
        #very well for like this
        if self.search and self.text in ['on', 'verder']:  #
            self.search = 2
        elif self.search and self.text in ['new', 'nieuw']:
            self.search = 3
        elif self.search and self.text in ['terug', 'back']:
            self.search = 4
        print 'dgndictation: %s' % self.text
示例#11
0
    def gotResults_iconswitch(self, words, fullResults):
        """go to specified icon in system tray (by number, or relative number)

        followed by an iconaction, like close or shortcut menu
        """
        ##        print 'icon switch, words: %s'% words
        direction = self.directionicon
        character = self.hasCommon(words, ICAlphabet)
        actions = self.ini.get('iconaction')
        act = self.hasCommon(words, actions)
        counts = self.getNumbersFromSpoken(words, self.iconCounts)
        if counts:
            count = int(counts[0])
        else:
            count = 0
        hasMousePos = 0
        if direction:
            count = count or 1
            print '_general, iconswitch: relative count: %s' % count
            keystroke("{%s %s}" % (direction, count))

        else:
            if count:
                gotit = self.getIconNumber(count)
            elif character:
                print 'get icon with letter: %s' % character[0]
                gotit = self.getIconLetter(character[0])
            else:
                print '_general, iconswitch: no count or letter, should not come here'
                return
        # wait a little
        if act:
            action('W')
            self.doIconAction(act)
示例#12
0
    def gotResults_navigatepages(self, words, fullResults):
        """go to next or previous page(s) and refresh possibly"""
        ##        print 'navigate pages: %s'% words
        ## not active at the moment, possibly reactivate...
        dir = None
        command = self.getFromInifile(words, 'pagecommands', noWarning=1)

        if self.hasCommon(
                words, ['next', 'verder', 'volgende', 'vooruit', 'forward']):
            dir = 'right'
        elif self.hasCommon(words, ['previous', 'terug', 'vorige', 'back']):
            dir = 'left'
        else:
            print 'no direction found in command: %s' % words

        counts = self.getNumbersFromSpoken(words)
        if counts:
            count = counts[0]
        else:
            count = 1
##        print 'PAGES:     dir: %s, count: |%s|, command: |%s|'% (dir, counlinker balkt, command)

        if dir:
            while count > 0:
                count = count - 1
                keystroke('{alt+%s}' % (dir))
                natqh.Wait(
                    0.5)  #0.3 seem too short for going back pages in chrome

        if command:
            action(command)
示例#13
0
 def gotResults_cancelnumbers(self, words, fullResults):
     """also stops loading the page when not finished"""
     ##        print 'cancel numbers, doing: %s'% Escape
     if mode == 'hah':
         keystroke(Escape[mode])
     else:
         keystroke(getNumbers[mode])
示例#14
0
    def gotResults_getnumbers(self, words, fullResults):
        """works also if numbers already given, but cancels the loading of a page

        """
        ##        print 'getnumbers, doing: %s'% Escape + getNumbers
        if mode == 'hah':
            keystroke(Escape[mode])
        keystroke(getNumbers[mode])
示例#15
0
 def gotResults_replace(self, words, fullResults):
     place = self.getFromInifile(words, 'placeholders', noWarning=1)
     action('<<startsearch>>')
     keystroke(place)
     action('<<searchgo>>')
     action('<<cancel>>')
     if self.hasCommon(words, ['with']):
         self.replace_text = 1
示例#16
0
    def gotResults_getnumbers(self,words,fullResults):
        """works also if numbers already given, but cancels the loading of a page

        """
##        print 'getnumbers, doing: %s'% Escape + getNumbers
        if mode == 'hah':
            keystroke(Escape[mode])
        keystroke(getNumbers[mode])
 def exitDialog(self):
     """finish the open dialog, normally by pressing enter"""
     dTitle = self.foldersGram.dialogWindowTitle
     if dTitle and natqh.matchModule(
             'natspeak', wantedTitle=dTitle, titleExact=1, caseExact=1):
         natqh.rememberWindow()
         keystroke("{enter}")  # exit dialog.
     natqh.waitForNewWindow()
    def rule_notesaddition(self, words):
        "<notesnavigate>{notesaddition}"
        # if words end with Off, On or End, they are in front of the first word and separated from the last.
        self.justInsert = False
        if not self.notesIndexes:
            print 'notesaddition, no notes found in selection'
            return

        prepost = self.getFromInifile(words[-1], 'notesaddition')
        print 'prepost: "%s"' % prepost
        doEachNote = False
        # to be switched on with eg ()() (eachnoteslur)
        if not prepost:
            return
        if ":" in prepost:
            pre, post = prepost.split(":")
        else:
            lenpart = len(prepost) / 2
            pre, post = prepost[:lenpart], prepost[-lenpart:]
        if pre == post and len(pre) > 1:
            lenpart = len(pre) / 2
            pre, post = pre[:lenpart], post[-lenpart:]
            print 'pre: %s, post: %s, do continuous' % (pre, post)
            doEachNote = True
        startNote = self.wordsList[self.notesIndexes[0]]
        print 'notesIndexes: %s, notesWanted: %s' % (self.notesIndexes,
                                                     self.notesWanted)
        endNote = self.wordsList[self.notesIndexes[self.notesWanted - 1]]

        startNote.updateNote(pre)
        endNote.updateNote(post)
        if doEachNote and self.notesWanted > 2:
            for i in range(1, self.notesWanted - 1):
                print 'do extra for note %s' % i
                note = self.wordsList[self.notesIndexes[i]]
                note.updateNote(post)
                note.updateNote(pre)

        #for ending in ['On', 'Off']:  # strange bit here
        #    if post.endswith(ending):
        #        self.wordsList.insert(endNote, post)
        #        break
        #else:
        #    self.wordsList.insert(endNote+1, post)
        #
        #for ending in ['On', 'Off', 'End']:
        #    if pre.endswith(ending):
        #        self.wordsList.insert(startNote, pre)
        #        print 'pre "%s" ending: "%s", wordsList: %s'% (pre, ending, self.wordsList)
        #        break
        #else:
        #    print 'pre "%s" general, wordList: %s'% (pre, self.wordsList)
        #    self.wordsList.insert(startNote+1, pre)

        snippet = " ".join([str(x).strip() for x in self.wordsList])
        print 'new snippet: %s' % snippet
        keystroke(snippet)
        self.gotoNextNote()
示例#19
0
    def gotResults_hyphenatephrase(self,words,fullResults):
        # selection or last utterance is spelled out with all caps and hyphens
        # Quintijn, August 15, 2009

        # save clipboard, release after the action:                                 
        action("CLIPSAVE")
        # hasCommon function for possibility of translations/synonyms without altering the code:
        if self.hasCommon(words[-1], "phrase"):
            keystroke("{Ctrl+c}")
            # do contents of clipboard:
            t = string.strip(natlink.getClipboard())
            if not t:
                if self.language == 'nld':
                    com = "Selecteer dat"
                else:
                    com  = "Select That"
                if natqh.getDNSVersion() >= 7:
                    com = com.lower()
                action("HW %s"%com)
                natqh.Wait(0.5)
                keystroke("{Ctrl+c}")
                t = string.strip(natlink.getClipboard())
            if not t:                    
                self.DisplayMessage("select a text first")
                action("CLIPRESTORE")
                return
        elif self.hasCommon(words, ('word', 'words')):
            counts = self.getNumbersFromSpoken(words)
            if counts:
                count = counts[0]
            else:
                count = 1
            keystroke("{shift+ctrl+left %s}"% count)
            keystroke("{Ctrl+c}")
            t = string.strip(natlink.getClipboard())
            if not t:                    
                self.DisplayMessage("could not select a valid text")
                action("CLIPRESTORE")
                return
        else:
            self.DisplayMessage("unexpected last word in command phrase: %s"% words[-1])
            action("CLIPRESTORE")
            return
            

        # first paste back the selected text, and add a space if needed:
        L = []
        # for each word in utterance join uppercased characters of word with a '-'
        tWords = t.split()
        for word in tWords:
            L.append('-'.join([t.upper() for t in word]))
            L.append(' ')
        keystroke(''.join(L))
        action("CLIPRESTORE")
示例#20
0
    def gotResults_hyphenatephrase(self, words, fullResults):
        # selection or last utterance is spelled out with all caps and hyphens
        # Quintijn, August 15, 2009

        # save clipboard, release after the action:
        action("CLIPSAVE")
        # hasCommon function for possibility of translations/synonyms without altering the code:
        if self.hasCommon(words[-1], "phrase"):
            keystroke("{Ctrl+c}")
            # do contents of clipboard:
            t = string.strip(natlink.getClipboard())
            if not t:
                if self.language == 'nld':
                    com = "Selecteer dat"
                else:
                    com = "Select That"
                if natqh.getDNSVersion() >= 7:
                    com = com.lower()
                action("HW %s" % com)
                natqh.Wait(0.5)
                keystroke("{Ctrl+c}")
                t = string.strip(natlink.getClipboard())
            if not t:
                self.DisplayMessage("select a text first")
                action("CLIPRESTORE")
                return
        elif self.hasCommon(words, ('word', 'words')):
            counts = self.getNumbersFromSpoken(words)
            if counts:
                count = counts[0]
            else:
                count = 1
            keystroke("{shift+ctrl+left %s}" % count)
            keystroke("{Ctrl+c}")
            t = string.strip(natlink.getClipboard())
            if not t:
                self.DisplayMessage("could not select a valid text")
                action("CLIPRESTORE")
                return
        else:
            self.DisplayMessage("unexpected last word in command phrase: %s" %
                                words[-1])
            action("CLIPRESTORE")
            return

        # first paste back the selected text, and add a space if needed:
        L = []
        # for each word in utterance join uppercased characters of word with a '-'
        tWords = t.split()
        for word in tWords:
            L.append('-'.join([t.upper() for t in word]))
            L.append(' ')
        keystroke(''.join(L))
        action("CLIPRESTORE")
    def getPrevNotes(self, n=1):
        if self.justLeft is None:
            self.getPrevNext()
        if self.prevchars is None:
            self.prevchars = self.frescobaldi.getPrevLine()
        if self.inMiddleOfWord:
            print 'inMiddleOfWord %s' % self.inMiddleOfWord
            lastWord = self.prevchars.split()[-1]
            numcharsleft = len(lastWord)
            print 'go left %s characters' % numcharsleft
            keystroke("{left %s}" % numcharsleft)
            self.justLeft, self.justRight = self.prevchars[
                -numcharsleft - 1], self.prevchars[-numcharsleft]
            print 'after go left: justLeft: %s, justRight: %s' % self.justLeft, self.justRight
            self.getPrevNextVariables(self, self.justLeft, self.justRight)
            self.prevchars = self.prevchars[:-numcharsleft]
            print 'prevchars after go left to beginning of note: %s' % repr(
                self.prevchars)

        print 'prevchars: %s' % repr(self.prevchars)
        wordsList, notesIndexes = analyseString(self.prevchars)
        print 'wordsList: %s, notesIndexes: %s' % (wordsList, notesIndexes)
        notesFound = len(notesIndexes)

        if notesFound <= n:
            moreLines = 5
            print 'get %s more lines' % moreLines
            prevchars = self.frescobaldi.getPrevLine(moreLines)
            if prevchars == self.prevchars:
                raise Exception(
                    "getPrevNotes, not enough notes found: %s, wanted: %s" %
                    (notesFound, n))
            print '%s more lines prev:\n%s' % (moreLines, repr(prevchars))
            self.prevchars = prevchars

            wordsList, notesIndexes = analyseString(self.prevchars)
            notesFound = len(notesIndexes)
            print '----prevchars: %s' % repr(self.prevchars)
            if notesFound < n:
                print 'notesFound: %s' % notesFound
                print 'wordsList: %s, notesIndexes: %s' % (wordsList,
                                                           notesIndexes)
                raise Exception(
                    "too little notes caught in %s lines up: %s, wanted: %s" %
                    (moreLines, notesFound, n))
        else:
            self.hasAllInfoPrev = True  ## know enough

        wordsList, notesIndexes, afterNotes, beforeNotes, beforeNoteComplete = \
                              getNotesFromWordsList(n, wordsList, notesIndexes, reverse=True)
        beforeNoteComplete = beforeNoteComplete or self.hasAllInfoPrev
        return wordsList, notesIndexes, afterNotes, beforeNotes, beforeNoteComplete
 def gotResults_pastepart(self, words, fullResults):
     """paste part of clipboard, parts are separated by ";"
     """
     n = self.getNumberFromSpoken(words[-1])
     t = natqh.getClipboard()
     print '(%s) %s' % (type(t), t)
     T = self.partsSplitSpecial(t)
     if n <= len(T):
         keystroke(T[n - 1])
         # action("SCLIP %s"% T[n-1])
     else:
         print '_general, pastepart: length of list only: %s (t: %s)' % (
             len(T), t)
示例#23
0
    def getIconLetter(self, char):
        """get the icon with the specified count in focus

        """        
##        mod1 = natlink.getCurrentModule()
##        mod2 = mod1
##        nTry = 0
##        action('SSK {ctrl+esc}{esc}')
##        print 'mx, my:', mx, my
        action("TOCLOCK")   # get mouse there
        action("WINKEY b")  # get focus on icon tray (Gerrit van Wijk!)
        keystroke("{right}")
        keystroke(char[0])
示例#24
0
    def getIconLetter(self, char):
        """get the icon with the specified count in focus

        """
        ##        mod1 = natlink.getCurrentModule()
        ##        mod2 = mod1
        ##        nTry = 0
        ##        action('SSK {ctrl+esc}{esc}')
        ##        print 'mx, my:', mx, my
        action("TOCLOCK")  # get mouse there
        action("WINKEY b")  # get focus on icon tray (Gerrit van Wijk!)
        keystroke("{right}")
        keystroke(char[0])
示例#25
0
    def gotResults_searchinothertask(self, words, fullResults):
        ## rule for searching in another task, activated only if ...
        
        t = time.time()
        searchWord = self.getSelectedText()
        print 'searchWord from getSelectedText: %s'% searchWord
        if not searchWord:
            searchWord = action("SELECTWORD")
            if not searchWord:
                print '_tasks, searchinothertask: could not select text'
                return
        t1 = time.time() 
        print 'searchword: %s (%.2f)'% (searchWord, t1-t)
        countOrApp = words[1]
        #print 'switch to task: %s'% countOrApp
        result = self.gotoTask(countOrApp)
        if result is None:
            print '_tasks, could not switch to task: %s'% countOrApp
            return
        print 'result after taskswitch: %s'% repr(result)
        t2 = time.time() 

        prog, title, topchild, windowHandle = progInfo = result
        #print 'switched to "%s" (%.2f)'%  (prog, t2-t1)


        if prog == 'explorer' and not title:
            return # no centermouse!
        if self.centerMouse:
            natqh.Wait()
            natqh.doMouse(1, 5, 0.3, 0.3, 0, 0)  # relative in client area, no clicking           

        natqh.Wait()
        # now do the postprocessing
        print 'postprocessing for search: %s in app: %s'% (searchWord, prog)
        if prog in ['chrome', 'firefox','iexplore']:
            phrase = '"%s" site:nl'% searchWord
            keystroke("{ctrl+k}")
            keystroke(phrase + "{enter}")
        elif prog == 'dictionaryworkbench':
            # hardcoded for Arnoud
            keystroke('{ctrl+f}')
            action("SCLIP %s"% searchWord)
            keystroke('{enter}')
        else:
            #t3 = time.time()
            action("<<startsearch>>", progInfo=progInfo)
            #t4 = time.time()
            keystroke(searchWord, progInfo=progInfo)
            #t5 = time.time()
            action("<<searchgo>>", progInfo=progInfo)
示例#26
0
    def gotResults_searchinothertask(self, words, fullResults):
        ## rule for searching in another task, activated only if ...

        t = time.time()
        searchWord = self.getSelectedText()
        print 'searchWord from getSelectedText: %s' % searchWord
        if not searchWord:
            searchWord = action("SELECTWORD")
            if not searchWord:
                print '_tasks, searchinothertask: could not select text'
                return
        t1 = time.time()
        print 'searchword: %s (%.2f)' % (searchWord, t1 - t)
        countOrApp = words[1]
        #print 'switch to task: %s'% countOrApp
        result = self.gotoTask(countOrApp)
        if result is None:
            print '_tasks, could not switch to task: %s' % countOrApp
            return
        print 'result after taskswitch: %s' % repr(result)
        t2 = time.time()

        prog, title, topchild, windowHandle = progInfo = result
        #print 'switched to "%s" (%.2f)'%  (prog, t2-t1)

        if prog == 'explorer' and not title:
            return  # no centermouse!
        if self.centerMouse:
            natqh.Wait()
            natqh.doMouse(1, 5, 0.3, 0.3, 0,
                          0)  # relative in client area, no clicking

        natqh.Wait()
        # now do the postprocessing
        print 'postprocessing for search: %s in app: %s' % (searchWord, prog)
        if prog in ['chrome', 'firefox', 'iexplore']:
            phrase = '"%s" site:nl' % searchWord
            keystroke("{ctrl+k}")
            keystroke(phrase + "{enter}")
        elif prog == 'dictionaryworkbench':
            # hardcoded for Arnoud
            keystroke('{ctrl+f}')
            action("SCLIP %s" % searchWord)
            keystroke('{enter}')
        else:
            #t3 = time.time()
            action("<<startsearch>>", progInfo=progInfo)
            #t4 = time.time()
            keystroke(searchWord, progInfo=progInfo)
            #t5 = time.time()
            action("<<searchgo>>", progInfo=progInfo)
    def getNextNotes(self, n=1):
        if self.nextchars is None:
            self.nextchars = self.frescobaldi.getNextLine()
        print 'nextchars: |%s|' % self.nextchars
        if self.justLeft is None:
            self.getPrevNext()
        if self.inMiddleOfWord:
            print 'inMiddleOfWord %s' % self.inMiddleOfWord
            if not self.prevchars:
                self.prevchars = self.frescobaldi.getPrevLine()
            lastWord = self.prevchars.split()[-1]
            numcharsleft = len(lastWord)
            print 'go left %s characters' % numcharsleft
            keystroke("{left %s}" % numcharsleft)
            self.getPrevNext()
            self.nextchars = self.frescobaldi.getNextLine()

        print 'nextchars: %s' % repr(self.nextchars)
        wordsList, notesIndexes = analyseString(self.nextchars)
        print 'wordsList: %s, notesIndexes: %s' % (wordsList, notesIndexes)
        notesFound = len(notesIndexes)

        if notesFound <= n:
            moreLines = 5
            print 'get %s more lines' % moreLines
            nextchars = self.frescobaldi.getNextLine(moreLines)
            # nextcharsplit = self.nextchars.split('\n\n') # double empty line ends the search
            # if len(nextcharsplit) > 1:
            #     self.hasAllInfoNext = True
            # self.nextchars = nextcharsplit[0]
            if nextchars == self.nextchars:
                raise Exception(
                    "getNextNotes, not enough notes found: %s, wanted: %s" %
                    (notesFound, n))
            self.nextchars = nextchars
            wordsList, notesIndexes = analyseString(self.nextchars)
            notesFound = len(notesIndexes)
            print '----nextchars: %s' % repr(self.nextchars)
            if notesFound < n:
                print 'notesFound: %s' % notesFound
                print 'wordsList: %s, notesIndexes: %s' % (wordsList,
                                                           notesIndexes)
                raise Exception(
                    "too little notes caught in %s lines down: %s, wanted: %s"
                    % (moreLines, notesFound, n))
        else:
            self.hasAllInfoNext = True
        wordsList, notesIndexes, beforeNotes, afterNotes, afterNoteComplete = \
                              getNotesFromWordsList(n, wordsList, notesIndexes)
        afterNoteComplete = afterNoteComplete or self.hasAllInfoNext
        return wordsList, notesIndexes, beforeNotes, afterNotes, afterNoteComplete
示例#28
0
    def getIconNumber(self, count):
        """get the icon with the specified count in focus

        """
        ##        mod1 = nfile openfile openlink.getCurrentModule()
        ##        mod2 = mod1
        ##        nTry = 0
        ##        action('SSK {ctrl+esc}{esc}')
        ##        print 'mx, my:', mx, my
        action("TOCLOCK")
        action("WINKEY b")  # get focus on icon tray (Gerrit van Wijk!)
        natqh.visibleWait()
        n = count
        keystroke("{right %s}" % n)
示例#29
0
    def getIconNumber(self, count):
        """get the icon with the specified count in focus

        """        
##        mod1 = nfile openfile openlink.getCurrentModule()
##        mod2 = mod1
##        nTry = 0
##        action('SSK {ctrl+esc}{esc}')
##        print 'mx, my:', mx, my
        action("TOCLOCK")
        action("WINKEY b")  # get focus on icon tray (Gerrit van Wijk!)
        natqh.visibleWait()
        n = count
        keystroke("{right %s}"% n)
示例#30
0
 def rule_notesinsert(self, words):
     """[here] insert [<sequence>]"""
     ###
     ### position at correct position, possibly put a space.
     if self.hasCommon(words, 'here'):
         natqh.buttonClick()
     self.getPrevNext()
     # position at left of word
     while self.inMiddleOfWord:
         keystroke("{left}")
         self.getPrevNext()
     # and put a space:
     keystroke("{space}{left}")
     self.getPrevNext()
示例#31
0
    def gotResults_fileswitch(self, words, fullResults):
        """switch file to the named application

        mark cursor
        close in current app
        open in new app
        goto top
        goto cursor
        
        if filename cannot be got the process is stopped

        """
        fileName = actions.getPathOfOpenFile()
        if fileName:
            print 'fileName: %s' % fileName
        else:
            self.DisplayMessage(
                'cannot switch, filename cannot be established')
            return

        while fileName.endswith("*"):
            fileName = fileName[:-1]
        actions.putCursor()
        action("<<filesave>>")
        action("W")
        print "saved, now close: %s" % fileName
        action("<<documentclose>>")
        newApp = words[-1]
        newApp = self.ini.get('application', newApp, newApp)

        if not action("BRINGUP %s" % newApp):
            self.DisplayMessage(
                'cannot switch, application %s cannot be brought to front' %
                newApp)
            return

        # fileopen in emacs relies on maximised state of emacs, cannot be sure here:
        if newApp in ('emacs', 'voicecode'):
            action("{ctrl+x}{ctrl+f}; {shift+home}{del}")
        else:
            action("<<fileopen>>")
        action("W")
        keystroke(os.path.normpath(fileName))
        action("VW")
        keystroke("{enter}")
        action("<<topdocument>>")
        actions.findCursor()
        action("<<filesave>>")
示例#32
0
    def gotResults_namephrase(self,words,fullResults):
        # list of words that can be combined in a double christian name
        #  eg Jan Jaap or Jan-Marie 
        voornamenList = ['Jan', 'Jaap', 'Peter', 'Louise', 'Anne'
                         ]
        modInfo = natlink.getCurrentModule()
        action("CLIPSAVE")
        keystroke("{Ctrl+c}")

        # do contents of clipboard:
        t = string.strip(natlink.getClipboard())
        if not t:
            modInfo = natlink.getCurrentModule()
            if natqh.matchModule('natspeak', 'spell', modInfo):
                keystroke("{ExtHome}{Shift+ExtEnd}{Ctrl+x}")
                natqh.Wait(0.5)
                t = string.strip(natlink.getClipboard())
                if not t:
                    action("CLIPRESTORE")
                    return
            else:
                if self.language == 'nld':
                    com = "Selecteer dat"
                else:
                    com  = "Select That"
                if natqh.getDNSVersion() >= 7:
                    com = com.lower()
                action("HW %s"%com)
                natqh.Wait(0.5)
                keystroke("{Ctrl+c}")
                
                t = string.strip(natlink.getClipboard())
                if not t:                    
                    self.DisplayMessage("select a text first")
                    action("CLIPRESTORE")
                    return
        if self.hasCommon(words, ['naam', 'Name']):
            result = namelist.namelistUnimacro(t, ini=self.ini)
            print 'result of namelistUnimacro function: %s'% result
            for r in result:
                print 'adding part: %s'% r
                natqh.addWordIfNecessary(t)
            keystroke(r)
        else: # zonder naam in words, a normal phrase:
            print 'adding phrase %s'% t
            natqh.addWordIfNecessary(t)
            keystroke(t)
        action("CLIPRESTORE")
示例#33
0
    def gotResults(self, words, fullResults):
        tag = self.letters.strip()
        ##        print 'rule gotResults: %s'% tag
        pleft = pright = ""
        if not tag:
            return
        pleft = '<%s>' % tag
        if tag.find(' ') >= 0:
            endTag = ' '.split(tag)[0]
        else:
            endTag = tag
        pright = '</%s>' % endTag

        # see of something selected, leave clipboard intact
        natqh.saveClipboard()
        keystroke('{ctrl+x}')  # try to cut the selection
        contents = natlink.getClipboard().replace('\r', '').strip()
        natqh.restoreClipboard()

        leftText = rightText = leftTextDict = rightTextDict = ""
        #if contents:
        #    # strip from clipboard contents:
        #    contents, leftText, rightText = self.stripFromBothSides(contents)
        #if self.dictated.strip():
        #    contents, leftTextDict, rightTextDict = self.stripFromBothSides(self.dictated)
        #elif self.dictated:
        #    # the case of only a space-bar:
        #    leftTextDict = self.dictated
        #
        #lSpacing = leftText + leftTextDict
        #rSpacing = rightTextDict + rightText
        #
        #if lSpacing:
        #    keystroke(lSpacing)

        keystroke(pleft)
        if contents:
            #print 'contents: |%s|'% repr(contents)
            keystroke('{ctrl+v}')
        keystroke(pright)

        #if rSpacing:
        #    keystroke(rSpacing)

        if not contents:
            # go back so you stand inside the brackets:
            nLeft = len(pright)
            keystroke('{ExtLeft %s}' % nLeft)
示例#34
0
    def gotResults_namephrase(self, words, fullResults):
        # list of words that can be combined in a double christian name
        #  eg Jan Jaap or Jan-Marie
        voornamenList = ['Jan', 'Jaap', 'Peter', 'Louise', 'Anne']
        modInfo = natlink.getCurrentModule()
        action("CLIPSAVE")
        keystroke("{Ctrl+c}")

        # do contents of clipboard:
        t = string.strip(natlink.getClipboard())
        if not t:
            modInfo = natlink.getCurrentModule()
            if natqh.matchModule('natspeak', 'spell', modInfo):
                keystroke("{ExtHome}{Shift+ExtEnd}{Ctrl+x}")
                natqh.Wait(0.5)
                t = string.strip(natlink.getClipboard())
                if not t:
                    action("CLIPRESTORE")
                    return
            else:
                if self.language == 'nld':
                    com = "Selecteer dat"
                else:
                    com = "Select That"
                if natqh.getDNSVersion() >= 7:
                    com = com.lower()
                action("HW %s" % com)
                natqh.Wait(0.5)
                keystroke("{Ctrl+c}")

                t = string.strip(natlink.getClipboard())
                if not t:
                    self.DisplayMessage("select a text first")
                    action("CLIPRESTORE")
                    return
        if self.hasCommon(words, ['naam', 'Name']):
            result = namelist.namelistUnimacro(t, ini=self.ini)
            print 'result of namelistUnimacro function: %s' % result
            for r in result:
                print 'adding part: %s' % r
                natqh.addWordIfNecessary(t)
            keystroke(r)
        else:  # zonder naam in words, a normal phrase:
            print 'adding phrase %s' % t
            natqh.addWordIfNecessary(t)
            keystroke(t)
        action("CLIPRESTORE")
示例#35
0
    def gotResults_dgndictation(self, words, fullResults):
        #self.text = ' '.join(map(natqh.stripSpokenForm, words))
        # try with the improved nsformat function
        if self.gotPassword:
            print 'gotPassword, analyse password: %s' % words
            text = nsformat.formatPassword(words)
            keystroke(text)
            self.gotPassword = 0
            print 'reset gotPassword, ', self.gotPassword

        if self.search and self.text in ['on', 'verder']:  #
            self.search = 2
        elif self.search and self.text in ['new', 'nieuw']:
            self.search = 3
        elif self.search and self.text in ['terug', 'back']:
            self.search = 4
        print 'dgndictation: %s' % self.text
示例#36
0
    def flushAll(self):
        if self.buf:
            try:
                buf = ''.join(self.buf)
            except TypeError:
                print "---TypeError in flushAll of _keystrokes: %s" % repr(
                    self.buf)
                raise

            #print 'flushAll: %s'% buf
            if self.codes:
                action("SCLIP %s" % buf)
            elif buf.find("<<") >= 0:
                action(buf)
            else:
                keystroke(buf)
            self.buf = []
示例#37
0
    def gotResults_fileswitch(self, words, fullResults):
        """switch file to the named application

        mark cursor
        close in current app
        open in new app
        goto top
        goto cursor
        
        if filename cannot be got the process is stopped

        """
        fileName = actions.getPathOfOpenFile()
        if fileName:
            print 'fileName: %s'% fileName
        else:
            self.DisplayMessage('cannot switch, filename cannot be established')
            return
            
        while fileName.endswith("*"):
              fileName = fileName[:-1]
        actions.putCursor()
        action("<<filesave>>")
        action("W")
        print "saved, now close: %s"% fileName
        action("<<documentclose>>")
        newApp = words[-1]
        newApp = self.ini.get('application', newApp, newApp)
           
        if not action("BRINGUP %s"% newApp):
            self.DisplayMessage('cannot switch, application %s cannot be brought to front'% newApp)
            return

        # fileopen in emacs relies on maximised state of emacs, cannot be sure here:
        if newApp in ('emacs', 'voicecode'):
            action("{ctrl+x}{ctrl+f}; {shift+home}{del}")
        else:
            action("<<fileopen>>")
        action("W")
        keystroke(os.path.normpath(fileName))
        action("VW")
        keystroke("{enter}")
        action("<<topdocument>>")
        actions.findCursor()
        action("<<filesave>>")
示例#38
0
 def outputNumber(self, number):
     keystroke(number)
     #Step 5:
     # Here some extra postprocessing for different programs:
     prog = natqh.getProgName()
     if prog in ['iexplore', 'firefox', 'chrome', 'safari']:
         keystroke('{tab}')
     elif prog in ['natspeak']:  # DragonPad
         keystroke('{enter}')
     elif prog in ['excel']:
         keystroke('{tab}')
示例#39
0
    def gotResults_comment(self, words, fullResults):
        name = nameList[words[-1]]
        if name:
            ts = time.strftime("%d%m%Y", time.localtime(time.time()))
        else:
            ts = time.strftime("%d%m%y_", time.localtime(time.time()))

        m = natlink.getCurrentModule()
        if natqh.matchModule('pythonwin', modInfo=m):
            com = "#" + name + ts
        elif natqh.matchModule('textpad', 'html', modInfo=m):
            com = "<!--" + name + ts + "-->"
        elif natqh.matchModule(m, 'textpad', '.c', modInfo=m):
            com = "$$$$" + name + ts + "$$$$"
        elif natqh.matchModule(m, 'textpad', '.py', modInfo=m):
            com = "#" + name + ts
        else:
            com = name + ts
        keystroke(com + "\n")
示例#40
0
    def outputNumber(self, number):
        if type(number) in [types.IntType, types.FloatType]:
            number = str(number)

        keystroke(number)
        prog = natqh.getProgName()
        if prog in ['iexplore', 'firefox', 'chrome', 'safari']:
            keystroke('{tab}')
        elif prog in ['natspeak']:
            keystroke('{enter}')
        elif prog in ['excel', 'winword']:
            keystroke('{tab}')
示例#41
0
    def gotResults_comment(self,words,fullResults):
        name = nameList[words[-1]]
        if name:
            ts = time.strftime("%d%m%Y", time.localtime(time.time()))
        else:
            ts = time.strftime("%d%m%y_", time.localtime(time.time()))

        m = natlink.getCurrentModule()
        if natqh.matchModule('pythonwin', modInfo=m):
            com = "#" + name + ts
        elif natqh.matchModule('textpad', 'html', modInfo=m):
            com = "<!--" + name + ts + "-->"
        elif natqh.matchModule(m,'textpad', '.c', modInfo=m):
            com = "$$$$" + name + ts + "$$$$"
        elif natqh.matchModule(m,'textpad', '.py', modInfo=m):
            com = "#" + name + ts
        else:
            com = name + ts
        keystroke(com+"\n")
示例#42
0
    def gotResults_variable(self,words,fullResults):
        cmdVariable = self.hasCommon(words[0], 'Variable')
        cmdMethod = self.hasCommon(words[0], 'Method')
        
        c = self.getNumberFromSpoken(words[-1])
        
        if c:
            keystroke('{Shift+Ctrl+ExtLeft %s}' % c)
        else:
            action("HW select that")
            natqh.Wait(0.1)
        keystroke('{ctrl+x}')
        natqh.Wait(0.1)
        t = natlink.getClipboard()
        # put spaces if they were collected on the clipboard:
        while t and t[0] == " ":
            t = t[1:]
            keystroke(" ")
        t = t.strip()
        if not t:
            print 'no variable to compress!'
            return
        # split words into a list:
        w = t.split()
        if cmdVariable or cmdMethod:
            # uppercase each command word:
            w = map(self.capit, w)

        T = ''.join(w)
        if cmdVariable:
            T = T[0].lower() + T[1:]
        # add words to vocabulary!
        if natqh.getDNSVersion() >= 11:
            backslashes = '\\\\'
        else:
            backslashes = '\\'
        if len(w) > 1:
            natqh.addWordIfNecessary(T+backslashes+t)
        else:
            natqh.addWordIfNecessary(T)
            
        keystroke(T)
示例#43
0
    def gotResults_navigatepages(self,words,fullResults):
        """go to next or previous page(s) and refresh possibly"""
##        print 'navigate pages: %s'% words
        
        dir = None
        command = self.getFromInifile(words, 'pagecommands',noWarning=1)
        
        if self.hasCommon(words, ['next', 'verder', 'volgende', 'vooruit', 'forward']):
            dir = 'right'
        elif self.hasCommon(words, ['previous', 'terug', 'vorige', 'back']):
            dir = 'left'
        else:
            print 'no direction found in command: %s'% words
        
        counts = self.getNumbersFromSpoken(words)
        if counts:
            count = counts[0]
        else:
            count = 1
##        print 'PAGES:     dir: %s, count: |%s|, command: |%s|'% (dir, counlinker balkt, command)
        if mode == 'hah':
            keystroke(Escape[mode])

        getNumbersAgain = 1
        if dir:        
            while count > 0:
                count= count -1
                keystroke('{alt+ext%s}'%(dir))
                natqh.Wait(0.5) #0.3 seem too short for going back pages in Firefox
        #elif count:
        #    print "Ctl + number doesnot work always!"
        #    keystroke('{ctrl+%s}'% count)
        #    natqh.Wait(0.3)
            
        if command:
            action(command)
        if command.lower().find('f5') > 0:
            # refresh action:
            getNumbersAgain = 1

        # only get new numbers if no refresh was asked for
        if getNumbersAgain and mode =="hah":
            natqh.Wait(waitBeforeNewNumbers)
            keystroke(getNumbers[mode])
示例#44
0
 def gotResults_moretabsclose(self,words,fullResults):
     """close more tabs in one commands
     """
     n = self.getNumberFromSpoken(words[0])
     for i in range(n):
         keystroke("{ctrl+w}")
示例#45
0
    def gotResults(self, words, fullResults):
        """actions for task move, resize, position done here
        
        relevant data collected in other gotResult_... functions
        
        """
        if self.giveName:
            if self.namedictated:
                self.namedtaskDict[self.namedictated] = self.giveName
                self.setList('namedtask', self.namedtaskDict.keys())
                print 'name "%s" can now be used for switching to a task'% self.namedictated
            else:
                print 'giveName, no self.namedictated given...'
                
        if self.hadStartMenu:
            self.doStartMenu()
            if self.letters:
                keystroke(self.letters)

        if self.taskmoveresize:
            print 'taskmoveresize: %s'% self.taskmoveresize
            winHndle = win32gui.GetForegroundWindow()
            #print 'amount: %s'% self.amount
            #print 'units: %s'% self.units
            if self.directionplus in self.directions:
                direction = self.directions[self.directionplus]
            else:
                direction = self.directionplus
            print 'direction spoken: %s, direction taken: %s'% (self.directionplus, direction)
            canBeResized = monitorfunctions.window_can_be_resized(winHndle)
            if self.taskmoveresize == 'position':
                self.doTaskPositionCommand(winHndle, canBeResized, direction, self.amount, self.units)
            else:
                # move, stretch or shrink:
                if self.amount:
                    amount = self.amount
                    units = self.units or 'pixels'
                elif self.taskmoveresize == 'move':
                    amount = 1
                    units = 'relative'
                elif self.taskmoveresize == 'stretch':
                    amount = 1
                    units = 'relative'
                elif self.taskmoveresize == 'shrink':
                    amount = 0.5
                    units = 'relative'
                else:
                    print '_tasks, gotResults, invalid taskmoveresize: %s'% self.taskmoveresize
                    return

                print 'amount (adjusted): %s'% amount
                print 'units: (adjusted) %s'% units
    
                try:
                    func = getattr(monitorfunctions, '%s_window'% self.taskmoveresize, None)
                    if func:
                        #print 'doing func: %s'% func
                        func(winHndle, direction=self.directionplus, amount=amount, units=units)
                    else:
                        print 'invalid value for taskmoveresize: %s (could not find function)'% self.taskmoveresize                
                except ValueError:
                    print 'error in monitorfunctions.%s_window'% self.taskmoveresize
                    print sys.exc_info()[1]
示例#46
0
 def gotResults_update(self,words,fullResults):
     """forces refresh of numbers on the page with MLB"""
     keystroke('{alt+=}')
示例#47
0
    def gotResults_navigatetabs(self,words,fullResults):
        """switch to tabs in firefox

        goto numbered tab or to next|previous tab. optional command (refresh)
        """
##        print 'navigate tabs: %s'% words
        dir = None
        minus = None
        command = self.getFromInifile(words, 'tabcommands',noWarning=1)
        
        if self.hasCommon(words, ['next', 'verder', 'volgend','volgende']):
            dir = 'pgdn'
        elif self.hasCommon(words, ['previous', 'terug', 'vorig', 'vorige']):
            dir = 'pgup'
        elif self.hasCommon(words, ['minus', 'min']):
            minus = 1
            
        counts = self.getNumbersFromSpoken(words)
        if counts:
            count = counts[0]
        else:
            count = None
        #print 'TABS: dir: %s, count: |%s|, command: |%s|'% (dir, count, command)
        keystroke(Escape[mode])

        getNumbersAgain = 1
        if dir:        
            keystroke('{ctrl+ext%s %s}'%(dir, count or '1'))
            natqh.Wait(visiblePause)
        elif count:
            if mode == 'mlb':
                  if minus:
                      mbDonumber("01",'ctrl')
                      # need to wait:
                      natqh.Wait(visiblePause*2)
                      dir = 'pgup'
                      keystroke('{ctrl+ext%s %s}'%(dir, count or '1'))
                      natqh.Wait(visiblePause)
                  else:
##                      print 'go to tab: %s'% count
                      numberString = '%s%s'% (0,count)
                      mbDonumber(numberString,'ctrl')
            else:
                  if minus:
                      print 'not implemented in hah'
                  else:
                      keystroke('{ctrl+%s}'% count)
        else:
            getNumbersAgain = 0
            
        if command:
            natqh.Wait(visiblePause*2)
            action(command)

        if command.lower().find('f5') > 0:
            # refresh action:
            getNumbersAgain = 0

        if getNumbersAgain and mode =="hah":
            natqh.Wait(waitBeforeNewNumbers)
            keystroke(getNumbers[mode])
示例#48
0
    def gotResults(self,words,fullResults):
    
        # step 5, in got results collect the number:
        # only necessary in this grammar for collecting the choose command
        if not self.hadChoose:
            return
        self.collectNumber()
        print '%s: dictated number: %s'% (self.name, self.number)
        
        if mode =="hah":
##            print 'hah go to number:',self.number
            keystroke("%s"% self.number)
            # natqh.Wait(visiblePause)
            keystroke(getNumbers[mode])
            print 'firefox browsing with hah obsolete'
            return
            if self.hadChoose in ['focus']:
                pass
            elif not self.hadNew:
                keystroke("{enter}")
            elif self.hasCommon(self.hadNew,['tab', 'tabblad']):
                keystroke("{numpadd++}")
            elif self.hasCommon(self.hadNew, ['venster', 'window']):
                keystroke("{shift+enter}")
            elif self.hasCommon(self.hadNew, ['menu', 'snelmenu']): 
                keystroke("{shift+shift}")
                return
            elif self.hasCommon(self.hadNew,['new', 'nieuw']):
                keystroke("{numpadd++}")
                return
            else:
                print 'unknown word in command: %s'% self.hadNew
                keystroke("{enter}")

            natqh.Wait(waitBeforeNewNumbers)
            keystroke(getNumbers[mode])
            
        elif mode == "mlb":
            keystroke("{esc}")
            if self.chooseSpecification == 'new':
                #print 'firefox MLB: open in new tab'
                mbDonumber(self.number,'alt')
            elif self.chooseSpecification in ['focus', 'context menu']:
                #print 'firefox MLB: show focus'
                mbDonumber(self.number)
                keystroke("{shift}")
                if self.chooseSpecification == 'context menu':
                    keystroke("{shift+f10}")
            else:
                mbDonumber(self.number,'ctrl')
示例#49
0
 def gotResults(self,words,fullResults):
     """if stack auto, do after each move a {ctrl+a}"""
     if self.stackAuto:
         keystroke('{ctrl+a}')
示例#50
0
 def rule_stop_undo(self, words):
     "'hold on'|stop|undo"
     self.cancelMode()
     if self.hasCommon(words, 'undo'):
         keystroke('{ctrl+z}')
示例#51
0
    def gotResults(self,words,fullResults):
        if self.highlight:
            # for Shane
            asterisksSpacing = 1   # to be perfected later as option of this grammar
            if asterisksSpacing:
                if self.text.find('*'):
                    self.text = self.text.replace('*', ' * ')
            if self.text:
                action("<<startsearch>>")
                keystroke(self.text)
                action("<<searchgo>>")    
            else:
                print 'no text to highlight'
            return
            #keystroke("{ctrl+f}")
            #t = self.text
            #t = t.replace(' . ', '.')
            #t = t.replace('( ', '(')
            #t = t.replace(' )', ')')
            ##print 'execute highlight with "%s"'% highlightText
            #keystroke(t)
            #keystroke("{enter}")
            #return

        if self.search:
            progInfo = natqh.getProgInfo()

            # make provisions for searchwords (function (def), class (class) etc)
            if self.specialSearchWord:
                self.text = self.ini.get('searchwords', self.specialSearchWord) + self.text
            if self.count:
                count = int(self.count)
            else:
                count = 1
            if self.search == 'forward':
                # forward
                self.direc = 'down'
                res = self.searchOn(count, progInfo=progInfo)
                return
            elif self.search == 'new':
                # new, just start the search dialog:
                self.searchMarkSpot(progInfo=progInfo)
                action('<<startsearch>>', progInfo=progInfo)
                return
            elif self.search == 'back':
                # back:
                self.direc = 'up'
                res = self.searchOn(count, progInfo=progInfo)
                return
            elif self.search ==  'go back':
            # go back, return to origin
                print "search go back"
                self.searchGoBack(progInfo=progInfo)
                return
            elif self.search in ('for', 'before','after'):
                # new search with text
                self.direc = 'down'
                print 'new leap to text: %s'% self.text
                self.searchMarkSpot(progInfo=progInfo)
                res = self.searchForText(self.direc, self.text, progInfo=progInfo, beforeafter=self.search)
            elif self.search == 'extend':
                res = self.searchForText(self.direc, self.text, progInfo=progInfo, extend=1)
            elif self.search == 'insert':
                res = self.searchForText(self.direc, self.text, progInfo=progInfo, insert=1)
            else:
                print 'invalid search code: %s'% self.search
                self.DisplayMessage('search, invalid search code: %s'% self.search)
                return
            if res == -2:
            # search failed, did cancel mode
                return 
            natqh.visibleWait()
            print 'calling stop search'
            self.stopSearch(progInfo=progInfo)
示例#52
0
    def gotResults(self, words, fullResults):

        # see of something selected, leave clipboard intact
        natqh.saveClipboard()
        action('<<cut>>')
#        keystroke('{ctrl+x}')  # try to cut the selection
        contents = natlink.getClipboard().replace('\r','')
        natqh.restoreClipboard()

        leftText = rightText = leftTextDict = rightTextDict = ""
        if contents:
            # strip from clipboard contents:
            contents, leftText, rightText = self.stripFromBothSides(contents)

        if self.dictated.strip():
            contents, leftTextDict, rightTextDict = self.stripFromBothSides(self.dictated)
        elif self.dictated:
            # the case of only a space-bar:
            leftTextDict = self.dictated

        lSpacing = leftText + leftTextDict
        rSpacing = rightTextDict + rightText

        if lSpacing:
            keystroke(lSpacing)

        keystroke(self.pleft)
        if contents:
            #print 'contents: |%s|'% repr(contents)
            keystroke(contents)
        keystroke(self.pright)

        if rSpacing:
            keystroke(rSpacing)

        if not contents:
            # go back so you stand inside the brackets:
            nLeft = len(self.pright) + len(rSpacing)
            keystroke('{ExtLeft %s}'% nLeft)