def saveSettings(self): if not self._started: # Do not do saving during application start return for instance in ContainerRegistry.getInstance().findInstanceContainers(): if not instance.isDirty(): continue try: data = instance.serialize() except NotImplementedError: continue except Exception: Logger.logException("e", "An exception occurred when serializing container %s", instance.getId()) continue mime_type = ContainerRegistry.getMimeTypeForContainer(type(instance)) file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix instance_type = instance.getMetaDataEntry("type") path = None if instance_type == "material": path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name) elif instance_type == "quality" or instance_type == "quality_changes": path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name) elif instance_type == "user": path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name) elif instance_type == "variant": path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name) if path: instance.setPath(path) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data) for stack in ContainerRegistry.getInstance().findContainerStacks(): if not stack.isDirty(): continue try: data = stack.serialize() except NotImplementedError: continue except Exception: Logger.logException("e", "An exception occurred when serializing container %s", instance.getId()) continue mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack)) file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix stack_type = stack.getMetaDataEntry("type", None) path = None if not stack_type or stack_type == "machine": path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name) elif stack_type == "extruder_train": path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name) if path: stack.setPath(path) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data)
def saveAll(self) -> None: for instance in self.findInstanceContainers(): if not instance.isDirty(): continue try: data = instance.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException("e", "An exception occurred trying to serialize container %s", instance.getId()) continue mime_type = self.getMimeTypeForContainer(type(instance)) if mime_type is not None: file_name = urllib.parse.quote_plus(instance.getId()) + "." + mime_type.preferredSuffix path = Resources.getStoragePath(Resources.InstanceContainers, file_name) with SaveFile(path, "wt") as f: f.write(data) for stack in self.findContainerStacks(): if not stack.isDirty(): continue try: data = stack.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException("e", "An exception occurred trying to serialize container %s", stack.getId()) continue mime_type = self.getMimeTypeForContainer(type(stack)) if mime_type is not None: file_name = urllib.parse.quote_plus(stack.getId()) + "." + mime_type.preferredSuffix path = Resources.getStoragePath(Resources.ContainerStacks, file_name) with SaveFile(path, "wt") as f: f.write(data) for definition in self.findDefinitionContainers(): try: data = definition.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException("e", "An exception occurred trying to serialize container %s", definition.getId()) continue mime_type = self.getMimeTypeForContainer(type(definition)) if mime_type is not None: file_name = urllib.parse.quote_plus(definition.getId()) + "." + mime_type.preferredSuffix path = Resources.getStoragePath(Resources.DefinitionContainers, file_name) with SaveFile(path, "wt") as f: f.write(data)
def _onExit(self): for instance in ContainerRegistry.getInstance().findInstanceContainers( ): if not instance.isDirty(): continue try: data = instance.serialize() except NotImplementedError: continue except Exception: Logger.logException( "e", "An exception occurred when serializing container %s", instance.getId()) continue file_name = urllib.parse.quote_plus(instance.getId()) + ".inst.cfg" instance_type = instance.getMetaDataEntry("type") path = None if instance_type == "material": path = Resources.getStoragePath( self.ResourceTypes.MaterialInstanceContainer, file_name) elif instance_type == "quality": path = Resources.getStoragePath( self.ResourceTypes.QualityInstanceContainer, file_name) elif instance_type == "user": path = Resources.getStoragePath( self.ResourceTypes.UserInstanceContainer, file_name) elif instance_type == "variant": path = Resources.getStoragePath( self.ResourceTypes.VariantInstanceContainer, file_name) if path: with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data) for stack in ContainerRegistry.getInstance().findContainerStacks(): if not stack.isDirty(): continue try: data = stack.serialize() except NotImplementedError: continue except Exception: Logger.logException( "e", "An exception occurred when serializing container %s", instance.getId()) continue file_name = urllib.parse.quote_plus(stack.getId()) + ".stack.cfg" path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data)
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 saveStack(self, stack): if not stack.isDirty(): return try: data = stack.serialize() except NotImplementedError: return except Exception: Logger.logException( "e", "An exception occurred when serializing container %s", stack.getId()) return mime_type = ContainerRegistry.getMimeTypeForContainer(type(stack)) file_name = urllib.parse.quote_plus( stack.getId()) + "." + mime_type.preferredSuffix stack_type = stack.getMetaDataEntry("type", None) path = None if not stack_type or stack_type == "machine": path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name) elif stack_type == "extruder_train": path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name) if path: stack.setPath(path) with SaveFile(path, "wt") as f: f.write(data)
def saveContainer(self, container: "ContainerInterface") -> None: try: data = container.serialize() except NotImplementedError: return except Exception: Logger.logException("e", "An exception occurred when serializing container %s", container.getId()) return mime_type = ContainerRegistry.getMimeTypeForContainer(type(container)) file_name = urllib.parse.quote_plus(container.getId()) + "." + mime_type.preferredSuffix container_type = container.getMetaDataEntry("type") resource_types = ContainerRegistry.getInstance().getResourceTypes() if container_type in resource_types: path = Resources.getStoragePath(resource_types[container_type], file_name) with SaveFile(path, "wt") as f: f.write(data) container.setPath(path) # Register it internally as being saved self._id_to_path[container.getId()] = path self._id_to_mime[container.getId()] = self._pathToMime(path) base_file = container.getMetaData().get("base_file") if base_file: for container_md in ContainerRegistry.getInstance().findContainersMetadata(base_file = base_file): self._id_to_path[container_md["id"]] = path self._id_to_mime[container_md["id"]] = self._pathToMime(path) else: Logger.log("w", "Dirty container [%s] is not saved because the resource type is unknown in ContainerRegistry", container_type)
def test_singleWrite(self): path = os.path.join(self._temp_dir.name, "single_write") with SaveFile(path, "w") as f: f.write("test file") with open(path) as f: self.assertEqual(f.readline(), "test file")
def write_data(path, data): if not isinstance(data, str): data = data.serialize() print(data) with SaveFile(str(path), "wt") as f: f.write(data)
def write(self, path, profile): serialized = profile.serialize() try: with SaveFile(path, "wt", -1, "utf-8") as f: # Open the specified file. f.write(serialized) except Exception as e: Logger.log("e", "Failed to write profile to %s: %s", path, str(e)) return False return True
def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]: if not container_id or not file_type or not file_url_or_string: return {"status": "error", "message": "Invalid arguments"} if isinstance(file_url_or_string, QUrl): file_url = file_url_or_string.toLocalFile() else: file_url = file_url_or_string if not file_url: return {"status": "error", "message": "Invalid path"} if file_type not in self._container_name_filters: try: mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url) except MimeTypeNotFoundError: return {"status": "error", "message": "Unknown File Type"} else: mime_type = self._container_name_filters[file_type]["mime"] containers = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().findContainers(id = container_id) if not containers: return {"status": "error", "message": "Container not found"} container = containers[0] if Platform.isOSX() and "." in file_url: file_url = file_url[:file_url.rfind(".")] for suffix in mime_type.suffixes: if file_url.endswith(suffix): break else: file_url += "." + mime_type.preferredSuffix if not Platform.isWindows(): if os.path.exists(file_url): result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url)) if result == QMessageBox.No: return {"status": "cancelled", "message": "User cancelled"} try: contents = container.serialize() except NotImplementedError: return {"status": "error", "message": "Unable to serialize container"} if contents is None: return {"status": "error", "message": "Serialization returned None. Unable to write to file"} try: with SaveFile(file_url, "w") as f: f.write(contents) except OSError: return {"status": "error", "message": "Unable to write to this location.", "path": file_url} return {"status": "success", "message": "Successfully exported container", "path": file_url}
def saveSettings(self): if not self._started: # Do not do saving during application start return self.waitConfigLockFile() # When starting Cura, we check for the lockFile which is created and deleted here with lockFile(self._config_lock_filename): for instance in ContainerRegistry.getInstance( ).findInstanceContainers(): if not instance.isDirty(): continue try: data = instance.serialize() except NotImplementedError: continue except Exception: Logger.logException( "e", "An exception occurred when serializing container %s", instance.getId()) continue mime_type = ContainerRegistry.getMimeTypeForContainer( type(instance)) file_name = urllib.parse.quote_plus( instance.getId()) + "." + mime_type.preferredSuffix instance_type = instance.getMetaDataEntry("type") path = None if instance_type == "material": path = Resources.getStoragePath( self.ResourceTypes.MaterialInstanceContainer, file_name) elif instance_type == "quality" or instance_type == "quality_changes": path = Resources.getStoragePath( self.ResourceTypes.QualityInstanceContainer, file_name) elif instance_type == "user": path = Resources.getStoragePath( self.ResourceTypes.UserInstanceContainer, file_name) elif instance_type == "variant": path = Resources.getStoragePath( self.ResourceTypes.VariantInstanceContainer, file_name) elif instance_type == "definition_changes": path = Resources.getStoragePath( self.ResourceTypes.MachineStack, file_name) if path: instance.setPath(path) with SaveFile(path, "wt") as f: f.write(data) for stack in ContainerRegistry.getInstance().findContainerStacks(): self.saveStack(stack)
def saveToFile(self, file): serialised = self.serialise() #Serialise this profile instance to a string. try: with SaveFile(file, "wt", -1, "utf-8") as f: # Open the specified file. f.write(serialised) except Exception as e: Logger.log("e", "Failed to write profile to %s: %s", file, str(e)) return str(e) self._dirty = False return None
def writeToFile(self, file): parser = configparser.ConfigParser(interpolation = None) for group, group_entries in self._preferences.items(): parser[group] = {} for key, pref in group_entries.items(): if pref.getValue() != pref.getDefault(): parser[group][key] = str(pref.getValue()) parser["general"]["version"] = "2" try: with SaveFile(file, "wt") as f: parser.write(f) except Exception as e: Logger.log("e", "Failed to write preferences to %s: %s", file, str(e))
def saveContainer(self, container: "ContainerInterface") -> None: """Find out where to save a container and save it there""" try: data = container.serialize() except NotImplementedError: return except Exception: Logger.logException("e", "An exception occurred when serializing container %s", container.getId()) return mime_type = ContainerRegistry.getMimeTypeForContainer(type(container)) if mime_type is None: Logger.log("w", "Failed to get MIME type for container type [%s]", type(container)) return file_name = urllib.parse.quote_plus(container.getId()) + "." + mime_type.preferredSuffix container_type = container.getMetaDataEntry("type") resource_types = ContainerRegistry.getInstance().getResourceTypes() if container_type in resource_types: path = Resources.getStoragePath(resource_types[container_type], file_name) try: with SaveFile(path, "wt") as f: f.write(data) except OSError as e: Logger.log("e", "Unable to store local container to path {path}: {err}".format(path = path, err = str(e))) return container.setPath(path) # Register it internally as being saved self._id_to_path[container.getId()] = path mime = self._pathToMime(path) if mime is not None: self._id_to_mime[container.getId()] = mime else: Logger.log("e", "Failed to find MIME type for container ID [%s] with path [%s]", container.getId(), path) base_file = container.getMetaData().get("base_file") if base_file: for container_md in ContainerRegistry.getInstance().findContainersMetadata(base_file = base_file): self._id_to_path[container_md["id"]] = path mime = self._pathToMime(path) if mime is not None: self._id_to_mime[container_md["id"]] = mime else: Logger.log("e", "Failed to find MIME type for container ID [%s] with path [%s]", container.getId(), path) else: Logger.log("w", "Dirty container [%s] is not saved because the resource type is unknown in ContainerRegistry", container_type)
def writeToFile(self, file): parser = configparser.ConfigParser(interpolation = None) #pylint: disable=bad-whitespace for group, group_entries in self._preferences.items(): parser[group] = {} for key, pref in group_entries.items(): if pref.getValue() != pref.getDefault(): parser[group][key] = str(pref.getValue()) parser["general"]["version"] = str(Preferences.Version) try: if hasattr(file, "read"): # If it already is a stream like object, write right away parser.write(file) else: with SaveFile(file, "wt") as save_file: parser.write(save_file) except Exception as e: Logger.log("e", "Failed to write preferences to %s: %s", file, str(e))
def saveToFile(self, file): parser = configparser.ConfigParser(interpolation=None) parser.add_section("general") parser.set("general", "version", str(self.ProfileVersion)) parser.set("general", "name", self._name) parser.add_section("settings") for setting_key in self._changed_settings: parser.set("settings", setting_key, str(self._changed_settings[setting_key])) try: with SaveFile(file, "wt", -1, "utf-8") as f: parser.write(f) except Exception as e: Logger.log("e", "Failed to write profile to %s: %s", file, str(e)) return str(e) return None
def saveAll(self): for instance in self.findInstanceContainers(): if not instance.isDirty(): continue try: data = instance.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException( "e", "An exception occurred trying to serialize container %s", instance.getId()) continue file_name = urllib.parse.quote_plus(instance.getId()) + ".inst.cfg" path = Resources.getStoragePath(Resources.InstanceContainers, file_name) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data) for stack in self.findContainerStacks(): if not stack.isDirty(): continue try: data = stack.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException( "e", "An exception occurred trying to serialize container %s", stack.getId()) continue file_name = urllib.parse.quote_plus(stack.getId()) + ".stack.cfg" path = Resources.getStoragePath(Resources.ContainerStacks, file_name) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data) for definition in self.findDefinitionContainers(): try: data = definition.serialize() except NotImplementedError: # Serializing is not supported so skip this container continue except Exception: Logger.logException( "e", "An exception occurred trying to serialize container %s", instance.getId()) continue file_name = urllib.parse.quote_plus( definition.getId()) + ".def.cfg" path = Resources.getStoragePath(Resources.DefinitionContainers, file_name) with SaveFile(path, "wt", -1, "utf-8") as f: f.write(data)
def _upgradeFile(self, storage_path_absolute: str, configuration_file: str, old_configuration_type: str) -> bool: """Upgrades a single file to any version in self._current_versions. A single file will be taken as source file, but may result in any number of output files. :param storage_path_absolute: The path where to find the file. :param configuration_file: The file to upgrade to a current version. :param old_configuration_type: The type of the configuration file before upgrading it. :return: True if the file was successfully upgraded, or False otherwise. """ configuration_file_absolute = os.path.join(storage_path_absolute, configuration_file) # Read the old file. try: with open(configuration_file_absolute, encoding = "utf-8", errors = "ignore") as file_handle: files_data = [file_handle.read()] except MemoryError: # File is too big. It might be the log. return False except FileNotFoundError: # File was already moved to an /old directory. return False except IOError: Logger.log("w", "Can't open configuration file %s for reading.", configuration_file_absolute) return False # Get the version number of the old file. try: old_version = self._get_version_functions[old_configuration_type](files_data[0]) except: # Version getter gives an exception. Not a valid file. Can't upgrade it then. return False version = old_version configuration_type = old_configuration_type # Get the actual MIME type object, from the name. try: mime_type = UM.MimeTypeDatabase.MimeTypeDatabase.getMimeTypeForFile(configuration_file) except UM.MimeTypeDatabase.MimeTypeNotFoundError: return False filenames_without_extension = [self._stripMimeTypeExtension(mime_type, configuration_file)] result_data = self.updateFilesData(configuration_type, version, files_data, filenames_without_extension) if not result_data: return False configuration_type, version, files_data, filenames_without_extension = result_data # If the version changed, save the new files. if version != old_version or configuration_type != old_configuration_type: # Finding out where to store these files. resource_type, mime_type_name = self._current_versions[(configuration_type, version)] storage_path = Resources.getStoragePathForType(resource_type) mime_type = UM.MimeTypeDatabase.MimeTypeDatabase.getMimeType(mime_type_name) # Get the actual MIME type object, from the name. if mime_type.preferredSuffix: extension = "." + mime_type.preferredSuffix elif mime_type.suffixes: extension = "." + mime_type.suffixes[0] else: extension = "" # No known suffix. Put no extension behind it. new_filenames = [filename + extension for filename in filenames_without_extension] configuration_files_absolute = [os.path.join(storage_path, filename) for filename in new_filenames] for file_idx, configuration_file_absolute in enumerate(configuration_files_absolute): try: with SaveFile(os.path.join(configuration_file_absolute), "w", encoding = "utf-8") as file_handle: file_handle.write(files_data[file_idx]) # Save the new file. except IOError: Logger.log("w", "Couldn't write new configuration file to %s.", configuration_file_absolute) return False Logger.log("i", "Upgraded %s to version %s.", configuration_file, str(version)) return True return False # Version didn't change. Was already current.
def write_dual(path): with SaveFile(path, "w") as f: f.write("test file")