urwid 2.6.0.post0__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.

Potentially problematic release.


This version of urwid might be problematic. Click here for more details.

Files changed (75) hide show
  1. urwid/__init__.py +333 -0
  2. urwid/canvas.py +1413 -0
  3. urwid/command_map.py +137 -0
  4. urwid/container.py +59 -0
  5. urwid/decoration.py +65 -0
  6. urwid/display/__init__.py +97 -0
  7. urwid/display/_posix_raw_display.py +413 -0
  8. urwid/display/_raw_display_base.py +914 -0
  9. urwid/display/_web.css +12 -0
  10. urwid/display/_web.js +462 -0
  11. urwid/display/_win32.py +171 -0
  12. urwid/display/_win32_raw_display.py +269 -0
  13. urwid/display/common.py +1219 -0
  14. urwid/display/curses.py +690 -0
  15. urwid/display/escape.py +624 -0
  16. urwid/display/html_fragment.py +251 -0
  17. urwid/display/lcd.py +518 -0
  18. urwid/display/raw.py +37 -0
  19. urwid/display/web.py +636 -0
  20. urwid/event_loop/__init__.py +55 -0
  21. urwid/event_loop/abstract_loop.py +175 -0
  22. urwid/event_loop/asyncio_loop.py +231 -0
  23. urwid/event_loop/glib_loop.py +294 -0
  24. urwid/event_loop/main_loop.py +721 -0
  25. urwid/event_loop/select_loop.py +230 -0
  26. urwid/event_loop/tornado_loop.py +206 -0
  27. urwid/event_loop/trio_loop.py +302 -0
  28. urwid/event_loop/twisted_loop.py +269 -0
  29. urwid/event_loop/zmq_loop.py +275 -0
  30. urwid/font.py +695 -0
  31. urwid/graphics.py +96 -0
  32. urwid/highlight.css +19 -0
  33. urwid/listbox.py +1899 -0
  34. urwid/monitored_list.py +522 -0
  35. urwid/numedit.py +376 -0
  36. urwid/signals.py +330 -0
  37. urwid/split_repr.py +130 -0
  38. urwid/str_util.py +358 -0
  39. urwid/text_layout.py +632 -0
  40. urwid/treetools.py +515 -0
  41. urwid/util.py +557 -0
  42. urwid/version.py +16 -0
  43. urwid/vterm.py +1806 -0
  44. urwid/widget/__init__.py +181 -0
  45. urwid/widget/attr_map.py +161 -0
  46. urwid/widget/attr_wrap.py +140 -0
  47. urwid/widget/bar_graph.py +649 -0
  48. urwid/widget/big_text.py +77 -0
  49. urwid/widget/box_adapter.py +126 -0
  50. urwid/widget/columns.py +1145 -0
  51. urwid/widget/constants.py +574 -0
  52. urwid/widget/container.py +227 -0
  53. urwid/widget/divider.py +110 -0
  54. urwid/widget/edit.py +718 -0
  55. urwid/widget/filler.py +403 -0
  56. urwid/widget/frame.py +539 -0
  57. urwid/widget/grid_flow.py +539 -0
  58. urwid/widget/line_box.py +194 -0
  59. urwid/widget/overlay.py +829 -0
  60. urwid/widget/padding.py +597 -0
  61. urwid/widget/pile.py +971 -0
  62. urwid/widget/popup.py +170 -0
  63. urwid/widget/progress_bar.py +141 -0
  64. urwid/widget/scrollable.py +597 -0
  65. urwid/widget/solid_fill.py +44 -0
  66. urwid/widget/text.py +354 -0
  67. urwid/widget/widget.py +852 -0
  68. urwid/widget/widget_decoration.py +166 -0
  69. urwid/widget/wimp.py +792 -0
  70. urwid/wimp.py +23 -0
  71. urwid-2.6.0.post0.dist-info/COPYING +504 -0
  72. urwid-2.6.0.post0.dist-info/METADATA +332 -0
  73. urwid-2.6.0.post0.dist-info/RECORD +75 -0
  74. urwid-2.6.0.post0.dist-info/WHEEL +5 -0
  75. urwid-2.6.0.post0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,721 @@
1
+ # Urwid main loop code
2
+ # Copyright (C) 2004-2012 Ian Ward
3
+ # Copyright (C) 2008 Walter Mundt
4
+ # Copyright (C) 2009 Andrew Psaltis
5
+ #
6
+ # This library is free software; you can redistribute it and/or
7
+ # modify it under the terms of the GNU Lesser General Public
8
+ # License as published by the Free Software Foundation; either
9
+ # version 2.1 of the License, or (at your option) any later version.
10
+ #
11
+ # This library is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
+ # Lesser General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU Lesser General Public
17
+ # License along with this library; if not, write to the Free Software
18
+ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
+ #
20
+ # Urwid web site: https://urwid.org/
21
+
22
+
23
+ from __future__ import annotations
24
+
25
+ import heapq
26
+ import logging
27
+ import os
28
+ import sys
29
+ import time
30
+ import typing
31
+ import warnings
32
+ from contextlib import suppress
33
+
34
+ from urwid import display, signals
35
+ from urwid.command_map import Command, command_map
36
+ from urwid.display.common import INPUT_DESCRIPTORS_CHANGED
37
+ from urwid.util import StoppingContext, is_mouse_event
38
+ from urwid.widget import PopUpTarget
39
+
40
+ from .abstract_loop import ExitMainLoop
41
+ from .select_loop import SelectEventLoop
42
+
43
+ if typing.TYPE_CHECKING:
44
+ from collections.abc import Callable, Iterable
45
+
46
+ from typing_extensions import Self
47
+
48
+ from urwid.display import BaseScreen
49
+ from urwid.widget import Widget
50
+
51
+ from .abstract_loop import EventLoop
52
+
53
+ _T = typing.TypeVar("_T")
54
+
55
+
56
+ IS_WINDOWS = sys.platform == "win32"
57
+ PIPE_BUFFER_READ_SIZE = 4096 # can expect this much on Linux, so try for that
58
+
59
+ __all__ = ("CantUseExternalLoop", "MainLoop")
60
+
61
+
62
+ class CantUseExternalLoop(Exception):
63
+ pass
64
+
65
+
66
+ class MainLoop:
67
+ """
68
+ This is the standard main loop implementation for a single interactive
69
+ session.
70
+
71
+ :param widget: the topmost widget used for painting the screen, stored as
72
+ :attr:`widget` and may be modified. Must be a box widget.
73
+ :type widget: widget instance
74
+
75
+ :param palette: initial palette for screen
76
+ :type palette: iterable of palette entries
77
+
78
+ :param screen: screen to use, default is a new :class:`raw_display.Screen`
79
+ instance; stored as :attr:`screen`
80
+ :type screen: display module screen instance
81
+
82
+ :param handle_mouse: ``True`` to ask :attr:`.screen` to process mouse events
83
+ :type handle_mouse: bool
84
+
85
+ :param input_filter: a function to filter input before sending it to
86
+ :attr:`.widget`, called from :meth:`.input_filter`
87
+ :type input_filter: callable
88
+
89
+ :param unhandled_input: a function called when input is not handled by
90
+ :attr:`.widget`, called from :meth:`.unhandled_input`
91
+ :type unhandled_input: callable
92
+
93
+ :param event_loop: if :attr:`.screen` supports external an event loop it may be
94
+ given here, default is a new :class:`SelectEventLoop` instance;
95
+ stored as :attr:`.event_loop`
96
+ :type event_loop: event loop instance
97
+
98
+ :param pop_ups: `True` to wrap :attr:`.widget` with a :class:`PopUpTarget`
99
+ instance to allow any widget to open a pop-up anywhere on the screen
100
+ :type pop_ups: boolean
101
+
102
+
103
+ .. attribute:: screen
104
+
105
+ The screen object this main loop uses for screen updates and reading input
106
+
107
+ .. attribute:: event_loop
108
+
109
+ The event loop object this main loop uses for waiting on alarms and IO
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ widget: Widget,
115
+ palette: Iterable[
116
+ tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str]
117
+ ] = (),
118
+ screen: BaseScreen | None = None,
119
+ handle_mouse: bool = True,
120
+ input_filter: Callable[[list[str], list[int]], list[str]] | None = None,
121
+ unhandled_input: Callable[[str | tuple[str, int, int, int]], bool | None] | None = None,
122
+ event_loop: EventLoop | None = None,
123
+ pop_ups: bool = False,
124
+ ):
125
+ self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
126
+ self._widget = widget
127
+ self.handle_mouse = handle_mouse
128
+ self._pop_ups = False # only initialize placeholder
129
+ self.pop_ups = pop_ups # triggers property setting side-effect
130
+
131
+ if not screen:
132
+ screen = display.raw.Screen()
133
+
134
+ if palette:
135
+ screen.register_palette(palette)
136
+
137
+ self.screen: BaseScreen = screen
138
+ self.screen_size: tuple[int, int] | None = None
139
+
140
+ self._unhandled_input = unhandled_input
141
+ self._input_filter = input_filter
142
+
143
+ if not hasattr(screen, "hook_event_loop") and event_loop is not None:
144
+ raise NotImplementedError(f"screen object passed {screen!r} does not support external event loops")
145
+ if event_loop is None:
146
+ event_loop = SelectEventLoop()
147
+ self.event_loop: EventLoop = event_loop
148
+
149
+ if hasattr(self.screen, "signal_handler_setter"):
150
+ # Tell the screen what function it must use to set
151
+ # signal handlers
152
+ self.screen.signal_handler_setter = self.event_loop.set_signal_handler
153
+
154
+ self._watch_pipes: dict[int, tuple[Callable[[], typing.Any], int]] = {}
155
+
156
+ @property
157
+ def widget(self) -> Widget:
158
+ """
159
+ Property for the topmost widget used to draw the screen.
160
+ This must be a box widget.
161
+ """
162
+ return self._widget
163
+
164
+ @widget.setter
165
+ def widget(self, widget: Widget) -> None:
166
+ self._widget = widget
167
+ if self.pop_ups:
168
+ self._topmost_widget.original_widget = self._widget
169
+ else:
170
+ self._topmost_widget = self._widget
171
+
172
+ def _set_widget(self, widget: Widget) -> None:
173
+ warnings.warn(
174
+ f"method `{self.__class__.__name__}._set_widget` is deprecated, "
175
+ f"please use `{self.__class__.__name__}.widget` property",
176
+ DeprecationWarning,
177
+ stacklevel=2,
178
+ )
179
+ self.widget = widget
180
+
181
+ @property
182
+ def pop_ups(self) -> bool:
183
+ return self._pop_ups
184
+
185
+ @pop_ups.setter
186
+ def pop_ups(self, pop_ups: bool) -> None:
187
+ self._pop_ups = pop_ups
188
+ if pop_ups:
189
+ self._topmost_widget = PopUpTarget(self._widget)
190
+ else:
191
+ self._topmost_widget = self._widget
192
+
193
+ def _set_pop_ups(self, pop_ups) -> None:
194
+ warnings.warn(
195
+ f"method `{self.__class__.__name__}._set_pop_ups` is deprecated, "
196
+ f"please use `{self.__class__.__name__}.pop_ups` property",
197
+ DeprecationWarning,
198
+ stacklevel=2,
199
+ )
200
+ self.pop_ups = pop_ups
201
+
202
+ def set_alarm_in(self, sec: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None):
203
+ """
204
+ Schedule an alarm in *sec* seconds that will call *callback* from the
205
+ within the :meth:`run` method.
206
+
207
+ :param sec: seconds until alarm
208
+ :type sec: float
209
+ :param callback: function to call with two parameters: this main loop
210
+ object and *user_data*
211
+ :type callback: callable
212
+ :param user_data: optional user data to pass to the callback
213
+ :type user_data: object
214
+ """
215
+ self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}")
216
+
217
+ def cb():
218
+ callback(self, user_data)
219
+
220
+ return self.event_loop.alarm(sec, cb)
221
+
222
+ def set_alarm_at(self, tm: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None):
223
+ """
224
+ Schedule an alarm at *tm* time that will call *callback* from the
225
+ within the :meth:`run` function. Returns a handle that may be passed to
226
+ :meth:`remove_alarm`.
227
+
228
+ :param tm: time to call callback e.g. ``time.time() + 5``
229
+ :type tm: float
230
+ :param callback: function to call with two parameters: this main loop
231
+ object and *user_data*
232
+ :type callback: callable
233
+ :param user_data: optional user data to pass to the callback
234
+ :type user_data: object
235
+ """
236
+ sec = tm - time.time()
237
+ self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}")
238
+
239
+ def cb():
240
+ callback(self, user_data)
241
+
242
+ return self.event_loop.alarm(sec, cb)
243
+
244
+ def remove_alarm(self, handle) -> bool:
245
+ """
246
+ Remove an alarm. Return ``True`` if *handle* was found, ``False``
247
+ otherwise.
248
+ """
249
+ return self.event_loop.remove_alarm(handle)
250
+
251
+ if not IS_WINDOWS:
252
+
253
+ def watch_pipe(self, callback: Callable[[bytes], bool]) -> int:
254
+ """
255
+ Create a pipe for use by a subprocess or thread to trigger a callback
256
+ in the process/thread running the main loop.
257
+
258
+ :param callback: function taking one parameter to call from within
259
+ the process/thread running the main loop
260
+ :type callback: callable
261
+
262
+ This method returns a file descriptor attached to the write end of a
263
+ pipe. The read end of the pipe is added to the list of files
264
+ :attr:`event_loop` is watching. When data is written to the pipe the
265
+ callback function will be called and passed a single value containing
266
+ data read from the pipe.
267
+
268
+ This method may be used any time you want to update widgets from
269
+ another thread or subprocess.
270
+
271
+ Data may be written to the returned file descriptor with
272
+ ``os.write(fd, data)``. Ensure that data is less than 512 bytes (or 4K
273
+ on Linux) so that the callback will be triggered just once with the
274
+ complete value of data passed in.
275
+
276
+ If the callback returns ``False`` then the watch will be removed from
277
+ :attr:`event_loop` and the read end of the pipe will be closed. You
278
+ are responsible for closing the write end of the pipe with
279
+ ``os.close(fd)``.
280
+ """
281
+ import fcntl
282
+
283
+ pipe_rd, pipe_wr = os.pipe()
284
+ fcntl.fcntl(pipe_rd, fcntl.F_SETFL, os.O_NONBLOCK)
285
+ watch_handle = None
286
+
287
+ def cb() -> None:
288
+ data = os.read(pipe_rd, PIPE_BUFFER_READ_SIZE)
289
+ if not callback(data):
290
+ self.event_loop.remove_watch_file(watch_handle)
291
+ os.close(pipe_rd)
292
+
293
+ watch_handle = self.event_loop.watch_file(pipe_rd, cb)
294
+ self._watch_pipes[pipe_wr] = (watch_handle, pipe_rd)
295
+ return pipe_wr
296
+
297
+ def remove_watch_pipe(self, write_fd: int) -> bool:
298
+ """
299
+ Close the read end of the pipe and remove the watch created by
300
+ :meth:`watch_pipe`. You are responsible for closing the write end of
301
+ the pipe.
302
+
303
+ Returns ``True`` if the watch pipe exists, ``False`` otherwise
304
+ """
305
+ try:
306
+ watch_handle, pipe_rd = self._watch_pipes.pop(write_fd)
307
+ except KeyError:
308
+ return False
309
+
310
+ if not self.event_loop.remove_watch_file(watch_handle):
311
+ return False
312
+ os.close(pipe_rd)
313
+ return True
314
+
315
+ def watch_file(self, fd: int, callback: Callable[[], typing.Any]):
316
+ """
317
+ Call *callback* when *fd* has some data to read. No parameters are
318
+ passed to callback.
319
+
320
+ Returns a handle that may be passed to :meth:`remove_watch_file`.
321
+ """
322
+ self.logger.debug(f"Setting watch file descriptor {fd!r} with {callback!r}")
323
+ return self.event_loop.watch_file(fd, callback)
324
+
325
+ def remove_watch_file(self, handle):
326
+ """
327
+ Remove a watch file. Returns ``True`` if the watch file
328
+ exists, ``False`` otherwise.
329
+ """
330
+ return self.event_loop.remove_watch_file(handle)
331
+
332
+ def run(self) -> None:
333
+ """
334
+ Start the main loop handling input events and updating the screen. The
335
+ loop will continue until an :exc:`ExitMainLoop` exception is raised.
336
+
337
+ If you would prefer to manage the event loop yourself, don't use this
338
+ method. Instead, call :meth:`start` before starting the event loop,
339
+ and :meth:`stop` once it's finished.
340
+ """
341
+ with suppress(ExitMainLoop):
342
+ self._run()
343
+
344
+ def _test_run(self):
345
+ """
346
+ >>> w = _refl("widget") # _refl prints out function calls
347
+ >>> w.render_rval = "fake canvas" # *_rval is used for return values
348
+ >>> scr = _refl("screen")
349
+ >>> scr.get_input_descriptors_rval = [42]
350
+ >>> scr.get_cols_rows_rval = (20, 10)
351
+ >>> scr.started = True
352
+ >>> scr._urwid_signals = {}
353
+ >>> evl = _refl("event_loop")
354
+ >>> evl.enter_idle_rval = 1
355
+ >>> evl.watch_file_rval = 2
356
+ >>> ml = MainLoop(w, [], scr, event_loop=evl)
357
+ >>> ml.run() # doctest:+ELLIPSIS
358
+ screen.start()
359
+ screen.set_mouse_tracking()
360
+ screen.unhook_event_loop(...)
361
+ screen.hook_event_loop(...)
362
+ event_loop.enter_idle(<bound method MainLoop.entering_idle...>)
363
+ event_loop.run()
364
+ event_loop.remove_enter_idle(1)
365
+ screen.unhook_event_loop(...)
366
+ screen.stop()
367
+ >>> ml.draw_screen() # doctest:+ELLIPSIS
368
+ screen.get_cols_rows()
369
+ widget.render((20, 10), focus=True)
370
+ screen.draw_screen((20, 10), 'fake canvas')
371
+ """
372
+
373
+ def start(self) -> StoppingContext:
374
+ """
375
+ Sets up the main loop, hooking into the event loop where necessary.
376
+ Starts the :attr:`screen` if it hasn't already been started.
377
+
378
+ If you want to control starting and stopping the event loop yourself,
379
+ you should call this method before starting, and call `stop` once the
380
+ loop has finished. You may also use this method as a context manager,
381
+ which will stop the loop automatically at the end of the block:
382
+
383
+ with main_loop.start():
384
+ ...
385
+
386
+ Note that some event loop implementations don't handle exceptions
387
+ specially if you manage the event loop yourself. In particular, the
388
+ Twisted and asyncio loops won't stop automatically when
389
+ :exc:`ExitMainLoop` (or anything else) is raised.
390
+ """
391
+
392
+ self.logger.debug(f"Starting event loop {self.event_loop.__class__.__name__!r} to manage display.")
393
+
394
+ self.screen.start()
395
+
396
+ if self.handle_mouse:
397
+ self.screen.set_mouse_tracking()
398
+
399
+ if not hasattr(self.screen, "hook_event_loop"):
400
+ raise CantUseExternalLoop(f"Screen {self.screen!r} doesn't support external event loops")
401
+
402
+ with suppress(NameError):
403
+ signals.connect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors)
404
+
405
+ # watch our input descriptors
406
+ self._reset_input_descriptors()
407
+ self.idle_handle = self.event_loop.enter_idle(self.entering_idle)
408
+
409
+ # the screen is redrawn automatically after input and alarms,
410
+ # however, there can be none of those at the start,
411
+ # so draw the initial screen here unconditionally
412
+ self.event_loop.alarm(0, self.entering_idle)
413
+
414
+ return StoppingContext(self)
415
+
416
+ def stop(self) -> None:
417
+ """
418
+ Cleans up any hooks added to the event loop. Only call this if you're
419
+ managing the event loop yourself, after the loop stops.
420
+ """
421
+
422
+ self.event_loop.remove_enter_idle(self.idle_handle)
423
+ del self.idle_handle
424
+ signals.disconnect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors)
425
+ self.screen.unhook_event_loop(self.event_loop)
426
+
427
+ self.screen.stop()
428
+
429
+ def _reset_input_descriptors(self) -> None:
430
+ self.screen.unhook_event_loop(self.event_loop)
431
+ self.screen.hook_event_loop(self.event_loop, self._update)
432
+
433
+ def _run(self) -> None:
434
+ try:
435
+ self.start()
436
+ except CantUseExternalLoop:
437
+ try:
438
+ self._run_screen_event_loop()
439
+ return
440
+ finally:
441
+ self.screen.stop()
442
+
443
+ try:
444
+ self.event_loop.run()
445
+ except:
446
+ self.screen.stop() # clean up screen control
447
+ raise
448
+ self.stop()
449
+
450
+ def _update(self, keys: list[str], raw: list[int]) -> None:
451
+ """
452
+ >>> w = _refl("widget")
453
+ >>> w.selectable_rval = True
454
+ >>> w.mouse_event_rval = True
455
+ >>> scr = _refl("screen")
456
+ >>> scr.get_cols_rows_rval = (15, 5)
457
+ >>> evl = _refl("event_loop")
458
+ >>> ml = MainLoop(w, [], scr, event_loop=evl)
459
+ >>> ml._input_timeout = "old timeout"
460
+ >>> ml._update(['y'], [121]) # doctest:+ELLIPSIS
461
+ screen.get_cols_rows()
462
+ widget.selectable()
463
+ widget.keypress((15, 5), 'y')
464
+ >>> ml._update([("mouse press", 1, 5, 4)], [])
465
+ widget.mouse_event((15, 5), 'mouse press', 1, 5, 4, focus=True)
466
+ >>> ml._update([], [])
467
+ """
468
+ keys = self.input_filter(keys, raw)
469
+
470
+ if keys:
471
+ self.process_input(keys)
472
+ if "window resize" in keys:
473
+ self.screen_size = None
474
+
475
+ def _run_screen_event_loop(self) -> None:
476
+ """
477
+ This method is used when the screen does not support using external event loops.
478
+
479
+ The alarms stored in the SelectEventLoop in :attr:`event_loop` are modified by this method.
480
+ """
481
+ # pylint: disable=protected-access # special case for alarms handling
482
+ self.logger.debug(f"Starting screen {self.screen!r} event loop")
483
+
484
+ next_alarm = None
485
+
486
+ while True:
487
+ self.draw_screen()
488
+
489
+ if not next_alarm and self.event_loop._alarms:
490
+ next_alarm = heapq.heappop(self.event_loop._alarms)
491
+
492
+ keys: list[str] = []
493
+ raw: list[int] = []
494
+ while not keys:
495
+ if next_alarm:
496
+ sec = max(0.0, next_alarm[0] - time.time())
497
+ self.screen.set_input_timeouts(sec)
498
+ else:
499
+ self.screen.set_input_timeouts(None)
500
+ keys, raw = self.screen.get_input(True)
501
+ if not keys and next_alarm:
502
+ sec = next_alarm[0] - time.time()
503
+ if sec <= 0:
504
+ break
505
+
506
+ keys = self.input_filter(keys, raw)
507
+
508
+ if keys:
509
+ self.process_input(keys)
510
+
511
+ while next_alarm:
512
+ sec = next_alarm[0] - time.time()
513
+ if sec > 0:
514
+ break
515
+ _tm, _tie_break, callback = next_alarm
516
+ callback()
517
+
518
+ if self.event_loop._alarms:
519
+ next_alarm = heapq.heappop(self.event_loop._alarms)
520
+ else:
521
+ next_alarm = None
522
+
523
+ if "window resize" in keys:
524
+ self.screen_size = None
525
+
526
+ def _test_run_screen_event_loop(self):
527
+ """
528
+ >>> w = _refl("widget")
529
+ >>> scr = _refl("screen")
530
+ >>> scr.get_cols_rows_rval = (10, 5)
531
+ >>> scr.get_input_rval = [], []
532
+ >>> ml = MainLoop(w, screen=scr)
533
+ >>> def stop_now(loop, data):
534
+ ... raise ExitMainLoop()
535
+ >>> handle = ml.set_alarm_in(0, stop_now)
536
+ >>> try:
537
+ ... ml._run_screen_event_loop()
538
+ ... except ExitMainLoop:
539
+ ... pass
540
+ screen.get_cols_rows()
541
+ widget.render((10, 5), focus=True)
542
+ screen.draw_screen((10, 5), None)
543
+ screen.set_input_timeouts(0.0)
544
+ screen.get_input(True)
545
+ """
546
+
547
+ def process_input(self, keys: Iterable[str | tuple[str, int, int, int]]) -> bool:
548
+ """
549
+ This method will pass keyboard input and mouse events to :attr:`widget`.
550
+ This method is called automatically from the :meth:`run` method when
551
+ there is input, but may also be called to simulate input from the user.
552
+
553
+ *keys* is a list of input returned from :attr:`screen`'s get_input()
554
+ or get_input_nonblocking() methods.
555
+
556
+ Returns ``True`` if any key was handled by a widget or the
557
+ :meth:`unhandled_input` method.
558
+ """
559
+ self.logger.debug(f"Processing input: keys={keys!r}")
560
+ if not self.screen_size:
561
+ self.screen_size = self.screen.get_cols_rows()
562
+
563
+ something_handled = False
564
+
565
+ for k in keys:
566
+ if k == "window resize":
567
+ continue
568
+
569
+ if isinstance(k, str):
570
+ if self._topmost_widget.selectable():
571
+ k = self._topmost_widget.keypress(self.screen_size, k) # noqa: PLW2901
572
+
573
+ elif isinstance(k, tuple):
574
+ if is_mouse_event(k):
575
+ event, button, col, row = k
576
+ if hasattr(self._topmost_widget, "mouse_event") and self._topmost_widget.mouse_event(
577
+ self.screen_size,
578
+ event,
579
+ button,
580
+ col,
581
+ row,
582
+ focus=True,
583
+ ):
584
+ k = None # noqa: PLW2901
585
+
586
+ else:
587
+ raise TypeError(f"{k!r} is not str | tuple[str, int, int, int]")
588
+
589
+ if k:
590
+ if command_map[k] == Command.REDRAW_SCREEN:
591
+ self.screen.clear()
592
+ something_handled = True
593
+ else:
594
+ something_handled |= bool(self.unhandled_input(k))
595
+ else:
596
+ something_handled = True
597
+
598
+ return something_handled
599
+
600
+ def _test_process_input(self):
601
+ """
602
+ >>> w = _refl("widget")
603
+ >>> w.selectable_rval = True
604
+ >>> scr = _refl("screen")
605
+ >>> scr.get_cols_rows_rval = (10, 5)
606
+ >>> ml = MainLoop(w, [], scr)
607
+ >>> ml.process_input(['enter', ('mouse drag', 1, 14, 20)])
608
+ screen.get_cols_rows()
609
+ widget.selectable()
610
+ widget.keypress((10, 5), 'enter')
611
+ widget.mouse_event((10, 5), 'mouse drag', 1, 14, 20, focus=True)
612
+ True
613
+ """
614
+
615
+ def input_filter(self, keys: list[str], raw: list[int]) -> list[str]:
616
+ """
617
+ This function is passed each all the input events and raw keystroke
618
+ values. These values are passed to the *input_filter* function
619
+ passed to the constructor. That function must return a list of keys to
620
+ be passed to the widgets to handle. If no *input_filter* was
621
+ defined this implementation will return all the input events.
622
+ """
623
+ if self._input_filter:
624
+ return self._input_filter(keys, raw)
625
+ return keys
626
+
627
+ def unhandled_input(self, data: str | tuple[str, int, int, int]) -> bool | None:
628
+ """
629
+ This function is called with any input that was not handled by the
630
+ widgets, and calls the *unhandled_input* function passed to the
631
+ constructor. If no *unhandled_input* was defined then the input
632
+ will be ignored.
633
+
634
+ *input* is the keyboard or mouse input.
635
+
636
+ The *unhandled_input* function should return ``True`` if it handled
637
+ the input.
638
+ """
639
+ if self._unhandled_input:
640
+ return self._unhandled_input(data)
641
+ return False
642
+
643
+ def entering_idle(self) -> None:
644
+ """
645
+ This method is called whenever the event loop is about to enter the
646
+ idle state. :meth:`draw_screen` is called here to update the
647
+ screen when anything has changed.
648
+ """
649
+ if self.screen.started:
650
+ self.draw_screen()
651
+ else:
652
+ self.logger.debug(f"No redrawing screen: {self.screen!r} is not started.")
653
+
654
+ def draw_screen(self) -> None:
655
+ """
656
+ Render the widgets and paint the screen. This method is called
657
+ automatically from :meth:`entering_idle`.
658
+
659
+ If you modify the widgets displayed outside of handling input or
660
+ responding to an alarm you will need to call this method yourself
661
+ to repaint the screen.
662
+ """
663
+ if not self.screen_size:
664
+ self.screen_size = self.screen.get_cols_rows()
665
+ self.logger.debug(f"Screen size recalculated: {self.screen_size!r}")
666
+
667
+ canvas = self._topmost_widget.render(self.screen_size, focus=True)
668
+ self.screen.draw_screen(self.screen_size, canvas)
669
+
670
+
671
+ def _refl(name: str, rval=None, loop_exit=False):
672
+ """
673
+ This function is used to test the main loop classes.
674
+
675
+ >>> scr = _refl("screen")
676
+ >>> scr.function("argument")
677
+ screen.function('argument')
678
+ >>> scr.callme(when="now")
679
+ screen.callme(when='now')
680
+ >>> scr.want_something_rval = 42
681
+ >>> x = scr.want_something()
682
+ screen.want_something()
683
+ >>> x
684
+ 42
685
+
686
+ """
687
+
688
+ class Reflect:
689
+ def __init__(self, name: str, rval=None):
690
+ self._name = name
691
+ self._rval = rval
692
+
693
+ def __call__(self, *argl, **argd):
694
+ args = ", ".join([repr(a) for a in argl])
695
+ if args and argd:
696
+ args = f"{args}, "
697
+ args += ", ".join([f"{k}={v!r}" for k, v in argd.items()])
698
+ print(f"{self._name}({args})")
699
+ if loop_exit:
700
+ raise ExitMainLoop()
701
+ return self._rval
702
+
703
+ def __getattr__(self, attr):
704
+ if attr.endswith("_rval"):
705
+ raise AttributeError()
706
+ # print(self._name+"."+attr)
707
+ if hasattr(self, f"{attr}_rval"):
708
+ return Reflect(f"{self._name}.{attr}", getattr(self, f"{attr}_rval"))
709
+ return Reflect(f"{self._name}.{attr}")
710
+
711
+ return Reflect(name)
712
+
713
+
714
+ def _test():
715
+ import doctest
716
+
717
+ doctest.testmod()
718
+
719
+
720
+ if __name__ == "__main__":
721
+ _test()