RemovableDriveOutputDevice.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. import os.path
  5. from UM.Application import Application
  6. from UM.Logger import Logger
  7. from UM.Message import Message
  8. from UM.FileHandler.WriteFileJob import WriteFileJob
  9. from UM.FileHandler.FileWriter import FileWriter # To check against the write modes (text vs. binary).
  10. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  11. from UM.OutputDevice.OutputDevice import OutputDevice
  12. from UM.OutputDevice import OutputDeviceError
  13. from UM.i18n import i18nCatalog
  14. catalog = i18nCatalog("cura")
  15. class RemovableDriveOutputDevice(OutputDevice):
  16. def __init__(self, device_id, device_name):
  17. super().__init__(device_id)
  18. self.setName(device_name)
  19. self.setShortDescription(catalog.i18nc("@action:button Preceded by 'Ready to'.", "Save to Removable Drive"))
  20. self.setDescription(catalog.i18nc("@item:inlistbox", "Save to Removable Drive {0}").format(device_name))
  21. self.setIconName("save_sd")
  22. self.setPriority(1)
  23. self._writing = False
  24. self._stream = None
  25. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  26. """Request the specified nodes to be written to the removable drive.
  27. :param nodes: A collection of scene nodes that should be written to the
  28. removable drive.
  29. :param file_name: :type{string} A suggestion for the file name to write to.
  30. If none is provided, a file name will be made from the names of the
  31. meshes.
  32. :param limit_mimetypes: Should we limit the available MIME types to the
  33. MIME types available to the currently active machine?
  34. """
  35. filter_by_machine = True # This plugin is intended to be used by machine (regardless of what it was told to do)
  36. if self._writing:
  37. raise OutputDeviceError.DeviceBusyError()
  38. # Formats supported by this application (File types that we can actually write)
  39. if file_handler:
  40. file_formats = file_handler.getSupportedFileTypesWrite()
  41. else:
  42. file_formats = Application.getInstance().getMeshFileHandler().getSupportedFileTypesWrite()
  43. if filter_by_machine:
  44. container = Application.getInstance().getGlobalContainerStack().findContainer({"file_formats": "*"})
  45. # Create a list from supported file formats string
  46. machine_file_formats = [file_type.strip() for file_type in container.getMetaDataEntry("file_formats").split(";")]
  47. # Take the intersection between file_formats and machine_file_formats.
  48. format_by_mimetype = {format["mime_type"]: format for format in file_formats}
  49. file_formats = [format_by_mimetype[mimetype] for mimetype in machine_file_formats if mimetype in format_by_mimetype] # Keep them ordered according to the preference in machine_file_formats.
  50. if len(file_formats) == 0:
  51. Logger.log("e", "There are no file formats available to write with!")
  52. raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status", "There are no file formats available to write with!"))
  53. preferred_format = file_formats[0]
  54. # Just take the first file format available.
  55. if file_handler is not None:
  56. writer = file_handler.getWriterByMimeType(preferred_format["mime_type"])
  57. else:
  58. writer = Application.getInstance().getMeshFileHandler().getWriterByMimeType(preferred_format["mime_type"])
  59. extension = preferred_format["extension"]
  60. if file_name is None:
  61. file_name = self._automaticFileName(nodes)
  62. if extension: # Not empty string.
  63. extension = "." + extension
  64. file_name = os.path.join(self.getId(), file_name + extension)
  65. self._performWrite(file_name, preferred_format, writer, nodes)
  66. def _performWrite(self, file_name, preferred_format, writer, nodes):
  67. """Writes the specified nodes to the removable drive. This is split from
  68. requestWrite to allow interception in other plugins. See Ultimaker/Cura#10917.
  69. :param file_name: File path to write to.
  70. :param preferred_format: Preferred file format to write to.
  71. :param writer: Writer for writing to the file.
  72. :param nodes: A collection of scene nodes that should be written to the
  73. file.
  74. """
  75. try:
  76. Logger.log("d", "Writing to %s", file_name)
  77. # Using buffering greatly reduces the write time for many lines of gcode
  78. if preferred_format["mode"] == FileWriter.OutputMode.TextMode:
  79. self._stream = open(file_name, "wt", buffering = 1, encoding = "utf-8")
  80. else: #Binary mode.
  81. self._stream = open(file_name, "wb", buffering = 1)
  82. job = WriteFileJob(writer, self._stream, nodes, preferred_format["mode"])
  83. job.setFileName(file_name)
  84. job.progress.connect(self._onProgress)
  85. job.finished.connect(self._onFinished)
  86. message = Message(catalog.i18nc("@info:progress Don't translate the XML tags <filename>!",
  87. "Saving to Removable Drive <filename>{0}</filename>").format(self.getName()),
  88. 0, False, -1, catalog.i18nc("@info:title", "Saving"))
  89. message.show()
  90. self.writeStarted.emit(self)
  91. job.setMessage(message)
  92. self._writing = True
  93. job.start()
  94. except PermissionError as e:
  95. Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
  96. raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format(file_name, str(e))) from e
  97. except OSError as e:
  98. Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
  99. raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format(file_name, str(e))) from e
  100. def _automaticFileName(self, nodes):
  101. """Generate a file name automatically for the specified nodes to be saved in.
  102. The name generated will be the name of one of the nodes. Which node that
  103. is can not be guaranteed.
  104. :param nodes: A collection of nodes for which to generate a file name.
  105. """
  106. for root in nodes:
  107. for child in BreadthFirstIterator(root):
  108. if child.getMeshData():
  109. name = child.getName()
  110. if name:
  111. return name
  112. raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status Don't translate the tag {device}!", "Could not find a file name when trying to write to {device}.").format(device = self.getName()))
  113. def _onProgress(self, job, progress):
  114. self.writeProgress.emit(self, progress)
  115. def _onFinished(self, job):
  116. if self._stream:
  117. error = job.getError()
  118. try:
  119. # Explicitly closing the stream flushes the write-buffer
  120. self._stream.close()
  121. except Exception as e:
  122. if not error:
  123. # Only log new error if there was no previous one
  124. error = e
  125. self._stream = None
  126. self._writing = False
  127. self.writeFinished.emit(self)
  128. if not error:
  129. message = Message(
  130. catalog.i18nc("@info:status", "Saved to Removable Drive {0} as {1}").format(self.getName(),
  131. os.path.basename(
  132. job.getFileName())),
  133. title=catalog.i18nc("@info:title", "File Saved"),
  134. message_type=Message.MessageType.POSITIVE)
  135. message.addAction("eject", catalog.i18nc("@action:button", "Eject"), "eject",
  136. catalog.i18nc("@action", "Eject removable device {0}").format(self.getName()))
  137. message.actionTriggered.connect(self._onActionTriggered)
  138. message.show()
  139. self.writeSuccess.emit(self)
  140. else:
  141. try:
  142. os.remove(job.getFileName())
  143. except Exception as e:
  144. Logger.logException("e", "Exception when trying to remove incomplete exported file %s",
  145. str(job.getFileName()))
  146. message = Message(catalog.i18nc("@info:status",
  147. "Could not save to removable drive {0}: {1}").format(self.getName(),
  148. str(job.getError())),
  149. title=catalog.i18nc("@info:title", "Error"),
  150. message_type=Message.MessageType.ERROR)
  151. message.show()
  152. self.writeError.emit(self)
  153. def _onActionTriggered(self, message, action):
  154. if action == "eject":
  155. if Application.getInstance().getOutputDeviceManager().getOutputDevicePlugin("RemovableDriveOutputDevice").ejectDevice(self):
  156. message.hide()
  157. eject_message = Message(catalog.i18nc("@info:status",
  158. "Ejected {0}. You can now safely remove the drive.").format(self.getName()),
  159. title = catalog.i18nc("@info:title", "Safely Remove Hardware"))
  160. else:
  161. eject_message = Message(catalog.i18nc("@info:status",
  162. "Failed to eject {0}. Another program may be using the drive.").format(self.getName()),
  163. title = catalog.i18nc("@info:title", "Warning"),
  164. message_type = Message.MessageType.ERROR)
  165. eject_message.show()