SingleInstance.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import os
  5. from typing import List, Optional
  6. from PyQt5.QtNetwork import QLocalServer, QLocalSocket
  7. from UM.Qt.QtApplication import QtApplication #For typing.
  8. from UM.Logger import Logger
  9. class SingleInstance:
  10. def __init__(self, application: QtApplication, files_to_open: Optional[List[str]]) -> None:
  11. self._application = application
  12. self._files_to_open = files_to_open
  13. self._single_instance_server = None
  14. self._application.getPreferences().addPreference("cura/single_instance_clear_before_load", True)
  15. # Starts a client that checks for a single instance server and sends the files that need to opened if the server
  16. # exists. Returns True if the single instance server is found, otherwise False.
  17. def startClient(self) -> bool:
  18. Logger.log("i", "Checking for the presence of an ready running Cura instance.")
  19. single_instance_socket = QLocalSocket(self._application)
  20. Logger.log("d", "Full single instance server name: %s", single_instance_socket.fullServerName())
  21. single_instance_socket.connectToServer("ultimaker-cura")
  22. single_instance_socket.waitForConnected(msecs = 3000) # wait for 3 seconds
  23. if single_instance_socket.state() != QLocalSocket.ConnectedState:
  24. return False
  25. # We only send the files that need to be opened.
  26. if not self._files_to_open:
  27. Logger.log("i", "No file need to be opened, do nothing.")
  28. return True
  29. if single_instance_socket.state() == QLocalSocket.ConnectedState:
  30. Logger.log("i", "Connection has been made to the single-instance Cura socket.")
  31. # Protocol is one line of JSON terminated with a carriage return.
  32. # "command" field is required and holds the name of the command to execute.
  33. # Other fields depend on the command.
  34. if self._application.getPreferences().getValue("cura/single_instance_clear_before_load"):
  35. payload = {"command": "clear-all"}
  36. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
  37. payload = {"command": "focus"}
  38. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
  39. for filename in self._files_to_open:
  40. payload = {"command": "open", "filePath": os.path.abspath(filename)}
  41. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
  42. payload = {"command": "close-connection"}
  43. single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
  44. single_instance_socket.flush()
  45. single_instance_socket.waitForDisconnected()
  46. return True
  47. def startServer(self) -> None:
  48. self._single_instance_server = QLocalServer()
  49. if self._single_instance_server:
  50. self._single_instance_server.newConnection.connect(self._onClientConnected)
  51. self._single_instance_server.listen("ultimaker-cura")
  52. else:
  53. Logger.log("e", "Single instance server was not created.")
  54. def _onClientConnected(self) -> None:
  55. Logger.log("i", "New connection received on our single-instance server")
  56. connection = None #type: Optional[QLocalSocket]
  57. if self._single_instance_server:
  58. connection = self._single_instance_server.nextPendingConnection()
  59. if connection is not None:
  60. connection.readyRead.connect(lambda c = connection: self.__readCommands(c))
  61. def __readCommands(self, connection: QLocalSocket) -> None:
  62. line = connection.readLine()
  63. while len(line) != 0: # There is also a .canReadLine()
  64. try:
  65. payload = json.loads(str(line, encoding = "ascii").strip())
  66. command = payload["command"]
  67. # Command: Remove all models from the build plate.
  68. if command == "clear-all":
  69. self._application.callLater(lambda: self._application.deleteAll())
  70. # Command: Load a model or project file
  71. elif command == "open":
  72. self._application.callLater(lambda f = payload["filePath"]: self._application._openFile(f))
  73. # Command: Activate the window and bring it to the top.
  74. elif command == "focus":
  75. # Operating systems these days prevent windows from moving around by themselves.
  76. # 'alert' or flashing the icon in the taskbar is the best thing we do now.
  77. main_window = self._application.getMainWindow()
  78. if main_window is not None:
  79. self._application.callLater(lambda: main_window.alert(0)) # type: ignore # I don't know why MyPy complains here
  80. # Command: Close the socket connection. We're done.
  81. elif command == "close-connection":
  82. connection.close()
  83. else:
  84. Logger.log("w", "Received an unrecognized command " + str(command))
  85. except json.decoder.JSONDecodeError as ex:
  86. Logger.log("w", "Unable to parse JSON command '%s': %s", line, repr(ex))
  87. line = connection.readLine()