Esempio n. 1
0
 def appendList(self, listName, words):
     listName = utilsqh.convertToBinary(listName)
     if listName not in self.validLists:
         raise gramparser.GrammarError( "list %s was not defined in the grammar" % listName , self.scanObj)
     if type(words) in (six.binary_type, six.text_type):
         words = utilsqh.convertToBinary(words)
         self.gramObj.appendList(listName,words)
     else:
         for x in words:
             if type(x) == six.text_type:
                 x = utilsqh.convertToBinary(x)
             self.gramObj.appendList(listName,x)
def playString(keys, hooks=None):
    """do smarter and faster playString than natlink.playString
    
    If useMarkSendInput is set to 1 (True) (top of this file):
    the SendInput module of Mark Lillibridge is used.
    
    Disadvantage: does not work in elevated windows.
    
    This behaviour can be circumvented by adding a hook in the call,
    or by using SendDragonKeys, SendSystemKeys or SSK (Unimacro).
    
    If useMarkSendInput is set to 0 (False), or a hook is added
    (0x100 for normal behaviour, 0x200 for systemkeys behaviour)
    then natlink.playString is used, but a {shift} in front of the keystrokes is inserted,
    in order to prevent doubling or losing keystrokes.
    
    (if default behaviour is wanted, you can call natlink.playString directly)
    """
    if not keys:
        return
    keys = utilsqh.convertToBinary(keys)
    if hooks is None and useMarkSendInput:
        SendInput.send_input(
            ExtendedSendDragonKeys.senddragonkeys_to_events(keys))
    else:
        if hooks not in (None, 0x100):
            natlink.playString(keys, hooks)
        else:
            shiftkey = natlinkmain.shiftkey
            natlink.playString(shiftkey + keys)
Esempio n. 3
0
 def activate(self, ruleName, window=0, exclusive=None, noError=0):
     if type(ruleName) == six.text_type:
         ruleName = utilsqh.convertToBinary(ruleName)
     if ruleName not in self.validRules:
         raise gramparser.GrammarError(
             "rule %s was not exported in the grammar" % ruleName,
             self.scanObj)
     if type(ruleName) != six.binary_type:
         raise gramparser.GrammarError(
             'GrammarBase, wrong type in activate, %s (%s)' %
             (ruleName, type(ruleName)), self.scanObj)
     if ruleName in self.activeRules:
         if window == self.activeRules[ruleName]:
             print 'rule %s already active for window %s' % (ruleName,
                                                             window)
             return
         else:
             print 'change rule %s from window %s to window %s' % (
                 ruleName, self.activeRules[ruleName], window)
             self.gramObj.deactivate(ruleName)
     if debugLoad:
         print 'activate rule %s (window: %s)' % (ruleName, window)
     self.gramObj.activate(ruleName, window)
     self.activeRules[ruleName] = window
     if not exclusive is None:
         if debugLoad:
             print 'set exclusive mode to %s for rule %s' % (exclusive,
                                                             ruleName)
         self.setExclusive(exclusive)
     pass
    def load(self, gramSpec, allResults=0, hypothesis=0, grammarName=None):
        # print 'loading grammar %s, gramspec type: %s'% (grammarName, type(gramSpec))
        # code upper ascii characters with latin1 if they were in the process entered as unicode
        if not type(gramSpec) in (six.text_type, six.binary_type,
                                  types.ListType):
            raise TypeError(
                "grammar definition of %s must be a string or a list of strings, not %s"
                % (grammarName, type(gramSpec)))
        # print 'loading %s, type: %s'% (grammarName, type(gramSpec) )
        if type(gramSpec) == types.ListType:
            for i, grampart in enumerate(gramSpec):
                line = grampart
                if type(line) == six.binary_type:
                    line = utilsqh.convertToUnicode(line)
                if type(line) == six.text_type:
                    line = utilsqh.convertToBinary(line)
                if line != grampart:
                    gramSpec[i] = line
        if type(gramSpec) == six.binary_type:
            gramSpec = utilsqh.convertToUnicode(gramSpec)
        if type(gramSpec) == six.text_type:
            gramSpec = utilsqh.convertToBinary(gramSpec)
            gramSpec = gramSpec.split('\n')
            gramSpec = [g.rstrip() for g in gramSpec]

        gramparser.splitApartLines(gramSpec)
        parser = gramparser.GramParser(gramSpec, grammarName=grammarName)
        parser.doParse()
        parser.checkForErrors()
        gramBin = gramparser.packGrammar(parser)
        self.scanObj = parser.scanObj  # for later error messages.
        try:
            GramClassBase.load(self, gramBin, allResults, hypothesis)
        except natlink.BadGrammar:
            print 'GrammarBase, cannot load grammar, BadGrammar:\n%s\n' % gramSpec
            raise
        # we want to keep a list of the rules which can be activated and the
        # known lists so we can catch errors earlier
        self.validRules = parser.exportRules.keys()
        self.validLists = parser.knownLists.keys()

        # we reverse the rule dictionary so we can convert rule numbers back
        # to rule names during recognition
        self.ruleMap = {}
        for x in parser.knownRules.keys():
            self.ruleMap[parser.knownRules[x]] = x
        return 1
Esempio n. 5
0
 def emptyList(self, listName):
     if type(listName) == six.text_type:
         listName = utilsqh.convertToBinary(listName)
     if listName not in self.validLists:
         raise gramparser.GrammarError(
             "list %s was not defined in the grammar" % listName,
             self.scanObj)
     self.gramObj.emptyList(listName)
def checkForBinary(line):
    """ helper for converting to Binary
    """
    if type(line) == six.binary_type:
        return line
    elif type(line) == six.text_type:
        return utilsqh.convertToBinary(line)
    else:
        raise ValueError(
            "BrowseGrammar, checkForBinary should have binary or unicode as input, not: %s (%s)"
            % (line, type(line)))
Esempio n. 7
0
 def deactivate(self, ruleName, noError=0):
     if type(ruleName) == six.text_type:
         ruleName = utilsqh.convertToBinary(ruleName)
     if ruleName not in self.validRules:
         if noError: return
     if type(ruleName) != six.binary_type:
         print 'GrammarBase, deactivate, %s (%s)'% (ruleName, type(ruleName))
         raise gramparser.GrammarError( "rule %s (%s) was not exported in the grammar" %
                                       ruleName, type(ruleName), self.scanObj)
     if ruleName not in self.activeRules:
         if noError: return
         raise gramparser.GrammarError( "rule %s is not active", self.scanObj)
     if debugLoad: print 'deactivate rule %s'% ruleName
     self.gramObj.deactivate(ruleName)
     del self.activeRules[ruleName]
def getModifierKeyCodes(modifiers):
    """return a list with keycodes for modifiers
    
    input can be a list of valid modifiers (ctrl, shift or menu == alt ),
    either in a sequence or as single string. If string contains the + symbol or a space,
    the string is split before searching the keycodes
    
    Invalid input raises a KeyError.
    Testing in unittestNatLink, see testNatlinkUtilsFunctions
    
    """
    modifier_dict = dict(ctrl=vk_control,
                         shift=vk_shift,
                         menu=vk_menu,
                         alt=vk_menu)  # added alt  == menu
    if not modifiers: return
    if type(modifiers) == six.text_type:
        modifiers = utilsqh.convertToBinary(modifiers)
    if type(modifiers) == six.binary_type:
        modifiers = modifiers.replace("+", " ").split()
    return [modifier_dict[m] for m in modifiers]
Esempio n. 9
0
def splitApartLines(lines):
    """split apart the lines of a grammar and clean up unwanted spacing
    
    see  unittest still problems here!!
    """
    for x in range(len(lines) - 1, -1, -1):
        line = lines[x]
        if type(line) == six.binary_type:
            line = utilsqh.convertToUnicode(line)
        if type(line) == six.text_type:
            line = utilsqh.convertToBinary(line)
            lines[x] = line
        lines[x] = lines[x].rstrip()
        crlf = lines[x].find('\n')
        if crlf >= 0:
            if x > 0:
                print 'insert lines at item %s: %s' % (x, lines[x])
            lines[x:x + 1] = lines[x].split('\n')

    # spacing at end of lines:
    for i, line in enumerate(lines):
        if line != line.rstrip():
            lines[i] = line.rstrip()

    leftSpacing = [len(l) - len(l.lstrip()) for l in lines]
    if len(leftSpacing) == 0:
        raise ValueError("splitApartLines, empty grammar: %s" % repr(lines))

    if len(leftSpacing) > 1:
        minLeftSpacing = min(leftSpacing[1:])
    for i, line in enumerate(lines):
        if i == 0:
            if line != line.lstrip():
                lines[i] = line.lstrip()
        else:
            if minLeftSpacing:
                lines[i] = line[minLeftSpacing:]
 def setList(self, listName, words):
     listName = utilsqh.convertToBinary(listName)
     self.emptyList(listName)
     self.appendList(listName, words)  # other way around?
    def gotResults_info(self, words, fullResults):
        """display in a message box information about the window, user or unimacro


        """
        T = []
        extra = []
        if self.hasCommon(words, 'window'):
            m = natlink.getCurrentModule()
            hwnd = m[2]
            p = natqh.getProgInfo(m)
            toporchild = p[2]
            T.append('---from natqh.getProgInfo:')
            T.append('0 program: %s' % p[0])
            T.append('1 window title: %s' % p[1])
            T.append('2 toporchild: %s' % p[2])
            overruleIsTop = self.getTopOrChild()

            T.append('3 window handle: %s' % p[3])
            if toporchild == 'top':
                if not overruleIsTop:
                    T.append(
                        '****** but should be treated as child window according to actions.ini option "top behaves like child"'
                    )
            else:
                if overruleIsTop:
                    T.append(
                        '****** but should be treated as top window according to actions.ini option "top behaves like child"'
                    )
            T.append('')
            T.append('---from getCurrentModule:')
            T.append('0 program path: %s' % m[0])
            T.append('1 window title: %s' % m[1])
            T.append('2 window handle: %s' % m[2])
            T.append('')
            T.append('---from GetClassName:')
            T.append('class name: %s' % win32gui.GetClassName(hwnd))
        elif self.hasCommon(words, 'user'):
            T.append('user:\t\t%s' % natqh.getUser())
            T.append('userLanguage:\t%s' % natqh.getUserLanguage())
            T.append('language:\t%s' % self.language)
            bm = natqh.getBaseModel()
            bt = natqh.getBaseTopic()
            ut = natqh.getUserTopic()
            version = natqh.getDNSVersion()
            if version >= 15:
                T.append('UserTopic (DPI15):\t%s' % ut)
            if natqh.getDNSVersion() >= 15:
                T.append('BaseTopic (pre 15):\t%s' % bt)
            else:
                T.append('BaseTopic (or UserTopic):\t%s' % ut)
            T.append('BaseModel:\t%s' % bm)
            # T.append('see messages window for trainuser info')
            extra = []
            # extra.append(r'cd d:\natlink\miscscripts   (or different folder)')
            # extra.append(r'python trainuser.py d:\natlink\recordings\recordingcode "user name" "%s" "%s"'%\
            #              (bm, bt))
            # extra.append('change folders, recording code and user name of course')

        elif self.hasCommon(words, 'unimacro'):
            version = natqh.getDNSVersion()
            T.append('DNSVersion:\t\t%s  (%s)' % (version, type(version)))
            wVersion = natqh.getWindowsVersion()
            T.append('WindowsVersion:\t\t%s (%s)' % (wVersion, type(wVersion)))
            T.append('UnimacroDirectory:\t%s' % natqh.getUnimacroDirectory())
            T.append('UnimacroUserDirectory:\t%s' %
                     natqh.getUnimacroUserDirectory())
            T.append('DNSuserDirectory:\t%s' % natqh.getDNSuserDirectory())
        elif self.hasCommon(words, 'path'):
            T.append('the python path:')
            T.append(pprint.pformat(sys.path))
        elif self.hasCommon(words, "class"):
            T.append()
        else:
            T.append('no valid keyword found')

        try:
            s = '\n'.join(T)
        except UnicodeDecodeError:
            TT = [utilsqh.convertToBinary(t) for t in T]
            s = '\n'.join(TT)

        actions.Message(s)
        print s
        print
        for e in extra:
            print e
Esempio n. 12
0
 def setList(self, listName, words):
     if type(listName) == six.text_type:
         listName = utilsqh.convertToBinary(listName)
     self.emptyList(listName)
     self.appendList(listName, words)  # other way around?