-
Notifications
You must be signed in to change notification settings - Fork 13
/
base_components.py
1880 lines (1561 loc) · 74.9 KB
/
base_components.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
"""
Base Components are the building blocks for your Edifice application.
These components may all be imported from the edifice namespace::
import edifice
from edifice import View, Label
# you can now access edifice.Button, View, etc.
All components in this module inherit from :class:`QtWidgetComponent<edifice.QtWidgetComponent>`
and its props, such as :code:`style` and :code:`on_click`.
This means that all widgets could potentially respond to clicks and are stylable using css-like stylesheets.
The components here can roughly be divided into layout components and content components.
Layout components take a list of children and function as a container for its children;
it is most analogous to the :code:`<div>` html tag.
The two basic layout components are :class:`View<edifice.View>` and :class:`ScrollView<edifice.ScrollView>`.
They take a layout prop, which controls whether children are laid out in a row,
a column, or without any preset layout.
A layout component without children will appear as an empty spot in the window;
of course, you could still set the background color, borders,
and size, making this a handy way of reserving blank spot on the screen
or drawing an empty rectangle.
Content components display some information or control on the window.
The basic component for displaying text is :class:`Label<edifice.Label>`,
which simply displays the given text (or any Python object).
The font can be controlled using the style prop.
The :class:`Icon<edifice.Icon>` component is another handy component, displaying an icon from the
Font Awesome icon set.
Finally, the :class:`Button<edifice.Button>` and :class:`TextInput<edifice.TextInput>`
components allow you to collect input from the user.
"""
# pylint:disable=unused-argument
from . import logger
import asyncio
import functools
import inspect
import logging
import math
logger = logging.getLogger("Edifice")
import os
import re
import typing as tp
import numpy as np
from ._component import BaseComponent, WidgetComponent, RootComponent, register_props
from .qt import QT_VERSION
if QT_VERSION == "PyQt6":
from PyQt6 import QtWidgets
from PyQt6 import QtSvg, QtGui
from PyQt6 import QtCore
else:
from PySide6 import QtCore, QtWidgets, QtSvg, QtGui, QtSvgWidgets
Key = QtCore.Qt.Key
def _ensure_future(fn):
# Ensures future if fn is a coroutine, otherwise don't modify fn
if inspect.iscoroutinefunction(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.ensure_future(fn(*args, **kwargs))
return wrapper
return fn
StyleType = tp.Optional[tp.Union[tp.Mapping[tp.Text, tp.Any], tp.Sequence[tp.Mapping[tp.Text, tp.Any]]]]
RGBAType = tp.Tuple[int, int, int, int]
def _dict_to_style(d, prefix="QWidget"):
d = d or {}
stylesheet = prefix + "{%s}" % (";".join("%s: %s" % (k, v) for (k, v) in d.items()))
return stylesheet
def _array_to_pixmap(arr):
try:
import numpy as np
except ImportError:
raise ValueError("Image src must be filename or QImage or numpy array")
height, width, channel = arr.shape
if arr.dtype == np.float32 or arr.dtype == np.float64:
arr = (255 * arr).round()
arr = arr.astype(np.uint8)
return QtGui.QPixmap.fromImage(QtGui.QImage(arr.data, width, height, channel * width, QtGui.QImage.Format.Format_RGB888))
@functools.lru_cache(30)
def _get_image(path):
return QtGui.QPixmap(path)
def _image_descriptor_to_pixmap(inp):
if isinstance(inp, str):
return _get_image(inp)
elif isinstance(inp, QtGui.QImage):
return QtGui.QPixmap.fromImage(inp)
else:
return _array_to_pixmap(inp)
@functools.lru_cache(100)
def _get_svg_image_raw(icon_path, size):
svg_renderer = QtSvg.QSvgRenderer(icon_path)
image = QtGui.QImage(size, size, QtGui.QImage.Format.Format_ARGB32)
image.fill(0x00000000)
svg_renderer.render(QtGui.QPainter(image))
pixmap = QtGui.QPixmap.fromImage(image)
return pixmap
@functools.lru_cache(100)
def _get_svg_image(icon_path, size, rotation=0, color=(0, 0, 0, 255)):
pixmap = _get_svg_image_raw(icon_path, size)
if color == (0, 0, 0, 255) and rotation == 0:
return pixmap
pixmap = pixmap.copy()
if color != (0, 0, 0, 255):
mask = pixmap.mask()
pixmap.fill(QtGui.QColor(*color))
pixmap.setMask(mask)
if rotation != 0:
w, h = pixmap.width(), pixmap.height()
pixmap = pixmap.transformed(QtGui.QTransform().rotate(rotation))
new_w, new_h = pixmap.width(), pixmap.height()
pixmap = pixmap.copy((new_w - w) // 2, (new_h - h) // 2, w, h)
return pixmap
def _css_to_number(a):
if not isinstance(a, str):
return a
if a.endswith("px"):
return float(a[:-2])
return float(a)
_CURSORS = {
"default": QtCore.Qt.CursorShape.ArrowCursor,
"arrow": QtCore.Qt.CursorShape.ArrowCursor,
"pointer": QtCore.Qt.CursorShape.PointingHandCursor,
"grab": QtCore.Qt.CursorShape.OpenHandCursor,
"grabbing": QtCore.Qt.CursorShape.ClosedHandCursor,
"text": QtCore.Qt.CursorShape.IBeamCursor,
"crosshair": QtCore.Qt.CursorShape.CrossCursor,
"move": QtCore.Qt.CursorShape.SizeAllCursor,
"wait": QtCore.Qt.CursorShape.WaitCursor,
"ew-resize": QtCore.Qt.CursorShape.SizeHorCursor,
"ns-resize": QtCore.Qt.CursorShape.SizeVerCursor,
"nesw-resize": QtCore.Qt.CursorShape.SizeBDiagCursor,
"nwse-resize": QtCore.Qt.CursorShape.SizeFDiagCursor,
"not-allowed": QtCore.Qt.CursorShape.ForbiddenCursor,
"forbidden": QtCore.Qt.CursorShape.ForbiddenCursor,
}
ContextMenuType = tp.Mapping[tp.Text, tp.Union[None, tp.Callable[[], tp.Any], "ContextMenuType"]]
def _create_qmenu(menu: ContextMenuType, parent, title: tp.Optional[tp.Text] = None):
widget = QtWidgets.QMenu(parent)
if title is not None:
widget.setTitle(title)
for key, value in menu.items():
if isinstance(value, dict):
sub_menu = _create_qmenu(value, widget, key)
widget.addMenu(sub_menu)
elif value is None:
widget.addSeparator()
else:
widget.addAction(key, value)
return widget
class QtWidgetComponent(WidgetComponent):
"""Base Qt Widget.
All Qt widgets inherit from this component and its props, which add basic functionality
such as styling and event handlers.
Args:
style: style for the widget. Could either be a dictionary or a list of dictionaries.
See docs/style.md for a primer on styling.
tool_tip:
the tool tip displayed when hovering over the widget.
cursor:
the shape of the cursor when mousing over this widget. Must be one of:
default, arrow, pointer, grab, grabbing, text, crosshair, move, wait, ew-resize,
ns-resize, nesw-resize, nwse-resize, not-allowed, forbidden
context_menu:
the context menu to display when the user right clicks on the widget.
Expressed as a dict mapping the name of the context menu entry to either a function
(which will be called when this entry is clicked) or to another sub context menu.
For example, {"Copy": copy_fun, "Share": {"Twitter": twitter_share_fun, "Facebook": facebook_share_fun}}
css_class:
a string or a list of strings, which will be stored in the "css_class" property of the Qt Widget.
This can be used in an application stylesheet, like:
QLabel[css_class="heading"] { font-size: 18px; }
size_policy:
horizontal and vertical resizing policy, of type `QSizePolicy <https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QSizePolicy.html>`_
on_click:
callback for click events (mouse pressed and released). Takes a QMouseEvent object as argument
on_key_down:
callback for key down events (key pressed). Takes a QKeyEvent object as argument.
The key() method of QKeyEvent returns the raw key pressed (an element of the QtCore.Qt.Key enum,
which is conveniently exposed as edifice.Key).
The text() method returns the unicode of the key press, taking modifier keys (e.g. Shift)
into account.
on_key_up:
callback for key up events (key released). Takes a QKeyEvent object as argument.
on_mouse_down:
callback for mouse down events (mouse pressed). Takes a QMouseEvent object as argument
on_mouse_up:
callback for mouse up events (mouse released). Takes a QMouseEvent object as argument
on_mouse_enter:
callback for mouse enter events (triggered once every time mouse enters widget).
Takes a QMouseEvent object as argument
on_mouse_leave:
callback for mouse leave events (triggered once every time mouse leaves widget).
Takes a QMouseEvent object as argument
on_mouse_move:
callback for mouse move events (triggered every time mouse moves within widget).
Takes a QMouseEvent object as argument
"""
@register_props
def __init__(self, style: StyleType = None,
tool_tip: tp.Optional[tp.Text] = None,
cursor: tp.Optional[tp.Text] = None,
context_menu: tp.Optional[ContextMenuType] = None,
css_class: tp.Optional[tp.Any] = None,
size_policy: tp.Optional[QtWidgets.QSizePolicy] = None,
on_click: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
on_key_down: tp.Optional[tp.Callable[[QtGui.QKeyEvent], tp.Any]] = None,
on_key_up: tp.Optional[tp.Callable[[QtGui.QKeyEvent], tp.Any]] = None,
on_mouse_down: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
on_mouse_up: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
on_mouse_enter: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
on_mouse_leave: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
on_mouse_move: tp.Optional[tp.Callable[[QtGui.QMouseEvent], tp.Any]] = None,
):
super().__init__()
self._height = 0
self._width = 0
self._top = 0
self._left = 0
self._size_from_font = None
self._on_click = None
self._on_key_down = None
self._default_on_key_down = None
self._on_key_up = None
self._default_on_key_up = None
self._on_mouse_enter = None
self._on_mouse_leave = None
self._on_mouse_down = None
self._on_mouse_up = None
self._on_mouse_move = None
self._widget_children = []
self._default_mouse_press_event = None
self._default_mouse_release_event = None
self._default_mouse_move_event = None
self._default_mouse_enter_event = None
self._default_mouse_leave_event = None
self._context_menu = None
self._context_menu_connected = False
if cursor is not None:
if cursor not in _CURSORS:
raise ValueError("Unrecognized cursor %s. Cursor must be one of %s" % (cursor, list(_CURSORS.keys())))
def _destroy_widgets(self):
self.underlying = None
for child in self._widget_children:
child._destroy_widgets()
def _set_size(self, width, height, size_from_font=None):
self._height = height
self._width = width
self._size_from_font = size_from_font
def _get_width(self, children):
if self._width:
return self._width
layout = self.props._get("layout", "none")
if layout == "row":
return sum(max(0, child.component._width + child.component._left) for child in children)
try:
return max(max(0, child.component._width + child.component._left) for child in children)
except ValueError:
return 0
def _get_height(self, children):
if self._height:
return self._height
layout = self.props._get("layout", "none")
if layout == "column":
return sum(max(0, child.component._height + child.component._top) for child in children)
try:
return max(max(0, child.component._height + child.component._top) for child in children)
except ValueError:
return 0
def _mouse_press(self, ev):
if self._on_mouse_down is not None:
self._on_mouse_down(ev)
if self._default_mouse_press_event is not None:
self._default_mouse_press_event(ev)
def _mouse_release(self, ev):
event_pos = ev.pos()
if self._on_mouse_up is not None:
self._on_mouse_up(ev)
if self._default_mouse_release_event is not None:
self._default_mouse_release_event(ev)
geometry = self.underlying.geometry()
if 0 <= event_pos.x() <= geometry.width() and 0 <= event_pos.y() <= geometry.height():
self._mouse_clicked(ev)
self._mouse_pressed = False
def _mouse_clicked(self, ev):
if self._on_click:
self._on_click(ev)
def _set_on_click(self, underlying, on_click):
if on_click is not None:
self._on_click = _ensure_future(on_click)
else:
self._on_click = None
if self._default_mouse_press_event is None:
self._default_mouse_press_event = self.underlying.mousePressEvent
self.underlying.mousePressEvent = self._mouse_press
if self._default_mouse_release_event is None:
self._default_mouse_release_event = self.underlying.mouseReleaseEvent
self.underlying.mouseReleaseEvent = self._mouse_release
def _set_on_key_down(self, underlying, on_key_down):
if self._default_on_key_down is None:
self._default_on_key_down = self.underlying.keyPressEvent
if on_key_down is not None:
self._on_key_down = _ensure_future(on_key_down)
else:
self._on_key_down = self._default_on_key_down
self.underlying.keyPressEvent = self._on_key_down
def _set_on_key_up(self, underlying, on_key_up):
if self._default_on_key_up is None:
self._default_on_key_up = self.underlying.keyReleaseEvent
if on_key_up is not None:
self._on_key_up = _ensure_future(on_key_up)
else:
self._on_key_up = self._default_on_key_up
self.underlying.keyReleaseEvent = self._on_key_up
def _set_on_mouse_down(self, underlying, on_mouse_down):
if on_mouse_down is not None:
self._on_mouse_down = _ensure_future(on_mouse_down)
else:
self._on_mouse_down = None
if self._default_mouse_press_event is None:
self._default_mouse_press_event = self.underlying.mousePressEvent
self.underlying.mousePressEvent = self._mouse_press
def _set_on_mouse_up(self, underlying, on_mouse_up):
if on_mouse_up is not None:
self._on_mouse_up = _ensure_future(on_mouse_up)
else:
self._on_mouse_up = None
if self._default_mouse_release_event is None:
self._default_mouse_release_event = self.underlying.mouseReleaseEvent
self.underlying.mouseReleaseEvent = self._mouse_release
def _set_on_mouse_enter(self, underlying, on_mouse_enter):
if self._default_mouse_enter_event is None:
self._default_mouse_enter_event = self.underlying.enterEvent
if on_mouse_enter is not None:
self._on_mouse_enter = _ensure_future(on_mouse_enter)
self.underlying.enterEvent = self._on_mouse_enter
else:
self._on_mouse_enter = None
self.underlying.enterEvent = self._default_mouse_enter_event
def _set_on_mouse_leave(self, underlying, on_mouse_leave):
if self._default_mouse_leave_event is None:
self._default_mouse_leave_event = self.underlying.leaveEvent
if on_mouse_leave is not None:
self._on_mouse_leave = _ensure_future(on_mouse_leave)
self.underlying.leaveEvent = self._on_mouse_leave
else:
self.underlying.leaveEvent = self._default_mouse_leave_event
self._on_mouse_leave = None
def _set_on_mouse_move(self, underlying, on_mouse_move):
if self._default_mouse_move_event is None:
self._default_mouse_move_event = self.underlying.mouseMoveEvent
if on_mouse_move is not None:
self._on_mouse_move = _ensure_future(on_mouse_move)
self.underlying.mouseMoveEvent = self._on_mouse_move
self.underlying.setMouseTracking(True)
else:
self._on_mouse_move = None
self.underlying.mouseMoveEvent = self._default_mouse_move_event
def _gen_styling_commands(self, children, style, underlying, underlying_layout=None):
commands = []
if underlying_layout is not None:
set_margin = False
new_margin=[0, 0, 0, 0]
if "margin" in style:
new_margin = [_css_to_number(style["margin"])] * 4
style.pop("margin")
set_margin = True
if "margin-left" in style:
new_margin[0] = _css_to_number(style["margin-left"])
style.pop("margin-left")
set_margin = True
if "margin-right" in style:
new_margin[2] = _css_to_number(style["margin-right"])
style.pop("margin-right")
set_margin = True
if "margin-top" in style:
new_margin[1] = _css_to_number(style["margin-top"])
style.pop("margin-top")
set_margin = True
if "margin-bottom" in style:
new_margin[3] = _css_to_number(style["margin-bottom"])
style.pop("margin-bottom")
set_margin = True
set_align = None
if "align" in style:
if style["align"] == "left":
set_align = QtCore.Qt.AlignmentFlag.AlignLeft
elif style["align"] == "center":
set_align = QtCore.Qt.AlignmentFlag.AlignCenter
elif style["align"] == "right":
set_align = QtCore.Qt.AlignmentFlag.AlignRight
elif style["align"] == "justify":
set_align = QtCore.Qt.AlignmentFlag.AlignJustify
elif style["align"] == "top":
set_align = QtCore.Qt.AlignmentFlag.AlignTop
elif style["align"] == "bottom":
set_align = QtCore.Qt.AlignmentFlag.AlignBottom
else:
logger.warning("Unknown alignment: %s", style["align"])
style.pop("align")
if set_margin:
commands.append((underlying_layout.setContentsMargins, new_margin[0], new_margin[1], new_margin[2], new_margin[3]))
if set_align:
commands.append((underlying_layout.setAlignment, set_align))
else:
if "align" in style:
if style["align"] == "left":
set_align = "AlignLeft"
elif style["align"] == "center":
set_align = "AlignCenter"
elif style["align"] == "right":
set_align = "AlignRight"
elif style["align"] == "justify":
set_align = "AlignJustify"
elif style["align"] == "top":
set_align = "AlignTop"
elif style["align"] == "bottom":
set_align = "AlignBottom"
else:
logger.warning("Unknown alignment: %s", style["align"])
style.pop("align")
style["qproperty-alignment"] = set_align
if "font-size" in style:
font_size = _css_to_number(style["font-size"])
if self._size_from_font is not None:
size = self._size_from_font(font_size)
self._width = size[0]
self._height = size[1]
if not isinstance(style["font-size"], str):
style["font-size"] = "%dpx" % font_size
if "width" in style:
if "min-width" not in style:
style["min-width"] = style["width"]
if "max-width" not in style:
style["max-width"] = style["width"]
# else:
# if "min-width" not in style:
# style["min-width"] = self._get_width(children)
if "height" in style:
if "min-height" not in style:
style["min-height"] = style["height"]
if "max-height" not in style:
style["max-height"] = style["height"]
# else:
# if "min-height" not in style:
# style["min-height"] = self._get_height(children)
set_move = False
move_coords = [0, 0]
if "top" in style:
set_move = True
move_coords[1] = _css_to_number(style["top"])
self._top = move_coords[1]
if "left" in style:
set_move = True
move_coords[0] = _css_to_number(style["left"])
self._left = move_coords[0]
if set_move:
commands.append((self.underlying.move, move_coords[0], move_coords[1]))
css_string = _dict_to_style(style, "QWidget#" + str(id(self)))
commands.append((self.underlying.setStyleSheet, css_string))
return commands
def _set_context_menu(self, underlying):
if self._context_menu_connected:
underlying.customContextMenuRequested.disconnect()
self._context_menu_connected = True
underlying.customContextMenuRequested.connect(self._show_context_menu)
def _show_context_menu(self, pos):
if self.props.context_menu is not None:
menu = _create_qmenu(self.props.context_menu, self.underlying)
pos = self.underlying.mapToGlobal(pos)
menu.move(pos)
menu.show()
def _qt_update_commands(self, children, newprops, newstate, underlying, underlying_layout=None):
commands = []
for prop in newprops:
if prop == "style":
style = newprops[prop] or {}
if isinstance(style, list):
# style is nonempty since otherwise the or statement would make it a dict
first_style = style[0].copy()
for next_style in style[1:]:
first_style.update(next_style)
style = first_style
else:
style = dict(style)
commands.extend(self._gen_styling_commands(children, style, underlying, underlying_layout))
elif prop == "size_policy":
if newprops.size_policy is not None:
commands.append((underlying.setSizePolicy, newprops.size_policy))
elif prop == "on_click":
commands.append((self._set_on_click, underlying, newprops.on_click))
if newprops.on_click is not None and self.props.cursor is not None:
commands.append((underlying.setCursor, QtCore.Qt.PointingHandCursor))
elif prop == "on_key_down":
commands.append((self._set_on_key_down, underlying, newprops.on_key_down))
elif prop == "on_key_up":
commands.append((self._set_on_key_up, underlying, newprops.on_key_up))
elif prop == "on_mouse_down":
commands.append((self._set_on_mouse_down, underlying, newprops.on_mouse_down))
elif prop == "on_mouse_up":
commands.append((self._set_on_mouse_up, underlying, newprops.on_mouse_up))
elif prop == "on_mouse_enter":
commands.append((self._set_on_mouse_enter, underlying, newprops.on_mouse_enter))
elif prop == "on_mouse_leave":
commands.append((self._set_on_mouse_leave, underlying, newprops.on_mouse_leave))
elif prop == "on_mouse_move":
commands.append((self._set_on_mouse_move, underlying, newprops.on_mouse_move))
elif prop == "tool_tip":
if newprops.tool_tip is not None:
commands.append((underlying.setToolTip, newprops.tool_tip))
elif prop == "css_class":
css_class = newprops.css_class
if css_class is None:
css_class = []
commands.append((underlying.setProperty, "css_class", css_class))
commands.extend([(underlying.style().unpolish, underlying),
(underlying.style().polish, underlying)])
elif prop == "cursor":
cursor = self.props.cursor or ("default" if self.props.on_click is None else "pointer")
commands.append((underlying.setCursor, _CURSORS[cursor]))
elif prop == "context_menu":
if self._context_menu_connected:
underlying.customContextMenuRequested.disconnect()
if self.props.context_menu is not None:
commands.append((underlying.setContextMenuPolicy, QtCore.Qt.ContextMenuPolicy.CustomContextMenu))
commands.append((self._set_context_menu, underlying))
else:
commands.append((underlying.setContextMenuPolicy, QtCore.Qt.ContextMenuPolicy.DefaultContextMenu))
return commands
class Window(RootComponent):
"""Component that displays its child as a window.
Window will mount its child as a window.
It can be created as a child of any standard container.
This is useful if a window is logically associated with ::
class MyApp(Component):
def render(self):
return View()(
Window(Label("Hello"), title="Hello"),
)
if __name__ == "__main__":
App(MyApp()).start()
Args:
title:
the window title
icon:
the window icon
menu:
the window's menu bar. In some GUI settings, for example Mac OS,
this menu will appear seperately from the window.
on_close:
event handler for when this window is closed.
"""
@register_props
def __init__(self, title: tp.Text = "Edifice Application",
icon:tp.Optional[tp.Union[tp.Text, tp.Sequence]] = None,
menu=None,
on_close: tp.Optional[tp.Callable[[QtGui.QCloseEvent], tp.Any]] = None):
super().__init__()
self._previous_rendering = None
self._on_click = None
self._menu_bar = None
self.underlying = None
def will_unmount(self):
if self._previous_rendering:
self._previous_rendering.underlying.close()
def _set_on_close(self, underlying, on_close):
self._on_close = on_close
if on_close:
underlying.closeEvent = _ensure_future(self._on_close)
else:
underlying.closeEvent = lambda e: None
def _attach_menubar(self, menu_bar, menus):
menu_bar.setParent(self._previous_rendering.underlying)
for menu_title, menu in menus.items():
if not isinstance(menu, dict):
raise ValueError(
"Menu must be a dict of dicts (each of which describes a submenu)")
menu_bar.addMenu(_create_qmenu(menu, menu_title))
def _qt_update_commands(self, children, newprops, newstate):
if len(children) != 1:
raise ValueError("Window can only have 1 child")
child = children[0].component
commands = []
if self._previous_rendering:
old_position = self._previous_rendering.underlying.pos()
if child != self._previous_rendering:
commands.append((self._previous_rendering.underlying.close,))
if old_position:
commands.append((child.underlying.move, old_position))
commands.append((child.underlying.show,))
newprops = self.props
self._menu_bar = None
else:
commands.append((child.underlying.show,))
newprops = self.props
self._menu_bar = None
self._previous_rendering = child
for prop in newprops:
if prop == "title":
commands.append((self._previous_rendering.underlying.setWindowTitle, newprops.title))
elif prop == "on_close":
commands.append((self._set_on_close, self._previous_rendering.underlying, newprops.on_close))
elif prop == "icon" and newprops.icon:
pixmap = _image_descriptor_to_pixmap(newprops.icon)
commands.append((self._previous_rendering.underlying.setWindowIcon, QtGui.QIcon(pixmap)))
elif prop == "menu" and newprops.menu:
if self._menu_bar is not None:
self._menu_bar.setParent(None)
self._menu_bar = QtWidgets.QMenuBar()
commands.append((self._attach_menubar, self._menu_bar, newprops.menu))
return commands
class GroupBox(QtWidgetComponent):
@register_props
def __init__(self, title):
super().__init__()
self.underlying = None
def _initialize(self):
self.underlying = QtWidgets.QGroupBox(self.props.title)
self.underlying.setObjectName(str(id(self)))
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
if len(children) != 1:
raise ValueError("GroupBox expects exactly 1 child, got %s" % len(children))
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying)
commands.append((children[0].component.underlying.setParent, self.underlying))
commands.append((self.underlying.setTitle, self.props.title))
return commands
class Icon(QtWidgetComponent):
"""Display an Icon
.. figure:: /image/icons.png
:width: 300
Two icons. Note that you can set the color and rotation.
Icons are central to modern-looking UI design.
Edifice comes with the Font Awesome (https://fontawesome.com) regular and solid
icon sets, to save you time from looking up your own icon set.
You can specify an icon simplify using its name (and optionally the sub_collection).
Example::
Icon(name="share")
will create a classic share icon.
You can browse and search for icons here: https://fontawesome.com/icons?d=gallery&s=regular,solid
Args:
name:
name of the icon. Search for the name on https://fontawesome.com/icons?d=gallery&s=regular,solid
size:
size of the icon.
collection:
the icon package. Currently only font-awesome is supported.
sub_collection:
for font awesome, either solid or regular
color:
the RGBA value for the icon color
rotation:
an angle (in degrees) for the icon rotation
"""
@register_props
def __init__(self, name: tp.Text, size: int = 10, collection: tp.Text = "font-awesome",
sub_collection: tp.Text = "solid",
color: RGBAType = (0,0,0,255), rotation: float = 0, **kwargs):
super().__init__(**kwargs)
self.underlying = None
def _initialize(self):
self.underlying = QtWidgets.QLabel("")
self.underlying.setObjectName(str(id(self)))
def _render_image(self, icon_path, size, color, rotation):
pixmap = _get_svg_image(icon_path, size, color=color, rotation=rotation)
self.underlying.setPixmap(pixmap)
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
self._set_size(self.props.size, self.props.size)
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying)
icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"icons",
self.props.collection, self.props.sub_collection, self.props.name + ".svg")
if "name" in newprops or "size" in newprops or "collection" in newprops or "sub_collection" in newprops or "color" in newprops or "rotation" in newprops:
commands.append((self._render_image, icon_path, self.props.size, self.props.color, self.props.rotation))
return commands
class Button(QtWidgetComponent):
"""Basic button widget.
.. figure:: /image/textinput_button.png
:width: 300
Button on the right
Set the on_click prop (inherited from QtWidgetComponent) to define the behavior on click.
Args:
title:
the button text
style:
the styling of the button
"""
@register_props
def __init__(self, title: tp.Any = "", **kwargs):
super(Button, self).__init__(**kwargs)
self._connected = False
self.underlying = None
def _initialize(self):
self.underlying = QtWidgets.QPushButton(str(self.props.title))
self.underlying.setObjectName(str(id(self)))
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
size = self.underlying.font().pointSize()
self._set_size(size * len(self.props.title), size, lambda size: (size * len(self.props.title), size))
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying)
for prop in newprops:
if prop == "title":
commands.append((self.underlying.setText, str(newprops.title)))
return commands
class IconButton(Button):
"""Display an Icon Button.
.. figure:: /image/icons.png
:width: 300
Icon button on the very right.
Icons are fairly central to modern-looking UI design;
this component allows you to put an icon in a button.
Edifice comes with the Font Awesome (https://fontawesome.com) regular and solid
icon sets, to save you time from looking up your own icon set.
You can specify an icon simplify using its name (and optionally the sub_collection).
Example::
IconButton(name="share", on_click: self.share)
will create a button with a share icon.
You can browse and search for icons here: https://fontawesome.com/icons?d=gallery&s=regular,solid
Args:
name: name of the icon. Search for the name on https://fontawesome.com/icons?d=gallery&s=regular,solid
size: size of the icon.
collection: the icon package. Currently only font-awesome is supported.
sub_collection: for font awesome, either solid or regular
color: the RGBA value for the icon color
rotation: an angle (in degrees) for the icon rotation
"""
@register_props
def __init__(self, name, size=10, collection="font-awesome", sub_collection="solid",
color=(0, 0, 0, 255), rotation=0, **kwargs):
super().__init__(**kwargs)
def _qt_update_commands(self, children, newprops, newstate):
commands = super()._qt_update_commands(children, newprops, newstate)
icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"icons",
self.props.collection, self.props.sub_collection, self.props.name + ".svg")
size = self.underlying.font().pointSize()
self._set_size(self.props.size + 3 + size * len(self.props.title), size,
lambda size: (self.props.size + 3 + size * len(self.props.title), size))
def render_image(icon_path, size, color, rotation):
pixmap = _get_svg_image(icon_path, size, color=color, rotation=rotation)
self.underlying.setIcon(QtGui.QIcon(pixmap))
if "name" in newprops or "size" in newprops or "collection" in newprops or "sub_collection" in newprops or "color" in newprops or "rotation" in newprops:
commands.append((render_image, icon_path, self.props.size, self.props.color, self.props.rotation))
return commands
class Label(QtWidgetComponent):
"""Basic widget for displaying text.
.. figure:: /image/label.png
:width: 500
Three different label objects. You can embed HTML in labels to get rich text formatting.
Args:
text: the text to display. Can be any Python type; the text prop is converted to a string using str before being displayed
word_wrap: enable/disable word wrapping.
link_open: whether hyperlinks will open to the operating system. Defaults to False. `PySide6.QtWidgets.PySide6.QtWidgets.QLabel.setOpenExternalLinks <https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QLabel.html#PySide6.QtWidgets.PySide6.QtWidgets.QLabel.setOpenExternalLinks>`_
selectable: whether the content of the label can be selected. Defaults to False.
editable: whether the content of the label can be edited. Defaults to False.
"""
@register_props
def __init__(self, text: tp.Any = "", selectable: bool = False, editable: bool = False,
word_wrap: bool = True, link_open: bool = False, **kwargs):
super().__init__(**kwargs)
self.underlying = None
def _initialize(self):
self.underlying = QtWidgets.QLabel(str(self.props.text))
self.underlying.setObjectName(str(id(self)))
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
size = self.underlying.font().pointSize()
self._set_size(size * len(str(self.props.text)), size, lambda size: (size * len(str(self.props.text)), size))
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying, None)
for prop in newprops:
if prop == "text":
commands.append((self.underlying.setText, str(newprops[prop])))
elif prop == "word_wrap":
commands.append((self.underlying.setWordWrap, self.props.word_wrap))
elif prop == "link_open":
commands.append((self.underlying.setOpenExternalLinks, self.props.link_open))
elif prop == "selectable" or prop == "editable":
interaction_flags = 0
change_cursor = False
if self.props.selectable:
change_cursor = True
interaction_flags = (QtCore.Qt.TextInteractionFlag.TextSelectableByMouse | QtCore.Qt.TextInteractionFlag.TextSelectableByKeyboard)
if self.props.editable:
change_cursor = True
# PyQt5 doesn't support bitwise or with ints
# TODO What about PyQt6?
if interaction_flags:
interaction_flags |= QtCore.Qt.TextEditable
else:
interaction_flags = QtCore.Qt.TextEditable
if change_cursor and self.props.cursor is None:
commands.append((self.underlying.setCursor, _CURSORS["text"]))
if interaction_flags:
commands.append((self.underlying.setTextInteractionFlags, interaction_flags))
return commands
class Image(QtWidgetComponent):
"""An image container.
Args:
src: either the path to the image, or an RGB np array, or a QtGui.QImage. The np array must be 3 dimensional (height, width, channels)
scale_to_fit: if True, the image will be scaled to fit inside the container.
"""
@register_props
def __init__(self, src: tp.Any = "", scale_to_fit: bool = True, **kwargs):
super().__init__(**kwargs)
self.underlying = None
def _initialize(self):
self.underlying = QtWidgets.QLabel()
self.underlying.setObjectName(str(id(self)))
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying, None)
commands.append((self.underlying.setScaledContents, self.props.scale_to_fit))
for prop in newprops:
if prop == "src":
commands.append((self.underlying.setPixmap, _image_descriptor_to_pixmap(self.props.src)))
return commands
class ImageSvg(QtWidgetComponent):
"""An SVG Image container.
Args:
src: the path to the SVG image.
"""
@register_props
def __init__(self, src: str, **kwargs):
super().__init__(**kwargs)
self.underlying = None
def _initialize(self):
self.underlying = QtSvgWidgets.QSvgWidget()
self.underlying.setObjectName(str(id(self)))
def _qt_update_commands(self, children, newprops, newstate):
if self.underlying is None:
self._initialize()
commands = super()._qt_update_commands(children, newprops, newstate, self.underlying, None)
for prop in newprops:
if prop == "src":
commands.append((self.underlying.load, self.props.src))
return commands
# TODO
# It seems to me that the type for Completer should be
#
# Callable[[str], str]
#
# But Qt doesn’t like higher-order functions and they’ve done something
# much weirder and more complicated.