def read(self, file_name): prefix = ";SETTING_" + str(GCodeProfileReader.version) + " " prefix_length = len(prefix) #Loading all settings from the file. They are all at the end, but Python has no reverse seek any more since Python3. TODO: Consider moving settings to the start? serialised = "" #Will be filled with the serialised profile. try: with open(file_name) as f: for line in f: if line.startswith(prefix): serialised += line[prefix_length : -1] #Remove the prefix and the newline from the line, and add it to the rest. except IOError as e: Logger.log("e", "Unable to open file %s for reading: %s", file_name, str(e)) return None #Unescape the serialised profile. pattern = re.compile("|".join(GCodeProfileReader.escape_characters.keys())) serialised = pattern.sub(lambda m: GCodeProfileReader.escape_characters[re.escape(m.group(0))], serialised) #Perform the replacement with a regular expression. #Apply the changes to the current profile. profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) try: profile.unserialise(serialised) except Exception as e: #Not a valid g-code file. return None return profile
def loadProfiles(self): storage_path = Resources.getStoragePathForType(Resources.Profiles) dirs = Resources.getAllPathsForType(Resources.Profiles) for dir in dirs: if not os.path.isdir(dir): continue read_only = dir != storage_path for file_name in os.listdir(dir): path = os.path.join(dir, file_name) if os.path.isdir(path): continue profile = Profile(self, read_only) try: profile.loadFromFile(path) except Exception as e: Logger.log("e", "An exception occurred loading Profile %s: %s", path, str(e)) continue if not self.findProfile(profile.getName()): self._profiles.append(profile) profile.nameChanged.connect(self._onProfileNameChanged) profile = self.findProfile(Preferences.getInstance().getValue("machines/active_profile")) if profile: self.setActiveProfile(profile) self.profilesChanged.emit()
def test_createProfile(self, machine_manager): profile = Profile(machine_manager) assert isinstance(profile, Profile) profile = Profile(machine_manager, read_only = True) assert isinstance(profile, Profile) assert profile.isReadOnly()
def loadProfiles(self): storage_path = Resources.getStoragePathForType(Resources.Profiles) dirs = Resources.getAllPathsForType(Resources.Profiles) for dir in dirs: if not os.path.isdir(dir): continue read_only = dir != storage_path for root, dirs, files in os.walk(dir): for file_name in files: path = os.path.join(root, file_name) if os.path.isdir(path): continue profile = Profile(self, read_only) try: profile.loadFromFile(path) except Exception as e: Logger.log("e", "An exception occurred loading Profile %s: %s", path, str(e)) continue if not self.findProfile(profile.getName(), variant_name = profile.getMachineVariantName(), material_name = profile.getMaterialName(), instance = self._active_machine): self._profiles.append(profile) profile.nameChanged.connect(self._onProfileNameChanged) for instance in self._machine_instances: try: file_name = urllib.parse.quote_plus(instance.getName()) + ".curaprofile" instance.getWorkingProfile().loadFromFile(Resources.getStoragePath(Resources.MachineInstanceProfiles, file_name)) except Exception as e: Logger.log("w", "Could not load working profile: %s: %s", file_name, str(e)) self._setDefaultVariantMaterialProfile(instance) self._protect_working_profile = True if self._active_machine: profile_name = self._active_machine.getActiveProfileName() if profile_name == "": profile_name = "Normal Quality" profile = self.findProfile(self._active_machine.getActiveProfileName(), instance = self._active_machine) if profile: self.setActiveProfile(profile) else: profiles = self.getProfiles(instance = self._active_machine) if len(profiles) > 0: self.setActiveProfile(profiles[0]) self.profilesChanged.emit() self._protect_working_profile = False
def importProfile(self, url): path = url.toLocalFile() if not path: return profile = Profile(self._manager, read_only = False) try: profile.loadFromFile(path) except Exception as e: m = Message(catalog.i18nc("@info:status", "Failed to import profile from file <filename>{0}</filename>: <message>{1}</message>", path, str(e))) m.show() else: m = Message(catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName())) m.show() self._manager.addProfile(profile)
def read(self, file_name): profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) #Create an empty profile. serialised = "" try: with open(file_name) as f: #Open file for reading. serialised = f.read() except IOError as e: Logger.log("e", "Unable to open file %s for reading: %s", file_name, str(e)) return None try: profile.unserialise(serialised) except Exception as e: #Parsing error. This is not a (valid) Cura profile then. return None return profile
def __init__(self, machine_manager, **kwargs): super().__init__() self._machine_manager = machine_manager self._key = kwargs.get("key") self._name = kwargs.get("name", "") self._machine_definition = kwargs.get("definition", None) if self._machine_definition: self._machine_definition.loadAll() self._machine_setting_overrides = {} self._active_profile_name = None self._active_material_name = None self._working_profile = Profile(machine_manager) self._working_profile.setType("machine_instance_profile")
def test_loadAndSave(self, machine_manager, definition_file_name, instance_file_name, profile_file_name, target_profile_file_name): profile = Profile(machine_manager) definition = MachineDefinition(machine_manager, self._getDefinitionsFilePath(definition_file_name)) definition.loadMetaData() machine_manager.addMachineDefinition(definition) machine_instance = MachineInstance(machine_manager, definition = definition) machine_instance.loadFromFile(self._getInstancesFilePath(instance_file_name)) profile._active_instance = machine_instance profile.loadFromFile(self._getProfileFilePath(profile_file_name)) try: os.remove(self._getProfileFilePath(target_profile_file_name)) # Clear any previous tests except: pass profile.saveToFile(self._getProfileFilePath(target_profile_file_name)) config_loaded = configparser.ConfigParser() config_loaded.read(self._getProfileFilePath(instance_file_name)) config_saved = configparser.ConfigParser() config_saved.read(self._getProfileFilePath(target_profile_file_name)) for section in config_loaded.sections(): assert section in config_saved.sections() for key in config_loaded[section]: assert key in config_saved[section] assert config_loaded[section][key] == config_saved[section][key]
def test_profiles(self, machine_manager): profile_1 = Profile(machine_manager) profile_2 = Profile(machine_manager) definition = MachineDefinition(machine_manager, self._getDefinitionsFilePath("simple_machine.json")) definition.loadMetaData() machine_manager.addMachineDefinition(definition) machine_instance = MachineInstance(machine_manager, definition = definition, name = "Basic Test") machine_instance.loadFromFile(self._getInstancesFilePath("simple_machine.cfg")) machine_manager.addMachineInstance(machine_instance) profile_1._active_instance = machine_instance profile_2._active_instance = machine_instance profile_1.loadFromFile(self._getProfileFilePath("simple_machine_with_overrides.cfg")) profile_2.loadFromFile(self._getProfileFilePath("simple_machine_with_overrides.cfg")) machine_manager.addProfile(profile_1) assert machine_manager.getProfiles() == [profile_1] # Check if adding again has no effect machine_manager.addProfile(profile_1) assert machine_manager.getProfiles() == [profile_1] # Check that adding another profile with same name does not work with pytest.raises(DuplicateProfileError): machine_manager.addProfile(profile_2) # Changing the name and then adding it should work profile_2.setName("test") machine_manager.addProfile(profile_2) assert profile_1 in machine_manager.getProfiles() and profile_2 in machine_manager.getProfiles() assert machine_manager.findProfile("test") == profile_2 # Check if removing one of the profiles works machine_manager.removeProfile(profile_1) assert machine_manager.getProfiles() == [profile_2] machine_manager.setActiveProfile(profile_2) assert machine_manager.getActiveProfile() == profile_2 machine_manager.removeProfile(profile_2) assert machine_manager.getProfiles() == []
def loadProfiles(self): storage_path = Resources.getStoragePathForType(Resources.Profiles) dirs = Resources.getAllPathsForType(Resources.Profiles) for dir in dirs: if not os.path.isdir(dir): continue read_only = dir != storage_path for file_name in os.listdir(dir): path = os.path.join(dir, file_name) if os.path.isdir(path): continue profile = Profile(self, read_only) try: profile.loadFromFile(path) except Exception as e: Logger.log("e", "An exception occurred loading Profile %s: %s", path, str(e)) continue if not self.findProfile(profile.getName()): self._profiles.append(profile) profile.nameChanged.connect(self._onProfileNameChanged) profile = self.findProfile( Preferences.getInstance().getValue("machines/active_profile")) if profile: self.setActiveProfile(profile) else: if Preferences.getInstance().getValue( "machines/active_profile") == "": for profile in self._profiles: self.setActiveProfile( profile) #default to first profile you can find break self.profilesChanged.emit()
def read(self, file_name): if file_name.split(".")[-1] != "gcode": return None prefix = ";SETTING_" + str(GCodeProfileReader.version) + " " prefix_length = len(prefix) # Loading all settings from the file. # They are all at the end, but Python has no reverse seek any more since Python3. # TODO: Consider moving settings to the start? serialised = "" # Will be filled with the serialised profile. try: with open(file_name) as f: for line in f: if line.startswith(prefix): # Remove the prefix and the newline from the line and add it to the rest. serialised += line[prefix_length : -1] except IOError as e: Logger.log("e", "Unable to open file %s for reading: %s", file_name, str(e)) return None # Un-escape the serialised profile. pattern = re.compile("|".join(GCodeProfileReader.escape_characters.keys())) # Perform the replacement with a regular expression. serialised = pattern.sub(lambda m: GCodeProfileReader.escape_characters[re.escape(m.group(0))], serialised) # Apply the changes to the current profile. profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) try: profile.unserialise(serialised) profile.setType(None) # Force type to none so it's correctly added. profile.setReadOnly(False) profile.setDirty(True) except Exception as e: # Not a valid g-code file. Logger.log("e", "Unable to serialise the profile: %s", str(e)) return None return profile
def importProfile(self, url): path = url.toLocalFile() if not path: return profile = Profile(self._manager, read_only=False) try: profile.loadFromFile(path) self._manager.addProfile(profile) except SettingsError.DuplicateProfileError as e: count = 2 name = "{0} {1}".format(profile.getName(), count) while (self._manager.findProfile(name) != None): count += 1 name = "{0} {1}".format(profile.getName(), count) profile.setName(name) self._manager.addProfile(profile) return { "status": "duplicate", "message": catalog.i18nc("@info:status", "Profile was imported as {0}", name) } except Exception as e: return { "status": "error", "message": catalog.i18nc( "@info:status", "Failed to import profile from file <filename>{0}</filename>: <message>{1}</message>", path, str(e)) } else: return { "status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName()) }
def _createProfile(self, machine_manager, definition_file): definition = MachineDefinition( machine_manager, os.path.join(os.path.dirname(os.path.abspath(__file__)), "definitions", definition_file)) definition.loadAll() machine_manager.addMachineDefinition(definition) instance = MachineInstance(machine_manager, definition=definition) machine_manager.addMachineInstance(instance) machine_manager.setActiveMachineInstance(instance) profile = Profile(machine_manager) machine_manager.addProfile(profile) machine_manager.setActiveProfile(profile) return (definition, profile)
def test_profileOverride(self, machine_manager, definition_file_name, instance_file_name, profile_file_name, expected_values): profile = Profile(machine_manager) definition = MachineDefinition(machine_manager, self._getDefinitionsFilePath(definition_file_name)) definition.loadMetaData() machine_manager.addMachineDefinition(definition) machine_instance = MachineInstance(machine_manager, definition = definition) machine_instance.loadFromFile(self._getInstancesFilePath(instance_file_name)) profile._active_instance = machine_instance profile.loadFromFile(self._getProfileFilePath(profile_file_name)) for key in expected_values: assert profile.getSettingValue(key) == expected_values[key]
def importProfile(self, url): path = url.toLocalFile() if not path: return profile = Profile(self._manager, read_only = False) try: profile.loadFromFile(path) self._manager.addProfile(profile) except SettingsError.DuplicateProfileError as e: count = 2 name = "{0} {1}".format(profile.getName(), count) while(self._manager.findProfile(name) != None): count += 1 name = "{0} {1}".format(profile.getName(), count) profile.setName(name) self._manager.addProfile(profile) return { "status": "duplicate", "message": catalog.i18nc("@info:status", "Profile was imported as {0}", name) } except Exception as e: return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from file <filename>{0}</filename>: <message>{1}</message>", path, str(e)) } else: return { "status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName()) }
def test_profiles(self, machine_manager): profile_1 = Profile(machine_manager) profile_2 = Profile(machine_manager) definition = MachineDefinition( machine_manager, self._getDefinitionsFilePath("simple_machine.json")) definition.loadMetaData() machine_manager.addMachineDefinition(definition) machine_instance = MachineInstance(machine_manager, definition=definition, name="Basic Test") machine_instance.loadFromFile( self._getInstancesFilePath("simple_machine.cfg")) machine_manager.addMachineInstance(machine_instance) profile_1._active_instance = machine_instance profile_2._active_instance = machine_instance profile_1.loadFromFile( self._getProfileFilePath("simple_machine_with_overrides.cfg")) profile_2.loadFromFile( self._getProfileFilePath("simple_machine_with_overrides.cfg")) machine_manager.addProfile(profile_1) assert machine_manager.getProfiles() == [profile_1] # Check if adding again has no effect machine_manager.addProfile(profile_1) assert machine_manager.getProfiles() == [profile_1] # Check that adding another profile with same name does not work with pytest.raises(DuplicateProfileError): machine_manager.addProfile(profile_2) # Changing the name and then adding it should work profile_2.setName("test") machine_manager.addProfile(profile_2) assert profile_1 in machine_manager.getProfiles( ) and profile_2 in machine_manager.getProfiles() assert machine_manager.findProfile("test") == profile_2 # Check if removing one of the profiles works machine_manager.removeProfile(profile_1) assert machine_manager.getProfiles() == [profile_2] machine_manager.setActiveProfile(profile_2) assert machine_manager.getActiveProfile() == profile_2 machine_manager.removeProfile(profile_2) assert machine_manager.getProfiles() == []
class MachineInstance(SignalEmitter): MachineInstanceVersion = 1 def __init__(self, machine_manager, **kwargs): super().__init__() self._machine_manager = machine_manager self._key = kwargs.get("key") self._name = kwargs.get("name", "") self._machine_definition = kwargs.get("definition", None) if self._machine_definition: self._machine_definition.loadAll() self._machine_setting_overrides = {} self._active_profile_name = None self._active_material_name = None self._working_profile = Profile(machine_manager) self._working_profile.setType("machine_instance_profile") nameChanged = Signal() ## Get key of this machine instance. # This is different from the name in respect that it need not be human readable # The difference is simmilar with that of key & label for the settings. # \sa setKey def getKey(self): return self._key ## Set key of this machine instance. # This is different from the name in respect that it need not be human readable # The difference is simmilar with that of key & label for the settings. # \sa getKey def setKey(self, key): self._key = key def getName(self): return self._name def setName(self, name): if name != self._name: old_name = self._name self._name = self._machine_manager.makeUniqueMachineInstanceName(name, self._machine_definition.getName(), old_name) self.nameChanged.emit(self, old_name) def getWorkingProfile(self): return self._working_profile def getActiveProfileName(self): return self._active_profile_name def setActiveProfileName(self, active_profile_name): self._active_profile_name = active_profile_name def getMaterialName(self): return self._active_material_name def setMaterialName(self, material_name): self._active_material_name = material_name def hasMaterials(self): return len(self._machine_manager.getAllMachineMaterials(self._name)) > 0 def getMachineDefinition(self): return self._machine_definition def setMachineDefinition(self, definition): if not definition: return definition.loadAll() self._machine_definition = definition def setMachineSettingValue(self, setting, value): if not self._machine_definition.isMachineSetting(setting): Logger.log("w", "Tried to override setting %s that is not a machine setting", setting) return self._machine_setting_overrides[setting] = value def getMachineSettingValue(self, setting): if not self._machine_definition.isMachineSetting(setting): return if setting in self._machine_setting_overrides: return self._machine_setting_overrides[setting] return self._machine_definition.getSetting(setting).getDefaultValue() def getSettingValue(self, key): if not self._machine_definition.isSetting(key): return None if key in self._machine_setting_overrides: return self._machine_setting_overrides[key] return self._machine_definition.getSetting(key).getDefaultValue() def hasMachineSettingValue(self, key): return key in self._machine_setting_overrides def loadFromFile(self, path): config = configparser.ConfigParser(interpolation = None) config.read(path, "utf-8") if not config.has_section("general"): raise SettingsError.InvalidFileError(path) if not config.has_option("general", "version"): raise SettingsError.InvalidFileError(path) if not config.has_option("general", "name") or not config.has_option("general", "type"): raise SettingsError.InvalidFileError(path) if int(config.get("general", "version")) != self.MachineInstanceVersion: raise SettingsError.InvalidVersionError(path) type_name = config.get("general", "type") variant_name = config.get("general", "variant", fallback = "") self._machine_definition = self._machine_manager.findMachineDefinition(type_name, variant_name) if not self._machine_definition: raise SettingsError.DefinitionNotFoundError(type_name) self._machine_definition.loadAll() self._name = config.get("general", "name") self._key = config.get("general", "key", fallback = None) self._active_profile_name = config.get("general", "active_profile", fallback="") self._active_material_name = config.get("general", "material", fallback = "") for key, value in config["machine_settings"].items(): self._machine_setting_overrides[key] = value def saveToFile(self, path): config = configparser.ConfigParser(interpolation = None) config.add_section("general") config["general"]["name"] = self._name config["general"]["type"] = self._machine_definition.getId() config["general"]["active_profile"] = str(self._active_profile_name) config["general"]["version"] = str(self.MachineInstanceVersion) if self._key: config["general"]["key"] = str(self._key) if self._machine_definition.getVariantName(): config["general"]["variant"] = self._machine_definition.getVariantName() if self._active_material_name and self._active_material_name != "": config["general"]["material"] = self._active_material_name config.add_section("machine_settings") for key, value in self._machine_setting_overrides.items(): config["machine_settings"][key] = str(value) try: with SaveFile(path, "wt", -1, "utf-8") as f: config.write(f) except Exception as e: Logger.log("e", "Failed to write Instance to %s: %s", path, str(e))
def loadProfiles(self): storage_path = Resources.getStoragePathForType(Resources.Profiles) dirs = Resources.getAllPathsForType(Resources.Profiles) for dir in dirs: if not os.path.isdir(dir): continue read_only = dir != storage_path for root, dirs, files in os.walk(dir): for file_name in files: path = os.path.join(root, file_name) if os.path.isdir(path): continue profile = Profile(self, read_only) try: profile.loadFromFile(path) except Exception as e: Logger.log( "e", "An exception occurred loading Profile %s: %s", path, str(e)) continue if not self.findProfile( profile.getName(), variant_name=profile.getMachineVariantName(), material_name=profile.getMaterialName(), instance=self._active_machine): self._profiles.append(profile) profile.nameChanged.connect(self._onProfileNameChanged) for instance in self._machine_instances: try: file_name = urllib.parse.quote_plus( instance.getName()) + ".curaprofile" instance.getWorkingProfile().loadFromFile( Resources.getStoragePath(Resources.MachineInstanceProfiles, file_name)) except Exception as e: Logger.log("w", "Could not load working profile: %s: %s", file_name, str(e)) self._setDefaultVariantMaterialProfile(instance) self._protect_working_profile = True if self._active_machine: profile_name = self._active_machine.getActiveProfileName() if profile_name == "": profile_name = "Normal Quality" profile = self.findProfile( self._active_machine.getActiveProfileName(), instance=self._active_machine) if profile: self.setActiveProfile(profile) else: profiles = self.getProfiles(instance=self._active_machine) if len(profiles) > 0: self.setActiveProfile(profiles[0]) self.profilesChanged.emit() self._protect_working_profile = False
class MachineInstance(SignalEmitter): MachineInstanceVersion = 1 def __init__(self, machine_manager, **kwargs): super().__init__() self._machine_manager = machine_manager self._key = kwargs.get("key") self._name = kwargs.get("name", "") self._machine_definition = kwargs.get("definition", None) if self._machine_definition: self._machine_definition.loadAll() self._machine_setting_overrides = {} self._active_profile_name = None self._active_material_name = None self._working_profile = Profile(machine_manager) self._working_profile.setType("machine_instance_profile") nameChanged = Signal() ## Get key of this machine instance. # This is different from the name in respect that it need not be human readable # The difference is simmilar with that of key & label for the settings. # \sa setKey def getKey(self): return self._key ## Set key of this machine instance. # This is different from the name in respect that it need not be human readable # The difference is simmilar with that of key & label for the settings. # \sa getKey def setKey(self, key): self._key = key def getName(self): return self._name def setName(self, name): if name != self._name: old_name = self._name self._name = self._machine_manager.makeUniqueMachineInstanceName( name, self._machine_definition.getName(), old_name) self.nameChanged.emit(self, old_name) def getWorkingProfile(self): return self._working_profile def getActiveProfileName(self): return self._active_profile_name def setActiveProfileName(self, active_profile_name): self._active_profile_name = active_profile_name def getMaterialName(self): return self._active_material_name def setMaterialName(self, material_name): self._active_material_name = material_name def hasMaterials(self): return len(self._machine_manager.getAllMachineMaterials( self._name)) > 0 def getMachineDefinition(self): return self._machine_definition def setMachineDefinition(self, definition): if not definition: return definition.loadAll() self._machine_definition = definition def setMachineSettingValue(self, setting, value): if not self._machine_definition.isMachineSetting(setting): Logger.log( "w", "Tried to override setting %s that is not a machine setting", setting) return self._machine_setting_overrides[setting] = value def getMachineSettingValue(self, setting): if not self._machine_definition.isMachineSetting(setting): return if setting in self._machine_setting_overrides: return self._machine_setting_overrides[setting] return self._machine_definition.getSetting(setting).getDefaultValue() def getSettingValue(self, key): if not self._machine_definition.isSetting(key): return None if key in self._machine_setting_overrides: return self._machine_setting_overrides[key] return self._machine_definition.getSetting(key).getDefaultValue() def hasMachineSettingValue(self, key): return key in self._machine_setting_overrides def loadFromFile(self, path): config = configparser.ConfigParser(interpolation=None) config.read(path, "utf-8") if not config.has_section("general"): raise SettingsError.InvalidFileError(path) if not config.has_option("general", "version"): raise SettingsError.InvalidFileError(path) if not config.has_option("general", "name") or not config.has_option( "general", "type"): raise SettingsError.InvalidFileError(path) if int(config.get("general", "version")) != self.MachineInstanceVersion: raise SettingsError.InvalidVersionError(path) type_name = config.get("general", "type") variant_name = config.get("general", "variant", fallback="") self._machine_definition = self._machine_manager.findMachineDefinition( type_name, variant_name) if not self._machine_definition: raise SettingsError.DefinitionNotFoundError(type_name) self._machine_definition.loadAll() self._name = config.get("general", "name") self._key = config.get("general", "key", fallback=None) self._active_profile_name = config.get("general", "active_profile", fallback="") self._active_material_name = config.get("general", "material", fallback="") for key, value in config["machine_settings"].items(): self._machine_setting_overrides[key] = value def saveToFile(self, path): config = configparser.ConfigParser(interpolation=None) config.add_section("general") config["general"]["name"] = self._name config["general"]["type"] = self._machine_definition.getId() config["general"]["active_profile"] = str(self._active_profile_name) config["general"]["version"] = str(self.MachineInstanceVersion) if self._key: config["general"]["key"] = str(self._key) if self._machine_definition.getVariantName(): config["general"][ "variant"] = self._machine_definition.getVariantName() if self._active_material_name and self._active_material_name != "": config["general"]["material"] = self._active_material_name config.add_section("machine_settings") for key, value in self._machine_setting_overrides.items(): config["machine_settings"][key] = str(value) try: with SaveFile(path, "wt", -1, "utf-8") as f: config.write(f) except Exception as e: Logger.log("e", "Failed to write Instance to %s: %s", path, str(e))
def read(self, file_name): if file_name.split(".")[-1] != "ini": return None Logger.log("i", "Importing legacy profile from file " + file_name + ".") profile = Profile(machine_manager = Application.getInstance().getMachineManager(), read_only = False) #Create an empty profile. parser = configparser.ConfigParser(interpolation = None) try: with open(file_name) as f: parser.readfp(f) #Parse the INI file. except Exception as e: Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e)) return None #Legacy Cura saved the profile under the section "profile_N" where N is the ID of a machine, except when you export in which case it saves it in the section "profile". #Since importing multiple machine profiles is out of scope, just import the first section we find. section = "" for found_section in parser.sections(): if found_section.startswith("profile"): section = found_section break if not section: #No section starting with "profile" was found. Probably not a proper INI file. return None try: with open(os.path.join(PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f: dict_of_doom = json.load(f) #Parse the Dictionary of Doom. except IOError as e: Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e)) return None except Exception as e: Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e)) return None defaults = self.prepareDefaults(dict_of_doom) legacy_settings = self.prepareLocals(parser, section, defaults) #Gets the settings from the legacy profile. #Check the target version in the Dictionary of Doom with this application version. if "target_version" not in dict_of_doom: Logger.log("e", "Dictionary of Doom has no target version. Is it the correct JSON file?") return None if Profile.ProfileVersion != dict_of_doom["target_version"]: Logger.log("e", "Dictionary of Doom of legacy profile reader (version %s) is not in sync with the profile version (version %s)!", dict_of_doom["target_version"], str(Profile.ProfileVersion)) return None if "translation" not in dict_of_doom: Logger.log("e", "Dictionary of Doom has no translation. Is it the correct JSON file?") return None for new_setting in dict_of_doom["translation"]: #Evaluate all new settings that would get a value from the translations. old_setting_expression = dict_of_doom["translation"][new_setting] compiled = compile(old_setting_expression, new_setting, "eval") try: new_value = eval(compiled, {"math": math}, legacy_settings) #Pass the legacy settings as local variables to allow access to in the evaluation. value_using_defaults = eval(compiled, {"math": math}, defaults) #Evaluate again using only the default values to try to see if they are default. except Exception as e: #Probably some setting name that was missing or something else that went wrong in the ini file. Logger.log("w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.") continue if new_value != value_using_defaults and profile.getSettingValue(new_setting) != new_value: #Not equal to the default in the new Cura OR the default in the legacy Cura. profile.setSettingValue(new_setting, new_value) #Store the setting in the profile! if len(profile.getChangedSettings()) == 0: Logger.log("i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.") profile.setDirty(True) return profile
def read(self, file_name): if file_name.split(".")[-1] != "ini": return None Logger.log("i", "Importing legacy profile from file " + file_name + ".") profile = Profile( machine_manager=Application.getInstance().getMachineManager(), read_only=False) #Create an empty profile. parser = configparser.ConfigParser(interpolation=None) try: with open(file_name) as f: parser.readfp(f) #Parse the INI file. except Exception as e: Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e)) return None #Legacy Cura saved the profile under the section "profile_N" where N is the ID of a machine, except when you export in which case it saves it in the section "profile". #Since importing multiple machine profiles is out of scope, just import the first section we find. section = "" for found_section in parser.sections(): if found_section.startswith("profile"): section = found_section break if not section: #No section starting with "profile" was found. Probably not a proper INI file. return None try: with open( os.path.join( PluginRegistry.getInstance().getPluginPath( "LegacyProfileReader"), "DictionaryOfDoom.json"), "r", -1, "utf-8") as f: dict_of_doom = json.load(f) #Parse the Dictionary of Doom. except IOError as e: Logger.log("e", "Could not open DictionaryOfDoom.json for reading: %s", str(e)) return None except Exception as e: Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e)) return None defaults = self.prepareDefaults(dict_of_doom) legacy_settings = self.prepareLocals( parser, section, defaults) #Gets the settings from the legacy profile. #Check the target version in the Dictionary of Doom with this application version. if "target_version" not in dict_of_doom: Logger.log( "e", "Dictionary of Doom has no target version. Is it the correct JSON file?" ) return None if Profile.ProfileVersion != dict_of_doom["target_version"]: Logger.log( "e", "Dictionary of Doom of legacy profile reader (version %s) is not in sync with the profile version (version %s)!", dict_of_doom["target_version"], str(Profile.ProfileVersion)) return None if "translation" not in dict_of_doom: Logger.log( "e", "Dictionary of Doom has no translation. Is it the correct JSON file?" ) return None for new_setting in dict_of_doom[ "translation"]: #Evaluate all new settings that would get a value from the translations. old_setting_expression = dict_of_doom["translation"][new_setting] compiled = compile(old_setting_expression, new_setting, "eval") try: new_value = eval( compiled, {"math": math}, legacy_settings ) #Pass the legacy settings as local variables to allow access to in the evaluation. value_using_defaults = eval( compiled, {"math": math}, defaults ) #Evaluate again using only the default values to try to see if they are default. except Exception as e: #Probably some setting name that was missing or something else that went wrong in the ini file. Logger.log( "w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile." ) continue if new_value != value_using_defaults and profile.getSettingValue( new_setting ) != new_value: #Not equal to the default in the new Cura OR the default in the legacy Cura. profile.setSettingValue( new_setting, new_value) #Store the setting in the profile! if len(profile.getChangedSettings()) == 0: Logger.log( "i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile." ) profile.setDirty(True) return profile
def loadProfiles(self): storage_path = Resources.getStoragePathForType(Resources.Profiles) dirs = Resources.getAllPathsForType(Resources.Profiles) for dir in dirs: if not os.path.isdir(dir): continue read_only = dir != storage_path for root, dirs, files in os.walk(dir): for file_name in files: path = os.path.join(root, file_name) if os.path.isdir(path): continue # Bit of a hack, but we should only use cfg or curaprofile files in the profile folder. try: extension = path.split(".")[-1] if extension != "cfg" and extension != "curaprofile": continue except: continue # profile has no extension profile = Profile(self, read_only) try: profile.loadFromFile(path) except Exception as e: Logger.log( "e", "An exception occurred loading Profile %s: %s", path, str(e)) continue self._profiles.append(profile) profile.nameChanged.connect(self._onProfileNameChanged) for instance in self._machine_instances: try: file_name = urllib.parse.quote_plus( instance.getName()) + ".curaprofile" instance.getWorkingProfile().loadFromFile( Resources.getStoragePath(Resources.MachineInstanceProfiles, file_name)) except Exception as e: Logger.log("w", "Could not load working profile: %s: %s", file_name, str(e)) self._setDefaultVariantMaterialProfile(instance) self._protect_working_profile = True if self._active_machine: profile_name = self._active_machine.getActiveProfileName() if profile_name == "": profile_name = self._active_machine.getMachineDefinition( ).getPreference("prefered_profile") profile = self.findProfile( self._active_machine.getActiveProfileName(), instance=self._active_machine) if profile: self.setActiveProfile(profile) else: profiles = self.getProfiles(instance=self._active_machine) if len(profiles) > 0: self.setActiveProfile(profiles[0]) self.profilesChanged.emit() self._protect_working_profile = False