BackendPlugin.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright (c) 2023 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import subprocess
  4. from typing import Optional, List
  5. from UM.Logger import Logger
  6. from UM.Message import Message
  7. from UM.Settings.AdditionalSettingDefinitionAppender import AdditionalSettingDefinitionsAppender
  8. from UM.PluginObject import PluginObject
  9. from UM.i18n import i18nCatalog
  10. from UM.Platform import Platform
  11. class BackendPlugin(AdditionalSettingDefinitionsAppender, PluginObject):
  12. catalog = i18nCatalog("cura")
  13. def __init__(self) -> None:
  14. super().__init__()
  15. self.__port: int = 0
  16. self._plugin_address: str = "127.0.0.1"
  17. self._plugin_command: Optional[List[str]] = None
  18. self._process = None
  19. self._is_running = False
  20. self._supported_slots: List[int] = []
  21. self._use_plugin = True
  22. def usePlugin(self) -> bool:
  23. return self._use_plugin
  24. def getSupportedSlots(self) -> List[int]:
  25. return self._supported_slots
  26. def isRunning(self):
  27. return self._is_running
  28. def setPort(self, port: int) -> None:
  29. self.__port = port
  30. def getPort(self) -> int:
  31. return self.__port
  32. def getAddress(self) -> str:
  33. return self._plugin_address
  34. def _validatePluginCommand(self) -> list[str]:
  35. """
  36. Validate the plugin command and add the port parameter if it is missing.
  37. :return: A list of strings containing the validated plugin command.
  38. """
  39. if not self._plugin_command or "--port" in self._plugin_command:
  40. return self._plugin_command or []
  41. return self._plugin_command + ["--address", self.getAddress(), "--port", str(self.__port)]
  42. def start(self) -> bool:
  43. """
  44. Starts the backend_plugin process.
  45. :return: True if the plugin process started successfully, False otherwise.
  46. """
  47. if not self.usePlugin():
  48. return False
  49. try:
  50. # STDIN needs to be None because we provide no input, but communicate via a local socket instead.
  51. # The NUL device sometimes doesn't exist on some computers.
  52. Logger.info(f"Starting backend_plugin [{self._plugin_id}] with command: {self._validatePluginCommand()}")
  53. popen_kwargs = {"stdin": None}
  54. if Platform.isWindows():
  55. popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
  56. self._process = subprocess.Popen(self._validatePluginCommand(), **popen_kwargs)
  57. self._is_running = True
  58. return True
  59. except PermissionError:
  60. Logger.log("e", f"Couldn't start EnginePlugin: {self._plugin_id} No permission to execute process.")
  61. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  62. f"Couldn't start EnginePlugin: {self._plugin_id}\nNo permission to execute process."),
  63. message_type = Message.MessageType.ERROR)
  64. except FileNotFoundError:
  65. Logger.logException("e", f"Unable to find local EnginePlugin server executable for: {self._plugin_id}")
  66. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  67. f"Unable to find local EnginePlugin server executable for: {self._plugin_id}"),
  68. message_type = Message.MessageType.ERROR)
  69. except BlockingIOError:
  70. Logger.logException("e", f"Couldn't start EnginePlugin: {self._plugin_id} Resource is temporarily unavailable")
  71. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  72. f"Couldn't start EnginePlugin: {self._plugin_id}\nResource is temporarily unavailable"),
  73. message_type = Message.MessageType.ERROR)
  74. except OSError as e:
  75. Logger.logException("e", f"Couldn't start EnginePlugin {self._plugin_id} Operating system is blocking it (antivirus?)")
  76. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  77. f"Couldn't start EnginePlugin: {self._plugin_id}\nOperating system is blocking it (antivirus?)"),
  78. message_type = Message.MessageType.ERROR)
  79. return False
  80. def stop(self) -> bool:
  81. if not self._process:
  82. self._is_running = False
  83. return True # Nothing to stop
  84. try:
  85. self._process.terminate()
  86. return_code = self._process.wait()
  87. self._is_running = False
  88. Logger.log("d", f"EnginePlugin: {self._plugin_id} was killed. Received return code {return_code}")
  89. return True
  90. except PermissionError:
  91. Logger.log("e", f"Unable to kill running EnginePlugin: {self._plugin_id} Access is denied.")
  92. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  93. f"Unable to kill running EnginePlugin: {self._plugin_id}\nAccess is denied."),
  94. message_type = Message.MessageType.ERROR)
  95. return False
  96. def _showMessage(self, message: str, message_type: Message.MessageType = Message.MessageType.ERROR) -> None:
  97. Message(message, title=self.catalog.i18nc("@info:title", "EnginePlugin"), message_type = message_type).show()