AutoSave.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import QTimer
  4. from typing import Any, TYPE_CHECKING
  5. from UM.Logger import Logger
  6. import time
  7. if TYPE_CHECKING:
  8. from cura.CuraApplication import CuraApplication
  9. class AutoSave:
  10. def __init__(self, application: "CuraApplication") -> None:
  11. self._application = application
  12. self._application.getPreferences().preferenceChanged.connect(self._triggerTimer)
  13. self._global_stack = None
  14. self._application.getPreferences().addPreference("cura/autosave_delay", 1000 * 10)
  15. self._change_timer = QTimer()
  16. self._change_timer.setInterval(int(self._application.getPreferences().getValue("cura/autosave_delay")))
  17. self._change_timer.setSingleShot(True)
  18. self._enabled = True
  19. self._saving = False
  20. def initialize(self) -> None:
  21. # only initialise if the application is created and has started
  22. self._change_timer.timeout.connect(self._onTimeout)
  23. self._application.globalContainerStackChanged.connect(self._onGlobalStackChanged)
  24. self._onGlobalStackChanged()
  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. save_start_time = time.time()
  45. self._application.saveSettings()
  46. Logger.log("d", "Autosaving preferences, instances and profiles took %s seconds", time.time() - save_start_time)
  47. self._saving = False