File: timeline.py

package info (click to toggle)
backintime 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 10,424 kB
  • sloc: python: 27,312; sh: 886; makefile: 174; xml: 62
file content (305 lines) | stat: -rw-r--r-- 10,180 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# SPDX-FileCopyrightText: © 2008-2022 Oprea Dan
# SPDX-FileCopyrightText: © 2008-2022 Bart de Koning
# SPDX-FileCopyrightText: © 2008-2022 Richard Bailey
# SPDX-FileCopyrightText: © 2008-2022 Germar Reitze
# SPDX-FileCopyrightText: © 2024 Christian Buhtz <c.buhtz@posteo.jp>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of the program "Back In Time" which is released under GNU
# General Public License v2 (GPLv2). See LICENSES directory or go to
# <https://spdx.org/licenses/GPL-2.0-or-later.html>.
#
# File was split from "qt/qttools.py".
"""Time line widget.
"""
from datetime import (datetime, date, timedelta)
from calendar import monthrange
from PyQt6.QtGui import QFont, QPalette
from PyQt6.QtCore import (Qt,
                          pyqtSlot,
                          pyqtSignal)
from PyQt6.QtWidgets import (QAbstractItemView,
                             QApplication,
                             QTreeWidget,
                             QTreeWidgetItem)
import snapshots
from qttools_path import register_backintime_path
register_backintime_path('common')


class TimeLine(QTreeWidget):
    """A list like widget containing existing backups.

    The widget is placed on the right side of the main window.
    """
    update_files_view = pyqtSignal(int)

    def __init__(self, parent):
        super().__init__(parent)
        self.setRootIsDecorated(False)
        self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.setSelectionMode(
            QAbstractItemView.SelectionMode.ExtendedSelection)
        self.setHeaderLabels([_('Backups'), 'foo'])
        self.setSortingEnabled(True)
        self.sortByColumn(1, Qt.SortOrder.DescendingOrder)
        self.hideColumn(1)
        self.header().setSectionsClickable(False)

        self.parent = parent
        self.snapshots = parent.snapshots
        self._root_item = None
        self._reset_header_data()

    def clear(self):
        """Clear all entries from the widget."""
        self._reset_header_data()
        return super().clear()

    def _reset_header_data(self):
        self.now = date.today()

        # list of tuples with (text, startDate, endDate)
        self._header_data = []

        # Today
        today_min = datetime.combine(self.now, datetime.min.time())
        today_max = datetime.combine(self.now, datetime.max.time())
        self._header_data.append((_('Today'), today_min, today_max))

        # Yesterday
        yesterday_min = datetime.combine(
            self.now - timedelta(days=1), datetime.min.time())
        yesterday_max = datetime.combine(
            today_min - timedelta(hours=1), datetime.max.time())
        self._header_data.append(
            (_('Yesterday'), yesterday_min, yesterday_max))

        # This week
        this_week_min = datetime.combine(
            self.now - timedelta(self.now.weekday()), datetime.min.time())
        this_week_max = datetime.combine(
            yesterday_min - timedelta(hours=1), datetime.max.time())

        if this_week_min < this_week_max:
            self._header_data.append(
                (_('This week'), this_week_min, this_week_max))

        # Last week
        last_week_min = datetime.combine(
            self.now - timedelta(self.now.weekday() + 7), datetime.min.time())
        last_week_max = datetime.combine(
            self._header_data[-1][1] - timedelta(hours=1), datetime.max.time())
        self._header_data.append(
            (_('Last week'), last_week_min, last_week_max))

        # Rest of current month. Otherwise this months header would be
        # above today.
        this_month_min = datetime.combine(
            self.now - timedelta(self.now.day - 1), datetime.min.time())
        this_month_max = datetime.combine(
            last_week_min - timedelta(hours=1), datetime.max.time())
        if this_month_min < this_month_max:
            self._header_data.append((
                this_month_min.strftime('%B').capitalize(),
                this_month_min,
                this_month_max))

        # Rest of last month
        last_month_max = datetime.combine(
            self._header_data[-1][1] - timedelta(hours=1), datetime.max.time())
        last_month_min = datetime.combine(
            date(last_month_max.year, last_month_max.month, 1),
            datetime.min.time()
        )
        self._header_data.append((
            last_month_min.strftime('%B').capitalize(),
            last_month_min,
            last_month_max))

    def add_root(self, sid):
        """Dev note: What is 'root' in this context?

        Args:
            sid: Snapshot ID

        Returns:
            The root item itself.
        """
        self._root_item = self.addSnapshot(sid)

        return self._root_item

    @pyqtSlot(snapshots.SID)
    # pylint: disable-next=invalid-name
    def addSnapshot(self, sid):  # noqa: N802
        """Slot to handle selection of snapshots."""
        item = SnapshotItem(sid)

        self.addTopLevelItem(item)

        # Select the snapshot that was selected before
        if sid == self.parent.sid:
            self._set_current_item(item)

        if not sid.isRoot:
            self.add_header(sid)

        return item

    def add_header(self, sid):
        """Add an entry as a header item."""

        for text, start_date, end_date in self._header_data:
            if start_date <= sid.date <= end_date:
                self._create_header_item(text, end_date)
                return

        # Any previous months
        year = sid.date.year
        month = sid.date.month

        if year == self.now.year:
            text = date(year, month, 1).strftime('%B').capitalize()
        else:
            text = date(year, month, 1).strftime('%B, %Y').capitalize()

        start_date = datetime.combine(
            date(year, month, 1), datetime.min.time())
        end_date = datetime.combine(
            date(year, month, monthrange(year, month)[1]), datetime.max.time())

        if self._create_header_item(text, end_date):
            self._header_data.append((text, start_date, end_date))

    def _create_header_item(self, text, end_date):
        for item in self._iter_header_items():
            if item.snapshot_id.date == end_date:
                return False

        item = HeaderItem(text, snapshots.SID(end_date, self.parent.config))
        self.addTopLevelItem(item)

        return True

    @pyqtSlot()
    # pylint: disable-next=invalid-name
    def checkSelection(self):  # noqa: N802
        """Slot handling selection events."""
        if self.currentItem() is None:
            self.select_root_item()

    def select_root_item(self):
        """Dev note: Don't know what 'root' means in this context."""
        self._set_current_item(self._root_item)

        if not self.parent.sid.isRoot:
            self.parent.sid = self._root_item.snapshot_id
            self.update_files_view.emit(2)

    def selected_snapshot_ids(self):
        """Snapshot IDs of all selected entries."""
        return [i.snapshot_id for i in self.selectedItems()]

    def current_snapshot_id(self):
        """Snapshot ID of current selected entry."""
        item = self.currentItem()

        return item.snapshot_id if item else None

    def set_current_snapshot_id(self, sid):
        """Select entry related to the snapshot ID."""
        for item in self._iter_items():

            if item.snapshot_id == sid:
                self._set_current_item(item)
                break

    def _set_current_item(self, item, *args, **kwargs):
        self.setCurrentItem(item, *args, **kwargs)

        if self.parent.sid != item.snapshot_id:
            self.parent.sid = item.snapshot_id
            self.update_files_view.emit(2)

    def _iter_items(self):
        for index in range(self.topLevelItemCount()):
            yield self.topLevelItem(index)

    def iter_snapshot_items(self):
        """Iterate over all items."""
        for item in self._iter_items():
            if isinstance(item, SnapshotItem):
                yield item

    def _iter_header_items(self):
        for item in self._iter_items():
            if isinstance(item, HeaderItem):
                yield item


class TimeLineItem(QTreeWidgetItem):
    """Base class for TimeLine entry widgets.

    Dev note (buhtz, 2025-03): I don't see a need for this. SnapshotItem and
    HeaderItem can directly derive from QTreeWidgetItem.
    """

    def __lt__(self, other):
        return self.snapshot_id < other.snapshot_id

    @property
    def snapshot_id(self):
        """Id of the related snapshot."""
        return self.data(0, Qt.ItemDataRole.UserRole)


class SnapshotItem(TimeLineItem):
    """Snapshot entry widget used in TimeLine."""

    def __init__(self, sid):
        super().__init__()
        self.setText(0, sid.displayName)

        self.setData(0, Qt.ItemDataRole.UserRole, sid)

        if sid.isRoot:
            self.setToolTip(
                0,
                _('This is NOT a backup but a live view '
                  'of the local files.'))
        else:
            self.setToolTip(
                0,
                _('Last check {time}').format(time=sid.lastChecked))

    def update_text(self):
        """Update the widgets text with its snapshots displayName."""
        sid = self.snapshot_id
        self.setText(0, sid.displayName)


class HeaderItem(TimeLineItem):  # pylint: disable=too-few-public-methods
    """Header entry widget used in TimeLine."""

    def __init__(self, name, sid):
        """
        Dev note (buhtz, 2024-01-14): Parts of that code are redundant with
        app.py::MainWindow.addPlace().
        """
        super().__init__()
        self.setText(0, name)
        font = self.font(0)
        font.setWeight(QFont.Weight.Bold)
        self.setFont(0, font)

        palette = QApplication.instance().palette()
        self.setForeground(
            0, palette.color(QPalette.ColorRole.PlaceholderText))
        self.setBackground(
            0, palette.color(QPalette.ColorRole.AlternateBase))

        self.setFlags(Qt.ItemFlag.NoItemFlags)

        self.setData(0, Qt.ItemDataRole.UserRole, sid)