Debian Codegraph @

docs/walkthroughs/inline.md

raw symbols SCIP
1 Our objective today will be to implement a function that lets us use PyTermGUI widgets in an inline-context, e.g. from the terminal prompt while retaining the shell's state.
2
3 This type of usage is common for simple prompts that are part of a greater, CLI-based application; they give you the cool-factor of the TUI, and in our case its mouse & keyboard input options, while staying in a CLI environment.
4
5 ```termage-svg height=9 include=docs/src/inline_login.py
6 ```
7
8 ## Defining our goals
9
10 Our target syntax will be this:
11
12 ```python
13 prompt_widget = ptg.inline(built_prompt())
14 ```
15
16 ...which gives us the general signature:
17
18 ```python
19 def inline(widget):
20 ...
21
22 return widget
23 ```
24
25 ## Basic implementation
26
27 Let's start with getting the widget to read keyboard inputs and render after each one of them. To do this, we will sit in a `while` loop, use the [getch](/reference/pytermgui/input#pytermgui.input.getch) function and send its output to our widget's [handle_key](/reference/pytermgui/widgets/base#pytermgui.widgets.base.Widget.handle_key) method.
28
29 ```python title="inline.py"
30 from pytermgui import getch, Widget
31
32 def inline(widget):
33 while True:
34 key = getch()
35
36 widget.handle_key(key)
37
38 for line in widget.get_lines():
39 print(line)
40
41 return widget
42 ```
43
44 If you run the above, you will notice 2 things:
45
46 - Pressing ++ctrl+c++ leaves us with an ugly `KeyboardInterrupt`
47 - The widget lines aren't overwritten, but written to the terminal sequentially
48
49 There is also no mouse interaction, but we'll leave that for later.
50
51 ## Implementing clean exits
52
53 Let's focus on our first problem, relating to the `KeyboardInterrupt` error. This is trivial to fix; we can tell `getch` to convert `KeyboardInterrupt` into the character ++ctrl+c++ sends, and break the loop when we see said character.
54
55 The reason we need to do this lies deep in the trenches of the terminal, but here is the gist: When ++ctrl+c++ is detected, the "interrupt" signal is sent to the current foreground task. This signal (in simple terms) tells the program:
56
57 > Hey there! I think you should stop running.
58
59 It's important to note that this is not a full hard _drop everything you're doing and flee_ signal. This one is meant to allow programs to clean up after themselves before quitting, which is exactly what we will need to do.
60
61 !!! note
62
63 To see the above in effect, you can try the following code:
64
65 ```python
66 from time import time
67
68 while True:
69 try:
70 print(time())
71 except KeyboardInterrupt:
72 pass
73
74 return widget
75 ```
76
77 You will now be unable to leave the program, haha! Just kidding. Press ++ctrl+"\\"++ to send the "kill" signal to the program, which will stop the loop in its tracks. You can also press ++ctrl+l++, or type `reset` into the shell if your terminal got too messed up.
78
79 I feel like this goes without saying, but:
80
81 **Please do not put inescapable loops into your code**
82
83
84 === "Changes"
85
86 ```diff
87 from typing import TypeVar
88 - from pytermgui import getch, Widget
89 + from pytermgui import getch, keys, Widget
90
91 T = TypeVar("T", bound=Widget)
92
93 def inline(widget):
94 while True:
95 - key = getch()
96 + key = getch(interrupts=False)
97 +
98 + if key == keys.CTRL_C:
99 + break
100
101 widget.handle_key(key)
102
103 for line in widget.get_lines():
104 print(line)
105
106 return widget
107 ```
108
109 === "Updated file"
110
111 ```python linenums="1" title="inline.py"
112 from typing import TypeVar
113 from pytermgui import getch, keys, Widget
114
115 T = TypeVar("T", bound=Widget)
116
117 def inline(widget):
118 while True:
119 key = getch(interrupts=False)
120
121 if key == keys.CTRL_C:
122 break
123
124 widget.handle_key(key)
125
126 for line in widget.get_lines():
127 print(line)
128
129 return widget
130 ```
131
132 If you now run this and press ++ctrl+c++, you should see the program quit cleanly.
133
134 ## Improving printing
135
136 The print routine above was pretty rudimentary. We can do better!
137
138 To achieve the 'prompt' look we are aiming for, we need to always start printing at the same location. The simplest way to do this is to use the [save_cursor](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.save_cursor) and [restore_cursor](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.restore_cursor) methods. These tell the terminal to store the current cursor location somewhere, and to move the cursor to the stored location, respectively.
139
140 Let's start by making the following changes:
141
142
143 === "Changes"
144
145 ```diff
146 from typing import TypeVar
147 - from pytermgui import getch, keys, Widget
148 + from pytermgui import getch, keys, save_cursor, restore_cursor, Widget
149
150 def inline(widget):
151 while True:
152 key = getch(interrupts=False)
153
154 if key == keys.CTRL_C:
155 break
156
157 widget.handle_key(key)
158
159 + save_cursor()
160 +
161 for line in widget.get_lines():
162 print(line)
163 +
164 + restore_cursor()
165
166 return widget
167 ```
168
169 === "Updated file"
170
171 ```python linenums="1" title="inline.py"
172 from typing import TypeVar
173 from pytermgui import getch, keys, save_cursor, restore_cursor, Widget
174
175 def inline(widget):
176 while True:
177 key = getch(interrupts=False)
178
179 if key == keys.CTRL_C:
180 break
181
182 widget.handle_key(key)
183
184 save_cursor()
185
186 for line in widget.get_lines():
187 print(line)
188
189 restore_cursor()
190
191 return widget
192 ```
193
194 This fixes the issue, but you may notice our widget only gets printed after the first input. That happens because we call `getch` before the first prints. Let's fix it, and also move the printing logic into an inner function to make things cleaner:
195
196 === "Changes"
197
198 ```diff
199 from typing import TypeVar
200 from pytermgui import getch, keys, save_cursor, restore_cursor, Widget
201
202 def inline(widget):
203 + def _print_widget():
204 + save_cursor()
205 +
206 + for line in widget.get_lines():
207 + print(line)
208 +
209 + restore_cursor()
210 +
211 + _print_widget()
212 +
213 while True:
214 key = getch(interrupts=False)
215
216 if key == keys.CTRL_C:
217 break
218
219 widget.handle_key(key)
220
221 + _print_widget()
222 - save_cursor()
223 -
224 - for line in widget.get_lines():
225 - print(line)
226 -
227 - restore_cursor()
228
229 return widget
230 ```
231
232 === "Updated file"
233
234 ```python linenums="1" title="inline.py"
235 from typing import TypeVar
236 from pytermgui import getch, keys, save_cursor, restore_cursor, Widget
237
238 def inline(widget):
239 def _print_widget():
240 save_cursor()
241
242 for line in widget.get_lines():
243 print(line)
244
245 restore_cursor()
246
247 _print_widget()
248
249 while True:
250 key = getch(interrupts=False)
251
252 if key == keys.CTRL_C:
253 break
254
255 widget.handle_key(key)
256
257 _print_widget()
258
259 return widget
260 ```
261
262 You may have noticed that when exiting, part of the widget remains on the screen. This is the _last_ print-related issue we need to fix!
263
264 We can use the [clear](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.clear) function with the "line" parameter to clear all the affected lines of the terminal.
265
266 Let's introduce a new inner function, `_clear_widget`:
267
268 ```python linenums="15"
269 def _clear_widget():
270 save_cursor()
271
272 for _ in range(widget.height):
273 clear("line")
274 terminal.write("\n") # (1)
275
276 restore_cursor()
277 terminal.flush()
278 ```
279
280 1. We need to increment the cursor using newlines to make sure we aren't just clearing the same line over and over.
281
282 To include this, we need to import both `clear` and `terminal`. We also probably want to call our new function, specifically **before** the call to print and at the end of our `inline` routine.
283
284 Here is a snapshot of our work so far:
285
286 === "Changes"
287
288 ```diff
289 from typing import TypeVar
290 - from pytermgui import getch, keys, save_cursor, restore_cursor, Widget
291 + from pytermgui import (
292 + getch,
293 + keys,
294 + save_cursor,
295 + restore_cursor,
296 + Widget,
297 + clear,
298 + get_terminal,
299 + )
300
301 def inline(widget):
302 + # Make sure we use the global terminal
303 + terminal = get_terminal()
304 +
305 def _print_widget():
306 save_cursor()
307
308 for line in widget.get_lines():
309 print(line)
310
311 restore_cursor()
312
313 + def _clear_widget():
314 + save_cursor()
315 +
316 + for _ in range(widget.height):
317 + clear("line")
318 + terminal.write("\n")
319 +
320 + restore_cursor()
321 + terminal.flush()
322
323 _print_widget()
324
325 while True:
326 key = getch(interrupts=False)
327
328 if key == keys.CTRL_C:
329 break
330
331 widget.handle_key(key)
332
333 + _clear_widget()
334 _print_widget()
335 +
336 + _clear_widget()
337 return widget
338 ```
339
340 === "Updated file"
341
342 ```python linenums="1" title="inline.py"
343 from typing import TypeVar
344 from pytermgui import (
345 getch,
346 keys,
347 save_cursor,
348 restore_cursor,
349 Widget,
350 clear,
351 get_terminal,
352 )
353
354 def inline(widget):
355 # Make sure we use the global terminal
356 terminal = get_terminal()
357
358 def _print_widget():
359 save_cursor()
360
361 for line in widget.get_lines():
362 print(line)
363
364 restore_cursor()
365
366 def _clear_widget():
367 save_cursor()
368
369 for _ in range(widget.height):
370 clear("line")
371 terminal.write("\n")
372
373 restore_cursor()
374 terminal.flush()
375
376 _print_widget()
377
378 while True:
379 key = getch(interrupts=False)
380
381 if key == keys.CTRL_C:
382 break
383
384 widget.handle_key(key)
385
386 _clear_widget()
387 _print_widget()
388
389 _clear_widget()
390 return widget
391 ```
392
393 And with that, our printing routine is exactly how we want it to be! Now onto the fancy things.
394
395 ## Mouse support
396
397 Traditionally, mouse support is the "big bad" enemy of writing terminal programs. However, PyTermGUI makes it a _lot_ easier than you would've thought!
398
399 The only new thing we will need to import is the [mouse_handler](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.mouse_handler) context manager. This function does 2 things:
400
401 - Tells the terminal to send mouse events
402 - Returns a function that can translate mouse codes into [MouseEvent](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.MouseEvent) instances
403
404 To use it, we will wrap our `while True` loop into the context, and try to handle keys as mouse events when our widget didn't handle them successfully. Each widget denotes "successful" event handling by returning `True` from the given method, so the check will be simple:
405
406 ```diff linenums="37"
407 + with mouse_handler(["all"], "decimal_xterm") as translate:
408 while True:
409 key = getch(interrupts=False)
410
411 if key == keys.CTRL_C:
412 break
413
414 - widget.handle_key(key)
415 + if not widget.handle_key(key):
416 + for event in translate(key):
417 + if event is None:
418 + continue
419 + widget.handle_mouse(event)
420
421 _clear_widget()
422 _print_widget()
423
424 _clear_widget()
425 return widget
426 ```
427
428 There is a tiny bug with our mouse handling, however. We never tell the widget _where_ it is located, so it will reject most events. We can easily fix this by using the [report_mouse](/reference/pytermgui/ansi_interface#pytermgui.ansi_interface.report_mouse) and inserting the following line at the top of our function:
429
430 ```python
431 widget.pos = report_cursor()
432 ```
433
434
435 With the above changes, our file looks like the following:
436
437 ```python linenums="1" title="inline.py"
438 from typing import TypeVar
439 from pytermgui import (
440 getch,
441 keys,
442 save_cursor,
443 restore_cursor,
444 report_cursor,
445 Widget,
446 clear,
447 get_terminal,
448 mouse_handler,
449 )
450
451 def inline(widget):
452 # Make sure we use the global terminal
453 terminal = get_terminal()
454
455 widget.pos = report_cursor()
456
457 def _print_widget():
458 save_cursor()
459
460 for line in widget.get_lines():
461 print(line)
462
463 restore_cursor()
464
465 def _clear_widget():
466 save_cursor()
467
468 for _ in range(widget.height):
469 clear("line")
470 terminal.write("\n")
471
472 restore_cursor()
473 terminal.flush()
474
475 _print_widget()
476
477 with mouse_handler(["all"], "decimal_xterm") as translate:
478 while True:
479 key = getch(interrupts=False)
480
481 if key == keys.CTRL_C:
482 break
483
484 if not widget.handle_key(key):
485 events = translate(key)
486 # Don't try iterating when there are no events
487 if events is None:
488 continue
489
490 for event in events:
491 if event is None:
492 continue
493 widget.handle_mouse(event)
494
495 _clear_widget()
496 _print_widget()
497
498 _clear_widget()
499 return widget
500 ```
501
502 ## Congratulations!
503
504 **You just implemented PyTermGUI's [inline](/reference/pytermgui/widgets/inline#pytermgui.widgets.inline) function!**
505
506 Make sure to look at its source code for the final version of the code we've been working with, along with a few extra improvements, such as handling each the widget's `positioned_line_buffer`.