File: connect.py

package info (click to toggle)
python-echo 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 368 kB
  • sloc: python: 2,421; makefile: 148
file content (631 lines) | stat: -rw-r--r-- 21,471 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# The functions in this module are used to connect callback properties to Qt
# widgets.

from datetime import datetime
import math

from qtpy import QtGui, QtWidgets
from qtpy.QtCore import Qt, QDateTime

import numpy as np

from ..core import add_callback, remove_callback
from ..selection import SelectionCallbackProperty, ChoiceSeparator

__all__ = ['connect_checkable_button', 'connect_text', 'connect_combo_data',
           'connect_combo_text', 'connect_float_text', 'connect_value',
           'connect_combo_selection', 'connect_list_selection', 'connect_datetime',
           'BaseConnection']


class UserDataWrapper(object):
    def __init__(self, data):
        self.data = data


class BaseConnection(object):

    def __init__(self, instance, prop, widget):

        self._instance = instance
        self._prop = prop
        self._widget = widget


class connect_checkable_button(BaseConnection):
    """
    Connect a boolean callback property with a Qt button widget.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setChecked``
        method and the ``toggled`` signal.
    """

    def __init__(self, instance, prop, widget):
        super(connect_checkable_button, self).__init__(instance, prop, widget)
        self.connect()

    def update_widget(self, value):
        self._widget.setChecked(value)

    def update_prop(self, value):
        setattr(self._instance, self._prop, value)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.toggled.connect(self.update_prop)
        self._widget.setChecked(getattr(self._instance, self._prop) or False)

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.toggled.disconnect(self.update_prop)


class connect_text(BaseConnection):
    """
    Connect a string callback property with a Qt widget containing text.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setText`` and
        ``text`` methods as well optionally the ``editingFinished`` signal.
    """

    def __init__(self, instance, prop, widget):
        super(connect_text, self).__init__(instance, prop, widget)
        self.connect()

    def update_prop(self):
        value = self._widget.text()
        setattr(self._instance, self._prop, value)

    def update_widget(self, value):
        if hasattr(self._widget, 'editingFinished'):
            self._widget.blockSignals(True)
            self._widget.setText(value)
            self._widget.blockSignals(False)
            self._widget.editingFinished.emit()
        else:
            self._widget.setText(value)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        try:
            self._widget.editingFinished.connect(self.update_prop)
        except AttributeError:
            pass
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        try:
            self._widget.editingFinished.disconnect(self.update_prop)
        except AttributeError:
            pass


class connect_combo_data(BaseConnection):
    """
    Connect a callback property with a QComboBox widget based on the userData.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QComboBox
        The combo box to connect.

    See Also
    --------
    connect_combo_text: connect a callback property with a QComboBox widget based on the text.
    """

    def __init__(self, instance, prop, widget):
        super(connect_combo_data, self).__init__(instance, prop, widget)
        self.connect()

    def update_widget(self, value):
        try:
            idx = _find_combo_data(self._widget, value)
        except ValueError:
            if value is None:
                idx = -1
            else:
                raise
        self._widget.setCurrentIndex(idx)

    def update_prop(self, idx):
        if idx == -1:
            setattr(self._instance, self._prop, None)
        else:
            data_wrapper = self._widget.itemData(idx)
            if data_wrapper is None:
                setattr(self._instance, self._prop, None)
            else:
                setattr(self._instance, self._prop, data_wrapper.data)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.disconnect(self.update_prop)


class connect_combo_text(BaseConnection):
    """
    Connect a callback property with a QComboBox widget based on the text.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QComboBox
        The combo box to connect.

    See Also
    --------
    connect_combo_data: connect a callback property with a QComboBox widget based on the userData.
    """

    def __init__(self, instance, prop, widget):
        super(connect_combo_text, self).__init__(instance, prop, widget)
        self.connect()

    def update_widget(self, value):
        try:
            idx = _find_combo_text(self._widget, value)
        except ValueError:
            if value is None:
                idx = -1
            else:
                raise
        self._widget.setCurrentIndex(idx)

    def update_prop(self, idx):
        if idx == -1:
            setattr(self._instance, self._prop, None)
        else:
            setattr(self._instance, self._prop, self._widget.itemText(idx))

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.disconnect(self.update_prop)


class connect_float_text(BaseConnection):
    """
    Connect a numerical callback property with a Qt widget containing text.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setText`` and
        ``text`` methods as well optionally the ``editingFinished`` signal.
    fmt : str or func
        This should be either a format string (in the ``{}`` notation), or a
        function that takes a number and returns a string.
    """

    def __init__(self, instance, prop, widget, fmt="{:g}"):

        super(connect_float_text, self).__init__(instance, prop, widget)

        if callable(fmt):
            format_func = fmt
        else:
            def format_func(x):
                try:
                    return fmt.format(x)
                except ValueError:
                    return str(x)

        self._format_func = format_func

        self.connect()

    def update_prop(self):
        value = self._widget.text()
        try:
            value = float(value)
        except ValueError:
            try:
                value = np.datetime64(value)
            except Exception:
                value = 0
        setattr(self._instance, self._prop, value)

    def update_widget(self, value):
        if value is None:
            value = 0.
        self._widget.setText(self._format_func(value))

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        try:
            self._widget.editingFinished.connect(self.update_prop)
        except AttributeError:
            pass
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        try:
            self._widget.editingFinished.disconnect(self.update_prop)
        except AttributeError:
            pass


class connect_value(BaseConnection):
    """
    Connect a numerical callback property with a Qt widget representing a value.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setText`` and
        ``text`` methods as well optionally the ``editingFinished`` signal.
    value_range : iterable, optional
        A pair of two values representing the true range of values (since
        Qt widgets such as sliders can only have values in certain ranges).
    log : bool, optional
        Whether the Qt widget value should be mapped to the log of the callback
        property.
    """

    def __init__(self, instance, prop, widget, value_range=None, log=False):

        super(connect_value, self).__init__(instance, prop, widget)

        if log:
            if value_range is None:
                raise ValueError("log option can only be set if value_range is given")
            else:
                self._value_range = math.log10(value_range[0]), math.log10(value_range[1])
        else:
            self._value_range = value_range
        self._log = log

        self.connect()

    def update_prop(self):
        value = self._widget.value()
        if self._value_range is not None:
            imin, imax = self._widget.minimum(), self._widget.maximum()
            value = ((value - imin) / (imax - imin)
                     * (self._value_range[1] - self._value_range[0]) + self._value_range[0])
        if self._log:
            value = 10 ** value
        setattr(self._instance, self._prop, value)

    def update_widget(self, value):
        if value is None:
            self._widget.setValue(0)
            return
        if self._log:
            value = math.log10(value)
        if self._value_range is not None:
            imin, imax = self._widget.minimum(), self._widget.maximum()
            value = ((value - self._value_range[0])
                     / (self._value_range[1] - self._value_range[0]) * (imax - imin) + imin)
        if isinstance(self._widget, (QtWidgets.QSlider, QtWidgets.QSpinBox)):
            self._widget.setValue(int(value))
        else:
            self._widget.setValue(value)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.valueChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.valueChanged.disconnect(self.update_prop)


class connect_button(BaseConnection):
    """
    Connect a button with a callback method

    Parameters
    ----------
    instance : object
        The class instance that the callback method is attached to
    prop : str
        The name of the callback method
    widget : QtWidget
        The Qt widget to connect. This should implement the ``clicked`` method
    """

    def __init__(self, instance, prop, widget):
        super(connect_button, self).__init__(instance, prop, widget)
        self.connect()

    def connect(self):
        self._widget.clicked.connect(getattr(self._instance, self._prop))

    def disconnect(self):
        self._widget.clicked.disconnect(self.update_prop)


def _find_combo_data(widget, value):
    """
    Returns the index in a combo box where itemData == value

    Raises a ValueError if data is not found
    """
    # Here we check that the result is True, because some classes may overload
    # == and return other kinds of objects whether true or false.
    for idx in range(widget.count()):
        if widget.itemData(idx) is not None:
            if isinstance(widget.itemData(idx), UserDataWrapper):
                if widget.itemData(idx).data is value or (widget.itemData(idx).data == value) is True:
                    return idx
            else:
                if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True:
                    return idx
    else:
        raise ValueError("%s not found in combo box" % (value,))


def _find_combo_text(widget, value):
    """
    Returns the index in a combo box where text == value

    Raises a ValueError if data is not found
    """
    i = widget.findText(value)
    if i == -1:
        raise ValueError("%s not found in combo box" % value)
    else:
        return i


class connect_combo_selection(BaseConnection):

    def __init__(self, instance, prop, widget):

        if not isinstance(getattr(type(instance), prop), SelectionCallbackProperty):
            raise TypeError('connect_combo_selection requires a SelectionCallbackProperty')

        super(connect_combo_selection, self).__init__(instance, prop, widget)
        self.connect()

    def update_widget(self, value):

        # Update choices in the combo box

        combo_data = [self._widget.itemData(idx) for idx in range(self._widget.count())]
        combo_text = [self._widget.itemText(idx) for idx in range(self._widget.count())]

        choices = getattr(type(self._instance), self._prop).get_choices(self._instance)
        choice_labels = getattr(type(self._instance), self._prop).get_choice_labels(self._instance)

        if combo_data == choices and combo_text == choice_labels:
            choices_updated = False
        else:

            self._widget.blockSignals(True)
            self._widget.clear()

            if len(choices) == 0:
                return

            combo_model = self._widget.model()

            for index, (label, choice) in enumerate(zip(choice_labels, choices)):

                self._widget.addItem(label, userData=UserDataWrapper(choice))

                # We interpret None data as being disabled rows (used for headers)
                if isinstance(choice, ChoiceSeparator):
                    item = combo_model.item(index)
                    palette = self._widget.palette()
                    item.setFlags(item.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsEnabled))
                    item.setData(palette.color(QtGui.QPalette.Disabled, QtGui.QPalette.Text))

            choices_updated = True

        # Update current selection
        try:
            idx = _find_combo_data(self._widget, value)
        except ValueError:
            if value is None:
                idx = -1
            else:
                raise

        if idx == self._widget.currentIndex() and not choices_updated:
            return

        self._widget.setCurrentIndex(idx)
        self._widget.blockSignals(False)
        self._widget.currentIndexChanged.emit(idx)

    def update_prop(self, idx):
        if idx == -1:
            setattr(self._instance, self._prop, None)
        else:
            data_wrapper = self._widget.itemData(idx)
            if data_wrapper is None:
                setattr(self._instance, self._prop, None)
            else:
                setattr(self._instance, self._prop, data_wrapper.data)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.currentIndexChanged.disconnect(self.update_prop)


class connect_list_selection(BaseConnection):

    def __init__(self, instance, prop, widget):
        """
        Connect a SelectionCallbackProperty with a QListWidget that supports
        single-item selection.
        """

        if not isinstance(getattr(type(instance), prop), SelectionCallbackProperty):
            raise TypeError('connect_list_selection requires a SelectionCallbackProperty')

        super(connect_list_selection, self).__init__(instance, prop, widget)
        self.connect()

    def update_widget(self, value, force=False):

        items = [self._widget.item(idx) for idx in range(self._widget.count())]
        list_text = [item.text() for item in items]
        list_data = [item.data(Qt.UserRole) for item in items]
        list_data = [d.data if d is not None else d for d in list_data]

        choices = getattr(type(self._instance), self._prop).get_choices(self._instance)
        choice_labels = getattr(type(self._instance), self._prop).get_choice_labels(self._instance)

        for idx in range(len(choices)):
            if choices[idx] is value or (choices[idx] == value) is True:
                break
        else:
            idx = -1

        self._widget.blockSignals(True)

        choices_match = list_data == choices and list_text == choice_labels

        if force or not choices_match:

            self._widget.clear()

            if len(choices) == 0:
                self._widget.blockSignals(False)
                return

            for index, (label, choice) in enumerate(zip(choice_labels, choices)):

                item = QtWidgets.QListWidgetItem(label)
                item.setData(Qt.UserRole, UserDataWrapper(choice))
                self._widget.addItem(item)

                # We interpret None data as being disabled rows (used for headers)
                if isinstance(choice, ChoiceSeparator):
                    item.setFlags(item.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsEnabled))

        if len(self._widget.selectedItems()) == 0:
            current_index = -1
        else:
            selected_item = self._widget.selectedItems()[0]
            for current_index, item in enumerate(items):
                if item is selected_item:
                    break
            else:
                current_index = -1

        if idx == current_index and choices_match:
            self._widget.blockSignals(False)
            return

        self._widget.setCurrentItem(self._widget.item(idx))
        self._widget.blockSignals(False)
        self._widget.itemSelectionChanged.emit()

    def update_prop(self):

        if len(self._widget.selectedItems()) == 0:
            setattr(self._instance, self._prop, None)
        else:
            data_wrapper = self._widget.selectedItems()[0].data(Qt.UserRole)
            if data_wrapper is None:
                setattr(self._instance, self._prop, None)
            else:
                setattr(self._instance, self._prop, data_wrapper.data)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.itemSelectionChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.itemSelectionChanged.disconnect(self.update_prop)


class connect_datetime(BaseConnection):
    """
    Connect a CallbackProperty to a QDateTimeEdit.
    Since QDateEdit and QTimeEdit are subclasses of QDateTimeEdit, this connection
    will work for those more specific widgets as well.
    """

    def __init__(self, instance, prop, widget):
        super(connect_datetime, self).__init__(instance, prop, widget)
        self.connect()

    def update_prop(self):
        qdatetime = self._widget.dateTime().toUTC()
        value = np.datetime64(qdatetime.toPython())
        setattr(self._instance, self._prop, value)

    def update_widget(self, value):
        if value is None:
            value = np.datetime64('now')
        dt = value.item()

        # datetime64::item can return a date
        # If this happens, we use midnight as our time
        # (datetime is a subclass of date so we need to check this way)
        if not isinstance(dt, datetime):
            date = dt
            time = datetime.min.time()
        else:
            date = dt.date()
            time = dt.time()

        qdatetime = QDateTime(date, time, Qt.TimeSpec.UTC).toTimeSpec(self._widget.timeSpec())
        self._widget.setDateTime(qdatetime)

    def connect(self):
        add_callback(self._instance, self._prop, self.update_widget)
        self._widget.dateTimeChanged.connect(self.update_prop)
        self._widget.dateChanged.connect(self.update_prop)
        self._widget.timeChanged.connect(self.update_prop)
        self.update_widget(getattr(self._instance, self._prop))

    def disconnect(self):
        remove_callback(self._instance, self._prop, self.update_widget)
        self._widget.dateTimeChanged.disconnect(self.update_prop)
        self._widget.dateChanged.disconnect(self.update_prop)
        self._widget.timeChanged.disconnect(self.update_prop)