-
Notifications
You must be signed in to change notification settings - Fork 54
/
pytest_qt_extras.py
1718 lines (1378 loc) · 50.5 KB
/
pytest_qt_extras.py
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#################################################################################
# FOQUS Copyright (c) 2012 - 2024, by the software owners: Oak Ridge Institute
# for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence
# Livermore National Security, LLC., The Regents of the University of
# California, through Lawrence Berkeley National Laboratory, Battelle Memorial
# Institute, Pacific Northwest Division through Pacific Northwest National
# Laboratory, Carnegie Mellon University, West Virginia University, Boston
# University, the Trustees of Princeton University, The University of Texas at
# Austin, URS Energy & Construction, Inc., et al. All rights reserved.
#
# Please see the file LICENSE.md for full copyright and license information,
# respectively. This file is also available online at the URL
# "https://github.com/CCSI-Toolset/FOQUS".
#################################################################################
import contextlib
from dataclasses import dataclass, field, asdict, is_dataclass
import enum
from functools import singledispatch
import logging
from pathlib import Path
import typing as t
from types import ModuleType
import time
try: # available starting with Python 3.8
from functools import singledispatchmethod
except ImportError:
from singledispatchmethod import singledispatchmethod
import oyaml as yaml
# import yaml
from slugify import slugify
from PyQt5 import QtWidgets as W, QtCore, QtGui
from pytestqt import plugin as pytestqt_plugin
from _pytest.monkeypatch import MonkeyPatch
# NOTE these values can be given to aliases used as kwargs when an actual filter is not needed
# the actual value is a matter of synctactic sugar but it should suggest the meaning of
# "any result is fine, no need to filter since I expect it to be the only one"
KWARGS_PLACEHOLDER_VALUES = {True, any, next, ..., "*", ""}
_logger = logging.getLogger("pytest_qt_extras")
class _SerializableMixin:
@classmethod
def to_yaml(cls, dumper, obj):
return dumper.represent_mapping(f"!{type(obj).__qualname__}", obj.as_record())
def __str__(self):
return self.dump()
def as_record(self):
return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
def dump(self):
return yaml.dump(self, Dumper=yaml.Dumper)
def _object_to_yaml(dumper, obj):
return dumper.represent_scalar(f"!{type(obj).__qualname__}", str(obj))
yaml.add_multi_representer(object, _object_to_yaml)
yaml.add_multi_representer(QtCore.QObject, _object_to_yaml)
yaml.add_multi_representer(_SerializableMixin, _SerializableMixin.to_yaml)
@singledispatch
def get_text(w: W.QWidget):
raise NotImplementedError
@get_text.register
def _(btn: W.QAbstractButton):
return btn.text().replace("&", "")
@get_text.register
def _(label: W.QLabel):
return label.text()
@get_text.register
def _(group_box: W.QGroupBox):
return group_box.title()
class ObjLogger:
def __init__(self, **kwargs):
self._logger_opts = kwargs
def _get_logger_instance(self, cls: type):
attr_name = "_logger"
logger = getattr(cls, attr_name, None)
if logger is None:
name = cls.__qualname__
logger = logging.getLogger(name, **self._logger_opts)
setattr(logger, "__call__", logger.info)
setattr(cls, attr_name, logger)
return logger
def __get__(self, obj, objtype=None):
if obj is not None:
return self._get_logger_instance(type(obj))
return self._get_logger_instance(objtype)
@dataclass
class Action:
name: str
target: str
args: tuple = None
prose_template: str = None
@property
def readable_name(self):
return self.name.capitalize().replace("_", " ")
@property
def description(self):
if not self.args:
return f"{self.name.title()} the {self.target}."
return f"Using the {self.target}, {self.name} {_join(self.args)}."
class When(str, enum.Enum):
BEGIN = "BEGIN"
END = "END"
@dataclass
class CallInfo:
callee: callable
args: tuple
kwargs: dict
name: str
instance: t.Optional[object] = None
exception: t.Optional[Exception] = None
result: t.Optional[object] = None
parameters: dict = field(default_factory=dict)
@dataclass
class _WrappedCallable:
wrapped: t.Callable = None
name: str = None
instance: object = None
wrapper: t.Callable = None
def matches_call(self, call: CallInfo) -> bool:
return call.callee is self.wrapped and call.name == self.name
def _wrap_callable(
func: t.Callable,
call_begin: t.Callable[[CallInfo], t.Any],
call_end: t.Callable[[CallInfo], t.Any],
) -> t.Callable[[t.Any], t.Any]:
name = getattr(func, "__name__", None)
instance = getattr(func, "__self__", None)
is_bound_method = instance is not None
def _wrapped(*args, **kwargs):
info = CallInfo(
callee=func,
args=args,
kwargs=kwargs,
name=name,
instance=instance,
# parameters=signature.bind(*args, **kwargs)
)
call_begin(info)
try:
res = func(*args, **kwargs)
except Exception as e:
info.exception = e
raise e from None
else:
info.result = res
finally:
call_end(info)
return _wrapped
@contextlib.contextmanager
def instrument(target, signal_begin=None, signal_end=None):
mp = MonkeyPatch()
_logger.info(f"instrumenting target {target}")
if isinstance(target, tuple) and len(target) == 2:
owner, name = target
instance = None
# TODO check if methodtype?
else:
instance = getattr(target, "__self__", None)
owner = instance.__class__
name = target.__name__
func = getattr(owner, name)
assert callable(func), f"{func} must be callable"
_logger.debug(dict(target=target, name=name, owner=owner, func=func))
def _do_nothing(*args, **kwargs): ...
_patched_callable = _wrap_callable(
func,
call_begin=signal_begin.emit if signal_begin else _do_nothing,
call_end=signal_end.emit if signal_end else _do_nothing,
)
mp.setattr(owner, name, _patched_callable)
patched_info = _WrappedCallable(
wrapped=func,
name=name,
instance=instance,
wrapper=_patched_callable,
)
_logger.debug("returning patched object")
yield patched_info
_logger.debug("start undoing monkeypatching")
mp.undo()
_logger.debug("monkeypatching done")
@dataclass
class _DialogProxy:
window_title: str = ""
text: str = ""
@dataclass
class _ModalPatcher:
dialog_cls: type
scope: t.Optional[ModuleType] = None
def __post_init__(self):
if self.scope:
assert isinstance(self.scope, ModuleType), (
"If given, 'scope' should be a module object, "
f"but it is {type(self.scope)} instead"
)
self._patch = MonkeyPatch()
def _apply_patch(self, owner: object, name: str, replacement: object):
self._patch.setattr(
owner,
name,
replacement,
)
def _replace_entire_class(self, replacement: type):
self._apply_patch(
owner=self.scope, name=self.dialog_cls.__name__, replacement=replacement
)
def _replace_individual_methods(self, replacement: type, method_names: t.List[str]):
for meth_name in method_names:
self._apply_patch(
owner=self.dialog_cls,
name=meth_name,
replacement=getattr(replacement, meth_name),
)
@contextlib.contextmanager
def patching(self, dispatch_func: t.Callable):
# TODO: consider if using type(...) to build the class object would make things clearer
class tmp(self.dialog_cls):
def exec_(inst):
return dispatch_func(inst)
def exec(inst):
return dispatch_func(inst)
def show(inst):
dispatch_func(inst)
def open(inst):
dispatch_func(inst)
if self.scope is not None:
self._replace_entire_class(tmp)
else:
self._replace_individual_methods(
tmp, method_names=["exec_", "exec", "show", "open"]
)
try:
yield self
finally:
self._patch.undo()
@contextlib.contextmanager
def replace_with_signal(target, signal, retval=None):
mp = MonkeyPatch()
_logger.info(f"replacing target {target} with signal {signal}")
if isinstance(target, tuple) and len(target) == 2:
owner, name = target
instance = None
# TODO check if methodtype?
else:
instance = getattr(target, "__self__", None)
owner = instance.__class__
name = target.__name__
func = getattr(owner, name)
assert callable(func), f"{func} must be callable"
_logger.debug(dict(target=target, name=name, owner=owner, func=func))
def _proxy_call(*args, **kwargs):
call_info = CallInfo(
callee=func, args=args, kwargs=kwargs, name=name, instance=instance
)
signal.emit(call_info)
return retval
mp.setattr(owner, name, _proxy_call)
patched_info = _WrappedCallable(
wrapped=func,
name=name,
instance=instance,
wrapper=_proxy_call,
)
_logger.debug("returning patched object")
yield patched_info
_logger.debug("start undoing monkeypatching")
mp.undo()
_logger.debug("monkeypatching done")
class _Signals(QtCore.QObject):
__instance = None
callBegin = QtCore.pyqtSignal(CallInfo)
callEnd = QtCore.pyqtSignal(CallInfo)
actionBegin = QtCore.pyqtSignal(Action)
actionEnd = QtCore.pyqtSignal(Action)
locateBegin = QtCore.pyqtSignal(object)
locateEnd = QtCore.pyqtSignal(object)
callProxy = QtCore.pyqtSignal(CallInfo)
dialogDisplay = QtCore.pyqtSignal(_DialogProxy)
@property
def by_type_and_when(self):
return {
Action: {
When.BEGIN: self.actionBegin,
When.END: self.actionEnd,
},
CallInfo: {
When.BEGIN: self.callBegin,
When.END: self.callEnd,
},
}
def __getitem__(self, key):
return self.by_type_and_when[key]
@classmethod
def instance(cls) -> "_Signals":
if cls.__instance is None:
cls.__instance = cls()
return cls.__instance
def _join(it, sep=" "):
def is_to_skip(s):
return str(s).strip() not in {str(None), ""}
return str.join(sep, [str(_) for _ in it if not is_to_skip(_)])
def action(f):
cls = Action
signals = _Signals.instance()[cls]
name = f.__name__
def _wrapped(*args, **kwargs):
handler = args[0]
action = cls(name=name, target=handler.target, args=args[1:])
signals[When.BEGIN].emit(action)
f(*args, **kwargs)
signals[When.END].emit(action)
...
return _wrapped
class Dispatcher(_SerializableMixin):
log = ObjLogger()
def __init__(self, **kwargs):
self.alias_map = kwargs
def resolve_alias(self, kwargs: dict) -> t.Tuple[type, str]:
alias_map = self.alias_map
alias_in_kwargs: t.Set = kwargs.keys() & alias_map.keys()
self.log.debug(f"alias_in_kwargs={alias_in_kwargs}")
InvalidMatchError.check(alias_in_kwargs, expected=1)
alias = alias_in_kwargs.pop()
widget_cls = alias_map[alias]
return widget_cls, alias
@singledispatchmethod
def get_target(self, widget: W.QWidget, **kwargs):
return Target(widget, dispatcher=self, **kwargs)
@singledispatchmethod
def get_handler(self, widget, *args, **kwargs):
return Handler(widget, *args, **kwargs)
@get_handler.register
def get_table_handler(self, widget: W.QTableWidget, *args, **kwargs):
return TableHandler(widget, *args, **kwargs)
@get_handler.register(list)
def get_handler_from_list(self, widgets: t.List[W.QWidget], *args, **kwargs):
return [self.get_handler(w, *args, **kwargs) for w in widgets]
def as_record(self):
return dict(self.alias_map)
# this should have as little behavior as possible that depends directly on the widget type
# we should be relying on stateless functions managed by singledispatch
class Handler(_SerializableMixin):
log = ObjLogger()
dispatcher = Dispatcher(
button=W.QAbstractButton,
radio_button=W.QRadioButton,
combo_box=W.QComboBox,
group_box=W.QGroupBox,
table=W.QTableWidget,
item_list=W.QListView,
spin_box=W.QSpinBox,
text_edit_area=W.QTextEdit,
line_edit_area=W.QLineEdit,
)
def __init__(self, widget, located_by=None):
self._widget = widget
self._located_by = located_by
@property
def widget(self):
return self._widget
@property
def target(self):
"""
Here we can use some dispatch logic to create a human-readable summary of the widget and how it was located
in the context of the action
"""
return self.widget
@classmethod
def create(cls, *args, **kwargs):
return cls.dispatcher.get_handler(*args, **kwargs)
def locate(self, *args, **kwargs):
_logger.info(f"Starting locate for args: {args}, kwargs: {kwargs}")
if not args:
if not kwargs:
raise ValueError
widget_cls, alias = self.dispatcher.resolve_alias(kwargs)
hint = kwargs.pop(alias)
# locate(button=...)
if hint in KWARGS_PLACEHOLDER_VALUES:
hint = None
# locate(button='Click here')
else:
if not len(args) in {1, 2}:
raise ValueError(f"Invalid number of args specified")
if len(args) == 1:
# locate(QPushButton)
target, hint = args[0], None
else:
# locate(QPushButton, 'Click here')
target, hint = args
if isinstance(target, W.QWidget):
return self.create(target, located_by=None)
elif isinstance(target, type) and issubclass(target, W.QWidget):
widget_cls = target
else:
raise ValueError(f"Invalid type for target: {type(target)}")
search = VisibleWidgetSearch.build(hint=hint, **kwargs)
search.among_children(root=self.widget, widget_cls=widget_cls)
search.summarize()
result = search.result
_logger.info(f"search result: {result}")
return self.create(result, located_by=search)
@action
def click(self):
self._click(self.widget)
@singledispatchmethod
def _click(self, button: W.QAbstractButton):
button.click()
@action
def select(self):
self._select(self.widget)
@singledispatchmethod
def _select(self, radio_button: W.QRadioButton):
radio_button.click()
@action
def set_option(self, *args):
self._set_option(self.widget, *args)
@singledispatchmethod
def _set_option(self, combo_box: W.QComboBox, text=str):
matching_idx = combo_box.findText(text)
if matching_idx == -1:
raise NotEnoughMatchesError()
combo_box.setCurrentIndex(matching_idx)
@_set_option.register
def _(self, list_box: W.QListWidget, text=str):
matches = list_box.findItems(text, QtCore.Qt.MatchExactly)
InvalidMatchError.check(matches, expected=1)
list_box.setCurrentItem(matches[0])
@action
def enter_value(self, val):
self._enter_value(self.widget, val)
@singledispatchmethod
def _enter_value(self, spin_box: W.QSpinBox, val):
spin_box.setValue(val)
@_enter_value.register
def _(self, text_edit: W.QTextEdit, val):
text_edit.setText(str(value))
@action
def select_tab(self, key: t.Union[int, str]):
return self._select_tab(self.widget, key)
def _select_tab(self, tabs: W.QTabWidget, text: str):
for tab_idx in range(tabs.count()):
tab_text = tabs.tabText(tab_idx)
if text in tab_text:
tabs.setCurrentIndex(tab_idx)
return tab_idx
def __repr__(self):
return f"<{type(self).__name__}({self._widget})>"
def as_record(self):
return dict(widget=self.widget, located_by=self._located_by)
TableRowSpec = t.Union[int, str, None]
TableColumnSpec = t.Union[int, str]
@dataclass
class TableRowSearch(_SerializableMixin):
hint: TableRowSpec
idx: int
count: int = None
@classmethod
def run(cls, table, hint: TableRowSpec):
count = table.rowCount()
if isinstance(hint, int):
if hint < count:
idx = hint
else:
raise InvalidMatchError(
f"row index {hint} out of range: (count: {count})"
)
elif hint is None:
if count == 1:
idx = 0
else:
hint = "currentRow"
idx = table.currentRow()
else:
raise ValueError(f"Invalid hint: {hint!r}")
return cls(hint=hint, idx=idx, count=count)
@dataclass
class TableColumnSearch(_SerializableMixin):
hint: TableColumnSpec
idx: int
count: int = None
name: str = None
@classmethod
def get_name(cls, table, idx):
return table.horizontalHeaderItem(idx).text()
@classmethod
def run(cls, table, hint: TableColumnSpec):
count = table.columnCount()
name = None
if isinstance(hint, int):
if hint < count:
idx = hint
else:
raise InvalidMatchError(
f"Column index {hint} out of range: (count: {count})"
)
elif isinstance(hint, str):
name_by_idx = {i: cls.get_name(table, i) for i in range(count)}
for idx, name in name_by_idx.items():
if name == hint:
break
idx = idx
name = name
else:
raise InvalidMatchError(
f'Hint "{hint}" does not match any of {list(name_by_idx.values())}'
)
elif hint is None:
if count == 1:
idx = 0
else:
raise ValueError(f"Invalid hint: {hint!r}")
return cls(
hint=hint, idx=idx, name=name or cls.get_name(table, idx), count=count
)
@dataclass
class TableCellSearch(_SerializableMixin):
idx: t.Tuple[int, int]
row_search: TableRowSearch
column_search: TableColumnSearch
widget: W.QWidget = None
item: W.QTableWidgetItem = None
@classmethod
def run(cls, table, row, col):
row_search = TableRowSearch.run(table, row)
column_search = TableColumnSearch.run(table, col)
idx = row_search.idx, column_search.idx
widget = table.cellWidget(*idx)
item = table.item(*idx)
return cls(
idx=idx,
row_search=row_search,
column_search=column_search,
widget=widget,
item=item,
)
@property
def content(self):
if self.widget is not None:
return self.widget
return self.item
@property
def row_idx(self):
return self.idx[0]
@property
def column_idx(self):
return self.idx[1]
class TableHandler(Handler):
@property
def table(self) -> W.QTableWidget:
return self.widget
@action
def select_row(self, row: TableRowSpec):
search = TableRowSearch.run(self.table, row)
self.table.selectRow(search.idx)
_logger.debug(f"self.table.currentRow()={self.table.currentRow()}")
_logger.debug(f"self.table.currentColumn()={self.table.currentColumn()}")
@action
def select_cell(self, row: TableRowSpec, col: TableColumnSpec):
search = TableCellSearch.run(self.table, row, col)
self.table.setCurrentCell(*search.idx)
@action
def select(self, row: TableRowSpec = None, col: TableColumnSpec = 0):
self.select_cell(row, col)
def has_matching_row(self, row_spec: dict):
for row_idx in range(self.table.rowCount()):
row_matches = {}
for key, val in row_spec.items():
# TODO check if column exists
col_idx = self._get_col_idx(key)
value_in_row = self._get_cell_content(col_idx, row_idx)
row_matches[key] = value_in_row == val
entire_row_matches = all(row_matches.values())
if entire_row_matches:
return row_idx
def locate(
self, row: TableRowSpec = None, column: TableColumnSpec = None, **kwargs
):
"Locate a widget within (i.e. in a cell of) the table."
if column is None and len(kwargs) == 1:
column = set(kwargs.values()).pop()
cell_match = TableCellSearch.run(self.table, row, column)
_logger.debug(f"cell_match: {cell_match}")
return self.create(cell_match.content, located_by=cell_match)
class TreePath:
def __init__(self, indices: t.Iterable[int] = None):
self._indices = list(indices or [])
def with_appended(self, idx):
return type(self)(self._indices + [idx])
def __iter__(self):
return iter(self._indices)
def __str__(self):
return str.join(".", [str(i) for i in self])
@classmethod
def root(cls):
return cls([0])
@dataclass
class WidgetDecoration(_SerializableMixin):
rect: QtCore.QRect
text: str = None
color: t.Any = None
@dataclass
class TextOnOffsetLabel(WidgetDecoration):
line_width: int = 2
line_style: t.Any = QtCore.Qt.SolidLine
text_color: t.Any = QtCore.Qt.white
text_align: t.Any = QtCore.Qt.AlignCenter
def make_text_box(self, text_height: int):
return self.rect.adjusted(0, -text_height, 0, -self.rect.height())
def draw_rect(self, painter):
painter.setPen(QtGui.QPen(self.color, self.line_width, self.line_style))
painter.drawRect(self.rect)
def draw_text(self, painter, text_height):
pen = QtGui.QPen(self.text_color)
text_box = self.make_text_box(text_height)
painter.fillRect(text_box, self.color)
painter.drawRect(text_box)
painter.setPen(pen)
painter.drawText(text_box, self.text_align, self.text)
def __call__(self, painter, text_height):
self.draw_rect(painter)
if self.text:
self.draw_text(painter, text_height)
class Annotations(W.QWidget):
@classmethod
def from_widget(cls, w, color=None, **kwargs):
self = cls(color=color)
cls.add(w, **kwargs)
return cls
def __init__(self, parent=None, color=QtCore.Qt.gray):
super().__init__(parent=parent)
self._items = {}
self._window = None
self.color = color
self.text_height = self.fontMetrics().ascent()
@property
def window(self):
return self._window
@window.setter
def window(self, win):
self._window = win
self.setParent(win)
self.setGeometry(win.rect())
def get_rect(self, w: W.QWidget):
orig = w.rect()
topleft_wrt_window = w.mapTo(self.window, orig.topLeft())
return orig.translated(topleft_wrt_window)
@contextlib.contextmanager
def updating_once(self):
old_update = self.update
self.update = lambda *a, **kw: None
yield self
self.update = old_update
self.update()
def add_widgets(self, *widgets, make_decoration=None, color=None, **kwargs):
self.window = widgets[0].window()
make_decoration = make_decoration or TextOnOffsetLabel
for w in widgets:
key = id(w)
self._items[key] = make_decoration(
rect=self.get_rect(w), color=color or self.color, **kwargs
)
self.update()
@singledispatchmethod
def add(self, widget: W.QWidget, **kwargs):
self.add_widgets(widget, **kwargs)
@singledispatchmethod
def remove(self, key):
del self._items[key]
self.update()
@remove.register
def remove_widget(self, w: W.QWidget):
self.remove(id(w))
@add.register
def add_action(self, action: Action, **kwargs):
self.add(
action.target,
text=action.readable_name,
make_decoration=TextOnOffsetLabel,
**kwargs,
)
@remove.register
def remove_action(self, action: Action):
self.remove(action.target)
def paintEvent(self, ev):
painter = QtGui.QPainter()
painter.begin(self)
for deco in self._items.values():
deco(painter, text_height=self.text_height)
painter.end()
@dataclass
class WidgetInfo:
id_: str
type_: type = None
parent: str = None
text: str = None
is_visible: bool = None
# tree_path: TreePath = None
geometry: t.Any = None
children: t.Dict = None
_widget: W.QWidget = None
@property
def abbrev(self):
return f"{self.type_}(...{self.id_[-5:]})"
@classmethod
def link_display(cls, w):
return cls(id_=str(hex(id(w))), type_=type(w).__qualname__).abbrev
@singledispatchmethod
@classmethod
def collect(cls, w: W.QWidget, parent=None, children=None, **kwargs):
id_ = str(hex(id(w)))
type_ = type(w).__qualname__
info = cls(
id_=id_,
type_=type_,
)
if parent:
info.parent = cls.link_display(parent)
if children:
info.children = {
i: cls.link_display(child) for i, child in enumerate(children)
}
if isinstance(w, W.QWidget):
info.is_visible = w.isVisible()
try:
info.text = get_text(w)
except Exception as e:
pass
return info
@classmethod
def walk(cls, w: W.QWidget, tree_path=None, parent=None, collect=None):
collect = collect or cls.collect
tree_path = tree_path or TreePath.root()
children = w.children()
info = collect(w, parent=parent, children=children, tree_path=tree_path)
yield tree_path, info
for idx, child in enumerate(children):
yield from cls.walk(
child, tree_path=tree_path.with_appended(idx), parent=w, collect=collect
)
def items_to_publish(self):
for k, v in self.__dict__.items():
if v is None or k.startswith("_"):
continue
yield k, v
def as_record(self):
return dict(self.items_to_publish())
class HierarchyInfo(_SerializableMixin):
def __init__(self, root: W.QWidget):
self._root = root
self._items = None
def collect(self, w: W.QWidget, **kwargs):
info = WidgetInfo.collect(w, **kwargs)
info._widget = w
return info
def __iter__(self):
if self._items is None:
self._items = list(WidgetInfo.walk(self._root, collect=self.collect))
return iter(self._items)
def as_record(self):
return {str(path): info.as_record() for path, info in self}
@contextlib.contextmanager
def annotating(self):
known_classes = tuple(Handler.dispatcher.alias_map.values())
paths = []
try:
mann = Annotations(color=QtCore.Qt.blue)
for path, info in self:
path = str(path)
if info.is_visible and isinstance(info._widget, known_classes):
mann.add(info._widget, text=path, text_align=QtCore.Qt.AlignRight)
# ann = Annotation.create(
# info._widget, text=path, color=QtCore.Qt.darkRed,
# )
paths.append(path)
# ann.show()
mann.show()
# yield annotations
yield mann
except Exception as e:
_logger.exception(e)
finally:
mann.hide()
mann.deleteLater()
# for ann in annotations.values():
# ann.deleteLater()
class InvalidMatchError(ValueError):
@classmethod
def check(cls, found: t.Iterable, expected: int = 1, **kwargs):
found = list(found)
n_found = len(found)
if n_found == expected:
return True
exc = NotEnoughMatchesError if n_found < expected else TooManyMatchesError
raise exc(expected=expected, found=found, **kwargs)
def __init__(self, *args, explain: t.Callable = (lambda: None), **kwargs):
super().__init__(*args)
self.kwargs = kwargs
self.explain = explain
def __str__(self):
self.explain()
return super().__str__()