Ejemplo n.º 1
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))
                unimacroutils.Wait(
                    0.5)  #0.3 seem too short for going back pages in chrome

        if command:
            action(command)
Ejemplo n.º 2
0
    def gotResults_navigatetabs(self, words, fullResults):
        """go to next or previous tab(s) (documents) and refresh possibly"""
        print(f'navigate tabs: {words}')
        dir = None
        command = self.getFromInifile(words, 'tabcommands', noWarning=1)

        if self.hasCommon(
                words, ['next', 'verder', 'volgende', 'vooruit', 'forward']):
            dir = 'tab'
        elif self.hasCommon(words, ['previous', 'terug', 'vorige', 'back']):
            dir = 'shift+tab'
        else:
            print(f'no direction found in command: {words}')

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

        if dir:
            while count > 0:
                count -= 1
                keys = '{ctrl+' + dir + '}'
                keystroke(keys)
                unimacroutils.Wait(
                    0.5)  #0.3 seem too short for going back tabs in chrome

        if command:
            action(command)
    def tearDown(self):
        for hndle in self.tempFileHndles:
            if not win32gui.IsWindow(hndle):
                print("???window does not exist: %s"% hndle)
                continue
            if hndle == self.thisHndle:
                # print('window hndle %s may not match "thisHndle": %s'% (hndle, self.thisHndle))
                continue
            # print('close window with hndle: %s'% hndle)
            natlinkutilsqh.SetForegroundWindow(hndle)
            curHndle = natlinkutilsqh.GetForegroundWindow()

            if hndle == curHndle:
                if hndle in self.killActions:
                    # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
                    # place to break in debug mode
                    # natlinkutilsqh.SetForegroundWindow(curHndle)
                    action(self.killActions[hndle], modInfo=self.modInfos[hndle])
                else:
                    natlinkutils.playString("{alt+f4}")
        natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        self.disconnect()  # disabled, natConnect
        notClosedHndles = []
        for hndle in self.tempFileHndles:
            if hndle and win32gui.IsWindow(hndle):
                notClosedHndles.append(hndle)
    
        if self.frescHndle:
            if self.frescHndle in notClosedHndles:
                notClosedHndles.remove(self.frescHndle)
            else:
                raise TestError('Fresobaldi should not be closed after the test')
        if notClosedHndles:
            raise TestError('Hndles not close, but should: %s'% notClosedHndles)
Ejemplo n.º 4
0
    def gotResults_tabactions(self, words, fullResults):
        """do an actions to the current tab (doc)"""
        # print(f'tabactions words: {words}')
        command = self.getFromInifile(words, 'tabcommands')

        if command:
            action(command)
Ejemplo n.º 5
0
 def gotResults_filenamelastpage(self, words, fullResults):
     # additional command, compose filename with the last called page number(s).
     # need variables in inifile section [general]: filename pagenumber prefix and filename pagenumber postfix
     # if these are not set, of if no page numbers are "remembered", do nothing
     if self.lastPage:
         if self.lastThroug:
             lp, lt = int(self.lastPage), int(self.lastThroug)
             if lt > lp:
                 pagePart = '%s-%s' % (lp, lt)
             else:
                 pagePart = self.lastPage
         else:
             pagePart = self.lastPage
     else:
         print(
             'numbers extended: no page numbers command issued yet, skip command'
         )
         return
     if not self.filenamePagenumbersPrefix:
         print(
             '%s: command "%s", please specify "filename page numbers prefix" in section [general] of inifile'
             % (' '.join(words), self.name))
     if not self.filenamePagenumbersPostfix:
         print(
             '%s: command "%s", please specify "filename page numbers postfix" in section [general] of inifile'
             % (' '.join(words), self.name))
     if self.filenamePagenumbersPrefix and self.filenamePagenumbersPostfix:
         fName = self.filenamePagenumbersPrefix + pagePart + self.filenamePagenumbersPostfix
         action("SCLIP %s" % fName)
Ejemplo n.º 6
0
    def testAutoHotKey(self):
        """test ahk scripts
        """
        #action("AHK showmessageswindow.ahk")

        # action("AHK runcontrolget.ahk")

        action("AHK send hello")  ###h
        action("AHK send {backspace 4}")
Ejemplo n.º 7
0
    def rule_notechangemove(self, words):
        """<notesnavigate>(<sequence>|{noteaction}|forward)"""
        self.justInsert = False

        act = self.getFromInifile(words[-1], 'noteaction')
        if act:
            action(act)
            return
        if self.hasCommon(words[-1], 'forward'):
            self.gotoNextNote()
Ejemplo n.º 8
0
 def rule_backgroundcolor(self, words):
     """[here] background [color] {color}
     """
     app = self.excel.app
     if self.hasCommon(words[0], 'here'):
         action("MP 2,0,0;")
     colorCode = int(self.getFromInifile(words[-1], 'color'))
     if colorCode:
         app.ActiveCell.Interior.ColorIndex = colorCode
     else:
         app.ActiveCell.Interior.ColorIndex = None
Ejemplo n.º 9
0
 def doMouseMoveStopClick(self):
     """wait for mouse starting to move, stopping and then click
     """
     action("ALERT")
     if not action("WAITMOUSEMOVE"):
         action("ALERT 2")
         return
     if not action("WAITMOUSESTOP"):
         return
     action("ButtonClick")
     action("ALERT")
     return 1
Ejemplo n.º 10
0
    def gotResults_numberedtabs(self, words, fullResults):
        """go to a numbered tab (doc) and do an optional action"""
        print(f'numberedtabs: {words}')
        command = self.getFromInifile(words, 'tabcommands')

        counts = self.getNumbersFromSpoken(words)
        if not counts:
            print(
                f'_clickbyvoice, numberedtabs, no valid tab number found: {words}'
            )
            return

        if command:
            action(command)
Ejemplo n.º 11
0
    def setupFrescobaldiNewPane(self):
        """start an empty pane in Frescobaldi (front end for Lilypond music type setter)
        
        at shutdown do not kill this window
        """
        ## this extra makes an empty window, and goes to the message pane:
        extra = '\n'.join(["Sleep, 100", 'Send, ^n', "Sleep, 100"])

        result = actions.AutoHotkeyBringUp(app=r"C:\Program Files (x86)\Frescobaldi\frescobaldi.exe", title="Frescobaldi", extra=extra)
        pPath, wTitle, hndle = result
        action("Frescobaldi abacadabra")
        self.tempFileHndles.append(hndle)
        self.frescHndle = hndle
        self.killActions[hndle] = "KW({ctrl+w}, {right}{enter})"
        self.modInfos[hndle] = result
Ejemplo n.º 12
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 = []
Ejemplo n.º 13
0
 def tttest_getOutsideWindow(self):
     """try to position on the taskbar and get the position
     """
     
     action("RMP(5, 1, 0.5, noclick)") # relative in foreground window, tune to your testing!
     action("MP(2, 500, 0, noclick)")   # move a bit to the right
     initialPosition = natlink.getCursorPos()
     mousePos = natlinkutilsqh.getMousePosition() # abs, screen, corner not relevant
     if mousePos is None:
         self.fail("could not get mouse position")
     x, y = mousePos
     absorrel, which = 0, 0
     natlinkutilsqh.doMouse(absorrel, which, x, y, mouse="noclick")
     finalPosition = natlink.getCursorPos()
     log('command outside window(?): %s, %s, %s, %s, initial: %s, final: %s'% (absorrel, which, x, y, repr(initialPosition), repr(finalPosition)))
     self.assert_equal(initialPosition, finalPosition, "position of mouse after move outside the current window should be the same\n"
             "absorrel: %s, which: %s"% (absorrel, which))
Ejemplo n.º 14
0
 def tttest_getPositions(self):
     """test setting and getting positions in all possible ways
     
     use action RMP to go to the wanted position.
     
     then each time get a position
     (absolute/relative, absorrel, screen, active window or client area (0, 1, 5),
     and relative to one of the corners (0, 1, 2, 3))
     setting it again and see if same position is found
     
     get with: getMousePosition
     set with: doMouse
     """
     #absorrel = 0 # absolute
     #which = 0 # whole screen
     #corner = 0 # top left
     action("RMP(5, 0.3, 0.4, noclick)") # relative in foreground window, tune to your testing!
     
     initialPosition = natlink.getCursorPos()
     for absorrel in (0, 1):
         for which in (0, 1, 5):
             for cornerPos in range(4):
                 #absorrel, which, cornerPos = 1, 0, 0
                 #absorrel = 1
                 # each test, little shifting for relative allowed
                 if absorrel:
                     epsilon = 0 # relative, position may shift a bit...
                 else:
                     epsilon = 0  # absolute, caculations must fit
                 if absorrel == 0 and which == 0 and cornerPos > 0:
                     print('invalid combination to test: absorrel: %s, which: %s, cornerPos: %s'% (absorrel, which, cornerPos))
                     continue
                 initialPosition = natlink.getCursorPos()
                     
                 mousePos = natlinkutilsqh.getMousePosition(absorrel, which, cornerPos)
                 if mousePos is None:
                     self.fail('getMousePosition in test suite should not result in None (absorrel: %s, which: %s, cornerPos: %s)'%
                                (absorrel, which, cornerPos))
                 x, y = mousePos
                 natlinkutilsqh.doMouse(absorrel, which, x, y, mouse="noclick")
                 finalPosition = natlink.getCursorPos()
                 log('command: %s, %s, %s, %s, initial: %s, final: %s'% (absorrel, which, x, y, repr(initialPosition), repr(finalPosition)))
                 self.assert_equal(initialPosition, finalPosition, "position of mouse after simple action should be the same\n"
                         "absorrel: %s, which: %s, cornerPos: %s"% (absorrel, which, cornerPos),
                         epsilon=epsilon)
Ejemplo n.º 15
0
    def setupThunderbirdNewWindow(self):
        """start an empty mail message in Thunderbird
        
        at shutdown do not kill this window 
        """
        ## this extraaow, and goes to the message pane:
        extra = '\n'.join(['Send, ^n',
                'SetTitleMatchMode, 2',
                'WinWaitNotActive, ##title##',
                'Sleep, 100',
                'Send, {tab 2}'])     # note SetTitleMatchMode and Sleep, apparently necessary

        result = actions.AutoHotkeyBringUp(app="thunderbird.exe", title="Mozilla Thunderbird", extra=extra)
        pPath, wTitle, hndle = result
        self.tempFileHndles.append(hndle)
        self.thundHndle = hndle
        self.killActions[hndle] = "KW({ctrl+w}, w)"   # kill the window, with letter w if windows has text....
        self.modInfos[hndle] = result
        action("Thunderbird new window abacadabra")
Ejemplo n.º 16
0
 def doWordAction(self):
     """process count, direction and action
     
     if done, reset variables,
     if variables missing, do nothing
     """
     if self.count is None or self.wordAction is None:
         print('not ready for word action: %s, %s, %s' %
               (self.count, self.direction, self.wordAction))
         return
     if self.count == 0:
         #print 'doWordAction, single click: %s, %s, %s'% (self.count, self.direction, self.wordAction)
         pass
     else:
         #print 'doWordAction (select words): %s, %s, %s'% (self.count, self.direction, self.wordAction)
         wordSelect = "SELECTWORD %s, %s" % (self.count, self.direction)
         action(wordSelect)
     if self.wordAction:
         action(self.wordAction)
     self.resetWordVariables()
Ejemplo n.º 17
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
Ejemplo n.º 18
0
 def doSearchAction(self):
     """process count, direction and action, in this case a search into another window
     
     (coupling with tasks grammar)
     
     if done, reset variables,
     if variables missing, do nothing
     """
     if self.count is None or self.searchAction is None:
         print('not ready for word action: %s, %s, %s' %
               (self.count, self.direction, self.wordAction))
         return
     if self.count == 0:
         #print 'doWordAction, single click: %s, %s, %s'% (self.count, self.direction, self.wordAction)
         pass
     else:
         #print 'doWordAction (select words): %s, %s, %s'% (self.count, self.direction, self.wordAction)
         wordSelect = "SELECTWORD %s, %s" % (self.count, self.direction)
         action(wordSelect)
     if self.searchAction:
         print('now the search action in the tasks grammar: %s' %
               self.searchAction)
         self.tasksGrammar.rule_searchinothertask(self.searchAction)
     self.resetWordVariables()
Ejemplo n.º 19
0
    def get_selection_that(self, line=0):
        unimacroutils.saveClipboard()

        if line:
            action('<<selectline>><<cut>>')
        else:
            action('<<cut>>')
        contents = natlink.getClipboard().strip().replace('\r', '')
        if len(contents) == 0:
            if line:
                print('_latex, empty line')
                return ""
            action('HW select that')
            action('<<cut>>')
            contents = natlink.getClipboard().strip().replace('\r', '')
            if len(contents) == 0:
                print(
                    '_latex, empty contents, no last dicatate utterance available'
                )

        unimacroutils.restoreClipboard()
        return contents
Ejemplo n.º 20
0
    def gotResults(self, words, fullResults):

        #  see if something selected, leaving the clipboard intact
        #  keystroke('{ctrl+x}')  # try to cut the selection
        if self.between:
            cb = Clipboard(save_clear=True)
            action('<<cut>>')
            text = cb.get_text(waiting_interval=0.1, waiting_iterations=3)
        else:
            text = ""

        if self.here:
            unimacroutils.buttonClick('left', 1)
            unimacroutils.visibleWait()

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

        if self.dictated.strip():
            text, leftTextDict, rightTextDict = 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)

        action(self.pleft)
        unimacroutils.visibleWait()
        if text:
            #print 'text: |%s|'% repr(text)
            keystroke(text)
        unimacroutils.visibleWait()
        action(self.pright)
        unimacroutils.visibleWait()

        if rSpacing:
            keystroke(rSpacing)

        if not text:
            # go back so you stand inside the (brackets):
            nLeft = len(self.pright) + len(rSpacing)
            keystroke('{left %s}'% nLeft)
Ejemplo n.º 21
0
    def gotResults(self, words, fullResults):
        comment = 'command: %s' % ' '.join(words)
        self.prog = self.progInfo.prog
        self.collectNumber()
        #print 'lines command: %s (direction: %s)'% (comment, self.lastDirection)
        #print 'type line: %s'% type(self.line)
        #print 'base: %(base)s, line: %(line)s, through: %(through)s, ' \
        #      'movecopyto: %(movecopyto)s, action: %(action)s'% self.__dict__
        if self.movecopyto and self.action[1] == 'to':
            intLine = int(self.movecopyto)
            if intLine >= 100 or self.movecopyto.startswith('0'):
                self.movecopyto = intLine  # always absolute
            elif self.currentLine:
                intLine = getLineRelativeTo(intLine, self.currentLine)
                self.movecopyto = intLine
            else:
                self.movecopyto = intLine
        if self.line:
            intLine = int(self.line)
            #print 'intLine: %s, currentLine: %s'% (intLine, self.currentLine)
            if len(self.line) > 2:
                self.line = intLine  # always absolute
            elif self.currentLine:
                intLine = getLineRelativeTo(intLine, self.currentLine)
                print('getLineRelativeTo, old: %s new: %s (currentline: %s)' %
                      (self.line, intLine, self.currentLine))
                self.line = intLine
            else:
                self.line = intLine

        if self.through:
            intThrough = int(self.through)
            if intThrough > self.line:
                self.through = intThrough  # always absolute
            else:
                if len(self.through) == 2:
                    modulo = 100
                else:
                    modulo = 10
                print('modulo for through: %s' % modulo)
                intThrough = getLineRelativeTo(intThrough,
                                               self.line,
                                               modulo=modulo,
                                               minLine=self.line)
                self.through = intThrough

            ## should not happen often:
            if self.line > self.through:
                # calculate the next higher number respective to self.line
                ndigits = len(repr(self.through))
                steps = 10**ndigits
                leftPart = self.line // steps
                newThrough = leftPart * steps + self.through
                while newThrough < self.line:
                    leftPart += 1
                    newThrough = leftPart * steps + self.through
                self.through = newThrough

            self.numlines = self.through - self.line + 1
        #print 'line: "%(line)s", to: "%(through)s", movecopyto: "%(movecopyto)s"' \
        #     ', numlines "%(numlines)s", action: "%(action)s"'%  self.__dict__

        # doing the selection part:
        T = []
        self.goingUp = 0
        if self.previousLines:
            self.goingUp = 1
        if self.nextLines:
            T.append('{extdown}')
        if self.firstPart == 'that':
            pass
        elif self.firstPart == 'lineback':
            T.append('<<lineback>>')
        elif self.firstPart == 'lines':
            if self.goingUp:
                T.append('<<selectpreviousline>>')
                if self.numlines > 1:
                    T.append('<<selectup %s>>' % (self.numlines - 1, ))
            else:
                T.append('<<selectline>>')
                if self.numlines > 1:
                    T.append('<<selectdown %s>>' % (self.numlines - 1, ))
        elif self.firstPart == 'paras':
            print('paragraphs!')
            if self.goingUp:
                print('vorige alinea')
                T.append('<<selectpreviouspara>>')
                if self.numlines > 1:
                    T.append('<<selectparaup %s>>' % (self.numlines - 1, ))
            else:
                print('deze of volgende alinea')
                T.append('<<selectpara>>')
                if self.numlines > 1:
                    T.append('<<selectparadown %s>>' % (self.numlines - 1, ))

        elif self.firstPart == 'linesnum':
            T.append('<<gotoline %s>>' % self.line)
            if self.numlines > 1:
                T.append('<<selectline>>')
                T.append('<<selectdown %s>>' % (self.numlines - 1, ))
            elif self.action != None:
                # only when you call for a single line without action, NO
                # selection is done
                T.append('<<selectline>>')

        t1 = time.time()
        action(''.join(T), comment=comment)
        t2 = time.time()
        ##        print 'line select action: %s'% (t2-t1)
        T = []

        # doing the action part:
        if self.column:
            keystroke("{right %s}" % self.column)
            return
        if not self.action:
            return
        if isinstance(self.action, str):
            action(self.action, comment=comment)
        elif type(self.action) == list:
            if self.action[0] == 'move':
                T.append('<<cut>>')
            elif self.action[0] == 'copy':
                T.append('<<copy>>')
                if not self.prog in ['excel']:
                    if self.lastDirection == 'up':
                        T.append('{extleft}')
                    elif self.lastDirection == 'down':
                        T.append('{extright}')
            else:
                raise LinesError('invalid movecopy action (first word): %s' %
                                 self.action)

            print('gotResult: movecopyto: %s (%s)' %
                  (self.movecopyto, type(self.movecopyto)))
            print('gotResult: numlines: %s' % self.numlines)

            if self.action[1] == 'up':
                if self.prog in ['excel']:
                    T.append("<<movetotopofselection>>")
                if self.prog in ['pycharm64', 'pycharm32']:
                    print('pycharm, %s' % repr(T))
                    if self.action[0] == 'copy':
                        T.append("{ctrl+d}")  # duplicate
                    T.append("{shift+ctrl+up %s}" % self.numlines)
                else:
                    # all other applications
                    T.append('{up %s}' % self.movecopyto)

            elif self.action[1] == 'down':
                if self.prog in ['excel']:
                    T.append("<<movetobottomofselection>>")
                    self.movecopyto += 1
                if self.prog in ['pycharm64', 'pycharm32']:
                    print('pycharm, %s' % repr(T))
                    if T and T[0] == "<<copy>>":
                        T = ["{ctrl+d}"]  ## duplicate
                    else:
                        T = []
                    T.append("{shift+ctrl+down %s}" % self.numlines)
                else:
                    # all other applications:
                    T.append('{down %s}' % self.movecopyto)
            elif self.action[1] == 'to':
                if self.action[0] == 'move' and not self.prog in ['excel']:
                    # if new line below the current line, the cut lines have to be accounted for (not in excel though)
                    currentLine = self.line or self.currentLine
                    if currentLine:
                        if self.movecopyto > currentLine + self.numlines:
                            self.movecopyto -= self.numlines
                    else:
                        print(
                            '_lines: movecopyaction: current line not known, move can be wrong if target is below current line'
                        )

                T.append('<<gotoline %s>>' % self.movecopyto)
            else:
                raise LinesError('invalid movecopy action (second word): %s' %
                                 self.action)
            T.append('<<movecopypaste>>')
            if self.numlines and not self.prog in ['excel']:
                T.append('{extup %s}{exthome}' % self.numlines)
##            action('<<upafterpaste>>', comment=comment)
            T.append('<<afterlines>>')
        if T:
            t1 = time.time()
            action(''.join(T), comment=comment)
            t2 = time.time()
Ejemplo n.º 22
0
    def tttestCopyClipboardGetSetText(self):
        """use the clipboard for getting and the window text
        
        Run with one target at a time
        
        
        """
        print("testCopyClipboardSwitching")
        # self.setupDocxFile()
        self.setupThunderbirdNewWindow()
        self.testHndle = self.thundHndle
        # self.setupFrescobaldiNewPane()
        # self.testHndle = self.frescHndle
        # self.setupTextFiles()
        
        
        for i in range(1, 21, 10):
            waitTime = 0.001/i

            t0 = time.time()
    
            ## start with empty window
            action("{ctrl+a}{del}")
            
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime=waitTime)
            expText = ""
            expPosTuple = (0,0,0)  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
            
            action("Hello world")

            # these pair of lines provide the possibility to debug the tests
            # put the breakpoint at the second line...
            # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
            # natlinkutilsqh.SetForegroundWindow(self.testHndle)
    
    
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expText = "Hello world"
            expPosTuple = (11, 11, 11)  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
            pass

    
            # now select word world
            action("{shift+ctrl+left}")
    
            # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
            # natlinkutilsqh.SetForegroundWindow(self.testHndle)

    
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expText = "Hello world"
            expPosTuple = (6, 11, 11)  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")

            ## and again:
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
    
            # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
            # natlinkutilsqh.SetForegroundWindow(self.testHndle)
    
            # now replace the word world, and make a second line
            action('SCLIP(WORLD{enter}How are you going?{enter}In this Corona world?)')
            expText = "Hello WORLD\nHow are you going?\nIn this Corona world?"
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expPosTuple = (52, 52, 52)  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
            pass

            ## and again:    
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
    
            # select all
            action("{ctrl+home}{shift+ctrl+end}")
            expText = "Hello WORLD\nHow are you going?\nIn this Corona world?"
            # if self.testHndle == self.thundHndle:
            #     expText += "\n"
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expPosTuple = (0, len(expText), len(expText))  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")

            # and again:
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expPosTuple = (0, len(expText), len(expText))  # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")

            # select "are you"
            action("{ctrl+home}{down}{right 4}{shift+right 7}")
            expText = "Hello WORLD\nHow are you going?\nIn this Corona world?"
            # not here!!
            # if self.testHndle == self.thundHndle:
            #     expText += "\n"
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expPosTuple = (16, 23, 23) # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")
    
            ## and again:
            text, startSel, endSel, cursorPos = self.getTextViaClipboard(waitTime)
            expPosTuple = (16, 23, 23) # startSel, endSel, cursorPos
            self.assert_equal(expText, text, "text not as expected")
            self.assert_equal(expPosTuple, (startSel, endSel, cursorPos), "positions not as expected")


            t1 = time.time()
            elapsed = t1 - t0
            print("time %.6f for round with waitTime: %.6f "% (elapsed, waitTime))
Ejemplo n.º 23
0
def stringpaste(t):
    """paste via clipboard, to circumvent German keyboard issues
    """
    action('SCLIP "%s"' % t)
Ejemplo n.º 24
0
    def getTextViaClipboard(self, waitTime):
        """get text of window and selection or cursor via copy paste actions
        
        pass waitTime for testing response time.
        
        waiting_iterations is default 10, but changed to 3 if an empty clipboard is expected
        
        return: text, selStart, selEnd, cursorPos
               
        """
        cb = natlinkclipboard.Clipboard(save_clear=True, debug=1)
        waitTime = 0.001
      
        # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        # natlinkutilsqh.SetForegroundWindow(self.testHndle)
        
        ## first try if there is a selection:
        action("{ctrl+c}")
        selection = cb.get_text(waitTime, waiting_iterations=3)
        if selection:
            print('selection: %s'% selection)
            action("{left}")
            cb.clear_clipboard()

           
        # now try text left of selection:
        action("{ctrl+shift+home}{ctrl+c}")
     
        # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        # natlinkutilsqh.SetForegroundWindow(self.testHndle)
     
     
        before = cb.get_text(waitTime)
        if before:
            action("{right}")
            cb.clear_clipboard()
        else:
            print("at start of document")

        # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        # natlinkutilsqh.SetForegroundWindow(self.testHndle)

        text = before + selection
        selStart = len(before)
        selEnd = len(text)
    
        # skip to end of selection:       
        if selection:
            action("{right %s}"% len(selection))

        # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        # natlinkutilsqh.SetForegroundWindow(self.testHndle)
        
        if text:
            # now select to end:
            action("{shift+ctrl+end}{ctrl+c}")
            after = cb.get_text(waitTime)
            print("after: %s"% repr(after))
            
            if not after:
                if self.testHndle == self.thundHndle:
                    ## after an empty selection, go one to the left!!
                    action("{left}")
                    pass
                after = ""
            else:
                # undo selection
                action("{left}")
            if after.endswith('\0'):
                after = after.replace('\0', '')
                print("removed null char at end of selection (1): %s"% after)
                # after = afterplusone[1:]
        else:
            # presumably at start of buffer
            action("{shift+ctrl+end}{ctrl+c}")
            after = cb.get_text(waitTime, waiting_iterations=3)
            if after:
                # undo selection 
                action("{left}")
            else:
                pass
            if after.endswith('\0'):
                after = after.replace('\0', '')
                print("removed null char at end of selection (2): %s"% after)
                # after = afterplusone[1:]
                cb.clear_clipboard()

        if selection:
            lensel = len(selection)
            # select from left to right;
            
            # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
            # natlinkutilsqh.SetForegroundWindow(self.testHndle)
            
            action("{left %s}{shift+right %s}"% (lensel, lensel))

        text = text + after
        cursorPos = selEnd            

        # natlinkutilsqh.SetForegroundWindow(self.thisHndle)
        # natlinkutilsqh.SetForegroundWindow(self.testHndle)


        return text, selStart, selEnd, cursorPos
Ejemplo n.º 25
0
 def testUnimacroBringup(self):
     """test ahk scripts
     """
     notepadFile = testFilesDir / "testempty.txt"
     action("BRINGUP %s" % notepadFile)
Ejemplo n.º 26
0
    def gotResults(self, words, fullResults):
        # step 5, in got results collect the number:
        self.collectNumber()

        if self.totalNumber:
            # multiple numbers, AmsterdamZuid
            self.totalNumber += self.number
            print('gotResults totalNumber: ', self.totalNumber)
            if self.message:
                print(
                    'Error collecting the number, do NOT output the number...')
                print(self.message)
            else:
                self.outputNumber(self.totalNumber)
            if len(self.totalNumber) == 13 and self.totalNumber[-5] == '.':
                keystroke("{tab}")
            elif len(self.totalNumber) == 5 and self.totalNumber[0] == '.':
                keystroke("{tab}")

            return

        if self.page:
            ## page numbers rule (for child windows, adobe [acrord32] of pdf24.)
            self.lastPage, self.lastThroug = self.page, self.through
            print('setting lastPage and lastThroug: %s, %s' %
                  (self.lastPage, self.lastThroug))
            isTop = (self.progInfo[2] == 'top')
            ma = getMetaAction('pagestart', progInfo=self.progInfo)
            if not ma:
                print('no metaactions defined for pagestart, stop command %s' %
                      self.progInfo.prog)
                if isTop:
                    if self.through:
                        keystroke(" page %s-%s" % (self.page, self.through))
                    else:
                        keystroke(" page %s" % self.page)
                else:
                    print("cannot finish page command for child window: %s" %
                          repr(self.progInfo))
                return

            action("<<pagestart>>")
            keystroke(self.page)
            if self.progInfo.prog == 'pdf24-creator' and self.through == '':
                self.through = self.page

            if self.through:
                ## only child window here:
                action("<<pagethrough>>")
                keystroke(self.through)
            action("<<pagefinish>>")
            return  # page command

        elif self.pair:
            self.pair = self.doMinus('pair', 'minus')
            print("(%s, %s) " % (self.number, self.pair))

        #elif self.listtupleargument:
        #    print 'self.listtupleargument in gotResults: %s'% self.listtupleargument
        #    if self.number:
        #        self.number = self.doMinus('number', 'minus')
        #        self.Items.append(self.number)
        #
        #    if self.dictated:
        #        self.Items.append(''.join(self.dictated))
        #        self.dictated = None
        #
        #    result = repr(self.Items)
        #    print 'result: %s'% self.Items
        #    if self.listtupleargument == 'list':
        #        print 'list: %s'% result
        #    elif self.listtupleargument == 'tuple':
        #        result = repr(tuple(self.Items))
        #        print 'tuple: %s'% result
        #    else:
        #        result = repr(tuple(self.Items)).replace(', ', ',')
        #        result = result.replace(', ',',')
        #        print 'argument: %s'% result
        #
        elif self.ibanCheck and self.ibanHeader:
            try:
                # print 'ibanheader: %s, number: %s'% (self.ibanHeader, self.number)
                result = Iban = iban.create_iban(self.ibanHeader[:2],
                                                 self.ibanHeader[2:],
                                                 self.number)
            except iban.IBANError as err:
                print('invalid iban %s, %s (%s)' %
                      (self.ibanHeader, self.number, err))
                return
            if result[2:4] == str(self.ibanCheck):
                keystroke(result)
            else:
                print('invalid check: %s (%s) ' % (self.ibanCheck, result))

        elif self.number:
            # last part if all others failed:
            self.number = self.doMinus('number', 'minus')
            self.outputNumber(self.number)