AutoSave.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import QTimer
  4. from UM.Logger import Logger
  5. class AutoSave:
  6. def __init__(self, application):
  7. self._application = application
  8. self._application.getPreferences().preferenceChanged.connect(self._triggerTimer)
  9. self._global_stack = None
  10. self._application.getPreferences().addPreference("cura/autosave_delay", 1000 * 10)
  11. self._change_timer = QTimer()
  12. self._change_timer.setInterval(int(self._application.getPreferences().getValue("cura/autosave_delay")))
  13. self._change_timer.setSingleShot(True)
  14. self._enabled = True
  15. self._saving = False
  16. def initialize(self):
  17. # only initialise if the application is created and has started
  18. self._change_timer.timeout.connect(self._onTimeout)
  19. self._application.globalContainerStackChanged.connect(self._onGlobalStackChanged)
  20. self._onGlobalStackChanged()
  21. self._triggerTimer()
  22. def _triggerTimer(self, *args):
  23. if not self._saving:
  24. self._change_timer.start()
  25. def setEnabled(self, enabled: bool) -> None:
  26. self._enabled = enabled
  27. if self._enabled:
  28. self._change_timer.start()
  29. else:
  30. self._change_timer.stop()
  31. def _onGlobalStackChanged(self):
  32. if self._global_stack:
  33. self._global_stack.propertyChanged.disconnect(self._triggerTimer)
  34. self._global_stack.containersChanged.disconnect(self._triggerTimer)
  35. self._global_stack = self._application.getGlobalContainerStack()
  36. if self._global_stack:
  37. self._global_stack.propertyChanged.connect(self._triggerTimer)
  38. self._global_stack.containersChanged.connect(self._triggerTimer)
  39. def _onTimeout(self):
  40. self._saving = True # To prevent the save process from triggering another autosave.
  41. Logger.log("d", "Autosaving preferences, instances and profiles")
  42. self._application.saveSettings()
  43. self._saving = False