123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257 |
- import copy
- import io
- import json
- import os.path
- from typing import Any, Dict, List, Optional, Tuple, cast, Set, Union
- import xml.etree.ElementTree as ET
- from UM.PluginRegistry import PluginRegistry
- from UM.Resources import Resources
- from UM.Logger import Logger
- import UM.Dictionary
- from UM.Settings.InstanceContainer import InstanceContainer
- from UM.Settings.ContainerRegistry import ContainerRegistry
- from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
- from cura.CuraApplication import CuraApplication
- from cura.Machines.VariantType import VariantType
- try:
- from .XmlMaterialValidator import XmlMaterialValidator
- except (ImportError, SystemError):
- import XmlMaterialValidator
- class XmlMaterialProfile(InstanceContainer):
- """Handles serializing and deserializing material containers from an XML file"""
- CurrentFdmMaterialVersion = "1.3"
- Version = 1
- def __init__(self, container_id, *args, **kwargs):
- super().__init__(container_id, *args, **kwargs)
- self._inherited_files = []
- @staticmethod
- def xmlVersionToSettingVersion(xml_version: str) -> int:
- """Translates the version number in the XML files to the setting_version metadata entry.
- Since the two may increment independently we need a way to say which
- versions of the XML specification are compatible with our setting data
- version numbers.
- :param xml_version: The version number found in an XML file.
- :return: The corresponding setting_version.
- """
- if xml_version == "1.3":
- return CuraApplication.SettingVersion
- return 0
- def getInheritedFiles(self):
- return self._inherited_files
- def setMetaDataEntry(self, key, value, apply_to_all = True):
- """set the meta data for all machine / variant combinations
- The "apply_to_all" flag indicates whether this piece of metadata should be applied to all material containers
- or just this specific container.
- For example, when you change the material name, you want to apply it to all its derived containers, but for
- some specific settings, they should only be applied to a machine/variant-specific container.
- Overridden from InstanceContainer
- """
- registry = ContainerRegistry.getInstance()
- if registry.isReadOnly(self.getId()):
- Logger.log("w", "Can't change metadata {key} of material {material_id} because it's read-only.".format(key = key, material_id = self.getId()))
- return
-
-
- new_setting_values_dict = {}
- if key == "properties":
- for k, v in value.items():
- if k in self.__material_properties_setting_map:
- new_setting_values_dict[self.__material_properties_setting_map[k]] = v
- if not apply_to_all:
-
-
- container_query = [self]
- else:
- container_query = registry.findContainers(base_file = self.getMetaDataEntry("base_file"))
- for container in container_query:
- if key not in container.getMetaData() or container.getMetaData()[key] != value:
- container.getMetaData()[key] = value
- container.setDirty(True)
- container.metaDataChanged.emit(container)
- for k, v in new_setting_values_dict.items():
- self.setProperty(k, "value", v)
- def setName(self, new_name):
- """Overridden from InstanceContainer, similar to setMetaDataEntry.
- without this function the setName would only set the name of the specific nozzle / material / machine combination container
- The function is a bit tricky. It will not set the name of all containers if it has the correct name itself.
- """
- registry = ContainerRegistry.getInstance()
- if registry.isReadOnly(self.getId()):
- return
-
- if self.getName() == new_name:
- return
- super().setName(new_name)
- basefile = self.getMetaDataEntry("base_file", self.getId())
-
-
- containers = registry.findInstanceContainers(base_file = basefile)
- for container in containers:
- container.setName(new_name)
- def setDirty(self, dirty):
- """Overridden from InstanceContainer, to set dirty to base file as well."""
- super().setDirty(dirty)
- base_file = self.getMetaDataEntry("base_file", None)
- registry = ContainerRegistry.getInstance()
- if base_file is not None and base_file != self.getId() and not registry.isReadOnly(base_file):
- containers = registry.findContainers(id = base_file)
- if containers:
- containers[0].setDirty(dirty)
- def serialize(self, ignored_metadata_keys: Optional[Set[str]] = None):
- """Overridden from InstanceContainer
- base file: common settings + supported machines
- machine / variant combination: only changes for itself.
- """
- registry = ContainerRegistry.getInstance()
- base_file = self.getMetaDataEntry("base_file", "")
- if base_file and self.getId() != base_file:
-
-
-
- raise NotImplementedError("Ignoring serializing non-root XML materials, the data is contained in the base material")
- builder = ET.TreeBuilder()
- root = builder.start("fdmmaterial",
- {"xmlns": "http://www.ultimaker.com/material",
- "xmlns:cura": "http://www.ultimaker.com/cura",
- "version": self.CurrentFdmMaterialVersion})
-
- builder.start("metadata", {})
- metadata = copy.deepcopy(self.getMetaData())
-
- reserialize_settings = copy.deepcopy(metadata["reserialize_settings"])
-
- if ignored_metadata_keys is None:
- ignored_metadata_keys = set()
- ignored_metadata_keys |= {"setting_version", "definition", "status", "variant", "type", "base_file", "approximate_diameter", "id", "container_type", "name", "compatible", "reserialize_settings"}
-
- for key in ignored_metadata_keys:
- if key in metadata:
- del metadata[key]
- properties = metadata.pop("properties", {})
-
- builder.start("name", {})
- builder.start("brand", {})
- builder.data(metadata.pop("brand", ""))
- builder.end("brand")
- builder.start("material", {})
- builder.data(metadata.pop("material", ""))
- builder.end("material")
- builder.start("color", {})
- builder.data(metadata.pop("color_name", ""))
- builder.end("color")
- builder.start("label", {})
- builder.data(self.getName())
- builder.end("label")
- builder.end("name")
-
- for key, value in metadata.items():
- key_to_use = key
- if key in self._metadata_tags_that_have_cura_namespace:
- key_to_use = "cura:" + key_to_use
- builder.start(key_to_use, {})
- if value is not None:
-
-
- value = str(value)
- builder.data(value)
- builder.end(key_to_use)
- builder.end("metadata")
-
-
- builder.start("properties", {})
- for key, value in properties.items():
- builder.start(key, {})
- builder.data(value)
- builder.end(key)
- builder.end("properties")
-
-
- builder.start("settings", {})
- if self.getMetaDataEntry("definition") == "fdmprinter":
- for instance in self.findInstances():
- self._addSettingElement(builder, instance)
- machine_container_map = {}
- machine_variant_map = {}
- root_material_id = self.getMetaDataEntry("base_file")
- all_containers = registry.findInstanceContainers(base_file = root_material_id)
- for container in all_containers:
- definition_id = container.getMetaDataEntry("definition")
- if definition_id == "fdmprinter":
- continue
- if definition_id not in machine_container_map:
- machine_container_map[definition_id] = container
- if definition_id not in machine_variant_map:
- machine_variant_map[definition_id] = {}
- variant_name = container.getMetaDataEntry("variant_name")
- if not variant_name:
- machine_container_map[definition_id] = container
- continue
- variant_dict = {"variant_type": container.getMetaDataEntry("hardware_type", "nozzle"),
- "material_container": container}
- machine_variant_map[definition_id][variant_name] = variant_dict
-
- product_id_map = self.getProductIdMap()
- for definition_id, container in machine_container_map.items():
- definition_id = container.getMetaDataEntry("definition")
- definition_metadata = registry.findDefinitionContainersMetadata(id = definition_id)[0]
- product = definition_id
- for product_name, product_id_list in product_id_map.items():
- if definition_id in product_id_list:
- product = product_name
- break
- builder.start("machine", {})
- builder.start("machine_identifier", {
- "manufacturer": container.getMetaDataEntry("machine_manufacturer",
- definition_metadata.get("manufacturer", "Unknown")),
- "product": product
- })
- builder.end("machine_identifier")
- for instance in container.findInstances():
- if self.getMetaDataEntry("definition") == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
-
- continue
- self._addSettingElement(builder, instance)
-
- buildplate_dict = {}
- for variant_name, variant_dict in machine_variant_map[definition_id].items():
- variant_type = VariantType(variant_dict["variant_type"])
- if variant_type == VariantType.NOZZLE:
-
- builder.start("hotend", {"id": variant_name})
-
- material_container = variant_dict["material_container"]
- compatible = material_container.getMetaDataEntry("compatible")
- if compatible is not None:
- builder.start("setting", {"key": "hardware compatible"})
- if compatible:
- builder.data("yes")
- else:
- builder.data("no")
- builder.end("setting")
- for instance in material_container.findInstances():
- if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
-
- continue
- self._addSettingElement(builder, instance)
- if material_container.getMetaDataEntry("buildplate_compatible") and not buildplate_dict:
- buildplate_dict["buildplate_compatible"] = material_container.getMetaDataEntry("buildplate_compatible")
- buildplate_dict["buildplate_recommended"] = material_container.getMetaDataEntry("buildplate_recommended")
- buildplate_dict["material_container"] = material_container
- hotend_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
- for key, value in hotend_reserialize_settings.items():
- builder.start("setting", {"key": key})
- builder.data(value)
- builder.end("setting")
- builder.end("hotend")
- if buildplate_dict:
- for variant_name in buildplate_dict["buildplate_compatible"]:
- builder.start("buildplate", {"id": variant_name})
- material_container = buildplate_dict["material_container"]
- buildplate_compatible_dict = material_container.getMetaDataEntry("buildplate_compatible")
- buildplate_recommended_dict = material_container.getMetaDataEntry("buildplate_recommended")
- if buildplate_compatible_dict:
- compatible = buildplate_compatible_dict[variant_name]
- recommended = buildplate_recommended_dict[variant_name]
- builder.start("setting", {"key": "hardware compatible"})
- builder.data("yes" if compatible else "no")
- builder.end("setting")
- builder.start("setting", {"key": "hardware recommended"})
- builder.data("yes" if recommended else "no")
- builder.end("setting")
- buildplate_reserialize_settings = material_container.getMetaDataEntry("reserialize_settings")
- for key, value in buildplate_reserialize_settings.items():
- builder.start("setting", {"key": key})
- builder.data(value)
- builder.end("setting")
- builder.end("buildplate")
- machine_reserialize_settings = container.getMetaDataEntry("reserialize_settings")
- for key, value in machine_reserialize_settings.items():
- builder.start("setting", {"key": key})
- builder.data(value)
- builder.end("setting")
- builder.end("machine")
- for key, value in reserialize_settings.items():
- builder.start("setting", {"key": key})
- builder.data(value)
- builder.end("setting")
- builder.end("settings")
-
- builder.end("fdmmaterial")
- root = builder.close()
- _indent(root)
- stream = io.BytesIO()
- tree = ET.ElementTree(root)
-
- tree.write(stream, encoding = "utf-8", xml_declaration = True)
- return stream.getvalue().decode("utf-8")
- def getFileName(self) -> str:
- return (self.getMetaDataEntry("base_file") + ".xml.fdm_material").replace(" ", "+")
-
- def _resolveInheritance(self, file_name):
- xml = self._loadFile(file_name)
- inherits = xml.find("./um:inherits", self.__namespaces)
- if inherits is not None:
- inherited = self._resolveInheritance(inherits.text)
- xml = self._mergeXML(inherited, xml)
- return xml
- def _loadFile(self, file_name):
- path = Resources.getPath(CuraApplication.getInstance().ResourceTypes.MaterialInstanceContainer, file_name + ".xml.fdm_material")
- with open(path, encoding = "utf-8") as f:
- contents = f.read()
- self._inherited_files.append(path)
- return ET.fromstring(contents)
-
-
-
- def _expandMachinesXML(self, element):
- settings_element = element.find("./um:settings", self.__namespaces)
- machines = settings_element.iterfind("./um:machine", self.__namespaces)
- machines_to_add = []
- machines_to_remove = []
- for machine in machines:
- identifiers = list(machine.iterfind("./um:machine_identifier", self.__namespaces))
- has_multiple_identifiers = len(identifiers) > 1
- if has_multiple_identifiers:
-
- for identifier in identifiers:
- new_machine = copy.deepcopy(machine)
-
- other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
-
- new_machine_identifiers = list(new_machine.iterfind("./um:machine_identifier", self.__namespaces))
- for new_machine_identifier in new_machine_identifiers:
- key = self._createKey(new_machine_identifier)
-
- if key in other_identifiers:
- new_machine.remove(new_machine_identifier)
- machines_to_add.append(new_machine)
- machines_to_remove.append(machine)
- else:
- pass
-
- for machine_to_remove in machines_to_remove:
- settings_element.remove(machine_to_remove)
- for machine_to_add in machines_to_add:
- settings_element.append(machine_to_add)
- return element
- def _mergeXML(self, first, second):
- result = copy.deepcopy(first)
- self._combineElement(self._expandMachinesXML(result), self._expandMachinesXML(second))
- return result
- @staticmethod
- def _createKey(element):
- key = element.tag.split("}")[-1]
- if "key" in element.attrib:
- key += " key:" + element.attrib["key"]
- if "manufacturer" in element.attrib:
- key += " manufacturer:" + element.attrib["manufacturer"]
- if "product" in element.attrib:
- key += " product:" + element.attrib["product"]
- if key == "machine":
- for item in element:
- if "machine_identifier" in item.tag:
- key += " " + item.attrib["product"]
- return key
-
-
- @staticmethod
- def _combineElement(first, second):
-
- mapping = {}
- for element in first:
- key = XmlMaterialProfile._createKey(element)
- mapping[key] = element
- for element in second:
- key = XmlMaterialProfile._createKey(element)
- if len(element):
- try:
- if "setting" in element.tag and not "settings" in element.tag:
-
- for child in list(mapping[key]):
- mapping[key].remove(child)
- for child in element:
- mapping[key].append(child)
- else:
- XmlMaterialProfile._combineElement(mapping[key], element)
- except KeyError:
- mapping[key] = element
- first.append(element)
- else:
- try:
- mapping[key].text = element.text
- except KeyError:
- mapping[key] = element
- first.append(element)
- def clearData(self):
- self._metadata = {
- "id": self.getId(),
- "name": ""
- }
- self._definition = None
- self._instances = {}
- self._read_only = False
- self._dirty = False
- self._path = ""
- @classmethod
- def getConfigurationTypeFromSerialized(cls, serialized: str) -> Optional[str]:
- return "materials"
- @classmethod
- def getVersionFromSerialized(cls, serialized: str) -> int:
- data = ET.fromstring(serialized)
- version = XmlMaterialProfile.Version
-
- if "version" in data.attrib:
- setting_version = cls.xmlVersionToSettingVersion(data.attrib["version"])
- else:
- setting_version = cls.xmlVersionToSettingVersion("1.2")
- return version * 1000000 + setting_version
- @classmethod
- def getMetadataFromSerialized(cls, serialized: str, property_name: str) -> str:
- data = ET.fromstring(serialized)
- metadata = data.find("./um:metadata", cls.__namespaces)
- property = metadata.find("./um:" + property_name, cls.__namespaces)
-
- return property.text if property != None else ""
- def deserialize(self, serialized, file_name = None):
- """Overridden from InstanceContainer"""
- containers_to_add = []
-
- from UM.Settings.Interfaces import ContainerInterface
- serialized = ContainerInterface.deserialize(self, serialized, file_name)
- try:
- data = ET.fromstring(serialized)
- except:
- Logger.logException("e", "An exception occurred while parsing the material profile")
- return
-
- old_id = self.getId()
- self.clearData()
- meta_data = {}
- meta_data["type"] = "material"
- meta_data["base_file"] = self.getId()
- meta_data["status"] = "unknown"
- meta_data["id"] = old_id
- meta_data["container_type"] = XmlMaterialProfile
- meta_data["reserialize_settings"] = {}
- common_setting_values = {}
- inherits = data.find("./um:inherits", self.__namespaces)
- if inherits is not None:
- inherited = self._resolveInheritance(inherits.text)
- data = self._mergeXML(inherited, data)
-
- if "version" in data.attrib:
- meta_data["setting_version"] = self.xmlVersionToSettingVersion(data.attrib["version"])
- else:
- meta_data["setting_version"] = self.xmlVersionToSettingVersion("1.2")
- meta_data["name"] = "Unknown Material"
- for entry in data.iterfind("./um:metadata/*", self.__namespaces):
- tag_name = _tag_without_namespace(entry)
- if tag_name == "name":
- brand = entry.find("./um:brand", self.__namespaces)
- material = entry.find("./um:material", self.__namespaces)
- color = entry.find("./um:color", self.__namespaces)
- label = entry.find("./um:label", self.__namespaces)
- if label is not None and label.text is not None:
- meta_data["name"] = label.text
- else:
- meta_data["name"] = self._profile_name(material.text, color.text)
- meta_data["brand"] = brand.text if brand.text is not None else "Unknown Brand"
- meta_data["material"] = material.text if material.text is not None else "Unknown Type"
- meta_data["color_name"] = color.text if color.text is not None else "Unknown Color"
- continue
-
- if tag_name == "setting_version":
- continue
- meta_data[tag_name] = entry.text
- if tag_name in self.__material_metadata_setting_map:
- common_setting_values[self.__material_metadata_setting_map[tag_name]] = entry.text
- if "description" not in meta_data:
- meta_data["description"] = ""
- if "adhesion_info" not in meta_data:
- meta_data["adhesion_info"] = ""
- validation_message = XmlMaterialValidator.validateMaterialMetaData(meta_data)
- if validation_message is not None:
- ConfigurationErrorMessage.getInstance().addFaultyContainers(self.getId())
- Logger.log("e", "Not a valid material profile: {message}".format(message = validation_message))
- return
- property_values = {}
- properties = data.iterfind("./um:properties/*", self.__namespaces)
- for entry in properties:
- tag_name = _tag_without_namespace(entry)
- property_values[tag_name] = entry.text
- if tag_name in self.__material_properties_setting_map:
- common_setting_values[self.__material_properties_setting_map[tag_name]] = entry.text
- meta_data["approximate_diameter"] = str(round(float(property_values.get("diameter", 2.85))))
- meta_data["properties"] = property_values
- meta_data["definition"] = "fdmprinter"
- common_compatibility = True
- settings = data.iterfind("./um:settings/um:setting", self.__namespaces)
- for entry in settings:
- key = entry.get("key")
- if key in self.__material_settings_setting_map:
- if key == "processing temperature graph":
- graph_nodes = entry.iterfind("./um:point", self.__namespaces)
- graph_points = []
- for graph_node in graph_nodes:
- flow = float(graph_node.get("flow"))
- temperature = float(graph_node.get("temperature"))
- graph_points.append([flow, temperature])
- common_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
- else:
- common_setting_values[self.__material_settings_setting_map[key]] = entry.text
- elif key in self.__unmapped_settings:
- if key == "hardware compatible":
- common_compatibility = self._parseCompatibleValue(entry.text)
- elif key in self.__keep_serialized_settings:
- meta_data["reserialize_settings"][key] = entry.text
-
- settings = data.iterfind("./um:settings/cura:setting", self.__namespaces)
- for entry in settings:
- value = entry.text
- if value.lower() == "yes":
- value = True
- elif value.lower() == "no":
- value = False
- key = entry.get("key")
- common_setting_values[key] = value
- self._cached_values = common_setting_values
- meta_data["compatible"] = common_compatibility
- self.setMetaData(meta_data)
- self._dirty = False
-
- product_id_map = self.getProductIdMap()
- machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
- for machine in machines:
- machine_compatibility = common_compatibility
- machine_setting_values = {}
- settings = machine.iterfind("./um:setting", self.__namespaces)
- machine_reserialize_settings = {}
- for entry in settings:
- key = entry.get("key")
- if key in self.__material_settings_setting_map:
- if key == "processing temperature graph":
- graph_nodes = entry.iterfind("./um:point", self.__namespaces)
- graph_points = []
- for graph_node in graph_nodes:
- flow = float(graph_node.get("flow"))
- temperature = float(graph_node.get("temperature"))
- graph_points.append([flow, temperature])
- machine_setting_values[self.__material_settings_setting_map[key]] = str(graph_points)
- else:
- machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
- elif key in self.__unmapped_settings:
- if key == "hardware compatible":
- machine_compatibility = self._parseCompatibleValue(entry.text)
- elif key in self.__keep_serialized_settings:
- machine_reserialize_settings[key] = entry.text
- else:
- Logger.log("d", "Unsupported material setting %s", key)
-
- settings = machine.iterfind("./cura:setting", self.__namespaces)
- for entry in settings:
- value = entry.text
- if value.lower() == "yes":
- value = True
- elif value.lower() == "no":
- value = False
- key = entry.get("key")
- machine_setting_values[key] = value
- cached_machine_setting_properties = common_setting_values.copy()
- cached_machine_setting_properties.update(machine_setting_values)
- identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
- for identifier in identifiers:
- machine_id_list = product_id_map.get(identifier.get("product"), [])
- if not machine_id_list:
- machine_id_list = self.getPossibleDefinitionIDsFromName(identifier.get("product"))
- for machine_id in machine_id_list:
- definitions = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
- if not definitions:
- continue
- definition = definitions[0]
- machine_manufacturer = identifier.get("manufacturer", definition.get("manufacturer", "Unknown"))
-
-
- new_material_id = self.getId() + "_" + machine_id
-
-
-
-
- if ContainerRegistry.getInstance().isLoaded(new_material_id):
- new_material = ContainerRegistry.getInstance().findContainers(id = new_material_id)[0]
- is_new_material = False
- else:
- new_material = XmlMaterialProfile(new_material_id)
- is_new_material = True
- new_material.setMetaData(copy.deepcopy(self.getMetaData()))
- new_material.getMetaData()["id"] = new_material_id
- new_material.getMetaData()["name"] = self.getName()
- new_material.setDefinition(machine_id)
-
- new_material.getMetaData()["compatible"] = machine_compatibility
- new_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
- new_material.getMetaData()["definition"] = machine_id
- new_material.getMetaData()["reserialize_settings"] = machine_reserialize_settings
- new_material.setCachedValues(cached_machine_setting_properties)
- new_material._dirty = False
- if is_new_material:
- containers_to_add.append(new_material)
- hotends = machine.iterfind("./um:hotend", self.__namespaces)
- for hotend in hotends:
-
- hotend_name = hotend.get("id")
- if hotend_name is None:
- continue
- hotend_mapped_settings, hotend_unmapped_settings, hotend_reserialize_settings = self._getSettingsDictForNode(hotend)
- hotend_compatibility = hotend_unmapped_settings.get("hardware compatible", machine_compatibility)
-
- new_hotend_specific_material_id = self.getId() + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
-
- if ContainerRegistry.getInstance().isLoaded(new_hotend_specific_material_id):
- new_hotend_material = ContainerRegistry.getInstance().findContainers(id = new_hotend_specific_material_id)[0]
- is_new_material = False
- else:
- new_hotend_material = XmlMaterialProfile(new_hotend_specific_material_id)
- is_new_material = True
- new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
- new_hotend_material.getMetaData()["id"] = new_hotend_specific_material_id
- new_hotend_material.getMetaData()["name"] = self.getName()
- new_hotend_material.getMetaData()["variant_name"] = hotend_name
- new_hotend_material.setDefinition(machine_id)
-
- new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
- new_hotend_material.getMetaData()["machine_manufacturer"] = machine_manufacturer
- new_hotend_material.getMetaData()["definition"] = machine_id
- new_hotend_material.getMetaData()["reserialize_settings"] = hotend_reserialize_settings
- cached_hotend_setting_properties = cached_machine_setting_properties.copy()
- cached_hotend_setting_properties.update(hotend_mapped_settings)
- new_hotend_material.setCachedValues(cached_hotend_setting_properties)
- new_hotend_material._dirty = False
- if is_new_material:
- if ContainerRegistry.getInstance().isReadOnly(self.getId()):
- ContainerRegistry.getInstance().setExplicitReadOnly(new_hotend_material.getId())
- containers_to_add.append(new_hotend_material)
-
-
- break
- for container_to_add in containers_to_add:
- ContainerRegistry.getInstance().addContainer(container_to_add)
- @classmethod
- def _getSettingsDictForNode(cls, node) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
- node_mapped_settings_dict: Dict[str, Any] = dict()
- node_unmapped_settings_dict: Dict[str, Any] = dict()
- node_reserialize_settings_dict: Dict[str, Any] = dict()
-
- um_settings = node.iterfind("./um:setting", cls.__namespaces)
- for um_setting_entry in um_settings:
- setting_key = um_setting_entry.get("key")
-
- if setting_key in cls.__material_settings_setting_map:
- if setting_key == "processing temperature graph":
- graph_nodes = um_setting_entry.iterfind("./um:point", cls.__namespaces)
- graph_points = []
- for graph_node in graph_nodes:
- flow = float(graph_node.get("flow"))
- temperature = float(graph_node.get("temperature"))
- graph_points.append([flow, temperature])
- node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = str(
- graph_points)
- else:
- node_mapped_settings_dict[cls.__material_settings_setting_map[setting_key]] = um_setting_entry.text
-
- elif setting_key in cls.__unmapped_settings:
- if setting_key in ("hardware compatible", "hardware recommended"):
- node_unmapped_settings_dict[setting_key] = cls._parseCompatibleValue(um_setting_entry.text)
-
- elif setting_key in cls.__keep_serialized_settings:
- node_reserialize_settings_dict[setting_key] = um_setting_entry.text
-
- else:
- Logger.log("w", "Unsupported material setting %s", setting_key)
-
- cura_settings = node.iterfind("./cura:setting", cls.__namespaces)
- for cura_setting_entry in cura_settings:
- value = cura_setting_entry.text
- if value.lower() == "yes":
- value = True
- elif value.lower() == "no":
- value = False
- key = cura_setting_entry.get("key")
-
- node_mapped_settings_dict[key] = value
- return node_mapped_settings_dict, node_unmapped_settings_dict, node_reserialize_settings_dict
- @classmethod
- def deserializeMetadata(cls, serialized: str, container_id: str) -> List[Dict[str, Any]]:
- result_metadata = []
-
- serialized = cls._updateSerialized(serialized)
- base_metadata = {
- "type": "material",
- "status": "unknown",
- "container_type": XmlMaterialProfile,
- "id": container_id,
- "base_file": container_id
- }
- try:
- data = ET.fromstring(serialized)
- except:
- Logger.logException("e", "An exception occurred while parsing the material profile")
- return []
-
- if "version" in data.attrib:
- base_metadata["setting_version"] = cls.xmlVersionToSettingVersion(data.attrib["version"])
- else:
- base_metadata["setting_version"] = cls.xmlVersionToSettingVersion("1.2")
- for entry in data.iterfind("./um:metadata/*", cls.__namespaces):
- tag_name = _tag_without_namespace(entry)
- if tag_name == "name":
- brand = entry.find("./um:brand", cls.__namespaces)
- material = entry.find("./um:material", cls.__namespaces)
- color = entry.find("./um:color", cls.__namespaces)
- label = entry.find("./um:label", cls.__namespaces)
- if label is not None and label.text is not None:
- base_metadata["name"] = label.text
- else:
- if material is not None and color is not None:
- base_metadata["name"] = cls._profile_name(material.text, color.text)
- else:
- base_metadata["name"] = "Unknown Material"
- base_metadata["brand"] = brand.text if brand is not None and brand.text is not None else "Unknown Brand"
- base_metadata["material"] = material.text if material is not None and material.text is not None else "Unknown Type"
- base_metadata["color_name"] = color.text if color is not None and color.text is not None else "Unknown Color"
- continue
-
- if tag_name == "setting_version":
- continue
- base_metadata[tag_name] = entry.text
- if "description" not in base_metadata:
- base_metadata["description"] = ""
- if "adhesion_info" not in base_metadata:
- base_metadata["adhesion_info"] = ""
- property_values = {}
- properties = data.iterfind("./um:properties/*", cls.__namespaces)
- for entry in properties:
- tag_name = _tag_without_namespace(entry)
- property_values[tag_name] = entry.text
- base_metadata["approximate_diameter"] = str(round(float(cast(float, property_values.get("diameter", 2.85)))))
- base_metadata["properties"] = property_values
- base_metadata["definition"] = "fdmprinter"
-
- base_metadata["visible"] = not base_metadata.get("abstract_color", False)
- compatible_entries = data.iterfind("./um:settings/um:setting[@key='hardware compatible']", cls.__namespaces)
- try:
- common_compatibility = cls._parseCompatibleValue(next(compatible_entries).text)
- except StopIteration:
- common_compatibility = True
- base_metadata["compatible"] = common_compatibility
- result_metadata.append(base_metadata)
-
- product_id_map = cls.getProductIdMap()
- for machine in data.iterfind("./um:settings/um:machine", cls.__namespaces):
- machine_compatibility = common_compatibility
- for entry in machine.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
- if entry.text is not None:
- machine_compatibility = cls._parseCompatibleValue(entry.text)
- for identifier in machine.iterfind("./um:machine_identifier", cls.__namespaces):
- machine_id_list = product_id_map.get(identifier.get("product", ""), [])
- if not machine_id_list:
- machine_id_list = cls.getPossibleDefinitionIDsFromName(identifier.get("product"))
- for machine_id in machine_id_list:
- definition_metadatas = ContainerRegistry.getInstance().findDefinitionContainersMetadata(id = machine_id)
- if not definition_metadatas:
- continue
- definition_metadata = definition_metadatas[0]
- machine_manufacturer = identifier.get("manufacturer", definition_metadata.get("manufacturer", "Unknown"))
-
-
- new_material_id = container_id + "_" + machine_id
-
-
-
-
- new_material_metadata = {}
- new_material_metadata.update(base_metadata)
- new_material_metadata["id"] = new_material_id
- new_material_metadata["compatible"] = machine_compatibility
- new_material_metadata["machine_manufacturer"] = machine_manufacturer
- new_material_metadata["definition"] = machine_id
- result_metadata.append(new_material_metadata)
- buildplates = machine.iterfind("./um:buildplate", cls.__namespaces)
- buildplate_map = {}
- buildplate_map["buildplate_compatible"] = {}
- buildplate_map["buildplate_recommended"] = {}
- for buildplate in buildplates:
- buildplate_id = buildplate.get("id")
- if buildplate_id is None:
- continue
- variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(id = buildplate_id)
- if not variant_metadata:
-
- variant_metadata = ContainerRegistry.getInstance().findInstanceContainersMetadata(definition = machine_id, name = buildplate_id)
- if not variant_metadata:
- continue
- settings = buildplate.iterfind("./um:setting", cls.__namespaces)
- buildplate_compatibility = True
- buildplate_recommended = True
- for entry in settings:
- key = entry.get("key")
- if entry.text is not None:
- if key == "hardware compatible":
- buildplate_compatibility = cls._parseCompatibleValue(entry.text)
- elif key == "hardware recommended":
- buildplate_recommended = cls._parseCompatibleValue(entry.text)
- buildplate_map["buildplate_compatible"][buildplate_id] = buildplate_compatibility
- buildplate_map["buildplate_recommended"][buildplate_id] = buildplate_recommended
- for hotend in machine.iterfind("./um:hotend", cls.__namespaces):
- hotend_name = hotend.get("id")
- if hotend_name is None:
- continue
- hotend_compatibility = machine_compatibility
- for entry in hotend.iterfind("./um:setting[@key='hardware compatible']", cls.__namespaces):
- if entry.text is not None:
- hotend_compatibility = cls._parseCompatibleValue(entry.text)
- new_hotend_specific_material_id = container_id + "_" + machine_id + "_" + hotend_name.replace(" ", "_")
-
- new_hotend_material_metadata = {}
- new_hotend_material_metadata.update(base_metadata)
- new_hotend_material_metadata["variant_name"] = hotend_name
- new_hotend_material_metadata["compatible"] = hotend_compatibility
- new_hotend_material_metadata["machine_manufacturer"] = machine_manufacturer
- new_hotend_material_metadata["id"] = new_hotend_specific_material_id
- new_hotend_material_metadata["definition"] = machine_id
- if buildplate_map["buildplate_compatible"]:
- new_hotend_material_metadata["buildplate_compatible"] = buildplate_map["buildplate_compatible"]
- new_hotend_material_metadata["buildplate_recommended"] = buildplate_map["buildplate_recommended"]
- result_metadata.append(new_hotend_material_metadata)
-
-
-
- buildplates = hotend.iterfind("./um:buildplate", cls.__namespaces)
- for buildplate in buildplates:
-
- buildplate_name = buildplate.get("id")
- if buildplate_name is None:
- continue
- buildplate_mapped_settings, buildplate_unmapped_settings, buildplate_reserialize_settings = cls._getSettingsDictForNode(buildplate)
- buildplate_compatibility = buildplate_unmapped_settings.get("hardware compatible",
- buildplate_map["buildplate_compatible"])
- buildplate_recommended = buildplate_unmapped_settings.get("hardware recommended",
- buildplate_map["buildplate_recommended"])
-
- new_hotend_and_buildplate_specific_material_id = new_hotend_specific_material_id + "_" + buildplate_name.replace(
- " ", "_")
- new_hotend_and_buildplate_material_metadata = {}
- new_hotend_and_buildplate_material_metadata.update(new_hotend_material_metadata)
- new_hotend_and_buildplate_material_metadata["id"] = new_hotend_and_buildplate_specific_material_id
- new_hotend_and_buildplate_material_metadata["buildplate_name"] = buildplate_name
- new_hotend_and_buildplate_material_metadata["compatible"] = buildplate_compatibility
- new_hotend_and_buildplate_material_metadata["buildplate_compatible"] = buildplate_compatibility
- new_hotend_and_buildplate_material_metadata["buildplate_recommended"] = buildplate_recommended
- new_hotend_and_buildplate_material_metadata["reserialize_settings"] = buildplate_reserialize_settings
- result_metadata.append(new_hotend_and_buildplate_material_metadata)
-
-
- break
- return result_metadata
- def _addSettingElement(self, builder, instance):
- key = instance.definition.key
- if key in self.__material_settings_setting_map.values():
-
- key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
- tag_name = "setting"
- if key == "processing temperature graph":
- builder.start(tag_name, {"key": key})
- graph_str = str(instance.value)
- graph = graph_str.replace("[", "").replace("]", "").split(", ")
- graph = [graph[i:i + 2] for i in range(0, len(graph) - 1, 2)]
- for point in graph:
- builder.start("point", {"flow": point[0], "temperature": point[1]})
- builder.end("point")
- builder.end(tag_name)
- return
- elif key not in self.__material_properties_setting_map.values() and key not in self.__material_metadata_setting_map.values():
-
- tag_name = "cura:setting"
- else:
-
- return
- if instance.value is True:
- data = "yes"
- elif instance.value is False:
- data = "no"
- else:
- data = str(instance.value)
- builder.start(tag_name, { "key": key })
- builder.data(data)
- builder.end(tag_name)
- @staticmethod
- def _profile_name(material_name, color_name):
- if material_name is None:
- return "Unknown Material"
- if color_name != "Generic":
- return "%s %s" % (color_name, material_name)
- else:
- return material_name
- @staticmethod
- def getPossibleDefinitionIDsFromName(name):
- name_parts = name.lower().split(" ")
- merged_name_parts = []
- for part in name_parts:
- if len(part) == 0:
- continue
- if len(merged_name_parts) == 0:
- merged_name_parts.append(part)
- continue
- if part.isdigit():
-
-
- merged_name_parts[-1] = merged_name_parts[-1] + part
- else:
- merged_name_parts.append(part)
- id_list = {name.lower().replace(" ", ""),
- name.lower().replace(" ", "_"),
- "_".join(merged_name_parts),
- name.replace(" ", ""),
- name.replace(" ", "_")
- }
- id_list = list(id_list)
- return id_list
- __product_to_id_map: Optional[Dict[str, List[str]]] = None
- @classmethod
- def getProductIdMap(cls) -> Dict[str, List[str]]:
- """Gets a mapping from product names in the XML files to their definition IDs.
- This loads the mapping from a file.
- """
- if cls.__product_to_id_map is not None:
- return cls.__product_to_id_map
- plugin_path = cast(str, PluginRegistry.getInstance().getPluginPath("XmlMaterialProfile"))
- product_to_id_file = os.path.join(plugin_path, "product_to_id.json")
- with open(product_to_id_file, encoding = "utf-8") as f:
- contents = ""
- for line in f:
- contents += line if "#" not in line else "".join([line.replace("#", str(n)) for n in range(1, 12)])
- cls.__product_to_id_map = json.loads(contents)
- cls.__product_to_id_map = {key: [value] for key, value in cls.__product_to_id_map.items()}
-
-
- return cls.__product_to_id_map
- @staticmethod
- def _parseCompatibleValue(value: str):
- """Parse the value of the "material compatible" property."""
- return value in {"yes", "unknown"}
- def __str__(self):
- """Small string representation for debugging."""
- return "<XmlMaterialProfile '{my_id}' ('{name}') from base file '{base_file}'>".format(my_id = self.getId(), name = self.getName(), base_file = self.getMetaDataEntry("base_file"))
- _metadata_tags_that_have_cura_namespace = {"pva_compatible", "breakaway_compatible"}
-
- __material_settings_setting_map = {
- "print temperature": "default_material_print_temperature",
- "heated bed temperature": "default_material_bed_temperature",
- "standby temperature": "material_standby_temperature",
- "processing temperature graph": "material_flow_temp_graph",
- "print cooling": "cool_fan_speed",
- "retraction amount": "retraction_amount",
- "retraction speed": "retraction_speed",
- "adhesion tendency": "material_adhesion_tendency",
- "surface energy": "material_surface_energy",
- "build volume temperature": "build_volume_temperature",
- "anti ooze retract position": "material_anti_ooze_retracted_position",
- "anti ooze retract speed": "material_anti_ooze_retraction_speed",
- "break preparation position": "material_break_preparation_retracted_position",
- "break preparation speed": "material_break_preparation_speed",
- "break preparation temperature": "material_break_preparation_temperature",
- "break position": "material_break_retracted_position",
- "flush purge speed": "material_flush_purge_speed",
- "flush purge length": "material_flush_purge_length",
- "end of filament purge speed": "material_end_of_filament_purge_speed",
- "end of filament purge length": "material_end_of_filament_purge_length",
- "maximum park duration": "material_maximum_park_duration",
- "no load move factor": "material_no_load_move_factor",
- "break speed": "material_break_speed",
- "break temperature": "material_break_temperature"
- }
- __unmapped_settings = [
- "hardware compatible",
- "hardware recommended"
- ]
- __keep_serialized_settings = {
- "relative extrusion",
- "flow sensor detection margin",
- "different material purge volume",
- "same material purge volume",
- "end of print purge volume",
- "end of filament purge volume",
- "purge anti ooze retract position",
- "purge drop retract position",
- "purge retract speed",
- "purge unretract speed",
- "purge anti ooze dwell time",
- "purge drop dwell time",
- "dwell time before break preparation move",
- "pressure release dwell time",
- "tainted print core max temperature",
- "recommend cleaning after n prints",
- "maximum heated bed temperature",
- "material bed adhesion temperature",
- "maximum heated chamber temperature",
- "shrinkage percentage",
- "move to die distance",
- }
- __material_properties_setting_map = {
- "diameter": "material_diameter"
- }
- __material_metadata_setting_map = {
- "GUID": "material_guid"
- }
-
- __namespaces = {
- "um": "http://www.ultimaker.com/material",
- "cura": "http://www.ultimaker.com/cura"
- }
- def _indent(elem, level = 0):
- """Helper function for pretty-printing XML because ETree is stupid"""
- i = "\n" + level * " "
- if len(elem):
- if not elem.text or not elem.text.strip():
- elem.text = i + " "
- if not elem.tail or not elem.tail.strip():
- elem.tail = i
- for elem in elem:
- _indent(elem, level + 1)
- if not elem.tail or not elem.tail.strip():
- elem.tail = i
- else:
- if level and (not elem.tail or not elem.tail.strip()):
- elem.tail = i
- def _tag_without_namespace(element):
- return element.tag[element.tag.rfind("}") + 1:]
|