MachineErrorChecker.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import time
  4. from collections import deque
  5. from PyQt5.QtCore import QObject, QTimer, pyqtSignal, pyqtProperty
  6. from UM.Application import Application
  7. from UM.Logger import Logger
  8. from UM.Settings.SettingDefinition import SettingDefinition
  9. from UM.Settings.Validator import ValidatorState
  10. #
  11. # This class performs setting error checks for the currently active machine.
  12. #
  13. # The whole error checking process is pretty heavy which can take ~0.5 secs, so it can cause GUI to lag.
  14. # The idea here is to split the whole error check into small tasks, each of which only checks a single setting key
  15. # in a stack. According to my profiling results, the maximal runtime for such a sub-task is <0.03 secs, which should
  16. # be good enough. Moreover, if any changes happened to the machine, we can cancel the check in progress without wait
  17. # for it to finish the complete work.
  18. #
  19. class MachineErrorChecker(QObject):
  20. def __init__(self, parent = None):
  21. super().__init__(parent)
  22. self._global_stack = None
  23. self._has_errors = True # Result of the error check, indicating whether there are errors in the stack
  24. self._error_keys = set() # A set of settings keys that have errors
  25. self._error_keys_in_progress = set() # The variable that stores the results of the currently in progress check
  26. self._stacks_and_keys_to_check = None # a FIFO queue of tuples (stack, key) to check for errors
  27. self._need_to_check = False # Whether we need to schedule a new check or not. This flag is set when a new
  28. # error check needs to take place while there is already one running at the moment.
  29. self._check_in_progress = False # Whether there is an error check running in progress at the moment.
  30. self._application = Application.getInstance()
  31. self._machine_manager = self._application.getMachineManager()
  32. self._start_time = 0 # measure checking time
  33. # This timer delays the starting of error check so we can react less frequently if the user is frequently
  34. # changing settings.
  35. self._error_check_timer = QTimer(self)
  36. self._error_check_timer.setInterval(100)
  37. self._error_check_timer.setSingleShot(True)
  38. def initialize(self):
  39. self._error_check_timer.timeout.connect(self._rescheduleCheck)
  40. # Reconnect all signals when the active machine gets changed.
  41. self._machine_manager.globalContainerChanged.connect(self._onMachineChanged)
  42. # Whenever the machine settings get changed, we schedule an error check.
  43. self._machine_manager.globalContainerChanged.connect(self.startErrorCheck)
  44. self._machine_manager.globalValueChanged.connect(self.startErrorCheck)
  45. self._onMachineChanged()
  46. def _onMachineChanged(self):
  47. if self._global_stack:
  48. self._global_stack.propertyChanged.disconnect(self.startErrorCheck)
  49. self._global_stack.containersChanged.disconnect(self.startErrorCheck)
  50. for extruder in self._global_stack.extruders.values():
  51. extruder.propertyChanged.disconnect(self.startErrorCheck)
  52. extruder.containersChanged.disconnect(self.startErrorCheck)
  53. self._global_stack = self._machine_manager.activeMachine
  54. if self._global_stack:
  55. self._global_stack.propertyChanged.connect(self.startErrorCheck)
  56. self._global_stack.containersChanged.connect(self.startErrorCheck)
  57. for extruder in self._global_stack.extruders.values():
  58. extruder.propertyChanged.connect(self.startErrorCheck)
  59. extruder.containersChanged.connect(self.startErrorCheck)
  60. hasErrorUpdated = pyqtSignal()
  61. needToWaitForResultChanged = pyqtSignal()
  62. errorCheckFinished = pyqtSignal()
  63. @pyqtProperty(bool, notify = hasErrorUpdated)
  64. def hasError(self) -> bool:
  65. return self._has_errors
  66. @pyqtProperty(bool, notify = needToWaitForResultChanged)
  67. def needToWaitForResult(self) -> bool:
  68. return self._need_to_check or self._check_in_progress
  69. # Starts the error check timer to schedule a new error check.
  70. def startErrorCheck(self, *args):
  71. if not self._check_in_progress:
  72. self._need_to_check = True
  73. self.needToWaitForResultChanged.emit()
  74. self._error_check_timer.start()
  75. # This function is called by the timer to reschedule a new error check.
  76. # If there is no check in progress, it will start a new one. If there is any, it sets the "_need_to_check" flag
  77. # to notify the current check to stop and start a new one.
  78. def _rescheduleCheck(self):
  79. if self._check_in_progress and not self._need_to_check:
  80. self._need_to_check = True
  81. self.needToWaitForResultChanged.emit()
  82. return
  83. self._error_keys_in_progress = set()
  84. self._need_to_check = False
  85. self.needToWaitForResultChanged.emit()
  86. global_stack = self._machine_manager.activeMachine
  87. if global_stack is None:
  88. Logger.log("i", "No active machine, nothing to check.")
  89. return
  90. # Populate the (stack, key) tuples to check
  91. self._stacks_and_keys_to_check = deque()
  92. for stack in [global_stack] + list(global_stack.extruders.values()):
  93. for key in stack.getAllKeys():
  94. self._stacks_and_keys_to_check.append((stack, key))
  95. self._application.callLater(self._checkStack)
  96. self._start_time = time.time()
  97. Logger.log("d", "New error check scheduled.")
  98. def _checkStack(self):
  99. if self._need_to_check:
  100. Logger.log("d", "Need to check for errors again. Discard the current progress and reschedule a check.")
  101. self._check_in_progress = False
  102. self._application.callLater(self.startErrorCheck)
  103. return
  104. self._check_in_progress = True
  105. # If there is nothing to check any more, it means there is no error.
  106. if not self._stacks_and_keys_to_check:
  107. # Finish
  108. self._setResult(False)
  109. return
  110. # Get the next stack and key to check
  111. stack, key = self._stacks_and_keys_to_check.popleft()
  112. enabled = stack.getProperty(key, "enabled")
  113. if not enabled:
  114. self._application.callLater(self._checkStack)
  115. return
  116. validation_state = stack.getProperty(key, "validationState")
  117. if validation_state is None:
  118. # Setting is not validated. This can happen if there is only a setting definition.
  119. # We do need to validate it, because a setting definitions value can be set by a function, which could
  120. # be an invalid setting.
  121. definition = stack.getSettingDefinition(key)
  122. validator_type = SettingDefinition.getValidatorForType(definition.type)
  123. if validator_type:
  124. validator = validator_type(key)
  125. validation_state = validator(stack)
  126. if validation_state in (ValidatorState.Exception, ValidatorState.MaximumError, ValidatorState.MinimumError):
  127. # Finish
  128. self._setResult(True)
  129. return
  130. # Schedule the check for the next key
  131. self._application.callLater(self._checkStack)
  132. def _setResult(self, result: bool):
  133. if result != self._has_errors:
  134. self._has_errors = result
  135. self.hasErrorUpdated.emit()
  136. self._machine_manager.stacksValidationChanged.emit()
  137. self._need_to_check = False
  138. self._check_in_progress = False
  139. self.needToWaitForResultChanged.emit()
  140. self.errorCheckFinished.emit()
  141. Logger.log("i", "Error check finished, result = %s, time = %0.1fs", result, time.time() - self._start_time)