1#!/usr/bin/env python
2#
3# Urwid tour. It slices, it dices..
4# Copyright (C) 2004-2011 Ian Ward
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"""Urwid tour.
23
24Shows many of the standard widget types and features.
25"""
26
27from __future__ import annotations
28
29import typing
30
31import urwid
32from urwid.command_map import Command
33
34if typing.TYPE_CHECKING:
35 from collections.abc import Sequence
36
37PORTS = range(1, 65536)
38PRIVILEGED_PORTS = range(1, 1024)
39COLOURS = ("black", "brown", "dark blue", "dark cyan", "dark green", "dark red", "light blue", "light gray")
40
41
42class ReadlineEdit(urwid.Edit):
43 """Edit that takes the readline editing keys, from its own copy of the shared command map."""
44
45 _command_map = urwid.command_map.copy()
46 _command_map.bind_readline()
47
48
49class ContextMenuArea(urwid.WidgetWrap[urwid.ActionMenu]):
50 """Area whose right click opens its context menu below the pointer, through :meth:`ActionMenu.open_at`."""
51
52 def mouse_event(
53 self,
54 size: tuple[()] | tuple[int] | tuple[int, int],
55 event: str,
56 button: int,
57 col: int,
58 row: int,
59 focus: bool,
60 ) -> bool | None:
61 """Open the menu below the pressed cell on a right click; pass every other event on."""
62 if button == urwid.MouseButton.RIGHT and urwid.util.is_mouse_press(event):
63 self._w.open_at(col, row)
64 return True
65 return super().mouse_event(size, event, button, col, row, focus)
66
67
68def main() -> None:
69 """Build and run the tour of standard widget types and features."""
70 text_header = (
71 "Welcome to the urwid tour! UP / DOWN / PAGE UP / PAGE DOWN scroll. "
72 "TAB / SHIFT TAB move between fields. F8 exits."
73 )
74 text_intro: list[str | tuple[str, str]] = [
75 ("important", "Text"),
76 (
77 " widgets are the most common in "
78 "any urwid program. This Text widget was created "
79 "without setting the wrap or align mode, so it "
80 "defaults to left alignment with wrapping on space "
81 "characters. "
82 ),
83 ("important", "Change the window width"),
84 " to see how the widgets on this page react. This Text widget is wrapped with a ",
85 ("important", "Padding"),
86 " widget to keep it indented on the left and right.",
87 ]
88 text_right = "This Text widget is right aligned. Wrapped words stay to the right as well. "
89 text_center = "This one is center aligned."
90 text_clip = (
91 "Text widgets may be clipped instead of wrapped.\n"
92 "Extra text is discarded instead of wrapped to the next line. "
93 "65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
94 "Newlines embedded in the string are still respected."
95 )
96 text_right_clip = (
97 "This is a right aligned and clipped Text widget.\n"
98 "<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 "
99 "Text will be cut off at the left of this widget."
100 )
101 text_center_clip = "Center aligned and clipped widgets will have text cut off both sides."
102 text_ellipsis = (
103 "Text can be clipped using the ellipsis character (…)\n"
104 "Extra text is discarded and a … mark is shown."
105 "50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
106 )
107 text_any = (
108 "The 'any' wrap mode will wrap on any character. This "
109 "mode will not collapse space characters at the end of the "
110 "line but it still honors embedded newline characters.\n"
111 "Like this one."
112 )
113 text_padding = (
114 "Padding widgets have many options. This "
115 "is a standard Text widget wrapped with a Padding widget "
116 "with the alignment set to relative 20% and with its width "
117 "fixed at 40."
118 )
119 text_divider: list[str | tuple[str, str]] = [
120 "The ",
121 ("important", "Divider"),
122 " widget repeats the same character across the whole line. It can also add blank lines above and below.",
123 ]
124 text_edit: list[str | tuple[str, str]] = [
125 "The ",
126 ("important", "Edit"),
127 (
128 " widget is a simple text editing widget. It supports cursor "
129 "movement and tries to maintain the current column when focus "
130 "moves to another edit widget. It wraps and aligns the same "
131 "way as Text widgets."
132 ),
133 ]
134 text_edit_cap1 = ("editcp", "This is a caption. Edit here: ")
135 text_edit_text1 = "editable stuff"
136 text_edit_cap2 = ("editcp", "This one supports newlines: ")
137 text_edit_text2 = (
138 "line one starts them all\n"
139 "== line 2 == with some more text to edit.. words.. whee..\n"
140 "LINE III, the line to end lines one and two, unless you "
141 "change something."
142 )
143 text_edit_cap3 = ("editcp", "This one is clipped, try editing past the edge: ")
144 text_edit_text3 = "add some text here -> -> -> ...."
145 text_edit_cap4 = ("editcp", "This one takes at most 8 characters: ")
146 text_edit_text4 = "12345"
147 text_edit_cap5 = ("editcp", "This one shows a hint while empty and checks the port: ")
148 text_edit_cap6 = ("editcp", "This one completes a colour with TAB: ")
149 text_edit_cap7 = ("editcp", "This one takes readline keys, such as ctrl a, ctrl w, meta b and ctrl _ to undo: ")
150 text_edit_text7 = "ls /usr/local/share"
151 text_edit_alignments = "Different Alignments:"
152 text_edit_left = "left aligned (default)"
153 text_edit_center = "center aligned"
154 text_edit_right = "right aligned"
155 text_intedit: tuple[str, list[str | tuple[str, str]]] = (
156 "editcp",
157 [("important", "IntEdit"), " allows only numbers: "],
158 )
159 text_edit_padding = ("editcp", "Edit widget within a Padding widget ")
160 text_columns1: list[str | tuple[str, str]] = [
161 ("important", "Columns"),
162 (
163 " are used to share horizontal screen space. "
164 "This one splits the space into two parts with "
165 "three characters between each column. The "
166 "contents of each column is a single widget."
167 ),
168 ]
169 text_columns2: list[str | tuple[str, str]] = [
170 "When you need to put more than one widget into a column you can use a ",
171 ("important", "Pile"),
172 " to combine two or more widgets.",
173 ]
174 text_col_columns = "Columns may be placed inside other columns."
175 text_col_21 = "Col 2.1"
176 text_col_22 = "Col 2.2"
177 text_col_23 = "Col 2.3"
178 text_column_widths = (
179 "Columns may also have uneven relative "
180 "weights or fixed widths. Use a minimum width so that "
181 "columns don't become too small."
182 )
183 text_weight = "Weight %d"
184 text_fixed_9 = "<Fixed 9>" # should be 9 columns wide
185 text_fixed_14 = "<--Fixed 14-->" # should be 14 columns wide
186 text_edit_col_cap1 = ("editcp", "Edit widget within Columns")
187 text_edit_col_text1 = "here's\nsome\ninfo"
188 text_edit_col_cap2 = ("editcp", "and within Pile ")
189 text_edit_col_text2 = "more"
190 text_edit_col_cap3 = ("editcp", "another ")
191 text_edit_col_text3 = "still more"
192 text_gridflow: list[str | tuple[str, str]] = [
193 "A ",
194 ("important", "GridFlow"),
195 (
196 " widget "
197 "may be used to display a list of flow widgets with equal "
198 "widths. Widgets that don't fit on the first line will "
199 "flow to the next. This is useful for small widgets that "
200 "you want to keep together such as "
201 ),
202 ("important", "Button"),
203 ", ",
204 ("important", "CheckBox"),
205 " and ",
206 ("important", "RadioButton"),
207 " widgets. The ",
208 ("important", "GridFlow"),
209 " of buttons below sets ",
210 ("important", "unfocused_focus_attr"),
211 ", so its focus button stays marked while the focus is elsewhere. The check boxes use ",
212 ("important", "'pack'"),
213 " cells instead, each as wide as its label.",
214 ]
215 text_button_list = ["Yes", "No", "Perhaps", "Certainly", "Partially", "Tuesdays Only", "Help"]
216 text_cb_list = ["Wax", "Wash", "Buff", "Clear Coat", "Dry", "Racing Stripe"]
217 text_rb_list = ["Morning", "Afternoon", "Evening", "Weekend"]
218 text_table: list[str | tuple[str, str]] = [
219 "A ",
220 ("important", "Table"),
221 (
222 " widget lines up rows of cells between a fixed header and footer: every column is as wide as its "
223 "widest cell, a number, or a share of the rest. This one shows at most four rows at a time, with a "
224 "scrollbar while they do not all fit, a footer row of totals, and keeps the focused row marked while the "
225 "focus is elsewhere. A narrow window hides the Size column first, since its priority is the lowest. "
226 "Click a column label, or press UP at the first row and ENTER on a label, to sort by that column; again "
227 "to reverse the order. The check box below it shows or hides the Size column."
228 ),
229 ]
230 # (name, size, size in bytes for sorting, note)
231 table_rows = [
232 ("urwid", "1.2M", 1_258_291, "console user interface library"),
233 ("table.py", "34K", 34_816, "the widget shown here"),
234 ("tour.py", "18K", 18_432, "this program"),
235 ("palette", "1", 1, "a single entry"),
236 ("canvas.py", "52K", 53_248, "what widgets render to"),
237 ("\u4e2d\u6587", "2", 2, "wide characters line up too"),
238 ]
239 text_drop_down: list[str | tuple[str, str]] = [
240 "A ",
241 ("important", "DropDown"),
242 (
243 " widget shows the selected option. ENTER, SPACE or a mouse click "
244 "opens a list of all the options below it, or above it when there is no room "
245 "below; ESC or a click outside closes the list without a change. A long list scrolls. "
246 "A line separates groups of options, and a disabled option is shown but cannot be chosen. "
247 "The list is a pop-up, so the MainLoop is created with pop_ups=True."
248 ),
249 ]
250 text_drop_down_cap1 = "Color:"
251 # The separator splits the primary colours from the secondary ones; "Yellow" is disabled.
252 text_drop_down_list1 = ["Red", "Green", "Blue", None, "Cyan", "Magenta", "Yellow"]
253 text_drop_down_cap2 = "Month:"
254 text_drop_down_list2 = [
255 "January",
256 "February",
257 "March",
258 "April",
259 "May",
260 "June",
261 "July",
262 "August",
263 "September",
264 "October",
265 "November",
266 "December",
267 ]
268 text_action_menu: list[str | tuple[str, str]] = [
269 "An ",
270 ("important", "ActionMenu"),
271 (
272 " opens a list of actions with ENTER, SPACE or a click. The key in brackets chooses an item, "
273 "a disabled item cannot be focused, and Send to opens a submenu with RIGHT; LEFT or ESC closes it. "
274 "Near the right edge the submenu opens to the left of the list. View opens its list in the middle "
275 "of the screen. Each menu sets its own field. The two launchers form a menu bar: on an item without "
276 "a submenu, LEFT and RIGHT close the list and move to the other launcher."
277 ),
278 ]
279 text_context_menu = (
280 "Right-click anywhere in this paragraph. Its menu has no launcher of its own: the paragraph's mouse "
281 "handler calls open_at(), so the menu opens below the pointer, while a click on a launcher such as "
282 "Actions opens the list at the launcher's edge, as ENTER does."
283 )
284 text_tabs: list[str | tuple[str, str]] = [
285 "A ",
286 ("important", "Tabs"),
287 (
288 " widget shows one row of tab labels over the body of the selected tab. "
289 "META RIGHT / META LEFT or a mouse click switch tabs. UP from the body moves to the label row, "
290 "where LEFT / RIGHT and ENTER pick a tab and DOWN goes back. "
291 "Make the window narrow to see the label row scroll."
292 ),
293 ]
294 text_listbox: list[str | tuple[str, str]] = [
295 "All these widgets have been displayed with the help of a ",
296 ("important", "ListBox"),
297 " widget. ListBox widgets handle scrolling and changing focus. A ",
298 ("important", "Frame"),
299 " widget is used to keep the instructions at the top of the screen.",
300 ]
301
302 def button_press(button: urwid.Button) -> None:
303 frame.footer = urwid.AttrMap(urwid.Text(["Pressed: ", button.get_label()]), "header")
304
305 radio_button_group: list[urwid.RadioButton] = []
306
307 drop_down_options: tuple[Sequence[str | None], ...] = (text_drop_down_list1, text_drop_down_list2)
308 drop_down_selected = urwid.Text("")
309
310 def show_drop_down_selection(changed: urwid.DropDown | None = None, new_index: int = 0) -> None:
311 # 'change' is sent before changed.selected moves, so its new option is read from new_index.
312 markup: list[str | tuple[str, str]] = ["Selected: "]
313 for number, (drop_down, options) in enumerate(zip(drop_downs, drop_down_options, strict=True)):
314 index = new_index if drop_down is changed else drop_down.selected
315 if number:
316 markup.append(", ")
317 # The selected option is never a separator.
318 markup.append(("important", typing.cast("str", options[index])))
319 drop_down_selected.set_text(markup)
320
321 drop_downs = [
322 urwid.DropDown(drop_down_options[0], disabled={6}, attr_map="buttn", focus_map="buttnf", disabled_map="tab"),
323 urwid.DropDown(drop_down_options[1], selected=5, max_visible_items=5, attr_map="buttn", focus_map="buttnf"),
324 ]
325 for drop_down in drop_downs:
326 urwid.connect_signal(drop_down, "change", show_drop_down_selection)
327 show_drop_down_selection()
328 # One width for both, so the two drop-downs line up.
329 drop_down_width = max(drop_down.pack()[0] for drop_down in drop_downs)
330
331 table = urwid.Table(
332 [
333 urwid.TableColumn("Name"),
334 urwid.TableColumn("Size", align=urwid.RIGHT, attr="bright", priority=-1),
335 urwid.TableColumn("Note", width=(urwid.WEIGHT, 1), wrap=urwid.ELLIPSIS),
336 ],
337 header_attr="important",
338 footer=["6 entries", "1.3M"],
339 footer_attr="important",
340 focus_attr={None: "buttnf", "bright": "buttnf"},
341 unfocused_focus_attr={None: "buttnl", "bright": "buttnl"},
342 max_rows=4,
343 scrollbar=None,
344 scrollbar_thumb_char=urwid.ScrollBar.Symbols.DARK_SHADE,
345 scrollbar_trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
346 sortable=True,
347 header_focus_attr="buttnf",
348 )
349 table.body.extend(
350 table.layout.row([name, size, note], data=size_bytes) for name, size, size_bytes, note in table_rows
351 )
352
353 def sort_table(sorted_table: urwid.Table, column: int) -> bool:
354 # the same column again reverses the order; the Size column sorts by the number of bytes, not by its text
355 reverse = sorted_table.sort_column == column and not sorted_table.sort_reverse
356 if column == 1:
357 sorted_table.sort(column, key=lambda row: row.data, reverse=reverse)
358 else:
359 sorted_table.sort(column, reverse=reverse)
360 return True
361
362 urwid.connect_signal(table, "header activated", sort_table)
363
364 def show_sizes(_check_box: urwid.CheckBox, state: bool) -> None:
365 # the columns are named by the keys generated from their labels
366 table.layout.column_order = ("name", "size", "note") if state else ("name", "note")
367
368 show_sizes_box = urwid.CheckBox("Show sizes", state=True)
369 urwid.connect_signal(show_sizes_box, "change", show_sizes)
370
371 check_box_grid = urwid.GridFlow([], 10, 3, 1, urwid.LEFT, select_navigation=True)
372 check_box_grid.contents.extend(
373 (urwid.AttrMap(urwid.CheckBox(txt), "buttn", "buttnf"), check_box_grid.options("pack")) for txt in text_cb_list
374 )
375
376 action_chosen = urwid.Text(["Action: ", ("important", "none yet")])
377 view_chosen = urwid.Text(["View: ", ("important", "list")])
378 edit_chosen = urwid.Text(["Edit: ", ("important", "none yet")])
379
380 def show_choice(_menu: urwid.ActionMenu, item: urwid.MenuItem, field: tuple[urwid.Text, str]) -> None:
381 text, caption = field
382 text.set_text([caption, ("important", str(item.value))])
383
384 action_menu = urwid.ActionMenu(
385 "Actions",
386 [
387 urwid.MenuItem("(O)pen", "open", key="o"),
388 urwid.MenuItem("Re(n)ame", "rename", enabled=False, key="n"),
389 None,
390 urwid.MenuItem(
391 "(S)end to",
392 submenu=[
393 urwid.MenuItem("(M)ail", "send by mail", key="m"),
394 urwid.MenuItem("(P)rinter", "print", key="p"),
395 ],
396 key="s",
397 ),
398 urwid.MenuItem("(D)elete", "delete", key="d"),
399 ],
400 on_action=show_choice,
401 user_data=(action_chosen, "Action: "),
402 pass_arrows_below=True,
403 attr_map="buttn",
404 focus_map="buttnf",
405 disabled_map="tab",
406 )
407 view_menu = urwid.ActionMenu(
408 "View",
409 [
410 urwid.MenuItem("(L)ist", "list", key="l"),
411 urwid.MenuItem("(I)cons", "icons", key="i"),
412 urwid.MenuItem("(D)etails", "details", key="d"),
413 ],
414 on_action=show_choice,
415 user_data=(view_chosen, "View: "),
416 placement="center",
417 pass_arrows_below=True,
418 attr_map="buttn",
419 focus_map="buttnf",
420 disabled_map="tab",
421 )
422 context_menu = urwid.ActionMenu(
423 None,
424 [
425 urwid.MenuItem("(C)opy", "copy", key="c"),
426 urwid.MenuItem("Select (a)ll", "select all", key="a"),
427 ],
428 launcher=urwid.Text(text_context_menu),
429 # The paragraph opens the menu itself, so the menu takes no button of its own.
430 open_buttons=(),
431 on_action=show_choice,
432 user_data=(edit_chosen, "Edit: "),
433 attr_map="buttn",
434 focus_map="buttnf",
435 )
436
437 blank = urwid.Divider()
438 listbox_content: list[urwid.widget.AbstractFlowWidget] = [
439 blank,
440 urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20),
441 blank,
442 urwid.Text(text_right, align=urwid.RIGHT),
443 blank,
444 urwid.Text(text_center, align=urwid.CENTER),
445 blank,
446 urwid.Text(text_clip, wrap=urwid.CLIP),
447 blank,
448 urwid.Text(text_right_clip, align=urwid.RIGHT, wrap=urwid.CLIP),
449 blank,
450 urwid.Text(text_center_clip, align=urwid.CENTER, wrap=urwid.CLIP),
451 blank,
452 urwid.Text(text_ellipsis, wrap=urwid.ELLIPSIS),
453 blank,
454 urwid.Text(text_any, wrap=urwid.ANY),
455 blank,
456 urwid.Padding(urwid.Text(text_padding), (urwid.RELATIVE, 20), 40),
457 blank,
458 urwid.AttrMap(urwid.Divider("=", 1), "bright"),
459 urwid.Padding(urwid.Text(text_divider), left=2, right=2, min_width=20),
460 urwid.AttrMap(urwid.Divider("-", 0, 1), "bright"),
461 blank,
462 urwid.Padding(urwid.Text(text_edit), left=2, right=2, min_width=20),
463 blank,
464 urwid.AttrMap(urwid.Edit(text_edit_cap1, text_edit_text1), "editbx", "editfc"),
465 blank,
466 urwid.AttrMap(urwid.Edit(text_edit_cap2, text_edit_text2, multiline=True), "editbx", "editfc"),
467 blank,
468 urwid.AttrMap(urwid.Edit(text_edit_cap3, text_edit_text3, wrap=urwid.CLIP), "editbx", "editfc"),
469 blank,
470 urwid.AttrMap(urwid.Edit(text_edit_cap4, text_edit_text4, max_length=8), "editbx", "editfc"),
471 blank,
472 urwid.AttrMap(
473 urwid.Edit(
474 text_edit_cap5,
475 placeholder=("edithint", "e.g. 8080"),
476 validator=check_port,
477 validation_attr={urwid.Severity.WARNING: "editwarn", urwid.Severity.ERROR: "editerr"},
478 validation_focus_attr={urwid.Severity.WARNING: "editwarnf", urwid.Severity.ERROR: "editerrf"},
479 ),
480 "editbx",
481 "editfc",
482 ),
483 blank,
484 urwid.AttrMap(
485 urwid.Edit(text_edit_cap6, text_completer=complete_colour),
486 "editbx",
487 "editfc",
488 ),
489 blank,
490 urwid.AttrMap(ReadlineEdit(text_edit_cap7, text_edit_text7, undo_limit=50, kill_buffer=[]), "editbx", "editfc"),
491 blank,
492 urwid.Text(text_edit_alignments),
493 urwid.AttrMap(urwid.Edit("", text_edit_left, align=urwid.LEFT), "editbx", "editfc"),
494 urwid.AttrMap(urwid.Edit("", text_edit_center, align=urwid.CENTER), "editbx", "editfc"),
495 urwid.AttrMap(urwid.Edit("", text_edit_right, align=urwid.RIGHT), "editbx", "editfc"),
496 blank,
497 urwid.AttrMap(urwid.IntEdit(text_intedit, 123), "editbx", "editfc"),
498 blank,
499 urwid.Padding(urwid.AttrMap(urwid.Edit(text_edit_padding, ""), "editbx", "editfc"), left=10, width=50),
500 blank,
501 blank,
502 urwid.AttrMap(
503 urwid.Columns(
504 [
505 urwid.Divider("."),
506 urwid.Divider(","),
507 urwid.Divider("."),
508 ]
509 ),
510 "bright",
511 ),
512 blank,
513 urwid.Columns(
514 [
515 urwid.Padding(urwid.Text(text_columns1), left=2, right=0, min_width=20),
516 urwid.Pile([urwid.Divider("~"), urwid.Text(text_columns2), urwid.Divider("_")]),
517 ],
518 3,
519 ),
520 blank,
521 blank,
522 urwid.Columns(
523 [
524 urwid.Text(text_col_columns),
525 urwid.Columns(
526 [
527 urwid.Text(text_col_21),
528 urwid.Text(text_col_22),
529 urwid.Text(text_col_23),
530 ],
531 1,
532 ),
533 ],
534 2,
535 ),
536 blank,
537 urwid.Padding(urwid.Text(text_column_widths), left=2, right=2, min_width=20),
538 blank,
539 urwid.Columns(
540 [
541 urwid.AttrMap(urwid.Text(text_weight % 1), "reverse"),
542 (urwid.WEIGHT, 2, urwid.Text(text_weight % 2)),
543 (urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
544 (urwid.WEIGHT, 4, urwid.Text(text_weight % 4)),
545 (urwid.WEIGHT, 5, urwid.AttrMap(urwid.Text(text_weight % 5), "reverse")),
546 (urwid.WEIGHT, 6, urwid.Text(text_weight % 6)),
547 ],
548 0,
549 min_width=8,
550 ),
551 blank,
552 urwid.Columns(
553 [
554 (urwid.WEIGHT, 2, urwid.AttrMap(urwid.Text(text_weight % 2), "reverse")),
555 (9, urwid.Text(text_fixed_9)),
556 (urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
557 (14, urwid.Text(text_fixed_14)),
558 ],
559 0,
560 min_width=8,
561 ),
562 blank,
563 urwid.Columns(
564 [
565 urwid.AttrMap(urwid.Edit(text_edit_col_cap1, text_edit_col_text1, multiline=True), "editbx", "editfc"),
566 urwid.Pile(
567 [
568 urwid.AttrMap(urwid.Edit(text_edit_col_cap2, text_edit_col_text2), "editbx", "editfc"),
569 blank,
570 urwid.AttrMap(urwid.Edit(text_edit_col_cap3, text_edit_col_text3), "editbx", "editfc"),
571 ],
572 select_navigation=True,
573 ),
574 ],
575 1,
576 select_navigation=True,
577 ),
578 blank,
579 urwid.AttrMap(
580 urwid.Columns(
581 [
582 urwid.Divider("'"),
583 urwid.Divider('"'),
584 urwid.Divider("~"),
585 urwid.Divider('"'),
586 urwid.Divider("'"),
587 ]
588 ),
589 "bright",
590 ),
591 blank,
592 blank,
593 urwid.Padding(urwid.Text(text_gridflow), left=2, right=2, min_width=20),
594 blank,
595 urwid.Padding(
596 urwid.GridFlow(
597 [urwid.AttrMap(urwid.Button(txt, button_press), "buttn", "buttnf") for txt in text_button_list],
598 13,
599 3,
600 1,
601 urwid.LEFT,
602 select_navigation=True,
603 unfocused_focus_attr={"buttn": "buttnl"},
604 ),
605 left=4,
606 right=3,
607 min_width=13,
608 ),
609 blank,
610 urwid.Padding(
611 check_box_grid,
612 left=4,
613 right=3,
614 min_width=10,
615 ),
616 blank,
617 urwid.Padding(
618 urwid.GridFlow(
619 [urwid.AttrMap(urwid.RadioButton(radio_button_group, txt), "buttn", "buttnf") for txt in text_rb_list],
620 13,
621 3,
622 1,
623 urwid.LEFT,
624 select_navigation=True,
625 ),
626 left=4,
627 right=3,
628 min_width=13,
629 ),
630 blank,
631 blank,
632 urwid.Padding(urwid.Text(text_table), left=2, right=2, min_width=20),
633 blank,
634 urwid.Padding(
635 urwid.Pile([table, urwid.AttrMap(show_sizes_box, "buttn", "buttnf")]),
636 left=4,
637 right=3,
638 min_width=20,
639 ),
640 blank,
641 blank,
642 urwid.Padding(urwid.Text(text_drop_down), left=2, right=2, min_width=20),
643 blank,
644 urwid.Padding(
645 urwid.Columns(
646 [
647 (7, urwid.Text(text_drop_down_cap1)),
648 (drop_down_width, urwid.AttrMap(drop_downs[0], "buttn", "buttnf")),
649 ]
650 ),
651 left=4,
652 right=3,
653 min_width=20,
654 ),
655 urwid.Padding(
656 urwid.Columns(
657 [
658 (7, urwid.Text(text_drop_down_cap2)),
659 (drop_down_width, urwid.AttrMap(drop_downs[1], "buttn", "buttnf")),
660 ]
661 ),
662 left=4,
663 right=3,
664 min_width=20,
665 ),
666 blank,
667 urwid.Padding(drop_down_selected, left=4, right=3, min_width=20),
668 blank,
669 blank,
670 urwid.Padding(urwid.Text(text_action_menu), left=2, right=2, min_width=20),
671 blank,
672 urwid.Padding(
673 urwid.Columns(
674 [
675 (action_menu.pack()[0], urwid.AttrMap(action_menu, "buttn", "buttnf")),
676 (view_menu.pack()[0], urwid.AttrMap(view_menu, "buttn", "buttnf")),
677 ],
678 dividechars=2,
679 ),
680 left=4,
681 right=3,
682 min_width=20,
683 ),
684 urwid.Padding(urwid.Columns([action_chosen, view_chosen], dividechars=2), left=4, right=3, min_width=20),
685 blank,
686 urwid.Padding(ContextMenuArea(context_menu), left=4, right=3, min_width=20),
687 urwid.Padding(edit_chosen, left=4, right=3, min_width=20),
688 blank,
689 blank,
690 urwid.Padding(urwid.Text(text_tabs), left=2, right=2, min_width=20),
691 blank,
692 urwid.Padding(
693 urwid.Tabs(
694 [
695 ("Overview", urwid.Text("Each tab has its own body; only the selected one is drawn.")),
696 ("Name", urwid.AttrMap(urwid.Edit("Name: "), "editbx", "editfc")),
697 ("Options", urwid.Pile([urwid.CheckBox("Verbose"), urwid.CheckBox("Dry run")])),
698 ],
699 bar_selectable=True,
700 underline=(urwid.Tabs.Symbols.LINE_LIGHT, urwid.Tabs.Symbols.LINE_HEAVY),
701 attr_map="tab",
702 selected_map="tab selected",
703 focus_map="buttnf",
704 ),
705 left=4,
706 right=3,
707 min_width=20,
708 ),
709 blank,
710 blank,
711 urwid.Padding(urwid.Text(text_listbox), left=2, right=2, min_width=20),
712 blank,
713 blank,
714 ]
715
716 header = urwid.AttrMap(urwid.Text(text_header), "header")
717 # select_navigation lets TAB / SHIFT TAB visit every edit, button and check box in order
718 listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content), select_navigation=True)
719 scrollable = urwid.ScrollBar(
720 listbox,
721 trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
722 end_markers=(urwid.ScrollBar.Symbols.ARROW_TRIANGLE_UP, urwid.ScrollBar.Symbols.ARROW_TRIANGLE_DOWN),
723 scroll_by_focus=True,
724 )
725 frame: urwid.Frame[
726 urwid.AttrMap[urwid.ScrollBar[urwid.ListBox[int]]],
727 urwid.AttrMap[urwid.Text] | None,
728 urwid.AttrMap[urwid.Text] | None,
729 ] = urwid.Frame(
730 urwid.AttrMap(scrollable, "body"),
731 header=header,
732 )
733
734 palette: list[tuple[str, str, str] | tuple[str, str, str, str]] = [
735 ("body", "black", "light gray", "standout"),
736 ("reverse", "light gray", "black"),
737 ("header", "white", "dark red", "bold"),
738 ("important", "dark blue", "light gray", "standout,underline"),
739 ("editfc", "white", "dark blue", "bold"),
740 ("editbx", "light gray", "dark blue"),
741 ("editcp", "black", "light gray", "standout"),
742 ("edithint", "light cyan", "dark blue"),
743 ("editwarn", "yellow", "dark blue"),
744 ("editwarnf", "yellow", "dark blue", "bold"),
745 ("editerr", "light red", "dark blue"),
746 ("editerrf", "light red", "dark blue", "bold"),
747 ("bright", "dark gray", "light gray", "bold,standout"),
748 ("buttn", "black", "dark cyan"),
749 ("buttnf", "white", "dark blue", "bold"),
750 ("buttnl", "white", "dark cyan", "bold"),
751 ("tab", "dark gray", "light gray"),
752 ("tab selected", "dark blue", "light gray", "bold"),
753 ]
754
755 # use appropriate Screen class
756 if urwid.display.web.is_web_request():
757 screen = urwid.display.web.Screen()
758 else:
759 screen = urwid.display.raw.Screen()
760
761 def unhandled(key: str | tuple[str, int, int, int]) -> None:
762 if key == "f8":
763 raise urwid.ExitMainLoop
764
765 urwid.command_map.bind(Command.NEXT_TAB, "meta right")
766 urwid.command_map.bind(Command.PREVIOUS_TAB, "meta left")
767 # pop_ups=True adds the PopUpTarget that shows the open DropDown and ActionMenu lists.
768 urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled, pop_ups=True).run()
769
770
771def check_port(text: str) -> urwid.ValidationMessage | str | None:
772 """Return what is wrong with *text* as a TCP port number, or ``None`` for an empty or usable one."""
773 if not text:
774 return None
775 if not text.isdecimal() or int(text) not in PORTS:
776 return "not a port number"
777 if int(text) in PRIVILEGED_PORTS:
778 return urwid.ValidationMessage(urwid.Severity.WARNING, "a privileged port")
779 return None
780
781
782def complete_colour(text: str, pos: int) -> list[tuple[str, int]]:
783 """Return the colours that start with the text before the cursor, none for an empty field."""
784 prefix = text[:pos]
785 return [(name, len(name)) for name in COLOURS if name.startswith(prefix)] if prefix else []
786
787
788def setup() -> None:
789 """Run the tour as a web request when applicable, otherwise as a standalone program."""
790 urwid.display.web.set_preferences("Urwid Tour")
791 # try to handle short web requests quickly
792 if urwid.display.web.handle_short_request():
793 return
794
795 main()
796
797
798if __name__ == "__main__" or urwid.display.web.is_web_request():
799 setup()