Exemplo n.º 1
0
def changeListName(self, listwidget):
    """
    Used to change the name of a list and the folder it creates
    Returns True if the name has been changed successfully

    :param self: SettingsWindow
    :param listwidget: int
    :return: bool
    """

    if listwidget == 0:  # List Right
        savestate.NewListName = (self.ui.rlistname.text(), 0)
        print("Changing name of the right list to " + self.ui.rlistname.text())
        logWrite("Changing name of the right list to " +
                 self.ui.rlistname.text())
    elif listwidget == 1:  # List Left
        savestate.NewListName = (self.ui.llistname.text(), 1)
        print("Changing name of the left list to " + self.ui.llistname.text())
        logWrite("Changing name of the left list to " +
                 self.ui.llistname.text())
    savestate.saveLists["Left"].setToolTip(
        savestate.configList["LeftListName"])
    savestate.saveLists["Right"].setToolTip(
        savestate.configList["RightListName"])
    updateSettings()
    initTextFiles("initFolders")
    updateLists()
Exemplo n.º 2
0
def loadTexts():
    success = []
    for element in savestate.lineedit_list:
        try:
            savestate.lineedit_list[element].setText(
                savestate.txtlist[element])
            success.append(True)
        except KeyError as e:
            logWrite("Error occurred while loading texts from the savestate!")
            print(str(e) + " not found!")
            success.append(False)
        except AttributeError:
            # This should happen if there is no lineedit ( SpinBox for score )
            try:
                savestate.lineedit_list[element].setValue(
                    int(savestate.txtlist[element]))
            except KeyError as e:
                logWrite(
                    "Error occurred while loading texts from the savestate!")
                print(str(e) + " not found!")
            except ValueError:
                # Happens when the program is opened up the first time
                pass
    if False in success:
        print("The autosave seems to be incomplete or corrupted")
Exemplo n.º 3
0
def deleteFromItem(name):
    lkey = 0
    rkey = 0
    newlistright = {}
    newlistleft = {}
    print("Trying to delete: ", name)
    logWrite("Trying to delete: " + name)
    for item in savestate.saveListData["Left"]:
        if savestate.saveListData["Left"][item]["itemData"]["name"] != name:
            newlistleft[lkey] = savestate.saveListData["Left"][item]
            print(newlistleft[lkey])
            savestate.saveListItems["Left"][lkey] = savestate.saveListItems["Left"][item]
            lkey += 1
    for item in savestate.saveListData["Right"]:
        if savestate.saveListData["Right"][item]["itemData"]["name"] != name:
            newlistright[rkey] = savestate.saveListData["Right"][item]
            savestate.saveListItems["Right"][rkey] = savestate.saveListItems["Right"][item]
            rkey += 1
    savestate.saveListData.pop("Left", None)
    savestate.saveListData.pop("Right", None)
    savestate.saveListData["Left"] = newlistleft
    savestate.saveListData["Right"] = newlistright

    # print(savestate.saveListData)
    updateLists()
Exemplo n.º 4
0
def updateSettings():
    try:
        file = open(savestate.standardFilePath + savestate.symbol + "config.json", "w+", encoding="utf-8")
        output = json.dumps(savestate.configList, sort_keys=True, indent=4)
        file.write(output)
        file.close()
    except FileNotFoundError:
        logWrite("No config file could be found!")
        print("No config file found! Restart the program. If this error persists, please contact the developer.")
Exemplo n.º 5
0
def saveCurrentState():
    """
    Saves the lists to the autosave file

    :return: None
    """
    logWrite("Saving contents to the autosave...")
    thisSave = {"txtlist": savestate.txtlist, "morelist": savestate.morelist}
    writeToAutosave("eSports", thisSave)
Exemplo n.º 6
0
def readSettings():
    # This method reads the settings from the file on startup and writes them to the dict in savestate
    try:
        file = open(savestate.standardFilePath + savestate.symbol + "config.json", "r", encoding="utf-8")
        json_object = json.loads(file.read())
        savestate.configList = json_object
        file.close()
    except FileNotFoundError:
        print("No config file found! Restart the program. If this error persists, please contact the developer.")
        logWrite("No config file has been found!")
Exemplo n.º 7
0
def setHomeTeam(where):
    """
    This method is used to set a teams (determined by "where") city and name to the home teams'

    :param where: int
    :return: None
    """
    logWrite("Setting the home team to team " + str(where))
    savestate.lineedit_list["T" + str(where) + "_name"].setText(savestate.lineedit_list["HT_name"].text())
    savestate.lineedit_list["T" + str(where) + "_city"].setText(savestate.lineedit_list["HT_city"].text())
    editTxts("all")
Exemplo n.º 8
0
def information(text):
    logWrite("Information: " + text)
    w = QMessageBox()
    w.setText(text)
    w.setIcon(QMessageBox.Information)
    w.setStandardButtons(QMessageBox.Ok)
    w.setWindowTitle("Information")

    retval = w.exec_()
    # print("text", retval)
    return retval
Exemplo n.º 9
0
def resetSettings(self):
    """
    Used to reset the settings to standard values

    :param self: SettingsWindow
    :return: None
    """
    logWrite("Trying to reset the setting to standard...")
    savestate.configList = savestate.standardConfigList
    updateSettings()
    self.ui.infoReset.show()
Exemplo n.º 10
0
def loadConfig(self, basefilepath):
    # Loads a save file
    logWrite("Trying to load a config, waiting on user...")
    information("Loading a config file will delete all current contents!")
    file, ok = QFileDialog.getOpenFileName(self, "Open Save", basefilepath,
                                           "*.oi")
    if ok:
        logWrite("Loading config file...")
        # print(str(file))
        deleteAllItems()
        print("Opening file from: " + str(file))
        createListFiles(str(file))
Exemplo n.º 11
0
def initJSONFiles(path):
    logWrite("Initializing standard files...")
    for file in standardXMLNames:
        print("Opening files at " + path + savestate.symbol + file + ".json")
        data = open(path + savestate.symbol + file + ".json", "w+")
        if file == "config":
            arr = json.dumps(savestate.configList, indent=4)
            data.write(arr)
            data.close()
        if file == "autosave":
            arr = json.dumps(savestate.autosave_standard, indent=4)
            data.write(arr)
            data.close()
Exemplo n.º 12
0
def activateFolderSplitting(checkbox):
    """
    Used to create a folder for each list if the setting is changed while in the program

    :type checkbox: QCheckBox
    :return: None
    """
    savestate.configList["ListSplit"] = checkbox.isChecked()
    logWrite("List split has been set to: " +
             str(savestate.configList["ListSplit"]))
    updateSettings()
    createStandardFiles(1)
    initTextFiles("initFolders")
    updateLists()
Exemplo n.º 13
0
def autoUpdateFiles(self):
    """
    Enables Auto-Updating of the textfiles. This means, that when the cursor focus on the lineedit within a list item
    is lost, the textfile updates automatically without user interaction

    :param self: SettingsWindow
    :return: None
    """
    print("Auto updating files is set to ",
          str(self.ui.AutoUpdate.isChecked()))
    savestate.configList["AutoUpdateFiles"] = self.ui.AutoUpdate.isChecked()
    logWrite("Auto-Updating has been set to: " +
             str(savestate.configList["AutoUpdateFiles"]))
    updateSettings()
    updateLists()
Exemplo n.º 14
0
def erroreasy(text: str, errorcode: hex):
    """
    Used to create an error dialog, usually for smaller errors
    :param text: str
    :param errorcode: hex
    :return: None
    """
    w = QMessageBox()
    w.setText(text)
    w.setIcon(QMessageBox.Information)
    w.setStandardButtons(QMessageBox.Ok)
    w.setWindowTitle("Error")

    retval = w.exec_()
    print(text, retval, errorcode)
    logWrite(text + ", " + str(retval) + ", " + str(errorcode))
Exemplo n.º 15
0
def writeToAutosave(name, write):
    templist = savestate.autosave_standard
    try:
        templist = readAutosave()
        # print("Got ", templist)
    except JSONDecodeError:
        logWrite("Saving to autosave failed because the json could not be decoded!")
        print("There was a problem decoding the JSON. Please resort to a backup or try to fix it manually!")

    autosave = open(savestate.standardFilePath + savestate.symbol + "autosave.json", "w+", encoding="utf-8")

    templist[name] = write
    # print("Data saved without key!")

    autosave.write(json.dumps(templist, indent=4))
    autosave.close()
Exemplo n.º 16
0
def changeTextPath(self):
    """
    This method changes the textfilepath used around the program

    :param self: SettingsWindow
    :return: None
    """
    logWrite("Trying to change the text path...")
    directory = QFileDialog.getExistingDirectory(
        self, "Change text file path", savestate.configList["CustomFilePath"],
        QFileDialog.DontResolveSymlinks)
    logWrite("The given path is: " + directory)
    if ":" or "/" in directory:
        emptyDir(savestate.configList["CustomFilePath"] + savestate.symbol +
                 "textfiles")
        self.ui.TextFilePath.setText(directory)
        savestate.configList["CustomFilePath"] = directory
        print("Filepath changed to: " + directory)
        createStandardFiles(1)
        updateSettings()
        updateLists()
        initTextFiles("initFolders")
    else:
        logWrite("The path is not valid!")
        erroreasy("Please give a valid filepath!", 0x0304)
Exemplo n.º 17
0
def readAutosave(*filterkey):
    """
    This method is globally used to get data from the autosave

    :type filterkey: str
    :return: dict
    """
    if savestate.AUTOSAVE_LOG_LEVEL_OUTPUT == 4:
        logWrite("Parsing autosave...")
        savestate.AUTOSAVE_LOG_LEVEL_OUTPUT -= 1
    else:
        if savestate.AUTOSAVE_LOG_LEVEL_OUTPUT == 0:
            savestate.AUTOSAVE_LOG_LEVEL_OUTPUT = 4
        else:
            savestate.AUTOSAVE_LOG_LEVEL_OUTPUT -= 1
    try:
        with open(savestate.standardFilePath + savestate.symbol + "autosave.json", "r", encoding="utf-8") as autosave:
            json_object = json.loads(autosave.read())
            autosave.close()
            if filterkey:
                try:
                    print("Seaching for key:", filterkey[0])
                    return json_object[filterkey[0]]
                except KeyError:
                    return json_object
                except TypeError:
                    print("Type error occurred while processing" + filterkey[0], json_object)
            else:
                if json_object:
                    return json_object
                else:
                    return savestate.autosave_standard
    except FileNotFoundError:
        print("Autosave not found. Try restarting the program. Continuing for now...")
        logWrite("Autosave not found. This is not a critical error and a new one will be created...")
        return savestate.autosave_standard
Exemplo n.º 18
0
def saveConfig(self, basefilepath):
    """
    saves the current lists and eSports contents to a separate file

    :param self: SettingsWindow
    :param basefilepath: str
    :return: None
    """
    logWrite("Trying to save config, waiting on user...")
    filepath, ok = QFileDialog.getSaveFileName(self, "Create Save",
                                               basefilepath, ".oi")
    if ok:
        logWrite("Saving config...")
        file = str(filepath + ".oi")
        try:
            shutil.copy(
                str(savestate.standardFilePath + savestate.symbol +
                    "autosave.json"), file)
        except FileNotFoundError:
            information("Saving failed, please restart the program!")
            logWrite("Saving failed, please restart the program!")
        print("Exported save to: " + file)
Exemplo n.º 19
0
    def __init__(self):
        super().__init__()

        # set a window icon and show the early access info

        self.setWindowIcon(QIcon("images" + savestate.symbol + "icon.png"))

        # Check if the folder exists
        if savestate.platform == "linux":
            try:
                print("Trying to create the standard Folder under linux...")
                os.mkdir(savestate.home + "/Documents/StreamHelper")
            except FileExistsError:
                print("Folder exists!")
        else:
            try:
                print("Trying to create the standard Folder under windows...")
                os.mkdir(os.getenv('LOCALAPPDATA') + "\\StreamHelper")
            except FileExistsError:
                print("Folder exists!")

        # Lets create all the standard files (json and txt) or at least check if they exist
        createStandardFiles(0)

        # init a logfile
        logCreate()
        logWrite(
            "The Program is in developement! \n"
            "Currently, only the textfiles and numbers are working, the other stuff is WIP."
            "Masks aren't importable yet \n")
        information("The Program is in developement! \n"
                    "Please mind the changelog and updates.")

        # Parse the paths from the xml files so we know where to check for the files
        try:
            readSettings()
            print(savestate.configList)
        except FileNotFoundError:
            print(
                "The config file has not been created yet. Proceeding with standard settings..."
            )
            logWrite(
                "The config file has not been created yet. Proceeding with standard settings..."
            )
        except JSONDecodeError:
            print(
                "There was an error reading the config file! Please try restarting the program. \n"
                "If this error persists, consider reinstalling or contacting the developer."
            )
            logWrite(
                "There was an error reading the config file! Please try restarting the program. \n"
                "If this error persists, consider reinstalling or contacting the developer."
                "Using Standard Values for now.")
        oldFilePath = savestate.standardFilePath
        newFilePath = savestate.configList["CustomFilePath"]

        # Set the read filepath so we got it internally to work with
        # savestate.standardFilePath = newFilePath

        # Create the timer
        savestate.timer = QTimer()
        savestate.timer.setInterval(1000)
        savestate.timer.start()

        # Tell the log whats up
        print("Loading config data")
        print("Standard file path is ", oldFilePath,
              "\n" + "Custom file path is ",
              savestate.configList["CustomFilePath"])
        logWrite("Loading config data")
        logWrite(
            str(("Standard file path is: " + oldFilePath +
                 "   Custom file path is " +
                 savestate.configList["CustomFilePath"])))
        # Make it work

        # Basic loading and startup operations
        window = txlinit(self)

        # Connect the extra window
        savestate.ExtraFieldWidget = eSportsExtensionWidget(self)
        # initConnection(self)

        # Detect the interactions / NOW HANDLED IN DESIGNATED PACKAGES
        # There are only the menu-items binded here in the main package

        # This will be deprecated soon, moved to settings
        # window.actionSetMainFilePath.triggered.connect(lambda: setFilePath(self, newFilePath))
        # Show the documentation (links to online though)
        window.actionStreamHelperDocumentation.triggered.connect(
            lambda: webbrowser.open(
                "https://github.com/xFLLSquadronNorden/StreamHelper.py"))
        # Save and Load configs from files
        window.actionSave.triggered.connect(
            lambda: saveConfig(self, newFilePath))
        window.actionLoad.triggered.connect(
            lambda: loadConfig(self, newFilePath))
        # Quit the application
        window.actionQuit.triggered.connect(lambda: sys.exit(0))

        window.actionLog.triggered.connect(lambda: webbrowser.open(
            standardFilePath + savestate.symbol + "StreamLog.log"))
        # Show the new version Changes
        window.actionVersion_Changes.triggered.connect(
            lambda: webbrowser.open("CHANGELOG.txt"))

        # Load and save settings
        window.actionMain_Settings.triggered.connect(showSettings)

        # Show the bonus Tool
        window.actionPackage_Installer.triggered.connect(
            lambda: showPackageInstaller(self))
Exemplo n.º 20
0
def initTextFiles(access_token: str, *args):
    """
    !!! Another one of the "simplifications" !!!

    centralizes textfile creating and editing and other stuff like initializing all the files

    Error codes are:
        0 = Everything went smoothly, no errors

        1 = There was an Error somewhere (gets printed), the textfile could be created though

        2 = There was an Error somewhere (gets printed) and the file could NOT be created

        3 = Critical Failure, the function could not execute (either gets printed or the program dies)

    ARGS ARE REQUIRED FOR THESE OPERATIONS: "createFolder", "createFile", "deleteFile" \n
        Creating a folder:  arg = [String mode, String name, optional: String parentFolder]

        Creating a file:    arg = [String mode, String name, String text, optional: String parentFolder]

        Deleting a file:    arg = [String mode, String name, optional: String parentFolder]

        \nmode can be seen as where you want the file/folder to be. E.g.: mode="eSports" adds "eSports" to path
    There is no need to go deeper than two levels in this folder structure - yet

    :param access_token: String
    :return: int
    """
    error_code = 0
    if access_token == "initFolders":
        logWrite("Initializing Folders...")
        # Folder creation: Which folders need to be created?
        folder_list_esports = savestate.folderlist
        folder_list = savestate.standardDirNames

        # Where do they need to be created?
        folder_path = savestate.configList["CustomFilePath"] + s + "textfiles"

        # Check if they exist already and create them if they don't
        for folder in folder_list:
            path_to_folder = str(folder_path + s + folder)
            if not os.path.exists(path_to_folder):
                try:
                    os.mkdir(path_to_folder)
                except FileNotFoundError:
                    erroreasy(
                        "The path directory could not be found. It has been reset...",
                        0x0310)
                    savestate.configList[
                        "CustomFilePath"] = savestate.standardFilePath
            else:
                print("Directory already exists: " + folder)

        # Do the same for the subfolders
        try:
            for folder in folder_list_esports:
                path_to_folder = str(folder_path + s + "eSports" + s + folder)
                if not os.path.exists(path_to_folder):
                    os.mkdir(path_to_folder)
                else:
                    print("Directory already exists: " + folder)
        except FileNotFoundError:
            print("The folder \" eSports \" does not exist!")
            logWrite("The folder \"eSports\" does not exist!")
            return 2

        # Check for list split argument and delete the old folder
        if savestate.configList["ListSplit"]:
            logWrite("Creating split folders...")
            path_to_list_folder = ["left", "right"]
            if len(savestate.NewListName) >= 1:
                if savestate.NewListName[1] == 1:
                    print("Deleting old left folder and creating new one...")
                    emptyDir(folder_path + s + "Lists" + s +
                             savestate.configList["LeftListName"])
                    savestate.configList[
                        "LeftListName"] = savestate.NewListName[0]
                elif savestate.NewListName[1] == 0:
                    print("Deleting old right folder and creating new one...")
                    emptyDir(folder_path + s + "Lists" + s +
                             savestate.configList["RightListName"])
                    savestate.configList[
                        "RightListName"] = savestate.NewListName[0]
                else:
                    # if there was no other folder before the change
                    pass

            path_to_list_folder[0] = str(folder_path + s + "Lists" + s +
                                         savestate.configList["LeftListName"])
            path_to_list_folder[1] = str(folder_path + s + "Lists" + s +
                                         savestate.configList["RightListName"])
            for folder in path_to_list_folder:
                if not os.path.exists(folder):
                    try:
                        os.makedirs(folder)
                    except FileNotFoundError as e:
                        print(e)
                else:
                    print("List-splitting enabled and folder found: " + folder)
                for filename in os.listdir(folder):
                    file_path = os.path.join(folder, filename)
                    print("Trying to delete: ", file_path)
                    try:
                        if os.path.isfile(file_path) or os.path.islink(
                                file_path):
                            os.unlink(file_path)
                        elif os.path.isdir(file_path):
                            shutil.rmtree(file_path)
                    except Exception as e:
                        print('Failed to delete %s. Reason: %s' %
                              (file_path, e))
                        logWrite(
                            str('Failed to delete %s. Reason: %s' %
                                (file_path, e)))
                        return 2

        # We need to make sure that the List folder(s) are empty because otherwise there will be leftovers
        folder = folder_path + s + "Lists"
        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                if os.path.isdir(
                        file_path) and not savestate.configList["ListSplit"]:
                    shutil.rmtree(file_path)
            except Exception as e:
                print('Failed to delete %s. Reason: %s' % (file_path, e))
                logWrite(
                    str('Failed to delete %s. Reason: %s' % (file_path, e)))

        # Create the basic textfiles needed for operation
        createListFiles()

    if access_token == "createFolder":
        logWrite("Creating a new folder...")
        if len(args) > 2:
            os.mkdir(savestate.configList["CustomFilePath"] + s + args[0] + s +
                     args[2] + s + args[1])
            return 0
        else:
            os.mkdir(savestate.configList["CustomFilePath"] + s + args[0] + s +
                     args[1])
            return 0

    if access_token == "createFile":
        args = args[0]
        # print(args)
        # print(savestate.configList["ListSplit"])
        # logWrite("Creating a new file with name " + args[1] + "...")
        if args[0] == "Lists":
            if savestate.configList[
                    "ListSplit"]:  # This will give a special thingy to the parent folder
                file_path: str = str(savestate.configList["CustomFilePath"] +
                                     s + "textfiles" + s + args[0] + s +
                                     args[3] + s + args[1] + ".txt")

            else:
                file_path: str = str(savestate.configList["CustomFilePath"] +
                                     s + "textfiles" + s + args[0] + s +
                                     args[1] + ".txt")
        else:
            if len(args) == 3:
                # No parent given
                file_path: str = str(savestate.configList["CustomFilePath"] +
                                     s + "textfiles" + s + args[0] + s +
                                     args[1] + ".txt")
            else:
                # Parent given
                file_path: str = str(savestate.configList["CustomFilePath"] +
                                     s + "textfiles" + s + args[0] + s +
                                     args[3] + s + args[1] + ".txt")

        # print("Creating a file here: ", file_path)
        try:
            with open(file_path, "w+", encoding="utf-8") as f:
                f.write(args[2])
        except FileNotFoundError:
            print("The folders have been deleted! Rebuilding them...")
            logWrite(
                "The folders have been deleted while running! Rebuilding them..."
            )
            initTextFiles("initFolders")
    return error_code
Exemplo n.º 21
0
def createListFiles(*load: str):
    """
    This method recreates the list files from the autosave.json file or a savefile

    :param load: str
    :return: None
    """
    loadFileCheck = ""
    if load is not None:
        loadFileCheck = load

    print("Trying to open the savefile...")
    logWrite("Trying to open the savefile...")

    # Lets look in the json so we know what was up
    try:
        # print(savestate.standardFilePath)
        if len(loadFileCheck) > 0:
            print("Fetching save file from: ", load)
            logWrite("Fetching save file from: " + str(load))
            json_object = json.loads(
                open(load[0], "r", encoding="utf-8").read())
        else:
            json_object = readAutosave()

        # After parsing we need to get the values for each field. Then we put it in the list.
        # Make sure that every ChronoItem is turned off

        # Lists
        for key in json_object["Lists"]["Left"]:
            savestate.saveListData["Left"][int(
                key)] = json_object["Lists"]["Left"][key]
            if "chronotype" in savestate.saveListData["Left"][int(
                    key)]["itemData"]:
                savestate.saveListData["Left"][int(
                    key)]["itemData"]["running"] = False
        for key in json_object["Lists"]["Right"]:
            savestate.saveListData["Right"][int(
                key)] = json_object["Lists"]["Right"][key]
            if "chronotype" in savestate.saveListData["Right"][int(
                    key)]["itemData"]:
                savestate.saveListData["Right"][int(
                    key)]["itemData"]["running"] = False

        # eSports

        # check if this is a valid list
        success = True
        # print("json object = ", json_object["eSports"])
        # print("txtlist = ", savestate.txtlist)
        for key in savestate.txtlist:
            if key not in json_object["eSports"]["txtlist"]:
                print("The autosave does not contain: " + key,
                      ". Stopped loading!")
                logWrite("The autosave does not contain: " + key +
                         ". Stopped loading!")
                success = False
                break
        if success:
            # Save it to the savestate
            savestate.txtlist = json_object["eSports"]["txtlist"]
            # print(savestate.txtlist)
            loadTexts()
            editTxts("all")
    except FileNotFoundError:
        print("No autosave.json file found! Please restart the program")
        logWrite("Autosave missing! Please restart the program!")
    except JSONDecodeError:
        print("Not able to decode the file! JSON Decode Error thrown!")
        logWrite(
            "Autosave not readable in instance \"createListFiles\"! This error should never occur!"
        )
        erroreasy(
            "There was an error reading the old savefile! Please try to recover it or resort to a backup",
            0x0103)

    # last but not least, update every item and create the new files
    getTextOfItem()
    # print(savestate.saveListData)
    from resources.runtime.textlists.program import updateLists
    updateLists()
Exemplo n.º 22
0
def getTextOfItem():
    """
    This method will update every item (if it exists), creates them otherwise, then writes all the data into the
    autosave file and creates all textfiles needed

    :return: None
    """
    # Just copy the saved items in the array from savestate into the file. Update all first though
    handling = 0
    check = 0
    # print(savestate.saveListData)
    try:
        for index in savestate.saveListData["Left"]:
            handling = index
            # Get the current element on index
            savestate.saveListData["Left"][index]["itemData"] = \
                savestate.saveListItems["Left"][index]["item"].getProperties()
            savestate.saveListItems["Left"][index]["item"].setEdit(
                savestate.configList["AutoUpdateFiles"])
        for index in savestate.saveListData["Right"]:
            # Get the current element on index
            handling = index
            savestate.saveListData["Right"][index]["itemData"] = \
                savestate.saveListItems["Right"][index]["item"].getProperties()
            savestate.saveListItems["Right"][index]["item"].setEdit(
                savestate.configList["AutoUpdateFiles"])
    except KeyError:
        # The first time we load up the list, there can't be any items in there
        # print("KeyError occurred at " + str(handling) + ". This is an expected error the first time the program is "
        #                                                 "loaded.")
        # print(savestate.saveListData)
        # print(savestate.saveListItems)
        logWrite("KeyError occurred at " + str(handling) +
                 ". This is an expected error the first time the program is "
                 "loaded.")
    except RuntimeError:
        pass
    try:
        if savestate.saveLists["Left"].count(
        ) == 0 and savestate.saveLists["Right"].count() == 0:
            tempArray = savestate.saveListData
            savestate.saveListItems = {"Left": {}, "Right": {}}
        else:
            # put the savestate array into the json
            tempArray = savestate.saveListData
            # print(tempArray)
    except AttributeError:
        # If the lists aren't saved yet
        print("Expected List error 1")
        tempArray = savestate.saveListData
    # print("Temp array is: ", tempArray)
    writeToAutosave("Lists", tempArray)
    lname = savestate.configList["LeftListName"]
    rname = savestate.configList["RightListName"]

    # create the textFiles
    try:
        for index in savestate.saveListData["Left"]:
            now = savestate.saveListData["Left"][index]["itemData"]
            if "pretext" in now:
                arg = [
                    "Lists", now["name"],
                    str(now["pretext"] + str(now["value"])), lname
                ]
                check = initTextFiles("createFile", arg)
            elif "chronotype" in now:
                # Chronoitems edit their own textfiles in real time (hehe, time lol)
                pass
            elif "path" in now:
                # Image items dont have any textfiles, so theres no work to do here
                pass
            else:
                arg = ["Lists", now["name"], str(now["value"]), lname]
                check = initTextFiles("createFile", arg)
            if check > 0:
                print("Item not accepted: ",
                      savestate.saveListData["Left"][index])
        for index in savestate.saveListData["Right"]:
            now = savestate.saveListData["Right"][index]["itemData"]
            if "pretext" in now:
                arg = [
                    "Lists", now["name"],
                    str(now["pretext"] + str(now["value"])), rname
                ]
                check = initTextFiles("createFile", arg)
            elif "chronotype" in now:
                pass
            elif "path" in now:
                pass
            else:
                arg = ["Lists", now["name"], str(now["value"]), rname]
                check = initTextFiles("createFile", arg)
            if check > 0:
                print("Item not accepted: ",
                      savestate.saveListData["Left"][index])
    except KeyError as e:
        print(e)
Exemplo n.º 23
0
def scoreInteraction(action, value, operator):
    """
    This method handles score interactions within the application.

    It is used to set the score to zero or handle the score operations.

    Input parameters should be as follows:

        action = can be "zero", "zeroAll" or "operation"

        value = specifies the team number for "zero" or is the
                value for the operation

        operator = not used for "zero", but specifies the
                    operator to use on the scores. Can be
                        0 for "+ value",
                        1 for "- value" or
                        2 for "set score to value"

    :param action: str
    :param value: int
    :param operator: int
    :return: None
    """

    logWrite("Commencing operation " + action + " with value " + str(value) + " and operator number " + str(operator))

    if action == "zero":
        savestate.lineedit_list["T" + str(value) + "_score"].setValue(0)
        editTxts(str("T" + str(value) + "_score"))

    if action == "zeroAll":
        for team in range(1, 5):
            savestate.lineedit_list["T" + str(team) + "_score"].setValue(0)
            editTxts("T" + str(team) + "_score")

    if action == "operation":
        print(savestate.lastScoreChange, value)
        if operator == 0:  # +
            if savestate.lastScoreChange > value:
                savestate.lastScoreChange = value
            else:
                for team in range(1, 5):
                    currentValue = int(savestate.lineedit_list["T" + str(team) + "_score"].text()) - value + 1
                    savestate.lineedit_list["T" + str(team) + "_score"].setValue(currentValue + value)
                    editTxts("T" + str(team) + "_score")
                savestate.lastScoreChange = value

        if operator == 1:  # -
            if savestate.lastScoreChange > value:
                savestate.lastScoreChange = value
            else:
                for team in range(1, 5):
                    currentValue = int(
                        savestate.lineedit_list["T" + str(team) + "_score"].text()) + savestate.lastScoreChange
                    savestate.lineedit_list["T" + str(team) + "_score"].setValue(currentValue - value)
                    editTxts("T" + str(team) + "_score")
                savestate.lastScoreChange = value

        if operator == 2:  # Set
            if value != 0:
                for team in range(1, 5):
                    savestate.lineedit_list["T" + str(team) + "_score"].setValue(value)
                    editTxts("T" + str(team) + "_score")
    logWrite("Successfully executed operation!")
Exemplo n.º 24
0
def zeroScoreChanger(window):
    logWrite("Setting team scores to zero")
    window.T_ScoreDiff.setValue(0)
    for team in range(1, 5):
        editTxts("T" + str(team) + "_score")
Exemplo n.º 25
0
def initPackage(ui):
    """
    This Method creates all necessary textfiles for the eSports-UI and connects the line edits to them.
    I'm splitting the main interface into three parts, so lag shouldn't be a large problem, even on slower PCs.

    :type ui: uic.load element
    :return: bool
    """
    logWrite("Initializing eSports tab...")
    # Add each lineedit to the list in savestate for ease of access
    temp_lineedit_list = {"CS_League": ui.CS_League,
                          "CS_Game": ui.CS_Game,
                          "CS_Day": ui.CS_Day,
                          "CS_Group": ui.CS_Group,
                          "CS_Tournament": ui.CS_Tournament,
                          "HT_Player1": ui.HT_Player1,
                          "HT_Player2": ui.HT_Player2,
                          "HT_Player3": ui.HT_Player3,
                          "HT_Player4": ui.HT_Player4,
                          "HT_Player5": ui.HT_Player5,
                          "HT_Sub1": ui.HT_Sub1,
                          "HT_Sub2": ui.HT_Sub2,
                          "HT_abbreviation": ui.HT_abbreviation,
                          "HT_city": ui.HT_city,
                          "HT_name": ui.HT_name,
                          "HT_organisation": ui.HT_organisation,
                          "HT_Comment": ui.HT_comment,
                          "T1_name": ui.T1_name,
                          "T1_score": ui.T1_score,
                          "T1_city": ui.T1_city,
                          "T2_name": ui.T2_name,
                          "T2_score": ui.T2_score,
                          "T2_city": ui.T2_city,
                          "T3_name": ui.T3_name,
                          "T3_score": ui.T3_score,
                          "T3_city": ui.T3_city,
                          "T4_name": ui.T4_name,
                          "T4_score": ui.T4_score,
                          "T4_city": ui.T4_city
                          }

    savestate.lineedit_list = temp_lineedit_list

    # Create the bonus folders to differentiate
    initTextFiles("initFolders")

    # ! REDUNDANT ! - Now in fileedit
    # try:
    #    print("Trying to create eSports folder...")
    #    for folder in folderlist:
    #        makedirs(path + savestate.symbol + folder)
    # except FileExistsError:
    #    print("eSports folders are already created!")
    # except PermissionError:
    #    print("This location requires elevated permissions")

    # Load a save
    lists = readAutosave("eSports")
    savestate.txtlist = lists["txtlist"]
    savestate.morelist = lists["morelist"]
    loadTexts()

    # Connect the lineedits to the textfiles
    # Write to textfiles

    # Competitive Streaming
    ui.CS_Day.editingFinished.connect(lambda: editTxts("CS_Day"))
    ui.CS_Game.editingFinished.connect(lambda: editTxts("CS_Game"))
    ui.CS_League.editingFinished.connect(lambda: editTxts("CS_League"))
    ui.CS_Group.editingFinished.connect(lambda: editTxts("CS_Group"))
    ui.CS_Tournament.editingFinished.connect(lambda: editTxts("CS_Tournament"))
    ui.showMoreFieldsButton.clicked.connect(lambda: showAddFields())

    # Home Team
    ui.HT_Player1.editingFinished.connect(lambda: editTxts("HT_Player1"))
    ui.HT_Player2.editingFinished.connect(lambda: editTxts("HT_Player2"))
    ui.HT_Player3.editingFinished.connect(lambda: editTxts("HT_Player3"))
    ui.HT_Player4.editingFinished.connect(lambda: editTxts("HT_Player4"))
    ui.HT_Player5.editingFinished.connect(lambda: editTxts("HT_Player5"))

    ui.HT_Sub1.editingFinished.connect(lambda: editTxts("HT_Sub1"))
    ui.HT_Sub2.editingFinished.connect(lambda: editTxts("HT_Sub2"))
    ui.HT_abbreviation.editingFinished.connect(lambda: editTxts("HT_abbreviation"))
    ui.HT_city.editingFinished.connect(lambda: editTxts("HT_city"))
    ui.HT_name.editingFinished.connect(lambda: editTxts("HT_name"))
    ui.HT_organisation.editingFinished.connect(lambda: editTxts("HT_organisation"))

    ui.HT_comment.textChanged.connect(lambda: editTxts("HT_Comment"))

    # Teams section
    ui.T1_name.editingFinished.connect(lambda: editTxts("T1_name"))
    ui.T1_score.editingFinished.connect(lambda: editTxts("T1_score"))
    ui.T1_city.editingFinished.connect(lambda: editTxts("T1_city"))
    ui.T2_name.editingFinished.connect(lambda: editTxts("T2_name"))
    ui.T2_score.editingFinished.connect(lambda: editTxts("T2_score"))
    ui.T2_city.editingFinished.connect(lambda: editTxts("T2_city"))
    ui.T3_name.editingFinished.connect(lambda: editTxts("T3_name"))
    ui.T3_score.editingFinished.connect(lambda: editTxts("T3_score"))
    ui.T3_city.editingFinished.connect(lambda: editTxts("T3_city"))
    ui.T4_name.editingFinished.connect(lambda: editTxts("T4_name"))
    ui.T4_score.editingFinished.connect(lambda: editTxts("T4_score"))
    ui.T4_city.editingFinished.connect(lambda: editTxts("T4_city"))

    # Clears
    ui.T_clear.clicked.connect(lambda: clearSection("T"))
    ui.HT_clear.clicked.connect(lambda: clearSection("HT"))
    ui.CS_clear.clicked.connect(lambda: clearSection("CS"))

    # Swaps
    ui.t1t2_swap.clicked.connect(lambda: swapTeams(0))
    ui.t3t4_swap.clicked.connect(lambda: swapTeams(1))
    ui.T_swap.clicked.connect(lambda: swapTeams(2))

    # Saves
    ui.T_save.clicked.connect(lambda: saveCurrentState())
    ui.T_saveNoEdit.clicked.connect(lambda: saveCurrentState())
    ui.CS_save.clicked.connect(lambda: saveCurrentState())
    ui.HT_toTeam.clicked.connect(lambda: saveCurrentState())

    # HT interactions
    ui.T1_setHT.clicked.connect(lambda: setHomeTeam(1))
    ui.T2_setHT.clicked.connect(lambda: setHomeTeam(2))
    ui.T3_setHT.clicked.connect(lambda: setHomeTeam(3))
    ui.T4_setHT.clicked.connect(lambda: setHomeTeam(4))

    # Score Interactions
    ui.t1_zero.clicked.connect(lambda: scoreInteraction("zero", 1, 0))
    ui.t2_zero.clicked.connect(lambda: scoreInteraction("zero", 2, 0))
    ui.t3_zero.clicked.connect(lambda: scoreInteraction("zero", 3, 0))
    ui.t4_zero.clicked.connect(lambda: scoreInteraction("zero", 4, 0))
    ui.T_ScoreDiff.valueChanged.connect(lambda: scoreInteraction("operation",
                                                                 int(ui.T_ScoreDiff.text()),
                                                                 ui.T_ScoreOperator.currentIndex()))
    ui.T_ScoreDiff.editingFinished.connect(lambda: zeroScoreChanger(ui))
    ui.T_ZeroScore.clicked.connect(lambda: scoreInteraction("zeroAll", 0, 0))
Exemplo n.º 26
0
def swapTeams(way):
    """
    To swap two teams, it is enough to set the text in the lineedits accordingly and then call editTxts()

    ""way" is the direction the teams should be swapped:

        0 = Swap T1 and T2

        1 = Swap T3 and T4

        2 = Swap T1, T2 and T3, T4

    :type way: int
    :return: None
    """

    if way == 0:
        logWrite("Swapping team 1 and 2.")
        element: str
        for element in savestate.lineedit_list:
            if "T1" in element:
                try:
                    temp = savestate.lineedit_list[element].text()
                except AttributeError:
                    temp = savestate.lineedit_list[element].value()
                try:
                    savestate.lineedit_list[element].setText(
                        savestate.lineedit_list["T2_" + str(element.replace("T1_", ""))].text())
                    savestate.lineedit_list["T2_" + str(element.replace("T1_", ""))].setText(temp)
                except AttributeError:
                    savestate.lineedit_list[element].setValue(
                        int(savestate.lineedit_list["T2_" + str(element.replace("T1_", ""))].text()))
                    savestate.lineedit_list["T2_" + str(element.replace("T1_", ""))].setValue(int(temp))
        editTxts("all")

    if way == 1:
        logWrite("Swapping team 3 and 4.")

        element: str
        for element in savestate.lineedit_list:
            if "T3" in element:
                try:
                    temp = savestate.lineedit_list[element].text()
                except AttributeError:
                    temp = savestate.lineedit_list[element].value()
                try:
                    savestate.lineedit_list[element].setText(
                        savestate.lineedit_list["T4_" + str(element.replace("T3_", ""))].text())
                    savestate.lineedit_list["T4_" + str(element.replace("T3_", ""))].setText(temp)
                except AttributeError:
                    savestate.lineedit_list[element].setValue(
                        int(savestate.lineedit_list["T4_" + str(element.replace("T3_", ""))].text()))
                    savestate.lineedit_list["T4_" + str(element.replace("T3_", ""))].setValue(int(temp))
        editTxts("all")

    if way == 2:
        logWrite("Swapping all teams.")
        for element in savestate.lineedit_list:
            if "T3" in element:
                try:
                    temp = savestate.lineedit_list[element].text()
                except AttributeError:
                    temp = savestate.lineedit_list[element].value()
                try:
                    savestate.lineedit_list[element].setText(
                        savestate.lineedit_list["T1_" + str(element.replace("T3_", ""))].text())
                    savestate.lineedit_list["T1_" + str(element.replace("T3_", ""))].setText(temp)
                except AttributeError:
                    savestate.lineedit_list[element].setValue(
                        int(savestate.lineedit_list["T1_" + str(element.replace("T3_", ""))].text()))
                    savestate.lineedit_list["T1_" + str(element.replace("T3_", ""))].setValue(int(temp))
            if "T4" in element:
                try:
                    temp = savestate.lineedit_list[element].text()
                except AttributeError:
                    temp = savestate.lineedit_list[element].value()
                try:
                    savestate.lineedit_list[element].setText(
                        savestate.lineedit_list["T2_" + str(element.replace("T4_", ""))].text())
                    savestate.lineedit_list["T2_" + str(element.replace("T4_", ""))].setText(temp)
                except AttributeError:
                    savestate.lineedit_list[element].setValue(
                        int(savestate.lineedit_list["T2_" + str(element.replace("T4_", ""))].text()))
                    savestate.lineedit_list["T2_" + str(element.replace("T4_", ""))].setValue(int(temp))
        editTxts("all")
Exemplo n.º 27
0
def emptyDir(path):
    try:
        shutil.rmtree(path, ignore_errors=True)
    except FileNotFoundError:
        logWrite("The folder could not be found!")
Exemplo n.º 28
0
def clearSection(section):
    """
    This method clears all line edits within a section (HT, Teams or CS)

    :param section: str
    :return: None
    """
    logWrite("Clearing section " + section)
    success = []
    if section == "HT":
        for element in savestate.lineedit_list:
            if "HT_" in element:
                try:
                    savestate.lineedit_list[element].setText("")
                    success.append(True)
                except KeyError as e:

                    print(str(e) + " not found!")
                    success.append(False)
                except AttributeError:
                    # This should happen if there is no lineedit ( SpinBox for score )

                    try:
                        savestate.lineedit_list[element].setValue(0)
                    except KeyError as e:
                        logWrite("KeyError occurred while clearing section (number)!")
                        print(str(e) + " not found!")
    elif section == "CS":
        for element in savestate.lineedit_list:
            if "CS_" in element:
                try:
                    savestate.lineedit_list[element].setText("")
                    success.append(True)
                except KeyError as e:
                    logWrite("KeyError occurred while clearing section!")
                    print(str(e) + " not found!")
                    success.append(False)
                except AttributeError:
                    # This should happen if there is no lineedit ( SpinBox for score )

                    try:
                        savestate.lineedit_list[element].setValue(0)
                    except KeyError as e:
                        logWrite("KeyError occurred while clearing section (number)!")
                        print(str(e) + " not found!")
    else:
        for team in range(1, 5):
            try:
                savestate.lineedit_list["T" + str(team) + "_city"].setText("")
                savestate.lineedit_list["T" + str(team) + "_name"].setText("")
                savestate.lineedit_list["T" + str(team) + "_score"].setValue(0)
                success.append(True)
            except KeyError as e:
                logWrite("KeyError occurred while clearing teams!")
                print(str(e) + " not found!")
                success.append(False)
    if False in success:
        logWrite("The autosave seems to be incomplete or corrupted")
        print("The autosave seems to be incomplete or corrupted")
    editTxts("all")
    saveCurrentState()
Exemplo n.º 29
0
def syncSettings(self):
    """
    this is a method that's frequently used when opening the settings window. It synchronizes the settings from
    the file to the QWidget object and the user interface.
    :param self: SettingsWindow
    :return: None
    """
    logWrite("Trying to load up the settings window...")
    self.ui.treeWidget.itemClicked.connect(lambda: changeSheet(self))
    # File Path options
    self.ui.changeTextPath.clicked.connect(lambda: changeTextPath(self))
    self.ui.standardPath.setText(savestate.standardFilePath)
    self.ui.TextFilePath.setText(savestate.configList["CustomFilePath"])

    self.ui.infoReset.hide()

    self.ui.logoButton.setIcon(QIcon(":/images/common/icon2.png"))
    self.ui.logoButton.setIconSize(QSize(64, 64))
    self.ui.logoButton.clicked.connect(lambda: webbrowser.open(
        "https://www.paypal.com/donate?hosted_button_id=825RPFTRDCW7A"))

    # Lists
    self.ui.ChronoFormat.setText(savestate.configList["ChronoFormat"])
    self.ui.applyChronoFormat.clicked.connect(lambda: changeChronoFormat(self))
    self.ui.allowText.setChecked(
        savestate.configList["AllowedItems"]["Text Item"])
    self.ui.allowNumbers.setChecked(
        savestate.configList["AllowedItems"]["Number Item"])
    self.ui.allowChronos.setChecked(
        savestate.configList["AllowedItems"]["Chrono Item"])
    self.ui.allowImage.setChecked(
        savestate.configList["AllowedItems"]["Image Item"])
    self.ui.allowText.clicked.connect(lambda: changeAllowedItems(self))
    self.ui.allowNumbers.clicked.connect(lambda: changeAllowedItems(self))
    self.ui.allowChronos.clicked.connect(lambda: changeAllowedItems(self))
    self.ui.allowImage.clicked.connect(lambda: changeAllowedItems(self))

    self.ui.SplitLists.setChecked(savestate.configList["ListSplit"])
    self.ui.SplitLists.stateChanged.connect(
        lambda: activateFolderSplitting(self.ui.SplitLists))

    self.ui.AutoUpdate.setChecked(savestate.configList["AutoUpdateFiles"])
    self.ui.AutoUpdate.stateChanged.connect(lambda: autoUpdateFiles(self))

    self.ui.llistname.setText(savestate.configList["LeftListName"])
    self.ui.rlistname.setText(savestate.configList["RightListName"])
    self.ui.llistname.editingFinished.connect(lambda: changeListName(self, 1))
    self.ui.rlistname.editingFinished.connect(lambda: changeListName(self, 0))
    self.ui.linkChronoFormat.clicked.connect(
        lambda: webbrowser.open("https://doc.qt.io/qt-5/qtime.html#toString"))

    # Miscellaneous
    self.ui.StartupPage.setCurrentIndex(savestate.configList["StartupTab"])
    self.ui.StartupPage.currentIndexChanged.connect(
        lambda: changeStartupPage(self))

    self.ui.funnelFileSeparator.setText(
        savestate.configList["funnelfile_separator"])
    self.ui.applyFunnel.clicked.connect(
        lambda: changeFunnelFileSeparator(self))

    # About
    self.ui.resetSettings.clicked.connect(lambda: resetSettings(self))

    self.ui.showLicense.clicked.connect(
        lambda: webbrowser.open(savestate.SOURCE_PATH + "COPYING.txt"))
Exemplo n.º 30
0
def updateLists():
    """
    reset all the items and lists so we can load it from the data
    :return None
    """
    logWrite("Updating the lists...")
    try:
        savestate.saveLists["Left"].clear()
        savestate.saveLists["Right"].clear()
    except AttributeError:
        # If there are for some reason no lists saved
        print("List error - There are no lists!")
    savestate.saveListItems = {"Left": {}, "Right": {}}

    # perform a miracle and resurrect all items from savestate
    for key in savestate.saveListData["Left"]:
        if "pretext" in savestate.saveListData["Left"][key]["itemData"]:
            addToList(savestate.saveListData["Left"][key]["itemData"]["name"],
                      1,
                      savestate.saveListData["Left"][key]["itemData"]["value"],
                      0,
                      savestate.saveListData["Left"][key]["itemData"]["pretext"]
                      )
        elif "chronotype" in savestate.saveListData["Left"][key]["itemData"]:
            addToList(savestate.saveListData["Left"][key]["itemData"]["name"],
                      2,
                      str(savestate.saveListData["Left"][key]["itemData"]["valueTime"] + ":" +
                          str(savestate.saveListData["Left"][key]["itemData"]["running"]) + ":" +
                          str(savestate.saveListData["Left"][key]["itemData"]["chronotype"]) + ":" +
                          str(savestate.saveListData["Left"][key]["itemData"]["customFormat"])
                          ),
                      0,
                      savestate.saveListData["Left"][key]["itemData"]["returnMsg"]
                      )
        elif "path" in savestate.saveListData["Left"][key]["itemData"]:
            addToList(savestate.saveListData["Left"][key]["itemData"]["name"],
                      3,
                      savestate.saveListData["Left"][key]["itemData"]["path"],
                      0,
                      "")
        else:
            addToList(savestate.saveListData["Left"][key]["itemData"]["name"],
                      0,
                      savestate.saveListData["Left"][key]["itemData"]["value"],
                      0,
                      pretext=""
                      )

    # List 2
    for key in savestate.saveListData["Right"]:
        savestate.saveListData["Right"][int(key)] = savestate.saveListData["Right"][key]

        if "pretext" in savestate.saveListData["Right"][key]["itemData"]:
            addToList(savestate.saveListData["Right"][key]["itemData"]["name"],
                      1,
                      savestate.saveListData["Right"][key]["itemData"]["value"],
                      1,
                      savestate.saveListData["Right"][key]["itemData"]["pretext"]
                      )
        elif "chronotype" in savestate.saveListData["Right"][key]["itemData"]:
            addToList(savestate.saveListData["Right"][key]["itemData"]["name"],
                      2,
                      str(savestate.saveListData["Right"][key]["itemData"]["valueTime"] + ":" +
                          str(savestate.saveListData["Right"][key]["itemData"]["running"]) + ":" +
                          str(savestate.saveListData["Right"][key]["itemData"]["chronotype"]) + ":" +
                          str(savestate.saveListData["Right"][key]["itemData"]["customFormat"])),
                      1,
                      savestate.saveListData["Right"][key]["itemData"]["returnMsg"]
                      )
        elif "path" in savestate.saveListData["Right"][key]["itemData"]:
            addToList(savestate.saveListData["Right"][key]["itemData"]["name"],
                      3,
                      savestate.saveListData["Right"][key]["itemData"]["path"],
                      1,
                      "")
        else:
            addToList(savestate.saveListData["Right"][key]["itemData"]["name"],
                      0,
                      savestate.saveListData["Right"][key]["itemData"]["value"],
                      1,
                      pretext=""
                      )
    # Update the textfiles
    getTextOfItem()