RemovableDriveOutputDevice.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. ## Request the specified nodes to be written to the removable drive.
  25. #
  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
  29. # to. 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. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  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] #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(), os.path.splitext(file_name)[0] + extension)
  65. try:
  66. Logger.log("d", "Writing to %s", file_name)
  67. # Using buffering greatly reduces the write time for many lines of gcode
  68. if preferred_format["mode"] == FileWriter.OutputMode.TextMode:
  69. self._stream = open(file_name, "wt", buffering = 1, encoding = "utf-8")
  70. else: #Binary mode.
  71. self._stream = open(file_name, "wb", buffering = 1)
  72. job = WriteFileJob(writer, self._stream, nodes, preferred_format["mode"])
  73. job.setFileName(file_name)
  74. job.progress.connect(self._onProgress)
  75. job.finished.connect(self._onFinished)
  76. 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"))
  77. message.show()
  78. self.writeStarted.emit(self)
  79. job.setMessage(message)
  80. self._writing = True
  81. job.start()
  82. except PermissionError as e:
  83. Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
  84. 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
  85. except OSError as e:
  86. Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
  87. 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
  88. ## Generate a file name automatically for the specified nodes to be saved
  89. # in.
  90. #
  91. # The name generated will be the name of one of the nodes. Which node that
  92. # is can not be guaranteed.
  93. #
  94. # \param nodes A collection of nodes for which to generate a file name.
  95. def _automaticFileName(self, nodes):
  96. for root in nodes:
  97. for child in BreadthFirstIterator(root):
  98. if child.getMeshData():
  99. name = child.getName()
  100. if name:
  101. return name
  102. 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()))
  103. def _onProgress(self, job, progress):
  104. self.writeProgress.emit(self, progress)
  105. def _onFinished(self, job):
  106. if self._stream:
  107. # Explicitly closing the stream flushes the write-buffer
  108. try:
  109. self._stream.close()
  110. self._stream = None
  111. except:
  112. Logger.logException("w", "An execption occured while trying to write to removable drive.")
  113. message = Message(catalog.i18nc("@info:status", "Could not save to removable drive {0}: {1}").format(self.getName(),str(job.getError())),
  114. title = catalog.i18nc("@info:title", "Error"))
  115. message.show()
  116. self.writeError.emit(self)
  117. return
  118. self._writing = False
  119. self.writeFinished.emit(self)
  120. if job.getResult():
  121. 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"))
  122. message.addAction("eject", catalog.i18nc("@action:button", "Eject"), "eject", catalog.i18nc("@action", "Eject removable device {0}").format(self.getName()))
  123. message.actionTriggered.connect(self._onActionTriggered)
  124. message.show()
  125. self.writeSuccess.emit(self)
  126. else:
  127. 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"))
  128. message.show()
  129. self.writeError.emit(self)
  130. job.getStream().close()
  131. def _onActionTriggered(self, message, action):
  132. if action == "eject":
  133. if Application.getInstance().getOutputDeviceManager().getOutputDevicePlugin("RemovableDriveOutputDevice").ejectDevice(self):
  134. message.hide()
  135. 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"))
  136. else:
  137. 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"))
  138. eject_message.show()