File: bitwidgets.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 (274 lines) | stat: -rw-r--r-- 8,614 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
# 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".
"""Some comboboxes and other widegts.

Dev note (buhtz, 2025-03: Have look at "qt/manageprofiles/combobox.py" and
consolidate if possible.
"""
import itertools
from typing import Callable
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QCursor, QMouseEvent
from PyQt6.QtWidgets import (QCheckBox,
                             QComboBox,
                             QFrame,
                             QHBoxLayout,
                             QLabel,
                             QSizePolicy,
                             QToolTip,
                             QWidget)
import qttools


class SortedComboBox(QComboBox):
    """A combo box ensuring that its items are in sorted order.
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.sort_order = None
        self.sort_role = None

        self.set_ascending_order()
        self.set_role(Qt.ItemDataRole.DisplayRole)

    def set_ascending_order(self, ascending: bool = True) -> None:
        """Set the sort order."""
        self.sort_order = {
            True: Qt.SortOrder.AscendingOrder,
            False: Qt.SortOrder.DescendingOrder}[ascending]

    def set_role(self, role: Qt.ItemDataRole) -> None:
        """Set item data role."""
        self.sort_role = role

    def add_item(self, text, user_data=None):
        """
        QComboBox doesn't support sorting
        so this little hack is used to insert
        items in sorted order.
        """

        if self.sort_role == Qt.ItemDataRole.UserRole:
            sort_obj = user_data
        else:
            sort_obj = text

        the_list = [
            self.itemData(i, self.sort_role) for i in range(self.count())]
        the_list.append(sort_obj)

        reverse_sort = self.sort_order == Qt.SortOrder.DescendingOrder
        the_list.sort(reverse=reverse_sort)
        idx = the_list.index(sort_obj)

        self.insertItem(idx, text, user_data)

    def check_selection(self):
        """Dev note: Not sure what it is doing or why this is needed."""
        if self.currentIndex() < 0:
            self.setCurrentIndex(0)


class SnapshotCombo(SortedComboBox):
    """A combo box containing backups (aka snapshots)."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.set_ascending_order(False)
        self.set_role(Qt.ItemDataRole.UserRole)

    def add_snapshot_id(self, sid):
        """Add the snapshot with its ID/name."""
        self.add_item(sid.displayName, sid)

    def current_snapshot_id(self):
        """Return the ID/name of the current snapshot."""
        return self.itemData(self.currentIndex())

    def set_current_snapshot_id(self, sid):
        """Select entry by its snapshot id."""
        for idx in range(self.count()):
            if self.itemData(idx) == sid:
                self.setCurrentIndex(idx)
                break


class ProfileCombo(SortedComboBox):
    """A combo box containing profile names."""

    def __init__(self, parent):
        super().__init__(parent)
        self._config = parent.config

    def add_profile_id(self, profile_id):
        """Add item using the profiles name."""
        name = self._config.profileName(profile_id)
        self.add_item(name, profile_id)

    def current_profile_id(self):
        """Return the current selected profile id."""
        return self.itemData(self.currentIndex())

    def set_current_profile_id(self, profile_id):
        """Select the item using the given profile id."""
        for i in range(self.count()):
            if self.itemData(i) == profile_id:
                self.setCurrentIndex(i)
                break


class HLineWidget(QFrame):
    """Just a horizontal line.

    It really is the case that even in the year 2025 with Qt6 there is no
    dedicated widget class to draw a horizontal line.
    """
    # pylint: disable=too-few-public-methods

    def __init__(self):
        super().__init__()
        self.setFrameShape(QFrame.Shape.HLine)
        self.setFrameShadow(QFrame.Shadow.Sunken)


class WrappedCheckBox(QWidget):
    """A checkbox with word wrap capabilities.

    QCheckBox itself is not able to wrap text in its label, without hacks."""

    def __init__(self,
                 label: str,
                 tooltip: str = None,
                 parent: QWidget = None):
        super().__init__(parent)

        self.checkbox = QCheckBox()
        self.label = QLabel(label)

        layout = QHBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.checkbox, stretch=0)
        layout.addWidget(self.label, stretch=1)

        self.label.setWordWrap(True)
        self.label.setSizePolicy(
            QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)

        self.label.mouseReleaseEvent = self._slot_label_clicked

        if tooltip:
            qttools.set_wrapped_tooltip([self.checkbox, self.label], tooltip)

        self.setSizePolicy(
            QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)

        # # DEBUG
        # self.setStyleSheet("background: lightblue; border: 1px solid red;")

    def _slot_label_clicked(self, event: QMouseEvent):
        if event.button() == Qt.MouseButton.LeftButton:
            self.checkbox.toggle()

    @property
    def checked(self) -> bool:
        """Checked state of the check box"""
        return self.checkbox.isChecked()

    @checked.setter
    def checked(self, check: bool) -> None:
        self.checkbox.setChecked(check)


class Spinner(QLabel):
    """An activity indicator widget using unicode characters"""
    # STOP = '⠿'
    STOP = ' '

    def __init__(self,
                 parent: QWidget = None,
                 font_scale: float = None):
        super().__init__(parent)

        # self.spinner_sequence = ['◐', '◓', '◑', '◒']
        # self.spinner_sequence = ['🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖',
        #                          '🕗', '🕘', '🕙', '🕚', '🕛']

        # Unicode symbols used alternately
        self._sequence = itertools.cycle(['⠋', '⠙', '⠸', '⠴', '⠦', '⠇'])

        self.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.setText(Spinner.STOP)

        # font size
        if font_scale:
            font = self.font()
            font.setPointSize(int(font.pointSize() * font_scale))
            self.setFont(font)

        # cycle timer
        self._timer = QTimer(self)
        self._timer.timeout.connect(
            lambda: self.setText(next(self._sequence)))

    def start(self, interval_ms: int = 150) -> None:
        """Start the spinner"""
        self._timer.start(interval_ms)

    def stop(self) -> None:
        """Stop the spinner using `self.STOP` as label."""
        self._timer.stop()
        self.setText(Spinner.STOP)


class HypertextLabel(QLabel):
    """A label containing hyper links.

    In adtion to QLabel the link has a tooltip derived from its URL or a
    customized string.
    """

    # pylint: disable-next=too-many-arguments,too-many-positional-arguments
    def __init__(self,
                 label: str,
                 word_wrap: bool = False,
                 link_slot: Callable[[str], None] = None,
                 link_tooltip: str = None,
                 parent: QWidget = None):
        super().__init__(parent)

        self._link_tooltip = link_tooltip

        self.setText(label)
        self.setWordWrap(word_wrap)

        if link_slot:
            self.setOpenExternalLinks(False)
            self.linkActivated.connect(link_slot)

        self.linkHovered.connect(self.slot_link_hovered)

        # gpl.setTextInteractionFlags(
        #     Qt.TextInteractionFlag.TextBrowserInteraction)

    def slot_link_hovered(self, url: str):
        """Show URL in tooltip without anoing http-protocol prefixf."""

        if self._link_tooltip:
            txt = self._link_tooltip
        else:
            txt = url.replace('https://', '')

        QToolTip.showText(QCursor.pos(), txt)