def pythonwinCom2text(self, t): # t is the input text, to be stripped from "#"s # # look for starting spaces and '#' and spaces: m = PythonCommentLine.match(t) if m: self.prefix = m.group(0) # get list of paragraphs, with generator function, # regular expression for recognising comment lines given L = [par for par in stripPrefix(t, self.prefix)] return '\n'.join(L) elif not t: # starting with empty comment natqh.saveClipboard() action('<<selectline>>{ctrl+c}') t = natqh.getClipboard() natqh.restoreClipboard() p = len(t) - len(t.lstrip()) self.prefix = ' '*p + "# " if t.find(self.prefix) == 0: return t[len(self.prefix):] else: return t else: raise utilsqh.QHerror, 'not a valid python comment, try again'
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 pythonwinDocstring2text(self, t): # t is the input text m = StartingSpaces.match(t) if m: self.prefix = m.group(0) # get list of paragraphs, with generator function, # regular expression for recognising comment lines given L = [par for par in stripPrefix(t, self.prefix)] return '\n'.join(L) elif not t: # startin with current line natqh.saveClipboard() action('<<selectline>>{ctrl+c}') t = natqh.getClipboard() natqh.restoreClipboard() if not t: self.prefix = '' return '' p = len(t) - len(t.lstrip()) self.prefix = ' '*p if t.find(self.prefix) == 0: return t[len(self.prefix):] else: return t else: self.prefix = '' return t
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 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)
def gotResults_browsewith(self, words, fullResults): """show page in another browser""" m = natlink.getCurrentModule() prog, title, topchild = natqh.getProgInfo(modInfo=m) Iam2x = prog == '2xexplorer' IamExplorer = prog == 'explorer' browser = prog in ['iexplore', 'firefox', 'opera', 'netscp', 'chrome'] if not browser: self.DisplayMessage('command only for browsers') return print 'words:', words natqh.saveClipboard() action( '<<addressfield>>; {extend}{shift+exthome}{ctrl+c};<<addressfieldclose>>' ) askedBrowser = self.getFromInifile(words, 'browsers') if askedBrowser == prog: self.DisplayMessage('command only for another browser') return print 'try to bring up browser: |%s|' % askedBrowser action('RW') action('AppBringUp "%s"' % askedBrowser) action('WTC') action('<<addressfield>>; {ctrl+v}{enter}') natqh.restoreClipboard()
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_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)
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)
def rule_numbereddocument(self, words): """# go to a numbered document document ({documentcount} [{documentaction}] | {documentaction}) """ count = self.getNumberFromSpoken(words[1]) # returns a string or None if count: #print 'goto task, countOrApp: %s'% countOrApp result = self.gotoDocument(count) if result: if self.centerMouse: natqh.Wait() natqh.doMouse(1, 5, 0.3, 0.3, 0, 0) # relative in client area, no clicking else: prog, title, topchild, windowHandle = natqh.getProgInfo() print '_tasks, could not switch to document: %s (program: %s)' % ( count, prog) if words[1] == words[-1]: return Act = self.getFromInifile(words[-1], 'documentaction') print 'words[-1]: %s, Action: %s' % (words[-1], Act) if Act: action(Act)
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)
def gotResults_clicklocation(self, words, fullResults): locationWord = words[-1] print 'clicklocation: %s'% locationWord clicklocation = self.ini.get(self.currentModule, locationWord, "") if not clicklocation: print 'oops, no clicklocation found for %s'% locationWord return action(clicklocation)
def gotResults_clicklocation(self, words, fullResults): locationWord = words[-1] print 'clicklocation: %s' % locationWord clicklocation = self.ini.get(self.currentModule, locationWord, "") if not clicklocation: print 'oops, no clicklocation found for %s' % locationWord return action(clicklocation)
def gotResults_stopwatch(self, words, fullResults): """ stopwatch""" if self.hasCommon(words, 'start'): self.startTime = time.time() else: t = time.time() elapsed = t - self.startTime action('MSG %.2f seconds' % elapsed) self.startTime = t
def gotResults_mousefix(self,words,fullResults): fix = 0 xPos,yPos = natlink.getCursorPos() if self.hasCommon(words, ['vast', 'omlaag', 'Down', 'Fix']): action('MDOWN') elif self.hasCommon(words, ['los', 'omhoog', 'Up', 'Release']): action('ENDMOUSE') else: print '_general, mousefix, invalid keywords: %s'% words
def getSelectedText(self): """gets a copy of the selection, otherwise "" """ natqh.saveClipboard() action("<<copy>>") natqh.Wait() t = natqh.getClipboard() natqh.restoreClipboard() return t.strip()
def gotResults_stopwatch(self,words,fullResults): """ stopwatch""" if self.hasCommon(words, 'start'): self.startTime = time.time() else: t = time.time() elapsed = t - self.startTime action('MSG %.2f seconds'% elapsed) self.startTime = t
def gotResults_redo(self,words,fullResults): counts = self.getNumbersFromSpoken(words) if counts: count = counts[0] else: count = 1 #print 'count: %s'% count for i in range(count): action('<<redo>>')
def gotResults_redo(self, words, fullResults): counts = self.getNumbersFromSpoken(words) if counts: count = counts[0] else: count = 1 #print 'count: %s'% count for i in range(count): action('<<redo>>')
def gotResults_mousefix(self, words, fullResults): fix = 0 xPos, yPos = natlink.getCursorPos() if self.hasCommon(words, ['vast', 'omlaag', 'Down', 'Fix']): action('MDOWN') elif self.hasCommon(words, ['los', 'omhoog', 'Up', 'Release']): action('ENDMOUSE') else: print '_general, mousefix, invalid keywords: %s' % words
def doIconAction(self, actionWord, mouseOnPosition=0): """do action on icon """ if actionWord: act = self.ini.get('iconaction', actionWord) if act: action(act) else: print 'no action for iconaction: %s' % actionWord
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()
def doIconAction(self, actionWord, mouseOnPosition=0): """do action on icon """ if actionWord: act = self.ini.get('iconaction', actionWord) if act: action(act) else: print 'no action for iconaction: %s'% actionWord
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
def rule_startmenu(self, words): """start menu [{startmenucommands}] """ print 'got start menu' if self.hasCommon(words[0], 'start'): self.hadStartMenu = 1 Act = self.getFromInifile(words[-1], 'startmenucommands') if Act: self.hadStartMenu = 0 # no action in gotResults, doing it here self.doStartMenu() action(Act)
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
def doTaskAction(self, actionWord, mouseOnPosition=0): """do action on if mouseOnPosition, instead of {alt+space} a right click is done """ if actionWord: act = self.ini.get('taskaction', actionWord) if act: #natqh.visibleWait() action(act) else: print 'no action for taskaction: %s' % actionWord
def doTaskAction(self, actionWord, mouseOnPosition=0): """do action on if mouseOnPosition, instead of {alt+space} a right click is done """ if actionWord: act = self.ini.get('taskaction', actionWord) if act: #natqh.visibleWait() action(act) else: print 'no action for taskaction: %s'% actionWord
def main(): credentials = aiy.assistant.auth_helpers.get_assistant_credentials() with Assistant(credentials) as assistant: os.system("aplay ~/nicks-gassistant/sample-audio-files/Startup.wav") for event in assistant.start(): process_event(event) usercmd=event.args if 'trigger'.lower() in str(usercmd).lower(): assistant.stop_conversation() action(str(usercmd).lower()) if 'turn'.lower() in str(usercmd).lower(): assistant.stop_conversation() automate(str(usercmd).lower())
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])
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()
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)
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)
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
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")
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])
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 gotoDocument(self, count): """go to the specified document, by number or application name, return proginfo, or None if task was not found """ result = action('DOCUMENT %s' % count) print 'result of gotoDocument %s: %s' % (count, result) return result
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 searchOn(self, count, progInfo=None): """search up or down possibly more times""" if progInfo is None: progInfo = natqh.getProgInfo(modInfo) sectionList = actions.getSectionList(progInfo=progInfo) if self.direc == 'back': searchGoOn = actions.getMetaAction('searchgoback', sectionList=sectionList, progInfo=progInfo) else: searchGoOn = actions.getMetaAction('searchgoforward', sectionList=sectionList, progInfo=progInfo) for i in range(count): if searchGoOn: res = action(searchGoOn) else: res = self.searchForText(self.direc, progInfo=progInfo) self.direc = self.getLastSearchDirection( ) # in case back search changed it! if res == -2: # search failed, did cancel mode return natqh.visibleWait() if not searchGoOn: self.stopSearch(progInfo)
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])
def create_a_job(self, sess): new_action = action(ACTIONID = "BASICJOB", CMDLINE = QUICK_CMD, USERID = self.new_user.USERID) sess.add(new_action) sess.flush() new_job = job(ACTIONID = "BASICJOB", SCHEDID = "ONCE", status = 0) sess.add(new_job) sess.flush() q = sess.query(job).filter(job.ACTIONID == "BASICJOB").all() a = sess.query(action).filter(action.ACTIONID == "BASICJOB").first() return q
def editaction(self, id, time=None, dashboard=0): sess = db.getsession() try: j = sess.query(actions.action).filter(actions.action.ACTIONID==id).one() except: j = actions.action(ACTIONID = id, STDIN = "", COMMENTS = "", CMDLINE = "") j.USERID = cherrypy.session.get('hquserid') return self.lookup.get_template(ACTIONS + "editaction.html").render(action=j, table=db.action_table, dashboard=dashboard)
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()
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)
def gotResults_convertfile(self, words, fullResults): """copy file and change \n\r in \n or vice versa mark cursor cut all convert clipboard paste goto home goto cursor """ actions.putCursor() action("CLIPSAVE") action("<<selectall>><<cut>>") t = natlink.getClipboard() t = self.convertString(t, words[-1]) natqh.setClipboard(t) action("<<paste>>") action("<<topdocument>>") actions.findCursor() action("<<filesave>>")
def action(action_name, name, *args): if actions.set_info.no_info: return False, 'no_info' try: print(action_name, name, args) if (action_name == 'exist'): return True, actions.exist(name) proc = getattr(actions, action_name) return True, actions.action(proc, name, args) except: print str(sys.exc_info()[1]) return False, str(sys.exc_info()[1])
def subrule_closemultiple(self, words): """close (all|other) | (all|other) close """ # note the grammar alternatives, eg in Dutch the translation of # all close (alles sluiten) is more convenient. if not self.lastTaskCount: print '_tasks, close all | close multiple only works with a numbered task' return all = self.hasCommon(words, "all") multiple = self.hasCommon(words, "multiple") if all: action("MP 2, 0, 0, right; VW; {up}{enter}; VW") self.gotoTask("back") elif multiple: # close as long as special stacked window is found mousePos = natqh.getMousePosition() if mousePos is None: raise ValueError("could not get mouse position") x, y = mousePos className = natqh.getClassName() wNum = -1 # last window of stacked windows... #print 'tasks, subtask: %s'% wNum while className == "TaskListThumbnailWnd": #print 'got subtask, alternative window: %s'% words self.doAlternativeClick(className, wNum) action("<<windowclose>>") action("VW; MP 0, %s, %s"% mousePos) className = natqh.getClassName() self.gotoTask(self.lastTaskCount) if self.centerMouse: natqh.doMouse(1, 5, 0.3, 0.3, 0, 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()
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)
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 gotResults_browsewith(self,words,fullResults): """show page in another browser""" m = natlink.getCurrentModule() prog, title, topchild = natqh.getProgInfo(modInfo=m) Iam2x = prog == '2xexplorer' IamExplorer = prog == 'explorer' browser = prog in ['iexplore', 'firefox','opera', 'netscp', 'chrome'] if not browser: self.DisplayMessage ('command only for browsers') return print 'words:', words natqh.saveClipboard() action('<<addressfield>>; {extend}{shift+exthome}{ctrl+c};<<addressfieldclose>>') askedBrowser = self.getFromInifile(words, 'browsers') if askedBrowser == prog: self.DisplayMessage('command only for another browser') return print 'try to bring up browser: |%s|'% askedBrowser action('RW') action('AppBringUp "%s"'% askedBrowser) action('WTC') action('<<addressfield>>; {ctrl+v}{enter}') natqh.restoreClipboard()
#!/usr/bin/python from db import db from actions import action """ Drops any table name passed via any input. It is not recommended that this form action be used without a double prompt to prevent data loss. """ with action() as act: col_val = act.getColVal() for col, val in col_val.items(): if val == 'off': continue with db() as db: db.drop(col) # IN DEBUG MODE THERE SHOULD BE A PAGE DESCRIBING WHAT HAPPENED # AND A REDIRECT BUTTON
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)
@check_auth(ACTIONS_AUTH, db.EDIT_MINE) def saveaction(self, **kwargs): sess = db.getsession() u = sess.query(user).filter(user.USERID == cherrypy.session.get('hquserid')).one() try: if u.actions(db.EDIT_MINE) and not u.actions(db.EDIT): if kwargs["USERID"] != u.USERID: return "Error: Unable to save action , you do not have rights to do so." except Exception, e: return "Error: " + str(e) try: a = sess.query(actions.action).filter(actions.action.ACTIONID == kwargs["ACTIONID"]).one() except Exception, e: a = actions.action(ACTIONID = kwargs["ACTIONID"]) sess.add(a) try: fillobj(a, db.action_table, kwargs) sess.flush() except Exception, e: return str(e) return "Saved." saveaction.exposed = True @check_auth(ACTIONS_AUTH, db.EDIT_MINE) def saveactiondep(self, **kwargs): sess = db.getsession() try: sess.query(actiondeps.actiondep).filter(and_(actiondeps.actiondep.ACTIONID == kwargs["ACTIONID"], actiondeps.actiondep.DEPACTIONID == kwargs["DEPACTIONID"])).one()
def copyaction(self, id, newid): sess = db.getsession() try: astruct = sess.query(actions.action).filter(actions.action.ACTIONID == id).one() a = actions.action(ACTIONID = newid) a.TITLE = astruct.TITLE a.CMDLINE = astruct.CMDLINE a.STDIN = astruct.STDIN a.STARTINDIR = astruct.STARTINDIR a.MAXRUNTIME = astruct.MAXRUNTIME a.STDOUT = astruct.STDOUT a.CREATEEVENT = astruct.CREATEEVENT a.COMMENTS = astruct.COMMENTS a.USERID = cherrypy.session.get('hquserid') a.ACTIONID = newid a.STATUS = 4 sess.add(a) sess.flush() avalids = sess.query(validreturncode).filter(validreturncode.ACTIONID == id).all() for i in avalids: new_valid = validreturncode() new_valid.ACTIONID = newid new_valid.VALUE = i.VALUE sess.add(new_valid) sess.flush() adeps = sess.query(actiondeps.actiondep).filter(actiondeps.actiondep.ACTIONID == id).all() for i in adeps: new_dep = actiondeps.actiondep() new_dep.ACTIONID = newid new_dep.DEPACTIONID = i.DEPACTIONID sess.add(new_dep) sess.flush() fdeps = sess.query(filedep).filter(filedep.ACTIONID == id).all() for i in fdeps: new_dep = filedep() new_dep.ACTIONID = newid new_dep.SERVERID = i.SERVERID new_dep.FILENAME = i.FILENAME new_dep.TYPE = i.TYPE sess.add(new_dep) sess.flush() aservers = sess.query(actionservers.actionserver).filter(actionservers.actionserver.ACTIONID == id).all() for i in aservers: new_serv = actionservers.actionserver() new_serv.ACTIONID = newid new_serv.SERVERID = i.SERVERID sess.add(new_serv) sess.flush() agrps = sess.query(actiongroup).filter(actiongroup.ACTIONID == id).all() for i in agrps: new_grp = actiongroup() new_grp.ACTIONID = newid new_grp.GROUPID = i.GROUPID sess.add(new_grp) sess.flush() aevts = sess.query(actionevent).filter(actionevent.ACTIONID == id).all() for i in aevts: new_evt = actionevent() new_evt.ACTIONID = newid new_evt.EVENTNUM = i.EVENTNUM new_evt.RESULT = i.RESULT new_evt.TYPE = i.TYPE sess.add(new_evt) sess.flush() return "Copied" except Exception, e: return e