def test_WriteToFile(self):
        input = "A \"say This test passed\"\nB \"emote Yay!\""
        filePath = "./TestReferences/out.txt" 
        if (path.exists(filePath)):
            remove(filePath)
        target = BindFile(repr=input)
        self.assertEqual(target.FilePath, None, "FilePath set when loading from repr only")
        target.WriteBindsToFile(filePath)
        self.assertEqual(target.FilePath, filePath, "Did not set expected filePath")
        assert(path.exists(filePath))
        file = open(filePath)
        try:
            actual = file.read()
        finally:
            file.close() 
            remove(filePath)
        self.assertEqual(actual, input)

        filePath = "./TestReferences/NewDir/SubDir/out.txt" 
        target.WriteBindsToFile(filePath)
        self.assertEqual(target.FilePath, filePath, "Did not set expected filePath")
        assert(path.exists(filePath))
        file = open(filePath)
        try:
            actual = file.read()
        finally:
            file.close() 
            remove(filePath)
            os.removedirs("./TestReferences/NewDir/SubDir")
        self.assertEqual(actual, input)
 def GetCollection(self, includeUnbound=False):
     if (self.Dictionary == None):
         return None
     keyChains = []
     if (self.Dictionary[KEY_CHAINS] != NONE):
         if includeUnbound:
             chains = self.Dictionary[KEY_CHAINS]
         else:
             chains = [
                 p for p in self.Dictionary[KEY_CHAINS] if p[KEY] != UNBOUND
             ]
         for keyChain in chains:
             boundFiles = [
                 BindFile(repr=p[REPR], filePath=p[PATH])
                 for p in keyChain[BOUND_FILES]
             ]
             newChain = Keychain(key=keyChain[KEY],
                                 chord=keyChain[CHORD],
                                 boundFiles=boundFiles)
             keyChains.append(newChain)
     root = BindFile(filePath=self.Dictionary[PATH],
                     repr=self.Dictionary[ROOT])
     collection = BindFileCollection(filePath=root.FilePath,
                                     bindFile=root,
                                     keyChains=keyChains)
     return collection
    def CommitRepr(self, fileTags):
        editor = self.GetEditor(fileTags[0])
        if (editor == None):
            return
        bindFile = editor.Get()

        updateTree = False
        for fileTag in fileTags:
            chainIndex, fileIndex = self.ParseFileTag(fileTag)
            if (chainIndex < 0):
                oldRepr = self.Dictionary[ROOT]
                self.Dictionary[ROOT] = bindFile.__repr__()
            else:
                oldRepr = self.Dictionary[KEY_CHAINS][chainIndex][BOUND_FILES][
                    fileIndex][REPR]
                self.Dictionary[KEY_CHAINS][chainIndex][BOUND_FILES][
                    fileIndex][REPR] = bindFile.__repr__()

            self.SetEditor(fileTag, editor)

            if (not updateTree):
                #check for change in links
                oldBindFile = BindFile(repr=oldRepr)
                if (str(bindFile.GetLoadedFilePaths()) != str(
                        oldBindFile.GetLoadedFilePaths())):
                    updateTree = True

        if (updateTree):
            self._updateTree()
 def test_Clone(self):
     input = "A \"say This test failed\"\nB \"emote No!\""
     target = BindFile(filePath="keybinds.txt", repr=input)
     actual = target.Clone()
     actual.FilePath = "new_keybinds.text"
     actual.Binds[0].Key = "C"
     actual.Binds[0].Chord = "SHIFT"
     actual.Binds[0].Commands[0].Name = "em"
     actual.Binds[0].Commands[0].Text = "This test passed"
     actual.Binds[1].Key = "D"
     actual.Binds[1].Chord = "ALT"
     actual.Binds[1].Commands[0].Name = "say"
     actual.Binds[1].Commands[0].Text = "Yes!"
     self.assertNotEqual(actual.FilePath, target.FilePath, "FilePath not different")
     self.assertNotEqual(actual.Binds[0].Key, target.Binds[0].Key, "Binds[0].Key not different")
     self.assertNotEqual(actual.Binds[0].Chord, target.Binds[0].Chord, "Binds[0].Chord not different")
     self.assertNotEqual(actual.Binds[0].Commands[0].Name, target.Binds[0].Commands[0].Name, "Binds[0].Command[0].Name not different")
     self.assertNotEqual(actual.Binds[0].Commands[0].Text, target.Binds[0].Commands[0].Text, "Binds[0].Command[0].Text not different")
     self.assertNotEqual(actual.Binds[1].Key, target.Binds[1].Key, "Binds[0].Key not different")
     self.assertNotEqual(actual.Binds[1].Chord, target.Binds[1].Chord, "Binds[0].Chord not different")
     self.assertNotEqual(actual.Binds[1].Commands[0].Name, target.Binds[1].Commands[0].Name, "Binds[0].Command[0].Name not different")
     self.assertNotEqual(actual.Binds[1].Commands[0].Text, target.Binds[1].Commands[0].Text, "Binds[0].Command[0].Text not different")
     self.assertEqual(actual.FilePath, "new_keybinds.text", "FilePath not different")
     self.assertEqual(actual.Binds[0].Key, "C", "Binds[0].Key not different")
     self.assertEqual(actual.Binds[0].Chord, "SHIFT", "Binds[0].Chord not different")
     self.assertEqual(actual.Binds[0].Commands[0].Name, "em", "Binds[0].Command[0].Name not different")
     self.assertEqual(actual.Binds[0].Commands[0].Text, "This test passed", "Binds[0].Command[0].Text not different")
     self.assertEqual(actual.Binds[1].Key, "D", "Binds[0].Key not different")
     self.assertEqual(actual.Binds[1].Chord, "ALT", "Binds[0].Chord not different")
     self.assertEqual(actual.Binds[1].Commands[0].Name, "say", "Binds[0].Command[0].Name not different")
     self.assertEqual(actual.Binds[1].Commands[0].Text, "Yes!", "Binds[0].Command[0].Text not different")
Exemplo n.º 5
0
 def Parse(self, repr: str):
     keychainDict = ast.literal_eval(repr)
     self.parserBind = Bind(key=keychainDict[KEY], chord=keychainDict[CHORD])
     self.Key = self.parserBind.GetDefaultedKeyName()
     self.Chord = self.parserBind.GetDefaultedChordName()
     boundFilesRepr = keychainDict[BOUND_FILES]
     if boundFilesRepr == NONE:
         boundFiles = None
     else:
         boundFiles = []
         for boundFileEntry in boundFilesRepr:
             boundFile = BindFile(repr=boundFileEntry[REPR])
             boundFile.FilePath = boundFileEntry[PATH]
             boundFiles.append(boundFile)
     self.BoundFiles = boundFiles
    def _onSelectCallback(self, binds, *args):

        editor = self.Notebook.SelectedFrame().editor
        bindFilePath = editor.FilePath
        options = {}
        options['initialfile'] = "keybinds.kst"
        options['title'] = "Select File Destination"
        options['filetypes'] = (("Keybind Export Files", "*.kst"),
                                ("All Files", "*.*"))
        options['defaultextension'] = "kst"
        self.update()
        filePath = filedialog.asksaveasfilename(**options)
        self.update()
        if (filePath == ''):
            return False

        bindFile = BindFile(binds, filePath=bindFilePath)
        boundFilesSource = self._getBoundFilesSource()
        bindFileCollection = BindFileCollection()
        bindFileCollection.Load(bindFilePath,
                                bindFile=bindFile,
                                boundFilesSource=boundFilesSource)
        bindFileCollection.Serialize(filePath)

        return True
Exemplo n.º 7
0
 def Get(self) -> BindFile:
     binds = None
     if (self.view.Items != None):
         binds = [
             bind for bind in [item.Item.Get() for item in self.view.Items]
             if bind.Commands != None
         ]
     return BindFile(binds=binds, filePath=self.FilePath)
Exemplo n.º 8
0
 def Newlink(self, filePath) -> Keylink:
     filePath = os.path.abspath(filePath)
     #create load command
     loadCommand = SlashCommand(name=LOAD_FILE_COMMANDS[0],
                                text="\"%s\"" % filePath)
     loadBind = Bind(self.Key, self.Chord, [loadCommand])
     #create new bind file
     bindFile = BindFile(binds=[loadBind], filePath=filePath)
     return Keylink(bindFile, self.Key, self.Chord)
 def test_FromString(self):
     input = "A \"say This test passed\"\nB \"emote Yay!\""
     target = BindFile(repr=input)
     actual = len(target.Binds)
     self.assertEqual(actual, 2, "Did not find expected bind count")
     actual = str(target.Binds[0])
     expected = str(Bind(key="A", commands=[SlashCommand("say","This test passed")]))
     self.assertEqual(actual, expected, "Did not find expected 1st bind")
     actual = str(target.Binds[1])
     expected = str(Bind(key="B", commands=[SlashCommand("emote","Yay!")]))
     self.assertEqual(actual, expected, "Did not find expected 2nd bind")
 def Get(self, fileTag) -> BindFile:
     chainIndex, fileIndex = self.ParseFileTag(fileTag)
     if (chainIndex < 0):
         filePath = self.Dictionary[PATH]
         _repr = self.Dictionary[ROOT]
     else:
         filePath = self.Dictionary[KEY_CHAINS][chainIndex][BOUND_FILES][
             fileIndex][PATH]
         _repr = self.Dictionary[KEY_CHAINS][chainIndex][BOUND_FILES][
             fileIndex][REPR]
     return BindFile(repr=_repr, filePath=filePath)
 def test_Keychain(self):
     key = "MOUSECHORD"
     chord = "SHIFT"
     file1 = BindFile(repr="SHIFT+MOUSECHORD bind_load_file \"MOUSECHORD2.txt\"", filePath="MOUSECHORD1.txt")
     file2 = BindFile(repr="SHIFT+MOUSECHORD bind_load_file \"MOUSECHORD1.txt\"", filePath="MOUSECHORD2.txt")
     target = Keychain(key=key, chord=chord, boundFiles=[file1, file2])
     actual = target.__repr__()
     expected = '{\'key\': \'MOUSECHORD\', \'chord\': \'SHIFT\', \'bound_files\': [{\'path\': \'MOUSECHORD1.txt\', \'repr\': \'SHIFT+MOUSECHORD "bind_load_file "MOUSECHORD2.txt""\'}, {\'path\': \'MOUSECHORD2.txt\', \'repr\': \'SHIFT+MOUSECHORD "bind_load_file "MOUSECHORD1.txt""\'}]}'
     self.assertEqual(actual, expected)
     expected2 = expected.replace('MOUSECHORD', 'NUMPAD0', 1)
     expected2 = expected.replace('SHIFT', '', 1)
     target = Keychain(repr=expected2)
     actual = target.__repr__()
     self.assertEqual(actual, expected2)
     clone = target.Clone()
     clone.Key = 'MOUSECHORD'
     clone.Chord = 'SHIFT'
     actual = clone.__repr__()
     self.assertEqual(actual, expected)
     actual = target.__repr__()
     self.assertEqual(actual, expected2)
 def LoadDictionary(self, data, serialization = False):
     if serialization:
         self.FilePath = "C:\\keybinds.txt"
     else:
         path = data[PATH]
         if path == NEW_FILE:
             self.FilePath = None
         else:
             self.FilePath = data[PATH]
     description = data[DESCRIPTION]
     if (description == NONE):
         self.Description = None
     else:
         self.Description = description
     self.File = BindFile(repr=data[ROOT])
     self.File.FilePath = self.FilePath
     keyChains = data[KEY_CHAINS]
     if (keyChains == NONE):
         self.KeyChains = None
     else:
         self.KeyChains = []
         for entry in keyChains:
             self.KeyChains.append(Keychain(repr=entry.__repr__()))
def GetKeyChains(bindFile: BindFile, path: str, boundFiles = None):

    result = []   

    if (path == None):
        path = ""
    else:
        path = ComparableFilePath(path) 
    for bind in bindFile.GetLoadFileBinds():
        chainFiles = getBoundFiles(path, bind, [], boundFiles)
        if (len(chainFiles) > 0):
            result.append(Keychain(key=bind.Key, chord=bind.Chord, boundFiles=chainFiles))

    if (len(result) == 0):
        result = None

    return result
 def test_GetBindForKey(self):
     expected_2 = "2 \"powexec_slot 2\""
     expected_CTRL_2 = "CTRL+2 \"powexec_alt2slot 2\""
     expected_SHIFT_2 = "SHIFT+2 \"team_select 2\""
     expected_Alt_Names = "shift+period \"em this test passed\""
     input = "%s\n%s\n%s\n%s\n" % (expected_2, expected_CTRL_2, expected_SHIFT_2, expected_Alt_Names)
     target = BindFile(repr=input)
     actual = target.GetBindForKey(key = "2")
     self.assertEqual(1, len(actual))
     self.assertEqual(expected_2, str(actual[0]))
     actual = target.GetBindForKey(key = "2", chord="CTRL")
     self.assertEqual(1, len(actual))
     self.assertEqual(expected_CTRL_2, str(actual[0]))
     actual = target.GetBindForKey(key = "2", chord="SHIFT")
     self.assertEqual(1, len(actual))
     self.assertEqual(expected_SHIFT_2, str(actual[0]))
     actual = target.GetBindForKey(key = "A")
     self.assertEqual(0, len(actual))
     actual = target.GetBindForKey(key=".", chord="SHIFT")
     self.assertEqual(1, len(actual))
     self.assertEqual(expected_Alt_Names, str(actual[0]))
class BindFileCollection():

    def Load(self, filePath: str, bindFile = None, boundFilesSource = None):
        self.FilePath = filePath
        if (bindFile == None):
            bindFile = ReadBindsFromFile(filePath)
        self.File = bindFile
        if ((boundFilesSource != None) and (len(boundFilesSource) == 0)):
            boundFilesSource = None
        self.KeyChains = GetKeyChains(self.File, filePath, boundFilesSource)

    def New(self, defaults: bool = False):
            self.FilePath = None
            self.File = NewBindFile(defaults)

    def GetBoundFiles(self):
        result = []
        if self.KeyChains == None:
            return result
        for keyChain in self.KeyChains:
            if keyChain.BoundFiles == None:
                continue
            for boundFile in keyChain.BoundFiles:
                result.append(boundFile)
        return result

    def Serialize(self, filePath):
        clone = self.Clone()
        clone.RepointFilePaths("C:\\keybinds.txt", True)
        file_dict = clone.GetDictionary()
        with open(filePath, "w+") as json_file:
            json.dump(file_dict, json_file)

    def Deserialize(self, filePath):
        with open(filePath, "r") as json_file:
            data = json.load(json_file)
        self.LoadDictionary(data, serialization = True)

    def RepointFilePaths(self, newFilePath: str, overwrite: bool = False):

        if (newFilePath == None):
            self.FilePath = None
            self.File.FilePath = None

            boundFiles = self.GetBoundFiles()
            for boundFile in boundFiles:
                boundFile.FilePath = None

            return

        if (self.File.FilePath == None):
            return
        currentFilePath = os.path.abspath(self.File.FilePath)
        currentDirectory = os.path.dirname(currentFilePath)
        newFilePath = os.path.abspath(newFilePath)
        self.FilePath = newFilePath
        if (ComparableFilePath(currentFilePath) == ComparableFilePath(newFilePath)):
            return
        newDirectory = os.path.dirname(newFilePath)

        self.File.RepointFilePaths(newFilePath, overwrite)

        boundFiles = self.GetBoundFiles()
        for boundFile in boundFiles:
            newFilePath = os.path.join(newDirectory, GetDirPathFromRoot(currentDirectory, boundFile.FilePath))
            if ((not overwrite) and (os.path.exists(newFilePath))):
                newFilePath = GetUniqueFilePath(newFilePath)
            boundFile.RepointFilePaths(newFilePath, overwrite)

    def Save(self, filePath: str = None, overwrite: bool = False):
        if (filePath == None):
            filePath = self.File.FilePath
        currentFilePath = self.File.FilePath

        if (filePath != currentFilePath):
            self.RepointFilePaths(filePath, overwrite)

        self.File.WriteBindsToFile(filePath)

        boundFiles = self.GetBoundFiles()
        for boundFile in boundFiles:
            boundFile.WriteBindsToFile()


    def __init__(self, filePath: str = '', bindFile: BindFile = None, keyChains:[Keychain] = None, description = None, repr=''):

        if (repr != ''):
            self.Parse(repr)
        else:
            self.FilePath = filePath
            self.File = bindFile
            self.KeyChains = keyChains
            self.Description = description

    #Dictionary structure
    #PATH - File Path
    #DESCRIPTION - Description for import and export files
    #ROOT - repr string of root bind file
    #KEY_CHAINS - array bound file chain dictionaries, NONE is empty    
        #KEY - Key for bind in root file
        #CHORD - Chord for bind in root file
        #BOUND_FILES- Array of dictionaries for bound files
            #PATH - Path from load command
            #REPR - repr string of loaded bind file

    def LoadDictionary(self, data, serialization = False):
        if serialization:
            self.FilePath = "C:\\keybinds.txt"
        else:
            path = data[PATH]
            if path == NEW_FILE:
                self.FilePath = None
            else:
                self.FilePath = data[PATH]
        description = data[DESCRIPTION]
        if (description == NONE):
            self.Description = None
        else:
            self.Description = description
        self.File = BindFile(repr=data[ROOT])
        self.File.FilePath = self.FilePath
        keyChains = data[KEY_CHAINS]
        if (keyChains == NONE):
            self.KeyChains = None
        else:
            self.KeyChains = []
            for entry in keyChains:
                self.KeyChains.append(Keychain(repr=entry.__repr__()))

    def GetDictionary(self):
        data = {}
        if self.FilePath == None:
            data[PATH] = NEW_FILE
        else:
            data[PATH] = self.FilePath
        if self.Description == None:
            data[DESCRIPTION] = None
        else:
            data[DESCRIPTION] = self.Description
        data[ROOT] = self.File.__repr__()
        if self.KeyChains == None:
            data[KEY_CHAINS] = NONE
        else:
            keyChains = []
            for keyChain in self.KeyChains:
                chain_dict = keyChain.GetDictionary()
                keyChains.append(chain_dict)
            data[KEY_CHAINS] = keyChains
        return data

    def Parse(self, repr: str):
        data = ast.literal_eval(repr)
        self.LoadDictionary(data)

    def __repr__(self)->str:
        return self.GetDictionary().__repr__()

    def Clone(self):
        return BindFileCollection(repr=self.__repr__())
 def New(self, defaults: bool = False):
         self.FilePath = None
         self.File = NewBindFile(defaults)
 def test__repr__(self):
     expected = "A \"say This test passed\"\nB \"emote Yay!\""
     binds = [Bind(key="A", commands=[SlashCommand("say", "This test passed")]), Bind(key="B", commands=[SlashCommand("emote", "Yay!")])]
     target = BindFile(binds)
     actual = str(target)
     self.assertEqual(actual, expected)