Welcome to mirror list, hosted at ThFree Co, Russian Federation.

XmlMaterialProfile.py « XmlMaterialProfile « plugins - github.com/Ultimaker/Cura.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 04fc09019b75c7544a5a85730e4b65c079ebbe95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

import copy
import io
from typing import Optional
import xml.etree.ElementTree as ET

from UM.Resources import Resources
from UM.Logger import Logger
from UM.Util import parseBool
from cura.CuraApplication import CuraApplication

import UM.Dictionary
from UM.Settings.InstanceContainer import InstanceContainer, InvalidInstanceError
from UM.Settings.ContainerRegistry import ContainerRegistry
from cura.Settings.CuraContainerRegistry import CuraContainerRegistry


##  Handles serializing and deserializing material containers from an XML file
class XmlMaterialProfile(InstanceContainer):
    CurrentFdmMaterialVersion = "1.3"
    Version = 1

    def __init__(self, container_id, *args, **kwargs):
        super().__init__(container_id, *args, **kwargs)
        self._inherited_files = []

    ##  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.
    def xmlVersionToSettingVersion(self, xml_version: str) -> int:
        if xml_version == "1.3":
            return 1
        return 0 #Older than 1.3.

    def getInheritedFiles(self):
        return self._inherited_files

    ##  Overridden from InstanceContainer
    def setReadOnly(self, read_only):
        super().setReadOnly(read_only)

        basefile = self.getMetaDataEntry("base_file", self._id)  # if basefile is self.id, this is a basefile.
        for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
            container._read_only = read_only  # prevent loop instead of calling setReadOnly

    ##  Overridden from InstanceContainer
    #   set the meta data for all machine / variant combinations
    def setMetaDataEntry(self, key, value):
        if self.isReadOnly():
            return

        super().setMetaDataEntry(key, value)

        basefile = self.getMetaDataEntry("base_file", self._id)  #if basefile is self.id, this is a basefile.
        # Update all containers that share basefile
        for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
            if container.getMetaDataEntry(key, None) != value: # Prevent recursion
                container.setMetaDataEntry(key, value)

    ##  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.
    def setName(self, new_name):
        if self.isReadOnly():
            return

        # Not only is this faster, it also prevents a major loop that causes a stack overflow.
        if self.getName() == new_name:
            return

        super().setName(new_name)

        basefile = self.getMetaDataEntry("base_file", self._id)  # if basefile is self.id, this is a basefile.
        # Update the basefile as well, this is actually what we're trying to do
        # Update all containers that share GUID and basefile
        containers = ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile)
        for container in containers:
            container.setName(new_name)

    ##  Overridden from InstanceContainer, to set dirty to base file as well.
    def setDirty(self, dirty):
        super().setDirty(dirty)
        base_file = self.getMetaDataEntry("base_file", None)
        if base_file is not None and base_file != self._id:
            containers = ContainerRegistry.getInstance().findContainers(id=base_file)
            if containers:
                base_container = containers[0]
                if not base_container.isReadOnly():
                    base_container.setDirty(dirty)

    ##  Overridden from InstanceContainer
    # def setProperty(self, key, property_name, property_value, container = None):
    #     if self.isReadOnly():
    #         return
    #
    #     super().setProperty(key, property_name, property_value)
    #
    #     basefile = self.getMetaDataEntry("base_file", self._id)  #if basefile is self.id, this is a basefile.
    #     for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
    #         if not container.isReadOnly():
    #             container.setDirty(True)

    ##  Overridden from InstanceContainer
    # base file: common settings + supported machines
    # machine / variant combination: only changes for itself.
    def serialize(self):
        registry = ContainerRegistry.getInstance()

        base_file = self.getMetaDataEntry("base_file", "")
        if base_file and self.id != base_file:
            # Since we create an instance of XmlMaterialProfile for each machine and nozzle in the profile,
            # we should only serialize the "base" material definition, since that can then take care of
            # serializing the machine/nozzle specific profiles.
            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",
                              "version": self.CurrentFdmMaterialVersion})

        ## Begin Metadata Block
        builder.start("metadata")

        metadata = copy.deepcopy(self.getMetaData())
        properties = metadata.pop("properties", {})

        # Metadata properties that should not be serialized.
        metadata.pop("status", "")
        metadata.pop("variant", "")
        metadata.pop("type", "")
        metadata.pop("base_file", "")
        metadata.pop("approximate_diameter", "")

        ## Begin Name Block
        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._name)
        builder.end("label")

        builder.end("name")
        ## End Name Block

        for key, value in metadata.items():
            builder.start(key)
            if value is not None: #Nones get handled well by the builder.
                #Otherwise the builder always expects a string.
                #Deserialize expects the stringified version.
                value = str(value)
            builder.data(value)
            builder.end(key)

        builder.end("metadata")
        ## End Metadata Block

        ## Begin Properties Block
        builder.start("properties")

        for key, value in properties.items():
            builder.start(key)
            builder.data(value)
            builder.end(key)

        builder.end("properties")
        ## End Properties Block

        ## Begin Settings Block
        builder.start("settings")

        if self.getDefinition().id == "fdmprinter":
            for instance in self.findInstances():
                self._addSettingElement(builder, instance)

        machine_container_map = {}
        machine_nozzle_map = {}

        all_containers = registry.findInstanceContainers(GUID = self.getMetaDataEntry("GUID"), base_file = self._id)
        for container in all_containers:
            definition_id = container.getDefinition().id
            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_nozzle_map:
                machine_nozzle_map[definition_id] = {}

            variant = container.getMetaDataEntry("variant")
            if variant:
                machine_nozzle_map[definition_id][variant] = container
                continue

            machine_container_map[definition_id] = container

        for definition_id, container in machine_container_map.items():
            definition = container.getDefinition()
            try:
                product = UM.Dictionary.findKey(self.__product_id_map, definition_id)
            except ValueError:
                # An unknown product id; export it anyway
                product = definition_id

            builder.start("machine")
            builder.start("machine_identifier", { "manufacturer": definition.getMetaDataEntry("manufacturer", ""), "product":  product})
            builder.end("machine_identifier")

            for instance in container.findInstances():
                if self.getDefinition().id == "fdmprinter" and self.getInstance(instance.definition.key) and self.getProperty(instance.definition.key, "value") == instance.value:
                    # If the settings match that of the base profile, just skip since we inherit the base profile.
                    continue

                self._addSettingElement(builder, instance)

            # Find all hotend sub-profiles corresponding to this material and machine and add them to this profile.
            for hotend_id, hotend in machine_nozzle_map[definition_id].items():
                variant_containers = registry.findInstanceContainers(id = hotend.getMetaDataEntry("variant"))
                if not variant_containers:
                    continue

                builder.start("hotend", {"id": variant_containers[0].getName()})

                # Compatible is a special case, as it's added as a meta data entry (instead of an instance).
                compatible = hotend.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 hotend.findInstances():
                    if container.getInstance(instance.definition.key) and container.getProperty(instance.definition.key, "value") == instance.value:
                        # If the settings match that of the machine profile, just skip since we inherit the machine profile.
                        continue

                    self._addSettingElement(builder, instance)

                builder.end("hotend")

            builder.end("machine")

        builder.end("settings")
        ## End Settings Block

        builder.end("fdmmaterial")

        root = builder.close()
        _indent(root)
        stream = io.BytesIO()
        tree = ET.ElementTree(root)
        # this makes sure that the XML header states encoding="utf-8"
        tree.write(stream, encoding="utf-8", xml_declaration=True)

        return stream.getvalue().decode('utf-8')

    # Recursively resolve loading inherited files
    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)

    # The XML material profile can have specific settings for machines.
    # Some machines share profiles, so they are only created once.
    # This function duplicates those elements so that each machine tag only has one identifier.
    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:
                # Multiple identifiers found. We need to create a new machine element and copy all it's settings there.
                for identifier in identifiers:
                    new_machine = copy.deepcopy(machine)
                    # Create list of identifiers that need to be removed from the copied element.
                    other_identifiers = [self._createKey(other_identifier) for other_identifier in identifiers if other_identifier is not identifier]
                    # As we can only remove by exact object reference, we need to look through the identifiers of copied machine.
                    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)
                        # Key was in identifiers to remove, so this element needs to be purged
                        if key in other_identifiers:
                            new_machine.remove(new_machine_identifier)
                    machines_to_add.append(new_machine)
                machines_to_remove.append(machine)
            else:
                pass  # Machine only has one identifier. Nothing to do.
        # Remove & add all required machines.
        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

    def _createKey(self, 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

    # Recursively merges XML elements. Updates either the text or children if another element is found in first.
    # If it does not exist, copies it from second.
    def _combineElement(self, first, second):
        # Create a mapping from tag name to element.

        mapping = {}
        for element in first:
            key = self._createKey(element)
            mapping[key] = element
        for element in second:
            key = self._createKey(element)
            if len(element):  # Check if element has children.
                try:
                    if "setting" in element.tag and not "settings" in element.tag:
                        # Setting can have points in it. In that case, delete all values and override them.
                        for child in list(mapping[key]):
                            mapping[key].remove(child)
                        for child in element:
                            mapping[key].append(child)
                    else:
                        self._combineElement(mapping[key], element)  # Multiple elements, handle those.
                except KeyError:
                    mapping[key] = element
                    first.append(element)
            else:
                try:
                    mapping[key].text = element.text
                except KeyError:  # Not in the mapping, so simply add it
                    mapping[key] = element
                    first.append(element)

    def clearData(self):
        self._metadata = {}
        self._name = ""
        self._definition = None
        self._instances = {}
        self._read_only = False
        self._dirty = False
        self._path = ""

    def getConfigurationTypeFromSerialized(self, serialized: str) -> Optional[str]:
        return "materials"

    def getVersionFromSerialized(self, serialized: str) -> Optional[int]:
        data = ET.fromstring(serialized)

        version = 1
        # get setting version
        if "version" in data.attrib:
            setting_version = self.xmlVersionToSettingVersion(data.attrib["version"])
        else:
            setting_version = self.xmlVersionToSettingVersion("1.2")

        return version * 1000000 + setting_version

    ##  Overridden from InstanceContainer
    def deserialize(self, serialized):
        # update the serialized data first
        from UM.Settings.Interfaces import ContainerInterface
        serialized = ContainerInterface.deserialize(self, serialized)

        try:
            data = ET.fromstring(serialized)
        except:
            Logger.logException("e", "An exception occured while parsing the material profile")
            return

        # Reset previous metadata
        self.clearData() # Ensure any previous data is gone.
        meta_data = {}
        meta_data["type"] = "material"
        meta_data["base_file"] = self.id
        meta_data["status"] = "unknown"  # TODO: Add material verfication

        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") #1.2 and lower didn't have that version number there yet.
        metadata = data.iterfind("./um:metadata/*", self.__namespaces)
        for entry in metadata:
            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:
                    self._name = label.text
                else:
                    self._name = self._profile_name(material.text, color.text)
                meta_data["brand"] = brand.text
                meta_data["material"] = material.text
                meta_data["color_name"] = color.text
                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"] = ""

        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)))) # In mm
        meta_data["properties"] = property_values

        self.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])

        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:
                common_setting_values[self.__material_settings_setting_map[key]] = entry.text
            elif key in self.__unmapped_settings:
                if key == "hardware compatible":
                    common_compatibility = parseBool(entry.text)
            else:
                Logger.log("d", "Unsupported material setting %s", key)
        self._cached_values = common_setting_values # from InstanceContainer ancestor

        meta_data["compatible"] = common_compatibility
        self.setMetaData(meta_data)
        self._dirty = False

        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)
            for entry in settings:
                key = entry.get("key")
                if key in self.__material_settings_setting_map:
                    machine_setting_values[self.__material_settings_setting_map[key]] = entry.text
                elif key in self.__unmapped_settings:
                    if key == "hardware compatible":
                        machine_compatibility = parseBool(entry.text)
                else:
                    Logger.log("d", "Unsupported material setting %s", key)

            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 = self.__product_id_map.get(identifier.get("product"), None)
                if machine_id is None:
                    # Lets try again with some naive heuristics.
                    machine_id = identifier.get("product").replace(" ", "").lower()

                definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
                if not definitions:
                    Logger.log("w", "No definition found for machine ID %s", machine_id)
                    continue

                definition = definitions[0]

                if machine_compatibility:
                    new_material_id = self.id + "_" + machine_id

                    new_material = XmlMaterialProfile(new_material_id)

                    # Update the private directly, as we want to prevent the lookup that is done when using setName
                    new_material._name = self.getName()
                    new_material.setMetaData(copy.deepcopy(self.getMetaData()))
                    new_material.setDefinition(definition)
                    # Don't use setMetadata, as that overrides it for all materials with same base file
                    new_material.getMetaData()["compatible"] = machine_compatibility

                    new_material.setCachedValues(cached_machine_setting_properties)

                    new_material._dirty = False

                    ContainerRegistry.getInstance().addContainer(new_material)

                hotends = machine.iterfind("./um:hotend", self.__namespaces)
                for hotend in hotends:
                    hotend_id = hotend.get("id")
                    if hotend_id is None:
                        continue

                    variant_containers = ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
                    if not variant_containers:
                        # It is not really properly defined what "ID" is so also search for variants by name.
                        variant_containers = ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)

                    if not variant_containers:
                        #Logger.log("d", "No variants found with ID or name %s for machine %s", hotend_id, definition.id)
                        continue

                    hotend_compatibility = machine_compatibility
                    hotend_setting_values = {}
                    settings = hotend.iterfind("./um:setting", self.__namespaces)
                    for entry in settings:
                        key = entry.get("key")
                        if key in self.__material_settings_setting_map:
                            hotend_setting_values[self.__material_settings_setting_map[key]] = entry.text
                        elif key in self.__unmapped_settings:
                            if key == "hardware compatible":
                                hotend_compatibility = parseBool(entry.text)
                        else:
                            Logger.log("d", "Unsupported material setting %s", key)

                    new_hotend_id = self.id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")

                    new_hotend_material = XmlMaterialProfile(new_hotend_id)

                    # Update the private directly, as we want to prevent the lookup that is done when using setName
                    new_hotend_material._name = self.getName()
                    new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
                    new_hotend_material.setDefinition(definition)
                    new_hotend_material.addMetaDataEntry("variant", variant_containers[0].id)
                    # Don't use setMetadata, as that overrides it for all materials with same base file
                    new_hotend_material.getMetaData()["compatible"] = hotend_compatibility

                    cached_hotend_setting_properties = cached_machine_setting_properties.copy()
                    cached_hotend_setting_properties.update(hotend_setting_values)

                    new_hotend_material.setCachedValues(cached_hotend_setting_properties)

                    new_hotend_material._dirty = False

                    ContainerRegistry.getInstance().addContainer(new_hotend_material)

    def _addSettingElement(self, builder, instance):
        try:
            key = UM.Dictionary.findKey(self.__material_settings_setting_map, instance.definition.key)
        except ValueError:
            return

        builder.start("setting", { "key": key })
        builder.data(str(instance.value))
        builder.end("setting")

    def _profile_name(self, material_name, color_name):
        if color_name != "Generic":
            return "%s %s" % (color_name, material_name)
        else:
            return material_name

    # Map XML file setting names to internal names
    __material_settings_setting_map = {
        "print temperature": "default_material_print_temperature",
        "heated bed temperature": "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"
    }
    __unmapped_settings = [
        "hardware compatible"
    ]
    __material_properties_setting_map = {
        "diameter": "material_diameter"
    }
    __material_metadata_setting_map = {
        "GUID": "material_guid"
    }

    # Map XML file product names to internal ids
    # TODO: Move this to definition's metadata
    __product_id_map = {
        "Ultimaker 3": "ultimaker3",
        "Ultimaker 3 Extended": "ultimaker3_extended",
        "Ultimaker 2": "ultimaker2",
        "Ultimaker 2+": "ultimaker2_plus",
        "Ultimaker 2 Go": "ultimaker2_go",
        "Ultimaker 2 Extended": "ultimaker2_extended",
        "Ultimaker 2 Extended+": "ultimaker2_extended_plus",
        "Ultimaker Original": "ultimaker_original",
        "Ultimaker Original+": "ultimaker_original_plus",
        "IMADE3D JellyBOX": "imade3d_jellybox"
    }

    # Map of recognised namespaces with a proper prefix.
    __namespaces = {
        "um": "http://www.ultimaker.com/material"
    }

##  Helper function for pretty-printing XML because ETree is stupid
def _indent(elem, level = 0):
    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


# The namespace is prepended to the tag name but between {}.
# We are only interested in the actual tag name, so discard everything
# before the last }
def _tag_without_namespace(element):
    return element.tag[element.tag.rfind("}") + 1:]