-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfcui.py
2608 lines (2176 loc) · 89.6 KB
/
fcui.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
# -*- coding: utf-8 -*-
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# (c) 2024 Frank David Martínez Muñoz.
#
from __future__ import annotations
__author__ = "Frank David Martínez Muñoz"
__copyright__ = "(c) 2024 Frank David Martínez Muñoz."
__license__ = "LGPL 2.1"
__version__ = "1.0.0-beta4"
__min_python__ = "3.10"
__min_freecad__ = "0.22"
# Conventions for sections in this file:
# See: vscode extension: aaron-bond.better-comments
# ──────────────────────────────────────────────────────────────────────────────
# Normal comments
##: Code execute at import time, create objects in global module scope
##$ Template code, meta-programming
##@ Decorators code
##% Type definitions, Widgets, Builders
##! Warning note
# ──────────────────────────────────────────────────────────────────────────────
##: [SECTION] Builtin Imports
##: ────────────────────────────────────────────────────────────────────────────
import json
import re
import sys
import threading
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple, Union, Hashable
##: [SECTION] FreeCAD Imports
##: ────────────────────────────────────────────────────────────────────────────
import FreeCAD as App # type: ignore
import FreeCADGui as Gui # type: ignore
from FreeCAD import Base # type: ignore
##: [SECTION] Qt/PySide Imports
##: ────────────────────────────────────────────────────────────────────────────
from PySide.QtCore import ( # type: ignore
QMargins,
QObject,
QPoint,
QRect,
Qt,
QTimer,
Signal,
Slot,
)
from PySide.QtGui import ( # type: ignore
QAbstractItemView,
QApplication,
QBrush,
QCheckBox,
QCloseEvent,
QColor,
QComboBox,
QDialog,
QDoubleSpinBox,
QFileDialog,
QFontDatabase,
QFrame,
QGroupBox,
QHBoxLayout,
QIcon,
QLabel,
QLayout,
QLineEdit,
QMainWindow,
QMessageBox,
QPainter,
QPaintEvent,
QPen,
QPixmap,
QPlainTextEdit,
QPushButton,
QAbstractButton,
QScrollArea,
QSpinBox,
QSplitter,
QTableWidget,
QTableWidgetItem,
QTabWidget,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from PySide.QtSvg import QSvgRenderer # type: ignore
##: [SECTION] Type Aliases
##: ────────────────────────────────────────────────────────────────────────────
Numeric = Union[int, float]
Vector = Base.Vector
##: [SECTION] Core Widgets, Contexts and Decorators
##: ────────────────────────────────────────────────────────────────────────────
# ──────────────────────────────────────────────────────────────────────────────
def set_qt_attrs(qobject: QObject, **kwargs):
"""
Call setters on Qt objects by argument names.
:param QObject qobject: Object instance.
:param dict[str, Any] kwargs: dict of property_name to value.
"""
for name, value in kwargs.items():
if value is not None:
if name == "properties":
for prop_name, prop_value in value.items():
qobject.setProperty(prop_name, prop_value)
continue
setter = getattr(qobject, f"set{name[0].upper()}{name[1:]}", None)
if setter:
if isinstance(value, tuple):
setter(*value)
else:
setter(value)
else:
raise NameError(f"Invalid property {name}")
# ──────────────────────────────────────────────────────────────────────────────
def setup_layout(layout: QLayout, add: bool = True, **kwargs):
"""
Setup layouts adding wrapper widget if required.
"""
set_qt_attrs(layout, **kwargs)
parent = build_context().current()
if parent.layout() is not None or add is False:
w = QWidget()
w.setLayout(layout)
if add:
parent.layout().addWidget(w)
with build_context().stack(w):
yield w
else:
parent.setLayout(layout)
yield parent
# ──────────────────────────────────────────────────────────────────────────────
def place_widget(
widget: QWidget,
label: Union[QWidget, str] = None,
stretch: int = 0,
alignment=Qt.Alignment(),
) -> None:
"""
Place widget in layout.
"""
current = build_context().current()
if isinstance(current, QScrollArea):
if current.widget():
raise ValueError("Scroll can contains only one widget")
current.setWidget(widget)
return
if isinstance(current, QSplitter):
current.addWidget(widget)
return
if isinstance(current, QMainWindow):
current.setCentralWidget(widget)
return
layout = current.layout()
if layout is None:
layout = build_context().default_layout_provider()
current.setLayout(layout)
if label is None:
layout.addWidget(widget, stretch, alignment)
else:
layout.addWidget(widget_with_label_row(widget, label, stretch, alignment))
##% [Widget] QWidget with label and widget in Vertical or Horizontal layout
##% ────────────────────────────────────────────────────────────────────────────
def widget_with_label_row(
widget: QWidget,
label: Union[QWidget, str],
stretch: int = 0,
alignment=Qt.Alignment(),
orientation: Qt.Orientation = Qt.Orientation.Horizontal,
) -> QWidget:
"""
Create a widget with a label and widget.
"""
row = QWidget()
if orientation == Qt.Orientation.Vertical:
layout = QVBoxLayout()
else:
layout = QHBoxLayout()
row.setLayout(layout)
layout.setContentsMargins(0, 0, 0, 0)
if isinstance(label, QWidget):
layout.addWidget(label)
elif label:
layout.addWidget(QLabel(str(label)))
layout.addWidget(widget, stretch, alignment)
return row
##% Color
##% ────────────────────────────────────────────────────────────────────────────
class Color(QColor):
"""
QColor with additional constructor for hex rgba color code.
Use like Color(code='#ff0000'), Color(code='#ff0000ff')
"""
def __init__(self, *args, code: str = None, alpha: float = None, **kwargs):
if code is not None:
if code.startswith("#"):
code = code[1:]
if len(code) < 8:
code += "FFFFFFFF"
r, g, b, a = (
int(code[:2], 16),
int(code[2:4], 16),
int(code[4:6], 16),
int(code[6:8], 16),
)
super().__init__(r, g, b, a)
elif len(args) == 1 and isinstance(args[0], QColor):
super().__init__()
self.setRgba(args[0].rgba())
else:
super().__init__(*args, **kwargs)
if isinstance(alpha, float):
self.setAlphaF(alpha)
def __str__(self) -> str:
return f"rgba({self.red()},{self.green()},{self.blue()},{self.alpha()})"
##% [Widget] ColorIcon
##% ────────────────────────────────────────────────────────────────────────────
class ColorIcon(QIcon):
"""
Monochromatic Icon with transparent background.
"""
def __init__(self, path, color):
pixmap = QPixmap(path)
mask = pixmap.createMaskFromColor(QColor("transparent"), Qt.MaskInColor)
pixmap.fill(color)
pixmap.setMask(mask)
super().__init__(pixmap)
self.setIsMask(True)
##% PySignal
##% ───────────────────────────────────────────────────────────────────────────
class PySignal:
"""
Imitate Qt Signals for non QObject objects
"""
_listeners: Set[Callable]
def __init__(self):
self._listeners = set()
def connect(self, listener: Callable):
self._listeners.add(listener)
def disconnect(self, listener: Callable):
try:
self._listeners.remove(listener)
except KeyError:
pass # Not found, Ok
def emit(self, *args, **kwargs):
for listener in self._listeners:
listener(*args, **kwargs)
##@ [Decorator] on_event
##@ ────────────────────────────────────────────────────────────────────────────
def on_event(target, event=None):
"""
Event binder decorator. Connects the decorated function to `event` signal
on all targets.
:param QObject | Signal | list[QObject|Signal] target: target object or objects.
:param str event: name of the signal.
"""
if not target:
raise ValueError("Invalid empty target")
if not isinstance(target, (list, tuple, set)):
target = [target]
if event is None:
def deco(fn):
for t in target:
t.connect(fn)
return fn
else:
def deco(fn):
for t in target:
getattr(t, event).connect(fn)
return fn
return deco
##% SelectedObject
##% ────────────────────────────────────────────────────────────────────────────
class SelectedObject:
"""
Store Selection information of a single object+sub
"""
def __init__(self, doc: str, obj: str, sub: str = None, pnt: Vector = None):
self.doc = doc
self.obj = obj
self.sub = sub
self.pnt = pnt
def __iter__(self):
yield App.getDocument(self.doc).getObject(self.obj)
yield self.sub
yield self.pnt
def __repr__(self) -> str:
return f"{self.doc}#{self.obj}.{self.sub}"
def __hash__(self) -> int:
return hash((self.doc, self.obj, self.sub))
def __eq__(self, __o: object) -> bool:
return hash(self) == hash(__o)
def __ne__(self, __o: object) -> bool:
return not self.__eq__(__o)
def resolve_object(self):
return App.getDocument(self.doc).getObject(self.obj)
def resolve_sub(self):
return getattr(self.resolve_object(), self.sub)
# ──────────────────────────────────────────────────────────────────────────────
def register_select_observer(owner: QWidget, observer):
"""Add observer with auto remove on owner destroyed"""
Gui.Selection.addObserver(observer)
def destroyed(*_):
Gui.Selection.removeObserver(observer)
owner.destroyed.connect(destroyed)
# [Context] selection
# ──────────────────────────────────────────────────────────────────────────────
@contextmanager
def selection(*names, clean: bool = True, doc: App.Document = None):
"""
Add objects identified by names into current selection.
:param bool clean: remove selection at the end, defaults to True
:param App.Document doc: Document, defaults to App.ActiveDocument
:yield list[DocumentObject]: list of selected objects.
"""
sel = Gui.Selection
try:
doc_name = (doc or App.ActiveDocument).Name
if len(names) == 0:
yield sel.getSelection(doc_name)
else:
sel.clearSelection()
for name in names:
if isinstance(name, (tuple, list)):
sel.addSelection(doc_name, *name)
elif isinstance(name, SelectedObject):
sel.addSelection(name.doc, name.obj, name.sub)
else:
sel.addSelection(doc_name, name)
yield sel.getSelection(doc_name)
finally:
if clean:
sel.clearSelection()
##% BuildContext class
##% ────────────────────────────────────────────────────────────────────────────
class _BuildContext:
"""
Qt Widget tree build context and stack
"""
def __init__(self):
self._stack = []
self.default_layout_provider = QVBoxLayout
def push(self, widget):
self._stack.append(widget)
def pop(self):
self._stack.pop()
def reset(self):
last = self._stack[-1] if self._stack else None
self._stack = []
return last
@contextmanager
def stack(self, widget):
self.push(widget)
try:
yield widget
finally:
self.pop()
@contextmanager
def parent(self):
if len(self._stack) > 1:
current = self._stack[-1]
self._stack.pop()
parent = self._stack[-1]
try:
yield parent
finally:
self._stack.append(current)
def current(self):
return self._stack[-1]
def dump(self):
print(f"BuildContext: {self._stack}")
# ──────────────────────────────────────────────────────────────────────────────
def build_context() -> _BuildContext:
"""
Build context for the current thread.
"""
bc = getattr(_thread_local_gui_vars, "BuildContext", None)
if bc is None:
_thread_local_gui_vars.BuildContext = _BuildContext()
return _thread_local_gui_vars.BuildContext
else:
return bc
##% [Context] Parent
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Parent():
"""Put parent in context"""
with build_context().parent() as p:
yield p
##% Dialogs
##% ────────────────────────────────────────────────────────────────────────────
class Dialogs:
"""
Keeps a list of Active dialogs
"""
_list = []
@classmethod
def dump(cls):
print(f"Dialogs: {cls._list}")
@classmethod
def register(cls, dialog):
cls._list.append(dialog)
dialog.closeEvent = lambda e: cls.destroy_dialog(dialog)
@classmethod
def destroy_dialog(cls, dlg):
cls._list.remove(dlg)
dlg.deleteLater()
@classmethod
def open(cls, w, modal: bool = True):
Dialogs.register(w)
if modal:
w.open()
else:
w.show()
try:
w.raise_() # Mac ?? Wayland ??
except Exception as ex:
print_err(str(ex))
if hasattr(w, "requestActivate"):
w.requestActivate()
##% [Widget Impl] DialogWidget
##% ────────────────────────────────────────────────────────────────────────────
class DialogWidget(QDialog):
"""
Simple Dialog with onClose as signal.
"""
onClose = Signal(QCloseEvent)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def closeEvent(self, event: QCloseEvent):
self.onClose.emit(event)
super().closeEvent(event)
##% [Widget] Dialog
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Dialog(
title: str = None,
*,
size: Tuple[int, int] = None,
show: bool = True,
modal: bool = True,
parent: QWidget = None,
**kwargs,
) -> Generator[QDialog, Any, Any]:
"""
Dialog context manager/widget.
Example:
~:code:../examples/ui/widgets.py[Dialog]:~
:param str title: window title, defaults to None
:param Tuple[int, int] size: dialog size, defaults to None
:param bool show: show automatically, defaults to True
:param bool modal: window modality, defaults to True
:param QWidget parent: parent widget, defaults to None
:param Dict[str, Any] **kwargs: Qt properties
:return QDialog: The Dialog
"""
if parent is None:
parent = find_active_window()
w = DialogWidget(parent=parent)
if title is not None:
w.setWindowTitle(title)
set_qt_attrs(w, **kwargs)
build_context().reset()
with build_context().stack(w):
yield w
if isinstance(size, (tuple, list)):
w.resize(size[0], size[1])
else:
w.adjustSize()
if show:
Dialogs.open(w, modal)
##% [Widget] Scroll
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Scroll(*, add: bool = True, **kwargs) -> Generator[QScrollArea, Any, Any]:
"""
Scrollable area context manager/widget.
Example:
~:code:../examples/ui/widgets.py[Scroll]:~
:param bool add: add to context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QScrollArea: Scroll widget
"""
w = QScrollArea()
set_qt_attrs(w, **kwargs)
if add:
place_widget(w)
with build_context().stack(w):
yield w
##% [Widget] GroupBox
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def GroupBox(
title: str = None,
*,
add: bool = True,
**kwargs,
) -> Generator[QGroupBox, Any, Any]:
"""
GroupBox context manager/widget.
Example:
~:code:../examples/ui/widgets.py[GroupBox]:~
:param str title: Group title, defaults to None
:param bool add: add to context, defaults to True
:param bool add: add to context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QGroupBox: The group widget
"""
w = QGroupBox()
if title:
w.setTitle(title)
set_qt_attrs(w, **kwargs)
if add:
place_widget(w)
with build_context().stack(w):
yield w
##% [Widget] Container
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Container(*, add: bool = True, **kwargs) -> Generator[QFrame, Any, Any]:
"""
Simple container context/widget.
Example
~:code:../examples/ui/widgets.py[Scroll]:~
:param bool add: add to context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QFrame: The container widget
"""
w = QWidget()
set_qt_attrs(w, **kwargs)
if add:
place_widget(w)
with build_context().stack(w):
yield w
##% [Layout tool] Stretch
##% ────────────────────────────────────────────────────────────────────────────
def Stretch(stretch: int = 0) -> None:
"""
Adds stretch factor to the current layout
:param int stretch: 0-100 stretch factor, defaults to 0
"""
layout = build_context().current().layout()
if layout:
layout.addStretch(stretch)
##% [Layout tool] Spacing
##% ────────────────────────────────────────────────────────────────────────────
def Spacing(size: int) -> None:
"""
Adds spacing ro the current layout.
:param int size: spacing
"""
layout = build_context().current().layout()
if layout:
layout.addSpacing(size)
##% [Widget] TabContainer
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def TabContainer(
*,
stretch: int = 0,
add: bool = True,
**kwargs,
) -> Generator[QTabWidget, Any, Any]:
"""
Tab Container context/widget
Example:
~:code:../examples/ui/widgets.py[TabContainer]:~
:param int stretch: stretch, defaults to 0
:param bool add: add to the context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QTabWidget: The widget
"""
w = QTabWidget()
set_qt_attrs(w, **kwargs)
if add:
place_widget(w, stretch=stretch)
with build_context().stack(w):
yield w
##% [Widget] Tab
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Tab(
title: str,
*,
icon: QIcon = None,
add: bool = True,
**kwargs,
) -> Generator[QWidget, Any, Any]:
"""
Tab widget/context in a tab container
Example:
~:code:../examples/ui/widgets.py[TabContainer]:~
:param str title: Tab's title
:param QIcon icon: Icon, defaults to None
:param bool add: add to the context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QWidget: the widget
"""
w = QWidget()
set_qt_attrs(w, **kwargs)
with build_context().stack(w):
yield w
if add:
if icon:
build_context().current().addTab(w, icon, title)
else:
build_context().current().addTab(w, title)
##% [Widget] Splitter
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Splitter(*, add=True, **kwargs) -> Generator[QSplitter, Any, Any]:
"""
Split context/container
Example:
~:code:../examples/ui/widgets.py[Splitter]:~
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QSplitter: The splitter widget
"""
w = QSplitter()
set_qt_attrs(w, **kwargs)
if add:
place_widget(w)
with build_context().stack(w):
yield w
##% [Layout] Col (Vertical Box)
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Col(*, add: bool = True, **kwargs) -> Generator[QWidget, Any, Any]:
"""
Vertical context/layout
Example:
~:code:../examples/ui/widgets.py[Col]:~
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QWidget: A container widget with Vertical layout
"""
yield from setup_layout(QVBoxLayout(), add=add, **kwargs)
##% [Layout] Row (Horizontal Box)
##% ────────────────────────────────────────────────────────────────────────────
@contextmanager
def Row(*, add: bool = True, **kwargs):
"""
Horizontal context/layout
Example:
~:code:../examples/ui/widgets.py[Row]:~
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QWidget: A container widget with Horizontal layout
"""
yield from setup_layout(QHBoxLayout(), add=add, **kwargs)
##% [Widget Impl] HtmlWidget
##% ────────────────────────────────────────────────────────────────────────────
class HtmlWidget(QLabel):
"""
Html template widget.
"""
VAR_RE = re.compile(r"\{\{(.*?)\}\}") # template var: {{name}}
base_path: Path
css: str
def __init__(self, base_path: Path, css: str):
super().__init__()
self.css = css or ""
self.base_path = base_path
def interpolator(self, variables: Dict[str, Any]):
if variables:
def replacer(match: re.Match) -> str:
var_name = match.group(1)
if var_name == "__base__":
return str(self.base_path)
return str(variables.get(var_name, ""))
else:
def replacer(match: re.Match) -> str:
if match.group(1) == "__base__":
return str(self.base_path)
else:
return ""
return replacer
def setValue(self, html: str, variables: Dict[str, Any] = None):
content = HtmlWidget.VAR_RE.sub(self.interpolator(variables), html)
self.setText(f"<style>{self.css}</style>{content}")
##% [Widget] Html
##% ────────────────────────────────────────────────────────────────────────────
def Html(
*,
html: str = None,
file: str = None,
css: str = None,
css_file: str = None,
base_path: str = None,
background: str = None,
stretch: int = 0,
alignment: Qt.Alignment = Qt.Alignment(),
variables: Dict[str, Any] = None,
add: bool = True,
**kwargs,
) -> HtmlWidget:
"""
Basic HTML Render widget
Example:
~:code:../examples/ui/widgets.py[Html]:~
:param str html: raw html content, defaults to None
:param str file: path to html file, defaults to None
:param str css: raw css code, defaults to None
:param str css_file: path to css file, defaults to None
:param str base_path: base dir for loading resources, defaults to None
:param str background: background color code, defaults to None
:param int stretch: layout stretch, defaults to 0
:param Qt.Alignment alignment: layout alignment, defaults to Qt.Alignment()
:param Dict[str, Any] variables: interpolation variables, defaults to None
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties of QLabel
:return HtmlWidget: Html Widget
"""
if html and file:
raise ValueError("html and file arguments are mutually exclusive")
if base_path:
base_path = Path(base_path)
if file:
file = Path(base_path, file)
if css_file:
css_file = Path(base_path, css_file)
elif file:
base_path = Path(file).parent
if css_file:
css_file = Path(base_path, css_file)
if html is None:
with open(file, "r") as f:
html = f.read()
base_css = ""
if css_file:
with open(css_file, "r") as f:
base_css = f.read()
if css is not None:
base_css += css
label = HtmlWidget(base_path, base_css)
label.setValue(html, variables)
if background is not None:
label.setStyleSheet(f"background-color: {background};")
set_qt_attrs(label, **kwargs)
if add:
place_widget(label, stretch=stretch, alignment=alignment)
return label
##% [Widget] TextLabel
##% ────────────────────────────────────────────────────────────────────────────
def TextLabel(
text: str = "",
*,
stretch: int = 0,
alignment: Qt.Alignment = Qt.Alignment(),
add: bool = True,
**kwargs,
) -> QLabel:
"""
Simple text label widget
Example:
~:code:../examples/ui/widgets.py[TextLabel]:~
:param str text: text, defaults to ""
:param int stretch: layout stretch, defaults to 0
:param Qt.Alignment alignment: layout alignment, defaults to Qt.Alignment()
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties of QLabel
:return QLabel: The widget
"""
label = QLabel(text)
set_qt_attrs(label, **kwargs)
if add:
place_widget(label, stretch=stretch, alignment=alignment)
return label
##% [Widget] InputFloat
##% ────────────────────────────────────────────────────────────────────────────
def InputFloat(
value: float = 0.0,
*,
name: str = None,
min: float = 0.0,
max: float = sys.float_info.max,
decimals: int = 6,
step: float = 0.01,
label: Union[QWidget, str] = None,
stretch: int = 0,
alignment: Qt.Alignment = Qt.Alignment(),
add: bool = True,
**kwargs,
) -> QDoubleSpinBox:
"""
Input float widget
Example:
~:code:../examples/ui/widgets.py[InputFloat]:~
:param float value: initial value, defaults to 0.0
:param str name: objectName, defaults to None
:param float min: minimum accepted value, defaults to 0.0
:param float max: maximum accepted value, defaults to sys.float_info.max
:param int decimals: decimal digits, defaults to 6
:param float step: spin steps, defaults to 0.01
:param Union[QWidget, str] label: ui label, defaults to None
:param int stretch: layout stretch, defaults to 0
:param Qt.Alignment alignment: layout alignment, defaults to Qt.Alignment()
:param bool add: add to current context, defaults to True
:param Dict[str, Any] **kwargs: Qt properties
:return QDoubleSpinBox: The input widget
"""
widget = QDoubleSpinBox()
widget.setMinimum(min)
widget.setMaximum(max)
widget.setSingleStep(step)
widget.setDecimals(decimals)
widget.setValue(value)
set_qt_attrs(widget, **kwargs)
if name:
widget.setObjectName(name)
if add:
place_widget(widget, label=label, stretch=stretch, alignment=alignment)
return widget