Script.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # Copyright (c) 2015 Jaime van Kessel
  2. # Copyright (c) 2018 Ultimaker B.V.
  3. # The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.
  4. from UM.Signal import Signal, signalemitter
  5. from UM.i18n import i18nCatalog
  6. # Setting stuff import
  7. from UM.Application import Application
  8. from UM.Settings.ContainerFormatError import ContainerFormatError
  9. from UM.Settings.ContainerStack import ContainerStack
  10. from UM.Settings.InstanceContainer import InstanceContainer
  11. from UM.Settings.DefinitionContainer import DefinitionContainer
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. import re
  14. import json
  15. import collections
  16. i18n_catalog = i18nCatalog("cura")
  17. ## Base class for scripts. All scripts should inherit the script class.
  18. @signalemitter
  19. class Script:
  20. def __init__(self):
  21. super().__init__()
  22. self._settings = None
  23. self._stack = None
  24. setting_data = self.getSettingData()
  25. self._stack = ContainerStack(stack_id = str(id(self)))
  26. self._stack.setDirty(False) # This stack does not need to be saved.
  27. ## Check if the definition of this script already exists. If not, add it to the registry.
  28. if "key" in setting_data:
  29. definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = setting_data["key"])
  30. if definitions:
  31. # Definition was found
  32. self._definition = definitions[0]
  33. else:
  34. self._definition = DefinitionContainer(setting_data["key"])
  35. try:
  36. self._definition.deserialize(json.dumps(setting_data))
  37. ContainerRegistry.getInstance().addContainer(self._definition)
  38. except ContainerFormatError:
  39. self._definition = None
  40. return
  41. self._stack.addContainer(self._definition)
  42. self._instance = InstanceContainer(container_id="ScriptInstanceContainer")
  43. self._instance.setDefinition(self._definition.getId())
  44. self._instance.addMetaDataEntry("setting_version", self._definition.getMetaDataEntry("setting_version", default = 0))
  45. self._stack.addContainer(self._instance)
  46. self._stack.propertyChanged.connect(self._onPropertyChanged)
  47. ContainerRegistry.getInstance().addContainer(self._stack)
  48. settingsLoaded = Signal()
  49. valueChanged = Signal() # Signal emitted whenever a value of a setting is changed
  50. def _onPropertyChanged(self, key, property_name):
  51. if property_name == "value":
  52. self.valueChanged.emit()
  53. # Property changed: trigger reslice
  54. # To do this we use the global container stack propertyChanged.
  55. # Reslicing is necessary for setting changes in this plugin, because the changes
  56. # are applied only once per "fresh" gcode
  57. global_container_stack = Application.getInstance().getGlobalContainerStack()
  58. global_container_stack.propertyChanged.emit(key, property_name)
  59. ## Needs to return a dict that can be used to construct a settingcategory file.
  60. # See the example script for an example.
  61. # It follows the same style / guides as the Uranium settings.
  62. # Scripts can either override getSettingData directly, or use getSettingDataString
  63. # to return a string that will be parsed as json. The latter has the benefit over
  64. # returning a dict in that the order of settings is maintained.
  65. def getSettingData(self):
  66. setting_data = self.getSettingDataString()
  67. if type(setting_data) == str:
  68. setting_data = json.loads(setting_data, object_pairs_hook = collections.OrderedDict)
  69. return setting_data
  70. def getSettingDataString(self):
  71. raise NotImplementedError()
  72. def getDefinitionId(self):
  73. if self._stack:
  74. return self._stack.getBottom().getId()
  75. def getStackId(self):
  76. if self._stack:
  77. return self._stack.getId()
  78. ## Convenience function that retrieves value of a setting from the stack.
  79. def getSettingValueByKey(self, key):
  80. return self._stack.getProperty(key, "value")
  81. ## Convenience function that finds the value in a line of g-code.
  82. # When requesting key = x from line "G1 X100" the value 100 is returned.
  83. def getValue(self, line, key, default = None):
  84. if not key in line or (';' in line and line.find(key) > line.find(';')):
  85. return default
  86. sub_part = line[line.find(key) + 1:]
  87. m = re.search('^-?[0-9]+\.?[0-9]*', sub_part)
  88. if m is None:
  89. return default
  90. try:
  91. return float(m.group(0))
  92. except:
  93. return default
  94. ## Convenience function to produce a line of g-code.
  95. #
  96. # You can put in an original g-code line and it'll re-use all the values
  97. # in that line.
  98. # All other keyword parameters are put in the result in g-code's format.
  99. # For instance, if you put ``G=1`` in the parameters, it will output
  100. # ``G1``. If you put ``G=1, X=100`` in the parameters, it will output
  101. # ``G1 X100``. The parameters G and M will always be put first. The
  102. # parameters T and S will be put second (or first if there is no G or M).
  103. # The rest of the parameters will be put in arbitrary order.
  104. # \param line The original g-code line that must be modified. If not
  105. # provided, an entirely new g-code line will be produced.
  106. # \return A line of g-code with the desired parameters filled in.
  107. def putValue(self, line = "", **kwargs):
  108. #Strip the comment.
  109. comment = ""
  110. if ";" in line:
  111. comment = line[line.find(";"):]
  112. line = line[:line.find(";")] #Strip the comment.
  113. #Parse the original g-code line.
  114. for part in line.split(" "):
  115. if part == "":
  116. continue
  117. parameter = part[0]
  118. if parameter in kwargs:
  119. continue #Skip this one. The user-provided parameter overwrites the one in the line.
  120. value = part[1:]
  121. kwargs[parameter] = value
  122. #Write the new g-code line.
  123. result = ""
  124. priority_parameters = ["G", "M", "T", "S", "F", "X", "Y", "Z", "E"] #First some parameters that get priority. In order of priority!
  125. for priority_key in priority_parameters:
  126. if priority_key in kwargs:
  127. if result != "":
  128. result += " "
  129. result += priority_key + str(kwargs[priority_key])
  130. del kwargs[priority_key]
  131. for key, value in kwargs.items():
  132. if result != "":
  133. result += " "
  134. result += key + str(value)
  135. #Put the comment back in.
  136. if comment != "":
  137. if result != "":
  138. result += " "
  139. result += ";" + comment
  140. return result
  141. ## This is called when the script is executed.
  142. # It gets a list of g-code strings and needs to return a (modified) list.
  143. def execute(self, data):
  144. raise NotImplementedError()