pydevices-pdwidgets 0.0.22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. pdwidgets/__init__.py +160 -0
  2. pdwidgets/_compat.py +11 -0
  3. pdwidgets/_constants.py +90 -0
  4. pdwidgets/_focus.py +122 -0
  5. pdwidgets/_icon_load.py +52 -0
  6. pdwidgets/_themes.py +149 -0
  7. pdwidgets/_util.py +64 -0
  8. pdwidgets/_write_font.py +120 -0
  9. pdwidgets/console.py +258 -0
  10. pdwidgets/display.py +469 -0
  11. pdwidgets/icons/LICENSE +202 -0
  12. pdwidgets/icons/README.md +15 -0
  13. pdwidgets/icons/__init__.py +4 -0
  14. pdwidgets/icons/add_18dp.py +10 -0
  15. pdwidgets/icons/add_24dp.py +11 -0
  16. pdwidgets/icons/add_36dp.py +18 -0
  17. pdwidgets/icons/add_48dp.py +24 -0
  18. pdwidgets/icons/battery_full_color_24dp.py +78 -0
  19. pdwidgets/icons/bluetooth_color_24dp.py +78 -0
  20. pdwidgets/icons/check_box_18dp.py +10 -0
  21. pdwidgets/icons/check_box_24dp.py +11 -0
  22. pdwidgets/icons/check_box_36dp.py +18 -0
  23. pdwidgets/icons/check_box_48dp.py +24 -0
  24. pdwidgets/icons/check_box_outline_blank_18dp.py +10 -0
  25. pdwidgets/icons/check_box_outline_blank_24dp.py +11 -0
  26. pdwidgets/icons/check_box_outline_blank_36dp.py +18 -0
  27. pdwidgets/icons/check_box_outline_blank_48dp.py +24 -0
  28. pdwidgets/icons/close_18dp.py +10 -0
  29. pdwidgets/icons/close_24dp.py +11 -0
  30. pdwidgets/icons/close_36dp.py +18 -0
  31. pdwidgets/icons/close_48dp.py +24 -0
  32. pdwidgets/icons/error_18dp.py +10 -0
  33. pdwidgets/icons/error_24dp.py +11 -0
  34. pdwidgets/icons/error_36dp.py +18 -0
  35. pdwidgets/icons/error_48dp.py +24 -0
  36. pdwidgets/icons/expand_more_18dp.py +10 -0
  37. pdwidgets/icons/expand_more_24dp.py +11 -0
  38. pdwidgets/icons/expand_more_36dp.py +18 -0
  39. pdwidgets/icons/expand_more_48dp.py +24 -0
  40. pdwidgets/icons/home_filled_18dp.py +10 -0
  41. pdwidgets/icons/home_filled_24dp.py +11 -0
  42. pdwidgets/icons/home_filled_36dp.py +18 -0
  43. pdwidgets/icons/home_filled_48dp.py +24 -0
  44. pdwidgets/icons/info_18dp.py +10 -0
  45. pdwidgets/icons/info_24dp.py +11 -0
  46. pdwidgets/icons/info_36dp.py +18 -0
  47. pdwidgets/icons/info_48dp.py +24 -0
  48. pdwidgets/icons/keyboard_arrow_down_18dp.py +10 -0
  49. pdwidgets/icons/keyboard_arrow_down_24dp.py +11 -0
  50. pdwidgets/icons/keyboard_arrow_down_36dp.py +18 -0
  51. pdwidgets/icons/keyboard_arrow_down_48dp.py +24 -0
  52. pdwidgets/icons/keyboard_arrow_left_18dp.py +10 -0
  53. pdwidgets/icons/keyboard_arrow_left_24dp.py +11 -0
  54. pdwidgets/icons/keyboard_arrow_left_36dp.py +18 -0
  55. pdwidgets/icons/keyboard_arrow_left_48dp.py +24 -0
  56. pdwidgets/icons/keyboard_arrow_right_18dp.py +10 -0
  57. pdwidgets/icons/keyboard_arrow_right_24dp.py +11 -0
  58. pdwidgets/icons/keyboard_arrow_right_36dp.py +18 -0
  59. pdwidgets/icons/keyboard_arrow_right_48dp.py +24 -0
  60. pdwidgets/icons/keyboard_arrow_up_18dp.py +10 -0
  61. pdwidgets/icons/keyboard_arrow_up_24dp.py +11 -0
  62. pdwidgets/icons/keyboard_arrow_up_36dp.py +18 -0
  63. pdwidgets/icons/keyboard_arrow_up_48dp.py +24 -0
  64. pdwidgets/icons/menu_18dp.py +10 -0
  65. pdwidgets/icons/menu_24dp.py +11 -0
  66. pdwidgets/icons/menu_36dp.py +18 -0
  67. pdwidgets/icons/menu_48dp.py +24 -0
  68. pdwidgets/icons/notifications_color_24dp.py +78 -0
  69. pdwidgets/icons/radio_button_checked_18dp.py +10 -0
  70. pdwidgets/icons/radio_button_checked_24dp.py +11 -0
  71. pdwidgets/icons/radio_button_checked_36dp.py +18 -0
  72. pdwidgets/icons/radio_button_checked_48dp.py +24 -0
  73. pdwidgets/icons/radio_button_unchecked_18dp.py +10 -0
  74. pdwidgets/icons/radio_button_unchecked_24dp.py +11 -0
  75. pdwidgets/icons/radio_button_unchecked_36dp.py +18 -0
  76. pdwidgets/icons/radio_button_unchecked_48dp.py +24 -0
  77. pdwidgets/icons/remove_18dp.py +10 -0
  78. pdwidgets/icons/remove_24dp.py +11 -0
  79. pdwidgets/icons/remove_36dp.py +18 -0
  80. pdwidgets/icons/remove_48dp.py +24 -0
  81. pdwidgets/icons/toggle_off_18dp.py +10 -0
  82. pdwidgets/icons/toggle_off_24dp.py +11 -0
  83. pdwidgets/icons/toggle_off_36dp.py +18 -0
  84. pdwidgets/icons/toggle_off_48dp.py +24 -0
  85. pdwidgets/icons/toggle_on_18dp.py +10 -0
  86. pdwidgets/icons/toggle_on_24dp.py +11 -0
  87. pdwidgets/icons/toggle_on_36dp.py +18 -0
  88. pdwidgets/icons/toggle_on_48dp.py +24 -0
  89. pdwidgets/icons/warning_18dp.py +10 -0
  90. pdwidgets/icons/warning_24dp.py +11 -0
  91. pdwidgets/icons/warning_36dp.py +18 -0
  92. pdwidgets/icons/warning_48dp.py +24 -0
  93. pdwidgets/pct.py +143 -0
  94. pdwidgets/screen.py +77 -0
  95. pdwidgets/task.py +49 -0
  96. pdwidgets/widget-dependencies.md +78 -0
  97. pdwidgets/widget.py +553 -0
  98. pdwidgets/widgets/__init__.py +130 -0
  99. pdwidgets/widgets/_layout.py +64 -0
  100. pdwidgets/widgets/_raised.py +126 -0
  101. pdwidgets/widgets/accordion.py +81 -0
  102. pdwidgets/widgets/app_bar.py +88 -0
  103. pdwidgets/widgets/badge.py +79 -0
  104. pdwidgets/widgets/bottom_sheet.py +77 -0
  105. pdwidgets/widgets/button.py +264 -0
  106. pdwidgets/widgets/card.py +164 -0
  107. pdwidgets/widgets/chart.py +87 -0
  108. pdwidgets/widgets/check_box.py +55 -0
  109. pdwidgets/widgets/chip.py +106 -0
  110. pdwidgets/widgets/color_picker.py +128 -0
  111. pdwidgets/widgets/column.py +34 -0
  112. pdwidgets/widgets/date_picker.py +176 -0
  113. pdwidgets/widgets/dialog.py +133 -0
  114. pdwidgets/widgets/digital_clock.py +81 -0
  115. pdwidgets/widgets/divider.py +47 -0
  116. pdwidgets/widgets/drawer.py +78 -0
  117. pdwidgets/widgets/dropdown.py +197 -0
  118. pdwidgets/widgets/form.py +74 -0
  119. pdwidgets/widgets/form_row.py +66 -0
  120. pdwidgets/widgets/gauge.py +79 -0
  121. pdwidgets/widgets/grid.py +67 -0
  122. pdwidgets/widgets/icon.py +135 -0
  123. pdwidgets/widgets/icon_button.py +98 -0
  124. pdwidgets/widgets/image.py +117 -0
  125. pdwidgets/widgets/keyboard.py +171 -0
  126. pdwidgets/widgets/label.py +157 -0
  127. pdwidgets/widgets/list_view.py +141 -0
  128. pdwidgets/widgets/menu.py +98 -0
  129. pdwidgets/widgets/navigator.py +90 -0
  130. pdwidgets/widgets/number_stepper.py +121 -0
  131. pdwidgets/widgets/page.py +53 -0
  132. pdwidgets/widgets/password_field.py +77 -0
  133. pdwidgets/widgets/pin_pad.py +82 -0
  134. pdwidgets/widgets/progress_bar.py +138 -0
  135. pdwidgets/widgets/radio_button.py +68 -0
  136. pdwidgets/widgets/radio_group.py +55 -0
  137. pdwidgets/widgets/row.py +34 -0
  138. pdwidgets/widgets/scroll_bar.py +148 -0
  139. pdwidgets/widgets/scroll_view.py +128 -0
  140. pdwidgets/widgets/segmented_control.py +128 -0
  141. pdwidgets/widgets/slider.py +151 -0
  142. pdwidgets/widgets/spinner.py +84 -0
  143. pdwidgets/widgets/switch.py +84 -0
  144. pdwidgets/widgets/tab_view.py +175 -0
  145. pdwidgets/widgets/text_box.py +96 -0
  146. pdwidgets/widgets/text_input.py +119 -0
  147. pdwidgets/widgets/toast.py +108 -0
  148. pdwidgets/widgets/toggle.py +80 -0
  149. pdwidgets/widgets/toggle_button.py +55 -0
  150. pydevices_pdwidgets-0.0.22.dist-info/METADATA +132 -0
  151. pydevices_pdwidgets-0.0.22.dist-info/RECORD +154 -0
  152. pydevices_pdwidgets-0.0.22.dist-info/WHEEL +5 -0
  153. pydevices_pdwidgets-0.0.22.dist-info/licenses/LICENSE +21 -0
  154. pydevices_pdwidgets-0.0.22.dist-info/top_level.txt +1 -0
pdwidgets/__init__.py ADDED
@@ -0,0 +1,160 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `pdwidgets`
6
+ ====================================================
7
+ Provides a collection of widgets for creating graphical user interfaces on embedded systems.
8
+ It includes base classes for widgets, as well as specific widgets such as buttons, labels, sliders, and more.
9
+
10
+ Core (always imported): Display, Screen, Task, Widget, themes, constants.
11
+
12
+ Widgets load lazily via ``__getattr__`` so MCU images only pay for modules you
13
+ touch. Lean path::
14
+
15
+ from pdwidgets.widgets.button import Button
16
+
17
+ Convenience::
18
+
19
+ import pdwidgets as pd
20
+ pd.Button(...) # imports widgets.button on first access
21
+
22
+ See ``widget-dependencies.md`` for the peer import graph.
23
+
24
+ Proportional fonts:
25
+ ``Label`` (and widgets built on it) gains proportional-font rendering when a
26
+ ``font`` module is supplied. That path uses the private
27
+ :mod:`pdwidgets._write_font` helper (fonts from ``write_font_converter``).
28
+
29
+ Timer architecture:
30
+ pdwidgets owns **no** timer of its own. Each :class:`Display` wires itself
31
+ into the shared ``appdev.App`` at construction. Apps just build the UI;
32
+ the app keeps itself alive past the end of the script.
33
+ """
34
+
35
+ import events
36
+ from pygraphics import Area
37
+
38
+ from . import pct
39
+ from ._constants import (
40
+ ALIGN, #: Widget alignment flags (``ALIGN.TOP_LEFT``, ``ALIGN.CENTER``, …).
41
+ DEFAULT_PADDING, #: Default ``(PAD, PAD, PAD, PAD)`` inset for widgets.
42
+ ICON_SIZE, #: Valid icon sizes: ``SMALL`` (18), ``MEDIUM`` (24), ``LARGE`` (36), ``XLARGE`` (48).
43
+ PAD, #: Default padding unit in pixels (2).
44
+ POSITION, #: Bit flags combined into :data:`ALIGN` (``LEFT``, ``TOP``, ``OUTER``, …).
45
+ TEXT_SIZE, #: Romfont heights: ``SMALL`` (8), ``MEDIUM`` (14), ``LARGE`` (16).
46
+ TEXT_WIDTH, #: Fixed romfont character width in pixels (8).
47
+ )
48
+ from ._themes import ColorTheme, IconTheme, get_palette, icon_theme
49
+ from .display import Display, tick
50
+ from .screen import Screen
51
+ from .task import Task
52
+ from .widget import Widget
53
+
54
+ DEBUG = False #: When ``True``, enable extra debug logging in pdwidgets.
55
+ MARK_UPDATES = False #: When ``True``, draw a colored border around flushed areas.
56
+
57
+ # Widget name -> (import path, attribute). Core names live above.
58
+ _LAZY = {
59
+ "Accordion": ("pdwidgets.widgets.accordion", "Accordion"),
60
+ "AppBar": ("pdwidgets.widgets.app_bar", "AppBar"),
61
+ "Badge": ("pdwidgets.widgets.badge", "Badge"),
62
+ "BottomSheet": ("pdwidgets.widgets.bottom_sheet", "BottomSheet"),
63
+ "Button": ("pdwidgets.widgets.button", "Button"),
64
+ "Card": ("pdwidgets.widgets.card", "Card"),
65
+ "Chart": ("pdwidgets.widgets.chart", "Chart"),
66
+ "CheckBox": ("pdwidgets.widgets.check_box", "CheckBox"),
67
+ "Chip": ("pdwidgets.widgets.chip", "Chip"),
68
+ "ColorPicker": ("pdwidgets.widgets.color_picker", "ColorPicker"),
69
+ "Column": ("pdwidgets.widgets.column", "Column"),
70
+ "DatePicker": ("pdwidgets.widgets.date_picker", "DatePicker"),
71
+ "Dialog": ("pdwidgets.widgets.dialog", "Dialog"),
72
+ "DigitalClock": ("pdwidgets.widgets.digital_clock", "DigitalClock"),
73
+ "Divider": ("pdwidgets.widgets.divider", "Divider"),
74
+ "Drawer": ("pdwidgets.widgets.drawer", "Drawer"),
75
+ "Dropdown": ("pdwidgets.widgets.dropdown", "Dropdown"),
76
+ "Form": ("pdwidgets.widgets.form", "Form"),
77
+ "FormRow": ("pdwidgets.widgets.form_row", "FormRow"),
78
+ "Gauge": ("pdwidgets.widgets.gauge", "Gauge"),
79
+ "Grid": ("pdwidgets.widgets.grid", "Grid"),
80
+ "Icon": ("pdwidgets.widgets.icon", "Icon"),
81
+ "IconButton": ("pdwidgets.widgets.icon_button", "IconButton"),
82
+ "Image": ("pdwidgets.widgets.image", "Image"),
83
+ "Keyboard": ("pdwidgets.widgets.keyboard", "Keyboard"),
84
+ "Label": ("pdwidgets.widgets.label", "Label"),
85
+ "ListView": ("pdwidgets.widgets.list_view", "ListView"),
86
+ "Menu": ("pdwidgets.widgets.menu", "Menu"),
87
+ "Navigator": ("pdwidgets.widgets.navigator", "Navigator"),
88
+ "NumberStepper": ("pdwidgets.widgets.number_stepper", "NumberStepper"),
89
+ "Page": ("pdwidgets.widgets.page", "Page"),
90
+ "PasswordField": ("pdwidgets.widgets.password_field", "PasswordField"),
91
+ "PinPad": ("pdwidgets.widgets.pin_pad", "PinPad"),
92
+ "ProgressBar": ("pdwidgets.widgets.progress_bar", "ProgressBar"),
93
+ "RadioButton": ("pdwidgets.widgets.radio_button", "RadioButton"),
94
+ "RadioGroup": ("pdwidgets.widgets.radio_group", "RadioGroup"),
95
+ "Row": ("pdwidgets.widgets.row", "Row"),
96
+ "ScrollBar": ("pdwidgets.widgets.scroll_bar", "ScrollBar"),
97
+ "ScrollView": ("pdwidgets.widgets.scroll_view", "ScrollView"),
98
+ "SegmentedControl": ("pdwidgets.widgets.segmented_control", "SegmentedControl"),
99
+ "Slider": ("pdwidgets.widgets.slider", "Slider"),
100
+ "Spinner": ("pdwidgets.widgets.spinner", "Spinner"),
101
+ "Switch": ("pdwidgets.widgets.switch", "Switch"),
102
+ "TabView": ("pdwidgets.widgets.tab_view", "TabView"),
103
+ "TextBox": ("pdwidgets.widgets.text_box", "TextBox"),
104
+ "TextInput": ("pdwidgets.widgets.text_input", "TextInput"),
105
+ "Toast": ("pdwidgets.widgets.toast", "Toast"),
106
+ "Toggle": ("pdwidgets.widgets.toggle", "Toggle"),
107
+ "ToggleButton": ("pdwidgets.widgets.toggle_button", "ToggleButton"),
108
+ }
109
+
110
+ __all__ = [
111
+ "ALIGN",
112
+ "DEBUG",
113
+ "DEFAULT_PADDING",
114
+ "ICON_SIZE",
115
+ "MARK_UPDATES",
116
+ "pct",
117
+ "PAD",
118
+ "POSITION",
119
+ "TEXT_SIZE",
120
+ "TEXT_WIDTH",
121
+ "Area",
122
+ "ColorTheme",
123
+ "Display",
124
+ "IconTheme",
125
+ "Screen",
126
+ "Task",
127
+ "Widget",
128
+ "events",
129
+ "get_palette",
130
+ "icon_theme",
131
+ "tick",
132
+ ]
133
+ __all__ += list(_LAZY.keys())
134
+
135
+
136
+ def __getattr__(name):
137
+ """Lazily import a widget class listed in ``_LAZY``.
138
+
139
+ Args:
140
+ name: Public widget name (for example ``"Button"``).
141
+
142
+ Returns:
143
+ The resolved class or object.
144
+
145
+ Raises:
146
+ AttributeError: If ``name`` is not a known lazy export.
147
+ """
148
+ spec = _LAZY.get(name)
149
+ if spec is None:
150
+ raise AttributeError(f"module 'pdwidgets' has no attribute {name!r}")
151
+ mod_path, attr = spec
152
+ mod = __import__(mod_path, None, None, [attr])
153
+ val = getattr(mod, attr)
154
+ globals()[name] = val
155
+ return val
156
+
157
+
158
+ def __dir__():
159
+ """Return sorted public names including lazy widget exports."""
160
+ return sorted(set(__all__) | set(globals().keys()))
pdwidgets/_compat.py ADDED
@@ -0,0 +1,11 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Small compatibility helpers for Python hosts without ``micropython``."""
5
+
6
+ try:
7
+ from micropython import const
8
+ except ImportError:
9
+
10
+ def const(value):
11
+ return value
@@ -0,0 +1,90 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ Constants used by the pdwidgets library.
6
+ """
7
+
8
+ from ._compat import const
9
+
10
+ PAD = const(2)
11
+ DEFAULT_PADDING = (PAD, PAD, PAD, PAD)
12
+ TEXT_WIDTH = const(8)
13
+
14
+
15
+ class _Constants:
16
+ """
17
+ A base class for creating a struct-like class. The class may be used to check if a value is one of the built-in values, for instance:
18
+ ```
19
+ CONSTANTS = _Constants()
20
+ if value in CONSTANTS:
21
+ print("Value is valid")
22
+ ```
23
+ May also be used to iterate over the values:
24
+ ```
25
+ CONSTANTS = _Constants()
26
+ for value in CONSTANTS:
27
+ print(value)
28
+ ```
29
+ """
30
+
31
+ @classmethod
32
+ def __contains__(cls, item):
33
+ return item in cls.__dict__.values()
34
+
35
+ @classmethod
36
+ def __iter__(cls):
37
+ return iter(cls.__dict__.values())
38
+
39
+
40
+ class _IconSize(_Constants):
41
+ SMALL = 18
42
+ MEDIUM = 24
43
+ LARGE = 36
44
+ XLARGE = 48
45
+
46
+
47
+ ICON_SIZE = _IconSize()
48
+
49
+
50
+ class _TextSize(_Constants):
51
+ SMALL = 8
52
+ MEDIUM = 14
53
+ LARGE = 16
54
+
55
+
56
+ TEXT_SIZE = _TextSize()
57
+
58
+
59
+ class _Position(_Constants):
60
+ LEFT = 1 << 0
61
+ RIGHT = 1 << 1
62
+ TOP = 1 << 2
63
+ BOTTOM = 1 << 3
64
+ OUTER = 1 << 4
65
+
66
+
67
+ POSITION = _Position()
68
+
69
+
70
+ class _Align(_Constants):
71
+ CENTER = 0 # 0
72
+ TOP_LEFT = POSITION.TOP | POSITION.LEFT # 5
73
+ TOP = POSITION.TOP # 4
74
+ TOP_RIGHT = POSITION.TOP | POSITION.RIGHT # 6
75
+ LEFT = POSITION.LEFT # 1
76
+ RIGHT = POSITION.RIGHT # 2
77
+ BOTTOM_LEFT = POSITION.BOTTOM | POSITION.LEFT # 9
78
+ BOTTOM = POSITION.BOTTOM # 8
79
+ BOTTOM_RIGHT = POSITION.BOTTOM | POSITION.RIGHT # 10
80
+ OUTER_TOP_LEFT = POSITION.TOP | POSITION.LEFT | POSITION.OUTER # 21
81
+ OUTER_TOP = POSITION.TOP | POSITION.OUTER # 20
82
+ OUTER_TOP_RIGHT = POSITION.TOP | POSITION.RIGHT | POSITION.OUTER # 22
83
+ OUTER_LEFT = POSITION.LEFT | POSITION.OUTER # 17
84
+ OUTER_RIGHT = POSITION.RIGHT | POSITION.OUTER # 18
85
+ OUTER_BOTTOM_LEFT = POSITION.BOTTOM | POSITION.LEFT | POSITION.OUTER # 25
86
+ OUTER_BOTTOM = POSITION.BOTTOM | POSITION.OUTER # 24
87
+ OUTER_BOTTOM_RIGHT = POSITION.BOTTOM | POSITION.RIGHT | POSITION.OUTER # 26
88
+
89
+
90
+ ALIGN = _Align()
pdwidgets/_focus.py ADDED
@@ -0,0 +1,122 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Keyboard focus ring for pdwidgets (Tab / Shift-Tab / arrows)."""
5
+
6
+ import events
7
+ import keys
8
+
9
+
10
+ class FocusManager:
11
+ """Tracks focusable widgets and moves focus without a pointer.
12
+
13
+ Pointer modality (:meth:`Widget.set_modal`) remains separate: it captures
14
+ mouse/touch only. FocusManager owns which field receives keystrokes.
15
+ """
16
+
17
+ def __init__(self):
18
+ self._widgets = []
19
+ self._index = -1
20
+
21
+ @property
22
+ def focused(self):
23
+ if 0 <= self._index < len(self._widgets):
24
+ return self._widgets[self._index]
25
+ return None
26
+
27
+ def register(self, widget):
28
+ """Add ``widget`` to the focus ring (idempotent)."""
29
+ if widget not in self._widgets:
30
+ self._widgets.append(widget)
31
+
32
+ def unregister(self, widget):
33
+ """Remove ``widget`` from the focus ring."""
34
+ if widget in self._widgets:
35
+ i = self._widgets.index(widget)
36
+ self._widgets.remove(widget)
37
+ if self._index == i:
38
+ self._index = -1
39
+ if hasattr(widget, "focused"):
40
+ widget.focused = False
41
+ elif self._index > i:
42
+ self._index -= 1
43
+
44
+ def focus(self, widget):
45
+ """Give keyboard focus to ``widget`` (must be registered)."""
46
+ if widget is None:
47
+ self.blur()
48
+ return
49
+ if widget not in self._widgets:
50
+ self.register(widget)
51
+ prev = self.focused
52
+ if prev is widget:
53
+ return
54
+ if prev is not None:
55
+ if hasattr(prev, "focused"):
56
+ prev.focused = False
57
+ if hasattr(prev, "invalidate"):
58
+ prev.invalidate()
59
+ self._index = self._widgets.index(widget)
60
+ if hasattr(widget, "focused"):
61
+ widget.focused = True
62
+ if hasattr(widget, "invalidate"):
63
+ widget.invalidate()
64
+ # Keep TextInput._focused in sync for soft-keyboard fallbacks.
65
+ try:
66
+ from .widgets.text_input import TextInput
67
+
68
+ TextInput._focused = widget if isinstance(widget, TextInput) else None
69
+ except ImportError:
70
+ pass
71
+
72
+ def blur(self):
73
+ """Clear keyboard focus."""
74
+ prev = self.focused
75
+ self._index = -1
76
+ if prev is not None:
77
+ if hasattr(prev, "focused"):
78
+ prev.focused = False
79
+ if hasattr(prev, "invalidate"):
80
+ prev.invalidate()
81
+ try:
82
+ from .widgets.text_input import TextInput
83
+
84
+ TextInput._focused = None
85
+ except ImportError:
86
+ pass
87
+
88
+ def focus_next(self, reverse=False):
89
+ """Move focus to the next (or previous) visible focusable widget."""
90
+ if not self._widgets:
91
+ return
92
+ n = len(self._widgets)
93
+ step = -1 if reverse else 1
94
+ start = self._index if self._index >= 0 else (0 if not reverse else n - 1)
95
+ for i in range(1, n + 1):
96
+ idx = (start + step * i) % n
97
+ w = self._widgets[idx]
98
+ if getattr(w, "visible", True):
99
+ self.focus(w)
100
+ return
101
+
102
+ def handle_key(self, event):
103
+ """Handle Tab / arrows for focus movement.
104
+
105
+ Returns:
106
+ bool: ``True`` if the event was consumed as a focus-change key.
107
+ """
108
+ if not self._widgets or event.type != events.KEYDOWN:
109
+ return False
110
+ key = event.key
111
+ mod = getattr(event, "mod", 0) or 0
112
+ shift = bool(mod & keys.KMOD_SHIFT)
113
+ if key == keys.K_TAB:
114
+ self.focus_next(reverse=shift)
115
+ return True
116
+ if key in (keys.K_DOWN, keys.K_RIGHT):
117
+ self.focus_next(reverse=False)
118
+ return True
119
+ if key in (keys.K_UP, keys.K_LEFT):
120
+ self.focus_next(reverse=True)
121
+ return True
122
+ return False
@@ -0,0 +1,52 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Load icon / image assets into ``FrameBuffer`` instances."""
5
+
6
+ from pygraphics import FrameBuffer
7
+
8
+
9
+ def _from_module(mod):
10
+ """Prefer ``FrameBuffer.from_module``; fall back for native cmod builds."""
11
+ from_module = getattr(FrameBuffer, "from_module", None)
12
+ if from_module is not None:
13
+ return from_module(mod)
14
+ buf = mod.BITMAP
15
+ if not isinstance(buf, bytearray):
16
+ buf = bytearray(buf)
17
+ return FrameBuffer(buf, mod.WIDTH, mod.HEIGHT, mod.FORMAT)
18
+
19
+
20
+ def load_framebuffer(value):
21
+ """Load a framebuffer from a package module name or filesystem path.
22
+
23
+ Package icons are plain Python modules under ``pdwidgets.icons`` (e.g.
24
+ ``pdwidgets.icons.home_filled_36dp``) with ``WIDTH``, ``HEIGHT``,
25
+ ``FORMAT``, and ``BITMAP`` (prefer a writable ``bytearray``). Filesystem
26
+ ``.pbm`` / ``.bmp`` / ``.pgm`` paths still use ``FrameBuffer.from_file``.
27
+ """
28
+ if not isinstance(value, str):
29
+ raise TypeError("icon value must be a module name or file path string")
30
+
31
+ # Dotted import path (no path separators) — preferred for shipped icons.
32
+ if "/" not in value and "\\" not in value and "." in value and not value.endswith(
33
+ (".pbm", ".bmp", ".pgm", ".py")
34
+ ):
35
+ mod = __import__(value, None, None, ("BITMAP", "WIDTH", "HEIGHT", "FORMAT"))
36
+ return _from_module(mod)
37
+
38
+ if value.endswith(".py"):
39
+ # Filesystem .py module (authoring / absolute path).
40
+ try:
41
+ import importlib.util
42
+ except ImportError as exc: # pragma: no cover — CPython authoring helper
43
+ raise ValueError(f"Cannot load .py icon on this interpreter: {value}") from exc
44
+ stem = value.rsplit("/", 1)[-1].rsplit("\\", 1)[-1][:-3]
45
+ spec = importlib.util.spec_from_file_location(stem, value)
46
+ if spec is None or spec.loader is None:
47
+ raise ValueError(f"Cannot load icon module {value!r}")
48
+ mod = importlib.util.module_from_spec(spec)
49
+ spec.loader.exec_module(mod)
50
+ return _from_module(mod)
51
+
52
+ return FrameBuffer.from_file(value)
pdwidgets/_themes.py ADDED
@@ -0,0 +1,149 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ Themes used by the pdwidgets library. The IconTheme class is used to manage icons and the ColorTheme class is used to manage colors.
6
+ """
7
+
8
+ from palettes import get_palette # noqa: F401
9
+
10
+ from ._constants import ICON_SIZE
11
+
12
+
13
+ class IconTheme:
14
+ """Resolve shipped icon assets as importable ``pdwidgets.icons.*`` modules."""
15
+
16
+ _suffix = "dp"
17
+ _pkg = "pdwidgets.icons"
18
+ _home = "home_filled_"
19
+ _up_arrow = "keyboard_arrow_up_"
20
+ _down_arrow = "keyboard_arrow_down_"
21
+ _left_arrow = "keyboard_arrow_left_"
22
+ _right_arrow = "keyboard_arrow_right_"
23
+ _check_box_checked = "check_box_"
24
+ _check_box_unchecked = "check_box_outline_blank_"
25
+ _radio_button_checked = "radio_button_checked_"
26
+ _radio_button_unchecked = "radio_button_unchecked_"
27
+ _toggle_on = "toggle_on_"
28
+ _toggle_off = "toggle_off_"
29
+ _close = "close_"
30
+ _add = "add_"
31
+ _remove = "remove_"
32
+ _info = "info_"
33
+ _warning = "warning_"
34
+ _error = "error_"
35
+ _dropdown = "expand_more_"
36
+ _menu = "menu_"
37
+
38
+ def __init__(self, path=None):
39
+ """Create an icon theme that resolves shipped ``pdwidgets.icons`` modules.
40
+
41
+ Module stems look like ``home_filled_36dp`` (sizes from
42
+ :data:`~pdwidgets.ICON_SIZE`: 18, 24, 36, 48). Access icons via
43
+ attribute callables such as ``icon_theme.home(ICON_SIZE.LARGE)``.
44
+
45
+ Args:
46
+ path (str): Accepted for call-site compatibility and ignored; icons are
47
+ always loaded by module name.
48
+
49
+ Example:
50
+ >>> from pdwidgets import IconTheme, ICON_SIZE, IconButton
51
+ >>> icon_theme = IconTheme()
52
+ >>> IconButton(screen, icon_file=icon_theme.home(ICON_SIZE.LARGE))
53
+ """
54
+ del path # retained for call-site compatibility
55
+
56
+ def _icon(self, name, size):
57
+ if size not in ICON_SIZE:
58
+ raise ValueError("Invalid icon size.")
59
+ stem = f"{getattr(self, '_' + name)}{size}{self._suffix}"
60
+ return f"{self._pkg}.{stem}"
61
+
62
+ def __getattr__(self, name):
63
+ """Return a ``(size) -> module_path`` callable for a named icon.
64
+
65
+ Args:
66
+ name: Icon stem without size or ``dp`` suffix (for example
67
+ ``"home"``, ``"menu"``, ``"close"``).
68
+
69
+ Returns:
70
+ A callable that takes an :data:`~pdwidgets.ICON_SIZE` value and
71
+ returns the fully qualified icon module path.
72
+
73
+ Raises:
74
+ AttributeError: If ``name`` is private (starts with ``_``).
75
+ """
76
+ if name.startswith("_"):
77
+ raise AttributeError(name)
78
+ return lambda size: self._icon(name, size)
79
+
80
+
81
+ icon_theme = IconTheme()
82
+
83
+
84
+ class ColorTheme:
85
+ """
86
+ Semantic color theme for pdwidgets.
87
+
88
+ The default palette is a friendly, slightly colorful "early color Mac" look:
89
+ a soft warm-cream background, near-black ink, and a small set of muted
90
+ pastel accents (slate blue, warm gold, soft coral) with warm greys for
91
+ inactive states — chunky-but-clean rather than a saturated Material blue.
92
+
93
+ Colors are computed through ``pal.color565`` so the display's byteswap is
94
+ respected. Widgets reference these slots by name, so re-skinning the whole
95
+ toolkit is a matter of assigning different values here (or after
96
+ construction via ``display.color_theme``).
97
+
98
+ Args:
99
+ pal (Palette): A palette object from the ``palettes`` package; used only
100
+ for its ``color565`` conversion (and byteswap handling).
101
+ """
102
+
103
+ def __init__(self, pal):
104
+ """Build semantic color slots from a palette's ``color565`` converter.
105
+
106
+ Args:
107
+ pal (Palette): A :class:`~palettes.Palette` (or compatible) object used only
108
+ for ``color565`` conversion and byteswap handling.
109
+ """
110
+ c = pal.color565
111
+ # Neutrals
112
+ self.background = c(0xF2EEE3) # warm cream page
113
+ self.on_background = c(0x2A2A30) # near-black ink
114
+ self.surface = c(0xFBF8F0) # card / raised surface
115
+ self.on_surface = c(0x2A2A30)
116
+ self.surface_variant = c(0xE7E1D3) # subtle sunken panel
117
+ self.outline = c(0xB6AE9C) # hairline borders
118
+ self.shadow = c(0xCAC3B4) # cheap fake drop shadow (warm grey)
119
+ # Accents
120
+ self.primary = c(0x4E6E8E) # muted slate blue
121
+ self.on_primary = c(0xFFFFFF)
122
+ self.primary_variant = c(0x3A536B) # darker slate (pressed / shadow)
123
+ self.secondary = c(0xE6B24C) # warm muted gold
124
+ self.on_secondary = c(0x2A2A30)
125
+ self.secondary_variant = c(0xCC7A5C) # soft coral (third accent)
126
+ self.tertiary = c(0x9E978A) # warm grey (inactive)
127
+ self.on_tertiary = c(0x2A2A30)
128
+ self.tertiary_variant = c(0xC4BDAD) # light warm grey
129
+ # Status
130
+ self.error = c(0xC1544A) # muted brick red
131
+ self.on_error = c(0xFFFFFF)
132
+ self.success = c(0x5E9E6E) # muted green (status dots, badges)
133
+ self.on_success = c(0xFFFFFF)
134
+ self.transparent = False
135
+ # Priority B controls (map widgets to these; no hard-coded RGB)
136
+ # Chip compact filters
137
+ self.chip = self.surface_variant
138
+ self.chip_selected = self.primary
139
+ self.on_chip = self.on_surface
140
+ self.on_chip_selected = self.on_primary
141
+ # Modal sheets / drawers / menus (opaque scrims — no alpha on MCU FB)
142
+ self.sheet_scrim = self.shadow
143
+ self.menu_surface = self.surface
144
+ self.on_menu = self.on_surface
145
+ # SegmentedControl / Accordion chrome
146
+ self.segment = self.surface_variant
147
+ self.segment_selected = self.primary
148
+ self.on_segment = self.on_surface
149
+ self.on_segment_selected = self.on_primary
pdwidgets/_util.py ADDED
@@ -0,0 +1,64 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Internal helpers for pdwidgets."""
5
+
6
+ import events
7
+
8
+
9
+ def _log(*args, **kwargs):
10
+ """Print when ``pdwidgets.DEBUG`` is truthy (checked at call time)."""
11
+ import sys
12
+
13
+ mod = sys.modules.get("pdwidgets")
14
+ if mod is not None and getattr(mod, "DEBUG", False):
15
+ print(*args, **kwargs)
16
+
17
+
18
+ def _cond_pointer(child, event, point):
19
+ """Event condition: child's padded area contains the (translated) pointer."""
20
+ return child.padded_area.contains(point)
21
+
22
+
23
+ def _cond_always(child, event, point):
24
+ """Event condition: always deliver (non-pointer events)."""
25
+ return True
26
+
27
+
28
+ # Input event types delivered to the widget tree (QUIT is handled by the
29
+ # app itself, so it is intentionally excluded).
30
+ _WIDGET_EVENTS = (
31
+ events.KEYDOWN,
32
+ events.KEYUP,
33
+ events.MOUSEMOTION,
34
+ events.MOUSEBUTTONDOWN,
35
+ events.MOUSEBUTTONUP,
36
+ events.MOUSEWHEEL,
37
+ )
38
+
39
+
40
+ _POINTER_EVENTS = (events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP, events.MOUSEMOTION)
41
+
42
+
43
+ _display_drv_get_attrs = {
44
+ "set_vscroll",
45
+ "tfa",
46
+ "bfa",
47
+ "vsa",
48
+ "vscroll",
49
+ "tfa_area",
50
+ "bfa_area",
51
+ "vsa_area",
52
+ "scroll_by",
53
+ "scroll_to",
54
+ "translate_point",
55
+ }
56
+ _display_drv_set_attrs = {"vscroll"}
57
+
58
+
59
+ def _root_screen(widget):
60
+ """Return the top-level screen ancestor of ``widget`` (child of the Display)."""
61
+ node = widget
62
+ while node.parent is not None and node.parent.parent is not None:
63
+ node = node.parent
64
+ return node