RemovableDriveOutputDevice.py 8.7 KB

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