RemovableDriveOutputDevice.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import os.path
  2. from UM.Application import Application
  3. from UM.Logger import Logger
  4. from UM.Message import Message
  5. from UM.Mesh.WriteMeshJob import WriteMeshJob
  6. from UM.Mesh.MeshWriter import MeshWriter
  7. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  8. from UM.OutputDevice.OutputDevice import OutputDevice
  9. from UM.OutputDevice import OutputDeviceError
  10. from UM.i18n import i18nCatalog
  11. catalog = i18nCatalog("cura")
  12. class RemovableDriveOutputDevice(OutputDevice):
  13. def __init__(self, device_id, device_name):
  14. super().__init__(device_id)
  15. self.setName(device_name)
  16. self.setShortDescription(catalog.i18nc("@action:button", "Save to Removable Drive"))
  17. self.setDescription(catalog.i18nc("@item:inlistbox", "Save to Removable Drive {0}").format(device_name))
  18. self.setIconName("save_sd")
  19. self.setPriority(1)
  20. self._writing = False
  21. def requestWrite(self, node, file_name = None, filter_by_machine = False):
  22. filter_by_machine = True # This plugin is indended to be used by machine (regardless of what it was told to do)
  23. if self._writing:
  24. raise OutputDeviceError.DeviceBusyError()
  25. # Formats supported by this application (File types that we can actually write)
  26. file_formats = Application.getInstance().getMeshFileHandler().getSupportedFileTypesWrite()
  27. if filter_by_machine:
  28. container = Application.getInstance().getGlobalContainerStack().findContainer({"file_formats": "*"})
  29. # Create a list from supported file formats string
  30. machine_file_formats = [file_type.strip() for file_type in container.getMetaDataEntry("file_formats").split(";")]
  31. # Take the intersection between file_formats and machine_file_formats.
  32. file_formats = list(filter(lambda file_format: file_format["mime_type"] in machine_file_formats, file_formats))
  33. if len(file_formats) == 0:
  34. Logger.log("e", "There are no file formats available to write with!")
  35. raise OutputDeviceError.WriteRequestFailedError()
  36. # Just take the first file format available.
  37. writer = Application.getInstance().getMeshFileHandler().getWriterByMimeType(file_formats[0]["mime_type"])
  38. extension = file_formats[0]["extension"]
  39. if file_name is None:
  40. for n in BreadthFirstIterator(node):
  41. if n.getMeshData():
  42. file_name = n.getName()
  43. if file_name:
  44. break
  45. if not file_name:
  46. Logger.log("e", "Could not determine a proper file name when trying to write to %s, aborting", self.getName())
  47. raise OutputDeviceError.WriteRequestFailedError()
  48. if extension: # Not empty string.
  49. extension = "." + extension
  50. file_name = os.path.join(self.getId(), os.path.splitext(file_name)[0] + extension)
  51. try:
  52. Logger.log("d", "Writing to %s", file_name)
  53. stream = open(file_name, "wt")
  54. job = WriteMeshJob(writer, stream, node, MeshWriter.OutputMode.TextMode)
  55. job.setFileName(file_name)
  56. job.progress.connect(self._onProgress)
  57. job.finished.connect(self._onFinished)
  58. message = Message(catalog.i18nc("@info:progress", "Saving to Removable Drive <filename>{0}</filename>").format(self.getName()), 0, False, -1)
  59. message.show()
  60. self.writeStarted.emit(self)
  61. job._message = message
  62. self._writing = True
  63. job.start()
  64. except PermissionError as e:
  65. Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
  66. raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format(file_name, str(e))) from e
  67. except OSError as e:
  68. Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
  69. raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format(file_name, str(e))) from e
  70. def _onProgress(self, job, progress):
  71. if hasattr(job, "_message"):
  72. job._message.setProgress(progress)
  73. self.writeProgress.emit(self, progress)
  74. def _onFinished(self, job):
  75. if hasattr(job, "_message"):
  76. job._message.hide()
  77. job._message = None
  78. self._writing = False
  79. self.writeFinished.emit(self)
  80. if job.getResult():
  81. message = Message(catalog.i18nc("@info:status", "Saved to Removable Drive {0} as {1}").format(self.getName(), os.path.basename(job.getFileName())))
  82. message.addAction("eject", catalog.i18nc("@action:button", "Eject"), "eject", catalog.i18nc("@action", "Eject removable device {0}").format(self.getName()))
  83. message.actionTriggered.connect(self._onActionTriggered)
  84. message.show()
  85. self.writeSuccess.emit(self)
  86. else:
  87. message = Message(catalog.i18nc("@info:status", "Could not save to removable drive {0}: {1}").format(self.getName(), str(job.getError())))
  88. message.show()
  89. self.writeError.emit(self)
  90. job.getStream().close()
  91. def _onActionTriggered(self, message, action):
  92. if action == "eject":
  93. Application.getInstance().getOutputDeviceManager().getOutputDevicePlugin("RemovableDriveOutputDevice").ejectDevice(self)