Debian Codegraph @

docs/widgets/custom.md

raw symbols SCIP
1 While the default widgets are pretty nifty themselves, sometimes you might wanna do your own thing. Luckily for you, PyTermGUI's `Widget` API is ridiculously easy to build upon!
2
3 ## What to know
4
5 Firstly, you should know some things about the shape and function of various parts of the API.
6
7 ### Output & rendering
8
9 The most important method to a widget is its `get_lines`. This returns a list of strings, which is what is used to eventually display it in the terminal. This method is called a _healthy_ amount, so you probably wanna make all state changes in some other place, so `get_lines` can request _mostly_ static data.
10
11 ### Selectables
12
13 Each widget can be made selectable by either setting `widget._selectables_length` to a non-zero value, or overwriting the `selectables_length` property of said widget.
14
15 If you want to make parent widgets know that your widget can be selected, you can just define `_selectables_length` as 1. If you have multiple inner-widgets you need to handle selecting, you should inherit from `Container` and let it handle all the plumbing for you. If you're interested in how it does all that magic, see it's [selectables](/reference/pytermgui/widgets/containers#pytermgui.widgets.containers.Container.selectables) property, and its [select](/reference/pytermgui/widgets/containers#pytermgui.widgets.containers.Container.select) method.
16
17 ### Input handling
18
19 Both keyboard and mouse inputs are cascaded down from the `WindowManager` to each widget. A widget can mark some input as "handled" and stop it from cascading further by having its handler method return `True`.
20
21 !!! note
22
23 The base `Widget` class may go through some routines for each input, such as calling any widget bindings, or, in the case of mouse inputs, call semantic handlers.
24
25 Because of this, and to ensure future backwards-compatibility (weird phrase, I know), you should start all your input handlers by calling the parent class' handler:
26
27 ```python
28 class MyWidget(Widget):
29 def handle_key(self, key: str) -> bool:
30 if super().handle_key(key):
31 return
32
33 # Do our own handling
34 ```
35
36
37 #### Keyboard input
38
39 The signature of the keyboard handler is pretty simple:
40
41 ```python
42 def handle_key(self, key: str) -> bool
43 ```
44
45 To compare key codes to canonical names (e.g. `CTRL_B` to `\x02`), you can use the `keys` singleton:
46
47 ```python
48 from pytermgui import Widget, keys
49
50
51 class MyWidget(Widget):
52 def handle_key(self, key: str) -> bool:
53 if super().handle_key(key):
54 return True
55
56 if key == keys.CTRL_F:
57 self.do_something()
58 return True
59
60 return False
61 ```
62
63 #### Mouse input
64
65 While terminal mouse inputs are historically pretty hard to handle, PTG offers a simple interface to hide all that paperwork.
66
67 An interface symmetrical to the keyboard handlers exists, and is the base of all that comes below:
68
69 ```python
70 def handle_mouse(self, event: MouseEvent) -> bool:
71 ```
72
73 The only argument is the `event`, which is an instance of [MouseEvent](/reference/pytermgui/ansi_interface/#pytermgui.ansi_interface.MouseEvent). This is what it looks like:
74
75 ```termage-svg height=28 title=inspect(MouseEvent)
76 from pytermgui import MouseEvent, inspect
77
78 print(inspect(MouseEvent))
79 ```
80
81 Depending on your circumstances, you can test the event's `position` or `action` attributes:
82
83 ```python
84 from pytermgui import Widget, MouseEvent, MouseAction
85
86 class MyWidget(Widget):
87 def handle_mouse(self, event: MouseEvent) -> bool:
88 if super().handle_mouse(event):
89 return True
90
91 if event.action == MouseAction.LEFT_CLICK:
92 self.do_something()
93 ```
94
95 Since comparing against actions gets a _li'l_ tedious over time, we have a system called **semantic mouse handlers** to help you. These are optional methods that are looked for when `Widget` is handling some mouse event, and only called when present.
96
97 They all follow the syntax `on_{event_name}`. events can be one of:
98
99 ```python
100 [
101 "left_click",
102 "right_click",
103 "click",
104 "left_drag",
105 "right_drag",
106 "drag",
107 "scroll_up",
108 "scroll_down",
109 "scroll",
110 "shift_scroll_up",
111 "shift_scroll_down",
112 "shift_scroll",
113 "hover",
114 ]
115 ```
116
117 Handler methods are looked for in the order of highest specifity. For example, the following widget:
118
119 ```python
120 from pytermgui import MouseEvent, Widget
121
122
123 class MyWidget(Widget):
124 label: str = "No action"
125
126 def get_lines(self) -> list[str]:
127 return [self.label]
128
129 def on_left_click(self, event: MouseEvent) -> bool:
130 self.label = "Left click"
131
132 return True
133
134 def on_click(self, event: MouseEvent) -> bool:
135 self.label = "Generic click"
136
137 return True
138
139 def handle_mouse(self, event: MouseEvent) -> bool:
140 # Make sure we call the super handler
141 if super().handle_mouse(event):
142 return True
143
144 self.label = "No action"
145 return True
146 ```
147
148 ...will display `Left click` only on left clicks, `Generic click` only on right clicks (as `on_right_click` isn't defined) and `No action` on any other mouse input.
149
150
151 ## FAQ
152
153 ### How do I dynamically update a widget's content?
154
155 The pattern I've come to adopt for this purpose is based on a regularly updated inner state that gets displayed within `get_lines`. For example, let's say we have a `Weather` widget that regularly requests weather information and displays it.
156
157 Here is how I would do it. Take _extra_ notice of the highlighted lines:
158
159 ```termage include=docs/src/widgets/weather.py linenums="1" hl_lines="51 52 62 63 64 65 66 67 68 69"
160 ```
161
162 As you can see, I made the widget inherit `Container`. This is _usually_ what you want when dealing with a widget that:
163
164 - Contains inner content representable by sub-widgets (`Label` in our case)
165 - Has to periodically update said inner content
166
167 We also use a thread to do all the monitoring & updating, instead of doing it in `get_lines` or some other periodically called method. Since `get_lines` is called _very_ regularly, and its time-to-return is critical for the rendering of an application, we need to make sure to avoid putting anything with noticable delays in there.
168
169 ??? warning "Don't overuse threads"
170
171 If you have multiple widgets that run on a thread-based monitor, you are likely better of creating a single master thread that updates every widget periodically. A simple monitor implementation like the following should work alright:
172
173 ```python
174 from __future__ import annotations
175
176 from dataclasses import dataclass, field
177 from threading import Thread
178 from time import sleep, time
179 from typing import Callable
180
181
182 @dataclass
183 class Listener:
184 callback: Callable[[], None]
185 period: float
186 time_till_next: float
187
188
189 @dataclass
190 class Monitor:
191 update_frequency: float = 0.5
192 listeners: list[Listener] = field(default_factory=list)
193
194 def attach(self, callback: Callable[[], None], *, period: float) -> Listener:
195 listener = Listener(callback, period, period)
196 self.listeners.append(listener)
197
198 return listener
199
200 def start(self) -> Monitor:
201 def _monitor() -> None:
202 previous = time()
203
204 while True:
205 elapsed = time() - previous
206
207 for listener in self.listeners:
208 listener.time_till_next -= elapsed
209
210 if listener.time_till_next <= 0.0:
211 listener.callback()
212 listener.time_till_next = listener.period
213
214 previous = time()
215 sleep(self.update_frequency)
216
217 Thread(target=_monitor).start()
218 return self
219 ```
220
221 You can then use this in your widgets:
222
223 ```py
224 from .monitor import Monitor
225 from pytermgui import Container
226
227 monitor = Monitor().start()
228
229 class Weather(Container):
230 def __init__(self, location: str, timeout: float, **attrs: Any) -> None:
231 ... # Standard init code (see above)
232
233 monitor.attach(self._request_and_update, timeout)
234
235 def _request_and_update(self) -> None:
236 self.data = self._request()
237 self.update_content()
238 ```
239
240 **Let's talk about those highlighted lines, shall we?**
241
242 In the first set of lines we send out a request to the (imaginary) external API, and update ourselves accordingly. This update is done in the second set of lines, where the `set_widgets` method is used to overwrite the current widget selection.
243
244 **Why use this method instead of manually overwriting `_widgets`?**
245
246 The reason this method was created in the first place was to simplify the process of:
247
248 - Emptying the container's widgets
249 - Resetting its height
250 - Going through a list, running `auto` on each item and adding it to the container
251
252 It makes things a lot simpler, and it also accounts for any future oddities that mess with the process!