Script.py 7.8 KB

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