summaryrefslogtreecommitdiff
path: root/qutebrowser/misc/savemanager.py
blob: ee22ba14deaa724a9440efc0bc0f2de114cd8683 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.

"""Saving things to disk periodically."""

import os.path
import collections
from typing import MutableMapping

from PyQt5.QtCore import pyqtSlot, QObject, QTimer

from qutebrowser.config import config
from qutebrowser.api import cmdutils
from qutebrowser.utils import utils, log, message, usertypes, error
from qutebrowser.misc import objects


class Saveable:

    """A single thing which can be saved.

    Attributes:
        _name: The name of the thing to be saved.
        _dirty: Whether the saveable was changed since the last save.
        _save_handler: The function to call to save this Saveable.
        _save_on_exit: Whether to always save this saveable on exit.
        _config_opt: A config option which decides whether to auto-save or not.
                     None if no such option exists.
        _filename: The filename of the underlying file.
    """

    def __init__(self, name, save_handler, changed=None, config_opt=None,
                 filename=None):
        self._name = name
        self._dirty = False
        self._save_handler = save_handler
        self._config_opt = config_opt
        if changed is not None:
            changed.connect(self.mark_dirty)
            self._save_on_exit = False
        else:
            self._save_on_exit = True
        self._filename = filename
        if filename is not None and not os.path.exists(filename):
            self._dirty = True
            self.save()

    def __repr__(self):
        return utils.get_repr(self, name=self._name, dirty=self._dirty,
                              save_handler=self._save_handler,
                              config_opt=self._config_opt,
                              save_on_exit=self._save_on_exit,
                              filename=self._filename)

    def mark_dirty(self):
        """Mark this saveable as dirty (having changes)."""
        log.save.debug("Marking {} as dirty.".format(self._name))
        self._dirty = True

    def save(self, is_exit=False, explicit=False, silent=False, force=False):
        """Save this saveable.

        Args:
            is_exit: Whether we're currently exiting qutebrowser.
            explicit: Whether the user explicitly requested this save.
            silent: Don't write information to log.
            force: Force saving, no matter what.
        """
        if (self._config_opt is not None and
                (not config.instance.get(self._config_opt)) and
                (not explicit) and (not force)):
            if not silent:
                log.save.debug("Not saving {name} because autosaving has been "
                               "disabled by {cfg[0]} -> {cfg[1]}.".format(
                                   name=self._name, cfg=self._config_opt))
            return
        do_save = self._dirty or (self._save_on_exit and is_exit) or force
        if not silent:
            log.save.debug("Save of {} requested - dirty {}, save_on_exit {}, "
                           "is_exit {}, force {} -> {}".format(
                               self._name, self._dirty, self._save_on_exit,
                               is_exit, force, do_save))
        if do_save:
            self._save_handler()
            self._dirty = False


class SaveManager(QObject):

    """Responsible to save 'saveables' periodically and on exit.

    Attributes:
        saveables: A dict mapping names to Saveable instances.
        _save_timer: The Timer used to periodically auto-save things.
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.saveables: MutableMapping[str, Saveable] = collections.OrderedDict()
        self._save_timer = usertypes.Timer(self, name='save-timer')
        self._save_timer.timeout.connect(self.autosave)
        self._set_autosave_interval()
        config.instance.changed.connect(self._set_autosave_interval)

    def __repr__(self):
        return utils.get_repr(self, saveables=self.saveables)

    @config.change_filter('auto_save.interval')
    def _set_autosave_interval(self):
        """Set the auto-save interval."""
        interval = config.val.auto_save.interval
        if interval == 0:
            self._save_timer.stop()
        else:
            self._save_timer.setInterval(interval)
            self._save_timer.start()

    def add_saveable(self, name, save, changed=None, config_opt=None,
                     filename=None, dirty=False):
        """Add a new saveable.

        Args:
            name: The name to use.
            save: The function to call to save this saveable.
            changed: The signal emitted when this saveable changed.
            config_opt: An option deciding whether to auto-save or not.
            filename: The filename of the underlying file, so we can force
                      saving if it doesn't exist.
            dirty: Whether the saveable is already dirty.
        """
        if name in self.saveables:
            raise ValueError("Saveable {} already registered!".format(name))
        saveable = Saveable(name, save, changed, config_opt, filename)
        self.saveables[name] = saveable
        if dirty:
            saveable.mark_dirty()
            QTimer.singleShot(0, saveable.save)

    def save(self, name, is_exit=False, explicit=False, silent=False,
             force=False):
        """Save a saveable by name.

        Args:
            is_exit: Whether we're currently exiting qutebrowser.
            explicit: Whether this save operation was triggered explicitly.
            silent: Don't write information to log. Used to reduce log spam
                    when autosaving.
            force: Force saving, no matter what.
        """
        self.saveables[name].save(is_exit=is_exit, explicit=explicit,
                                  silent=silent, force=force)

    def save_all(self, *args, **kwargs):
        """Save all saveables."""
        for saveable in self.saveables:
            self.save(saveable, *args, **kwargs)

    @pyqtSlot()
    def autosave(self):
        """Slot used when the configs are auto-saved."""
        for (key, saveable) in self.saveables.items():
            try:
                saveable.save(silent=True)
            except OSError as e:
                message.error("Failed to auto-save {}: {}".format(key, e))

    @cmdutils.register(instance='save-manager', name='save',
                       star_args_optional=True)
    def save_command(self, *what):
        """Save configs and state.

        Args:
            *what: What to save (`config`/`key-config`/`cookies`/...).
                   If not given, everything is saved.
        """
        if what:
            explicit = True
        else:
            what = tuple(self.saveables)
            explicit = False
        for key in what:
            if key not in self.saveables:
                message.error("{} is nothing which can be saved".format(key))
            else:
                try:
                    self.save(key, explicit=explicit, force=True)
                except OSError as e:
                    message.error("Could not save {}: {}".format(key, e))
        log.save.debug(":save saved {}".format(', '.join(what)))

    @pyqtSlot()
    def shutdown(self):
        """Save all saveables when shutting down."""
        for key in self.saveables:
            try:
                self.save(key, is_exit=True)
            except OSError as e:
                error.handle_fatal_exc(
                    e, "Error while saving!",
                    pre_text="Error while saving {}".format(key),
                    no_err_windows=objects.args.no_err_windows)