AutoSave.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. def _triggerTimer(self, *args: Any) -> None:
  25. if not self._saving:
  26. self._change_timer.start()
  27. def setEnabled(self, enabled: bool) -> None:
  28. self._enabled = enabled
  29. if self._enabled:
  30. self._change_timer.start()
  31. else:
  32. self._change_timer.stop()
  33. def _onGlobalStackChanged(self) -> None:
  34. if self._global_stack:
  35. self._global_stack.propertyChanged.disconnect(self._triggerTimer)
  36. self._global_stack.containersChanged.disconnect(self._triggerTimer)
  37. self._global_stack = self._application.getGlobalContainerStack()
  38. if self._global_stack:
  39. self._global_stack.propertyChanged.connect(self._triggerTimer)
  40. self._global_stack.containersChanged.connect(self._triggerTimer)
  41. def _onTimeout(self) -> None:
  42. self._saving = True # To prevent the save process from triggering another autosave.
  43. Logger.log("d", "Autosaving preferences, instances and profiles")
  44. self._application.saveSettings()
  45. self._saving = False