File: recent_manager.py

package info (click to toggle)
secrets 11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,744 kB
  • sloc: python: 6,509; xml: 7; makefile: 4
file content (70 lines) | stat: -rw-r--r-- 1,937 bytes parent folder | download
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
# SPDX-License-Identifier: GPL-3.0-only
from collections import deque

from gi.repository import Gio, GObject

from gsecrets.const import APP_ID

MAX_RECENT_ITEMS = 10


class RecentManager(GObject.Object):
    changed = GObject.Signal(arg_types=())

    def __init__(self):
        super().__init__()

        self.settings = Gio.Settings.new(APP_ID)

        self._load_items()
        self.settings.connect("changed::last-opened-list", self._on_settings_changed)

    def __iter__(self):
        return iter(self.recents)

    def __reversed__(self):
        return reversed(self.recents)

    def add_item(self, item: Gio.File) -> None:
        if found := next(
            (f for f in self.recents if f.get_uri() == item.get_uri()), None
        ):
            if bool(self.recents) and found != self.recents[-1]:
                self.recents.remove(found)
            else:
                return

        self.recents.append(item)
        self._save_items()
        self.emit(self.changed)

    def remove_item(self, item: Gio.File) -> None:
        if found := next(
            (f for f in self.recents if f.get_uri() == item.get_uri()), None
        ):
            self.recents.remove(found)
            self.emit(self.changed)

    def is_empty(self) -> bool:
        return not bool(self.recents)

    def purge_items(self) -> None:
        if self.is_empty():
            return

        self.recents.clear()
        self._save_items()
        self.emit(self.changed)

    def _save_items(self):
        uris = [item.get_uri() for item in self.recents]
        self.settings.set_strv("last-opened-list", uris)

    def _load_items(self):
        uris = self.settings.get_strv("last-opened-list")
        items = [Gio.File.new_for_uri(uri) for uri in uris]
        self.recents = deque(items, MAX_RECENT_ITEMS)

    def _on_settings_changed(self, _settings, _key):
        self._load_items()
        self.emit(self.changed)