import os, sys, json import tkinter as tk from tkinter import ttk import gui_helper, util class Config: def __init__(self, file_path, default_config): self.__file_path = file_path self.__default_config = default_config self.__current_config = {} if os.path.isfile(file_path): try: config_file = open(self.__file_path, "r") self.__current_config = json.loads(config_file.read()) config_file.close() except: util.error("An exception occurred while trying to load the configuration.", handle_gracefully=False) else: # config not found dialog_interaction_handler = gui_helper.Window_Interaction_Handler() dialog = tk.Tk() dialog.title("No configuration found") ttk.Label(dialog, text="No configuration found!").pack() buttons_frame = tk.Frame(dialog) buttons_frame.pack() ttk.Button(buttons_frame, text="Create", command=lambda: dialog_interaction_handler.interact("create", True, additional_action=dialog.destroy)).grid(column=0, row=0) ttk.Button(buttons_frame, text="Quit", command=lambda: dialog_interaction_handler.interact("create", False, additional_action=dialog.destroy)).grid(column=1, row=0) dialog.resizable(0,0) dialog.mainloop() if dialog_interaction_handler.get_result("create"): self.__current_config = default_config try: config_file = open(self.__file_path, "w") config_file.write(json.dumps(self.__current_config)) config_file.close() except: util.warn("Failed to save initial config file.", is_exception=True) dialog = tk.Tk() dialog.title("Failed to save initial config file") ttk.Label(dialog, text="Failed to save the initial config file.\n" + "The IDE can still run, but it is likely that all changes to the configuration will be lost where they would be saved otherwise.").pack() ttk.Button(dialog, text="Continue", command=dialog.destroy).pack() dialog.resizable(0,0) dialog.mainloop() else: util.error("No config present and user chose not to create one. Exiting.", is_exception=False, handle_gracefully=True) # exit with success exit code anyway because this is not a program failure sys.exit(util.EXIT_SUCCESS) def get_configuration_value(self, key): if not key in self.__current_config: util.info("Requested configuration value for "+str(key)+" not in configuration. Loading from default configuration.") try: self.__current_config[key] = self.__default_config[key] except KeyError: util.error("Requested an invalid configuration key.") return None return self.__current_config[key] def set_configuration_value(self, key, value, save_to_disk=True): if not key in self.__current_config: util.info("Writing configuration for previously unknown key "+str(key)+".") self.__current_config[key]=value if save_to_disk: try: config_file = open(self.__file_path, "w") config_file.write(json.dumps(self.__current_config)) config_file.close() except: util.error("Failed to save config file.")