AutoSave.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 typing import Any, TYPE_CHECKING
  5. from UM.Logger import Logger
  6. if TYPE_CHECKING:
  7. from cura.CuraApplication import CuraApplication
  8. class AutoSave:
  9. def __init__(self, application: "CuraApplication") -> None:
  10. self._application = application
  11. self._application.getPreferences().preferenceChanged.connect(self._triggerTimer)
  12. self._global_stack = None
  13. self._application.getPreferences().addPreference("cura/autosave_delay", 1000 * 10)
  14. self._change_timer = QTimer()
  15. self._change_timer.setInterval(int(self._application.getPreferences().getValue("cura/autosave_delay")))
  16. self._change_timer.setSingleShot(True)
  17. self._enabled = True
  18. self._saving = False
  19. def initialize(self) -> None:
  20. # only initialise if the application is created and has started
  21. self._change_timer.timeout.connect(self._onTimeout)
  22. self._application.globalContainerStackChanged.connect(self._onGlobalStackChanged)
  23. self._onGlobalStackChanged()
  24. self._triggerTimer()
  25. def _triggerTimer(self, *args: Any) -> None:
  26. if not self._saving:
  27. self._change_timer.start()
  28. def setEnabled(self, enabled: bool) -> None:
  29. self._enabled = enabled
  30. if self._enabled:
  31. self._change_timer.start()
  32. else:
  33. self._change_timer.stop()
  34. def _onGlobalStackChanged(self) -> None:
  35. if self._global_stack:
  36. self._global_stack.propertyChanged.disconnect(self._triggerTimer)
  37. self._global_stack.containersChanged.disconnect(self._triggerTimer)
  38. self._global_stack = self._application.getGlobalContainerStack()
  39. if self._global_stack:
  40. self._global_stack.propertyChanged.connect(self._triggerTimer)
  41. self._global_stack.containersChanged.connect(self._triggerTimer)
  42. def _onTimeout(self) -> None:
  43. self._saving = True # To prevent the save process from triggering another autosave.
  44. Logger.log("d", "Autosaving preferences, instances and profiles")
  45. self._application.saveSettings()
  46. self._saving = False