RemovableDrivePlugin.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Uranium is released under the terms of the AGPLv3 or higher.
  3. import threading
  4. import time
  5. from UM.Signal import Signal
  6. from UM.Message import Message
  7. from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
  8. from . import RemovableDriveOutputDevice
  9. from UM.i18n import i18nCatalog
  10. catalog = i18nCatalog("uranium")
  11. class RemovableDrivePlugin(OutputDevicePlugin):
  12. def __init__(self):
  13. super().__init__()
  14. self._update_thread = threading.Thread(target = self._updateThread)
  15. self._update_thread.setDaemon(True)
  16. self._check_updates = True
  17. self._drives = {}
  18. def start(self):
  19. self._update_thread.start()
  20. def stop(self):
  21. self._check_updates = False
  22. self._update_thread.join()
  23. self._addRemoveDrives({})
  24. def checkRemovableDrives(self):
  25. raise NotImplementedError()
  26. def ejectDevice(self, device):
  27. result = self.performEjectDevice(device)
  28. if result:
  29. message = Message(catalog.i18n("Ejected {0}. You can now safely remove the drive.").format(device.getName()))
  30. message.show()
  31. else:
  32. message = Message(catalog.i18n("Failed to eject {0}. Maybe it is still in use?").format(device.getName()))
  33. message.show()
  34. def performEjectDevice(self, device):
  35. raise NotImplementedError()
  36. def _updateThread(self):
  37. while self._check_updates:
  38. result = self.checkRemovableDrives()
  39. self._addRemoveDrives(result)
  40. time.sleep(5)
  41. def _addRemoveDrives(self, drives):
  42. # First, find and add all new or changed keys
  43. for key, value in drives.items():
  44. if key not in self._drives:
  45. self.getOutputDeviceManager().addOutputDevice(RemovableDriveOutputDevice.RemovableDriveOutputDevice(key, value))
  46. continue
  47. if self._drives[key] != value:
  48. self.getOutputDeviceManager().removeOutputDevice(key)
  49. self.getOutputDeviceManager().addOutputDevice(RemovableDriveOutputDevice.RemovableDriveOutputDevice(key, value))
  50. # Then check for keys that have been removed
  51. for key in self._drives.keys():
  52. if key not in drives:
  53. self.getOutputDeviceManager().removeOutputDevice(key)
  54. self._drives = drives