RemovableDrivePlugin.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. # Python built-ins
  4. import threading
  5. import time
  6. # Uranium/Messaging
  7. from UM.Logger import Logger
  8. # Uranium/IO
  9. from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
  10. from . import RemovableDriveOutputDevice
  11. # Uranium/l18n
  12. from UM.i18n import i18nCatalog
  13. catalog = i18nCatalog("cura")
  14. class RemovableDrivePlugin(OutputDevicePlugin):
  15. def __init__(self):
  16. super().__init__()
  17. self._update_thread = threading.Thread(target = self._updateThread)
  18. self._update_thread.daemon = True
  19. self._check_updates = True
  20. self._drives = {}
  21. def start(self):
  22. self._update_thread.start()
  23. def stop(self):
  24. self._check_updates = False
  25. self._update_thread.join()
  26. self._addRemoveDrives({})
  27. def checkRemovableDrives(self):
  28. raise NotImplementedError()
  29. def ejectDevice(self, device):
  30. try:
  31. Logger.log("i", "Attempting to eject the device")
  32. result = self.performEjectDevice(device)
  33. except Exception as e:
  34. Logger.log("e", "Ejection failed due to: %s" % str(e))
  35. result = False
  36. if result:
  37. Logger.log("i", "Successfully ejected the device")
  38. return result
  39. def performEjectDevice(self, device):
  40. raise NotImplementedError()
  41. def _updateThread(self):
  42. while self._check_updates:
  43. result = self.checkRemovableDrives()
  44. self._addRemoveDrives(result)
  45. time.sleep(5)
  46. def _addRemoveDrives(self, drives):
  47. # First, find and add all new or changed keys
  48. for key, value in drives.items():
  49. if key not in self._drives:
  50. self.getOutputDeviceManager().addOutputDevice(RemovableDriveOutputDevice.RemovableDriveOutputDevice(key, value))
  51. continue
  52. if self._drives[key] != value:
  53. self.getOutputDeviceManager().removeOutputDevice(key)
  54. self.getOutputDeviceManager().addOutputDevice(RemovableDriveOutputDevice.RemovableDriveOutputDevice(key, value))
  55. # Then check for keys that have been removed
  56. for key in self._drives.keys():
  57. if key not in drives:
  58. self.getOutputDeviceManager().removeOutputDevice(key)
  59. self._drives = drives