id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
1,200
urwid_attr.py.xdotool
urwid_urwid/docs/tutorial/urwid_attr.py.xdotool
windowsize --usehints $RXVTWINDOWID 21 7 windowsize --usehints $RXVTWINDOWID 10 9 windowsize --usehints $RXVTWINDOWID 30 3 windowsize --usehints $RXVTWINDOWID 15 2
164
Python
.py
4
40
40
0.825
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,201
smenu.py
urwid_urwid/docs/tutorial/smenu.py
from __future__ import annotations import typing import urwid if typing.TYPE_CHECKING: from collections.abc import Iterable choices = "Chapman Cleese Gilliam Idle Jones Palin".split() def menu(title: str, choices_: Iterable[str]) -> urwid.ListBox: body = [urwid.Text(title), urwid.Divider()] for c in choices_: button = urwid.Button(c) urwid.connect_signal(button, "click", item_chosen, c) body.append(urwid.AttrMap(button, None, focus_map="reversed")) return urwid.ListBox(urwid.SimpleFocusListWalker(body)) def item_chosen(button: urwid.Button, choice: str) -> None: response = urwid.Text(["You chose ", choice, "\n"]) done = urwid.Button("Ok") urwid.connect_signal(done, "click", exit_program) main.original_widget = urwid.Filler( urwid.Pile( [ response, urwid.AttrMap(done, None, focus_map="reversed"), ] ) ) def exit_program(button: urwid.Button) -> None: raise urwid.ExitMainLoop() main = urwid.Padding(menu("Pythons", choices), left=2, right=2) top = urwid.Overlay( main, urwid.SolidFill("\N{MEDIUM SHADE}"), align=urwid.CENTER, width=(urwid.RELATIVE, 60), valign=urwid.MIDDLE, height=(urwid.RELATIVE, 60), min_width=20, min_height=9, ) urwid.MainLoop(top, palette=[("reversed", "standout", "")]).run()
1,390
Python
.py
39
30.025641
70
0.660941
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,202
test_padding.py
urwid_urwid/tests/test_padding.py
from __future__ import annotations import unittest import urwid class PaddingTest(unittest.TestCase): def test_sizing(self) -> None: fixed_only = urwid.BigText("3", urwid.HalfBlock5x4Font()) fixed_flow = urwid.Text("Some text", align=urwid.CENTER) flow_only = urwid.ProgressBar(None, None) with self.subTest("Fixed only"): widget = urwid.Padding(fixed_only) self.assertEqual(frozenset((urwid.FIXED,)), widget.sizing()) cols, rows = 5, 4 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "▄▀▀▄ ", " ▄▀ ", "▄ █ ", " ▀▀ ", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("Fixed only + relative size & default align"): widget = urwid.Padding(fixed_only, width=(urwid.RELATIVE, 50)) self.assertEqual(frozenset((urwid.FIXED,)), widget.sizing()) cols, rows = 10, 4 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "▄▀▀▄ ", " ▄▀ ", "▄ █ ", " ▀▀ ", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("FIXED/FLOW"): widget = urwid.Padding(fixed_flow) self.assertEqual(frozenset((urwid.FIXED, urwid.FLOW)), widget.sizing()) cols, rows = 9, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( ["Some text"], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("FIXED/FLOW + relative size & right align"): widget = urwid.Padding(fixed_flow, width=(urwid.RELATIVE, 65), align=urwid.RIGHT) self.assertEqual(frozenset((urwid.FIXED, urwid.FLOW)), widget.sizing()) cols, rows = 14, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [" Some text"], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("GIVEN FLOW make FIXED"): widget = urwid.Padding(flow_only, width=5, align=urwid.RIGHT, right=1) self.assertEqual(frozenset((urwid.FIXED, urwid.FLOW)), widget.sizing()) cols, rows = 6, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [" 0 % "], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("GIVEN FIXED = error"): widget = urwid.Padding(fixed_only, width=5) with self.assertWarns(urwid.widget.padding.PaddingWarning) as ctx, self.assertRaises(AttributeError): widget.sizing() self.assertEqual( f"WHSettings.GIVEN expect BOX or FLOW widget to be used, but received {fixed_only}", str(ctx.warnings[0].message), ) widget.pack(()) self.assertEqual( f"WHSettings.GIVEN expect BOX or FLOW widget to be used, but received {fixed_only}", str(ctx.warnings[1].message), ) with self.assertRaises(ValueError) as err_ctx: widget.render(()) self.assertEqual( "FixedWidget takes only () for size.passed: (5,)", str(err_ctx.exception), ) def test_fixed(self) -> None: """Test real-world like scenario with padded contents.""" col_list = [ urwid.SolidFill(), urwid.Button("OK", align=urwid.CENTER), urwid.SolidFill(), urwid.Button("Cancel", align=urwid.CENTER), urwid.SolidFill(), ] body = urwid.Pile( ( (urwid.Text("Window content text here and it should not touch line", align=urwid.CENTER)), (urwid.PACK, urwid.Columns(col_list, dividechars=1, box_columns=(0, 2, 4))), ) ) widget = urwid.LineBox( urwid.Pile( ( urwid.Text("Modal window", align=urwid.CENTER), urwid.Divider("─"), urwid.Padding(body, width=urwid.PACK, left=1, right=1), ) ) ) self.assertEqual(frozenset((urwid.FIXED, urwid.FLOW)), widget.sizing()) cols, rows = 57, 6 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "┌───────────────────────────────────────────────────────┐", "│ Modal window │", "│───────────────────────────────────────────────────────│", "│ Window content text here and it should not touch line │", "│ < OK > < Cancel > │", "└───────────────────────────────────────────────────────┘", ], [line.decode("utf-8") for line in canvas.text], ) # Forward keypress self.assertEqual("OK", body.focus.focus.label) widget.keypress((), "right") self.assertEqual("Cancel", body.focus.focus.label) def test_insufficient_space(self): width = 10 widget = urwid.Padding(urwid.Text("Some text"), width=width) with self.assertWarns(urwid.widget.PaddingWarning) as ctx: canvas = widget.render((width - 1,)) self.assertEqual("Some text", str(canvas)) self.assertEqual(width - 1, canvas.cols()) def ptest(self, desc, align, width, maxcol, left, right, min_width=None): p = urwid.Padding(None, align, width, min_width) l, r = p.padding_values((maxcol,), False) assert (l, r) == (left, right), f"{desc} expected {left, right} but got {l, r}" def petest(self, desc, align, width): self.assertRaises(urwid.PaddingError, lambda: urwid.Padding(None, align, width)) def test_create(self): self.petest("invalid pad", 6, 5) self.petest("invalid pad type", ("bad", 2), 5) self.petest("invalid width", "center", "42") self.petest("invalid width type", "center", ("gouranga", 4)) def test_values(self): self.ptest("left align 5 7", "left", 5, 7, 0, 2) self.ptest("left align 7 7", "left", 7, 7, 0, 0) self.ptest("left align 9 7", "left", 9, 7, 0, 0) self.ptest("right align 5 7", "right", 5, 7, 2, 0) self.ptest("center align 5 7", "center", 5, 7, 1, 1) self.ptest("fixed left", ("fixed left", 3), 5, 10, 3, 2) self.ptest("fixed left reduce", ("fixed left", 3), 8, 10, 2, 0) self.ptest("fixed left shrink", ("fixed left", 3), 18, 10, 0, 0) self.ptest("fixed left, right", ("fixed left", 3), ("fixed right", 4), 17, 3, 4) self.ptest("fixed left, right, min_width", ("fixed left", 3), ("fixed right", 4), 10, 3, 2, 5) self.ptest("fixed left, right, min_width 2", ("fixed left", 3), ("fixed right", 4), 10, 2, 0, 8) self.ptest("fixed right", ("fixed right", 3), 5, 10, 2, 3) self.ptest("fixed right reduce", ("fixed right", 3), 8, 10, 0, 2) self.ptest("fixed right shrink", ("fixed right", 3), 18, 10, 0, 0) self.ptest("fixed right, left", ("fixed right", 3), ("fixed left", 4), 17, 4, 3) self.ptest("fixed right, left, min_width", ("fixed right", 3), ("fixed left", 4), 10, 2, 3, 5) self.ptest("fixed right, left, min_width 2", ("fixed right", 3), ("fixed left", 4), 10, 0, 2, 8) self.ptest("relative 30", ("relative", 30), 5, 10, 1, 4) self.ptest("relative 50", ("relative", 50), 5, 10, 2, 3) self.ptest("relative 130 edge", ("relative", 130), 5, 10, 5, 0) self.ptest("relative -10 edge", ("relative", -10), 4, 10, 0, 6) self.ptest("center relative 70", "center", ("relative", 70), 10, 1, 2) self.ptest("center relative 70 grow 8", "center", ("relative", 70), 10, 1, 1, 8) def mctest(self, desc, left, right, size, cx, innercx): class Inner: def __init__(self, desc, innercx): self.desc = desc self.innercx = innercx def move_cursor_to_coords(self, size, cx, cy): assert cx == self.innercx, desc i = Inner(desc, innercx) p = urwid.Padding(i, ("fixed left", left), ("fixed right", right)) p.move_cursor_to_coords(size, cx, 0) def test_cursor(self): self.mctest("cursor left edge", 2, 2, (10, 2), 2, 0) self.mctest("cursor left edge-1", 2, 2, (10, 2), 1, 0) self.mctest("cursor right edge", 2, 2, (10, 2), 7, 5) self.mctest("cursor right edge+1", 2, 2, (10, 2), 8, 5) def test_reduced_padding_cursor(self): # FIXME: This is at least consistent now, but I don't like it. # pack() on an Edit should leave room for the cursor # fixing this gets deep into things like Edit._shift_view_to_cursor # though, so this might not get fixed for a while p = urwid.Padding(urwid.Edit("", ""), width="pack", left=4) self.assertEqual(p.render((10,), True).cursor, None) self.assertEqual(p.get_cursor_coords((10,)), None) self.assertEqual(p.render((4,), True).cursor, None) self.assertEqual(p.get_cursor_coords((4,)), None) p = urwid.Padding(urwid.Edit("", ""), width=("relative", 100), left=4) self.assertEqual(p.render((10,), True).cursor, (4, 0)) self.assertEqual(p.get_cursor_coords((10,)), (4, 0)) self.assertEqual(p.render((4,), True).cursor, None) self.assertEqual(p.get_cursor_coords((4,)), None)
11,217
Python
.py
214
38.425234
113
0.526714
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,203
test_container.py
urwid_urwid/tests/test_container.py
from __future__ import annotations import unittest import urwid class WidgetSquishTest(unittest.TestCase): def wstest(self, w): c = w.render((80, 0), focus=False) assert c.rows() == 0 c = w.render((80, 0), focus=True) assert c.rows() == 0 c = w.render((80, 1), focus=False) assert c.rows() == 1 c = w.render((0, 25), focus=False) c = w.render((1, 25), focus=False) def fwstest(self, w): def t(cols: int, focus: bool): wrows = w.rows((cols,), focus) c = w.render((cols,), focus) self.assertEqual(c.rows(), wrows, f"Canvas rows {c.rows()} != widget rows {wrows}") if focus and hasattr(w, "get_cursor_coords"): gcc = w.get_cursor_coords((cols,)) self.assertEqual(c.cursor, gcc, f"Canvas cursor {c.cursor} != widget cursor {gcc}") for cols, focus in ((0, False), (1, False), (0, True), (1, True)): with self.subTest(f"{w.__class__.__name__} cols={cols} and focus={focus}"): t(cols, focus) def test_listbox(self): self.wstest(urwid.ListBox(urwid.SimpleListWalker([]))) self.wstest(urwid.ListBox(urwid.SimpleListWalker([urwid.Text("hello")]))) def test_bargraph(self): self.wstest(urwid.BarGraph(["foo", "bar"])) def test_graphvscale(self): self.wstest(urwid.GraphVScale([(0, "hello")], 1)) self.wstest(urwid.GraphVScale([(5, "hello")], 1)) def test_solidfill(self): self.wstest(urwid.SolidFill()) def test_filler(self): self.wstest(urwid.Filler(urwid.Text("hello"))) def test_overlay(self): self.wstest( urwid.Overlay( urwid.BigText("hello", urwid.Thin6x6Font()), urwid.SolidFill(), "center", None, "middle", None ) ) self.wstest(urwid.Overlay(urwid.Text("hello"), urwid.SolidFill(), "center", ("relative", 100), "middle", None)) def test_frame(self): self.wstest(urwid.Frame(urwid.SolidFill())) self.wstest(urwid.Frame(urwid.SolidFill(), header=urwid.Text("hello"))) self.wstest(urwid.Frame(urwid.SolidFill(), header=urwid.Text("hello"), footer=urwid.Text("hello"))) def test_pile(self): self.wstest(urwid.Pile([urwid.SolidFill()])) self.wstest(urwid.Pile([("flow", urwid.Text("hello"))])) self.wstest(urwid.Pile([])) def test_columns(self): self.wstest(urwid.Columns([urwid.SolidFill()])) self.wstest(urwid.Columns([(4, urwid.SolidFill())])) def test_buttons(self): self.fwstest(urwid.Button("hello")) self.fwstest(urwid.RadioButton([], "hello")) def testFocus(self): expect_focused = urwid.Button("Focused") pile = urwid.Pile((urwid.Button("First"), expect_focused, urwid.Button("Last")), focus_item=expect_focused) self.assertEqual(1, pile.focus_position) self.assertEqual(expect_focused, pile.focus) class CommonContainerTest(unittest.TestCase): def test_list_box(self): lb = urwid.ListBox(urwid.SimpleFocusListWalker([])) self.assertEqual(lb.focus, None) self.assertRaises(IndexError, lambda: getattr(lb, "focus_position")) self.assertRaises(IndexError, lambda: setattr(lb, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(lb, "focus_position", 0)) t1 = urwid.Text("one") t2 = urwid.Text("two") lb = urwid.ListBox(urwid.SimpleListWalker([t1, t2])) self.assertEqual(lb.focus, t1) self.assertEqual(lb.focus_position, 0) lb.focus_position = 1 self.assertEqual(lb.focus, t2) self.assertEqual(lb.focus_position, 1) lb.focus_position = 0 self.assertRaises(IndexError, lambda: setattr(lb, "focus_position", -1)) self.assertRaises(IndexError, lambda: setattr(lb, "focus_position", 2)) def test_focus_path(self): # big tree of containers t = urwid.Text("x") e = urwid.Edit("?") c = urwid.Columns([t, e, t, t]) p = urwid.Pile([t, t, c, t]) a = urwid.AttrMap(p, "gets ignored") s = urwid.SolidFill("/") o = urwid.Overlay(e, s, "center", "pack", "middle", "pack") lb = urwid.ListBox(urwid.SimpleFocusListWalker([t, a, o, t])) lb.focus_position = 1 g = urwid.GridFlow([t, t, t, t, e, t], 10, 0, 0, "left") g.focus_position = 4 f = urwid.Frame(lb, header=t, footer=g) self.assertEqual(f.get_focus_path(), ["body", 1, 2, 1]) f.set_focus_path(["footer"]) # same as f.focus_position = 'footer' self.assertEqual(f.get_focus_path(), ["footer", 4]) f.set_focus_path(["body", 1, 2, 2]) self.assertEqual(f.get_focus_path(), ["body", 1, 2, 2]) self.assertRaises(IndexError, lambda: f.set_focus_path([0, 1, 2])) self.assertRaises(IndexError, lambda: f.set_focus_path(["body", 2, 2])) f.set_focus_path(["body", 2]) # focus the overlay self.assertEqual(f.get_focus_path(), ["body", 2, 1])
5,094
Python
.py
103
40.631068
119
0.603944
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,204
test_columns.py
urwid_urwid/tests/test_columns.py
from __future__ import annotations import typing import unittest import urwid from tests.util import SelectableText if typing.TYPE_CHECKING: from collections.abc import Collection from typing_extensions import Literal class ColumnsTest(unittest.TestCase): def test_basic_sizing(self) -> None: box_only = urwid.SolidFill("#") flow_only = urwid.ProgressBar(None, None) fixed_only = urwid.BigText("0", urwid.Thin3x3Font()) flow_fixed = urwid.Text("text") with self.subTest("No sizing calculation possible"), self.assertWarns(urwid.widget.ColumnsWarning) as ctx: widget = urwid.Columns(((urwid.PACK, fixed_only), box_only), box_columns=(1,)) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) for description, kwargs in ( ("BOX-only widget", {"widget_list": (box_only,)}), ('BOX-only widget with "get height from max"', {"widget_list": (box_only,), "box_columns": (0,)}), ("No FLOW - BOX only", {"widget_list": (box_only, urwid.SolidFill(" ")), "box_columns": (0, 1)}), ("GIVEN BOX only -> BOX only", {"widget_list": ((5, box_only),), "box_columns": (0,)}), ): with self.subTest(description): widget = urwid.Columns(**kwargs) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) cols, rows = 2, 2 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FLOW-only"): widget = urwid.Columns((flow_only,)) self.assertEqual(frozenset((urwid.FLOW,)), widget.sizing()) cols, rows = 2, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest('BOX/FLOW by "box_columns": can be rendered as box only as fallback'): widget = urwid.Columns((flow_only, box_only), box_columns=(1,)) self.assertEqual(frozenset((urwid.FLOW,)), widget.sizing()) cols, rows = 2, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FLOW/FIXED"): widget = urwid.Columns((flow_fixed,)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 4, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) cols, rows = 2, 2 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FIXED only"): widget = urwid.Columns(((urwid.PACK, fixed_only),)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 3, 3 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FIXED only use FLOW methods - drop & replace by solid"): widget = urwid.Columns(((urwid.PACK, fixed_only),)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 2, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual(" ", str(canvas)) with self.subTest("FIXED only use FLOW methods - add empty space"): widget = urwid.Columns(((urwid.PACK, fixed_only),)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 5, 3 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( ( "┌─┐ ", "│ │ ", "└─┘ ", ), canvas.decoded_text, ) with self.subTest("GIVEN BOX + FLOW/FIXED, but other widgets do not support box"): widget = urwid.Columns((flow_fixed, (3, box_only)), box_columns=(1,)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 7, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) cols, rows = 4, 4 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual([b"t###", b"e###", b"x###", b"t###"], canvas.text) cols, rows = 2, 2 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual([b"te", b"xt"], canvas.text) with self.subTest("Wrong sizing -> fallback to historic hardcoded"): with self.assertWarns(urwid.widget.ColumnsWarning) as ctx: widget = urwid.Columns(((urwid.PACK, box_only),)) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) self.assertEqual( f"Sizing combination of widget {box_only} (position=0) not supported: PACK box=False", str(ctx.warnings[0].message), ) with self.subTest("Wrong sizing -> fallback to historic hardcoded 2"): with self.assertWarns(urwid.widget.ColumnsWarning) as ctx: widget = urwid.Columns(((urwid.WEIGHT, 1, fixed_only),)) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) self.assertEqual( f"Sizing combination of widget {fixed_only} (position=0) not supported: WEIGHT box=False", str(ctx.warnings[0].message), ) with self.subTest( 'BOX not added to "box_columns" but widget handled as FLOW', ), self.assertWarns( urwid.widget.ColumnsWarning, ) as ctx: self.maxDiff = None contents = ( (urwid.WEIGHT, 1, urwid.SolidFill()), (urwid.FIXED, 10, urwid.Button("OK", align=urwid.CENTER)), (urwid.WEIGHT, 1, urwid.SolidFill()), (urwid.FIXED, 10, urwid.Button("Cancel", align=urwid.CENTER)), (urwid.WEIGHT, 1, urwid.SolidFill()), ) widget = urwid.Columns(contents) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) self.assertEqual( "Columns widget contents flags not allow to determine supported render kind:\n" "BOX WEIGHT, FIXED|FLOW GIVEN\n" "Using fallback hardcoded BOX|FLOW sizing kind.", str(ctx.warnings[0].message), ) cols, rows = 30, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(rows, canvas.rows()) self.assertEqual(cols, canvas.cols()) self.assertEqual([b" < OK > < Cancel > "], canvas.text) self.assertEqual( "Widgets in columns [0, 2, 4] " f"({[elem[-1] for elem in contents[:6:2]]}) " f'are BOX widgets not marked "box_columns" ' f"while FLOW render is requested (size=(30,))", str(ctx.warnings[2].message), ) self.assertEqual("OK", widget.focus.label) self.assertIsNone(widget.keypress((cols,), "right")) self.assertEqual( "Widgets in columns [0, 2, 4] " f"({[elem[-1] for elem in contents[:6:2]]}) " f'are BOX widgets not marked "box_columns" ' f"while FLOW render is requested (size=(30,))", str(ctx.warnings[3].message), ) self.assertEqual("Cancel", widget.focus.label) def test_pack_render_fixed(self) -> None: """Cover weighted FIXED/FLOW widgets pack. One of the popular use-cases: rows of buttons/radiobuttons/checkboxes in pop-up windows. """ widget = urwid.Columns( (urwid.Button(label, align=urwid.CENTER) for label in ("OK", "Cancel", "Help")), dividechars=1, ) self.assertEqual((32, 1), widget.pack(())) self.assertEqual([b"< OK > < Cancel > < Help >"], widget.render(()).text) def test_render_fixed_consistency(self) -> None: """Widgets supporting FIXED should be rendered with PACK side the same way as not FIXED.""" widget = urwid.Columns(((urwid.PACK, urwid.Text("Prefix:")), (urwid.PACK, urwid.Button("Btn"))), dividechars=1) cols, _ = widget.pack(()) self.assertEqual(((7, 7), (1, 1), ((), ())), widget.get_column_sizes(())) self.assertEqual(((7, 7), (1, 1), ((7,), (7,))), widget.get_column_sizes((cols,))) self.assertEqual(("Prefix: < Btn >",), widget.render(()).decoded_text) self.assertEqual(("Prefix: < Btn >",), widget.render((cols,)).decoded_text) def test_render_pack_item_not_fit(self): items = urwid.Text("123"), urwid.Text("456") widget = urwid.Columns((urwid.PACK, item) for item in items) # Make width < widget fixed pack width = items[0].pack(())[0] - 1 height = items[0].rows((width,)) self.assertEqual((width, height), widget.pack((width,))) canvas = widget.render((width,)) # Rendered should be not empty self.assertEqual(items[0].render((width,)).decoded_text, canvas.decoded_text) self.assertEqual(width, canvas.cols()) def test_pack_render_broken_sizing(self) -> None: use_sizing = frozenset((urwid.BOX,)) class BrokenSizing(urwid.Text): def sizing(self) -> frozenset[urwid.Sizing]: return use_sizing with self.assertWarns(urwid.widget.ColumnsWarning) as ctx: element = BrokenSizing("Test") widget = urwid.Columns(((urwid.PACK, element),)) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) self.assertEqual( f"Sizing combination of widget {element} (position=0) not supported: PACK box=False", str(ctx.warnings[0].message), ) with self.assertWarns(urwid.widget.ColumnsWarning) as ctx: canvas = widget.render((10,)) self.assertEqual([b"Test "], canvas.text) self.assertEqual( f"Unusual widget {element} sizing for {urwid.PACK} (box=False). " f"Assuming wrong sizing and using FLOW for width calculation", str(ctx.warnings[0].message), ) def test_pack_render_skip_widget(self): widget = urwid.Columns(((0, urwid.Text("Ignore\nme")), (urwid.Text("Count")))) cols, rows = 5, 1 self.assertEqual((cols, rows), widget.pack(())) self.assertEqual((cols, rows), widget.pack((cols,))) self.assertEqual("Count", str(widget.render(()))) self.assertEqual("Count", str(widget.render((cols,)))) def test_pack_flow_with_fixed_item(self): widget = urwid.Columns( ( (urwid.PACK, urwid.BigText("3", urwid.Thin3x3Font())), (urwid.Text("Multi\nline\ntext\n???")), ), dividechars=1, ) with self.subTest("Skip"): self.assertEqual(3, widget.rows((3,))) self.assertEqual((3, 3), widget.pack((3,))) self.assertEqual( ( "┌─┐", " ─┤", "└─┘", ), widget.render((3,)).decoded_text, ) with self.subTest("Fit all"): self.assertEqual(4, widget.rows((9,))) self.assertEqual((9, 4), widget.pack((9,))) self.assertEqual( ( "┌─┐ Multi", " ─┤ line ", "└─┘ text ", " ??? ", ), widget.render((9,)).decoded_text, ) with self.subTest("Use SolidCanvas instead"): self.assertEqual(1, widget.rows((2,))) self.assertEqual((2, 1), widget.pack((2,))) self.assertEqual((" ",), widget.render((2,)).decoded_text) def test_pack_render_empty_widget(self): widget = urwid.Columns(()) self.assertEqual(frozenset((urwid.FLOW, urwid.BOX)), widget.sizing()) cols, rows = 10, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(rows, canvas.rows()) self.assertEqual((" ",), canvas.decoded_text) def test_not_a_widget(self): class NotAWidget: __slots__ = ("name", "symbol") def __init__(self, name: str, symbol: bytes) -> None: self.name = name self.symbol = symbol def __repr__(self) -> str: return f"{self.__class__.__name__}(name={self.name!r}, symbol={self.symbol!r})" def selectable(self) -> bool: return False def rows(self, max_col_row: tuple[int], focus: bool = False) -> int: return 1 def render(self, max_col_row: tuple[int, int] | tuple[int], focus: bool = False) -> urwid.Canvas: maxcol = max_col_row[0] line = self.symbol * maxcol if len(max_col_row) == 1: return urwid.TextCanvas((line,), maxcol=maxcol) return urwid.TextCanvas((line,) * max_col_row[1], maxcol=maxcol) with self.subTest("Box"), self.assertWarns(urwid.widget.ColumnsWarning) as ctx: items = (NotAWidget("First", b"*"), NotAWidget("Second", b"^")) widget = urwid.Columns(items) self.assertEqual(("**^^", "**^^"), widget.render((4, 2)).decoded_text) self.assertEqual(f"{items[0]!r} is not a Widget", str(ctx.warnings[0].message)) self.assertEqual(f"{items[1]!r} is not a Widget", str(ctx.warnings[1].message)) with self.subTest("Flow"), self.assertWarns(urwid.widget.ColumnsWarning) as ctx: items = (NotAWidget("First", b"*"), NotAWidget("Second", b"^")) widget = urwid.Columns(items) self.assertEqual(("***^^^",), widget.render((6,)).decoded_text) self.assertEqual(f"{items[0]!r} is not a Widget", str(ctx.warnings[0].message)) self.assertEqual(f"{items[1]!r} is not a Widget", str(ctx.warnings[1].message)) def test_zero_width_column(self): elem_1 = urwid.BoxAdapter(urwid.SolidFill("#"), 2) elem_2 = urwid.BoxAdapter(urwid.SolidFill("*"), 4) widget = urwid.Columns((elem_1, (0, elem_2))) self.assertEqual((3, 2), widget.pack((3,))) canvas = widget.render((3,)) self.assertEqual(2, canvas.rows()) self.assertEqual(3, canvas.cols()) self.assertEqual([b"###", b"###"], canvas.text) def test_focus_column(self): button_1 = urwid.Button("Selectable") button_2 = urwid.Button("Other selectable") widget_list = [ (urwid.PACK, urwid.Text("Non selectable")), (urwid.PACK, button_1), (urwid.PACK, button_2), (urwid.PACK, urwid.Text("The end")), ] with self.subTest("Not provided -> select first selectable"): widget = urwid.Columns(widget_list) self.assertEqual(1, widget.focus_position) widget.keypress((), "left") self.assertEqual(1, widget.focus_position) with self.subTest("Exact index"): widget = urwid.Columns(widget_list, focus_column=2) self.assertEqual(2, widget.focus_position) widget.keypress((), "left") self.assertEqual(1, widget.focus_position) with self.subTest("Exact widget"): widget = urwid.Columns(widget_list, focus_column=button_2) self.assertEqual(2, widget.focus_position) self.assertEqual(button_2, widget.focus) widget.keypress((), "left") self.assertEqual(1, widget.focus_position) def test_pack_not_enough_info(self): """Test special case for not official fixed pack and render support.""" widget = urwid.Columns( ( (urwid.WEIGHT, 16, urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE)), (10, urwid.Button("First")), urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE), (10, urwid.Button("Second")), (urwid.WEIGHT, 16, urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE)), ), box_columns=(0, 2, 4), ) cols, rows = 53, 1 self.assertEqual(frozenset((urwid.FLOW,)), widget.sizing()) self.assertEqual((cols, rows), widget.pack(())) self.assertEqual( ("░░░░░░░░░░░░░░░░< First >░< Second >░░░░░░░░░░░░░░░░",), widget.render(()).decoded_text, ) def test_no_height(self): widget = urwid.Columns( ( (urwid.WEIGHT, 16, urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE)), urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE), (urwid.WEIGHT, 16, urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE)), ), box_columns=(0, 1, 2), ) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) with self.assertRaises(urwid.widget.ColumnsError): widget.pack(()) def assert_column_widths( self, expected: Collection[int], widget: urwid.Columns, size: tuple[int, int] | tuple[int] | tuple[()], description: str, ) -> None: column_widths, _, _ = widget.get_column_sizes(size) self.assertEqual(expected, column_widths, f"{description} expected {expected}, got {column_widths}") def test_widths(self): x = urwid.Text("") # sample "column" self.assert_column_widths((20,), urwid.Columns([x]), (20,), "simple 1") self.assert_column_widths((10, 10), urwid.Columns([x, x]), (20,), "simple 2") self.assert_column_widths((10, 9), urwid.Columns([x, x], 1), (20,), "simple 2+1") self.assert_column_widths((6, 6, 6), urwid.Columns([x, x, x], 1), (20,), "simple 3+1") self.assert_column_widths((5, 6, 5), urwid.Columns([x, x, x], 2), (20,), "simple 3+2") self.assert_column_widths((6, 6, 5), urwid.Columns([x, x, x], 2), (21,), "simple 3+2") simple_4 = urwid.Columns([x, x, x, x], 1) for expected, cols, description in ( ((6, 5, 6, 5), 25, "simple 4+1"), ((1, 1, 1, 1), 7, "squish 4+1"), ((1, 2, 1), 6, "squish 4+1"), ((2, 1), 4, "squish 4+1"), ): with self.subTest(description): self.assert_column_widths(expected, simple_4, (cols,), description) fixed = urwid.Columns([("fixed", 4, x), ("fixed", 6, x), ("fixed", 2, x)], 1) for expected, size, description in ( ((4, 6, 2), (), "FIXED"), ((4, 6, 2), (25,), "fixed 3"), ((4, 6), (13,), "fixed 3 cut"), ((4,), (10,), "fixed 3 cut2"), ): with self.subTest(description): self.assert_column_widths(expected, fixed, size, description) mixed = urwid.Columns([("weight", 2, x), ("fixed", 5, x), x, ("weight", 3, x)], 1) for expected, cols, description in ( ((2, 5, 1, 3), 14, "mixed 4"), ((1, 5, 1, 2), 12, "mixed 4 a"), ((2, 5, 1), 10, "mixed 4 b"), ((4, 5, 2, 6), 20, "mixed 4 c"), ): with self.subTest(description): self.assert_column_widths(expected, mixed, (cols,), description) def test_widths_focus_end(self): x = urwid.Text("") # sample "column" self.assert_column_widths( (10, 10), urwid.Columns([x, x], focus_column=1), (20,), "end simple 2", ) self.assert_column_widths( (10, 9), urwid.Columns([x, x], 1, 1), (20,), "end simple 2+1", ) self.assert_column_widths( (6, 6, 6), urwid.Columns([x, x, x], 1, 2), (20,), "end simple 3+1", ) self.assert_column_widths( (5, 6, 5), urwid.Columns([x, x, x], 2, 2), (20,), "end simple 3+2", ) self.assert_column_widths( (6, 6, 5), urwid.Columns([x, x, x], 2, 2), (21,), "end simple 3+2", ) simple_4 = urwid.Columns([x, x, x, x], 1, 3) for expected, cols, description in ( ((6, 5, 6, 5), 25, "end simple 4+1"), ((1, 1, 1, 1), 7, "end squish 4+1"), ((0, 1, 2, 1), 6, "end squish 4+1"), ((0, 0, 2, 1), 4, "end squish 4+1"), ): with self.subTest(description): self.assert_column_widths(expected, simple_4, (cols,), description) fixed = urwid.Columns([("fixed", 4, x), ("fixed", 6, x), ("fixed", 2, x)], 1, 2) for expected, size, description in ( ((4, 6, 2), (), "FIXED"), ((4, 6, 2), (25,), "end fixed 3"), ((0, 6, 2), (13,), "end fixed 3 cut"), ((0, 0, 2), (8,), "end fixed 3 cut2"), ): with self.subTest(description): self.assert_column_widths(expected, fixed, size, description) mixed = urwid.Columns([("weight", 2, x), ("fixed", 5, x), x, ("weight", 3, x)], 1, 3) for expected, cols, description in ( ((2, 5, 1, 3), 14, "end mixed 4"), ((1, 5, 1, 2), 12, "end mixed 4 a"), ((0, 5, 1, 2), 10, "end mixed 4 b"), ((4, 5, 2, 6), 20, "end mixed 4 c"), ): with self.subTest(description): self.assert_column_widths(expected, mixed, (cols,), description) def check_move_cursor( self, expected: bool, widget: urwid.Columns, size: tuple[int, int] | tuple[int] | tuple[()], col: int | Literal["left", "right"], row: int, focus_position: int, pref_col: int | Literal["left", "right"] | None, description: str, ) -> None: moved = widget.move_cursor_to_coords(size, col, row) self.assertEqual(expected, moved, f"{description} expected {expected!r}, got {moved!r}") self.assertEqual( focus_position, widget.focus_position, f"{description} expected focus_position {focus_position!r}, got {widget.focus_position!r}", ) w_pref_col = widget.get_pref_col(size) self.assertEqual( pref_col, w_pref_col, f"{description} expected pref_col {pref_col!r}, got {w_pref_col!r}", ) def test_move_cursor(self): e, s, x = urwid.Edit("", ""), SelectableText(""), urwid.Text("") self.check_move_cursor( False, urwid.Columns([x, x, x], 1), (20,), 9, 0, 0, None, "nothing selectable", ) mid = urwid.Columns([x, s, x], 1) self.check_move_cursor( True, mid, (20,), 9, 0, 1, 9, "dead on", ) self.check_move_cursor( True, mid, (20,), 6, 0, 1, 6, "l edge", ) self.check_move_cursor( True, mid, (20,), 13, 0, 1, 13, "r edge", ) self.check_move_cursor( True, mid, (20,), 2, 0, 1, 2, "l off", ) self.check_move_cursor( True, mid, (20,), 17, 0, 1, 17, "r off", ) self.check_move_cursor( True, urwid.Columns([x, x, s], 1), (20,), 2, 0, 2, 2, "l off 2", ) self.check_move_cursor( True, urwid.Columns([s, x, x], 1), (20,), 17, 0, 0, 17, "r off 2", ) self.check_move_cursor( True, urwid.Columns([s, s, x], 1), (20,), 6, 0, 0, 6, "l between", ) self.check_move_cursor( True, urwid.Columns([x, s, s], 1), (20,), 13, 0, 1, 13, "r between", ) l_2 = urwid.Columns([s, s, x], 2) self.check_move_cursor( True, l_2, (22,), 6, 0, 0, 6, "l between 2l", ) self.check_move_cursor( True, l_2, (22,), 7, 0, 1, 7, "l between 2r", ) r_2 = urwid.Columns([x, s, s], 2) self.check_move_cursor( True, r_2, (22,), 14, 0, 1, 14, "r between 2l", ) self.check_move_cursor( True, r_2, (22,), 15, 0, 2, 15, "r between 2r", ) # unfortunate pref_col shifting edge = urwid.Columns([x, e, x], 1) self.check_move_cursor( True, edge, (20,), 6, 0, 1, 7, "l e edge", ) self.check_move_cursor( True, edge, (20,), 13, 0, 1, 12, "r e edge", ) # 'left'/'right' special cases full = urwid.Columns([e, e, e]) self.check_move_cursor( True, full, (12,), "right", 0, 2, "right", "l e edge", ) self.check_move_cursor( True, full, (12,), "left", 0, 0, "left", "r e edge", ) def test_init_with_a_generator(self): urwid.Columns(urwid.Text(c) for c in "ABC") def test_old_attributes(self): c = urwid.Columns([urwid.Text("a"), urwid.SolidFill("x")], box_columns=[1]) with self.assertWarns(PendingDeprecationWarning): self.assertEqual(c.box_columns, [1]) with self.assertWarns(PendingDeprecationWarning): c.box_columns = [] self.assertEqual(c.box_columns, []) def test_box_column(self): c = urwid.Columns([urwid.Filler(urwid.Edit()), urwid.Text("")], box_columns=[0]) c.keypress((10,), "x") c.get_cursor_coords((10,)) c.move_cursor_to_coords((10,), 0, 0) c.mouse_event((10,), "foo", 1, 0, 0, True) c.get_pref_col((10,)) def test_length(self): columns = urwid.Columns(urwid.Text(c) for c in "ABC") self.assertEqual(3, len(columns)) self.assertEqual(3, len(columns.contents)) def test_common(self): t1 = urwid.Text("one") t2 = urwid.Text("two") t3 = urwid.Text("three") sf = urwid.SolidFill("x") c = urwid.Columns([]) with self.subTest("Focus"): self.assertEqual(c.focus, None) self.assertRaises(IndexError, lambda: getattr(c, "focus_position")) self.assertRaises(IndexError, lambda: setattr(c, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(c, "focus_position", 0)) with self.subTest("Contents change"): c.contents = [ (t1, ("pack", None, False)), (t2, ("weight", 1, False)), (sf, ("weight", 2, True)), (t3, ("given", 10, False)), ] c.focus_position = 1 del c.contents[0] self.assertEqual(c.focus_position, 0) c.contents[0:0] = [(t3, ("given", 10, False)), (t2, ("weight", 1, False))] c.contents.insert(3, (t1, ("pack", None, False))) self.assertEqual(c.focus_position, 2) with self.subTest("Contents change validation"): c.contents.clear() self.assertRaises(urwid.ColumnsError, lambda: c.contents.append(t1)) self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, None))) self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, "given"))) self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, ("given", None)))) # Incorrect kind self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, ("what", 1, False)))) # Incorrect box field self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, ("given", 1, None)))) # Incorrect size type self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, ("given", (), False)))) # Incorrect size self.assertRaises(urwid.ColumnsError, lambda: c.contents.append((t1, ("given", -1, False)))) # Float and int weight accepted c.contents.append((t1, ("weight", 1, False))) c.contents.append((t2, ("weight", 0.5, False))) self.assertEqual(("one two",), c.render(()).decoded_text) def test_focus_position(self): t1 = urwid.Text("one") t2 = urwid.Text("two") c = urwid.Columns([t1, t2]) self.assertEqual(c.focus, t1) self.assertEqual(c.focus_position, 0) c.focus_position = 1 self.assertEqual(c.focus, t2) self.assertEqual(c.focus_position, 1) c.focus_position = 0 self.assertRaises(IndexError, lambda: setattr(c, "focus_position", -1)) self.assertRaises(IndexError, lambda: setattr(c, "focus_position", 2)) def test_deprecated(self): t1 = urwid.Text("one") t2 = urwid.Text("two") sf = urwid.SolidFill("x") # old methods: c = urwid.Columns([t1, ("weight", 3, t2), sf], box_columns=[2]) with self.subTest("Focus"): c.set_focus(0) self.assertRaises(IndexError, lambda: c.set_focus(-1)) self.assertRaises(IndexError, lambda: c.set_focus(3)) c.set_focus(t2) self.assertEqual(c.focus_position, 1) self.assertRaises(ValueError, lambda: c.set_focus("nonexistant")) with self.subTest("Contents"): self.assertEqual(c.widget_list, [t1, t2, sf]) self.assertEqual(c.column_types, [("weight", 1), ("weight", 3), ("weight", 1)]) self.assertEqual(c.box_columns, [2]) with self.subTest("Contents change"): c.widget_list = [t2, t1, sf] self.assertEqual(c.widget_list, [t2, t1, sf]) self.assertEqual(c.box_columns, [2]) self.assertEqual( c.contents, [(t2, ("weight", 1, False)), (t1, ("weight", 3, False)), (sf, ("weight", 1, True))], ) self.assertEqual(c.focus_position, 1) # focus unchanged c.column_types = [("flow", None), ("weight", 2), ("fixed", 5)] # use the old name self.assertEqual(c.column_types, [("flow", None), ("weight", 2), ("fixed", 5)]) self.assertEqual( c.contents, [(t2, ("pack", None, False)), (t1, ("weight", 2, False)), (sf, ("given", 5, True))], ) self.assertEqual(c.focus_position, 1) # focus unchanged with self.subTest("Contents change 2"): c.widget_list = [t1] self.assertEqual(len(c.contents), 1) self.assertEqual(c.focus_position, 0) c.widget_list.extend([t2, t1]) self.assertEqual(len(c.contents), 3) self.assertEqual(c.column_types, [("flow", None), ("weight", 1), ("weight", 1)]) c.column_types[:] = [("weight", 2)] self.assertEqual(len(c.contents), 1) def test_regression_columns_different_height(self): size = (20, 5) box_w = urwid.SolidFill("#") f_f_widget = urwid.Text("Fixed/Flow") box_flow = urwid.LineBox(urwid.Filler(f_f_widget, valign=urwid.TOP)) self.assertIn(urwid.BOX, box_w.sizing()) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), box_flow.sizing()) with self.subTest("BoxFlow weight"): widget = urwid.Columns(((1, box_w), box_flow)) self.assertEqual( ( "#┌─────────────────┐", "#│Fixed/Flow │", "#│ │", "#│ │", "#└─────────────────┘", ), widget.render(size, False).decoded_text, ) with self.subTest("BoxFlow GIVEN"): widget = urwid.Columns((box_w, (12, box_flow))) self.assertEqual( ( "########┌──────────┐", "########│Fixed/Flow│", "########│ │", "########│ │", "########└──────────┘", ), widget.render(size, False).decoded_text, )
35,893
Python
.py
835
30.461078
119
0.511257
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,205
util.py
urwid_urwid/tests/util.py
from __future__ import annotations import urwid class SelectableText(urwid.Text): def selectable(self): return True def keypress(self, size, key): return key
186
Python
.py
7
21.571429
34
0.708571
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,206
test_event_loops.py
urwid_urwid/tests/test_event_loops.py
from __future__ import annotations import asyncio import concurrent.futures import socket import sys import typing import unittest import urwid if typing.TYPE_CHECKING: from concurrent.futures import Future from types import TracebackType try: import gi.repository except ImportError: GLIB_AVAILABLE = False else: GLIB_AVAILABLE = True try: import tornado except ImportError: TORNADO_AVAILABLE = False else: TORNADO_AVAILABLE = True try: import twisted except ImportError: TWISTED_AVAILABLE = False else: TWISTED_AVAILABLE = True try: import trio except ImportError: TRIO_AVAILABLE = False else: TRIO_AVAILABLE = True try: import zmq except ImportError: ZMQ_AVAILABLE = False else: ZMQ_AVAILABLE = True IS_WINDOWS = sys.platform == "win32" class ClosingSocketPair(typing.ContextManager[typing.Tuple[socket.socket, socket.socket]]): __slots__ = ("rd_s", "wr_s") def __init__(self) -> None: self.rd_s: socket.socket | None = None self.wr_s: socket.socket | None = None def __enter__(self) -> tuple[socket.socket, socket.socket]: self.rd_s, self.wr_s = socket.socketpair() return self.rd_s, self.wr_s def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: if self.rd_s is not None: self.rd_s.close() if self.wr_s is not None: self.wr_s.close() class EventLoopTestMixin: evl: urwid.EventLoop def test_event_loop(self): evl: urwid.EventLoop = self.evl out = [] rd: socket.socket wr: socket.socket def step1(): out.append("writing") wr.send(b"hi") def step2(): out.append(rd.recv(2).decode("ascii")) raise urwid.ExitMainLoop with ClosingSocketPair() as (rd, wr): _handle = evl.alarm(0, step1) _handle = evl.watch_file(rd.fileno(), step2) evl.run() self.assertEqual(out, ["writing", "hi"]) def test_remove_alarm(self): evl: urwid.EventLoop = self.evl handle = evl.alarm(50, lambda: None) def step1(): self.assertTrue(evl.remove_alarm(handle)) self.assertFalse(evl.remove_alarm(handle)) raise urwid.ExitMainLoop evl.alarm(0, step1) evl.run() def test_remove_watch_file(self): evl: urwid.EventLoop = self.evl with ClosingSocketPair() as (rd, _wr): handle = evl.watch_file(rd.fileno(), lambda: None) def step1(): self.assertTrue(evl.remove_watch_file(handle)) self.assertFalse(evl.remove_watch_file(handle)) raise urwid.ExitMainLoop evl.alarm(0, step1) evl.run() _expected_idle_handle = 1 def test_run(self): evl: urwid.EventLoop = self.evl out = [] wr: socket.socket rd: socket.socket def say_hello(): out.append("hello") def say_waiting(): out.append("waiting") def exit_clean() -> typing.NoReturn: out.append("clean exit") raise urwid.ExitMainLoop def exit_error() -> typing.NoReturn: 1 / 0 with ClosingSocketPair() as (rd, wr): self.assertEqual(wr.send(b"data"), 4) _handle = evl.alarm(0.01, exit_clean) _handle = evl.alarm(0.005, say_hello) idle_handle = evl.enter_idle(say_waiting) if self._expected_idle_handle is not None: self.assertEqual(idle_handle, 1) evl.run() self.assertTrue("waiting" in out, out) self.assertTrue("hello" in out, out) self.assertTrue("clean exit" in out, out) handle = evl.watch_file(rd.fileno(), exit_clean) del out[:] evl.run() self.assertEqual(["clean exit"], out) self.assertTrue(evl.remove_watch_file(handle)) _handle = evl.alarm(0, exit_error) self.assertRaises(ZeroDivisionError, evl.run) _handle = evl.watch_file(rd.fileno(), exit_error) self.assertRaises(ZeroDivisionError, evl.run) def test_run_in_executor(self): out: list[str] = [] with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: def start(): out.append("started") self.evl.run_in_executor(executor, func).add_done_callback(callback) def func() -> bool: out.append("future called") return True def callback(fut: Future) -> None: out.append(f"callback called with future outcome: {fut.result()}") def exit_clean() -> typing.NoReturn: out.append("clean exit") raise urwid.ExitMainLoop _handle = self.evl.alarm(0.1, exit_clean) _handle = self.evl.alarm(0.005, start) self.evl.run() self.assertEqual( [ "started", "future called", "callback called with future outcome: True", "clean exit", ], out, ) class SelectEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.SelectEventLoop() @unittest.skipIf(IS_WINDOWS, "Windows is temporary not supported by AsyncioEventLoop.") class AsyncioEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.AsyncioEventLoop() _expected_idle_handle = None def test_error(self): evl = self.evl evl.alarm(0, lambda: 1 / 0) # Simulate error in event loop self.assertRaises(ZeroDivisionError, evl.run) @unittest.skipIf( sys.implementation.name == "pypy", "Well known dead wait (lock?) on pypy.", ) def test_coroutine_error(self): evl = self.evl async def error_coro(): result = 1 / 0 # Simulate error in coroutine return result asyncio.ensure_future(error_coro(), loop=asyncio.get_event_loop_policy().get_event_loop()) self.assertRaises(ZeroDivisionError, evl.run) @unittest.skipUnless(GLIB_AVAILABLE, "GLIB unavailable") class GLibEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.GLibEventLoop() def test_error(self): evl = self.evl evl.alarm(0, lambda: 1 / 0) # Simulate error in event loop self.assertRaises(ZeroDivisionError, evl.run) @unittest.skipUnless(TORNADO_AVAILABLE, "Tornado not available") @unittest.skipIf( IS_WINDOWS, "Windows is temporary not supported by TornadoEventLoop due to race conditions.", ) class TornadoEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): from tornado.ioloop import IOLoop self.evl = urwid.TornadoEventLoop(IOLoop()) _expected_idle_handle = None @unittest.skipUnless(TWISTED_AVAILABLE, "Twisted is not available") @unittest.skipIf( IS_WINDOWS, "Windows is temporary not supported by TwistedEventLoop due to race conditions.", ) class TwistedEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.TwistedEventLoop() # can't restart twisted reactor, so use shortened tests def test_event_loop(self): pass def test_remove_alarm(self): pass def test_remove_watch_file(self): pass def test_run(self): from twisted.internet import threads evl = self.evl out = [] wr: socket.socket rd: socket.socket def step2(): out.append(rd.recv(2).decode("ascii")) def say_hello(): out.append("hello") def say_waiting(): out.append("waiting") def test_remove_alarm(): handle = evl.alarm(50, lambda: None) self.assertTrue(evl.remove_alarm(handle)) self.assertFalse(evl.remove_alarm(handle)) out.append("remove_alarm ok") def test_remove_watch_file(): with ClosingSocketPair() as (rd_, _wr): handle = evl.watch_file(rd_.fileno(), lambda: None) self.assertTrue(evl.remove_watch_file(handle)) self.assertFalse(evl.remove_watch_file(handle)) out.append("remove_watch_file ok") def test_threaded(): out.append("schedule to thread") threads.deferToThread(func).addCallback(callback) def func() -> bool: out.append("future called") return True def callback(result: bool) -> None: out.append(f"callback called with future outcome: {result}") def exit_clean() -> typing.NoReturn: out.append("clean exit") raise urwid.ExitMainLoop def exit_error() -> typing.NoReturn: 1 / 0 with ClosingSocketPair() as (rd, wr): self.assertEqual(wr.send(b"data"), 4) _handle = evl.watch_file(rd.fileno(), step2) _handle = evl.alarm(0.1, exit_clean) _handle = evl.alarm(0.05, say_hello) _handle = evl.alarm(0.06, test_remove_alarm) _handle = evl.alarm(0.07, test_remove_watch_file) _handle = evl.alarm(0.08, test_threaded) self.assertEqual(evl.enter_idle(say_waiting), 1) evl.run() self.assertIn("da", out) self.assertIn("ta", out) self.assertIn("hello", out) self.assertIn("remove_alarm ok", out) self.assertIn("clean exit", out) self.assertIn("schedule to thread", out) self.assertIn("future called", out) self.assertIn("callback called with future outcome: True", out) def test_error(self): evl = self.evl evl.alarm(0, lambda: 1 / 0) # Simulate error in event loop self.assertRaises(ZeroDivisionError, evl.run) @unittest.skip("not implemented for twisted event loop") def test_run_in_executor(self): """Not implemented for twisted event loop.""" @unittest.skipUnless(TRIO_AVAILABLE, "Trio not available") @unittest.skipIf( IS_WINDOWS, "Windows is temporary not supported by TrioEventLoop due to race conditions.", ) class TrioEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.TrioEventLoop() _expected_idle_handle = None def test_error(self): evl = self.evl evl.alarm(0, lambda: 1 / 0) # Simulate error in event loop self.assertRaises(ZeroDivisionError, evl.run) @unittest.skip("not implemented for trio event loop") def test_run_in_executor(self): """Not implemented for trio event loop.""" @unittest.skipUnless(ZMQ_AVAILABLE, "ZMQ is not available") @unittest.skipIf(IS_WINDOWS, "ZMQEventLoop is not supported under windows") class ZMQEventLoopTest(unittest.TestCase, EventLoopTestMixin): def setUp(self): self.evl = urwid.ZMQEventLoop()
11,238
Python
.py
296
29.219595
98
0.620334
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,207
test_font.py
urwid_urwid/tests/test_font.py
from __future__ import annotations import unittest import urwid from urwid.util import get_encoding class TestFontRender(unittest.TestCase): def setUp(self) -> None: self.old_encoding = get_encoding() urwid.set_encoding("utf-8") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def test_001_basic(self): font = urwid.Thin3x3Font() rendered = b"\n".join(font.render("1").text).decode() expected = " ┐ \n │ \n ┴ " self.assertEqual(expected, rendered) def test_002_non_rect(self): """Test non rect symbol, which causes spaces based padding. Lines as bytes should be not equal length. """ font = urwid.Thin3x3Font() rendered = b"\n".join(font.render("2").text).decode() expected = "┌─┐\n┌─┘\n└─ " self.assertEqual(expected, rendered)
905
Python
.py
23
31.478261
67
0.634977
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,208
test_scrollable.py
urwid_urwid/tests/test_scrollable.py
from __future__ import annotations import string import typing import unittest import urwid if typing.TYPE_CHECKING: from collections.abc import Iterable LGPL_HEADER = """ Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ class TestScrollable(unittest.TestCase): def test_basic(self): """Test basic init and scroll.""" long_content = urwid.Text(LGPL_HEADER) reduced_size = (80, 5) content_size = long_content.pack() widget = urwid.Scrollable(long_content) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) cropped_content_canvas = urwid.CompositeCanvas(long_content.render((reduced_size[0],))) cropped_content_canvas.trim_end(content_size[1] - reduced_size[1]) top_decoded = cropped_content_canvas.decoded_text self.assertEqual( top_decoded, widget.render(reduced_size).decoded_text, ) for key_1, key_2 in (("down", "up"), ("page down", "page up"), ("end", "home")): widget.keypress(reduced_size, key_1) self.assertNotEqual(top_decoded, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, key_2) self.assertEqual(top_decoded, widget.render(reduced_size).decoded_text) def test_negative(self): with self.assertRaises(ValueError): urwid.Scrollable(urwid.SolidFill(" ")) class TestScrollBarScrollable(unittest.TestCase): def test_basic(self): """Test basic init and scroll. Unlike `Scrollable`, `ScrollBar` can be also scrolled with a mouse wheel. """ long_content = urwid.Text(LGPL_HEADER) reduced_size = (40, 5) widget = urwid.ScrollBar(urwid.Scrollable(long_content)) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) top_position_rendered = ( " █", "Copyright (C) <year> <name of author> ", " ", "This library is free software; you can ", "redistribute it and/or ", ) pos_1_down_rendered = ( "Copyright (C) <year> <name of author> ", " █", "This library is free software; you can ", "redistribute it and/or ", "modify it under the terms of the GNU ", ) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "page down") self.assertEqual( ( "redistribute it and/or ", "modify it under the terms of the GNU █", "Lesser General Public ", "License as published by the Free ", "Software Foundation; either ", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "end") self.assertEqual( ( "not, write to the Free Software ", "Foundation, Inc., 51 Franklin Street, ", "Fifth Floor, Boston, MA 02110-1301 ", "USA ", " █", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "home") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 5, 1, 1, False)) self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 4, 1, 1, False)) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) def test_alt_symbols(self): long_content = urwid.Text(LGPL_HEADER) reduced_size = (40, 5) widget = urwid.ScrollBar( urwid.Scrollable(long_content), trough_char=urwid.ScrollBar.Symbols.LITE_SHADE, ) self.assertEqual( ( " █", "Copyright (C) <year> <name of author> ░", " ░", "This library is free software; you can ░", "redistribute it and/or ░", ), widget.render(reduced_size).decoded_text, ) def test_fixed(self): """Test with fixed wrapped widget.""" widget = urwid.ScrollBar( urwid.Scrollable(urwid.BigText("1", urwid.HalfBlockHeavy6x5Font())), trough_char=urwid.ScrollBar.Symbols.LITE_SHADE, thumb_char=urwid.ScrollBar.Symbols.DARK_SHADE, ) reduced_size = (8, 3) self.assertEqual( ( " ▐█▌ ▓", " ▀█▌ ▓", " █▌ ░", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page down") self.assertEqual( ( " █▌ ░", " █▌ ▓", " ███▌ ▓", ), widget.render(reduced_size).decoded_text, ) def test_negative(self): with self.assertRaises(ValueError): urwid.ScrollBar(urwid.Text(" ")) with self.assertRaises(TypeError): urwid.ScrollBar(urwid.SolidFill(" ")) def test_no_scrollbar(self): """If widget fit without scroll - no scrollbar needed""" widget = urwid.ScrollBar( urwid.Scrollable(urwid.BigText("1", urwid.HalfBlockHeavy6x5Font())), trough_char=urwid.ScrollBar.Symbols.LITE_SHADE, thumb_char=urwid.ScrollBar.Symbols.DARK_SHADE, ) reduced_size = (8, 5) self.assertEqual( ( " ▐█▌ ", " ▀█▌ ", " █▌ ", " █▌ ", " ███▌ ", ), widget.render(reduced_size).decoded_text, ) class TestScrollBarListBox(unittest.TestCase): def test_relative_non_selectable(self): widget = urwid.ScrollBar( urwid.ListBox(urwid.SimpleListWalker(urwid.Text(line) for line in LGPL_HEADER.splitlines())) ) reduced_size = (40, 5) top_position_rendered = ( " █", "Copyright (C) <year> <name of author> ", " ", "This library is free software; you can ", "redistribute it and/or ", ) pos_1_down_rendered = ( "Copyright (C) <year> <name of author> ", " █", "This library is free software; you can ", "redistribute it and/or ", "modify it under the terms of the GNU ", ) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "page down") self.assertEqual( ( "modify it under the terms of the GNU ", "Lesser General Public █", "License as published by the Free ", "Software Foundation; either ", "version 2.1 of the License, or (at your ", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "end") self.assertEqual( ( "License along with this library; if ", "not, write to the Free Software ", "Foundation, Inc., 51 Franklin Street, ", "Fifth Floor, Boston, MA 02110-1301 ", "USA █", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "home") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 5, 1, 1, False)) self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 4, 1, 1, False)) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) def test_empty(self): """Empty widget should be correctly rendered.""" widget = urwid.ScrollBar(urwid.ListBox(urwid.SimpleListWalker(()))) reduced_size = (10, 5) self.assertEqual( ( " ", " ", " ", " ", " ", ), widget.render(reduced_size).decoded_text, ) def trivial_AttrMap(widget): return urwid.AttrMap(widget, {}) class TestScrollableAttrMap(unittest.TestCase): def test_basic(self): """Test basic init and scroll.""" long_content = urwid.Text(LGPL_HEADER) reduced_size = (80, 5) content_size = long_content.pack() widget = urwid.Scrollable(trivial_AttrMap(long_content)) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) cropped_content_canvas = urwid.CompositeCanvas(long_content.render((reduced_size[0],))) cropped_content_canvas.trim_end(content_size[1] - reduced_size[1]) top_decoded = cropped_content_canvas.decoded_text self.assertEqual( top_decoded, widget.render(reduced_size).decoded_text, ) for key_1, key_2 in (("down", "up"), ("page down", "page up"), ("end", "home")): widget.keypress(reduced_size, key_1) self.assertNotEqual(top_decoded, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, key_2) self.assertEqual(top_decoded, widget.render(reduced_size).decoded_text) def test_negative(self): with self.assertRaises(ValueError): urwid.Scrollable(trivial_AttrMap(urwid.SolidFill(" "))) class TestScrollBarAttrMap(unittest.TestCase): def test_basic(self): """Test basic init and scroll. Unlike `Scrollable`, `ScrollBar` can be also scrolled with a mouse wheel. """ long_content = urwid.Text(LGPL_HEADER) reduced_size = (40, 5) widget = urwid.ScrollBar(urwid.Scrollable(trivial_AttrMap(long_content))) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) top_position_rendered = ( " █", "Copyright (C) <year> <name of author> ", " ", "This library is free software; you can ", "redistribute it and/or ", ) pos_1_down_rendered = ( "Copyright (C) <year> <name of author> ", " █", "This library is free software; you can ", "redistribute it and/or ", "modify it under the terms of the GNU ", ) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "page down") self.assertEqual( ( "redistribute it and/or ", "modify it under the terms of the GNU █", "Lesser General Public ", "License as published by the Free ", "Software Foundation; either ", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "end") self.assertEqual( ( "not, write to the Free Software ", "Foundation, Inc., 51 Franklin Street, ", "Fifth Floor, Boston, MA 02110-1301 ", "USA ", " █", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "home") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 5, 1, 1, False)) self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 4, 1, 1, False)) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) class TestScrollBarListBoxAttrMap(unittest.TestCase): def test_relative_non_selectable(self): widget = urwid.ScrollBar( trivial_AttrMap( urwid.ListBox(urwid.SimpleListWalker(urwid.Text(line) for line in LGPL_HEADER.splitlines())) ) ) reduced_size = (40, 5) top_position_rendered = ( " █", "Copyright (C) <year> <name of author> ", " ", "This library is free software; you can ", "redistribute it and/or ", ) pos_1_down_rendered = ( "Copyright (C) <year> <name of author> ", " █", "This library is free software; you can ", "redistribute it and/or ", "modify it under the terms of the GNU ", ) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "page down") self.assertEqual( ( "modify it under the terms of the GNU ", "Lesser General Public █", "License as published by the Free ", "Software Foundation; either ", "version 2.1 of the License, or (at your ", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "end") self.assertEqual( ( "License along with this library; if ", "not, write to the Free Software ", "Foundation, Inc., 51 Franklin Street, ", "Fifth Floor, Boston, MA 02110-1301 ", "USA █", ), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "home") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 5, 1, 1, False)) self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 4, 1, 1, False)) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) def test_large_non_selectable(self): top = urwid.Text("\n".join(string.ascii_letters)) bottom = urwid.Text("\n".join(string.digits)) widget = urwid.ScrollBar(urwid.ListBox(urwid.SimpleListWalker((top, bottom)))) reduced_size = (3, 5) top_position_rendered = ("a █", "b ", "c ", "d ", "e ") pos_1_down_rendered = ("b ", "c █", "d ", "e ", "f ") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "page down") self.assertEqual( ("f ", "g █", "h ", "i ", "j "), widget.render(reduced_size).decoded_text, ) widget.keypress(reduced_size, "page up") self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 5, 1, 1, False)) self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) self.assertTrue(widget.mouse_event(reduced_size, "mouse press", 4, 1, 1, False)) self.assertEqual(top_position_rendered, widget.render(reduced_size).decoded_text) def test_large_selectable(self): """Input is handled by LineBox and wrapped widgets.""" top = urwid.Edit("\n".join(string.ascii_letters)) bottom = urwid.IntEdit("\n".join(string.digits)) widget = urwid.ScrollBar(urwid.ListBox(urwid.SimpleListWalker((top, bottom)))) reduced_size = (3, 10) top_position_rendered = ("a █", "b █", "c ", "d ", "e ", "f ", "g ", "h ", "i ", "j ") pos_1_down_rendered = ("0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 █", "9 █") self.assertEqual((top_position_rendered), widget.render(reduced_size).decoded_text) widget.keypress(reduced_size, "down") self.assertEqual(pos_1_down_rendered, widget.render(reduced_size).decoded_text) def test_hinted_len(self): class HintedWalker(urwid.ListWalker): def __init__(self, items: Iterable[str]) -> None: self.items: tuple[str] = tuple(items) self.focus = 0 self.requested_numbers: set[int] = set() def __length_hint__(self) -> int: return len(self.items) def __getitem__(self, item: int) -> urwid.Text: self.requested_numbers.add(item) return urwid.Text(self.items[item]) def set_focus(self, item: int) -> None: self.focus = item def next_position(self, position: int) -> int: if position + 1 < len(self.items): return position + 1 raise IndexError def prev_position(self, position: int) -> int: if position - 1 >= 0: return position - 1 raise IndexError widget = urwid.ScrollBar(urwid.ListBox(HintedWalker((f"Line {idx:02}") for idx in range(1, 51)))) size = (10, 10) widget.original_widget.focus_position = 19 self.assertEqual( ( "Line 16 ", "Line 17 ", "Line 18 ", "Line 19 █", "Line 20 █", "Line 21 ", "Line 22 ", "Line 23 ", "Line 24 ", "Line 25 ", ), widget.render(size).decoded_text, ) self.assertNotIn( 30, widget.original_widget.body.requested_numbers, "Requested index out of range [0, last shown]. This means not relative scroll bar built.", )
22,145
Python
.py
454
37.204846
108
0.549689
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,209
test_frame.py
urwid_urwid/tests/test_frame.py
from __future__ import annotations import unittest import urwid class FrameTest(unittest.TestCase): def ftbtest(self, desc: str, focus_part, header_rows, footer_rows, size, focus, top, bottom): class FakeWidget: def __init__(self, rows, want_focus): self.ret_rows = rows self.want_focus = want_focus def rows(self, size, focus=False): assert self.want_focus == focus return self.ret_rows with self.subTest(desc): header = footer = None if header_rows: header = FakeWidget(header_rows, focus and focus_part == "header") if footer_rows: footer = FakeWidget(footer_rows, focus and focus_part == "footer") f = urwid.Frame(urwid.SolidFill(), header, footer, focus_part) rval = f.frame_top_bottom(size, focus) exp = (top, bottom), (header_rows, footer_rows) self.assertEqual(exp, rval) def test(self): self.ftbtest("simple", "body", 0, 0, (9, 10), True, 0, 0) self.ftbtest("simple h", "body", 3, 0, (9, 10), True, 3, 0) self.ftbtest("simple f", "body", 0, 3, (9, 10), True, 0, 3) self.ftbtest("simple hf", "body", 3, 3, (9, 10), True, 3, 3) self.ftbtest("almost full hf", "body", 4, 5, (9, 10), True, 4, 5) self.ftbtest("full hf", "body", 5, 5, (9, 10), True, 4, 5) self.ftbtest("x full h+1f", "body", 6, 5, (9, 10), False, 4, 5) self.ftbtest("full h+1f", "body", 6, 5, (9, 10), True, 4, 5) self.ftbtest("full hf+1", "body", 5, 6, (9, 10), True, 3, 6) self.ftbtest("F full h+1f", "footer", 6, 5, (9, 10), True, 5, 5) self.ftbtest("F full hf+1", "footer", 5, 6, (9, 10), True, 4, 6) self.ftbtest("F full hf+5", "footer", 5, 11, (9, 10), True, 0, 10) self.ftbtest("full hf+5", "body", 5, 11, (9, 10), True, 0, 9) self.ftbtest("H full hf+1", "header", 5, 6, (9, 10), True, 5, 5) self.ftbtest("H full h+1f", "header", 6, 5, (9, 10), True, 6, 4) self.ftbtest("H full h+5f", "header", 11, 5, (9, 10), True, 10, 0) def test_common(self): s1 = urwid.SolidFill("1") f = urwid.Frame(s1) self.assertEqual(f.focus, s1) self.assertEqual(f.focus_position, "body") self.assertRaises(IndexError, lambda: setattr(f, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(f, "focus_position", "header")) t1 = urwid.Text("one") t2 = urwid.Text("two") t3 = urwid.Text("three") f = urwid.Frame(s1, t1, t2, "header") self.assertEqual(f.focus, t1) self.assertEqual(f.focus_position, "header") f.focus_position = "footer" self.assertEqual(f.focus, t2) self.assertEqual(f.focus_position, "footer") self.assertRaises(IndexError, lambda: setattr(f, "focus_position", -1)) self.assertRaises(IndexError, lambda: setattr(f, "focus_position", 2)) del f.contents["footer"] self.assertEqual(f.footer, None) self.assertEqual(f.focus_position, "body") f.contents.update(footer=(t3, None), header=(t2, None)) self.assertEqual(f.header, t2) self.assertEqual(f.footer, t3) def set1(): f.contents["body"] = t1 self.assertRaises(urwid.FrameError, set1) def set2(): f.contents["body"] = (t1, "given") self.assertRaises(urwid.FrameError, set2) def test_focus(self): header = urwid.Text("header") body = urwid.ListBox((urwid.Text("first"), urwid.Text("second"))) footer = urwid.Text("footer") with self.subTest("default"): widget = urwid.Frame(body, header, footer) self.assertEqual(body, widget.focus) self.assertEqual("body", widget.focus_part) with self.subTest("body"): widget = urwid.Frame(body, header, footer, focus_part=body) self.assertEqual(body, widget.focus) self.assertEqual("body", widget.focus_part) with self.subTest("header"): widget = urwid.Frame(body, header, footer, focus_part=header) self.assertEqual(header, widget.focus) self.assertEqual("header", widget.focus_part) with self.subTest("footer"): widget = urwid.Frame(body, header, footer, focus_part=footer) self.assertEqual(footer, widget.focus) self.assertEqual("footer", widget.focus_part)
4,559
Python
.py
89
40.955056
97
0.579681
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,210
test_filler.py
urwid_urwid/tests/test_filler.py
from __future__ import annotations import unittest import urwid class FillerTest(unittest.TestCase): def ftest( self, desc: str, valign, height, maxrow: int, top: int, bottom: int, min_height: int | None = None, ) -> None: with self.subTest(desc): f = urwid.Filler(None, valign, height, min_height) t, b = f.filler_values((20, maxrow), False) self.assertEqual( (t, b), (top, bottom), f"{desc} expected {top, bottom} but got {t, b}", ) def fetest(self, desc: str, valign, height) -> None: with self.subTest(desc): self.assertRaises(urwid.FillerError, urwid.Filler, None, valign, height) def test_create(self): self.fetest("invalid pad", 6, 5) self.fetest("invalid pad type", ("bad", 2), 5) self.fetest("invalid width", "middle", "42") self.fetest("invalid width type", "middle", ("gouranga", 4)) self.fetest("invalid combination", ("relative", 20), ("fixed bottom", 4)) self.fetest("invalid combination 2", ("relative", 20), ("fixed top", 4)) def test_values(self): self.ftest("top align 5 7", "top", 5, 7, 0, 2) self.ftest("top align 7 7", "top", 7, 7, 0, 0) self.ftest("top align 9 7", "top", 9, 7, 0, 0) self.ftest("bottom align 5 7", "bottom", 5, 7, 2, 0) self.ftest("middle align 5 7", "middle", 5, 7, 1, 1) self.ftest("fixed top", ("fixed top", 3), 5, 10, 3, 2) self.ftest("fixed top reduce", ("fixed top", 3), 8, 10, 2, 0) self.ftest("fixed top shrink", ("fixed top", 3), 18, 10, 0, 0) self.ftest( "fixed top, bottom", ("fixed top", 3), ("fixed bottom", 4), 17, 3, 4, ) self.ftest( "fixed top, bottom, min_width", ("fixed top", 3), ("fixed bottom", 4), 10, 3, 2, 5, ) self.ftest( "fixed top, bottom, min_width 2", ("fixed top", 3), ("fixed bottom", 4), 10, 2, 0, 8, ) self.ftest("fixed bottom", ("fixed bottom", 3), 5, 10, 2, 3) self.ftest("fixed bottom reduce", ("fixed bottom", 3), 8, 10, 0, 2) self.ftest("fixed bottom shrink", ("fixed bottom", 3), 18, 10, 0, 0) self.ftest( "fixed bottom, top", ("fixed bottom", 3), ("fixed top", 4), 17, 4, 3, ) self.ftest( "fixed bottom, top, min_height", ("fixed bottom", 3), ("fixed top", 4), 10, 2, 3, 5, ) self.ftest( "fixed bottom, top, min_height 2", ("fixed bottom", 3), ("fixed top", 4), 10, 0, 2, 8, ) self.ftest("relative 30", ("relative", 30), 5, 10, 1, 4) self.ftest("relative 50", ("relative", 50), 5, 10, 2, 3) self.ftest("relative 130 edge", ("relative", 130), 5, 10, 5, 0) self.ftest("relative -10 edge", ("relative", -10), 4, 10, 0, 6) self.ftest("middle relative 70", "middle", ("relative", 70), 10, 1, 2) self.ftest( "middle relative 70 grow 8", "middle", ("relative", 70), 10, 1, 1, 8, ) def test_repr(self): self.assertEqual( "<Filler box/flow widget <Text fixed/flow widget 'hai'>>", repr(urwid.Filler(urwid.Text("hai"))), ) def test_sizing(self): with self.subTest("Flow supported for PACK height (flow widget)"): widget = urwid.Filler(urwid.Text("Some text")) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) cols, rows = 10, 1 self.assertEqual((cols, rows), widget.pack((cols,))) # top and bottom are 0 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("Flow supported for GIVEN height (box widget)"): widget = urwid.Filler(urwid.SolidFill("#"), height=3) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) cols, rows = 5, 3 self.assertEqual((cols, rows), widget.pack((cols,))) # top and bottom are 0 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("Flow is not supported for RELATIVE scenarios"): widget = urwid.Filler(urwid.SolidFill(""), height=(urwid.RELATIVE, 10)) cols = 10 with self.assertRaises(urwid.widget.WidgetError) as ctx: widget.pack((cols,)) self.assertEqual( f"Cannot pack (maxcol,) size, this is not a flow widget: {widget!r}", str(ctx.exception), ) with self.assertRaises(urwid.widget.WidgetError) as ctx: widget.render((cols,)) self.assertEqual( f"Cannot pack (maxcol,) size, this is not a flow widget: {widget!r}", str(ctx.exception), ) def test_render_focused_not_fit(self): """Test that a focused widget will be shown and top trimmed if not enough height.""" widget = urwid.Filler( urwid.Pile( ( urwid.Text("First"), urwid.Text("Second"), urwid.Text("Third"), urwid.Button("Selectable"), urwid.Text("Last"), ), ) ) canvas = widget.render((14, 3), focus=True) self.assertEqual( [ b"Second ", b"Third ", b"< Selectable >", ], canvas.text, )
6,687
Python
.py
177
26.033898
92
0.49476
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,211
test_str_util.py
urwid_urwid/tests/test_str_util.py
from __future__ import annotations import unittest from urwid.display.escape import str_util class DecodeOneTest(unittest.TestCase): def gwt(self, ch, exp_ord, exp_pos): ch = ch.encode("iso8859-1") o, pos = str_util.decode_one(ch, 0) assert o == exp_ord, f" got:{o!r} expected:{exp_ord!r}" assert pos == exp_pos, f" got:{pos!r} expected:{exp_pos!r}" def test1byte(self): self.gwt("ab", ord("a"), 1) self.gwt("\xc0a", ord("?"), 1) # error def test2byte(self): self.gwt("\xc2", ord("?"), 1) # error self.gwt("\xc0\x80", ord("?"), 1) # error self.gwt("\xc2\x80", 0x80, 2) self.gwt("\xdf\xbf", 0x7FF, 2) def test3byte(self): self.gwt("\xe0", ord("?"), 1) # error self.gwt("\xe0\xa0", ord("?"), 1) # error self.gwt("\xe0\x90\x80", ord("?"), 1) # error self.gwt("\xe0\xa0\x80", 0x800, 3) self.gwt("\xef\xbf\xbf", 0xFFFF, 3) def test4byte(self): self.gwt("\xf0", ord("?"), 1) # error self.gwt("\xf0\x90", ord("?"), 1) # error self.gwt("\xf0\x90\x80", ord("?"), 1) # error self.gwt("\xf0\x80\x80\x80", ord("?"), 1) # error self.gwt("\xf0\x90\x80\x80", 0x10000, 4) self.gwt("\xf3\xbf\xbf\xbf", 0xFFFFF, 4)
1,303
Python
.py
30
35.9
67
0.53913
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,212
test_canvas.py
urwid_urwid/tests/test_canvas.py
from __future__ import annotations import unittest import urwid from urwid import canvas from urwid.util import get_encoding class CanvasCacheTest(unittest.TestCase): def setUp(self): # purge the cache urwid.CanvasCache._widgets.clear() def cct(self, widget, size, focus, expected): with self.subTest(widget=widget, size=size, focus=focus, expected=expected): got = urwid.CanvasCache.fetch(widget, urwid.Widget, size, focus) self.assertEqual(expected, got, f"got: {got} expected: {expected}") def test1(self): a = urwid.Text("") b = urwid.Text("") blah = urwid.TextCanvas() blah.finalize(a, (10, 1), False) blah2 = urwid.TextCanvas() blah2.finalize(a, (15, 1), False) bloo = urwid.TextCanvas() bloo.finalize(b, (20, 2), True) urwid.CanvasCache.store(urwid.Widget, blah) urwid.CanvasCache.store(urwid.Widget, blah2) urwid.CanvasCache.store(urwid.Widget, bloo) self.cct(a, (10, 1), False, blah) self.cct(a, (15, 1), False, blah2) self.cct(a, (15, 1), True, None) self.cct(a, (10, 2), False, None) self.cct(b, (20, 2), True, bloo) self.cct(b, (21, 2), True, None) urwid.CanvasCache.invalidate(a) self.cct(a, (10, 1), False, None) self.cct(a, (15, 1), False, None) self.cct(b, (20, 2), True, bloo) class CanvasTest(unittest.TestCase): def test_basic_info(self): """Test str and repr methods for debugging purposes.""" string = "Hello World!" rendered = urwid.Text(string).render(()) self.assertEqual(string, str(rendered)) self.assertEqual( f"<TextCanvas finalized=True cols={len(string)} rows=1 at 0x{id(rendered):X}>", repr(rendered), ) def test_composite_basic_info(self): """Composite canvas contain info about canvas inside. Use canvas caching feature for test. """ string = "Hello World!" widget = urwid.Text(string) rendered_widget = widget.render(()) disabled = urwid.WidgetDisable(widget) rendered = disabled.render(()) self.assertEqual( f"<CompositeCanvas " f"finalized=True cols={rendered_widget.cols()} rows={rendered_widget.rows()} " f"children=({rendered_widget!r}) at 0x{id(rendered):X}>", repr(rendered), ) def ct(self, text, attr, exp_content): with self.subTest(text=text, attr=attr, exp_content=exp_content): c = urwid.TextCanvas([t.encode("iso8859-1") for t in text], attr) content = list(c.content()) self.assertEqual(content, exp_content, f"got: {content!r} expected: {exp_content!r}") def ct2(self, text, attr, left, top, cols, rows, def_attr, exp_content): c = urwid.TextCanvas([t.encode("iso8859-1") for t in text], attr) content = list(c.content(left, top, cols, rows, def_attr)) self.assertEqual(content, exp_content, f"got: {content!r} expected: {exp_content!r}") def test1(self): self.ct(["Hello world"], None, [[(None, None, b"Hello world")]]) self.ct(["Hello world"], [[("a", 5)]], [[("a", None, b"Hello"), (None, None, b" world")]]) self.ct(["Hi", "There"], None, [[(None, None, b"Hi ")], [(None, None, b"There")]]) def test2(self): self.ct2( ["Hello"], None, 0, 0, 5, 1, None, [[(None, None, b"Hello")]], ) self.ct2( ["Hello"], None, 1, 0, 4, 1, None, [[(None, None, b"ello")]], ) self.ct2( ["Hello"], None, 0, 0, 4, 1, None, [[(None, None, b"Hell")]], ) self.ct2( ["Hi", "There"], None, 1, 0, 3, 2, None, [[(None, None, b"i ")], [(None, None, b"her")]], ) self.ct2( ["Hi", "There"], None, 0, 0, 5, 1, None, [[(None, None, b"Hi ")]], ) self.ct2( ["Hi", "There"], None, 0, 1, 5, 1, None, [[(None, None, b"There")]], ) class ShardBodyTest(unittest.TestCase): def sbt(self, shards, shard_tail, expected): result = canvas.shard_body(shards, shard_tail, False) assert result == expected, f"got: {result!r} expected: {expected!r}" def sbttail(self, num_rows, sbody, expected): result = canvas.shard_body_tail(num_rows, sbody) assert result == expected, f"got: {result!r} expected: {expected!r}" def sbtrow(self, sbody, expected): result = list(canvas.shard_body_row(sbody)) assert result == expected, f"got: {result!r} expected: {expected!r}" def test1(self): cviews = [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 5, None, "bar")] self.sbt( cviews, [], [(0, None, (0, 0, 10, 5, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar"))], ) self.sbt( cviews, [(0, 3, None, (0, 0, 5, 8, None, "baz"))], [ (3, None, (0, 0, 5, 8, None, "baz")), (0, None, (0, 0, 10, 5, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar")), ], ) self.sbt( cviews, [(10, 3, None, (0, 0, 5, 8, None, "baz"))], [ (0, None, (0, 0, 10, 5, None, "foo")), (3, None, (0, 0, 5, 8, None, "baz")), (0, None, (0, 0, 5, 5, None, "bar")), ], ) self.sbt( cviews, [(15, 3, None, (0, 0, 5, 8, None, "baz"))], [ (0, None, (0, 0, 10, 5, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar")), (3, None, (0, 0, 5, 8, None, "baz")), ], ) def test2(self): sbody = [ (0, None, (0, 0, 10, 5, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar")), (3, None, (0, 0, 5, 8, None, "baz")), ] self.sbttail(5, sbody, []) self.sbttail( 3, sbody, [ (0, 3, None, (0, 0, 10, 5, None, "foo")), (0, 3, None, (0, 0, 5, 5, None, "bar")), (0, 6, None, (0, 0, 5, 8, None, "baz")), ], ) sbody = [ (0, None, (0, 0, 10, 3, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar")), (3, None, (0, 0, 5, 9, None, "baz")), ] self.sbttail( 3, sbody, [(10, 3, None, (0, 0, 5, 5, None, "bar")), (0, 6, None, (0, 0, 5, 9, None, "baz"))], ) def test3(self): self.sbtrow( [ (0, None, (0, 0, 10, 5, None, "foo")), (0, None, (0, 0, 5, 5, None, "bar")), (3, None, (0, 0, 5, 8, None, "baz")), ], [20], ) self.sbtrow( [ (0, iter("foo"), (0, 0, 10, 5, None, "foo")), (0, iter("bar"), (0, 0, 5, 5, None, "bar")), (3, iter("zzz"), (0, 0, 5, 8, None, "baz")), ], ["f", "b", "z"], ) class ShardsTrimTest(unittest.TestCase): def sttop(self, shards, top, expected): result = canvas.shards_trim_top(shards, top) assert result == expected, f"got: {result!r} expected: {expected!r}" def strows(self, shards, rows, expected): result = canvas.shards_trim_rows(shards, rows) assert result == expected, f"got: {result!r} expected: {expected!r}" def stsides(self, shards, left, cols, expected): result = canvas.shards_trim_sides(shards, left, cols) assert result == expected, f"got: {result!r} expected: {expected!r}" def test1(self): shards = [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 5, None, "bar")])] self.sttop(shards, 2, [(3, [(0, 2, 10, 3, None, "foo"), (0, 2, 5, 3, None, "bar")])]) self.strows(shards, 2, [(2, [(0, 0, 10, 2, None, "foo"), (0, 0, 5, 2, None, "bar")])]) shards = [(5, [(0, 0, 10, 5, None, "foo")]), (3, [(0, 0, 10, 3, None, "bar")])] self.sttop(shards, 2, [(3, [(0, 2, 10, 3, None, "foo")]), (3, [(0, 0, 10, 3, None, "bar")])]) self.sttop(shards, 5, [(3, [(0, 0, 10, 3, None, "bar")])]) self.sttop(shards, 7, [(1, [(0, 2, 10, 1, None, "bar")])]) self.strows(shards, 7, [(5, [(0, 0, 10, 5, None, "foo")]), (2, [(0, 0, 10, 2, None, "bar")])]) self.strows(shards, 5, [(5, [(0, 0, 10, 5, None, "foo")])]) self.strows(shards, 4, [(4, [(0, 0, 10, 4, None, "foo")])]) shards = [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz")]), (3, [(0, 0, 10, 3, None, "bar")])] self.sttop( shards, 2, [ (3, [(0, 2, 10, 3, None, "foo"), (0, 2, 5, 6, None, "baz")]), (3, [(0, 0, 10, 3, None, "bar")]), ], ) self.sttop(shards, 5, [(3, [(0, 0, 10, 3, None, "bar"), (0, 5, 5, 3, None, "baz")])]) self.sttop(shards, 7, [(1, [(0, 2, 10, 1, None, "bar"), (0, 7, 5, 1, None, "baz")])]) self.strows( shards, 7, [ (5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 7, None, "baz")]), (2, [(0, 0, 10, 2, None, "bar")]), ], ) self.strows(shards, 5, [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 5, None, "baz")])]) self.strows(shards, 4, [(4, [(0, 0, 10, 4, None, "foo"), (0, 0, 5, 4, None, "baz")])]) def test2(self): shards = [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 5, None, "bar")])] self.stsides(shards, 0, 15, [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 5, None, "bar")])]) self.stsides(shards, 6, 9, [(5, [(6, 0, 4, 5, None, "foo"), (0, 0, 5, 5, None, "bar")])]) self.stsides(shards, 6, 6, [(5, [(6, 0, 4, 5, None, "foo"), (0, 0, 2, 5, None, "bar")])]) self.stsides(shards, 0, 10, [(5, [(0, 0, 10, 5, None, "foo")])]) self.stsides(shards, 10, 5, [(5, [(0, 0, 5, 5, None, "bar")])]) self.stsides(shards, 1, 7, [(5, [(1, 0, 7, 5, None, "foo")])]) shards = [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz")]), (3, [(0, 0, 10, 3, None, "bar")])] self.stsides( shards, 0, 15, [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz")]), (3, [(0, 0, 10, 3, None, "bar")])], ) self.stsides( shards, 2, 13, [(5, [(2, 0, 8, 5, None, "foo"), (0, 0, 5, 8, None, "baz")]), (3, [(2, 0, 8, 3, None, "bar")])], ) self.stsides( shards, 2, 10, [(5, [(2, 0, 8, 5, None, "foo"), (0, 0, 2, 8, None, "baz")]), (3, [(2, 0, 8, 3, None, "bar")])], ) self.stsides( shards, 2, 8, [(5, [(2, 0, 8, 5, None, "foo")]), (3, [(2, 0, 8, 3, None, "bar")])], ) self.stsides( shards, 2, 6, [(5, [(2, 0, 6, 5, None, "foo")]), (3, [(2, 0, 6, 3, None, "bar")])], ) self.stsides(shards, 10, 5, [(8, [(0, 0, 5, 8, None, "baz")])]) self.stsides(shards, 11, 3, [(8, [(1, 0, 3, 8, None, "baz")])]) class ShardsJoinTest(unittest.TestCase): def sjt(self, shard_lists, expected): result = canvas.shards_join(shard_lists) assert result == expected, f"got: {result!r} expected: {expected!r}" def test(self): shards1 = [(5, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz")]), (3, [(0, 0, 10, 3, None, "bar")])] shards2 = [(3, [(0, 0, 10, 3, None, "aaa")]), (5, [(0, 0, 10, 5, None, "bbb")])] shards3 = [ (3, [(0, 0, 10, 3, None, "111")]), (2, [(0, 0, 10, 3, None, "222")]), (3, [(0, 0, 10, 3, None, "333")]), ] self.sjt([shards1], shards1) self.sjt( [shards1, shards2], [ (3, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz"), (0, 0, 10, 3, None, "aaa")]), (2, [(0, 0, 10, 5, None, "bbb")]), (3, [(0, 0, 10, 3, None, "bar")]), ], ) self.sjt( [shards1, shards3], [ (3, [(0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz"), (0, 0, 10, 3, None, "111")]), (2, [(0, 0, 10, 3, None, "222")]), (3, [(0, 0, 10, 3, None, "bar"), (0, 0, 10, 3, None, "333")]), ], ) self.sjt( [shards1, shards2, shards3], [ ( 3, [ (0, 0, 10, 5, None, "foo"), (0, 0, 5, 8, None, "baz"), (0, 0, 10, 3, None, "aaa"), (0, 0, 10, 3, None, "111"), ], ), (2, [(0, 0, 10, 5, None, "bbb"), (0, 0, 10, 3, None, "222")]), (3, [(0, 0, 10, 3, None, "bar"), (0, 0, 10, 3, None, "333")]), ], ) class CanvasJoinTest(unittest.TestCase): def cjtest(self, desc, l, expected): l = [(c, None, False, n) for c, n in l] result = list(urwid.CanvasJoin(l).content()) assert result == expected, f"{desc} expected {expected!r}, got {result!r}" def test(self): C = urwid.TextCanvas hello = C([b"hello"]) there = C([b"there"], [[("a", 5)]]) a = C([b"a"]) hi = C([b"hi"]) how = C([b"how"], [[("a", 1)]]) dy = C([b"dy"]) how_you = C([b"how", b"you"]) self.cjtest("one", [(hello, 5)], [[(None, None, b"hello")]]) self.cjtest( "two", [(hello, 5), (there, 5)], [[(None, None, b"hello"), ("a", None, b"there")]], ) self.cjtest( "two space", [(hello, 7), (there, 5)], [[(None, None, b"hello"), (None, None, b" "), ("a", None, b"there")]], ) self.cjtest( "three space", [(hi, 4), (how, 3), (dy, 2)], [ [(None, None, b"hi"), (None, None, b" "), ("a", None, b"h"), (None, None, b"ow"), (None, None, b"dy")], ], ) self.cjtest( "four space", [(a, 2), (hi, 3), (dy, 3), (a, 1)], [ [ (None, None, b"a"), (None, None, b" "), (None, None, b"hi"), (None, None, b" "), (None, None, b"dy"), (None, None, b" "), (None, None, b"a"), ] ], ) self.cjtest( "pile 2", [(how_you, 4), (hi, 2)], [ [(None, None, b"how"), (None, None, b" "), (None, None, b"hi")], [(None, None, b"you"), (None, None, b" "), (None, None, b" ")], ], ) self.cjtest( "pile 2r", [(hi, 4), (how_you, 3)], [ [(None, None, b"hi"), (None, None, b" "), (None, None, b"how")], [(None, None, b" "), (None, None, b"you")], ], ) class CanvasOverlayTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = get_encoding() def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def cotest(self, desc, bgt, bga, fgt, fga, l, r, et): with self.subTest(desc): bgt = bgt.encode("iso8859-1") fgt = fgt.encode("iso8859-1") bg = urwid.CompositeCanvas(urwid.TextCanvas([bgt], [bga])) fg = urwid.CompositeCanvas(urwid.TextCanvas([fgt], [fga])) bg.overlay(fg, l, 0) result = list(bg.content()) assert result == et, f"{desc} expected {et!r}, got {result!r}" def test1(self): self.cotest( "left", "qxqxqxqx", [], "HI", [], 0, 6, [[(None, None, b"HI"), (None, None, b"qxqxqx")]], ) self.cotest( "right", "qxqxqxqx", [], "HI", [], 6, 0, [[(None, None, b"qxqxqx"), (None, None, b"HI")]], ) self.cotest( "center", "qxqxqxqx", [], "HI", [], 3, 3, [[(None, None, b"qxq"), (None, None, b"HI"), (None, None, b"xqx")]], ) self.cotest( "center2", "qxqxqxqx", [], "HI ", [], 2, 2, [[(None, None, b"qx"), (None, None, b"HI "), (None, None, b"qx")]], ) self.cotest( "full", "rz", [], "HI", [], 0, 0, [[(None, None, b"HI")]], ) def test2(self): self.cotest( "same", "asdfghjkl", [("a", 9)], "HI", [("a", 2)], 4, 3, [[("a", None, b"asdf"), ("a", None, b"HI"), ("a", None, b"jkl")]], ) self.cotest( "diff", "asdfghjkl", [("a", 9)], "HI", [("b", 2)], 4, 3, [[("a", None, b"asdf"), ("b", None, b"HI"), ("a", None, b"jkl")]], ) self.cotest( "None end", "asdfghjkl", [("a", 9)], "HI ", [("a", 2)], 2, 3, [[("a", None, b"as"), ("a", None, b"HI"), (None, None, b" "), ("a", None, b"jkl")]], ) self.cotest( "float end", "asdfghjkl", [("a", 3)], "HI", [("a", 2)], 4, 3, [[("a", None, b"asd"), (None, None, b"f"), ("a", None, b"HI"), (None, None, b"jkl")]], ) self.cotest( "cover 2", "asdfghjkl", [("a", 5), ("c", 4)], "HI", [("b", 2)], 4, 3, [[("a", None, b"asdf"), ("b", None, b"HI"), ("c", None, b"jkl")]], ) self.cotest( "cover 2-2", "asdfghjkl", [("a", 4), ("d", 1), ("e", 1), ("c", 3)], "HI", [("b", 2)], 4, 3, [[("a", None, b"asdf"), ("b", None, b"HI"), ("c", None, b"jkl")]], ) def test3(self): urwid.set_encoding("euc-jp") self.cotest( "db0", "\xA1\xA1\xA1\xA1\xA1\xA1", [], "HI", [], 2, 2, [[(None, None, b"\xA1\xA1"), (None, None, b"HI"), (None, None, b"\xA1\xA1")]], ) self.cotest( "db1", "\xA1\xA1\xA1\xA1\xA1\xA1", [], "OHI", [], 1, 2, [[(None, None, b" "), (None, None, b"OHI"), (None, None, b"\xA1\xA1")]], ) self.cotest( "db2", "\xA1\xA1\xA1\xA1\xA1\xA1", [], "OHI", [], 2, 1, [[(None, None, b"\xA1\xA1"), (None, None, b"OHI"), (None, None, b" ")]], ) self.cotest( "db3", "\xA1\xA1\xA1\xA1\xA1\xA1", [], "OHIO", [], 1, 1, [[(None, None, b" "), (None, None, b"OHIO"), (None, None, b" ")]], ) class CanvasPadTrimTest(unittest.TestCase): def cptest(self, desc, ct, ca, l, r, et): with self.subTest(desc): ct = ct.encode("iso8859-1") c = urwid.CompositeCanvas(urwid.TextCanvas([ct], [ca])) c.pad_trim_left_right(l, r) result = list(c.content()) self.assertEqual(result, et, f"{desc} expected {et!r}, got {result!r}") def test1(self): self.cptest("none", "asdf", [], 0, 0, [[(None, None, b"asdf")]]) self.cptest("left pad", "asdf", [], 2, 0, [[(None, None, b" "), (None, None, b"asdf")]]) self.cptest("right pad", "asdf", [], 0, 2, [[(None, None, b"asdf"), (None, None, b" ")]]) def test2(self): self.cptest("left trim", "asdf", [], -2, 0, [[(None, None, b"df")]]) self.cptest("right trim", "asdf", [], 0, -2, [[(None, None, b"as")]])
21,234
Python
.py
595
24.231933
120
0.399009
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,213
test_widget.py
urwid_urwid/tests/test_widget.py
from __future__ import annotations import unittest import urwid from urwid.util import set_temporary_encoding class TextTest(unittest.TestCase): def setUp(self): self.t = urwid.Text("I walk the\ncity in the night") def test1_wrap(self): expected = [t.encode("iso8859-1") for t in ("I walk the", "city in ", "the night ")] got = self.t.render((10,))._text assert got == expected, f"got: {got!r} expected: {expected!r}" def test2_left(self): self.t.set_align_mode("left") expected = [t.encode("iso8859-1") for t in ("I walk the ", "city in the night ")] got = self.t.render((18,))._text assert got == expected, f"got: {got!r} expected: {expected!r}" def test3_right(self): self.t.set_align_mode("right") expected = [t.encode("iso8859-1") for t in (" I walk the", " city in the night")] got = self.t.render((18,))._text assert got == expected, f"got: {got!r} expected: {expected!r}" def test4_center(self): self.t.set_align_mode("center") expected = [t.encode("iso8859-1") for t in (" I walk the ", " city in the night")] got = self.t.render((18,))._text assert got == expected, f"got: {got!r} expected: {expected!r}" def test5_encode_error(self): with set_temporary_encoding("ascii"): expected = [b"? "] got = urwid.Text("û").render((3,))._text assert got == expected, f"got: {got!r} expected: {expected!r}" class EditTest(unittest.TestCase): def setUp(self): self.t1 = urwid.Edit(b"", "blah blah") self.t2 = urwid.Edit(b"stuff:", "blah blah") self.t3 = urwid.Edit(b"junk:\n", "blah blah\n\nbloo", 1) self.t4 = urwid.Edit("better:") def ktest(self, e, key, expected, pos, desc): got = e.keypress((12,), key) assert got == expected, f"{desc}. got: {got!r} expected:{expected!r}" assert e.edit_pos == pos, f"{desc}. pos: {e.edit_pos!r} expected pos: {pos!r}" def test1_left(self): self.t1.set_edit_pos(0) self.ktest(self.t1, "left", "left", 0, "left at left edge") self.ktest(self.t2, "left", None, 8, "left within text") self.t3.set_edit_pos(10) self.ktest(self.t3, "left", None, 9, "left after newline") def test2_right(self): self.ktest(self.t1, "right", "right", 9, "right at right edge") self.t2.set_edit_pos(8) self.ktest(self.t2, "right", None, 9, "right at right edge-1") self.t3.set_edit_pos(0) self.t3.keypress((12,), "right") assert self.t3.get_pref_col((12,)) == 1 def test3_up(self): self.ktest(self.t1, "up", "up", 9, "up at top") self.t2.set_edit_pos(2) self.t2.keypress((12,), "left") assert self.t2.get_pref_col((12,)) == 7 self.ktest(self.t2, "up", "up", 1, "up at top again") assert self.t2.get_pref_col((12,)) == 7 self.t3.set_edit_pos(10) self.ktest(self.t3, "up", None, 0, "up at top+1") def test4_down(self): self.ktest(self.t1, "down", "down", 9, "down single line") self.t3.set_edit_pos(5) self.ktest(self.t3, "down", None, 10, "down line 1 to 2") self.ktest(self.t3, "down", None, 15, "down line 2 to 3") self.ktest(self.t3, "down", "down", 15, "down at bottom") def test_utf8_input(self): with set_temporary_encoding("utf-8"): self.t1.set_edit_text("") self.t1.keypress((12,), "û") self.assertEqual(self.t1.edit_text, "û".encode()) self.t4.keypress((12,), "û") self.assertEqual(self.t4.edit_text, "û") class EditRenderTest(unittest.TestCase): def rtest(self, w, expected_text, expected_cursor): expected_text = [t.encode("iso8859-1") for t in expected_text] get_cursor = w.get_cursor_coords((4,)) assert get_cursor == expected_cursor, f"got: {get_cursor!r} expected: {expected_cursor!r}" r = w.render((4,), focus=1) text = [t for a, cs, t in [ln[0] for ln in r.content()]] assert text == expected_text, f"got: {text!r} expected: {expected_text!r}" assert r.cursor == expected_cursor, f"got: {r.cursor!r} expected: {expected_cursor!r}" def test1_SpaceWrap(self): w = urwid.Edit("", "blah blah") w.set_edit_pos(0) self.rtest(w, ["blah", "blah"], (0, 0)) w.set_edit_pos(4) self.rtest(w, ["lah ", "blah"], (3, 0)) w.set_edit_pos(5) self.rtest(w, ["blah", "blah"], (0, 1)) w.set_edit_pos(9) self.rtest(w, ["blah", "lah "], (3, 1)) def test2_ClipWrap(self): w = urwid.Edit("", "blah\nblargh", 1) w.set_wrap_mode("clip") w.set_edit_pos(0) self.rtest(w, ["blah", "blar"], (0, 0)) w.set_edit_pos(10) self.rtest(w, ["blah", "argh"], (3, 1)) w.set_align_mode("right") w.set_edit_pos(6) self.rtest(w, ["blah", "larg"], (0, 1)) def test3_AnyWrap(self): w = urwid.Edit("", "blah blah") w.set_wrap_mode("any") self.rtest(w, ["blah", " bla", "h "], (1, 2)) def test4_CursorNudge(self): w = urwid.Edit("", "hi", align="right") w.keypress((4,), "end") self.rtest(w, [" hi "], (3, 0)) w.keypress((4,), "left") self.rtest(w, [" hi"], (3, 0))
5,435
Python
.py
115
38.756522
98
0.5605
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,214
test_graphics.py
urwid_urwid/tests/test_graphics.py
from __future__ import annotations import unittest import urwid from urwid.util import get_encoding from urwid.widget import bar_graph class BarGraphTest(unittest.TestCase): def bgtest(self, desc, data, top, widths, maxrow, exp): rval = bar_graph.calculate_bargraph_display(data, top, widths, maxrow) assert rval == exp, f"{desc} expected {exp!r}, got {rval!r}" def test1(self): self.bgtest("simplest", [[0]], 5, [1], 1, [(1, [(0, 1)])]), self.bgtest( "simpler", [[0], [0]], 5, [1, 2], 5, [(5, [(0, 3)])], ) self.bgtest( "simple", [[5]], 5, [1], 1, [(1, [(1, 1)])], ) self.bgtest( "2col-1", [[2], [0]], 5, [1, 2], 5, [(3, [(0, 3)]), (2, [(1, 1), (0, 2)])], ) self.bgtest( "2col-2", [[0], [2]], 5, [1, 2], 5, [(3, [(0, 3)]), (2, [(0, 1), (1, 2)])], ) self.bgtest( "2col-3", [[2], [3]], 5, [1, 2], 5, [(2, [(0, 3)]), (1, [(0, 1), (1, 2)]), (2, [(1, 3)])], ) self.bgtest( "3col-1", [[5], [3], [0]], 5, [2, 1, 1], 5, [(2, [(1, 2), (0, 2)]), (3, [(1, 3), (0, 1)])], ) self.bgtest( "3col-2", [[4], [4], [4]], 5, [2, 1, 1], 5, [(1, [(0, 4)]), (4, [(1, 4)])], ) self.bgtest( "3col-3", [[1], [2], [3]], 5, [2, 1, 1], 5, [(2, [(0, 4)]), (1, [(0, 3), (1, 1)]), (1, [(0, 2), (1, 2)]), (1, [(1, 4)])], ) self.bgtest( "3col-4", [[4], [2], [4]], 5, [1, 2, 1], 5, [(1, [(0, 4)]), (2, [(1, 1), (0, 2), (1, 1)]), (2, [(1, 4)])], ) def test2(self): self.bgtest( "simple1a", [[2, 0], [2, 1]], 2, [1, 1], 2, [(1, [(1, 2)]), (1, [(1, 1), (2, 1)])], ) self.bgtest( "simple1b", [[2, 1], [2, 0]], 2, [1, 1], 2, [(1, [(1, 2)]), (1, [(2, 1), (1, 1)])], ) self.bgtest("cross1a", [[2, 2], [1, 2]], 2, [1, 1], 2, [(2, [(2, 2)])]) self.bgtest("cross1b", [[1, 2], [2, 2]], 2, [1, 1], 2, [(2, [(2, 2)])]) self.bgtest( "mix1a", [[3, 2, 1], [2, 2, 2], [1, 2, 3]], 3, [1, 1, 1], 3, [(1, [(1, 1), (0, 1), (3, 1)]), (1, [(2, 1), (3, 2)]), (1, [(3, 3)])], ) self.bgtest( "mix1b", [[1, 2, 3], [2, 2, 2], [3, 2, 1]], 3, [1, 1, 1], 3, [(1, [(3, 1), (0, 1), (1, 1)]), (1, [(3, 2), (2, 1)]), (1, [(3, 3)])], ) class SmoothBarGraphTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = get_encoding() urwid.set_encoding("utf-8") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def sbgtest(self, desc, data, top, exp): g = urwid.BarGraph(["black", "red", "blue"], None, {(1, 0): "red/black", (2, 1): "blue/red"}) g.set_data(data, top) rval = g.calculate_display((5, 3)) assert rval == exp, f"{desc} expected {exp!r}, got {rval!r}" def test1(self): self.sbgtest( "simple", [[3]], 5, [(1, [(0, 5)]), (1, [((1, 0, 6), 5)]), (1, [(1, 5)])], ) self.sbgtest( "boring", [[4, 2]], 6, [(1, [(0, 5)]), (1, [(1, 5)]), (1, [(2, 5)])], ) self.sbgtest( "two", [[4], [2]], 6, [(1, [(0, 5)]), (1, [(1, 3), (0, 2)]), (1, [(1, 5)])], ) self.sbgtest( "twos", [[3], [4]], 6, [(1, [(0, 5)]), (1, [((1, 0, 4), 3), (1, 2)]), (1, [(1, 5)])], ) self.sbgtest( "twof", [[4], [3]], 6, [(1, [(0, 5)]), (1, [(1, 3), ((1, 0, 4), 2)]), (1, [(1, 5)])], )
4,508
Python
.py
160
17.18125
101
0.294674
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,215
test_raw_display.py
urwid_urwid/tests/test_raw_display.py
from __future__ import annotations import unittest import urwid class TestRawDisplay(unittest.TestCase): def test_attrspec_to_escape(self): s = urwid.display.raw.Screen() s.set_terminal_properties(colors=256) a2e = s._attrspec_to_escape self.assertEqual("\x1b[0;33;42m", a2e(s.AttrSpec("brown", "dark green"))) self.assertEqual("\x1b[0;38;5;229;4;48;5;164m", a2e(s.AttrSpec("#fea,underline", "#d0d")))
450
Python
.py
10
39.2
98
0.681193
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,216
test_escapes.py
urwid_urwid/tests/test_escapes.py
#!/usr/bin/python """ Tests covering escape sequences processing """ from __future__ import annotations import unittest from urwid.display import escape class InputEscapeSequenceParserTest(unittest.TestCase): """Tests for parser of input escape sequences""" def test_bare_escape(self): codes = [27] expected = ["esc"] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_meta(self): codes = [27, ord("4"), ord("2")] expected = ["meta 4"] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([ord("2")], rest) def test_shift_arrows(self): codes = [27, ord("["), ord("a")] expected = ["shift up"] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_ctrl_pgup(self): codes = [27, 91, 53, 59, 53, 126] expected = ["ctrl page up"] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_esc_meta_1(self): codes = [27, 27, 49] expected = ["esc", "meta 1"] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_midsequence(self): # '[11~' is F1, '[12~' is F2, etc codes = [27, ord("["), ord("1")] with self.assertRaises(escape.MoreInputRequired): escape.process_keyqueue(codes, more_available=True) actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(["meta ["], actual) self.assertListEqual([ord("1")], rest) def test_mouse_press(self): codes = [27, 91, 77, 32, 41, 48] expected = [("mouse press", 1.0, 8, 15)] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_bug_104(self): """GH #104: click-Esc & Esc-click crashes urwid apps""" codes = [27, 27, 91, 77, 32, 127, 59] expected = ["esc", ("mouse press", 1.0, 94, 26)] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) codes = [27, 27, 91, 77, 35, 120, 59] expected = ["esc", ("mouse release", 0, 87, 26)] actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertListEqual(expected, actual) self.assertListEqual([], rest) def test_functional_keys(self): """Test for functional keys F1-F4, F5-F12.""" def check_key(expected: str, codes: list[int]) -> None: actual, rest = escape.process_keyqueue(codes, more_available=False) self.assertEqual( [expected], actual, f"Codes {codes!r} ({[chr(code) for code in codes]}) was not decoded to {expected!r}", ) # F1-F4 for num in range(1, 5): codes = [27, ord("O"), 79 + num] check_key(f"f{num}", codes) # F5-F8 for num, offset in enumerate((0, 2, 3, 4), start=5): codes = [27, ord("["), ord("1"), 53 + offset, ord("~")] check_key(f"f{num}", codes) # F9-F12 for num, offset in enumerate((0, 1, 3, 4), start=9): codes = [27, ord("["), ord("2"), 48 + offset, ord("~")] check_key(f"f{num}", codes) def test_functional_keys_mods_f1_f4(self): """Test for modifiers handling for functional keys F1-F4.""" prefixes = ("O", "[1;") masks = "12345678" letters = "PQRS" for prefix in prefixes: encoded_prefix = tuple(ord(element) for element in prefix) for num, letter in enumerate(letters, start=1): for mask in masks: codes = [27, *encoded_prefix, ord(mask), ord(letter)] actual, rest = escape.process_keyqueue(codes, more_available=False) expected = escape.escape_modifier(mask) + f"f{num}" self.assertEqual( [expected], actual, f"Codes {codes!r} ({[chr(code) for code in codes]}) was not decoded to {expected!r}", ) def test_functional_keys_mods_simple_f1_20(self): """Test for modifiers handling for functional keys F1-F20.""" masks = "12345678" numbers = (11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 31, 32, 33, 34) for num, number in enumerate(numbers, start=1): encoded_number = tuple(ord(element) for element in str(number)) for mask in masks: codes = [27, ord("["), *encoded_number, ord(";"), ord(mask), ord("~")] actual, rest = escape.process_keyqueue(codes, more_available=False) expected = escape.escape_modifier(mask) + f"f{num}" self.assertEqual( [expected], actual, f"Codes {codes!r} ({[chr(code) for code in codes]}) was not decoded to {expected!r}", ) def test_sgrmouse(self): prefix = (27, ord("["), ord("<")) x = 4 y = 8 coord = (ord(f"{x + 1}"), ord(";"), ord(f"{y + 1}")) action = ord("M") modifiers = ((0, ""), (8, "meta "), (16, "ctrl "), (24, "meta ctrl ")) for key, code in enumerate((0b0, 0b1, 0b10, 0b1000000, 0b1000001), start=1): for mod_code, mod in modifiers: key_code = tuple(ord(element) for element in str(code | mod_code)) codes = [*prefix, *key_code, ord(";"), *coord, action] actual, rest = escape.process_keyqueue(codes, more_available=False) expected = [(mod + "mouse press", key, x, y)] self.assertEqual( expected, actual, f"Codes {codes!r} ({[chr(code) for code in codes]}) was not decoded to {expected!r}", )
6,494
Python
.py
134
37.328358
109
0.559994
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,217
test_grid_flow.py
urwid_urwid/tests/test_grid_flow.py
from __future__ import annotations import unittest from unittest import mock import urwid class GridFlowTest(unittest.TestCase): def test_fixed(self): grid = urwid.GridFlow( (urwid.Button(tag, align=urwid.CENTER) for tag in ("OK", "Cancel", "Help")), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, ) self.assertEqual(frozenset((urwid.FIXED, urwid.FLOW)), grid.sizing()) cols, rows = 32, 1 self.assertEqual((cols, rows), grid.pack(())) canvas = grid.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual([b"< OK > < Cancel > < Help >"], canvas.text) def test_default_focus(self): with self.subTest("Simple"): grid = urwid.GridFlow( (urwid.Button("btn"), urwid.Button("btn")), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, ) self.assertTrue(grid.selectable()) self.assertEqual(0, grid.focus_position) with self.subTest("Simple not selectable"): grid = urwid.GridFlow( (urwid.Text("btn"), urwid.Text("btn")), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, ) self.assertFalse(grid.selectable()) self.assertEqual(0, grid.focus_position) with self.subTest("Explicit index"): grid = urwid.GridFlow( (urwid.Button("btn"), urwid.Button("btn")), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, focus=1, ) self.assertEqual(1, grid.focus_position) with self.subTest("Explicit widget"): btn2 = urwid.Button("btn 2") grid = urwid.GridFlow( (urwid.Button("btn"), btn2), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, focus=btn2, ) self.assertEqual(1, grid.focus_position) with self.subTest("Selectable not first"): grid = urwid.GridFlow( (urwid.Text("text"), urwid.Button("btn")), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, ) self.assertEqual(1, grid.focus_position) def test_cell_width(self): gf = urwid.GridFlow([], 5, 0, 0, "left") self.assertEqual(gf.cell_width, 5) def test_not_fit(self): """Test scenario with maxcol < cell_width (special case, warning will be produced).""" widget = urwid.GridFlow( [urwid.Button("first"), urwid.Button("second")], 5, 0, 0, "left", ) size = (3,) with self.assertWarns(urwid.widget.GridFlowWarning): canvas = widget.render(size) self.assertEqual( ("< f", " i", " r", " s", " t", "< s", " e", " c", " o", " n", " d"), canvas.decoded_text, ) def test_multiline(self): """Test widgets fit only with multiple lines""" widget = urwid.GridFlow( [urwid.Button("first"), urwid.Button("second")], 10, 0, 0, "left", ) size = (10,) canvas = widget.render(size) self.assertEqual( ("< first >", "< second >"), canvas.decoded_text, ) def test_multiline_2(self): """Test widgets fit only with multiple lines""" widget = urwid.GridFlow( [urwid.Button("first"), urwid.Button("second"), urwid.Button("third"), urwid.Button("forth")], 10, 0, 0, "left", ) size = (20,) canvas = widget.render(size) self.assertEqual( ( "< first >< second >", "< third >< forth >", ), canvas.decoded_text, ) def test_basics(self): repr(urwid.GridFlow([], 5, 0, 0, "left")) # should not fail def test_v_sep(self): gf = urwid.GridFlow([urwid.Text("test")], 10, 3, 1, "center") self.assertEqual(gf.rows((40,), False), 1) def test_keypress_v_sep_0(self): """ Ensure proper keypress handling when v_sep is 0. https://github.com/urwid/urwid/issues/387 """ call_back = mock.Mock() button = urwid.Button("test", call_back) gf = urwid.GridFlow([button], 10, 3, v_sep=0, align="center") self.assertEqual(gf.keypress((20,), "enter"), None) call_back.assert_called_with(button) def test_length(self): grid = urwid.GridFlow((urwid.Text(c) for c in "ABC"), 1, 0, 0, "left") self.assertEqual(3, len(grid)) self.assertEqual(3, len(grid.contents)) def test_common(self): gf = urwid.GridFlow([], 5, 1, 0, "left") with self.subTest("Focus"): self.assertEqual(gf.focus, None) self.assertEqual(gf.contents, []) self.assertRaises(IndexError, lambda: getattr(gf, "focus_position")) self.assertRaises(IndexError, lambda: setattr(gf, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(gf, "focus_position", 0)) with self.subTest("Contents options"): self.assertEqual(gf.options(), ("given", 5)) self.assertEqual(gf.options(width_amount=9), ("given", 9)) self.assertRaises(urwid.GridFlowError, lambda: gf.options("pack", None)) def test_focus_position(self): t1 = urwid.Text("one") t2 = urwid.Text("two") gf = urwid.GridFlow([t1, t2], 5, 1, 0, "left") self.assertEqual(gf.focus, t1) self.assertEqual(gf.focus_position, 0) self.assertEqual(gf.contents, [(t1, ("given", 5)), (t2, ("given", 5))]) gf.focus_position = 1 self.assertEqual(gf.focus, t2) self.assertEqual(gf.focus_position, 1) gf.contents.insert(0, (t2, ("given", 5))) self.assertEqual(gf.focus_position, 2) self.assertRaises(urwid.GridFlowError, lambda: gf.contents.append(())) self.assertRaises(urwid.GridFlowError, lambda: gf.contents.insert(1, (t1, ("pack", None)))) gf.focus_position = 0 self.assertRaises(IndexError, lambda: setattr(gf, "focus_position", -1)) self.assertRaises(IndexError, lambda: setattr(gf, "focus_position", 3)) def test_deprecated(self): t1 = urwid.Text("one") t2 = urwid.Text("two") gf = urwid.GridFlow([t1, t2], 5, 1, 0, "left") # old methods: gf.set_focus(0) self.assertRaises(IndexError, lambda: gf.set_focus(-1)) self.assertRaises(IndexError, lambda: gf.set_focus(3)) gf.set_focus(t1) self.assertEqual(gf.focus_position, 0) self.assertRaises(ValueError, lambda: gf.set_focus("nonexistant")) def test_empty(self): """Test behaviour of empty widget.""" grid = urwid.GridFlow( (), cell_width=10, h_sep=1, v_sep=1, align=urwid.CENTER, ) self.assertEqual(frozenset((urwid.FLOW,)), grid.sizing(), "Empty grid can not be handled as FIXED") rows = 1 with self.subTest("Flow"): maxcol = 1 self.assertEqual((maxcol, rows), grid.pack((maxcol,))) rendered = grid.render((maxcol,)) self.assertEqual(maxcol, rendered.cols()) self.assertEqual(rows, rendered.rows()) with self.subTest("Fixed"): maxcol = 0 self.assertEqual((maxcol, rows), grid.pack(())) with self.assertRaises(ValueError): grid.render(())
8,040
Python
.py
204
28.264706
107
0.535211
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,218
test_floatedit.py
urwid_urwid/tests/test_floatedit.py
import unittest from decimal import Decimal from itertools import product from urwid.numedit import FloatEdit class FloatEditNoPreservePrecicionTest(unittest.TestCase): def test(self): for v in ("1.01", "2.5", "300", "4.100", "5.001"): f = FloatEdit(preserveSignificance=False) f.set_edit_text(v) print(f.value(), Decimal(v)) self.assertEqual(Decimal(v), f.value()) def test_int(self): corner_value = "1" # just int f = FloatEdit(preserveSignificance=False) f.set_edit_text(corner_value) self.assertEqual(Decimal(corner_value), f.value()) def test_no_post_dot(self): corner_value = "1." # forced float 1.0 with trimmed end f = FloatEdit(preserveSignificance=False) f.set_edit_text(corner_value) self.assertEqual(Decimal(corner_value), f.value()) class FloatEditPreservePrecicionTest(unittest.TestCase): def test(self): for v, sig, sep in product(("1.010", "2.500", "300.000", "4.100", "5.001"), (0, 1, 2, 3), (".", ",")): precision_template = "0." + "0" * sig expected = Decimal(v).quantize(Decimal(precision_template)) f = FloatEdit(preserveSignificance=True, default=precision_template, decimalSeparator=sep) f.set_edit_text(v.replace(".", sep)) self.assertEqual(expected, f.value(), f"{f.value()} != {expected} (significance={sig!r})")
1,453
Python
.py
29
41.793103
110
0.635593
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,219
test_util.py
urwid_urwid/tests/test_util.py
from __future__ import annotations import locale import unittest import urwid from urwid import str_util, util class CalcWidthTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = util.get_encoding() def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def wtest(self, desc, s, exp): s = s.encode("iso8859-1") result = str_util.calc_width(s, 0, len(s)) assert result == exp, f"{desc} got:{result!r} expected:{exp!r}" def test1(self): util.set_encoding("utf-8") self.wtest("narrow", "hello", 5) self.wtest("wide char", "\xe6\x9b\xbf", 2) self.wtest("invalid", "\xe6", 1) self.wtest("zero width", "\xcc\x80", 0) self.wtest("mixed", "hello\xe6\x9b\xbf\xe6\x9b\xbf", 9) def test2(self): util.set_encoding("euc-jp") self.wtest("narrow", "hello", 5) self.wtest("wide", "\xA1\xA1\xA1\xA1", 4) self.wtest("invalid", "\xA1", 1) class ConvertDecSpecialTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = util.get_encoding() def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def ctest(self, desc, s, exp, expcs): exp = exp.encode("iso8859-1") util.set_encoding("ascii") c = urwid.Text(s).render((5,)) result = c._text[0] assert result == exp, f"{desc} got:{result!r} expected:{exp!r}" resultcs = c._cs[0] assert resultcs == expcs, f"{desc} got:{resultcs!r} expected:{expcs!r}" def test1(self): self.ctest("no conversion", "hello", "hello", [(None, 5)]) self.ctest("only special", "£££££", "}}}}}", [("0", 5)]) self.ctest("mix left", "££abc", "}}abc", [("0", 2), (None, 3)]) self.ctest("mix right", "abc££", "abc}}", [(None, 3), ("0", 2)]) self.ctest("mix inner", "a££bc", "a}}bc", [(None, 1), ("0", 2), (None, 2)]) self.ctest("mix well", "£a£b£", "}a}b}", [("0", 1), (None, 1), ("0", 1), (None, 1), ("0", 1)]) class WithinDoubleByteTest(unittest.TestCase): def setUp(self): self.old_encoding = util.get_encoding() urwid.set_encoding("euc-jp") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def wtest(self, s, ls, pos, expected, desc): result = str_util.within_double_byte(s.encode("iso8859-1"), ls, pos) assert result == expected, f"{desc} got:{result!r} expected: {expected!r}" def test1(self): self.wtest("mnopqr", 0, 2, 0, "simple no high bytes") self.wtest("mn\xA1\xA1qr", 0, 2, 1, "simple 1st half") self.wtest("mn\xA1\xA1qr", 0, 3, 2, "simple 2nd half") self.wtest("m\xA1\xA1\xA1\xA1r", 0, 3, 1, "subsequent 1st half") self.wtest("m\xA1\xA1\xA1\xA1r", 0, 4, 2, "subsequent 2nd half") self.wtest("mn\xA1@qr", 0, 3, 2, "simple 2nd half lo") self.wtest("mn\xA1\xA1@r", 0, 4, 0, "subsequent not 2nd half lo") self.wtest("m\xA1\xA1\xA1@r", 0, 4, 2, "subsequent 2nd half lo") def test2(self): self.wtest("\xA1\xA1qr", 0, 0, 1, "begin 1st half") self.wtest("\xA1\xA1qr", 0, 1, 2, "begin 2nd half") self.wtest("\xA1@qr", 0, 1, 2, "begin 2nd half lo") self.wtest("\xA1\xA1\xA1\xA1r", 0, 2, 1, "begin subs. 1st half") self.wtest("\xA1\xA1\xA1\xA1r", 0, 3, 2, "begin subs. 2nd half") self.wtest("\xA1\xA1\xA1@r", 0, 3, 2, "begin subs. 2nd half lo") self.wtest("\xA1@\xA1@r", 0, 3, 2, "begin subs. 2nd half lo lo") self.wtest("@\xA1\xA1@r", 0, 3, 0, "begin subs. not 2nd half lo") def test3(self): self.wtest("abc \xA1\xA1qr", 4, 4, 1, "newline 1st half") self.wtest("abc \xA1\xA1qr", 4, 5, 2, "newline 2nd half") self.wtest("abc \xA1@qr", 4, 5, 2, "newline 2nd half lo") self.wtest("abc \xA1\xA1\xA1\xA1r", 4, 6, 1, "newl subs. 1st half") self.wtest("abc \xA1\xA1\xA1\xA1r", 4, 7, 2, "newl subs. 2nd half") self.wtest("abc \xA1\xA1\xA1@r", 4, 7, 2, "newl subs. 2nd half lo") self.wtest("abc \xA1@\xA1@r", 4, 7, 2, "newl subs. 2nd half lo lo") self.wtest("abc @\xA1\xA1@r", 4, 7, 0, "newl subs. not 2nd half lo") class CalcTextPosTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = util.get_encoding() def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def ctptest(self, text, tests): text = text.encode("iso8859-1") for s, e, p, expected in tests: got = str_util.calc_text_pos(text, s, e, p) assert got == expected, f"{s, e, p!r} got:{got!r} expected:{expected!r}" def test1(self): text = "hello world out there" tests = [ (0, 21, 0, (0, 0)), (0, 21, 5, (5, 5)), (0, 21, 21, (21, 21)), (0, 21, 50, (21, 21)), (2, 15, 50, (15, 13)), (6, 21, 0, (6, 0)), (6, 21, 3, (9, 3)), ] self.ctptest(text, tests) def test2_wide(self): util.set_encoding("euc-jp") text = "hel\xA1\xA1 world out there" tests = [ (0, 21, 0, (0, 0)), (0, 21, 4, (3, 3)), (2, 21, 2, (3, 1)), (2, 21, 3, (5, 3)), (6, 21, 0, (6, 0)), ] self.ctptest(text, tests) def test3_utf8(self): util.set_encoding("utf-8") text = "hel\xc4\x83 world \xe2\x81\x81 there" tests = [ (0, 21, 0, (0, 0)), (0, 21, 4, (5, 4)), (2, 21, 1, (3, 1)), (2, 21, 2, (5, 2)), (2, 21, 3, (6, 3)), (6, 21, 7, (15, 7)), (6, 21, 8, (16, 8)), ] self.ctptest(text, tests) def test4_utf8(self): util.set_encoding("utf-8") text = "he\xcc\x80llo \xe6\x9b\xbf world" tests = [ (0, 15, 0, (0, 0)), (0, 15, 1, (1, 1)), (0, 15, 2, (4, 2)), (0, 15, 4, (6, 4)), (8, 15, 0, (8, 0)), (8, 15, 1, (8, 0)), (8, 15, 2, (11, 2)), (8, 15, 5, (14, 5)), ] self.ctptest(text, tests) class TagMarkupTest(unittest.TestCase): mytests = [ ("simple one", "simple one", []), (("blue", "john"), "john", [("blue", 4)]), (["a ", "litt", "le list"], "a little list", []), ( ["mix", [" it", ("high", [" up", ("ital", " a")])], " little"], "mix it up a little", [(None, 6), ("high", 3), ("ital", 2)], ), (["££", "x££"], "££x££", []), ([b"\xc2\x80", b"\xc2\x80"], b"\xc2\x80\xc2\x80", []), ] def test(self): for input, text, attr in self.mytests: restext, resattr = urwid.decompose_tagmarkup(input) assert restext == text, f"got: {restext!r} expected: {text!r}" assert resattr == attr, f"got: {resattr!r} expected: {attr!r}" def test_bad_tuple(self): self.assertRaises(urwid.TagMarkupException, lambda: urwid.decompose_tagmarkup((1, 2, 3))) def test_bad_type(self): self.assertRaises(urwid.TagMarkupException, lambda: urwid.decompose_tagmarkup(5)) class RleTest(unittest.TestCase): def test_rle_prepend(self): rle0 = [("A", 10), ("B", 15)] # the rle functions are mutating, so make a few copies of rle0 rle1, rle2 = rle0[:], rle0[:] util.rle_prepend_modify(rle1, ("A", 3)) util.rle_prepend_modify(rle2, ("X", 2)) self.assertListEqual(rle1, [("A", 13), ("B", 15)]) self.assertListEqual(rle2, [("X", 2), ("A", 10), ("B", 15)]) def test_rle_append(self): rle0 = [("A", 10), ("B", 15)] rle3, rle4 = rle0[:], rle0[:] util.rle_append_modify(rle3, ("B", 5)) util.rle_append_modify(rle4, ("K", 1)) self.assertListEqual(rle3, [("A", 10), ("B", 20)]) self.assertListEqual(rle4, [("A", 10), ("B", 15), ("K", 1)]) class PortabilityTest(unittest.TestCase): def test_locale(self): initial = locale.getlocale() locale.setlocale(locale.LC_ALL, (None, None)) util.detect_encoding() self.assertEqual(locale.getlocale(), (None, None)) try: locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8")) except locale.Error as exc: if "unsupported locale setting" not in str(exc): raise print( f"Locale change impossible, probably locale not supported by system (libc ignores this error).\n" f"{exc}" ) return util.detect_encoding() self.assertEqual(locale.getlocale(), ("en_US", "UTF-8")) try: locale.setlocale(locale.LC_ALL, initial) except locale.Error as exc: if "unsupported locale setting" not in str(exc): raise print( f"Locale restore impossible, probably locale not supported by system (libc ignores this error).\n" f"{exc}" ) class TestEmptyMarkup(unittest.TestCase): def test_001_empty(self): text = urwid.Text("") text.set_text(text.get_text()) self.assertEqual("", text.text)
9,312
Python
.py
212
34.622642
114
0.528565
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,220
test_listbox.py
urwid_urwid/tests/test_listbox.py
from __future__ import annotations import unittest import urwid from tests.util import SelectableText class ListBoxCalculateVisibleTest(unittest.TestCase): def cvtest( self, desc: str, body, focus: int, offset_rows: int, inset_fraction, exp_offset_inset: int, exp_cur: tuple[int, int] | None, ) -> None: with self.subTest(desc): lbox = urwid.ListBox(urwid.SimpleListWalker(body)) lbox.body.set_focus(focus) lbox.offset_rows = offset_rows lbox.inset_fraction = inset_fraction middle, top, bottom = lbox.calculate_visible((4, 5), focus=1) offset_inset, focus_widget, focus_pos, _ign, cursor = middle if cursor is not None: x, y = cursor y += offset_inset cursor = x, y self.assertEqual(exp_offset_inset, offset_inset) self.assertEqual(exp_cur, cursor) def test1_simple(self): T = urwid.Text l = [T(""), T(""), T("\n"), T("\n\n"), T("\n"), T(""), T("")] self.cvtest( "simple top position", l, 3, 0, (0, 1), 0, None, ) self.cvtest( "simple middle position", l, 3, 1, (0, 1), 1, None, ) self.cvtest( "simple bottom position", l, 3, 2, (0, 1), 2, None, ) self.cvtest( "straddle top edge", l, 3, 0, (1, 2), -1, None, ) self.cvtest( "straddle bottom edge", l, 3, 4, (0, 1), 4, None, ) self.cvtest( "off bottom edge", l, 3, 5, (0, 1), 4, None, ) self.cvtest( "way off bottom edge", l, 3, 100, (0, 1), 4, None, ) self.cvtest( "gap at top", l, 0, 2, (0, 1), 0, None, ) self.cvtest( "gap at top and off bottom edge", l, 2, 5, (0, 1), 2, None, ) self.cvtest( "gap at bottom", l, 6, 1, (0, 1), 4, None, ) self.cvtest( "gap at bottom and straddling top edge", l, 4, 0, (1, 2), 1, None, ) self.cvtest( "gap at bottom cannot completely fill", [T(""), T(""), T("")], 1, 0, (0, 1), 1, None, ) self.cvtest( "gap at top and bottom", [T(""), T(""), T("")], 1, 2, (0, 1), 1, None, ) def test2_cursor(self): T, E = urwid.Text, urwid.Edit l1 = [T(""), T(""), T("\n"), E("", "\n\nX"), T("\n"), T(""), T("")] l2 = [T(""), T(""), T("\n"), E("", "YY\n\n"), T("\n"), T(""), T("")] l2[3].set_edit_pos(2) self.cvtest( "plain cursor in view", l1, 3, 1, (0, 1), 1, (1, 3), ) self.cvtest( "cursor off top", l2, 3, 0, (1, 3), 0, (2, 0), ) self.cvtest( "cursor further off top", l2, 3, 0, (2, 3), 0, (2, 0), ) self.cvtest( "cursor off bottom", l1, 3, 3, (0, 1), 2, (1, 4), ) self.cvtest( "cursor way off bottom", l1, 3, 100, (0, 1), 2, (1, 4), ) def test_sized(self): lbox = urwid.ListBox(urwid.SimpleListWalker([urwid.Text(str(num)) for num in range(5)])) self.assertEqual(5, len(lbox)) def test_not_sized(self): class TestWalker(urwid.ListWalker): @property def contents(self): return self @staticmethod def next_position(position: int) -> tuple[urwid.Text, int]: return urwid.Text(str(position)), position @staticmethod def prev_position(position: int) -> tuple[urwid.Text, int]: return urwid.Text(str(position)), position lbox = urwid.ListBox(TestWalker()) with self.assertRaises(AttributeError) as exc: len(lbox) self.assertEqual(f"{TestWalker.__name__} is not Sized", str(exc.exception)) class ListBoxChangeFocusTest(unittest.TestCase): def cftest( self, desc: str, body, pos: int, offset_inset: int, coming_from, cursor: tuple[int, int] | None, snap_rows, exp_offset_rows: int, exp_inset_fraction, exp_cur: tuple[int, int] | None, ): with self.subTest(desc): lbox = urwid.ListBox(urwid.SimpleListWalker(body)) lbox.change_focus((4, 5), pos, offset_inset, coming_from, cursor, snap_rows) exp = exp_offset_rows, exp_inset_fraction act = lbox.offset_rows, lbox.inset_fraction cursor = None focus_widget, focus_pos = lbox.body.get_focus() if focus_widget.selectable(): if hasattr(focus_widget, "get_cursor_coords"): cursor = focus_widget.get_cursor_coords((4,)) self.assertEqual(exp, act) self.assertEqual(exp_cur, cursor) def test1unselectable(self): T = urwid.Text l = [T("\n"), T("\n\n"), T("\n\n"), T("\n\n"), T("\n")] self.cftest( "simple unselectable", l, 2, 0, None, None, None, 0, (0, 1), None, ) self.cftest( "unselectable", l, 2, 1, None, None, None, 1, (0, 1), None, ) self.cftest( "unselectable off top", l, 2, -2, None, None, None, 0, (2, 3), None, ) self.cftest( "unselectable off bottom", l, 3, 2, None, None, None, 2, (0, 1), None, ) def test2selectable(self): T, S = urwid.Text, SelectableText l = [T("\n"), T("\n\n"), S("\n\n"), T("\n\n"), T("\n")] self.cftest( "simple selectable", l, 2, 0, None, None, None, 0, (0, 1), None, ) self.cftest( "selectable", l, 2, 1, None, None, None, 1, (0, 1), None, ) self.cftest( "selectable at top", l, 2, 0, "below", None, None, 0, (0, 1), None, ) self.cftest( "selectable at bottom", l, 2, 2, "above", None, None, 2, (0, 1), None, ) self.cftest( "selectable off top snap", l, 2, -1, "below", None, None, 0, (0, 1), None, ) self.cftest( "selectable off bottom snap", l, 2, 3, "above", None, None, 2, (0, 1), None, ) self.cftest( "selectable off top no snap", l, 2, -1, "above", None, None, 0, (1, 3), None, ) self.cftest( "selectable off bottom no snap", l, 2, 3, "below", None, None, 3, (0, 1), None, ) def test3large_selectable(self): T, S = urwid.Text, SelectableText l = [T("\n"), S("\n\n\n\n\n\n"), T("\n")] self.cftest( "large selectable no snap", l, 1, -1, None, None, None, 0, (1, 7), None, ) self.cftest( "large selectable snap up", l, 1, -2, "below", None, None, 0, (0, 1), None, ) self.cftest( "large selectable snap up2", l, 1, -2, "below", None, 2, 0, (0, 1), None, ) self.cftest( "large selectable almost snap up", l, 1, -2, "below", None, 1, 0, (2, 7), None, ) self.cftest( "large selectable snap down", l, 1, 0, "above", None, None, 0, (2, 7), None, ) self.cftest( "large selectable snap down2", l, 1, 0, "above", None, 2, 0, (2, 7), None, ) self.cftest( "large selectable almost snap down", l, 1, 0, "above", None, 1, 0, (0, 1), None, ) m = [T("\n\n\n\n"), S("\n\n\n\n\n"), T("\n\n\n\n")] self.cftest( "large selectable outside view down", m, 1, 4, "above", None, None, 0, (0, 1), None, ) self.cftest( "large selectable outside view up", m, 1, -5, "below", None, None, 0, (1, 6), None, ) def test4cursor(self): T, E = urwid.Text, urwid.Edit # ... def test5set_focus_valign(self): T, E = urwid.Text, urwid.Edit lbox = urwid.ListBox(urwid.SimpleFocusListWalker([T(""), T("")])) lbox.set_focus_valign("middle") # TODO: actually test the result class ListBoxRenderTest(unittest.TestCase): def ltest( self, desc: str, body, focus: int, offset_inset_rows: int, exp_text: list[bytes], exp_cur: tuple[int, int] | None, ) -> None: with self.subTest(desc): exp_text = [t.encode("iso8859-1") for t in exp_text] lbox = urwid.ListBox(urwid.SimpleListWalker(body)) lbox.body.set_focus(focus) lbox.shift_focus((4, 10), offset_inset_rows) canvas = lbox.render((4, 5), focus=1) self.assertEqual(exp_text, canvas.text) self.assertEqual(exp_cur, canvas.cursor) def test1_simple(self): T = urwid.Text self.ltest( "simple one text item render", [T("1\n2")], 0, 0, ["1 ", "2 ", " ", " ", " "], None, ) self.ltest( "simple multi text item render off bottom", [T("1"), T("2"), T("3\n4"), T("5"), T("6")], 2, 2, ["1 ", "2 ", "3 ", "4 ", "5 "], None, ) self.ltest( "simple multi text item render off top", [T("1"), T("2"), T("3\n4"), T("5"), T("6")], 2, 1, ["2 ", "3 ", "4 ", "5 ", "6 "], None, ) def test2_trim(self): T = urwid.Text self.ltest( "trim unfocused bottom", [T("1\n2"), T("3\n4"), T("5\n6")], 1, 2, ["1 ", "2 ", "3 ", "4 ", "5 "], None, ) self.ltest( "trim unfocused top", [T("1\n2"), T("3\n4"), T("5\n6")], 1, 1, ["2 ", "3 ", "4 ", "5 ", "6 "], None, ) self.ltest( "trim none full focus", [T("1\n2\n3\n4\n5")], 0, 0, ["1 ", "2 ", "3 ", "4 ", "5 "], None, ) self.ltest( "trim focus bottom", [T("1\n2\n3\n4\n5\n6")], 0, 0, ["1 ", "2 ", "3 ", "4 ", "5 "], None, ) self.ltest( "trim focus top", [T("1\n2\n3\n4\n5\n6")], 0, -1, ["2 ", "3 ", "4 ", "5 ", "6 "], None, ) self.ltest( "trim focus top and bottom", [T("1\n2\n3\n4\n5\n6\n7")], 0, -1, ["2 ", "3 ", "4 ", "5 ", "6 "], None, ) def test3_shift(self): T, E = urwid.Text, urwid.Edit self.ltest( "shift up one fit", [T("1\n2"), T("3"), T("4"), T("5"), T("6")], 4, 5, ["2 ", "3 ", "4 ", "5 ", "6 "], None, ) e = E("", "ab\nc", 1) e.set_edit_pos(2) self.ltest( "shift down one cursor over edge", [e, T("3"), T("4"), T("5\n6")], 0, -1, ["ab ", "c ", "3 ", "4 ", "5 "], (2, 0), ) self.ltest( "shift up one cursor over edge", [T("1\n2"), T("3"), T("4"), E("", "d\ne")], 3, 4, ["2 ", "3 ", "4 ", "d ", "e "], (1, 4), ) self.ltest( "shift none cursor top focus over edge", [E("", "ab\n"), T("3"), T("4"), T("5\n6")], 0, -1, [" ", "3 ", "4 ", "5 ", "6 "], (0, 0), ) e = E("", "abc\nd") e.set_edit_pos(3) self.ltest( "shift none cursor bottom focus over edge", [T("1\n2"), T("3"), T("4"), e], 3, 4, ["1 ", "2 ", "3 ", "4 ", "abc "], (3, 4), ) def test4_really_large_contents(self): T, E = urwid.Text, urwid.Edit self.ltest( "really large edit", [T("hello" * 100)], 0, 0, ["hell", "ohel", "lohe", "lloh", "ello"], None, ) self.ltest( "really large edit", [E("", "hello" * 100)], 0, 0, ["hell", "ohel", "lohe", "lloh", "llo "], (3, 4), ) class ListBoxKeypressTest(unittest.TestCase): def ktest( self, desc: str, key, body, focus: int, offset_inset: int, exp_focus: int, exp_offset_inset: int, exp_cur: tuple[int, int] | None, lbox=None, ) -> tuple[str | None, urwid.ListBox]: if lbox is None: lbox = urwid.ListBox(urwid.SimpleListWalker(body)) lbox.body.set_focus(focus) lbox.shift_focus((4, 10), offset_inset) ret_key = lbox.keypress((4, 5), key) middle, top, bottom = lbox.calculate_visible((4, 5), focus=1) offset_inset, focus_widget, focus_pos, _ign, cursor = middle if cursor is not None: x, y = cursor y += offset_inset cursor = x, y exp = exp_focus, exp_offset_inset act = focus_pos, offset_inset self.assertEqual(exp, act) self.assertEqual(exp_cur, cursor) return ret_key, lbox def test1_up(self): T, S, E = urwid.Text, SelectableText, urwid.Edit self.ktest( "direct selectable both visible", "up", [S(""), S("")], 1, 1, 0, 0, None, ) self.ktest( "selectable skip one all visible", "up", [S(""), T(""), S("")], 2, 2, 0, 0, None, ) key, lbox = self.ktest( "nothing above no scroll", "up", [S("")], 0, 0, 0, 0, None, ) self.assertEqual("up", key) key, lbox = self.ktest( "unselectable above no scroll", "up", [T(""), T(""), S("")], 2, 2, 2, 2, None, ) self.assertEqual("up", key) self.ktest( "unselectable above scroll 1", "up", [T(""), S(""), T("\n\n\n")], 1, 0, 1, 1, None, ) self.ktest( "selectable above scroll 1", "up", [S(""), S(""), T("\n\n\n")], 1, 0, 0, 0, None, ) self.ktest( "selectable above too far", "up", [S(""), T(""), S(""), T("\n\n\n")], 2, 0, 2, 1, None, ) self.ktest( "selectable above skip 1 scroll 1", "up", [S(""), T(""), S(""), T("\n\n\n")], 2, 1, 0, 0, None, ) self.ktest( "tall selectable above scroll 2", "up", [S(""), S("\n"), S(""), T("\n\n\n")], 2, 0, 1, 0, None, ) self.ktest( "very tall selectable above scroll 5", "up", [S(""), S("\n\n\n\n"), S(""), T("\n\n\n\n")], 2, 0, 1, 0, None, ) self.ktest( "very tall selected scroll within 1", "up", [S(""), S("\n\n\n\n\n")], 1, -1, 1, 0, None, ) self.ktest( "edit above pass cursor", "up", [E("", "abc"), E("", "de")], 1, 1, 0, 0, (2, 0), ) key, lbox = self.ktest( "edit too far above pass cursor A", "up", [E("", "abc"), T("\n\n\n\n"), E("", "de")], 2, 4, 1, 0, None, ) self.ktest( "edit too far above pass cursor B", "up", None, None, None, 0, 0, (2, 0), lbox, ) self.ktest( "within focus cursor made not visible", "up", [T("\n\n\n"), E("hi\n", "ab")], 1, 3, 0, 0, None, ) self.ktest( "within focus cursor made not visible (2)", "up", [T("\n\n\n\n"), E("hi\n", "ab")], 1, 3, 0, -1, None, ) self.ktest( "force focus unselectable", "up", [T("\n\n\n\n"), S("")], 1, 4, 0, 0, None, ) self.ktest( "pathological cursor widget", "up", [T("\n"), E("\n\n\n\n\n", "a")], 1, 4, 0, -1, None, ) self.ktest( "unselectable to unselectable", "up", [T(""), T(""), T(""), T(""), T(""), T(""), T("")], 2, 0, 1, 0, None, ) self.ktest( "unselectable over edge to same", "up", [T(""), T("12\n34"), T(""), T(""), T(""), T("")], 1, -1, 1, 0, None, ) key, lbox = self.ktest( "edit short between pass cursor A", "up", [E("", "abcd"), E("", "a"), E("", "def")], 2, 2, 1, 1, (1, 1), ) self.ktest( "edit short between pass cursor B", "up", None, None, None, 0, 0, (3, 0), lbox, ) e = E("", "\n\n\n\n\n") e.set_edit_pos(1) key, lbox = self.ktest( "edit cursor force scroll", "up", [e], 0, -1, 0, 0, (0, 0), ) self.assertEqual(0, lbox.inset_fraction[0]) def test2_down(self): T, S, E = urwid.Text, SelectableText, urwid.Edit self.ktest( "direct selectable both visible", "down", [S(""), S("")], 0, 0, 1, 1, None, ) self.ktest( "selectable skip one all visible", "down", [S(""), T(""), S("")], 0, 0, 2, 2, None, ) key, lbox = self.ktest( "nothing below no scroll", "down", [S("")], 0, 0, 0, 0, None, ) self.assertEqual("down", key) key, lbox = self.ktest( "unselectable below no scroll", "down", [S(""), T(""), T("")], 0, 0, 0, 0, None, ) self.assertEqual("down", key) self.ktest( "unselectable below scroll 1", "down", [T("\n\n\n"), S(""), T("")], 1, 4, 1, 3, None, ) self.ktest( "selectable below scroll 1", "down", [T("\n\n\n"), S(""), S("")], 1, 4, 2, 4, None, ) self.ktest( "selectable below too far", "down", [T("\n\n\n"), S(""), T(""), S("")], 1, 4, 1, 3, None, ) self.ktest( "selectable below skip 1 scroll 1", "down", [T("\n\n\n"), S(""), T(""), S("")], 1, 3, 3, 4, None, ) self.ktest( "tall selectable below scroll 2", "down", [T("\n\n\n"), S(""), S("\n"), S("")], 1, 4, 2, 3, None, ) self.ktest( "very tall selectable below scroll 5", "down", [T("\n\n\n\n"), S(""), S("\n\n\n\n"), S("")], 1, 4, 2, 0, None, ) self.ktest( "very tall selected scroll within 1", "down", [S("\n\n\n\n\n"), S("")], 0, 0, 0, -1, None, ) self.ktest( "edit below pass cursor", "down", [E("", "de"), E("", "abc")], 0, 0, 1, 1, (2, 1), ) key, lbox = self.ktest( "edit too far below pass cursor A", "down", [E("", "de"), T("\n\n\n\n"), E("", "abc")], 0, 0, 1, 0, None, ) self.ktest( "edit too far below pass cursor B", "down", None, None, None, 2, 4, (2, 4), lbox, ) odd_e = E("", "hi\nab") odd_e.set_edit_pos(2) # disble cursor movement in odd_e object odd_e.move_cursor_to_coords = lambda s, c, xy: 0 self.ktest( "within focus cursor made not visible", "down", [odd_e, T("\n\n\n\n")], 0, 0, 1, 1, None, ) self.ktest( "within focus cursor made not visible (2)", "down", [ odd_e, T("\n\n\n\n"), ], 0, 0, 1, 1, None, ) self.ktest( "force focus unselectable", "down", [S(""), T("\n\n\n\n")], 0, 0, 1, 0, None, ) odd_e.set_edit_text("hi\n\n\n\n\n") self.ktest( "pathological cursor widget", "down", [odd_e, T("\n")], 0, 0, 1, 4, None, ) self.ktest( "unselectable to unselectable", "down", [T(""), T(""), T(""), T(""), T(""), T(""), T("")], 4, 4, 5, 4, None, ) self.ktest( "unselectable over edge to same", "down", [T(""), T(""), T(""), T(""), T("12\n34"), T("")], 4, 4, 4, 3, None, ) key, lbox = self.ktest( "edit short between pass cursor A", "down", [E("", "abc"), E("", "a"), E("", "defg")], 0, 0, 1, 1, (1, 1), ) self.ktest( "edit short between pass cursor B", "down", None, None, None, 2, 2, (3, 2), lbox, ) e = E("", "\n\n\n\n\n") e.set_edit_pos(4) key, lbox = self.ktest( "edit cursor force scroll", "down", [e], 0, 0, 0, -1, (0, 4), ) self.assertEqual(1, lbox.inset_fraction[0]) def test3_page_up(self): T, S, E = urwid.Text, SelectableText, urwid.Edit self.ktest( "unselectable aligned to aligned", "page up", [T(""), T("\n"), T("\n\n"), T(""), T("\n"), T("\n\n")], 3, 0, 1, 0, None, ) self.ktest( "unselectable unaligned to aligned", "page up", [T(""), T("\n"), T("\n"), T("\n"), T("\n"), T("\n\n")], 3, -1, 1, 0, None, ) self.ktest( "selectable to unselectable", "page up", [T(""), T("\n"), T("\n"), T("\n"), S("\n"), T("\n\n")], 4, 1, 1, -1, None, ) self.ktest( "selectable to cut off selectable", "page up", [S("\n\n"), T("\n"), T("\n"), S("\n"), T("\n\n")], 3, 1, 0, -1, None, ) self.ktest( "seletable to selectable", "page up", [T("\n\n"), S("\n"), T("\n"), S("\n"), T("\n\n")], 3, 1, 1, 1, None, ) self.ktest( "within very long selectable", "page up", [S(""), S("\n\n\n\n\n\n\n\n"), T("\n")], 1, -6, 1, -1, None, ) e = E("", "\n\nab\n\n\n\n\ncd\n") e.set_edit_pos(11) self.ktest( "within very long cursor widget", "page up", [S(""), e, T("\n")], 1, -6, 1, -2, (2, 0), ) self.ktest( "pathological cursor widget", "page up", [T(""), E("\n\n\n\n\n\n\n\n", "ab"), T("")], 1, -5, 0, 0, None, ) e = E("", "\nab\n\n\n\n\ncd\n") e.set_edit_pos(10) self.ktest( "very long cursor widget snap", "page up", [T(""), e, T("\n")], 1, -5, 1, 0, (2, 1), ) self.ktest( "slight scroll selectable", "page up", [T("\n"), S("\n"), T(""), S(""), T("\n\n\n"), S("")], 5, 4, 3, 0, None, ) self.ktest( "scroll into snap region", "page up", [T("\n"), S("\n"), T(""), T(""), T("\n\n\n"), S("")], 5, 4, 1, 0, None, ) self.ktest( "mid scroll short", "page up", [T("\n"), T(""), T(""), S(""), T(""), T("\n"), S(""), T("\n")], 6, 2, 3, 1, None, ) self.ktest( "mid scroll long", "page up", [T("\n"), S(""), T(""), S(""), T(""), T("\n"), S(""), T("\n")], 6, 2, 1, 0, None, ) self.ktest( "mid scroll perfect", "page up", [T("\n"), S(""), S(""), S(""), T(""), T("\n"), S(""), T("\n")], 6, 2, 2, 0, None, ) self.ktest( "cursor move up fail short", "page up", [T("\n"), T("\n"), E("", "\nab"), T(""), T("")], 2, 1, 2, 4, (0, 4), ) self.ktest( "cursor force fail short", "page up", [T("\n"), T("\n"), E("\n", "ab"), T(""), T("")], 2, 1, 0, 0, None, ) odd_e = E("", "hi\nab") odd_e.set_edit_pos(2) # disble cursor movement in odd_e object odd_e.move_cursor_to_coords = lambda s, c, xy: 0 self.ktest( "cursor force fail long", "page up", [odd_e, T("\n"), T("\n"), T("\n"), S(""), T("\n")], 4, 2, 1, -1, None, ) self.ktest( "prefer not cut off", "page up", [S("\n"), T("\n"), S(""), T("\n\n"), S(""), T("\n")], 4, 2, 2, 1, None, ) self.ktest( "allow cut off", "page up", [S("\n"), T("\n"), T(""), T("\n\n"), S(""), T("\n")], 4, 2, 0, -1, None, ) self.ktest( "at top fail", "page up", [T("\n\n"), T("\n"), T("\n\n\n")], 0, 0, 0, 0, None, ) self.ktest( "all visible fail", "page up", [T("a"), T("\n")], 0, 0, 0, 0, None, ) self.ktest( "current ok fail", "page up", [T("\n\n"), S("hi")], 1, 3, 1, 3, None, ) self.ktest( "all visible choose top selectable", "page up", [T(""), S("a"), S("b"), S("c")], 3, 3, 1, 1, None, ) self.ktest( "bring in edge choose top", "page up", [S("b"), T("-"), S("-"), T("c"), S("d"), T("-")], 4, 3, 0, 0, None, ) self.ktest( "bring in edge choose top selectable", "page up", [T("b"), S("-"), S("-"), T("c"), S("d"), T("-")], 4, 3, 1, 1, None, ) def test4_page_down(self): T, S, E = urwid.Text, SelectableText, urwid.Edit self.ktest( "unselectable aligned to aligned", "page down", [T("\n\n"), T("\n"), T(""), T("\n\n"), T("\n"), T("")], 2, 4, 4, 3, None, ) self.ktest( "unselectable unaligned to aligned", "page down", [T("\n\n"), T("\n"), T("\n"), T("\n"), T("\n"), T("")], 2, 4, 4, 3, None, ) self.ktest( "selectable to unselectable", "page down", [T("\n\n"), S("\n"), T("\n"), T("\n"), T("\n"), T("")], 1, 2, 4, 4, None, ) self.ktest( "selectable to cut off selectable", "page down", [T("\n\n"), S("\n"), T("\n"), T("\n"), S("\n\n")], 1, 2, 4, 3, None, ) self.ktest( "seletable to selectable", "page down", [T("\n\n"), S("\n"), T("\n"), S("\n"), T("\n\n")], 1, 1, 3, 2, None, ) self.ktest( "within very long selectable", "page down", [T("\n"), S("\n\n\n\n\n\n\n\n"), S("")], 1, 2, 1, -3, None, ) e = E("", "\nab\n\n\n\n\ncd\n\n") e.set_edit_pos(2) self.ktest( "within very long cursor widget", "page down", [T("\n"), e, S("")], 1, 2, 1, -2, (1, 4), ) odd_e = E("", "ab\n\n\n\n\n\n\n\n\n") odd_e.set_edit_pos(1) # disble cursor movement in odd_e object odd_e.move_cursor_to_coords = lambda s, c, xy: 0 self.ktest( "pathological cursor widget", "page down", [T(""), odd_e, T("")], 1, 1, 2, 4, None, ) e = E("", "\nab\n\n\n\n\ncd\n") e.set_edit_pos(2) self.ktest( "very long cursor widget snap", "page down", [T("\n"), e, T("")], 1, 2, 1, -3, (1, 3), ) self.ktest( "slight scroll selectable", "page down", [S(""), T("\n\n\n"), S(""), T(""), S("\n"), T("\n")], 0, 0, 2, 4, None, ) self.ktest( "scroll into snap region", "page down", [S(""), T("\n\n\n"), T(""), T(""), S("\n"), T("\n")], 0, 0, 4, 3, None, ) self.ktest( "mid scroll short", "page down", [T("\n"), S(""), T("\n"), T(""), S(""), T(""), T(""), T("\n")], 1, 2, 4, 3, None, ) self.ktest( "mid scroll long", "page down", [T("\n"), S(""), T("\n"), T(""), S(""), T(""), S(""), T("\n")], 1, 2, 6, 4, None, ) self.ktest( "mid scroll perfect", "page down", [T("\n"), S(""), T("\n"), T(""), S(""), S(""), S(""), T("\n")], 1, 2, 5, 4, None, ) e = E("", "hi\nab") e.set_edit_pos(1) self.ktest( "cursor move up fail short", "page down", [T(""), T(""), e, T("\n"), T("\n")], 2, 1, 2, -1, (1, 0), ) odd_e = E("", "hi\nab") odd_e.set_edit_pos(1) # disble cursor movement in odd_e object odd_e.move_cursor_to_coords = lambda s, c, xy: 0 self.ktest( "cursor force fail short", "page down", [T(""), T(""), odd_e, T("\n"), T("\n")], 2, 2, 4, 3, None, ) self.ktest( "cursor force fail long", "page down", [T("\n"), S(""), T("\n"), T("\n"), T("\n"), E("hi\n", "ab")], 1, 2, 4, 4, None, ) self.ktest( "prefer not cut off", "page down", [T("\n"), S(""), T("\n\n"), S(""), T("\n"), S("\n")], 1, 2, 3, 3, None, ) self.ktest( "allow cut off", "page down", [T("\n"), S(""), T("\n\n"), T(""), T("\n"), S("\n")], 1, 2, 5, 4, None, ) self.ktest( "at bottom fail", "page down", [T("\n\n"), T("\n"), T("\n\n\n")], 2, 1, 2, 1, None, ) self.ktest( "all visible fail", "page down", [T("a"), T("\n")], 1, 1, 1, 1, None, ) self.ktest( "current ok fail", "page down", [S("hi"), T("\n\n")], 0, 0, 0, 0, None, ) self.ktest( "all visible choose last selectable", "page down", [S("a"), S("b"), S("c"), T("")], 0, 0, 2, 2, None, ) self.ktest( "bring in edge choose last", "page down", [T("-"), S("d"), T("c"), S("-"), T("-"), S("b")], 1, 1, 5, 4, None, ) self.ktest( "bring in edge choose last selectable", "page down", [T("-"), S("d"), T("c"), S("-"), S("-"), T("b")], 1, 1, 4, 3, None, ) class ZeroHeightContentsTest(unittest.TestCase): def test_listbox_pile(self): lb = urwid.ListBox(urwid.SimpleListWalker([urwid.Pile([])])) size = (2, 5) canvas = lb.render(size, focus=True) self.assertEqual([b" ", b" ", b" ", b" ", b" "], canvas.text) def test_listbox_text_pile_page_down(self): lb = urwid.ListBox(urwid.SimpleListWalker([urwid.Text("above"), urwid.Pile([])])) size = (7, 5) lb.keypress(size, "page down") self.assertEqual(lb.focus_position, 0) lb.keypress(size, "page down") # second one caused ListBox failure self.assertEqual(lb.focus_position, 0) canvas = lb.render(size, focus=True) self.assertEqual([b"above ", b" ", b" ", b" ", b" "], canvas.text) def test_listbox_text_pile_page_up(self): lb = urwid.ListBox(urwid.SimpleListWalker([urwid.Pile([]), urwid.Text("below")])) size = (7, 5) lb.set_focus(1) lb.keypress(size, "page up") self.assertEqual(lb.focus_position, 1) lb.keypress(size, "page up") # second one caused pile failure self.assertEqual(lb.focus_position, 1) canvas = lb.render(size, focus=True) self.assertEqual([b"below ", b" ", b" ", b" ", b" "], canvas.text) def test_listbox_text_pile_down(self): sp = urwid.Pile([]) sp.selectable = lambda: True # abuse our Pile lb = urwid.ListBox(urwid.SimpleListWalker([urwid.Text("above"), sp])) size = (7, 5) lb.keypress(size, "down") self.assertEqual(lb.focus_position, 0) lb.keypress(size, "down") self.assertEqual(lb.focus_position, 0) canvas = lb.render(size, focus=True) self.assertEqual([b"above ", b" ", b" ", b" ", b" "], canvas.text) def test_listbox_text_pile_up(self): sp = urwid.Pile([]) sp.selectable = lambda: True # abuse our Pile lb = urwid.ListBox(urwid.SimpleListWalker([sp, urwid.Text("below")])) size = (7, 5) lb.set_focus(1) lb.keypress(size, "up") self.assertEqual(lb.focus_position, 1) lb.keypress(size, "up") self.assertEqual(lb.focus_position, 1) canvas = lb.render(size, focus=True) self.assertEqual([b"below ", b" ", b" ", b" ", b" "], canvas.text) class ListBoxSetBodyTest(unittest.TestCase): def test_signal_connected(self): lb = urwid.ListBox([]) lb.body = urwid.SimpleListWalker([]) self.assertEqual( lb.body._urwid_signals["modified"][0][1], lb._invalidate, "outdated canvas cache reuse after ListWalker's contents modified", ) class TestListWalkerFromIterable(unittest.TestCase): def test_01_simple_list_walker(self): walker = urwid.SimpleListWalker(str(num) for num in range(5)) self.assertEqual(5, len(walker)) def test_02_simple_focus_list_walker(self): walker = urwid.SimpleFocusListWalker(str(num) for num in range(5)) self.assertEqual(5, len(walker))
43,876
Python
.py
1,775
12.871549
99
0.328559
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,221
test_doctests.py
urwid_urwid/tests/test_doctests.py
from __future__ import annotations import doctest import sys import unittest import urwid import urwid.numedit def load_tests(loader: unittest.TestLoader, tests: unittest.BaseTestSuite, ignore) -> unittest.BaseTestSuite: module_doctests = [ urwid.widget.attr_map, urwid.widget.attr_wrap, urwid.widget.bar_graph, urwid.widget.big_text, urwid.widget.box_adapter, urwid.widget.columns, urwid.widget.constants, urwid.widget.container, urwid.widget.divider, urwid.widget.edit, urwid.widget.filler, urwid.widget.frame, urwid.widget.grid_flow, urwid.widget.line_box, urwid.widget.overlay, urwid.widget.padding, urwid.widget.pile, urwid.widget.popup, urwid.widget.progress_bar, urwid.widget.solid_fill, urwid.widget.text, urwid.widget.widget, urwid.widget.widget_decoration, urwid.widget.wimp, urwid.widget.monitored_list, urwid.display.common, urwid.display.raw, urwid.event_loop.main_loop, urwid.numedit, urwid.raw_display, urwid.font, "urwid.split_repr", # override function with same name urwid.util, urwid.signals, ] try: module_doctests.append(urwid.display.curses) except (AttributeError, NameError): pass # Curses is not loaded option_flags = doctest.ELLIPSIS | doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.IGNORE_EXCEPTION_DETAIL for m in module_doctests: tests.addTests(doctest.DocTestSuite(m, optionflags=option_flags)) try: from urwid import curses_display except ImportError: pass # do not run tests else: tests.addTests(doctest.DocTestSuite(curses_display, optionflags=option_flags)) if sys.platform == "win32": tests.addTests(doctest.DocTestSuite("urwid.display._win32_raw_display", optionflags=option_flags)) else: tests.addTests(doctest.DocTestSuite("urwid.display._posix_raw_display", optionflags=option_flags)) return tests
2,125
Python
.py
61
27.42623
109
0.674769
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,222
test_overlay.py
urwid_urwid/tests/test_overlay.py
from __future__ import annotations import unittest import urwid class OverlayTest(unittest.TestCase): def test_sizing_flow_fixed(self) -> None: top_w = urwid.Text("Flow and Fixed widget") bottom_w = urwid.SolidFill("#") widgets = {"top_w": top_w, "bottom_w": bottom_w} for description, kwargs, sizing in ( ( "Fixed render no size", { **widgets, "align": urwid.CENTER, "width": None, "valign": urwid.MIDDLE, "height": None, }, frozenset((urwid.BOX, urwid.FIXED)), ), ( "Fixed render + corners", { **widgets, "align": urwid.CENTER, "width": None, "valign": urwid.MIDDLE, "height": None, "left": 1, "right": 1, "top": 1, "bottom": 1, }, frozenset((urwid.BOX, urwid.FIXED)), ), ( "Fixed render from FLOW", { **widgets, "align": urwid.CENTER, "width": 10, "valign": urwid.MIDDLE, "height": None, }, frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), ), ( "Fixed render from FLOW + corners", { **widgets, "align": urwid.CENTER, "width": 10, "valign": urwid.MIDDLE, "height": None, "left": 1, "right": 1, "top": 1, "bottom": 1, }, frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), ), ): with self.subTest(description): widget = urwid.Overlay(**kwargs) self.assertEqual(sizing, widget.sizing()) def_cols, def_rows = top_w.pack() if kwargs["width"] is None: args_cols = def_cols else: args_cols = kwargs["width"] cols = args_cols + kwargs.get("left", 0) + kwargs.get("right", 0) rows = top_w.rows((args_cols,)) + kwargs.get("top", 0) + kwargs.get("bottom", 0) self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("Fixed Relative"): min_width = 23 relative_width = 90 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=(urwid.RELATIVE, relative_width), valign=urwid.MIDDLE, height=None, min_width=23, ) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) cols = int(min_width * 100 / relative_width + 0.5) rows = top_w.rows((min_width,)) self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual("#Flow and Fixed widget ##", str(canvas)) with self.subTest("Flow Relative"): cols = 25 min_width = 23 relative_width = 90 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=(urwid.RELATIVE, relative_width), valign=urwid.MIDDLE, height=None, min_width=23, ) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) rows = top_w.rows((min_width,)) self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual("#Flow and Fixed widget #", str(canvas)) with self.subTest("Fixed Relative + corners"): min_width = 23 relative_width = 90 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=(urwid.RELATIVE, relative_width), valign=urwid.MIDDLE, height=None, min_width=23, top=1, bottom=1, ) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) cols = int(min_width * 100 / relative_width + 0.5) rows = top_w.rows((min_width,)) + 2 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( "##########################\n" "#Flow and Fixed widget ##\n" "##########################", str(canvas), ) with self.subTest("Fixed Relative + corners"): cols = 25 min_width = 23 relative_width = 90 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=(urwid.RELATIVE, relative_width), valign=urwid.MIDDLE, height=None, min_width=23, top=1, bottom=1, ) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) rows = top_w.rows((min_width,)) + 2 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( "#########################\n" "#Flow and Fixed widget #\n" "#########################", str(canvas), ) def test_sizing_box_fixed_given(self): top_w = urwid.SolidFill("*") bottom_w = urwid.SolidFill("#") min_width = 5 min_height = 3 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=min_width, valign=urwid.MIDDLE, height=min_height, top=1, bottom=1, left=2, right=2, ) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) cols = min_width + 4 rows = min_height + 2 for description, call_args in ( ("All GIVEN FIXED", ()), ("ALL GIVEN FLOW", (cols,)), ("ALL GIVEN BOX", (cols, rows)), ): with self.subTest(description): self.assertEqual((cols, rows), widget.pack(call_args)) canvas = widget.render(call_args) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "#########", "##*****##", "##*****##", "##*****##", "#########", ], [line.decode("utf-8") for line in canvas.text], ) def test_sizing_box_fixed_relative(self): top_w = urwid.SolidFill("*") bottom_w = urwid.SolidFill("#") relative_width = 50 relative_height = 50 min_width = 4 min_height = 2 widget = urwid.Overlay( top_w, bottom_w, align=urwid.CENTER, width=(urwid.RELATIVE, relative_width), valign=urwid.MIDDLE, height=(urwid.RELATIVE, relative_height), min_width=min_width, min_height=min_height, top=1, bottom=1, left=2, right=2, ) cols = int(min_width * 100 / relative_width + 0.5) rows = int(min_height * 100 / relative_height + 0.5) for description, call_args in ( ("All GIVEN FIXED", ()), ("ALL GIVEN FLOW", (cols,)), ("ALL GIVEN BOX", (cols, rows)), ): with self.subTest(description): self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) self.assertEqual((cols, rows), widget.pack(call_args)) canvas = widget.render(call_args) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "########", "##****##", "##****##", "########", ], [line.decode("utf-8") for line in canvas.text], ) def test_relative(self): ovl = urwid.Overlay( urwid.Text("aaa"), urwid.SolidFill(urwid.SolidFill.Symbols.LITE_SHADE), width=urwid.PACK, height=urwid.PACK, align=(urwid.RELATIVE, 30), valign=(urwid.RELATIVE, 70), ) self.assertEqual( ovl.contents[1][1], (urwid.RELATIVE, 30, urwid.PACK, None, None, 0, 0, urwid.RELATIVE, 70, urwid.PACK, None, None, 0, 0), ) self.assertEqual( ( "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░aaa░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", "░░░░░░░░░░░░░░░░░░░░", ), ovl.render((20, 10)).decoded_text, ) def test_old_params(self): o1 = urwid.Overlay( urwid.SolidFill("X"), urwid.SolidFill("O"), ("fixed left", 5), ("fixed right", 4), ("fixed top", 3), ("fixed bottom", 2), ) self.assertEqual( o1.contents[1][1], ("left", None, "relative", 100, None, 5, 4, "top", None, "relative", 100, None, 3, 2), ) o2 = urwid.Overlay( urwid.SolidFill("X"), urwid.SolidFill("O"), ("fixed right", 5), ("fixed left", 4), ("fixed bottom", 3), ("fixed top", 2), ) self.assertEqual( o2.contents[1][1], ("right", None, "relative", 100, None, 4, 5, "bottom", None, "relative", 100, None, 2, 3), ) def test_get_cursor_coords(self): self.assertEqual( urwid.Overlay( urwid.Filler(urwid.Edit()), urwid.SolidFill("B"), "right", 1, "bottom", 1, ).get_cursor_coords((2, 2)), (1, 1), ) def test_length(self): ovl = urwid.Overlay( urwid.SolidFill("X"), urwid.SolidFill("O"), "center", ("relative", 20), "middle", ("relative", 20), ) self.assertEqual(2, len(ovl)) self.assertEqual(2, len(ovl.contents)) def test_common(self): s1 = urwid.SolidFill("1") s2 = urwid.SolidFill("2") o = urwid.Overlay(s1, s2, "center", ("relative", 50), "middle", ("relative", 50)) self.assertEqual(o.focus, s1) self.assertEqual(o.focus_position, 1) self.assertRaises(IndexError, lambda: setattr(o, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(o, "focus_position", 2)) self.assertEqual(o.contents[0], (s2, urwid.Overlay._DEFAULT_BOTTOM_OPTIONS)) self.assertEqual( o.contents[1], (s1, ("center", None, "relative", 50, None, 0, 0, "middle", None, "relative", 50, None, 0, 0)), )
13,126
Python
.py
338
23.363905
113
0.435543
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,223
test_moved_imports.py
urwid_urwid/tests/test_moved_imports.py
from __future__ import annotations import unittest class TestMovedImports(unittest.TestCase): def test_moved_imports_direct(self) -> None: with self.assertWarns(DeprecationWarning): from urwid import web_display from urwid.display import web self.assertIs(web, web_display) def test_moved_imports_nested(self) -> None: from urwid.display import html_fragment from urwid.html_fragment import HtmlGenerator self.assertIs(html_fragment.HtmlGenerator, HtmlGenerator)
538
Python
.py
12
37.583333
65
0.732177
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,224
test_text_layout.py
urwid_urwid/tests/test_text_layout.py
from __future__ import annotations import typing import unittest import urwid from urwid import text_layout from urwid.util import get_encoding, set_temporary_encoding if typing.TYPE_CHECKING: from typing_extensions import Literal class CalcBreaksTest(unittest.TestCase): def cbtest(self, width, exp, mode, text): result = text_layout.default_layout.calculate_text_segments(text, width, mode) self.assertEqual(len(exp), len(result), f"Expected: {exp!r}, got {result!r}") for l, e in zip(result, exp): end = l[-1][-1] self.assertEqual(e, end, f"Expected: {exp!r}, got {result!r}") def validate(self, mode, text, do): for width, exp in do: self.cbtest(width, exp, mode, text) def test_calc_breaks_char(self): self.validate( mode="any", text=b"abfghsdjf askhtrvs\naltjhgsdf ljahtshgf", do=[ (100, [18, 38]), (6, [6, 12, 18, 25, 31, 37, 38]), (10, [10, 18, 29, 38]), ], ) def test_calc_reaks_db_char(self): with urwid.util.set_temporary_encoding("euc-jp"): self.validate( mode="any", text=b"abfgh\xA1\xA1j\xA1\xA1xskhtrvs\naltjhgsdf\xA1\xA1jahtshgf", do=[ (10, [10, 18, 28, 38]), (6, [5, 11, 17, 18, 25, 31, 37, 38]), (100, [18, 38]), ], ) def test_calc_breaks_word(self): self.validate( mode="space", text=b"hello world\nout there. blah", do=[ (10, [5, 11, 22, 27]), (5, [5, 11, 17, 22, 27]), (100, [11, 27]), ], ) def test_calc_breaks_word_2(self): self.validate( mode="space", text=b"A simple set of words, really....", do=[ (10, [8, 15, 22, 33]), (17, [15, 33]), (13, [12, 22, 33]), ], ) def test_calc_breaks_db_word(self): with urwid.util.set_temporary_encoding("euc-jp"): self.validate( mode="space", text=b"hel\xA1\xA1 world\nout-\xA1\xA1tre blah", # tests do=[ (10, [5, 11, 21, 26]), (5, [5, 11, 16, 21, 26]), (100, [11, 26]), ], ) def test_calc_breaks_utf8(self): with urwid.util.set_temporary_encoding("utf-8"): self.validate( mode="space", # As text: "替洼渎溏潺" text=b"\xe6\x9b\xbf\xe6\xb4\xbc\xe6\xb8\x8e\xe6\xba\x8f\xe6\xbd\xba", do=[ (4, [6, 12, 15]), (10, [15]), (5, [6, 12, 15]), ], ) class CalcBreaksCantDisplayTest(unittest.TestCase): def test(self): with set_temporary_encoding("euc-jp"): self.assertRaises( text_layout.CanNotDisplayText, text_layout.default_layout.calculate_text_segments, b"\xA1\xA1", 1, "space", ) with set_temporary_encoding("utf-8"): self.assertRaises( text_layout.CanNotDisplayText, text_layout.default_layout.calculate_text_segments, "颖", 1, "space", ) class SubsegTest(unittest.TestCase): def setUp(self): self.old_encoding = get_encoding() urwid.set_encoding("euc-jp") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def st(self, seg, text: bytes, start: int, end: int, exp): s = urwid.LayoutSegment(seg) result = s.subseg(text, start, end) self.assertEqual(exp, result, f"Expected {exp!r}, got {result!r}") def test1_padding(self): self.st((10, None), b"", 0, 8, [(8, None)]) self.st((10, None), b"", 2, 10, [(8, None)]) self.st((10, 0), b"", 3, 7, [(4, 0)]) self.st((10, 0), b"", 0, 20, [(10, 0)]) def test2_text(self): self.st((10, 0, b"1234567890"), b"", 0, 8, [(8, 0, b"12345678")]) self.st((10, 0, b"1234567890"), b"", 2, 10, [(8, 0, b"34567890")]) self.st((10, 0, b"12\xA1\xA156\xA1\xA190"), b"", 2, 8, [(6, 0, b"\xA1\xA156\xA1\xA1")]) self.st((10, 0, b"12\xA1\xA156\xA1\xA190"), b"", 3, 8, [(5, 0, b" 56\xA1\xA1")]) self.st((10, 0, b"12\xA1\xA156\xA1\xA190"), b"", 2, 7, [(5, 0, b"\xA1\xA156 ")]) self.st((10, 0, b"12\xA1\xA156\xA1\xA190"), b"", 3, 7, [(4, 0, b" 56 ")]) self.st((10, 0, b"12\xA1\xA156\xA1\xA190"), b"", 0, 20, [(10, 0, b"12\xA1\xA156\xA1\xA190")]) def test3_range(self): t = b"1234567890" self.st((10, 0, 10), t, 0, 8, [(8, 0, 8)]) self.st((10, 0, 10), t, 2, 10, [(8, 2, 10)]) self.st((6, 2, 8), t, 1, 6, [(5, 3, 8)]) self.st((6, 2, 8), t, 0, 5, [(5, 2, 7)]) self.st((6, 2, 8), t, 1, 5, [(4, 3, 7)]) t = b"12\xA1\xA156\xA1\xA190" self.st((10, 0, 10), t, 0, 8, [(8, 0, 8)]) self.st((10, 0, 10), t, 2, 10, [(8, 2, 10)]) self.st((6, 2, 8), t, 1, 6, [(1, 3), (4, 4, 8)]) self.st((6, 2, 8), t, 0, 5, [(4, 2, 6), (1, 6)]) self.st((6, 2, 8), t, 1, 5, [(1, 3), (2, 4, 6), (1, 6)]) class CalcTranslateTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = get_encoding() urwid.set_encoding("utf-8") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def check(self, text, mode, width, result_left, result_center, result_right) -> None: with self.subTest("left"): result = urwid.default_layout.layout(text, width, "left", mode) self.assertEqual(result_left, result) with self.subTest("center"): result = urwid.default_layout.layout(text, width, "center", mode) self.assertEqual(result_center, result) with self.subTest("right"): result = urwid.default_layout.layout(text, width, "right", mode) self.assertEqual(result_right, result) def test_calc_translate_char(self): self.check( text="It's out of control!\nYou've got to", mode="any", width=15, result_left=[[(15, 0, 15)], [(5, 15, 20), (0, 20)], [(13, 21, 34), (0, 34)]], result_center=[[(15, 0, 15)], [(5, None), (5, 15, 20), (0, 20)], [(1, None), (13, 21, 34), (0, 34)]], result_right=[[(15, 0, 15)], [(10, None), (5, 15, 20), (0, 20)], [(2, None), (13, 21, 34), (0, 34)]], ) def test_calc_translate_word(self): self.check( text="It's out of control!\nYou've got to", mode="space", width=14, result_left=[ [(11, 0, 11), (0, 11)], [(8, 12, 20), (0, 20)], [(13, 21, 34), (0, 34)], ], result_center=[ [(2, None), (11, 0, 11), (0, 11)], [(3, None), (8, 12, 20), (0, 20)], [(1, None), (13, 21, 34), (0, 34)], ], result_right=[ [(3, None), (11, 0, 11), (0, 11)], [(6, None), (8, 12, 20), (0, 20)], [(1, None), (13, 21, 34), (0, 34)], ], ) def test_calc_translate(self): self.check( text="It's out of control!\nYou've got to ", mode="space", width=14, result_left=[ [(11, 0, 11), (0, 11)], [(8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)], ], result_center=[ [(2, None), (11, 0, 11), (0, 11)], [(3, None), (8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)], ], result_right=[ [(3, None), (11, 0, 11), (0, 11)], [(6, None), (8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)], ], ) def test_calc_translate_word_2(self): self.check( text="It's out of control!\nYou've got to ", mode="space", width=14, result_left=[[(11, 0, 11), (0, 11)], [(8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)]], result_center=[ [(2, None), (11, 0, 11), (0, 11)], [(3, None), (8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)], ], result_right=[ [(3, None), (11, 0, 11), (0, 11)], [(6, None), (8, 12, 20), (0, 20)], [(14, 21, 35), (0, 35)], ], ) def test_calc_translate_word_3(self): # As bytes: b'\xe6\x9b\xbf\xe6\xb4\xbc\n\xe6\xb8\x8e\xe6\xba\x8f\xe6\xbd\xba' # Decoded as UTF-8: "替洼\n渎溏潺" self.check( text=b"\xe6\x9b\xbf\xe6\xb4\xbc\n\xe6\xb8\x8e\xe6\xba\x8f\xe6\xbd\xba", width=10, mode="space", result_left=[[(4, 0, 6), (0, 6)], [(6, 7, 16), (0, 16)]], result_center=[[(3, None), (4, 0, 6), (0, 6)], [(2, None), (6, 7, 16), (0, 16)]], result_right=[[(6, None), (4, 0, 6), (0, 6)], [(4, None), (6, 7, 16), (0, 16)]], ) def test_calc_translate_word_3_decoded(self): # As bytes: b'\xe6\x9b\xbf\xe6\xb4\xbc\n\xe6\xb8\x8e\xe6\xba\x8f\xe6\xbd\xba' # Decoded as UTF-8: "替洼\n渎溏潺" self.check( text="替洼\n渎溏潺", width=10, mode="space", result_left=[[(4, 0, 2), (0, 2)], [(6, 3, 6), (0, 6)]], result_center=[[(3, None), (4, 0, 2), (0, 2)], [(2, None), (6, 3, 6), (0, 6)]], result_right=[[(6, None), (4, 0, 2), (0, 2)], [(4, None), (6, 3, 6), (0, 6)]], ) def test_calc_translate_word_4(self): self.check( text=" Die Gedank", width=3, mode="space", result_left=[[(0, 0)], [(3, 1, 4), (0, 4)], [(3, 5, 8)], [(3, 8, 11), (0, 11)]], result_center=[[(2, None), (0, 0)], [(3, 1, 4), (0, 4)], [(3, 5, 8)], [(3, 8, 11), (0, 11)]], result_right=[[(3, None), (0, 0)], [(3, 1, 4), (0, 4)], [(3, 5, 8)], [(3, 8, 11), (0, 11)]], ) def test_calc_translate_word_5(self): self.check( text=" Word.", width=3, mode="space", result_left=[[(3, 0, 3)], [(3, 3, 6), (0, 6)]], result_center=[[(3, 0, 3)], [(3, 3, 6), (0, 6)]], result_right=[[(3, 0, 3)], [(3, 3, 6), (0, 6)]], ) def test_calc_translate_clip(self): self.check( text="It's out of control!\nYou've got to\n\nturn it off!!!", mode="clip", width=14, result_left=[ [(20, 0, 20), (0, 20)], [(13, 21, 34), (0, 34)], [(0, 35)], [(14, 36, 50), (0, 50)], ], result_center=[ [(-3, None), (20, 0, 20), (0, 20)], [(1, None), (13, 21, 34), (0, 34)], [(7, None), (0, 35)], [(14, 36, 50), (0, 50)], ], result_right=[ [(-6, None), (20, 0, 20), (0, 20)], [(1, None), (13, 21, 34), (0, 34)], [(14, None), (0, 35)], [(14, 36, 50), (0, 50)], ], ) def test_calc_translate_clip_2(self): self.check( text="Hello!\nto\nWorld!", mode="clip", width=5, # line width (of first and last lines) minus one result_left=[ [(6, 0, 6), (0, 6)], [(2, 7, 9), (0, 9)], [(6, 10, 16), (0, 16)], ], result_center=[ [(6, 0, 6), (0, 6)], [(2, None), (2, 7, 9), (0, 9)], [(6, 10, 16), (0, 16)], ], result_right=[ [(-1, None), (6, 0, 6), (0, 6)], [(3, None), (2, 7, 9), (0, 9)], [(-1, None), (6, 10, 16), (0, 16)], ], ) def test_calc_translate_cant_display(self): self.check( text="Hello颖", mode="space", width=1, result_left=[[]], result_center=[[]], result_right=[[]], ) class CalcPosTest(unittest.TestCase): def setUp(self): self.text = "A" * 27 self.trans = [[(2, None), (7, 0, 7), (0, 7)], [(13, 8, 21), (0, 21)], [(3, None), (5, 22, 27), (0, 27)]] self.mytests = [ (1, 0, 0), (2, 0, 0), (11, 0, 7), (-3, 1, 8), (-2, 1, 8), (1, 1, 9), (31, 1, 21), (1, 2, 22), (11, 2, 27), ] def tests(self): for x, y, expected in self.mytests: got = text_layout.calc_pos(self.text, self.trans, x, y) self.assertEqual(expected, got, f"{x, y!r} got:{got!r} expected:{expected!r}") class Pos2CoordsTest(unittest.TestCase): pos_list = [5, 9, 20, 26] text = "1234567890" * 3 mytests = [ ([[(15, 0, 15)], [(15, 15, 30), (0, 30)]], [(5, 0), (9, 0), (5, 1), (11, 1)]), ([[(9, 0, 9)], [(12, 9, 21)], [(9, 21, 30), (0, 30)]], [(5, 0), (0, 1), (11, 1), (5, 2)]), ([[(2, None), (15, 0, 15)], [(2, None), (15, 15, 30), (0, 30)]], [(7, 0), (11, 0), (7, 1), (13, 1)]), ([[(3, 6, 9), (0, 9)], [(5, 20, 25), (0, 25)]], [(0, 0), (3, 0), (0, 1), (5, 1)]), ([[(10, 0, 10), (0, 10)]], [(5, 0), (9, 0), (10, 0), (10, 0)]), ] def test(self): for t, answer in self.mytests: for pos, a in zip(self.pos_list, answer): r = text_layout.calc_coords(self.text, t, pos) self.assertEqual(a, r, f"{t!r} got: {r!r} expected: {a!r}") class TestEllipsis(unittest.TestCase): def test_ellipsis_encoding_support(self): widget = urwid.Text("Test label", wrap=urwid.WrapMode.ELLIPSIS) with self.subTest("Unicode"), set_temporary_encoding("utf-8"): widget._invalidate() canvas = widget.render((5,)) self.assertEqual("Test…", str(canvas)) with self.subTest("ascii"), set_temporary_encoding("ascii"): widget._invalidate() canvas = widget.render((5,)) self.assertEqual("Te...", str(canvas)) with self.subTest("ascii not fit"), set_temporary_encoding("ascii"): widget._invalidate() canvas = widget.render((3,)) self.assertEqual("T..", str(canvas)) with self.subTest("ascii nothing fit"), set_temporary_encoding("ascii"): widget._invalidate() canvas = widget.render((1,)) self.assertEqual("T", str(canvas)) class NumericLayout(urwid.TextLayout): """ TextLayout class for bottom-right aligned numbers """ def layout( self, text: str | bytes, width: int, align: Literal["left", "center", "right"] | urwid.Align, wrap: Literal["any", "space", "clip", "ellipsis"] | urwid.WrapMode, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """ Return layout structure for right justified numbers. """ lt = len(text) r = lt % width # remaining segment not full width wide if r: return [ [(width - r, None), (r, 0, r)], # right-align the remaining segment on 1st line *([(width, x, x + width)] for x in range(r, lt, width)), # fill the rest of the lines ] return [[(width, x, x + width)] for x in range(0, lt, width)] class TestTextLayoutNoPack(unittest.TestCase): def test(self): """Text widget pack should work also with layout not supporting `pack` method.""" widget = urwid.Text("123", layout=NumericLayout()) self.assertEqual((3, 1), widget.pack((3,)))
16,278
Python
.py
395
29.4
113
0.443381
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,225
test_line_box.py
urwid_urwid/tests/test_line_box.py
from __future__ import annotations import unittest import urwid from urwid.util import get_encoding class LineBoxTest(unittest.TestCase): def setUp(self) -> None: self.old_encoding = get_encoding() urwid.set_encoding("utf-8") def tearDown(self) -> None: urwid.set_encoding(self.old_encoding) def test_linebox_pack(self): # Bug #346 'pack' Padding does not run with LineBox t = urwid.Text("AAA\nCCC\nDDD") size = t.pack() l = urwid.LineBox(t) self.assertEqual(l.pack()[0], size[0] + 2) self.assertEqual(l.pack()[1], size[1] + 2) def test_border(self): wrapped = urwid.Text("Text\non\nfour\nlines", align=urwid.CENTER) l = urwid.LineBox(wrapped, tlcorner="╭", trcorner="╮", blcorner="╰", brcorner="╯") cols, rows = 7, 6 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "╭─────╮", "│ Text│", "│ on │", "│ four│", "│lines│", "╰─────╯", ], [line.decode("utf-8") for line in canvas.text], ) def test_header(self): wrapped = urwid.Text("Some text") l = urwid.LineBox(wrapped, title="Title", tlcorner="╭", trcorner="╮", blcorner="╰", brcorner="╯") cols, rows = 11, 3 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "╭─ Title ─╮", "│Some text│", "╰─────────╯", ], [line.decode("utf-8") for line in canvas.text], ) l.set_title("New") self.assertEqual( [ "╭── New ──╮", "│Some text│", "╰─────────╯", ], [line.decode("utf-8") for line in l.render(()).text], ) def test_negative(self): wrapped = urwid.Text("") with self.assertRaises(ValueError) as ctx: l = urwid.LineBox(wrapped, title="Title", tline="") self.assertEqual("Cannot have a title when tline is empty string", str(ctx.exception)) l = urwid.LineBox(wrapped, tline="") with self.assertRaises(ValueError) as ctx: l.set_title("Fail") self.assertEqual("Cannot set title when tline is unset", str(ctx.exception)) def test_partial_contour(self): def mark_pressed(btn: urwid.Button) -> None: nonlocal pressed pressed = True pressed = False wrapped = urwid.Button("Wrapped", on_press=mark_pressed) with self.subTest("No top line -> no top"): l = urwid.LineBox(wrapped, tline="") cols, rows = 13, 2 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "│< Wrapped >│", "└───────────┘", ], [line.decode("utf-8") for line in canvas.text], ) self.assertIsNone(l.keypress((), "enter")) self.assertTrue(pressed) pressed = False with self.subTest("No right side elements -> no side"): l = urwid.LineBox(wrapped, rline="") cols, rows = 12, 3 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "┌───────────", "│< Wrapped >", "└───────────", ], [line.decode("utf-8") for line in canvas.text], ) self.assertIsNone(l.keypress((), "enter")) self.assertTrue(pressed) pressed = False with self.subTest("No left side elements -> no side"): l = urwid.LineBox(wrapped, lline="") cols, rows = 12, 3 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "───────────┐", "< Wrapped >│", "───────────┘", ], [line.decode("utf-8") for line in canvas.text], ) self.assertIsNone(l.keypress((), "enter")) self.assertTrue(pressed) pressed = False with self.subTest("No bottom line -> no bottom"): l = urwid.LineBox(wrapped, bline="") cols, rows = 13, 2 self.assertEqual((cols, rows), l.pack(())) canvas = l.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "┌───────────┐", "│< Wrapped >│", ], [line.decode("utf-8") for line in canvas.text], ) self.assertIsNone(l.keypress((), "enter")) self.assertTrue(pressed) pressed = False def test_columns_of_lineboxes(self): # BUG #748 # Using PACK: width of widget 1 is 4, width of widget 2 is 5. # With equal weight widget 1 will be rendered also 5. columns = urwid.Columns( [ (urwid.PACK, urwid.LineBox(urwid.Text("lol"), rline="", trcorner="", brcorner="")), (urwid.PACK, urwid.LineBox(urwid.Text("wtf"), tlcorner="┬", blcorner="┴")), ] ) canvas = columns.render(()) self.assertEqual( [ "┌───┬───┐", "│lol│wtf│", "└───┴───┘", ], [line.decode("utf-8") for line in canvas.text], )
6,653
Python
.py
165
25.939394
105
0.480039
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,226
test_signals.py
urwid_urwid/tests/test_signals.py
import sys import unittest from unittest.mock import Mock from urwid import Edit, Signals, connect_signal, disconnect_signal, emit_signal, register_signal class SiglnalsTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.EmClass = type("EmClass", (object,), {}) register_signal(cls.EmClass, ["change", "test"]) def test_connect(self): obj = Mock() handler = Mock() edit = Edit("") key = connect_signal(edit, "change", handler, user_args=[obj]) self.assertIsNotNone(key) edit.set_edit_text("long test text") handler.assert_called_once_with(obj, edit, "long test text") handler.reset_mock() disconnect_signal(edit, "change", handler, user_args=[obj]) edit.set_edit_text("another text") handler.assert_not_called() @unittest.skipIf(sys.implementation.name == "pypy", "WeakRef works differently on PyPy") def test_weak_del(self): emitter = SiglnalsTest.EmClass() w1 = Mock(name="w1") w2 = Mock(name="w2") w3 = Mock(name="w3") handler1 = Mock(name="handler1") handler2 = Mock(name="handler2") k1 = connect_signal(emitter, "test", handler1, weak_args=[w1], user_args=[42, "abc"]) k2 = connect_signal(emitter, "test", handler2, weak_args=[w2, w3], user_args=[8]) self.assertIsNotNone(k2) emit_signal(emitter, "test", "Foo") handler1.assert_called_once_with(w1, 42, "abc", "Foo") handler2.assert_called_once_with(w2, w3, 8, "Foo") handler1.reset_mock() handler2.reset_mock() del w1 self.assertEqual( len(getattr(emitter, Signals._signal_attr)["test"]), 1, getattr(emitter, Signals._signal_attr)["test"], ) emit_signal(emitter, "test", "Bar") handler1.assert_not_called() handler2.assert_called_once_with(w2, w3, 8, "Bar") handler2.reset_mock() del w3 emit_signal(emitter, "test", "Baz") handler1.assert_not_called() handler2.assert_not_called() self.assertEqual(len(getattr(emitter, Signals._signal_attr)["test"]), 0) del w2
2,215
Python
.py
53
33.490566
96
0.617852
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,227
test_main_loop.py
urwid_urwid/tests/test_main_loop.py
from __future__ import annotations import concurrent.futures import os import socket import sys import threading import typing import unittest.mock import urwid if typing.TYPE_CHECKING: from types import TracebackType IS_WINDOWS = sys.platform == "win32" class ClosingTemporaryFilesPair(typing.ContextManager[typing.Tuple[typing.TextIO, typing.TextIO]]): """File pair context manager that closes temporary files on exit. Since `sys.stdout` is TextIO, tests have to use compatible api for the proper behavior imitation. """ __slots__ = ("rd_s", "wr_s", "rd_f", "wr_f") def __init__(self) -> None: self.rd_s: socket.socket | None = None self.wr_s: socket.socket | None = None self.rd_f: typing.TextIO | None = None self.wr_f: typing.TextIO | None = None def __enter__(self) -> tuple[typing.TextIO, typing.TextIO]: self.rd_s, self.wr_s = socket.socketpair() self.rd_f = os.fdopen(self.rd_s.fileno(), "r", encoding="utf-8", closefd=False) self.wr_f = os.fdopen(self.wr_s.fileno(), "w", encoding="utf-8", closefd=False) return self.rd_f, self.wr_f def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: """Close everything explicit without waiting for garbage collected.""" if self.rd_f is not None and not self.rd_f.closed: self.rd_f.close() if self.rd_s is not None: self.rd_s.close() if self.wr_f is not None and not self.wr_f.closed: self.wr_f.close() if self.wr_s is not None: self.wr_s.close() def stop_screen_cb(*_args, **_kwargs) -> typing.NoReturn: raise urwid.ExitMainLoop class TestMainLoop(unittest.TestCase): @unittest.skipIf(IS_WINDOWS, "selectors for pipe are not supported on Windows") def test_watch_pipe(self): """Test watching pipe is stopped on explicit False only.""" evt = threading.Event() # We need thread synchronization outcome: list[bytes] = [] def pipe_cb(data: bytes) -> typing.Any: outcome.append(data) if not evt.is_set(): evt.set() if data == b"false": return False if data == b"true": return True if data == b"null": return None return object() def pipe_writer(fd: int) -> None: os.write(fd, b"something") if evt.wait(0.1): evt.clear() os.write(fd, b"true") if evt.wait(0.1): evt.clear() os.write(fd, b"null") if evt.wait(0.1): evt.clear() os.write(fd, b"false") with ClosingTemporaryFilesPair() as ( rd_r, wr_r, ), ClosingTemporaryFilesPair() as ( rd_w, wr_w, ), concurrent.futures.ThreadPoolExecutor( max_workers=1, ) as executor, unittest.mock.patch( "subprocess.Popen", # we want to be sure that nothing outside is called autospec=True, ): evl = urwid.MainLoop( urwid.SolidFill(), screen=urwid.display.raw.Screen(input=rd_r, output=wr_w), # We need screen which support mocked IO handle_mouse=False, # Less external calls - better ) evl.set_alarm_in(1, stop_screen_cb) pipe_fd = evl.watch_pipe(pipe_cb) executor.submit(pipe_writer, pipe_fd) evl.run() self.assertEqual([b"something", b"true", b"null", b"false"], outcome) not_removed = evl.remove_watch_pipe(pipe_fd) self.assertFalse(not_removed)
3,860
Python
.py
96
30.322917
115
0.580283
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,228
test_tree.py
urwid_urwid/tests/test_tree.py
from __future__ import annotations import typing import unittest import urwid from urwid import TreeNode if typing.TYPE_CHECKING: from collections.abc import Collection, Hashable, Iterable class SelfRegisteringParent(urwid.ParentNode): def __init__( self, value: str, parent: SelfRegisteringParent | None = None, key: Hashable = None, depth: int | None = None, children: Iterable[SelfRegisteringChild | SelfRegisteringParent] = (), ) -> None: super().__init__(value, parent, key, depth) if parent: parent.set_child_node(key, self) self._child_keys = [] for child in children: key = child.get_key() self._children[key] = child self._child_keys.append(key) child.set_parent(self) def load_child_keys(self) -> Collection[Hashable]: return list(self._children) def set_child_node(self, key: Hashable, node: TreeNode) -> None: super().set_child_node(key, node) self._child_keys = self.load_child_keys() def set_parent(self, parent: SelfRegisteringParent) -> None: self._parent = parent class SelfRegisteringChild(urwid.TreeNode): def __init__( self, value: str, parent: SelfRegisteringParent | None = None, key: Hashable | None = None, depth: int | None = None, ) -> None: super().__init__(value, parent, key, depth) if parent: parent.set_child_node(key, self) def set_parent(self, parent: SelfRegisteringParent) -> None: self._parent = parent class TestTree(unittest.TestCase): def test_basic(self): root = SelfRegisteringParent( "root", key="/", children=(SelfRegisteringChild(f"child_{idx}", key=str(idx)) for idx in range(1, 4)), ) widget = urwid.TreeListBox(urwid.TreeWalker(root)) size = (15, 5) expanded = ( "- /: root ", " 1: child_1 ", " 2: child_2 ", " 3: child_3 ", " ", ) collapsed = ( "+ /: root ", *(" " * size[0] for _ in range(size[1] - 1)), ) self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "-") self.assertEqual(collapsed, widget.render(size).decoded_text) widget.keypress(size, "+") self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "down") self.assertIs(root, widget.focus_position) widget.keypress(size, "-") self.assertEqual(collapsed, widget.render(size).decoded_text) widget.keypress(size, "right") self.assertEqual(expanded, widget.render(size).decoded_text) def test_nested_behavior(self): root = SelfRegisteringParent( "root", key="/", children=( SelfRegisteringParent( f"nested_{idx}", key=f"{idx}/", children=(SelfRegisteringChild(f"child_{idx}{cidx}", key=str(cidx)) for cidx in range(1, 4)), ) for idx in range(1, 4) ), ) widget = urwid.TreeListBox(urwid.TreeWalker(root)) size = (18, 13) expanded = ( "- /: root ", " - 1/: nested_1 ", " 1: child_11 ", " 2: child_12 ", " 3: child_13 ", " - 2/: nested_2 ", " 1: child_21 ", " 2: child_22 ", " 3: child_23 ", " - 3/: nested_3 ", " 1: child_31 ", " 2: child_32 ", " 3: child_33 ", ) collapsed = ( "+ /: root ", *(" " * size[0] for _ in range(size[1] - 1)), ) self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "-") self.assertEqual(collapsed, widget.render(size).decoded_text) widget.keypress(size, "+") self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "down") widget.keypress(size, "-") self.assertEqual( ( "- /: root ", " + 1/: nested_1 ", " - 2/: nested_2 ", " 1: child_21 ", " 2: child_22 ", " 3: child_23 ", " - 3/: nested_3 ", " 1: child_31 ", " 2: child_32 ", " 3: child_33 ", " ", " ", " ", ), widget.render(size).decoded_text, ) widget.keypress(size, "right") self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "left") widget.keypress(size, "-") self.assertEqual(collapsed, widget.render(size).decoded_text) widget.keypress(size, "+") widget.keypress(size, "page down") widget.keypress(size, "-") self.assertEqual( ( "- /: root ", " - 1/: nested_1 ", " 1: child_11 ", " 2: child_12 ", " 3: child_13 ", " - 2/: nested_2 ", " 1: child_21 ", " 2: child_22 ", " 3: child_23 ", " + 3/: nested_3 ", " ", " ", " ", ), widget.render(size).decoded_text, ) def test_deep_nested_collapse_expand(self): root = SelfRegisteringParent( "root", key="/", children=( SelfRegisteringParent( f"nested_{top_idx}", key=f"{top_idx}/", children=( SelfRegisteringParent( f"nested_{top_idx}{first_idx}", key=f"{first_idx}/", children=( SelfRegisteringChild(f"child_{top_idx}{first_idx}{last_idx}", key=str(last_idx)) for last_idx in range(1, 3) ), ) for first_idx in range(1, 3) ), ) for top_idx in range(1, 3) ), ) widget = urwid.TreeListBox(urwid.TreeWalker(root)) size = (21, 15) expanded = ( "- /: root ", " - 1/: nested_1 ", " - 1/: nested_11", " 1: child_111", " 2: child_112", " - 2/: nested_12", " 1: child_121", " 2: child_122", " - 2/: nested_2 ", " - 1/: nested_21", " 1: child_211", " 2: child_212", " - 2/: nested_22", " 1: child_221", " 2: child_222", ) collapsed = ( "+ /: root ", *(" " * size[0] for _ in range(size[1] - 1)), ) collapsed_last = ( "- /: root ", " - 1/: nested_1 ", " - 1/: nested_11", " 1: child_111", " 2: child_112", " - 2/: nested_12", " 1: child_121", " 2: child_122", " - 2/: nested_2 ", " - 1/: nested_21", " 1: child_211", " 2: child_212", " + 2/: nested_22", " ", " ", ) self.assertEqual(expanded, widget.render(size).decoded_text) widget.keypress(size, "page down") widget.keypress(size, "-") self.assertEqual(collapsed_last, widget.render(size).decoded_text) widget.keypress(size, "left") widget.keypress(size, "-") self.assertEqual( ( "- /: root ", " - 1/: nested_1 ", " - 1/: nested_11", " 1: child_111", " 2: child_112", " - 2/: nested_12", " 1: child_121", " 2: child_122", " + 2/: nested_2 ", " ", " ", " ", " ", " ", " ", ), widget.render(size).decoded_text, ) widget.keypress(size, "right") self.assertEqual(collapsed_last, widget.render(size).decoded_text) widget.keypress(size, "home") widget.keypress(size, "-") self.assertEqual(collapsed, widget.render(size).decoded_text)
9,460
Python
.py
255
24.752941
113
0.415107
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,229
test_pile.py
urwid_urwid/tests/test_pile.py
from __future__ import annotations import unittest import urwid from tests.util import SelectableText class PileTest(unittest.TestCase): def test_basic_sizing(self) -> None: box_only = urwid.SolidFill("#") flow_only = urwid.ProgressBar(None, None) fixed_only = urwid.BigText("0", urwid.Thin3x3Font()) flow_fixed = urwid.Text("text") with self.subTest("BOX-only widget"): widget = urwid.Pile((box_only,)) self.assertEqual(frozenset((urwid.BOX,)), widget.sizing()) cols, rows = 2, 2 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("GIVEN BOX -> BOX/FLOW"): widget = urwid.Pile(((2, box_only),)) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW)), widget.sizing()) cols, rows = 2, 5 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) cols, rows = 5, 2 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FLOW-only"): widget = urwid.Pile((flow_only,)) self.assertEqual(frozenset((urwid.FLOW,)), widget.sizing()) cols, rows = 5, 1 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) with self.subTest("FIXED -> FIXED"): widget = urwid.Pile(((urwid.PACK, fixed_only),)) self.assertEqual(frozenset((urwid.FIXED,)), widget.sizing()) cols, rows = 3, 3 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "┌─┐", "│ │", "└─┘", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("FLOW/FIXED -> FLOW/FIXED"): widget = urwid.Pile(((urwid.PACK, flow_fixed),)) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 4, 1 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( ["text"], [line.decode("utf-8") for line in widget.render(()).text], ) cols, rows = 2, 2 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "te", "xt", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("FLOW + FLOW/FIXED -> FLOW/FIXED"): widget = urwid.Pile((flow_only, (urwid.PACK, flow_fixed))) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 4, 2 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ " 0 %", "text", ], [line.decode("utf-8") for line in canvas.text], ) cols, rows = 2, 3 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "0 ", "te", "xt", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("FLOW + FIXED widgets -> FLOW/FIXED"): widget = urwid.Pile((flow_only, (urwid.PACK, fixed_only))) self.assertEqual(frozenset((urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 3, 4 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "0 %", "┌─┐", "│ │", "└─┘", ], [line.decode("utf-8") for line in canvas.text], ) cols, rows = 10, 4 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ " 0 % ", "┌─┐", "│ │", "└─┘", ], [line.decode("utf-8") for line in canvas.text], ) with self.subTest("GIVEN BOX + FIXED widgets -> BOX/FLOW/FIXED"): widget = urwid.Pile(((1, box_only), (urwid.PACK, fixed_only), (1, box_only))) self.assertEqual(frozenset((urwid.BOX, urwid.FLOW, urwid.FIXED)), widget.sizing()) cols, rows = 3, 5 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "###", "┌─┐", "│ │", "└─┘", "###", ], [line.decode("utf-8") for line in canvas.text], ) cols, rows = 5, 5 self.assertEqual((cols, rows), widget.pack((cols,))) canvas = widget.render((cols,)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "#####", "┌─┐", "│ │", "└─┘", "#####", ], [line.decode("utf-8") for line in canvas.text], ) cols, rows = 5, 6 self.assertEqual((cols, rows), widget.pack((cols, rows))) canvas = widget.render((cols, rows)) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "#####", "┌─┐", "│ │", "└─┘", "#####", " ", ], [line.decode("utf-8") for line in canvas.text], ) def test_pack_render_fixed(self) -> None: """Potential real world case""" widget = urwid.LineBox( urwid.Pile( ( urwid.Text("Modal window", align=urwid.CENTER), urwid.Divider("─"), urwid.Columns( (urwid.Button(label, align=urwid.CENTER) for label in ("OK", "Cancel", "Help")), dividechars=1, ), ) ) ) cols, rows = 34, 5 self.assertEqual((cols, rows), widget.pack(())) canvas = widget.render(()) self.assertEqual(cols, canvas.cols()) self.assertEqual(rows, canvas.rows()) self.assertEqual( [ "┌────────────────────────────────┐", "│ Modal window │", "│────────────────────────────────│", "│< OK > < Cancel > < Help >│", "└────────────────────────────────┘", ], [line.decode("utf-8") for line in canvas.text], ) self.assertEqual("OK", widget.focus.focus.label) widget.keypress((), "right") self.assertEqual("Cancel", widget.focus.focus.label) def test_not_a_widget(self): class NotAWidget: __slots__ = ("name", "symbol") def __init__(self, name: str, symbol: bytes) -> None: self.name = name self.symbol = symbol def __repr__(self) -> str: return f"{self.__class__.__name__}(name={self.name!r}, symbol={self.symbol!r})" def selectable(self) -> bool: return False def pack(self, max_col_row: tuple[int, int] | tuple[int], focus: bool = False) -> int: if len(max_col_row) == 2: return max_col_row return max_col_row[0], self.rows(max_col_row) def rows(self, max_col_row: tuple[int], focus=False) -> int: return 1 def render(self, max_col_row: tuple[int, int] | tuple[int], focus: bool = False) -> urwid.Canvas: maxcol = max_col_row[0] line = self.symbol * maxcol if len(max_col_row) == 1: return urwid.TextCanvas((line,), maxcol=maxcol) return urwid.TextCanvas((line,) * max_col_row[1], maxcol=maxcol) with self.subTest("Box"), self.assertWarns(urwid.widget.PileWarning) as ctx: items = (NotAWidget("First", b"*"), NotAWidget("Second", b"^")) widget = urwid.Pile(items) self.assertEqual(("****", "^^^^"), widget.render((4, 2)).decoded_text) self.assertEqual(f"{items[0]!r} is not a Widget", str(ctx.warnings[0].message)) self.assertEqual(f"{items[1]!r} is not a Widget", str(ctx.warnings[1].message)) with self.subTest("Flow"), self.assertWarns(urwid.widget.PileWarning) as ctx: items = (NotAWidget("First", b"*"), NotAWidget("Second", b"^")) widget = urwid.Pile(items) self.assertEqual(("******", "^^^^^^"), widget.render((6,)).decoded_text) self.assertEqual(f"{items[0]!r} is not a Widget", str(ctx.warnings[0].message)) self.assertEqual(f"{items[1]!r} is not a Widget", str(ctx.warnings[1].message)) def ktest(self, desc, contents, focus_item, key, rkey, rfocus, rpref_col): p = urwid.Pile(contents, focus_item) rval = p.keypress((20,), key) assert rkey == rval, f"{desc} key expected {rkey!r} but got {rval!r}" new_focus = contents.index(p.focus) assert new_focus == rfocus, f"{desc} focus expected {rfocus!r} but got {new_focus!r}" new_pref = p.get_pref_col((20,)) assert new_pref == rpref_col, f"{desc} pref_col expected {rpref_col!r} but got {new_pref!r}" def test_select_change(self): self.ktest("simple up", [SelectableText("")], 0, "up", "up", 0, 0) self.ktest("simple down", [SelectableText("")], 0, "down", "down", 0, 0) self.ktest("ignore up", [urwid.Text(""), SelectableText("")], 1, "up", "up", 1, 0) self.ktest("ignore down", [SelectableText(""), urwid.Text("")], 0, "down", "down", 0, 0) self.ktest("step up", [SelectableText(""), SelectableText("")], 1, "up", None, 0, 0) self.ktest("step down", [SelectableText(""), SelectableText("")], 0, "down", None, 1, 0) self.ktest("skip step up", [SelectableText(""), urwid.Text(""), SelectableText("")], 2, "up", None, 0, 0) self.ktest("skip step down", [SelectableText(""), urwid.Text(""), SelectableText("")], 0, "down", None, 2, 0) self.ktest( "pad skip step up", [urwid.Text(""), SelectableText(""), urwid.Text(""), SelectableText("")], 3, "up", None, 1, 0, ) self.ktest( "pad skip step down", [SelectableText(""), urwid.Text(""), SelectableText(""), urwid.Text("")], 0, "down", None, 2, 0, ) self.ktest( "padi skip step up", [SelectableText(""), urwid.Text(""), SelectableText(""), urwid.Text(""), SelectableText("")], 4, "up", None, 2, 0, ) self.ktest( "padi skip step down", [SelectableText(""), urwid.Text(""), SelectableText(""), urwid.Text(""), SelectableText("")], 0, "down", None, 2, 0, ) e = urwid.Edit("", "abcd", edit_pos=1) e.keypress((20,), "right") # set a pref_col self.ktest("pref step up", [SelectableText(""), urwid.Text(""), e], 2, "up", None, 0, 2) self.ktest("pref step down", [e, urwid.Text(""), SelectableText("")], 0, "down", None, 2, 2) z = urwid.Edit("", "1234") self.ktest("prefx step up", [z, urwid.Text(""), e], 2, "up", None, 0, 2) assert z.get_pref_col((20,)) == 2 z = urwid.Edit("", "1234") self.ktest("prefx step down", [e, urwid.Text(""), z], 0, "down", None, 2, 2) assert z.get_pref_col((20,)) == 2 def test_init_with_a_generator(self): urwid.Pile(urwid.Text(c) for c in "ABC") def test_change_focus_with_mouse(self): p = urwid.Pile([urwid.Edit(), urwid.Edit()]) self.assertEqual(p.focus_position, 0) p.mouse_event((10,), "button press", 1, 1, 1, True) self.assertEqual(p.focus_position, 1) def test_zero_weight(self): p = urwid.Pile( [ urwid.SolidFill("a"), ("weight", 0, urwid.SolidFill("d")), ] ) p.render((5, 4)) def test_mouse_event_in_empty_pile(self): p = urwid.Pile([]) p.mouse_event((5,), "button press", 1, 1, 1, False) p.mouse_event((5,), "button press", 1, 1, 1, True) def test_length(self): pile = urwid.Pile(urwid.Text(c) for c in "ABC") self.assertEqual(3, len(pile)) self.assertEqual(3, len(pile.contents)) def test_common(self): t1 = urwid.Text("one") t2 = urwid.Text("two") t3 = urwid.Text("three") sf = urwid.SolidFill("x") p = urwid.Pile([]) with self.subTest("Focus"): self.assertEqual(p.focus, None) self.assertRaises(IndexError, lambda: getattr(p, "focus_position")) self.assertRaises(IndexError, lambda: setattr(p, "focus_position", None)) self.assertRaises(IndexError, lambda: setattr(p, "focus_position", 0)) with self.subTest("Contents change"): p.contents = [(t1, ("pack", None)), (t2, ("pack", None)), (sf, ("given", 3)), (t3, ("pack", None))] p.focus_position = 1 del p.contents[0] self.assertEqual(p.focus_position, 0) p.contents[0:0] = [(t3, ("pack", None)), (t2, ("pack", None))] p.contents.insert(3, (t1, ("pack", None))) self.assertEqual(p.focus_position, 2) with self.subTest("Contents change validation"): p.contents.clear() self.assertRaises(urwid.PileError, lambda: p.contents.append(t1)) self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, None))) self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, "given"))) self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, ("given",)))) # Incorrect kind self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, ("what", 0)))) # incorrect size type self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, ("given", ())))) # incorrect size self.assertRaises(urwid.PileError, lambda: p.contents.append((t1, ("given", -1)))) # Float and int weight accepted p.contents.append((t1, ("weight", 1))) p.contents.append((t2, ("weight", 0.5))) self.assertEqual(("one", "two"), p.render((3,)).decoded_text) def test_focus_position(self): t1 = urwid.Text("one") t2 = urwid.Text("two") p = urwid.Pile([t1, t2]) self.assertEqual(p.focus, t1) self.assertEqual(p.focus_position, 0) p.focus_position = 1 self.assertEqual(p.focus, t2) self.assertEqual(p.focus_position, 1) p.focus_position = 0 self.assertRaises(IndexError, lambda: setattr(p, "focus_position", -1)) self.assertRaises(IndexError, lambda: setattr(p, "focus_position", 2)) def test_deprecated(self): t1 = urwid.Text("one") t2 = urwid.Text("two") p = urwid.Pile([t1, t2]) # old methods: with self.subTest("Focus"): p.set_focus(0) self.assertRaises(IndexError, lambda: p.set_focus(-1)) self.assertRaises(IndexError, lambda: p.set_focus(2)) p.set_focus(t2) self.assertEqual(p.focus_position, 1) self.assertRaises(ValueError, lambda: p.set_focus("nonexistant")) with self.subTest("Contents"): self.assertEqual(p.widget_list, [t1, t2]) self.assertEqual(p.item_types, [("weight", 1), ("weight", 1)]) with self.subTest("Contents change"): p.widget_list = [t2, t1] self.assertEqual(p.widget_list, [t2, t1]) self.assertEqual(p.contents, [(t2, ("weight", 1)), (t1, ("weight", 1))]) self.assertEqual(p.focus_position, 1) # focus unchanged p.item_types = [("flow", None), ("weight", 2)] self.assertEqual(p.item_types, [("flow", None), ("weight", 2)]) self.assertEqual(p.contents, [(t2, ("pack", None)), (t1, ("weight", 2))]) self.assertEqual(p.focus_position, 1) # focus unchanged with self.subTest("Contents change 2"): p.widget_list = [t1] self.assertEqual(len(p.contents), 1) self.assertEqual(p.focus_position, 0) p.widget_list.extend([t2, t1]) self.assertEqual(len(p.contents), 3) self.assertEqual(p.item_types, [("flow", None), ("weight", 1), ("weight", 1)]) p.item_types[:] = [("weight", 2)] self.assertEqual(len(p.contents), 1)
19,432
Python
.py
419
32.582339
117
0.501609
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,230
test_vterm.py
urwid_urwid/tests/test_vterm.py
# Urwid terminal emulation widget unit tests # Copyright (C) 2010 aszlig # Copyright (C) 2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import errno import os import sys import typing import unittest from itertools import dropwhile from time import sleep import urwid from urwid.util import set_temporary_encoding IS_WINDOWS = sys.platform == "win32" class DummyCommand: QUITSTRING = b"|||quit|||" def __init__(self) -> None: self.reader, self.writer = os.pipe() def __call__(self) -> None: # reset stdout = getattr(sys.stdout, "buffer", sys.stdout) stdout.write(b"\x1bc") while True: data = self.read(1024) if self.QUITSTRING == data: break stdout.write(data) stdout.flush() def read(self, size: int) -> bytes: while True: try: return os.read(self.reader, size) except OSError as e: if e.errno != errno.EINTR: raise def write(self, data: bytes) -> None: os.write(self.writer, data) sleep(0.025) def quit(self) -> None: self.write(self.QUITSTRING) @unittest.skipIf(IS_WINDOWS, "Terminal is not supported under windows") class TermTest(unittest.TestCase): def setUp(self) -> None: self.command = DummyCommand() self.term = urwid.Terminal(self.command) self.resize(80, 24) def tearDown(self) -> None: self.command.quit() def connect_signal(self, signal: str): self._sig_response = None def _set_signal_response(widget: urwid.Widget, *args, **kwargs) -> None: self._sig_response = (args, kwargs) self._set_signal_response = _set_signal_response urwid.connect_signal(self.term, signal, self._set_signal_response) def expect_signal(self, *args, **kwargs): self.assertEqual(self._sig_response, (args, kwargs)) def disconnect_signal(self, signal: str) -> None: urwid.disconnect_signal(self.term, signal, self._set_signal_response) def caught_beep(self, obj): self.beeped = True def resize(self, width: int, height: int, soft: bool = False) -> None: self.termsize = (width, height) if not soft: self.term.render(self.termsize, focus=False) def write(self, data: str) -> None: data = data.encode("iso8859-1") self.command.write(data.replace(rb"\e", b"\x1b")) def flush(self) -> None: self.write(chr(0x7F)) @typing.overload def read(self, raw: bool = False, focus: bool = ...) -> bytes: ... @typing.overload def read(self, raw: bool = True, focus: bool = ...) -> list[list[bytes, typing.Any, typing.Any]]: ... def read(self, raw: bool = False, focus: bool = False) -> bytes | list[list[bytes, typing.Any, typing.Any]]: self.term.wait_and_feed() rendered = self.term.render(self.termsize, focus=focus) if raw: is_empty = lambda c: c == (None, None, b" ") content = list(rendered.content()) lines = (tuple(dropwhile(is_empty, reversed(line))) for line in content) return [list(reversed(line)) for line in lines if line] else: content = rendered.text lines = (line.rstrip() for line in content) return b"\n".join(lines).rstrip() def expect( self, what: str | list[tuple[typing.Any, str | None, bytes]], desc: str | None = None, raw: bool = False, focus: bool = False, ) -> None: if not isinstance(what, list): what = what.encode("iso8859-1") got = self.read(raw=raw, focus=focus) if desc is None: desc = "" else: desc += "\n" desc += f"Expected:\n{what!r}\nGot:\n{got!r}" self.assertEqual(got, what, desc) def test_simplestring(self): self.write("hello world") self.expect("hello world") def test_linefeed(self): self.write("hello\x0aworld") self.expect("hello\nworld") def test_linefeed2(self): self.write("aa\b\b\\eDbb") self.expect("aa\nbb") def test_carriage_return(self): self.write("hello\x0dworld") self.expect("world") def test_insertlines(self): self.write("\\e[0;0flast\\e[0;0f\\e[10L\\e[0;0ffirst\nsecond\n\\e[11D") self.expect("first\nsecond\n\n\n\n\n\n\n\n\nlast") def test_deletelines(self): self.write("1\n2\n3\n4\\e[2;1f\\e[2M") self.expect("1\n4") def test_nul(self): self.write("a\0b") self.expect("ab") def test_movement(self): self.write(r"\e[10;20H11\e[10;0f\e[20C\e[K") self.expect("\n" * 9 + " " * 19 + "1") self.write("\\e[A\\e[B\\e[C\\e[D\b\\e[K") self.expect("") self.write(r"\e[50A2") self.expect(" " * 19 + "2") self.write("\b\\e[K\\e[50B3") self.expect("\n" * 23 + " " * 19 + "3") self.write("\b\\e[K" + r"\eM" * 30 + r"\e[100C4") self.expect(" " * 79 + "4") self.write(r"\e[100D\e[K5") self.expect("5") def edgewall(self): edgewall = "1-\\e[1;%(x)df-2\\e[%(y)d;1f3-\\e[%(y)d;%(x)df-4\x0d" self.write(edgewall % {"x": self.termsize[0] - 1, "y": self.termsize[1] - 1}) def test_horizontal_resize(self): self.resize(80, 24) self.edgewall() self.expect("1-" + " " * 76 + "-2" + "\n" * 22 + "3-" + " " * 76 + "-4") self.resize(78, 24, soft=True) self.flush() self.expect("1-" + "\n" * 22 + "3-") self.resize(80, 24, soft=True) self.flush() self.expect("1-" + "\n" * 22 + "3-") def test_vertical_resize(self): self.resize(80, 24) self.edgewall() self.expect("1-" + " " * 76 + "-2" + "\n" * 22 + "3-" + " " * 76 + "-4") for y in range(23, 1, -1): self.resize(80, y, soft=True) self.write(r"\e[%df\e[J3-\e[%d;%df-4" % (y, y, 79)) desc = "try to rescale to 80x%d." % y self.expect("\n" * (y - 2) + "3-" + " " * 76 + "-4", desc) self.resize(80, 24, soft=True) self.flush() self.expect("1-" + " " * 76 + "-2" + "\n" * 22 + "3-" + " " * 76 + "-4") def write_movements(self, arg): fmt = "XXX\n\\e[faaa\\e[Bccc\\e[Addd\\e[Bfff\\e[Cbbb\\e[A\\e[Deee" self.write(fmt.replace(r"\e[", r"\e[" + arg)) def test_defargs(self): self.write_movements("") self.expect("aaa ddd eee\n ccc fff bbb") def test_nullargs(self): self.write_movements("0") self.expect("aaa ddd eee\n ccc fff bbb") def test_erase_line(self): self.write("1234567890\\e[5D\\e[K\n1234567890\\e[5D\\e[1K\naaaaaaaaaaaaaaa\\e[2Ka") self.expect("12345\n 7890\n a") def test_erase_display(self): self.write(r"1234567890\e[5D\e[Ja") self.expect("12345a") self.write(r"98765\e[8D\e[1Jx") self.expect(" x5a98765") def test_scrolling_region_simple(self): # TODO(Aleksei): Issue #544 self.write("\\e[10;20r\\e[10f1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\\e[faa") self.expect("aa" + "\n" * 9 + "2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12") def test_scrolling_region_reverse(self): self.write("\\e[2J\\e[1;2r\\e[5Baaa\r\\eM\\eM\\eMbbb\nXXX") self.expect("\n\nbbb\nXXX\n\naaa") def test_scrolling_region_move(self): self.write("\\e[10;20r\\e[2J\\e[10Bfoo\rbar\rblah\rmooh\r\\e[10Aone\r\\eM\\eMtwo\r\\eM\\eMthree\r\\eM\\eMa") self.expect("ahree\n\n\n\n\n\n\n\n\n\nmooh") def test_scrolling_twice(self): self.write(r"\e[?6h\e[10;20r\e[2;5rtest") self.expect("\ntest") def test_cursor_scrolling_region(self): # TODO(Aleksei): Issue #544 self.write("\\e[?6h\\e[10;20r\\e[10f1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\\e[faa") self.expect("\n" * 9 + "aa\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12") def test_scrolling_region_simple_with_focus(self): # TODO(Aleksei): Issue #544 self.write("\\e[10;20r\\e[10f1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\\e[faa") self.expect("aa" + "\n" * 9 + "2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12", focus=True) def test_scrolling_region_reverse_with_focus(self): self.write("\\e[2J\\e[1;2r\\e[5Baaa\r\\eM\\eM\\eMbbb\nXXX") self.expect("\n\nbbb\nXXX\n\naaa", focus=True) def test_scrolling_region_move_with_focus(self): self.write("\\e[10;20r\\e[2J\\e[10Bfoo\rbar\rblah\rmooh\r\\e[10Aone\r\\eM\\eMtwo\r\\eM\\eMthree\r\\eM\\eMa") self.expect("ahree\n\n\n\n\n\n\n\n\n\nmooh", focus=True) def test_scrolling_twice_with_focus(self): self.write(r"\e[?6h\e[10;20r\e[2;5rtest") self.expect("\ntest", focus=True) def test_cursor_scrolling_region_with_focus(self): # TODO(Aleksei): Issue #544 self.write("\\e[?6h\\e[10;20r\\e[10f1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\\e[faa") self.expect("\n" * 9 + "aa\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12", focus=True) def test_relative_region_jump(self): self.write(r"\e[21H---\e[10;20r\e[?6h\e[18Htest") self.expect("\n" * 19 + "test\n---") def test_set_multiple_modes(self): self.write(r"\e[?6;5htest") self.expect("test") self.assertTrue(self.term.term_modes.constrain_scrolling) self.assertTrue(self.term.term_modes.reverse_video) self.write(r"\e[?6;5l") self.expect("test") self.assertFalse(self.term.term_modes.constrain_scrolling) self.assertFalse(self.term.term_modes.reverse_video) def test_wrap_simple(self): self.write(r"\e[?7h\e[1;%dHtt" % self.term.width) self.expect(" " * (self.term.width - 1) + "t\nt") def test_wrap_backspace_tab(self): self.write("\\e[?7h\\e[1;%dHt\b\b\t\ta" % self.term.width) self.expect(" " * (self.term.width - 1) + "a") def test_cursor_visibility(self): self.write(r"\e[?25linvisible") self.expect("invisible", focus=True) self.assertEqual(self.term.term.cursor, None) self.write("\rvisible\\e[?25h\\e[K") self.expect("visible", focus=True) self.assertNotEqual(self.term.term.cursor, None) def test_get_utf8_len(self): length = self.term.term.get_utf8_len(int("11110000", 2)) self.assertEqual(length, 3) length = self.term.term.get_utf8_len(int("11000000", 2)) self.assertEqual(length, 1) length = self.term.term.get_utf8_len(int("11111101", 2)) self.assertEqual(length, 5) def test_encoding_unicode(self): with set_temporary_encoding("utf-8"): self.write("\\e%G\xe2\x80\x94") self.expect("\xe2\x80\x94") def test_encoding_unicode_ascii(self): with set_temporary_encoding("ascii"): self.write("\\e%G\xe2\x80\x94") self.expect("?") def test_encoding_wrong_unicode(self): with set_temporary_encoding("utf-8"): self.write("\\e%G\xc0\x99") self.expect("") def test_encoding_vt100_graphics(self): with set_temporary_encoding("ascii"): self.write("\\e)0\\e(0\x0fg\x0eg\\e)Bn\\e)0g\\e)B\\e(B\x0fn") self.expect( [[(None, "0", b"g"), (None, "0", b"g"), (None, None, b"n"), (None, "0", b"g"), (None, None, b"n")]], raw=True, ) def test_ibmpc_mapping(self): with set_temporary_encoding("ascii"): self.write("\\e[11m\x18\\e[10m\x18") self.expect([[(None, "U", b"\x18")]], raw=True) self.write("\\ec\\e)U\x0e\x18\x0f\\e[3h\x18\\e[3l\x18") self.expect([[(None, None, b"\x18")]], raw=True) self.write("\\ec\\e[11m\xdb\x18\\e[10m\xdb") self.expect( [[(None, "U", b"\xdb"), (None, "U", b"\x18"), (None, None, b"\xdb")]], raw=True, ) def test_set_title(self): self._the_title = None def _change_title(widget, title): self._the_title = title self.connect_signal("title") self.write("\\e]666parsed right?\\e\\te\\e]0;test title\007st1") self.expect("test1") self.expect_signal("test title") self.write("\\e];stupid title\\e\\\\e[0G\\e[2Ktest2") self.expect("test2") self.expect_signal("stupid title") self.disconnect_signal("title") def test_set_leds(self): self.connect_signal("leds") self.write(r"\e[0qtest1") self.expect("test1") self.expect_signal("clear") self.write(r"\e[3q\e[H\e[Ktest2") self.expect("test2") self.expect_signal("caps_lock") self.disconnect_signal("leds") def test_in_listbox(self): listbox = urwid.ListBox([urwid.BoxAdapter(self.term, 80)]) rendered = listbox.render((80, 24)) def test_bracketed_paste_mode_on(self): self.write(r"\e[?2004htest") self.expect("test") self.assertTrue(self.term.term_modes.bracketed_paste) self.term.keypress(None, "begin paste") self.term.keypress(None, "A") self.term.keypress(None, "end paste") sleep(0.1) self.expect(r"test^[[200~A^[[201~") def test_bracketed_paste_mode_off(self): self.write(r"\e[?2004ltest") self.expect("test") self.assertFalse(self.term.term_modes.bracketed_paste) self.term.keypress(None, "begin paste") self.term.keypress(None, "B") self.term.keypress(None, "end paste") sleep(0.1) self.expect(r"testB")
14,548
Python
.py
331
35.613293
116
0.581966
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,231
signals.py
urwid_urwid/urwid/signals.py
# Urwid signal dispatching # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import itertools import typing import warnings import weakref if typing.TYPE_CHECKING: from collections.abc import Callable, Collection, Container, Hashable, Iterable class MetaSignals(type): """ register the list of signals in the class variable signals, including signals in superclasses. """ def __init__(cls, name: str, bases: tuple[type, ...], d: dict[str, typing.Any]) -> None: signals = d.get("signals", []) for superclass in cls.__bases__: signals.extend(getattr(superclass, "signals", [])) signals = list(dict.fromkeys(signals).keys()) d["signals"] = signals register_signal(cls, signals) super().__init__(name, bases, d) def setdefaultattr(obj, name, value): # like dict.setdefault() for object attributes if hasattr(obj, name): return getattr(obj, name) setattr(obj, name, value) return value class Key: """ Minimal class, whose only purpose is to produce objects with a unique hash """ __slots__ = () class Signals: _signal_attr = "_urwid_signals" # attribute to attach to signal senders def __init__(self) -> None: self._supported = {} def register(self, sig_cls, signals: Container[Hashable]) -> None: """ :param sig_cls: the class of an object that will be sending signals :type sig_cls: class :param signals: a list of signals that may be sent, typically each signal is represented by a string :type signals: signal names This function must be called for a class before connecting any signal callbacks or emitting any signals from that class' objects """ self._supported[sig_cls] = signals def connect( self, obj, name: Hashable, callback: Callable[..., typing.Any], user_arg: typing.Any = None, *, weak_args: Iterable[typing.Any] = (), user_args: Iterable[typing.Any] = (), ) -> Key: """ :param obj: the object sending a signal :type obj: object :param name: the signal to listen for, typically a string :type name: signal name :param callback: the function to call when that signal is sent :type callback: function :param user_arg: deprecated additional argument to callback (appended after the arguments passed when the signal is emitted). If None no arguments will be added. Don't use this argument, use user_args instead. :param weak_args: additional arguments passed to the callback (before any arguments passed when the signal is emitted and before any user_args). These arguments are stored as weak references (but converted back into their original value before passing them to callback) to prevent any objects referenced (indirectly) from weak_args from being kept alive just because they are referenced by this signal handler. Use this argument only as a keyword argument, since user_arg might be removed in the future. :type weak_args: iterable :param user_args: additional arguments to pass to the callback, (before any arguments passed when the signal is emitted but after any weak_args). Use this argument only as a keyword argument, since user_arg might be removed in the future. :type user_args: iterable When a matching signal is sent, callback will be called. The arguments it receives will be the user_args passed at connect time (as individual arguments) followed by all the positional parameters sent with the signal. As an example of using weak_args, consider the following snippet: >>> import urwid >>> debug = urwid.Text('') >>> def handler(widget, newtext): ... debug.set_text("Edit widget changed to %s" % newtext) >>> edit = urwid.Edit('') >>> key = urwid.connect_signal(edit, 'change', handler) If you now build some interface using "edit" and "debug", the "debug" widget will show whatever you type in the "edit" widget. However, if you remove all references to the "debug" widget, it will still be kept alive by the signal handler. This because the signal handler is a closure that (implicitly) references the "edit" widget. If you want to allow the "debug" widget to be garbage collected, you can create a "fake" or "weak" closure (it's not really a closure, since it doesn't reference any outside variables, so it's just a dynamic function): >>> debug = urwid.Text('') >>> def handler(weak_debug, widget, newtext): ... weak_debug.set_text("Edit widget changed to %s" % newtext) >>> edit = urwid.Edit('') >>> key = urwid.connect_signal(edit, 'change', handler, weak_args=[debug]) Here the weak_debug parameter in print_debug is the value passed in the weak_args list to connect_signal. Note that the weak_debug value passed is not a weak reference anymore, the signals code transparently dereferences the weakref parameter before passing it to print_debug. Returns a key associated by this signal handler, which can be used to disconnect the signal later on using urwid.disconnect_signal_by_key. Alternatively, the signal handler can also be disconnected by calling urwid.disconnect_signal, which doesn't need this key. """ if user_arg is not None: warnings.warn( "Don't use user_arg argument, use user_args instead.", DeprecationWarning, stacklevel=2, ) sig_cls = obj.__class__ if name not in self._supported.get(sig_cls, ()): raise NameError(f"No such signal {name!r} for object {obj!r}") # Just generate an arbitrary (but unique) key key = Key() handlers = setdefaultattr(obj, self._signal_attr, {}).setdefault(name, []) # Remove the signal handler when any of the weakref'd arguments # are garbage collected. Note that this means that the handlers # dictionary can be modified _at any time_, so it should never # be iterated directly (e.g. iterate only over .keys() and # .items(), never over .iterkeys(), .iteritems() or the object # itself). # We let the callback keep a weakref to the object as well, to # prevent a circular reference between the handler and the # object (via the weakrefs, which keep strong references to # their callbacks) from existing. obj_weak = weakref.ref(obj) def weakref_callback(weakref): # pylint: disable=redefined-outer-name # bad, but not changing API o = obj_weak() if o: self.disconnect_by_key(o, name, key) user_args = self._prepare_user_args(weak_args, user_args, weakref_callback) handlers.append((key, callback, user_arg, user_args)) return key def _prepare_user_args( self, weak_args: Iterable[typing.Any] = (), user_args: Iterable[typing.Any] = (), callback: Callable[..., typing.Any] | None = None, ) -> tuple[Collection[weakref.ReferenceType], Collection[typing.Any]]: # Turn weak_args into weakrefs and prepend them to user_args w_args = tuple(weakref.ref(w_arg, callback) for w_arg in weak_args) args = tuple(user_args) or () return (w_args, args) def disconnect( self, obj, name: Hashable, callback: Callable[..., typing.Any], user_arg: typing.Any = None, *, weak_args: Iterable[typing.Any] = (), user_args: Iterable[typing.Any] = (), ) -> None: """ :param obj: the object to disconnect the signal from :type obj: object :param name: the signal to disconnect, typically a string :type name: signal name :param callback: the callback function passed to connect_signal :type callback: function :param user_arg: the user_arg parameter passed to connect_signal :param weak_args: the weak_args parameter passed to connect_signal :param user_args: the weak_args parameter passed to connect_signal This function will remove a callback from the list connected to a signal with connect_signal(). The arguments passed should be exactly the same as those passed to connect_signal(). If the callback is not connected or already disconnected, this function will simply do nothing. """ signals = setdefaultattr(obj, self._signal_attr, {}) if name not in signals: return None handlers = signals[name] # Do the same processing as in connect, so we can compare the # resulting tuple. user_args = self._prepare_user_args(weak_args, user_args) # Remove the given handler for h in handlers: if h[1:] == (callback, user_arg, user_args): return self.disconnect_by_key(obj, name, h[0]) return None def disconnect_by_key(self, obj, name: Hashable, key: Key) -> None: """ :param obj: the object to disconnect the signal from :type obj: object :param name: the signal to disconnect, typically a string :type name: signal name :param key: the key for this signal handler, as returned by connect_signal(). :type key: Key This function will remove a callback from the list connected to a signal with connect_signal(). The key passed should be the value returned by connect_signal(). If the callback is not connected or already disconnected, this function will simply do nothing. """ handlers = setdefaultattr(obj, self._signal_attr, {}).get(name, []) handlers[:] = [h for h in handlers if h[0] is not key] def emit(self, obj, name: Hashable, *args) -> bool: """ :param obj: the object sending a signal :type obj: object :param name: the signal to send, typically a string :type name: signal name :param args: zero or more positional arguments to pass to the signal callback functions This function calls each of the callbacks connected to this signal with the args arguments as positional parameters. This function returns True if any of the callbacks returned True. """ result = False handlers = getattr(obj, self._signal_attr, {}).get(name, []) for _key, callback, user_arg, (weak_args, user_args) in handlers: result |= self._call_callback(callback, user_arg, weak_args, user_args, args) return result def _call_callback( self, callback, user_arg: typing.Any, weak_args: Collection[weakref.ReferenceType], user_args: Collection[typing.Any], emit_args: Iterable[typing.Any], ) -> bool: args_to_pass = [] for w_arg in weak_args: real_arg = w_arg() if real_arg is not None: args_to_pass.append(real_arg) else: # de-referenced return False # The deprecated user_arg argument was added to the end # instead of the beginning. args = itertools.chain(args_to_pass, user_args, emit_args, (user_arg,) if user_arg is not None else ()) return bool(callback(*args)) _signals = Signals() emit_signal = _signals.emit register_signal = _signals.register connect_signal = _signals.connect disconnect_signal = _signals.disconnect disconnect_signal_by_key = _signals.disconnect_by_key
13,174
Python
.py
277
38.155235
111
0.631579
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,232
util.py
urwid_urwid/urwid/util.py
# Urwid utility functions # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import codecs import contextlib import sys import typing import warnings from contextlib import suppress from urwid import str_util if typing.TYPE_CHECKING: from collections.abc import Generator, Iterable from types import TracebackType from typing_extensions import Literal, Protocol, Self class CanBeStopped(Protocol): def stop(self) -> None: ... def __getattr__(name: str) -> typing.Any: if hasattr(str_util, name): warnings.warn( f"Do not import {name!r} from {__package__}.{__name__}, import it from 'urwid'.", DeprecationWarning, stacklevel=3, ) return getattr(str_util, name) raise AttributeError(f"{name} is not defined in {__package__}.{__name__}") def detect_encoding() -> str: # Windows is a special case: # CMD is Unicode and non-unicode at the same time: # Unicode display support depends on C API usage and partially limited by font settings. # By default, python is distributed in "Unicode" version, and since Python version 3.8 only Unicode. # In case of curses, "windows-curses" is distributed in unicode-only. # Since Windows 10 default console font is already unicode, # in older versions maybe need to set TTF font manually to support more symbols # (this does not affect unicode IO). if sys.platform == "win32" and sys.getdefaultencoding() == "utf-8": return "utf-8" # Try to determine if using a supported double-byte encoding import locale no_set_locale = locale.getpreferredencoding(False) if no_set_locale != "ascii": # ascii is fallback locale in case of detect failed return no_set_locale # Use actual `getpreferredencoding` with public API only old_loc = locale.setlocale(locale.LC_CTYPE) # == getlocale, but not mangle data try: with suppress(locale.Error): locale.setlocale(locale.LC_CTYPE, "") # internally call private `_get_locale_encoding` return locale.getpreferredencoding(False) finally: with suppress(locale.Error): locale.setlocale(locale.LC_CTYPE, old_loc) if "detected_encoding" not in locals(): detected_encoding = detect_encoding() else: raise RuntimeError("Encoding detection broken") _target_encoding = "ascii" _use_dec_special = True def set_encoding(encoding: str) -> None: """ Set the byte encoding to assume when processing strings and the encoding to use when converting unicode strings. """ encoding = encoding.lower() global _target_encoding, _use_dec_special # noqa: PLW0603 # noqa: PLW0603 # pylint: disable=global-statement if encoding in {"utf-8", "utf8", "utf"}: str_util.set_byte_encoding("utf8") _use_dec_special = False elif encoding in { "euc-jp", # JISX 0208 only "euc-kr", "euc-cn", "euc-tw", # CNS 11643 plain 1 only "gb2312", "gbk", "big5", "cn-gb", "uhc", # these shouldn't happen, should they? "eucjp", "euckr", "euccn", "euctw", "cncb", }: str_util.set_byte_encoding("wide") _use_dec_special = True else: str_util.set_byte_encoding("narrow") _use_dec_special = True # if encoding is valid for conversion from unicode, remember it _target_encoding = "ascii" with contextlib.suppress(LookupError): if encoding: "".encode(encoding) _target_encoding = encoding def get_encoding() -> str: """Get target encoding.""" return _target_encoding @contextlib.contextmanager def set_temporary_encoding(encoding_name: str) -> Generator[None]: """Internal helper for encoding specific validation in unittests/doctests. Not exported globally. """ old_encoding = _target_encoding try: set_encoding(encoding_name) yield finally: set_encoding(old_encoding) def get_encoding_mode() -> Literal["wide", "narrow", "utf8"]: """ Get the mode Urwid is using when processing text strings. Returns 'narrow' for 8-bit encodings, 'wide' for CJK encodings or 'utf8' for UTF-8 encodings. """ return str_util.get_byte_encoding() def apply_target_encoding(s: str | bytes) -> tuple[bytes, list[tuple[Literal["U", "0"] | None, int]]]: """ Return (encoded byte string, character set rle). """ # Import locally to warranty no circular imports from urwid.display import escape if _use_dec_special and isinstance(s, str): # first convert drawing characters s = s.translate(escape.DEC_SPECIAL_CHARMAP) if isinstance(s, str): s = s.replace(escape.SI + escape.SO, "") # remove redundant shifts s = codecs.encode(s, _target_encoding, "replace") if not isinstance(s, bytes): raise TypeError(s) SO = escape.SO.encode("ascii") SI = escape.SI.encode("ascii") sis = s.split(SO) sis0 = sis[0].replace(SI, b"") sout = [] cout = [] if sis0: sout.append(sis0) cout.append((None, len(sis0))) if len(sis) == 1: return sis0, cout for sn in sis[1:]: sl = sn.split(SI, 1) if len(sl) == 1: sin = sl[0] sout.append(sin) rle_append_modify(cout, (escape.DEC_TAG, len(sin))) continue sin, son = sl son = son.replace(SI, b"") if sin: sout.append(sin) rle_append_modify(cout, (escape.DEC_TAG, len(sin))) if son: sout.append(son) rle_append_modify(cout, (None, len(son))) outstr = b"".join(sout) return outstr, cout ###################################################################### # Try to set the encoding using the one detected by the locale module set_encoding(detected_encoding) ###################################################################### def supports_unicode() -> bool: """ Return True if python is able to convert non-ascii unicode strings to the current encoding. """ return _target_encoding and _target_encoding != "ascii" def calc_trim_text( text: str | bytes, start_offs: int, end_offs: int, start_col: int, end_col: int, ) -> tuple[int, int, int, int]: """ Calculate the result of trimming text. start_offs -- offset into text to treat as screen column 0 end_offs -- offset into text to treat as the end of the line start_col -- screen column to trim at the left end_col -- screen column to trim at the right Returns (start, end, pad_left, pad_right), where: start -- resulting start offset end -- resulting end offset pad_left -- 0 for no pad or 1 for one space to be added pad_right -- 0 for no pad or 1 for one space to be added """ spos = start_offs pad_left = pad_right = 0 if start_col > 0: spos, sc = str_util.calc_text_pos(text, spos, end_offs, start_col) if sc < start_col: pad_left = 1 spos, sc = str_util.calc_text_pos(text, start_offs, end_offs, start_col + 1) run = end_col - start_col - pad_left pos, sc = str_util.calc_text_pos(text, spos, end_offs, run) if sc < run: pad_right = 1 return (spos, pos, pad_left, pad_right) def trim_text_attr_cs(text: bytes, attr, cs, start_col: int, end_col: int): """ Return ( trimmed text, trimmed attr, trimmed cs ). """ spos, epos, pad_left, pad_right = calc_trim_text(text, 0, len(text), start_col, end_col) attrtr = rle_subseg(attr, spos, epos) cstr = rle_subseg(cs, spos, epos) if pad_left: al = rle_get_at(attr, spos - 1) rle_prepend_modify(attrtr, (al, 1)) rle_prepend_modify(cstr, (None, 1)) if pad_right: al = rle_get_at(attr, epos) rle_append_modify(attrtr, (al, 1)) rle_append_modify(cstr, (None, 1)) return (b"".rjust(pad_left) + text[spos:epos] + b"".rjust(pad_right), attrtr, cstr) def rle_get_at(rle, pos: int): """ Return the attribute at offset pos. """ x = 0 if pos < 0: return None for a, run in rle: if x + run > pos: return a x += run return None def rle_subseg(rle, start: int, end: int): """Return a sub segment of a rle list.""" sub_segment = [] x = 0 for a, run in rle: if start: if start >= run: start -= run x += run continue x += start run -= start # noqa: PLW2901 start = 0 if x >= end: break if x + run > end: run = end - x # noqa: PLW2901 x += run sub_segment.append((a, run)) return sub_segment def rle_len(rle: Iterable[tuple[typing.Any, int]]) -> int: """ Return the number of characters covered by a run length encoded attribute list. """ run = 0 for v in rle: if not isinstance(v, tuple): raise TypeError(rle) _a, r = v run += r return run def rle_prepend_modify(rle, a_r) -> None: """ Append (a, r) (unpacked from *a_r*) to BEGINNING of rle. Merge with first run when possible MODIFIES rle parameter contents. Returns None. """ a, r = a_r if not rle: rle[:] = [(a, r)] else: al, run = rle[0] if a == al: rle[0] = (a, run + r) else: rle[0:0] = [(a, r)] def rle_append_modify(rle, a_r) -> None: """ Append (a, r) (unpacked from *a_r*) to the rle list rle. Merge with last run when possible. MODIFIES rle parameter contents. Returns None. """ a, r = a_r if not rle or rle[-1][0] != a: rle.append((a, r)) return _la, lr = rle[-1] rle[-1] = (a, lr + r) def rle_join_modify(rle, rle2) -> None: """ Append attribute list rle2 to rle. Merge last run of rle with first run of rle2 when possible. MODIFIES attr parameter contents. Returns None. """ if not rle2: return rle_append_modify(rle, rle2[0]) rle += rle2[1:] def rle_product(rle1, rle2): """ Merge the runs of rle1 and rle2 like this: eg. rle1 = [ ("a", 10), ("b", 5) ] rle2 = [ ("Q", 5), ("P", 10) ] rle_product: [ (("a","Q"), 5), (("a","P"), 5), (("b","P"), 5) ] rle1 and rle2 are assumed to cover the same total run. """ i1 = i2 = 1 # rle1, rle2 indexes if not rle1 or not rle2: return [] a1, r1 = rle1[0] a2, r2 = rle2[0] result = [] while r1 and r2: r = min(r1, r2) rle_append_modify(result, ((a1, a2), r)) r1 -= r if r1 == 0 and i1 < len(rle1): a1, r1 = rle1[i1] i1 += 1 r2 -= r if r2 == 0 and i2 < len(rle2): a2, r2 = rle2[i2] i2 += 1 return result def rle_factor(rle): """ Inverse of rle_product. """ rle1 = [] rle2 = [] for (a1, a2), r in rle: rle_append_modify(rle1, (a1, r)) rle_append_modify(rle2, (a2, r)) return rle1, rle2 class TagMarkupException(Exception): pass def decompose_tagmarkup(tm): """Return (text string, attribute list) for tagmarkup passed.""" tl, al = _tagmarkup_recurse(tm, None) # join as unicode or bytes based on type of first element if tl: text = tl[0][:0].join(tl) else: text = "" if al and al[-1][0] is None: del al[-1] return text, al def _tagmarkup_recurse(tm, attr): """Return (text list, attribute list) for tagmarkup passed. tm -- tagmarkup attr -- current attribute or None""" if isinstance(tm, list): # for lists recurse to process each subelement rtl = [] ral = [] for element in tm: tl, al = _tagmarkup_recurse(element, attr) if ral: # merge attributes when possible last_attr, last_run = ral[-1] top_attr, top_run = al[0] if last_attr == top_attr: ral[-1] = (top_attr, last_run + top_run) del al[0] rtl += tl ral += al return rtl, ral if isinstance(tm, tuple): # tuples mark a new attribute boundary if len(tm) != 2: raise TagMarkupException(f"Tuples must be in the form (attribute, tagmarkup): {tm!r}") attr, element = tm return _tagmarkup_recurse(element, attr) if not isinstance(tm, (str, bytes)): raise TagMarkupException(f"Invalid markup element: {tm!r}") # text return [tm], [(attr, len(tm))] def is_mouse_event(ev: tuple[str, int, int, int] | typing.Any) -> bool: return isinstance(ev, tuple) and len(ev) == 4 and "mouse" in ev[0] def is_mouse_press(ev: str) -> bool: return "press" in ev class MetaSuper(type): """adding .__super""" def __init__(cls, name: str, bases, d): super().__init__(name, bases, d) if hasattr(cls, f"_{name}__super"): raise AttributeError("Class has same name as one of its super classes") @property def _super(self): warnings.warn( f"`{name}.__super` was a deprecated feature for old python versions." f"Please use `super()` call instead.", DeprecationWarning, stacklevel=3, ) return super(cls, self) setattr(cls, f"_{name}__super", _super) def int_scale(val: int, val_range: int, out_range: int) -> int: """ Scale val in the range [0, val_range-1] to an integer in the range [0, out_range-1]. This implementation uses the "round-half-up" rounding method. >>> "%x" % int_scale(0x7, 0x10, 0x10000) '7777' >>> "%x" % int_scale(0x5f, 0x100, 0x10) '6' >>> int_scale(2, 6, 101) 40 >>> int_scale(1, 3, 4) 2 """ num = int(val * (out_range - 1) * 2 + (val_range - 1)) dem = (val_range - 1) * 2 # if num % dem == 0 then we are exactly half-way and have rounded up. return num // dem class StoppingContext(typing.ContextManager["StoppingContext"]): """Context manager that calls ``stop`` on a given object on exit. Used to make the ``start`` method on `MainLoop` and `BaseScreen` optionally act as context managers. """ __slots__ = ("_wrapped",) def __init__(self, wrapped: CanBeStopped) -> None: self._wrapped = wrapped def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self._wrapped.stop()
15,735
Python
.py
448
28.370536
115
0.596192
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,233
split_repr.py
urwid_urwid/urwid/split_repr.py
# Urwid split_repr helper functions # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations from inspect import getfullargspec def split_repr(self): """ Return a helpful description of the object using self._repr_words() and self._repr_attrs() to add to the description. This function may be used by adding code to your class like this: >>> class Foo(object): ... __repr__ = split_repr ... def _repr_words(self): ... return ["words", "here"] ... def _repr_attrs(self): ... return {'attrs': "appear too"} >>> Foo() <Foo words here attrs='appear too'> >>> class Bar(Foo): ... def _repr_words(self): ... return Foo._repr_words(self) + ["too"] ... def _repr_attrs(self): ... return dict(Foo._repr_attrs(self), barttr=42) >>> Bar() <Bar words here too attrs='appear too' barttr=42> """ alist = sorted((str(k), normalize_repr(v)) for k, v in self._repr_attrs().items()) words = self._repr_words() if not words and not alist: # if we're just going to print the classname fall back # to the previous __repr__ implementation instead return super(self.__class__, self).__repr__() if words and alist: words.append("") return f"<{self.__class__.__name__} {' '.join(words) + ' '.join([f'{k}={v}' for k, v in alist])}>" def normalize_repr(v): """ Return dictionary repr sorted by keys, leave others unchanged >>> normalize_repr({1:2,3:4,5:6,7:8}) '{1: 2, 3: 4, 5: 6, 7: 8}' >>> normalize_repr('foo') "'foo'" """ if isinstance(v, dict): items = sorted((repr(k), repr(v)) for k, v in v.items()) return f"{{{', '.join(f'{k}: {v}' for k, v in items)}}}" return repr(v) def remove_defaults(d, fn): """ Remove keys in d that are set to the default values from fn. This method is used to unclutter the _repr_attrs() return value. d will be modified by this function. Returns d. >>> class Foo(object): ... def __init__(self, a=1, b=2): ... self.values = a, b ... __repr__ = split_repr ... def _repr_words(self): ... return ["object"] ... def _repr_attrs(self): ... d = dict(a=self.values[0], b=self.values[1]) ... return remove_defaults(d, Foo.__init__) >>> Foo(42, 100) <Foo object a=42 b=100> >>> Foo(10, 2) <Foo object a=10> >>> Foo() <Foo object> """ args, varargs, varkw, defaults, _, _, _ = getfullargspec(fn) # ignore *varargs and **kwargs if varkw: del args[-1] if varargs: del args[-1] # create a dictionary of args with default values ddict = dict(zip(args[len(args) - len(defaults) :], defaults)) for k in list(d.keys()): if k in ddict and ddict[k] == d[k]: # remove values that match their defaults del d[k] return d def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
3,899
Python
.py
104
32.701923
102
0.601486
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,234
vterm.py
urwid_urwid/urwid/vterm.py
# Urwid terminal emulation widget # Copyright (C) 2010 aszlig # Copyright (C) 2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import atexit import copy import errno import fcntl import os import pty import selectors import signal import struct import sys import termios import time import traceback import typing import warnings from collections import deque from contextlib import suppress from dataclasses import dataclass from urwid import event_loop, util from urwid.canvas import Canvas from urwid.display import AttrSpec, RealTerminal from urwid.display.escape import ALT_DEC_SPECIAL_CHARS, DEC_SPECIAL_CHARS from urwid.widget import Sizing, Widget from .display.common import _BASIC_COLORS, _color_desc_256, _color_desc_true if typing.TYPE_CHECKING: from collections.abc import Callable, Iterable, Mapping, Sequence from typing_extensions import Literal EOF = b"" ESC = chr(27) ESC_B = b"\x1b" KEY_TRANSLATIONS = { "enter": "\r", "backspace": chr(127), "tab": "\t", "esc": ESC, "up": f"{ESC}[A", "down": f"{ESC}[B", "right": f"{ESC}[C", "left": f"{ESC}[D", "home": f"{ESC}[1~", "insert": f"{ESC}[2~", "delete": f"{ESC}[3~", "end": f"{ESC}[4~", "page up": f"{ESC}[5~", "page down": f"{ESC}[6~", "begin paste": f"{ESC}[200~", "end paste": f"{ESC}[201~", "f1": f"{ESC}[[A", "f2": f"{ESC}[[B", "f3": f"{ESC}[[C", "f4": f"{ESC}[[D", "f5": f"{ESC}[[E", "f6": f"{ESC}[17~", "f7": f"{ESC}[18~", "f8": f"{ESC}[19~", "f9": f"{ESC}[20~", "f10": f"{ESC}[21~", "f11": f"{ESC}[23~", "f12": f"{ESC}[24~", } KEY_TRANSLATIONS_DECCKM = { "up": f"{ESC}OA", "down": f"{ESC}OB", "right": f"{ESC}OC", "left": f"{ESC}OD", "f1": f"{ESC}OP", "f2": f"{ESC}OQ", "f3": f"{ESC}OR", "f4": f"{ESC}OS", "f5": f"{ESC}[15~", } class CSIAlias(typing.NamedTuple): alias_mark: str # can not have constructor with default first and non-default second arg alias: bytes class CSICommand(typing.NamedTuple): num_args: int default: int callback: Callable[[TermCanvas, list[int], bool], typing.Any] # return value ignored CSI_COMMANDS: dict[bytes, CSIAlias | CSICommand] = { # possible values: # None -> ignore sequence # (<minimum number of args>, <fallback if no argument>, callback) # ('alias', <symbol>) # # while callback is executed as: # callback(<instance of TermCanvas>, arguments, has_question_mark) b"@": CSICommand(1, 1, lambda s, number, q: s.insert_chars(chars=number[0])), b"A": CSICommand(1, 1, lambda s, rows, q: s.move_cursor(0, -rows[0], relative=True)), b"B": CSICommand(1, 1, lambda s, rows, q: s.move_cursor(0, rows[0], relative=True)), b"C": CSICommand(1, 1, lambda s, cols, q: s.move_cursor(cols[0], 0, relative=True)), b"D": CSICommand(1, 1, lambda s, cols, q: s.move_cursor(-cols[0], 0, relative=True)), b"E": CSICommand(1, 1, lambda s, rows, q: s.move_cursor(0, rows[0], relative_y=True)), b"F": CSICommand(1, 1, lambda s, rows, q: s.move_cursor(0, -rows[0], relative_y=True)), b"G": CSICommand(1, 1, lambda s, col, q: s.move_cursor(col[0] - 1, 0, relative_y=True)), b"H": CSICommand(2, 1, lambda s, x_y, q: s.move_cursor(x_y[1] - 1, x_y[0] - 1)), b"J": CSICommand(1, 0, lambda s, mode, q: s.csi_erase_display(mode[0])), b"K": CSICommand(1, 0, lambda s, mode, q: s.csi_erase_line(mode[0])), b"L": CSICommand(1, 1, lambda s, number, q: s.insert_lines(lines=number[0])), b"M": CSICommand(1, 1, lambda s, number, q: s.remove_lines(lines=number[0])), b"P": CSICommand(1, 1, lambda s, number, q: s.remove_chars(chars=number[0])), b"X": CSICommand( 1, 1, lambda s, number, q: s.erase(s.term_cursor, (s.term_cursor[0] + number[0] - 1, s.term_cursor[1])), ), b"a": CSIAlias("alias", b"C"), b"c": CSICommand(0, 0, lambda s, none, q: s.csi_get_device_attributes(q)), b"d": CSICommand(1, 1, lambda s, row, q: s.move_cursor(0, row[0] - 1, relative_x=True)), b"e": CSIAlias("alias", b"B"), b"f": CSIAlias("alias", b"H"), b"g": CSICommand(1, 0, lambda s, mode, q: s.csi_clear_tabstop(mode[0])), b"h": CSICommand(1, 0, lambda s, modes, q: s.csi_set_modes(modes, q)), b"l": CSICommand(1, 0, lambda s, modes, q: s.csi_set_modes(modes, q, reset=True)), b"m": CSICommand(1, 0, lambda s, attrs, q: s.csi_set_attr(attrs)), b"n": CSICommand(1, 0, lambda s, mode, q: s.csi_status_report(mode[0])), b"q": CSICommand(1, 0, lambda s, mode, q: s.csi_set_keyboard_leds(mode[0])), b"r": CSICommand(2, 0, lambda s, t_b, q: s.csi_set_scroll(t_b[0], t_b[1])), b"s": CSICommand(0, 0, lambda s, none, q: s.save_cursor()), b"u": CSICommand(0, 0, lambda s, none, q: s.restore_cursor()), b"`": CSIAlias("alias", b"G"), } CHARSET_DEFAULT: Literal[1] = 1 # type annotated exclusively for buggy IDE CHARSET_UTF8: Literal[2] = 2 @dataclass(eq=True, order=False) class TermModes: # ECMA-48 display_ctrl: bool = False insert: bool = False lfnl: bool = False # DEC private modes keys_decckm: bool = False reverse_video: bool = False constrain_scrolling: bool = False autowrap: bool = True visible_cursor: bool = True bracketed_paste: bool = False # charset stuff main_charset: Literal[1, 2] = CHARSET_DEFAULT def reset(self) -> None: # ECMA-48 self.display_ctrl = False self.insert = False self.lfnl = False # DEC private modes self.keys_decckm = False self.reverse_video = False self.constrain_scrolling = False self.autowrap = True self.visible_cursor = True # charset stuff self.main_charset = CHARSET_DEFAULT class TermCharset: __slots__ = ("_g", "_sgr_mapping", "active", "current") MAPPING: typing.ClassVar[dict[str, str | None]] = { "default": None, "vt100": "0", "ibmpc": "U", "user": None, } def __init__(self) -> None: self._g = [ "default", "vt100", ] self._sgr_mapping = False # prepare defaults self.active = 0 self.current: str | None = None self.activate(0) def define(self, g: int, charset: str) -> None: """ Redefine G'g' with new mapping. """ self._g[g] = charset self.activate(g=self.active) def activate(self, g: int) -> None: """ Activate the given charset slot. """ self.active = g self.current = self.MAPPING.get(self._g[g], None) def set_sgr_ibmpc(self) -> None: """ Set graphics rendition mapping to IBM PC CP437. """ self._sgr_mapping = True def reset_sgr_ibmpc(self) -> None: """ Reset graphics rendition mapping to IBM PC CP437. """ self._sgr_mapping = False self.activate(g=self.active) def apply_mapping(self, char: bytes) -> bytes: if self._sgr_mapping or self._g[self.active] == "ibmpc": dec_pos = DEC_SPECIAL_CHARS.find(char.decode("cp437")) if dec_pos >= 0: self.current = "0" return ALT_DEC_SPECIAL_CHARS[dec_pos].encode("cp437") self.current = "U" return char return char class TermScroller(list): """ List subclass that handles the terminal scrollback buffer, truncating it as necessary. """ SCROLLBACK_LINES = 10000 def __init__(self, iterable: Iterable[typing.Any]) -> None: warnings.warn( "`TermScroller` is deprecated. Please use `collections.deque` with non-zero `maxlen` instead.", DeprecationWarning, stacklevel=3, ) super().__init__(iterable) def trunc(self) -> None: if len(self) >= self.SCROLLBACK_LINES: self.pop(0) def append(self, obj) -> None: self.trunc() super().append(obj) def insert(self, idx: typing.SupportsIndex, obj) -> None: self.trunc() super().insert(idx, obj) def extend(self, seq) -> None: self.trunc() super().extend(seq) class TermCanvas(Canvas): cacheable = False def __init__(self, width: int, height: int, widget: Terminal) -> None: super().__init__() self.width, self.height = width, height self.widget = widget self.modes: TermModes = widget.term_modes self.has_focus = False self.scrollback_buffer: deque[list[tuple[AttrSpec | None, str | None, bytes]]] = deque(maxlen=10000) self.scrolling_up = 0 self.utf8_eat_bytes: int | None = None self.utf8_buffer = bytearray() self.escbuf = b"" self.coords["cursor"] = (0, 0, None) self.term_cursor: tuple[int, int] = (0, 0) # do not allow to shoot in the leg at `set_term_cursor` self.within_escape = False self.parsestate = 0 self.attrspec: AttrSpec | None = None self.charset = TermCharset() self.saved_cursor: tuple[int, int] | None = None self.saved_attrs: tuple[AttrSpec | None, TermCharset] | None = None self.is_rotten_cursor = False self.scrollregion_start = 0 self.scrollregion_end = self.height - 1 self.tabstops: list[int] = [] self.term: list[list[tuple[AttrSpec | None, str | None, bytes]]] = [] self.reset() def set_term_cursor(self, x: int | None = None, y: int | None = None) -> None: """ Set terminal cursor to x/y and update canvas cursor. If one or both axes are omitted, use the values of the current position. """ if x is None: x = self.term_cursor[0] if y is None: y = self.term_cursor[1] self.term_cursor = self.constrain_coords(x, y) if self.has_focus and self.modes.visible_cursor and self.scrolling_up < self.height - y: self.cursor = (x, y + self.scrolling_up) else: self.cursor = None def reset_scroll(self) -> None: """ Reset scrolling region to full terminal size. """ self.scrollregion_start = 0 self.scrollregion_end = self.height - 1 def scroll_buffer(self, up: bool = True, reset: bool = False, lines: int | None = None) -> None: """ Scroll the scrolling buffer up (up=True) or down (up=False) the given amount of lines or half the screen height. If just 'reset' is True, set the scrollbuffer view to the current terminal content. """ if reset: self.scrolling_up = 0 self.set_term_cursor() return if lines is None: lines = self.height // 2 if not up: lines = -lines maxscroll = len(self.scrollback_buffer) self.scrolling_up += lines if self.scrolling_up > maxscroll: self.scrolling_up = maxscroll elif self.scrolling_up < 0: self.scrolling_up = 0 self.set_term_cursor() def reset(self) -> None: """ Reset the terminal. """ self.escbuf = b"" self.within_escape = False self.parsestate = 0 self.attrspec = None self.charset = TermCharset() self.saved_cursor = None self.saved_attrs = None self.is_rotten_cursor = False self.reset_scroll() self.init_tabstops() # terminal modes self.modes.reset() # initialize self.term self.clear() def init_tabstops(self, extend: bool = False) -> None: tablen, mod = divmod(self.width, 8) if mod > 0: tablen += 1 if extend: while len(self.tabstops) < tablen: self.tabstops.append(1 << 0) else: self.tabstops = [1 << 0] * tablen def set_tabstop(self, x: int | None = None, remove: bool = False, clear: bool = False) -> None: if clear: for tab in range(len(self.tabstops)): self.tabstops[tab] = 0 return if x is None: x = self.term_cursor[0] div, mod = divmod(x, 8) if remove: self.tabstops[div] &= ~(1 << mod) else: self.tabstops[div] |= 1 << mod def is_tabstop(self, x: int | None = None) -> bool: if x is None: x = self.term_cursor[0] div, mod = divmod(x, 8) return (self.tabstops[div] & (1 << mod)) > 0 def empty_line(self, char: bytes = b" ") -> list[tuple[AttrSpec | None, str | None, bytes]]: return [self.empty_char(char)] * self.width def empty_char(self, char: bytes = b" ") -> tuple[AttrSpec | None, str | None, bytes]: return (self.attrspec, self.charset.current, char) def addstr(self, data: Iterable[int]) -> None: if self.width <= 0 or self.height <= 0: # not displayable, do nothing! return for byte in data: self.addbyte(byte) def resize(self, width: int, height: int) -> None: """ Resize the terminal to the given width and height. """ x, y = self.term_cursor if width > self.width: # grow for y in range(self.height): self.term[y] += [self.empty_char()] * (width - self.width) elif width < self.width: # shrink for y in range(self.height): self.term[y] = self.term[y][:width] self.width = width if height > self.height: # grow for _y in range(self.height, height): try: last_line = self.scrollback_buffer.pop() except IndexError: # nothing in scrollback buffer, append an empty line self.term.append(self.empty_line()) self.scrollregion_end += 1 continue # adjust x axis of scrollback buffer to the current width padding = self.width - len(last_line) if padding > 0: last_line += [self.empty_char()] * padding else: last_line = last_line[: self.width] self.term.insert(0, last_line) elif height < self.height: # shrink for _y in range(height, self.height): self.scrollback_buffer.append(self.term.pop(0)) self.height = height self.reset_scroll() x, y = self.constrain_coords(x, y) self.set_term_cursor(x, y) # extend tabs self.init_tabstops(extend=True) def set_g01(self, char: bytes, mod: bytes) -> None: """ Set G0 or G1 according to 'char' and modifier 'mod'. """ if self.modes.main_charset != CHARSET_DEFAULT: return if mod == b"(": g = 0 else: g = 1 if char == b"0": cset = "vt100" elif char == b"U": cset = "ibmpc" elif char == b"K": cset = "user" else: cset = "default" self.charset.define(g, cset) def parse_csi(self, char: bytes) -> None: """ Parse ECMA-48 CSI (Control Sequence Introducer) sequences. """ qmark = self.escbuf.startswith(b"?") escbuf = [] for arg in self.escbuf[1 if qmark else 0 :].split(b";"): try: num = int(arg) except ValueError: num = None escbuf.append(num) cmd_ = CSI_COMMANDS[char] if cmd_ is not None: if isinstance(cmd_, CSIAlias): csi_cmd: CSICommand = CSI_COMMANDS[cmd_.alias] # type: ignore[assignment] elif isinstance(cmd_, CSICommand): csi_cmd = cmd_ elif cmd_[0] == "alias": # fallback, hard deprecated csi_cmd = CSI_COMMANDS[CSIAlias(*cmd_).alias] else: csi_cmd = CSICommand(*cmd_) # fallback, hard deprecated number_of_args, default_value, cmd = csi_cmd while len(escbuf) < number_of_args: escbuf.append(default_value) for i in range(len(escbuf)): if escbuf[i] is None or escbuf[i] == 0: escbuf[i] = default_value with suppress(ValueError): cmd(self, escbuf, qmark) # ignore commands that don't match the # unpacked tuples in CSI_COMMANDS. def parse_noncsi(self, char: bytes, mod: bytes = b"") -> None: """ Parse escape sequences which are not CSI. """ if mod == b"#" and char == b"8": self.decaln() elif mod == b"%": # select main character set if char == b"@": self.modes.main_charset = CHARSET_DEFAULT elif char in b"G8": # 8 is obsolete and only for backwards compatibility self.modes.main_charset = CHARSET_UTF8 elif mod in {b"(", b")"}: # define G0/G1 self.set_g01(char, mod) elif char == b"M": # reverse line feed self.linefeed(reverse=True) elif char == b"D": # line feed self.linefeed() elif char == b"c": # reset terminal self.reset() elif char == b"E": # newline self.newline() elif char == b"H": # set tabstop self.set_tabstop() elif char == b"Z": # DECID self.widget.respond(f"{ESC}[?6c") elif char == b"7": # save current state self.save_cursor(with_attrs=True) elif char == b"8": # restore current state self.restore_cursor(with_attrs=True) def parse_osc(self, buf: bytes) -> None: """ Parse operating system command. """ if buf.startswith((b";", b"0;", b"2;")): # set window title self.widget.set_title(buf.decode().partition(";")[2]) def parse_escape(self, char: bytes) -> None: if self.parsestate == 1: # within CSI if char in CSI_COMMANDS: self.parse_csi(char) self.parsestate = 0 elif char in b"0123456789;" or (not self.escbuf and char == b"?"): self.escbuf += char return elif self.parsestate == 0 and char == b"]": # start of OSC self.escbuf = b"" self.parsestate = 2 return elif self.parsestate == 2 and char == b"\a": # end of OSC self.parse_osc(self.escbuf.lstrip(b"0")) elif self.parsestate == 2 and self.escbuf[-1:] + char == f"{ESC}\\".encode("iso8859-1"): # end of OSC self.parse_osc(self.escbuf[:-1].lstrip(b"0")) elif self.parsestate == 2 and self.escbuf.startswith(b"P") and len(self.escbuf) == 8: # set palette (ESC]Pnrrggbb) pass elif self.parsestate == 2 and not self.escbuf and char == b"R": # reset palette pass elif self.parsestate == 2: self.escbuf += char return elif self.parsestate == 0 and char == b"[": # start of CSI self.escbuf = b"" self.parsestate = 1 return elif self.parsestate == 0 and char in {b"%", b"#", b"(", b")"}: # non-CSI sequence self.escbuf = char self.parsestate = 3 return elif self.parsestate == 3: self.parse_noncsi(char, self.escbuf) elif char in {b"c", b"D", b"E", b"H", b"M", b"Z", b"7", b"8", b">", b"="}: self.parse_noncsi(char) self.leave_escape() def leave_escape(self) -> None: self.within_escape = False self.parsestate = 0 self.escbuf = b"" def get_utf8_len(self, bytenum: int) -> int: """ Process startbyte and return the number of bytes following it to get a valid UTF-8 multibyte sequence. bytenum -- an integer ordinal """ length = 0 while bytenum & 0x40: bytenum <<= 1 length += 1 return length def addbyte(self, byte: int) -> None: """ Parse main charset and add the processed byte(s) to the terminal state machine. byte -- an integer ordinal """ if self.modes.main_charset == CHARSET_UTF8 or util.get_encoding() == "utf8": if byte >= 0xC0: # start multibyte sequence self.utf8_eat_bytes = self.get_utf8_len(byte) self.utf8_buffer = bytearray([byte]) return if 0x80 <= byte < 0xC0 and self.utf8_eat_bytes is not None: if self.utf8_eat_bytes > 1: # continue multibyte sequence self.utf8_eat_bytes -= 1 self.utf8_buffer.append(byte) return # end multibyte sequence self.utf8_eat_bytes = None sequence = (self.utf8_buffer + bytes([byte])).decode("utf-8", "ignore") if not sequence: # invalid multibyte sequence, stop processing return char = sequence.encode(util.get_encoding(), "replace") else: self.utf8_eat_bytes = None char = bytes([byte]) else: char = bytes([byte]) self.process_char(char) def process_char(self, char: int | bytes) -> None: """ Process a single character (single- and multi-byte). char -- a byte string """ x, y = self.term_cursor if isinstance(char, int): char = char.to_bytes(1, "little") dc = self.modes.display_ctrl if char == ESC_B and self.parsestate != 2: # escape self.within_escape = True elif not dc and char == b"\r": # carriage return CR self.carriage_return() elif not dc and char == b"\x0f": # activate G0 self.charset.activate(0) elif not dc and char == b"\x0e": # activate G1 self.charset.activate(1) elif not dc and char in b"\n\v\f": # line feed LF/VT/FF self.linefeed() if self.modes.lfnl: self.carriage_return() elif not dc and char == b"\t": # char tab self.tab() elif not dc and char == b"\b": # backspace BS if x > 0: self.set_term_cursor(x - 1, y) elif not dc and char == b"\a" and self.parsestate != 2: # BEL # we need to check if we're in parsestate 2, as an OSC can be # terminated by the BEL character! self.widget.beep() elif not dc and char in b"\x18\x1a": # CAN/SUB self.leave_escape() elif not dc and char in b"\x00\x7f": # NUL/DEL pass # this is ignored elif self.within_escape: self.parse_escape(char) elif not dc and char == b"\x9b": # CSI (equivalent to "ESC [") self.within_escape = True self.escbuf = b"" self.parsestate = 1 else: self.push_cursor(char) def set_char(self, char: bytes, x: int | None = None, y: int | None = None) -> None: """ Set character of either the current cursor position or a position given by 'x' and/or 'y' to 'char'. """ if x is None: x = self.term_cursor[0] if y is None: y = self.term_cursor[1] x, y = self.constrain_coords(x, y) self.term[y][x] = (self.attrspec, self.charset.current, char) def constrain_coords(self, x: int, y: int, ignore_scrolling: bool = False) -> tuple[int, int]: """ Checks if x/y are within the terminal and returns the corrected version. If 'ignore_scrolling' is set, constrain within the full size of the screen and not within scrolling region. """ if x >= self.width: x = self.width - 1 elif x < 0: x = 0 if self.modes.constrain_scrolling and not ignore_scrolling: if y > self.scrollregion_end: y = self.scrollregion_end elif y < self.scrollregion_start: y = self.scrollregion_start else: # noqa: PLR5501 # pylint: disable=else-if-used # readability if y >= self.height: y = self.height - 1 elif y < 0: y = 0 return x, y def linefeed(self, reverse: bool = False) -> None: """ Move the cursor down (or up if reverse is True) one line but don't reset horizontal position. """ x, y = self.term_cursor if reverse: if y <= 0 < self.scrollregion_start: pass elif y == self.scrollregion_start: self.scroll(reverse=True) else: y -= 1 else: # noqa: PLR5501 # pylint: disable=else-if-used # readability if y >= self.height - 1 > self.scrollregion_end: pass elif y == self.scrollregion_end: self.scroll() else: y += 1 self.set_term_cursor(x, y) def carriage_return(self) -> None: self.set_term_cursor(0, self.term_cursor[1]) def newline(self) -> None: """ Do a carriage return followed by a line feed. """ self.carriage_return() self.linefeed() def move_cursor( self, x: int, y: int, relative_x: bool = False, relative_y: bool = False, relative: bool = False, ) -> None: """ Move cursor to position x/y while constraining terminal sizes. If 'relative' is True, x/y is relative to the current cursor position. 'relative_x' and 'relative_y' is the same but just with the corresponding axis. """ if relative: relative_y = relative_x = True if relative_x: x += self.term_cursor[0] if relative_y: y += self.term_cursor[1] elif self.modes.constrain_scrolling: y += self.scrollregion_start self.set_term_cursor(x, y) def push_char(self, char: bytes | None, x: int, y: int) -> None: """ Push one character to current position and advance cursor to x/y. """ if char is not None: char = self.charset.apply_mapping(char) if self.modes.insert: self.insert_chars(char=char) else: self.set_char(char) self.set_term_cursor(x, y) def push_cursor(self, char: bytes | None = None) -> None: """ Move cursor one character forward wrapping lines as needed. If 'char' is given, put the character into the former position. """ x, y = self.term_cursor if self.modes.autowrap: if x + 1 >= self.width and not self.is_rotten_cursor: # "rotten cursor" - this is when the cursor gets to the rightmost # position of the screen, the cursor position remains the same but # one last set_char() is allowed for that piece of sh^H^H"border". self.is_rotten_cursor = True self.push_char(char, x, y) else: x += 1 if x >= self.width and self.is_rotten_cursor: if y >= self.scrollregion_end: self.scroll() else: y += 1 x = 1 self.set_term_cursor(0, y) self.push_char(char, x, y) self.is_rotten_cursor = False else: if x + 1 < self.width: x += 1 self.is_rotten_cursor = False self.push_char(char, x, y) def save_cursor(self, with_attrs: bool = False) -> None: self.saved_cursor = tuple(self.term_cursor) if with_attrs: self.saved_attrs = (copy.copy(self.attrspec), copy.copy(self.charset)) def restore_cursor(self, with_attrs: bool = False) -> None: if self.saved_cursor is None: return x, y = self.saved_cursor self.set_term_cursor(x, y) if with_attrs and self.saved_attrs is not None: self.attrspec, self.charset = (copy.copy(self.saved_attrs[0]), copy.copy(self.saved_attrs[1])) def tab(self, tabstop: int = 8) -> None: """ Moves cursor to the next 'tabstop' filling everything in between with spaces. """ x, y = self.term_cursor while x < self.width - 1: self.set_char(b" ") x += 1 if self.is_tabstop(x): break self.is_rotten_cursor = False self.set_term_cursor(x, y) def scroll(self, reverse: bool = False) -> None: """ Append a new line at the bottom and put the topmost line into the scrollback buffer. If reverse is True, do exactly the opposite, but don't save into scrollback buffer. """ if reverse: self.term.pop(self.scrollregion_end) self.term.insert(self.scrollregion_start, self.empty_line()) else: killed = self.term.pop(self.scrollregion_start) self.scrollback_buffer.append(killed) self.term.insert(self.scrollregion_end, self.empty_line()) def decaln(self) -> None: """ DEC screen alignment test: Fill screen with E's. """ for row in range(self.height): self.term[row] = self.empty_line(b"E") def blank_line(self, row: int) -> None: """ Blank a single line at the specified row, without modifying other lines. """ self.term[row] = self.empty_line() def insert_chars( self, position: tuple[int, int] | None = None, chars: int = 1, char: bytes | None = None, ) -> None: """ Insert 'chars' number of either empty characters - or those specified by 'char' - before 'position' (or the current position if not specified) pushing subsequent characters of the line to the right without wrapping. """ if position is None: position = self.term_cursor if chars == 0: chars = 1 if char is None: char_spec = self.empty_char() else: char_spec = (self.attrspec, self.charset.current, char) x, y = position while chars > 0: self.term[y].insert(x, char_spec) self.term[y].pop() chars -= 1 def remove_chars(self, position: tuple[int, int] | None = None, chars: int = 1) -> None: """ Remove 'chars' number of empty characters from 'position' (or the current position if not specified) pulling subsequent characters of the line to the left without joining any subsequent lines. """ if position is None: position = self.term_cursor if chars == 0: chars = 1 x, y = position while chars > 0: self.term[y].pop(x) self.term[y].append(self.empty_char()) chars -= 1 def insert_lines(self, row: int | None = None, lines: int = 1) -> None: """ Insert 'lines' of empty lines after the specified row, pushing all subsequent lines to the bottom. If no 'row' is specified, the current row is used. """ if row is None: row = self.term_cursor[1] else: row = self.scrollregion_start if lines == 0: lines = 1 while lines > 0: self.term.insert(row, self.empty_line()) self.term.pop(self.scrollregion_end) lines -= 1 def remove_lines(self, row: int | None = None, lines: int = 1) -> None: """ Remove 'lines' number of lines at the specified row, pulling all subsequent lines to the top. If no 'row' is specified, the current row is used. """ if row is None: row = self.term_cursor[1] else: row = self.scrollregion_start if lines == 0: lines = 1 while lines > 0: self.term.pop(row) self.term.insert(self.scrollregion_end, self.empty_line()) lines -= 1 def erase( self, start: tuple[int, int] | tuple[int, int, bool], end: tuple[int, int] | tuple[int, int, bool], ) -> None: """ Erase a region of the terminal. The 'start' tuple (x, y) defines the starting position of the erase, while end (x, y) the last position. For example if the terminal size is 4x3, start=(1, 1) and end=(1, 2) would erase the following region: .... .XXX XX.. """ sx, sy = self.constrain_coords(*start) ex, ey = self.constrain_coords(*end) # within a single row if sy == ey: for x in range(sx, ex + 1): self.term[sy][x] = self.empty_char() return # spans multiple rows y = sy while y <= ey: if y == sy: for x in range(sx, self.width): self.term[y][x] = self.empty_char() elif y == ey: for x in range(ex + 1): self.term[y][x] = self.empty_char() else: self.blank_line(y) y += 1 def sgi_to_attrspec( self, attrs: Sequence[int], fg: int, bg: int, attributes: set[str], prev_colors: int, ) -> AttrSpec | None: """ Parse SGI sequence and return an AttrSpec representing the sequence including all earlier sequences specified as 'fg', 'bg' and 'attributes'. """ idx = 0 colors = prev_colors while idx < len(attrs): attr = attrs[idx] if 30 <= attr <= 37: fg = attr - 30 colors = max(16, colors) elif 40 <= attr <= 47: bg = attr - 40 colors = max(16, colors) # AIXTERM bright color spec # https://en.wikipedia.org/wiki/ANSI_escape_code elif 90 <= attr <= 97: fg = attr - 90 + 8 colors = max(16, colors) elif 100 <= attr <= 107: bg = attr - 100 + 8 colors = max(16, colors) elif attr in {38, 48}: if idx + 2 < len(attrs) and attrs[idx + 1] == 5: # 8 bit color specification color = attrs[idx + 2] colors = max(256, colors) if attr == 38: fg = color else: bg = color idx += 2 elif idx + 4 < len(attrs) and attrs[idx + 1] == 2: # 24 bit color specification color = (attrs[idx + 2] << 16) + (attrs[idx + 3] << 8) + attrs[idx + 4] colors = 2**24 if attr == 38: fg = color else: bg = color idx += 4 elif attr == 39: # set default foreground color fg = None elif attr == 49: # set default background color bg = None elif attr == 10: self.charset.reset_sgr_ibmpc() self.modes.display_ctrl = False elif attr in {11, 12}: self.charset.set_sgr_ibmpc() self.modes.display_ctrl = True # set attributes elif attr == 1: attributes.add("bold") elif attr == 4: attributes.add("underline") elif attr == 5: attributes.add("blink") elif attr == 7: attributes.add("standout") # unset attributes elif attr == 24: attributes.discard("underline") elif attr == 25: attributes.discard("blink") elif attr == 27: attributes.discard("standout") elif attr == 0: # clear all attributes fg = bg = None attributes.clear() idx += 1 if "bold" in attributes and colors == 16 and fg is not None and fg < 8: fg += 8 def _defaulter(color: int | None, colors: int) -> str: if color is None: return "default" # Note: we can't detect 88 color mode if color > 255 or colors == 2**24: return _color_desc_true(color) if color > 15 or colors == 256: return _color_desc_256(color) return _BASIC_COLORS[color] decoded_fg = _defaulter(fg, colors) decoded_bg = _defaulter(bg, colors) if attributes: decoded_fg = ",".join((decoded_fg, *list(attributes))) if decoded_fg == decoded_bg == "default": return None if colors: return AttrSpec(decoded_fg, decoded_bg, colors=colors) return AttrSpec(decoded_fg, decoded_bg) def csi_set_attr(self, attrs: Sequence[int]) -> None: """ Set graphics rendition. """ if attrs[-1] == 0: self.attrspec = None attributes = set() if self.attrspec is None: fg = bg = None else: # set default values from previous attrspec if "default" in self.attrspec.foreground: fg = None else: fg = self.attrspec.foreground_number if fg >= 8 and self.attrspec.colors == 16: fg -= 8 if "default" in self.attrspec.background: bg = None else: bg = self.attrspec.background_number if bg >= 8 and self.attrspec.colors == 16: bg -= 8 for attr in ("bold", "underline", "blink", "standout"): if not getattr(self.attrspec, attr): continue attributes.add(attr) attrspec = self.sgi_to_attrspec(attrs, fg, bg, attributes, self.attrspec.colors if self.attrspec else 1) if self.modes.reverse_video: self.attrspec = self.reverse_attrspec(attrspec) else: self.attrspec = attrspec def reverse_attrspec(self, attrspec: AttrSpec | None, undo: bool = False) -> AttrSpec: """ Put standout mode to the 'attrspec' given and remove it if 'undo' is True. """ if attrspec is None: attrspec = AttrSpec("default", "default") attrs = [fg.strip() for fg in attrspec.foreground.split(",")] if "standout" in attrs and undo: attrs.remove("standout") attrspec = attrspec.copy_modified(fg=",".join(attrs)) elif "standout" not in attrs and not undo: attrs.append("standout") attrspec = attrspec.copy_modified(fg=",".join(attrs)) return attrspec def reverse_video(self, undo: bool = False) -> None: """ Reverse video/scanmode (DECSCNM) by swapping fg and bg colors. """ for y in range(self.height): for x in range(self.width): char = self.term[y][x] attrs = self.reverse_attrspec(char[0], undo=undo) self.term[y][x] = (attrs,) + char[1:] def set_mode( self, mode: Literal[1, 3, 4, 5, 6, 7, 20, 25, 2004], flag: bool, qmark: bool, reset: bool, ) -> None: """ Helper method for csi_set_modes: set single mode. """ if qmark: # DEC private mode if mode == 1: # cursor keys send an ESC O prefix, rather than ESC [ self.modes.keys_decckm = flag elif mode == 3: # deccolm just clears the screen self.clear() elif mode == 5: if self.modes.reverse_video != flag: self.reverse_video(undo=not flag) self.modes.reverse_video = flag elif mode == 6: self.modes.constrain_scrolling = flag self.set_term_cursor(0, 0) elif mode == 7: self.modes.autowrap = flag elif mode == 25: self.modes.visible_cursor = flag self.set_term_cursor() elif mode == 2004: self.modes.bracketed_paste = flag else: # noqa: PLR5501 # pylint: disable=else-if-used # readability # ECMA-48 if mode == 3: self.modes.display_ctrl = flag elif mode == 4: self.modes.insert = flag elif mode == 20: self.modes.lfnl = flag def csi_set_modes(self, modes: Iterable[int], qmark: bool, reset: bool = False) -> None: """ Set (DECSET/ECMA-48) or reset modes (DECRST/ECMA-48) if reset is True. """ flag = not reset for mode in modes: self.set_mode(mode, flag, qmark, reset) def csi_set_scroll(self, top: int = 0, bottom: int = 0) -> None: """ Set scrolling region, 'top' is the line number of first line in the scrolling region. 'bottom' is the line number of bottom line. If both are set to 0, the whole screen will be used (default). """ if not top: top = 1 if not bottom: bottom = self.height if top < bottom <= self.height: self.scrollregion_start = self.constrain_coords(0, top - 1, ignore_scrolling=True)[1] self.scrollregion_end = self.constrain_coords(0, bottom - 1, ignore_scrolling=True)[1] self.set_term_cursor(0, 0) def csi_clear_tabstop(self, mode: Literal[0, 3] = 0): """ Clear tabstop at current position or if 'mode' is 3, delete all tabstops. """ if mode == 0: self.set_tabstop(remove=True) elif mode == 3: self.set_tabstop(clear=True) def csi_get_device_attributes(self, qmark: bool) -> None: """ Report device attributes (what are you?). In our case, we'll report ourself as a VT102 terminal. """ if not qmark: self.widget.respond(f"{ESC}[?6c") def csi_status_report(self, mode: Literal[5, 6]) -> None: """ Report various information about the terminal status. Information is queried by 'mode', where possible values are: 5 -> device status report 6 -> cursor position report """ if mode == 5: # terminal OK self.widget.respond(f"{ESC}[0n") elif mode == 6: x, y = self.term_cursor self.widget.respond(ESC + f"[{y + 1:d};{x + 1:d}R") def csi_erase_line(self, mode: Literal[0, 1, 2]) -> None: """ Erase current line, modes are: 0 -> erase from cursor to end of line. 1 -> erase from start of line to cursor. 2 -> erase whole line. """ x, y = self.term_cursor if mode == 0: self.erase(self.term_cursor, (self.width - 1, y)) elif mode == 1: self.erase((0, y), (x, y)) elif mode == 2: self.blank_line(y) def csi_erase_display(self, mode: Literal[0, 1, 2]) -> None: """ Erase display, modes are: 0 -> erase from cursor to end of display. 1 -> erase from start to cursor. 2 -> erase the whole display. """ if mode == 0: self.erase(self.term_cursor, (self.width - 1, self.height - 1)) if mode == 1: self.erase((0, 0), (self.term_cursor[0] - 1, self.term_cursor[1])) elif mode == 2: self.clear(cursor=self.term_cursor) def csi_set_keyboard_leds(self, mode: Literal[0, 1, 2, 3] = 0) -> None: """ Set keyboard LEDs, modes are: 0 -> clear all LEDs 1 -> set scroll lock LED 2 -> set num lock LED 3 -> set caps lock LED This currently just emits a signal, so it can be processed by another widget or the main application. """ states = { 0: "clear", 1: "scroll_lock", 2: "num_lock", 3: "caps_lock", } if mode in states: self.widget.leds(states[mode]) def clear(self, cursor: tuple[int, int] | None = None) -> None: """ Clears the whole terminal screen and resets the cursor position to (0, 0) or to the coordinates given by 'cursor'. """ self.term = [self.empty_line() for _ in range(self.height)] if cursor is None: self.set_term_cursor(0, 0) else: self.set_term_cursor(*cursor) def cols(self) -> int: return self.width def rows(self) -> int: return self.height def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = None, rows: int | None = None, attr=None, ) -> Iterable[list[tuple[object, Literal["0", "U"] | None, bytes]]]: if self.scrolling_up == 0: yield from self.term else: buf = self.scrollback_buffer + self.term yield from buf[-(self.height + self.scrolling_up) : -self.scrolling_up] def content_delta(self, other: Canvas): if other is self: return [self.cols()] * self.rows() return self.content() class Terminal(Widget): _selectable = True _sizing = frozenset([Sizing.BOX]) signals: typing.ClassVar[list[str]] = ["closed", "beep", "leds", "title", "resize"] def __init__( self, command: Sequence[str | bytes] | Callable[[], typing.Any] | None, env: Mapping[str, str] | Iterable[tuple[str, str]] | None = None, main_loop: event_loop.EventLoop | None = None, escape_sequence: str | None = None, encoding: str = "utf-8", ): """ A terminal emulator within a widget. ``command`` is the command to execute inside the terminal, provided as a list of the command followed by its arguments. If 'command' is None, the command is the current user's shell. You can also provide a callable instead of a command, which will be executed in the subprocess. ``env`` can be used to pass custom environment variables. If omitted, os.environ is used. ``main_loop`` should be provided, because the canvas state machine needs to act on input from the PTY master device. This object must have watch_file and remove_watch_file methods. ``escape_sequence`` is the urwid key symbol which should be used to break out of the terminal widget. If it's not specified, ``ctrl a`` is used. ``encoding`` specifies the encoding that is being used when local keypresses in Unicode are encoded into raw bytes. UTF-8 is used by default. Set this to the encoding of your terminal if you need to transmit characters to the spawned process in non-UTF8 encoding. Applies to Python 3.x only. .. note:: If you notice your Terminal instance is not printing unicode glyphs correctly, make sure the global encoding for urwid is set to ``utf8`` with ``urwid.set_encoding("utf8")``. See :ref:`text-encodings` for more details. """ super().__init__() self.escape_sequence: str = escape_sequence or "ctrl a" self.env = dict(env or os.environ) self.command = command or [self.env.get("SHELL", "/bin/sh")] self.encoding = encoding self.keygrab = False self.last_key: str | None = None self.response_buffer: list[str] = [] self.term_modes = TermModes() if main_loop is not None: self.main_loop = main_loop else: self.main_loop = event_loop.SelectEventLoop() self.master: int | None = None self.pid: int | None = None self.width: int | None = None self.height: int | None = None self.term: TermCanvas | None = None self.has_focus = False self.terminated = False def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None: """Return the cursor coordinates for this terminal""" if self.term is None: return None # temporarily set width/height to figure out the new cursor position # given the provided width/height orig_width, orig_height = self.term.width, self.term.height self.term.width = size[0] self.term.height = size[1] x, y = self.term.constrain_coords( self.term.term_cursor[0], self.term.term_cursor[1], ) self.term.width, self.term.height = orig_width, orig_height return (x, y) def spawn(self) -> None: env = self.env env["TERM"] = "linux" self.pid, self.master = pty.fork() if self.pid == 0: if callable(self.command): try: # noinspection PyBroadException try: self.command() except BaseException: # special case sys.stderr.write(traceback.format_exc()) sys.stderr.flush() finally: os._exit(0) else: os.execvpe(self.command[0], self.command, env) # noqa: S606 if self.main_loop is None: fcntl.fcntl(self.master, fcntl.F_SETFL, os.O_NONBLOCK) atexit.register(self.terminate) def terminate(self) -> None: if self.terminated: return self.terminated = True self.remove_watch() self.change_focus(False) if self.pid > 0: self.set_termsize(0, 0) for sig in (signal.SIGHUP, signal.SIGCONT, signal.SIGINT, signal.SIGTERM, signal.SIGKILL): try: os.kill(self.pid, sig) pid, _status = os.waitpid(self.pid, os.WNOHANG) except OSError: break if pid == 0: break time.sleep(0.1) with suppress(OSError): os.waitpid(self.pid, 0) os.close(self.master) def beep(self) -> None: self._emit("beep") def leds(self, which: Literal["clear", "scroll_lock", "num_lock", "caps_lock"]) -> None: self._emit("leds", which) def respond(self, string: str) -> None: """ Respond to the underlying application with 'string'. """ self.response_buffer.append(string) def flush_responses(self) -> None: for string in self.response_buffer: os.write(self.master, string.encode("ascii")) self.response_buffer = [] def set_termsize(self, width: int, height: int) -> None: winsize = struct.pack("HHHH", height, width, 0, 0) fcntl.ioctl(self.master, termios.TIOCSWINSZ, winsize) def touch_term(self, width: int, height: int) -> None: process_opened = False if self.pid is None: self.spawn() process_opened = True if self.width == width and self.height == height: return self.set_termsize(width, height) if not self.term: self.term = TermCanvas(width, height, self) else: self.term.resize(width, height) self.width = width self.height = height if process_opened: self.add_watch() self._emit("resize", (width, height)) def set_title(self, title) -> None: self._emit("title", title) def change_focus(self, has_focus) -> None: """ Ignore SIGINT if this widget has focus. """ if self.terminated: return self.has_focus = has_focus if self.term is not None: self.term.has_focus = has_focus self.term.set_term_cursor() if has_focus: self.old_tios = RealTerminal().tty_signal_keys() RealTerminal().tty_signal_keys(*(["undefined"] * 5)) elif hasattr(self, "old_tios"): RealTerminal().tty_signal_keys(*self.old_tios) def render(self, size: tuple[int, int], focus: bool = False) -> TermCanvas: if not self.terminated: self.change_focus(focus) width, height = size self.touch_term(width, height) if self.main_loop is None: self.feed() return self.term def add_watch(self) -> None: if self.main_loop is None: return self.main_loop.watch_file(self.master, self.feed) def remove_watch(self) -> None: if self.main_loop is None: return self.main_loop.remove_watch_file(self.master) def wait_and_feed(self, timeout: float = 1.0) -> None: with selectors.DefaultSelector() as selector: selector.register(self.master, selectors.EVENT_READ) selector.select(timeout) self.feed() def feed(self) -> None: data = EOF try: data = os.read(self.master, 4096) except OSError as e: if e.errno == errno.EIO: # EIO, child terminated data = EOF elif e.errno == errno.EWOULDBLOCK: # empty buffer return else: raise if data == EOF: self.terminate() self._emit("closed") return self.term.addstr(data) self.flush_responses() def keypress(self, size: tuple[int, int], key: str) -> str | None: if self.terminated: return key if key in {"begin paste", "end paste"}: if self.term_modes.bracketed_paste: pass # passthrough bracketed paste sequences else: # swallow bracketed paste sequences self.last_key = key return None if key == "window resize": width, height = size self.touch_term(width, height) return None if self.last_key == key == self.escape_sequence: # escape sequence pressed twice... self.last_key = key self.keygrab = True # ... so pass it to the terminal elif self.keygrab: if self.escape_sequence == key: # stop grabbing the terminal self.keygrab = False self.last_key = key return None else: if key == "page up": self.term.scroll_buffer() self.last_key = key self._invalidate() return None if key == "page down": self.term.scroll_buffer(up=False) self.last_key = key self._invalidate() return None if self.last_key == self.escape_sequence and key != self.escape_sequence: # hand down keypress directly after ungrab. self.last_key = key return key if self.escape_sequence == key: # start grabbing the terminal self.keygrab = True self.last_key = key return None if self._command_map[key] is None or key == "enter": # printable character or escape sequence means: # lock in terminal... self.keygrab = True # ... and do key processing else: # hand down keypress self.last_key = key return key self.last_key = key self.term.scroll_buffer(reset=True) if key.startswith("ctrl "): if key[-1].islower(): key = chr(ord(key[-1]) - ord("a") + 1) else: key = chr(ord(key[-1]) - ord("A") + 1) else: # noqa: PLR5501 # pylint: disable=else-if-used # readability if self.term_modes.keys_decckm and key in KEY_TRANSLATIONS_DECCKM: key = KEY_TRANSLATIONS_DECCKM[key] else: key = KEY_TRANSLATIONS.get(key, key) # ENTER transmits both a carriage return and linefeed in LF/NL mode. if self.term_modes.lfnl and key == "\r": key += "\n" os.write(self.master, key.encode(self.encoding, "ignore")) return None
58,665
Python
.py
1,501
28.409727
112
0.541662
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,235
container.py
urwid_urwid/urwid/container.py
# Urwid container widget classes # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import warnings from urwid.widget import ( Columns, ColumnsError, Frame, FrameError, GridFlow, GridFlowError, Overlay, OverlayError, Pile, PileError, WidgetContainerMixin, ) __all__ = ( "Columns", "ColumnsError", "Frame", "FrameError", "GridFlow", "GridFlowError", "Overlay", "OverlayError", "Pile", "PileError", "WidgetContainerMixin", ) warnings.warn( f"{__name__!r} is not expected to be imported directly. " 'Please use public access from "urwid" package. ' f"Module {__name__!r} is deprecated and will be removed in the future.", DeprecationWarning, stacklevel=3, )
1,589
Python
.py
53
26.830189
78
0.706536
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,236
numedit.py
urwid_urwid/urwid/numedit.py
# # Urwid basic widget classes # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import re import warnings from decimal import Decimal from typing import TYPE_CHECKING from urwid import Edit if TYPE_CHECKING: from collections.abc import Container class NumEdit(Edit): """NumEdit - edit numerical types based on the characters in 'allowed' different numerical types can be edited: + regular int: 0123456789 + regular float: 0123456789. + regular oct: 01234567 + regular hex: 0123456789abcdef """ ALLOWED = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__( self, allowed: Container[str], caption, default: str | bytes, trimLeadingZeros: bool | None = None, *, trim_leading_zeros: bool = True, allow_negative: bool = False, ): super().__init__(caption, default) self._allowed = allowed self._trim_leading_zeros = trim_leading_zeros self._allow_negative = allow_negative if trimLeadingZeros is not None: warnings.warn( "'trimLeadingZeros' argument is deprecated. Use 'trim_leading_zeros' keyword argument", DeprecationWarning, stacklevel=3, ) self._trim_leading_zeros = trimLeadingZeros def valid_char(self, ch: str) -> bool: """ Return true for allowed characters. """ if len(ch) == 1: if ch.upper() in self._allowed: return True return self._allow_negative and ch == "-" and self.edit_pos == 0 and "-" not in self.edit_text return False def keypress( self, size: tuple[int], # type: ignore[override] key: str, ) -> str | None: """ Handle editing keystrokes. Remove leading zeros. >>> e, size = NumEdit("0123456789", "", "5002"), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> assert e.edit_text == "002" >>> e.keypress(size, 'end') >>> assert e.edit_text == "2" >>> # binary only >>> e, size = NumEdit("01", "", ""), (10,) >>> assert e.edit_text == "" >>> e.keypress(size, '1') >>> e.keypress(size, '0') >>> e.keypress(size, '1') >>> assert e.edit_text == "101" >>> e, size = NumEdit("0123456789", "", "", allow_negative=True), (10,) >>> e.keypress(size, "-") >>> e.keypress(size, '1') >>> e.edit_text '-1' >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> e.edit_text '1' >>> e.keypress(size, 'end') >>> e.keypress(size, "-") '-' >>> e.edit_text '1' """ unhandled = super().keypress(size, key) if not unhandled and self._trim_leading_zeros: # trim leading zeros while self.edit_pos > 0 and self.edit_text[:1] == "0": self.set_edit_pos(self.edit_pos - 1) self.set_edit_text(self.edit_text[1:]) return unhandled class IntegerEdit(NumEdit): """Edit widget for integer values""" def __init__( self, caption="", default: int | str | Decimal | None = None, base: int = 10, *, allow_negative: bool = False, ) -> None: """ caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> assert e.edit_text == "002" >>> e.keypress(size, 'end') >>> assert e.edit_text == "2" >>> e.keypress(size, '9') >>> e.keypress(size, '0') >>> assert e.edit_text == "290" >>> e, size = IntegerEdit("", ""), (10,) >>> assert e.value() is None >>> # binary >>> e, size = IntegerEdit(u"", "1010", base=2), (10,) >>> e.keypress(size, 'end') >>> e.keypress(size, '1') >>> assert e.edit_text == "10101" >>> assert e.value() == Decimal("21") >>> # HEX >>> e, size = IntegerEdit(u"", "10", base=16), (10,) >>> e.keypress(size, 'end') >>> e.keypress(size, 'F') >>> e.keypress(size, 'f') >>> assert e.edit_text == "10Ff" >>> assert e.keypress(size, 'G') == 'G' # unhandled key >>> assert e.edit_text == "10Ff" >>> # keep leading 0's when not base 10 >>> e, size = IntegerEdit(u"", "10FF", base=16), (10,) >>> assert e.edit_text == "10FF" >>> assert e.value() == Decimal("4351") >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> e.keypress(size, '0') >>> assert e.edit_text == "00FF" >>> # test exception on incompatible value for base >>> e, size = IntegerEdit(u"", "10FG", base=16), (10,) Traceback (most recent call last): ... ValueError: invalid value: 10FG for base 16 >>> # test exception on float init value >>> e, size = IntegerEdit(u"", 10.0), (10,) Traceback (most recent call last): ... ValueError: default: Only 'str', 'int', 'long' or Decimal input allowed >>> e, size = IntegerEdit(u"", Decimal("10.0")), (10,) Traceback (most recent call last): ... ValueError: not an 'integer Decimal' instance """ self.base = base val = "" allowed_chars = self.ALLOWED[: self.base] if default is not None: if not isinstance(default, (int, str, Decimal)): raise ValueError("default: Only 'str', 'int' or Decimal input allowed") # convert to a long first, this will raise a ValueError # in case a float is passed or some other error if isinstance(default, str) and len(default): # check if it is a valid initial value validation_re = f"^[{allowed_chars}]+$" if not re.match(validation_re, str(default), re.IGNORECASE): raise ValueError(f"invalid value: {default} for base {base}") elif isinstance(default, Decimal) and default.as_tuple()[2] != 0: # a Decimal instance with no fractional part raise ValueError("not an 'integer Decimal' instance") # convert possible int, long or Decimal to str val = str(default) super().__init__( allowed_chars, caption, val, trim_leading_zeros=(self.base == 10), allow_negative=allow_negative, ) def value(self) -> Decimal | None: """ Return the numeric value of self.edit_text. >>> e, size = IntegerEdit(), (10,) >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> assert e.value() == 51 """ if self.edit_text: return Decimal(int(self.edit_text, self.base)) return None def __int__(self) -> int: """Enforced int value return. >>> e, size = IntegerEdit(allow_negative=True), (10,) >>> assert int(e) == 0 >>> e.keypress(size, '-') >>> e.keypress(size, '4') >>> e.keypress(size, '2') >>> assert int(e) == -42 """ if self.edit_text: return int(self.edit_text, self.base) return 0 class FloatEdit(NumEdit): """Edit widget for float values.""" def __init__( self, caption="", default: str | int | Decimal | None = None, preserveSignificance: bool | None = None, decimalSeparator: str | None = None, *, preserve_significance: bool = True, decimal_separator: str = ".", allow_negative: bool = False, ) -> None: """ caption -- caption markup default -- default edit value preserve_significance -- return value has the same signif. as default decimal_separator -- use '.' as separator by default, optionally a ',' >>> FloatEdit(u"", "1.065434") <FloatEdit selectable flow widget '1.065434' edit_pos=8> >>> e, size = FloatEdit(u"", "1.065434"), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> assert e.edit_text == ".065434" >>> e.keypress(size, 'end') >>> e.keypress(size, 'backspace') >>> assert e.edit_text == ".06543" >>> e, size = FloatEdit(), (10,) >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> e.keypress(size, '.') >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> assert e.value() == Decimal("51.51"), e.value() >>> e, size = FloatEdit(decimal_separator=":"), (10,) Traceback (most recent call last): ... ValueError: invalid decimal separator: : >>> e, size = FloatEdit(decimal_separator=","), (10,) >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> e.keypress(size, ',') >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> assert e.edit_text == "51,51" >>> e, size = FloatEdit("", "3.1415", preserve_significance=True), (10,) >>> e.keypress(size, 'end') >>> e.keypress(size, 'backspace') >>> e.keypress(size, 'backspace') >>> assert e.edit_text == "3.14" >>> assert e.value() == Decimal("3.1400") >>> e.keypress(size, '1') >>> e.keypress(size, '5') >>> e.keypress(size, '9') >>> assert e.value() == Decimal("3.1416"), e.value() >>> e, size = FloatEdit("", ""), (10,) >>> assert e.value() is None >>> e, size = FloatEdit(u"", 10.0), (10,) Traceback (most recent call last): ... ValueError: default: Only 'str', 'int', 'long' or Decimal input allowed """ self.significance = None self._decimal_separator = decimal_separator if decimalSeparator is not None: warnings.warn( "'decimalSeparator' argument is deprecated. Use 'decimal_separator' keyword argument", DeprecationWarning, stacklevel=3, ) self._decimal_separator = decimalSeparator if self._decimal_separator not in {".", ","}: raise ValueError(f"invalid decimal separator: {self._decimal_separator}") if preserveSignificance is not None: warnings.warn( "'preserveSignificance' argument is deprecated. Use 'preserve_significance' keyword argument", DeprecationWarning, stacklevel=3, ) preserve_significance = preserveSignificance val = "" if default is not None and default != "": # noqa: PLC1901,RUF100 if not isinstance(default, (int, str, Decimal)): raise ValueError("default: Only 'str', 'int' or Decimal input allowed") if isinstance(default, str) and default: # check if it is a float, raises a ValueError otherwise float(default) default = Decimal(default) if preserve_significance and isinstance(default, Decimal): self.significance = default val = str(default) super().__init__(self.ALLOWED[0:10] + self._decimal_separator, caption, val, allow_negative=allow_negative) def value(self) -> Decimal | None: """ Return the numeric value of self.edit_text. """ if self.edit_text: normalized = Decimal(self.edit_text.replace(self._decimal_separator, ".")) if self.significance is not None: return normalized.quantize(self.significance) return normalized return None def __float__(self) -> float: """Enforced float value return. >>> e, size = FloatEdit(allow_negative=True), (10,) >>> assert float(e) == 0. >>> e.keypress(size, '-') >>> e.keypress(size, '4') >>> e.keypress(size, '.') >>> e.keypress(size, '2') >>> assert float(e) == -4.2 """ if self.edit_text: return float(self.edit_text.replace(self._decimal_separator, ".")) return 0.0
13,374
Python
.py
335
30.656716
115
0.546329
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,237
__init__.py
urwid_urwid/urwid/__init__.py
# Urwid __init__.py - all the stuff you're likely to care about # # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import importlib import sys import types import typing import warnings from urwid.canvas import ( BlankCanvas, Canvas, CanvasCache, CanvasCombine, CanvasError, CanvasJoin, CanvasOverlay, CompositeCanvas, SolidCanvas, TextCanvas, ) from urwid.command_map import ( ACTIVATE, CURSOR_DOWN, CURSOR_LEFT, CURSOR_MAX_LEFT, CURSOR_MAX_RIGHT, CURSOR_PAGE_DOWN, CURSOR_PAGE_UP, CURSOR_RIGHT, CURSOR_UP, REDRAW_SCREEN, CommandMap, command_map, ) from urwid.font import ( Font, FontRegistry, HalfBlock5x4Font, HalfBlock6x5Font, HalfBlock7x7Font, HalfBlockHeavy6x5Font, Sextant2x2Font, Sextant3x3Font, Thin3x3Font, Thin4x3Font, Thin6x6Font, get_all_fonts, ) from urwid.signals import ( MetaSignals, Signals, connect_signal, disconnect_signal, disconnect_signal_by_key, emit_signal, register_signal, ) from urwid.str_util import calc_text_pos, calc_width, is_wide_char, move_next_char, move_prev_char, within_double_byte from urwid.text_layout import LayoutSegment, StandardTextLayout, TextLayout, default_layout from urwid.util import ( MetaSuper, TagMarkupException, apply_target_encoding, calc_trim_text, decompose_tagmarkup, detected_encoding, get_encoding_mode, int_scale, is_mouse_event, set_encoding, supports_unicode, ) from urwid.version import version as __version__ from urwid.version import version_tuple as __version_tuple__ from . import display, event_loop, widget from .display import ( BLACK, BROWN, DARK_BLUE, DARK_CYAN, DARK_GRAY, DARK_GREEN, DARK_MAGENTA, DARK_RED, DEFAULT, LIGHT_BLUE, LIGHT_CYAN, LIGHT_GRAY, LIGHT_GREEN, LIGHT_MAGENTA, LIGHT_RED, UPDATE_PALETTE_ENTRY, WHITE, YELLOW, AttrSpec, AttrSpecError, BaseScreen, RealTerminal, ScreenError, ) from .event_loop import AsyncioEventLoop, EventLoop, ExitMainLoop, MainLoop, SelectEventLoop from .widget import ( ANY, BOTTOM, BOX, CENTER, CLIP, ELLIPSIS, FIXED, FLOW, GIVEN, LEFT, MIDDLE, PACK, RELATIVE, RELATIVE_100, RIGHT, SPACE, TOP, WEIGHT, Align, AttrMap, AttrMapError, AttrWrap, BarGraph, BarGraphError, BarGraphMeta, BigText, BoxAdapter, BoxAdapterError, BoxWidget, Button, CheckBox, CheckBoxError, Columns, ColumnsError, Divider, Edit, EditError, Filler, FillerError, FixedWidget, FlowWidget, Frame, FrameError, GraphVScale, GridFlow, GridFlowError, IntEdit, LineBox, ListBox, ListBoxError, ListWalker, ListWalkerError, MonitoredFocusList, MonitoredList, Overlay, OverlayError, Padding, PaddingError, ParentNode, Pile, PileError, PopUpLauncher, PopUpTarget, ProgressBar, RadioButton, Scrollable, ScrollBar, SelectableIcon, SimpleFocusListWalker, SimpleListWalker, Sizing, SolidFill, Text, TextError, TreeListBox, TreeNode, TreeWalker, TreeWidget, TreeWidgetError, VAlign, WHSettings, Widget, WidgetContainerMixin, WidgetDecoration, WidgetDisable, WidgetError, WidgetMeta, WidgetPlaceholder, WidgetWrap, WidgetWrapError, WrapMode, delegate_to_widget_mixin, fixed_size, scale_bar_values, ) # Optional event loops with external dependencies try: from .event_loop import TornadoEventLoop except ImportError: pass try: from .event_loop import GLibEventLoop except ImportError: pass try: from .event_loop import TwistedEventLoop except ImportError: pass try: from .event_loop import TrioEventLoop except ImportError: pass # OS Specific if sys.platform != "win32": from .vterm import TermCanvas, TermCharset, Terminal, TermModes, TermScroller # ZMQEventLoop cause interpreter crash on windows try: from .event_loop import ZMQEventLoop except ImportError: pass # Backward compatibility VERSION = __version_tuple__ # Moved modules handling __locals: dict[str, typing.Any] = locals() # use mutable access for pure lazy loading # Backward compatible lazy load with deprecation warnings _moved_warn: dict[str, str] = { "lcd_display": "urwid.display.lcd", "html_fragment": "urwid.display.html_fragment", "web_display": "urwid.display.web", "monitored_list": "urwid.widget.monitored_list", "listbox": "urwid.widget.listbox", "treetools": "urwid.widget.treetools", } # Backward compatible lazy load without any warnings # Before DeprecationWarning need to start PendingDeprecationWarning process. _moved_no_warn: dict[str, str] = { "display_common": "urwid.display.common", "raw_display": "urwid.display.raw", "curses_display": "urwid.display.curses", "escape": "urwid.display.escape", } class _MovedModule(types.ModuleType): """Special class to handle moved modules. PEP-0562 handles moved modules attributes, but unfortunately not handle nested modules access like "from xxx.yyy import zzz" """ __slots__ = ("_moved_from", "_moved_to") def __init__(self, moved_from: str, moved_to: str) -> None: super().__init__(moved_from.join(".")[-1]) self._moved_from = moved_from self._moved_to = moved_to def __getattr__(self, name: str) -> typing.Any: real_module = importlib.import_module(self._moved_to) sys.modules[self._moved_from] = real_module return getattr(real_module, name) class _MovedModuleWarn(_MovedModule): """Special class to handle moved modules. Produce DeprecationWarning messages for imports. """ __slots__ = () def __getattr__(self, name: str) -> typing.Any: warnings.warn( f"{self._moved_from} is moved to {self._moved_to}", DeprecationWarning, stacklevel=2, ) return super().__getattr__(name) for _name, _module in _moved_no_warn.items(): _module_path = f"{__name__}.{_name}" sys.modules[_module_path] = _MovedModule(_module_path, _module) for _name, _module in _moved_warn.items(): _module_path = f"{__name__}.{_name}" sys.modules[_module_path] = _MovedModuleWarn(_module_path, _module) def __getattr__(name: str) -> typing.Any: """Get attributes lazy. :return: attribute by name :raises AttributeError: attribute is not defined for lazy load """ if name in _moved_no_warn: mod = importlib.import_module(_moved_no_warn[name]) __locals[name] = mod return mod if name in _moved_warn: warnings.warn( f"{name} is moved to {_moved_warn[name]}", DeprecationWarning, stacklevel=2, ) mod = importlib.import_module(_moved_warn[name]) __locals[name] = mod return mod raise AttributeError(f"{name} not found in {__package__}")
8,041
Python
.py
311
21.270096
118
0.687719
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,238
canvas.py
urwid_urwid/urwid/canvas.py
# Urwid canvas class and functions # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import contextlib import dataclasses import typing import warnings import weakref from contextlib import suppress from urwid.str_util import calc_text_pos, calc_width from urwid.text_layout import LayoutSegment, trim_line from urwid.util import ( apply_target_encoding, get_encoding, rle_append_modify, rle_join_modify, rle_len, rle_product, trim_text_attr_cs, ) if typing.TYPE_CHECKING: from collections.abc import Hashable, Iterable, Iterator, Sequence from typing_extensions import Literal from .widget import Widget class CanvasCache: """ Cache for rendered canvases. Automatically populated and accessed by Widget render() MetaClass magic, cleared by Widget._invalidate(). Stores weakrefs to the canvas objects, so an external class must maintain a reference for this cache to be effective. At present the Screen classes store the last topmost canvas after redrawing the screen, keeping the canvases from being garbage collected. _widgets[widget] = {(wcls, size, focus): weakref.ref(canvas), ...} _refs[weakref.ref(canvas)] = (widget, wcls, size, focus) _deps[widget} = [dependent_widget, ...] """ _widgets: typing.ClassVar[ dict[ Widget, dict[ tuple[type[Widget], tuple[int, int] | tuple[int] | tuple[()], bool], weakref.ReferenceType, ], ] ] = {} _refs: typing.ClassVar[ dict[ weakref.ReferenceType, tuple[Widget, type[Widget], tuple[int, int] | tuple[int] | tuple[()], bool], ] ] = {} _deps: typing.ClassVar[dict[Widget, list[Widget]]] = {} hits = 0 fetches = 0 cleanups = 0 @classmethod def store(cls, wcls, canvas: Canvas) -> None: """ Store a weakref to canvas in the cache. wcls -- widget class that contains render() function canvas -- rendered canvas with widget_info (widget, size, focus) """ if not canvas.cacheable: return if not canvas.widget_info: raise TypeError("Can't store canvas without widget_info") widget, size, focus = canvas.widget_info def walk_depends(canv): """ Collect all child widgets for determining who we depend on. """ # FIXME: is this recursion necessary? The cache invalidating might work with only one level. depends = [] for _x, _y, c, _pos in canv.children: if c.widget_info: depends.append(c.widget_info[0]) elif hasattr(c, "children"): depends.extend(walk_depends(c)) return depends # use explicit depends_on if available from the canvas depends_on = getattr(canvas, "depends_on", None) if depends_on is None and hasattr(canvas, "children"): depends_on = walk_depends(canvas) if depends_on: for w in depends_on: if w not in cls._widgets: return for w in depends_on: cls._deps.setdefault(w, []).append(widget) ref = weakref.ref(canvas, cls.cleanup) cls._refs[ref] = (widget, wcls, size, focus) cls._widgets.setdefault(widget, {})[wcls, size, focus] = ref @classmethod def fetch(cls, widget, wcls, size, focus) -> Canvas | None: """ Return the cached canvas or None. widget -- widget object requested wcls -- widget class that contains render() function size, focus -- render() parameters """ cls.fetches += 1 # collect stats sizes = cls._widgets.get(widget, None) if not sizes: return None ref = sizes.get((wcls, size, focus), None) if not ref: return None canv = ref() if canv: cls.hits += 1 # more stats return canv @classmethod def invalidate(cls, widget): """ Remove all canvases cached for widget. """ with contextlib.suppress(KeyError): for ref in cls._widgets[widget].values(): with suppress(KeyError): del cls._refs[ref] del cls._widgets[widget] if widget not in cls._deps: return dependants = cls._deps.get(widget, []) with suppress(KeyError): del cls._deps[widget] for w in dependants: cls.invalidate(w) @classmethod def cleanup(cls, ref: weakref.ReferenceType) -> None: cls.cleanups += 1 # collect stats w = cls._refs.get(ref, None) del cls._refs[ref] if not w: return widget, wcls, size, focus = w sizes = cls._widgets.get(widget, None) if not sizes: return with suppress(KeyError): del sizes[wcls, size, focus] if not sizes: with contextlib.suppress(KeyError): del cls._widgets[widget] del cls._deps[widget] @classmethod def clear(cls) -> None: """ Empty the cache. """ cls._widgets = {} cls._refs = {} cls._deps = {} class CanvasError(Exception): pass class Canvas: """ base class for canvases """ cacheable = True _finalized_error = CanvasError( "This canvas has been finalized. Use CompositeCanvas to wrap this canvas if you need to make changes." ) def __init__(self) -> None: """Base Canvas class""" self._widget_info = None self.coords: dict[str, tuple[int, int, tuple[Widget, int, int]] | tuple[int, int, None]] = {} self.shortcuts: dict[str, str] = {} def finalize( self, widget: Widget, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool, ) -> None: """ Mark this canvas as finalized (should not be any future changes to its content). This is required before caching the canvas. This happens automatically after a widget's 'render call returns the canvas thanks to some metaclass magic. widget -- widget that rendered this canvas size -- size parameter passed to widget's render method focus -- focus parameter passed to widget's render method """ if self.widget_info: raise self._finalized_error self._widget_info = widget, size, focus @property def widget_info(self): return self._widget_info def _get_widget_info(self): warnings.warn( f"Method `{self.__class__.__name__}._get_widget_info` is deprecated, " f"please use property `{self.__class__.__name__}.widget_info`", DeprecationWarning, stacklevel=2, ) return self.widget_info @property def text(self) -> list[bytes]: """ Return the text content of the canvas as a list of strings, one for each row. """ return [b"".join([text for (attr, cs, text) in row]) for row in self.content()] @property def decoded_text(self) -> Sequence[str]: """Decoded text content of the canvas as a sequence of strings, one for each row.""" encoding = get_encoding() return tuple(line.decode(encoding) for line in self.text) def _text_content(self): warnings.warn( f"Method `{self.__class__.__name__}._text_content` is deprecated, " f"please use property `{self.__class__.__name__}.text`", DeprecationWarning, stacklevel=2, ) return self.text def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = None, rows: int | None = None, attr=None, ) -> Iterator[list[tuple[object, Literal["0", "U"] | None, bytes]]]: raise NotImplementedError() def cols(self) -> int: raise NotImplementedError() def rows(self) -> int: raise NotImplementedError() def content_delta(self, other: Canvas): raise NotImplementedError() def get_cursor(self) -> tuple[int, int] | None: c = self.coords.get("cursor", None) if not c: return None return c[:2] # trim off data part def set_cursor(self, c: tuple[int, int] | None) -> None: if self.widget_info and self.cacheable: raise self._finalized_error if c is None: with suppress(KeyError): del self.coords["cursor"] return self.coords["cursor"] = (*c, None) # data part cursor = property(get_cursor, set_cursor) def get_pop_up(self) -> tuple[int, int, tuple[Widget, int, int]] | None: c = self.coords.get("pop up", None) if not c: return None return c def set_pop_up(self, w: Widget, left: int, top: int, overlay_width: int, overlay_height: int) -> None: """ This method adds pop-up information to the canvas. This information is intercepted by a PopUpTarget widget higher in the chain to display a pop-up at the given (left, top) position relative to the current canvas. :param w: widget to use for the pop-up :type w: widget :param left: x position for left edge of pop-up >= 0 :type left: int :param top: y position for top edge of pop-up >= 0 :type top: int :param overlay_width: width of overlay in screen columns > 0 :type overlay_width: int :param overlay_height: height of overlay in screen rows > 0 :type overlay_height: int """ if self.widget_info and self.cacheable: raise self._finalized_error self.coords["pop up"] = (left, top, (w, overlay_width, overlay_height)) def translate_coords(self, dx: int, dy: int) -> dict[str, tuple[int, int, tuple[Widget, int, int]]]: """ Return coords shifted by (dx, dy). """ d = {} for name, (x, y, data) in self.coords.items(): d[name] = (x + dx, y + dy, data) return d def __repr__(self) -> str: extra = [""] with contextlib.suppress(BaseException): extra.append(f"cols={self.cols()}") with contextlib.suppress(BaseException): extra.append(f"rows={self.rows()}") if self.cursor: extra.append(f"cursor={self.cursor}") return f"<{self.__class__.__name__} finalized={bool(self.widget_info)}{' '.join(extra)} at 0x{id(self):X}>" def __str__(self) -> str: with contextlib.suppress(BaseException): return "\n".join(self.decoded_text) return repr(self) class TextCanvas(Canvas): """ class for storing rendered text and attributes """ def __init__( self, text: list[bytes] | None = None, attr: list[list[tuple[Hashable | None, int]]] | None = None, cs: list[list[tuple[Literal["0", "U"] | None, int]]] | None = None, cursor: tuple[int, int] | None = None, maxcol: int | None = None, check_width: bool = True, ) -> None: """ text -- list of strings, one for each line attr -- list of run length encoded attributes for text cs -- list of run length encoded character set for text cursor -- (x,y) of cursor or None maxcol -- screen columns taken by this canvas check_width -- check and fix width of all lines in text """ super().__init__() if text is None: text = [] if check_width: widths = [] for t in text: if not isinstance(t, bytes): raise CanvasError( "Canvas text must be plain strings encoded in the screen's encoding", repr(text), ) widths.append(calc_width(t, 0, len(t))) else: if not isinstance(maxcol, int): raise TypeError(maxcol) widths = [maxcol] * len(text) if maxcol is None: if widths: # find maxcol ourselves maxcol = max(widths) else: maxcol = 0 if attr is None: attr = [[] for _ in range(len(text))] if cs is None: cs = [[] for _ in range(len(text))] # pad text and attr to maxcol for i in range(len(text)): w = widths[i] if w > maxcol: raise CanvasError( f"Canvas text is wider than the maxcol specified:\n" f"maxcol={maxcol!r}\n" f"widths={widths!r}\n" f"text={text!r}\n" f"urwid target encoding={get_encoding()}" ) if w < maxcol: text[i] += b"".rjust(maxcol - w) a_gap = len(text[i]) - rle_len(attr[i]) if a_gap < 0: raise CanvasError(f"Attribute extends beyond text \n{text[i]!r}\n{attr[i]!r}") if a_gap: rle_append_modify(attr[i], (None, a_gap)) cs_gap = len(text[i]) - rle_len(cs[i]) if cs_gap < 0: raise CanvasError(f"Character Set extends beyond text \n{text[i]!r}\n{cs[i]!r}") if cs_gap: rle_append_modify(cs[i], (None, cs_gap)) self._attr = attr self._cs = cs self.cursor = cursor self._text = text self._maxcol = maxcol def rows(self) -> int: """Return the number of rows in this canvas.""" return len(self._text) def cols(self) -> int: """Return the screen column width of this canvas.""" return self._maxcol def translated_coords(self, dx: int, dy: int) -> tuple[int, int] | None: """ Return cursor coords shifted by (dx, dy), or None if there is no cursor. """ if self.cursor: x, y = self.cursor return x + dx, y + dy return None def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = 0, rows: int | None = 0, attr=None, ) -> Iterator[tuple[object, Literal["0", "U"] | None, bytes]]: """ Return the canvas content as a list of rows where each row is a list of (attr, cs, text) tuples. trim_left, trim_top, cols, rows may be set by CompositeCanvas when rendering a partially obscured canvas. """ maxcol, maxrow = self.cols(), self.rows() if not cols: cols = maxcol - trim_left if not rows: rows = maxrow - trim_top if not ((0 <= trim_left < maxcol) and (cols > 0 and trim_left + cols <= maxcol)): raise ValueError(trim_left) if not ((0 <= trim_top < maxrow) and (rows > 0 and trim_top + rows <= maxrow)): raise ValueError(trim_top) if trim_top or rows < maxrow: text_attr_cs = zip( self._text[trim_top : trim_top + rows], self._attr[trim_top : trim_top + rows], self._cs[trim_top : trim_top + rows], ) else: text_attr_cs = zip(self._text, self._attr, self._cs) for text, a_row, cs_row in text_attr_cs: if trim_left or cols < self._maxcol: text, a_row, cs_row = trim_text_attr_cs( # noqa: PLW2901 text, a_row, cs_row, trim_left, trim_left + cols, ) attr_cs = rle_product(a_row, cs_row) i = 0 row = [] for (a, cs), run in attr_cs: if attr and a in attr: a = attr[a] # noqa: PLW2901 row.append((a, cs, text[i : i + run])) i += run yield row def content_delta(self, other: Canvas): """ Return the differences between other and this canvas. If other is the same object as self this will return no differences, otherwise this is the same as calling content(). """ if other is self: return [self.cols()] * self.rows() return self.content() class BlankCanvas(Canvas): """ a canvas with nothing on it, only works as part of a composite canvas since it doesn't know its own size """ def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = 0, rows: int | None = 0, attr=None, ) -> Iterator[list[tuple[object, Literal["0", "U"] | None, bytes]]]: """ return (cols, rows) of spaces with default attributes. """ def_attr = None if attr and None in attr: def_attr = attr[None] line = [(def_attr, None, b"".rjust(cols))] for _ in range(rows): yield line def cols(self) -> typing.NoReturn: raise NotImplementedError("BlankCanvas doesn't know its own size!") def rows(self) -> typing.NoReturn: raise NotImplementedError("BlankCanvas doesn't know its own size!") def content_delta(self, other: Canvas) -> typing.NoReturn: raise NotImplementedError("BlankCanvas doesn't know its own size!") blank_canvas = BlankCanvas() class SolidCanvas(Canvas): """ A canvas filled completely with a single character. """ def __init__(self, fill_char: str | bytes, cols: int, rows: int) -> None: super().__init__() end, col = calc_text_pos(fill_char, 0, len(fill_char), 1) if col != 1: raise ValueError(f"Invalid fill_char: {fill_char!r}") self._text, cs = apply_target_encoding(fill_char[:end]) self._cs = cs[0][0] self.size = cols, rows self.cursor = None def cols(self) -> int: return self.size[0] def rows(self) -> int: return self.size[1] def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = None, rows: int | None = None, attr=None, ) -> Iterator[list[tuple[object, Literal["0", "U"] | None, bytes]]]: if cols is None: cols = self.size[0] if rows is None: rows = self.size[1] def_attr = None if attr and None in attr: def_attr = attr[None] line = [(def_attr, self._cs, self._text * cols)] for _ in range(rows): yield line def content_delta(self, other): """ Return the differences between other and this canvas. """ if other is self: return [self.cols()] * self.rows() return self.content() class CompositeCanvas(Canvas): """ class for storing a combination of canvases """ def __init__(self, canv: Canvas = None) -> None: """ canv -- a Canvas object to wrap this CompositeCanvas around. if canv is a CompositeCanvas, make a copy of its contents """ # a "shard" is a (num_rows, list of cviews) tuple, one for # each cview starting in this shard # a "cview" is a tuple that defines a view of a canvas: # (trim_left, trim_top, cols, rows, attr_map, canv) # a "shard tail" is a list of tuples: # (col_gap, done_rows, content_iter, cview) # tuples that define the unfinished cviews that are part of # shards following the first shard. super().__init__() if canv is None: self.shards: list[ tuple[ int, list[tuple[int, int, int, int, dict[Hashable | None, Hashable] | None, Canvas]], ] ] = [] self.children: list[tuple[int, int, Canvas, typing.Any]] = [] else: if hasattr(canv, "shards"): self.shards = canv.shards else: self.shards = [(canv.rows(), [(0, 0, canv.cols(), canv.rows(), None, canv)])] self.children = [(0, 0, canv, None)] self.coords.update(canv.coords) for shortcut in canv.shortcuts: self.shortcuts[shortcut] = "wrap" def __repr__(self) -> str: extra = [""] with contextlib.suppress(BaseException): extra.append(f"cols={self.cols()}") with contextlib.suppress(BaseException): extra.append(f"rows={self.rows()}") if self.cursor: extra.append(f"cursor={self.cursor}") if self.children: extra.append(f"children=({', '.join(repr(canv) for _, _, canv, _ in self.children)})") return f"<{self.__class__.__name__} finalized={bool(self.widget_info)}{' '.join(extra)} at 0x{id(self):X}>" def rows(self) -> int: for r, cv in self.shards: if not isinstance(r, int): raise TypeError(r, cv) return sum(r for r, cv in self.shards) def cols(self) -> int: if not self.shards: return 0 cols = sum(cv[2] for cv in self.shards[0][1]) if not isinstance(cols, int): raise TypeError(cols) return cols def content( self, trim_left: int = 0, trim_top: int = 0, cols: int | None = None, rows: int | None = None, attr=None, ) -> Iterator[list[tuple[object, Literal["0", "U"] | None, bytes]]]: """ Return the canvas content as a list of rows where each row is a list of (attr, cs, text) tuples. """ shard_tail = [] for num_rows, cviews in self.shards: # combine shard and shard tail sbody = shard_body(cviews, shard_tail) # output rows for _ in range(num_rows): yield shard_body_row(sbody) # prepare next shard tail shard_tail = shard_body_tail(num_rows, sbody) def content_delta(self, other: Canvas): """ Return the differences between other and this canvas. """ if not hasattr(other, "shards"): yield from self.content() return shard_tail = [] for num_rows, cviews in shards_delta(self.shards, other.shards): # combine shard and shard tail sbody = shard_body(cviews, shard_tail) # output rows row = [] for _ in range(num_rows): # if whole shard is unchanged, don't keep # calling shard_body_row if len(row) != 1 or not isinstance(row[0], int): row = shard_body_row(sbody) yield row # prepare next shard tail shard_tail = shard_body_tail(num_rows, sbody) def trim(self, top: int, count: int | None = None) -> None: """Trim lines from the top and/or bottom of canvas. top -- number of lines to remove from top count -- number of lines to keep, or None for all the rest """ if top < 0: raise ValueError(f"invalid trim amount {top:d}!") if top >= self.rows(): raise ValueError(f"cannot trim {top:d} lines from {self.rows():d}!") if self.widget_info: raise self._finalized_error if top: self.shards = shards_trim_top(self.shards, top) if count == 0: self.shards = [] elif count is not None: self.shards = shards_trim_rows(self.shards, count) self.coords = self.translate_coords(0, -top) def trim_end(self, end: int) -> None: """Trim lines from the bottom of the canvas. end -- number of lines to remove from the end """ if end <= 0: raise ValueError(f"invalid trim amount {end:d}!") if end > self.rows(): raise ValueError(f"cannot trim {end:d} lines from {self.rows():d}!") if self.widget_info: raise self._finalized_error self.shards = shards_trim_rows(self.shards, self.rows() - end) def pad_trim_left_right(self, left: int, right: int) -> None: """ Pad or trim this canvas on the left and right values > 0 indicate screen columns to pad values < 0 indicate screen columns to trim """ if self.widget_info: raise self._finalized_error shards = self.shards if left < 0 or right < 0: trim_left = max(0, -left) cols = self.cols() - trim_left - max(0, -right) shards = shards_trim_sides(shards, trim_left, cols) rows = self.rows() if left > 0 or right > 0: top_rows, top_cviews = shards[0] if left > 0: new_top_cviews = [(0, 0, left, rows, None, blank_canvas), *top_cviews] else: new_top_cviews = top_cviews.copy() if right > 0: new_top_cviews.append((0, 0, right, rows, None, blank_canvas)) shards = [(top_rows, new_top_cviews)] + shards[1:] self.coords = self.translate_coords(left, 0) self.shards = shards def pad_trim_top_bottom(self, top: int, bottom: int) -> None: """ Pad or trim this canvas on the top and bottom. """ if self.widget_info: raise self._finalized_error orig_shards = self.shards if top < 0 or bottom < 0: trim_top = max(0, -top) rows = self.rows() - trim_top - max(0, -bottom) self.trim(trim_top, rows) cols = self.cols() if top > 0: self.shards = [(top, [(0, 0, cols, top, None, blank_canvas)]), *self.shards] self.coords = self.translate_coords(0, top) if bottom > 0: if orig_shards is self.shards: self.shards = self.shards[:] self.shards.append((bottom, [(0, 0, cols, bottom, None, blank_canvas)])) def overlay(self, other: CompositeCanvas, left: int, top: int) -> None: """Overlay other onto this canvas.""" if self.widget_info: raise self._finalized_error width = other.cols() height = other.rows() right = self.cols() - left - width bottom = self.rows() - top - height if right < 0: raise ValueError(f"top canvas of overlay not the size expected!{(other.cols(), left, right, width)!r}") if bottom < 0: raise ValueError(f"top canvas of overlay not the size expected!{(other.rows(), top, bottom, height)!r}") shards = self.shards top_shards = [] side_shards = self.shards bottom_shards = [] if top: side_shards = shards_trim_top(shards, top) top_shards = shards_trim_rows(shards, top) if bottom: bottom_shards = shards_trim_top(side_shards, height) side_shards = shards_trim_rows(side_shards, height) left_shards = [] right_shards = [] if left > 0: left_shards = [shards_trim_sides(side_shards, 0, left)] if right > 0: right_shards = [shards_trim_sides(side_shards, max(0, left + width), right)] if not self.rows(): middle_shards = [] elif left or right: middle_shards = shards_join((*left_shards, other.shards, *right_shards)) else: middle_shards = other.shards self.shards = top_shards + middle_shards + bottom_shards self.coords.update(other.translate_coords(left, top)) def fill_attr(self, a: Hashable) -> None: """ Apply attribute a to all areas of this canvas with default attribute currently set to None, leaving other attributes intact. """ self.fill_attr_apply({None: a}) def fill_attr_apply(self, mapping: dict[Hashable | None, Hashable]) -> None: """ Apply an attribute-mapping dictionary to the canvas. mapping -- dictionary of original-attribute:new-attribute items """ if self.widget_info: raise self._finalized_error shards = [] for num_rows, original_cviews in self.shards: new_cviews = [] for cv in original_cviews: # cv[4] == attr_map if cv[4] is None: new_cviews.append(cv[:4] + (mapping,) + cv[5:]) else: combined = mapping.copy() combined.update([(k, mapping.get(v, v)) for k, v in cv[4].items()]) new_cviews.append(cv[:4] + (combined,) + cv[5:]) shards.append((num_rows, new_cviews)) self.shards = shards def set_depends(self, widget_list: Sequence[Widget]) -> None: """ Explicitly specify the list of widgets that this canvas depends on. If any of these widgets change this canvas will have to be updated. """ if self.widget_info: raise self._finalized_error self.depends_on = widget_list def shard_body_row(sbody): """ Return one row, advancing the iterators in sbody. ** MODIFIES sbody by calling next() on its iterators ** """ row = [] for _done_rows, content_iter, cview in sbody: if content_iter: row.extend(next(content_iter)) else: # noqa: PLR5501 # pylint: disable=else-if-used # readability # need to skip this unchanged canvas if row and isinstance(row[-1], int): row[-1] += cview[2] else: row.append(cview[2]) return row def shard_body_tail(num_rows: int, sbody): """ Return a new shard tail that follows this shard body. """ shard_tail = [] col_gap = 0 for done_rows, content_iter, cview in sbody: cols, rows = cview[2:4] done_rows += num_rows # noqa: PLW2901 if done_rows == rows: col_gap += cols continue shard_tail.append((col_gap, done_rows, content_iter, cview)) col_gap = 0 return shard_tail def shards_delta(shards, other_shards): """ Yield shards1 with cviews that are the same as shards2 having canv = None. """ # pylint: disable=stop-iteration-return other_shards_iter = iter(other_shards) other_num_rows = other_cviews = None done = other_done = 0 for num_rows, cviews in shards: if other_num_rows is None: other_num_rows, other_cviews = next(other_shards_iter) while other_done < done: other_done += other_num_rows other_num_rows, other_cviews = next(other_shards_iter) if other_done > done: yield (num_rows, cviews) done += num_rows continue # top-aligned shards, compare each cview yield (num_rows, shard_cviews_delta(cviews, other_cviews)) other_done += other_num_rows other_num_rows = None done += num_rows def shard_cviews_delta(cviews, other_cviews): # pylint: disable=stop-iteration-return other_cviews_iter = iter(other_cviews) other_cv = None cols = other_cols = 0 for cv in cviews: if other_cv is None: other_cv = next(other_cviews_iter) while other_cols < cols: other_cols += other_cv[2] other_cv = next(other_cviews_iter) if other_cols > cols: yield cv cols += cv[2] continue # top-left-aligned cviews, compare them if cv[5] is other_cv[5] and cv[:5] == other_cv[:5]: yield cv[:5] + (None,) + cv[6:] else: yield cv other_cols += other_cv[2] other_cv = None cols += cv[2] def shard_body(cviews, shard_tail, create_iter: bool = True, iter_default=None): """ Return a list of (done_rows, content_iter, cview) tuples for this shard and shard tail. If a canvas in cviews is None (eg. when unchanged from shard_cviews_delta()) or if create_iter is False then no iterator is created for content_iter. iter_default is the value used for content_iter when no iterator is created. """ col = 0 body = [] # build the next shard tail cviews_iter = iter(cviews) for col_gap, done_rows, content_iter, tail_cview in shard_tail: while col_gap: try: cview = next(cviews_iter) except StopIteration: break (trim_left, trim_top, cols, rows, attr_map, canv) = cview[:6] col += cols col_gap -= cols # noqa: PLW2901 if col_gap < 0: raise CanvasError("cviews overflow gaps in shard_tail!") if create_iter and canv: new_iter = canv.content(trim_left, trim_top, cols, rows, attr_map) else: new_iter = iter_default body.append((0, new_iter, cview)) body.append((done_rows, content_iter, tail_cview)) for cview in cviews_iter: (trim_left, trim_top, cols, rows, attr_map, canv) = cview[:6] if create_iter and canv: new_iter = canv.content(trim_left, trim_top, cols, rows, attr_map) else: new_iter = iter_default body.append((0, new_iter, cview)) return body def shards_trim_top(shards, top: int): """ Return shards with top rows removed. """ if top <= 0: raise ValueError(top) shard_iter = iter(shards) shard_tail = [] # skip over shards that are completely removed for num_rows, cviews in shard_iter: if top < num_rows: break sbody = shard_body(cviews, shard_tail, False) shard_tail = shard_body_tail(num_rows, sbody) top -= num_rows else: raise CanvasError("tried to trim shards out of existence") sbody = shard_body(cviews, shard_tail, False) shard_tail = shard_body_tail(num_rows, sbody) # trim the top of this shard new_sbody = [(0, content_iter, cview_trim_top(cv, done_rows + top)) for done_rows, content_iter, cv in sbody] sbody = new_sbody new_shards = [(num_rows - top, [cv for done_rows, content_iter, cv in sbody])] # write out the rest of the shards new_shards.extend(shard_iter) return new_shards def shards_trim_rows(shards, keep_rows: int): """ Return the topmost keep_rows rows from shards. """ if keep_rows < 0: raise ValueError(keep_rows) new_shards = [] done_rows = 0 for num_rows, cviews in shards: if done_rows >= keep_rows: break new_cviews = [] for cv in cviews: if cv[3] + done_rows > keep_rows: new_cviews.append(cview_trim_rows(cv, keep_rows - done_rows)) else: new_cviews.append(cv) if num_rows + done_rows > keep_rows: new_shards.append((keep_rows - done_rows, new_cviews)) else: new_shards.append((num_rows, new_cviews)) done_rows += num_rows return new_shards def shards_trim_sides(shards, left: int, cols: int): """ Return shards with starting from column left and cols total width. """ if left < 0: raise ValueError(left) if cols <= 0: raise ValueError(cols) shard_tail = [] new_shards = [] right = left + cols for num_rows, cviews in shards: sbody = shard_body(cviews, shard_tail, False) shard_tail = shard_body_tail(num_rows, sbody) new_cviews = [] col = 0 for done_rows, _content_iter, cv in sbody: cv_cols = cv[2] next_col = col + cv_cols if done_rows or next_col <= left or col >= right: col = next_col continue if col < left: cv = cview_trim_left(cv, left - col) # noqa: PLW2901 col = left if next_col > right: cv = cview_trim_cols(cv, right - col) # noqa: PLW2901 new_cviews.append(cv) col = next_col if not new_cviews: prev_num_rows, prev_cviews = new_shards[-1] new_shards[-1] = (prev_num_rows + num_rows, prev_cviews) else: new_shards.append((num_rows, new_cviews)) return new_shards def shards_join(shard_lists): """ Return the result of joining shard lists horizontally. All shards lists must have the same number of rows. """ shards_iters = [iter(sl) for sl in shard_lists] shards_current = [next(i) for i in shards_iters] new_shards = [] while True: new_cviews = [] num_rows = min(r for r, cv in shards_current) shards_next = [] for rows, cviews in shards_current: if cviews: new_cviews.extend(cviews) shards_next.append((rows - num_rows, None)) shards_current = shards_next new_shards.append((num_rows, new_cviews)) # advance to next shards try: for i in range(len(shards_current)): if shards_current[i][0] > 0: continue shards_current[i] = next(shards_iters[i]) except StopIteration: break return new_shards def cview_trim_rows(cv, rows: int): return cv[:3] + (rows,) + cv[4:] def cview_trim_top(cv, trim: int): return (cv[0], trim + cv[1], cv[2], cv[3] - trim) + cv[4:] def cview_trim_left(cv, trim: int): return (cv[0] + trim, cv[1], cv[2] - trim) + cv[3:] def cview_trim_cols(cv, cols: int): return cv[:2] + (cols,) + cv[3:] def CanvasCombine(canvas_info: Iterable[tuple[Canvas, typing.Any, bool]]) -> CompositeCanvas: """Stack canvases in l vertically and return resulting canvas. :param canvas_info: list of (canvas, position, focus) tuples: position a value that widget.set_focus will accept or None if not allowed focus True if this canvas is the one that would be in focus if the whole widget is in focus """ clist = [(CompositeCanvas(c), p, f) for c, p, f in canvas_info] combined_canvas = CompositeCanvas() shards = [] children = [] row = 0 focus_index = 0 for n, (canv, pos, focus) in enumerate(clist): if focus: focus_index = n children.append((0, row, canv, pos)) shards.extend(canv.shards) combined_canvas.coords.update(canv.translate_coords(0, row)) for shortcut in canv.shortcuts: combined_canvas.shortcuts[shortcut] = pos row += canv.rows() if focus_index: children = [children[focus_index]] + children[:focus_index] + children[focus_index + 1 :] combined_canvas.shards = shards combined_canvas.children = children return combined_canvas def CanvasOverlay(top_c: Canvas, bottom_c: Canvas, left: int, top: int) -> CompositeCanvas: """ Overlay canvas top_c onto bottom_c at position (left, top). """ overlayed_canvas = CompositeCanvas(bottom_c) overlayed_canvas.overlay(top_c, left, top) overlayed_canvas.children = [(left, top, top_c, None), (0, 0, bottom_c, None)] overlayed_canvas.shortcuts = {} # disable background shortcuts for shortcut in top_c.shortcuts: overlayed_canvas.shortcuts[shortcut] = "fg" return overlayed_canvas def CanvasJoin(canvas_info: Iterable[tuple[Canvas, typing.Any, bool, int]]) -> CompositeCanvas: """ Join canvases in l horizontally. Return result. :param canvas_info: list of (canvas, position, focus, cols) tuples: position value that widget.set_focus will accept or None if not allowed focus True if this canvas is the one that would be in focus if the whole widget is in focus cols is the number of screen columns that this widget will require, if larger than the actual canvas.cols() value then this widget will be padded on the right. """ l2 = [] focus_item = 0 maxrow = 0 for n, (canv, pos, focus, cols) in enumerate(canvas_info): rows = canv.rows() pad_right = cols - canv.cols() if focus: focus_item = n maxrow = max(maxrow, rows) l2.append((canv, pos, pad_right, rows)) shard_lists = [] children = [] joined_canvas = CompositeCanvas() col = 0 for canv, pos, pad_right, rows in l2: composite_canvas = CompositeCanvas(canv) if pad_right: composite_canvas.pad_trim_left_right(0, pad_right) if rows < maxrow: composite_canvas.pad_trim_top_bottom(0, maxrow - rows) joined_canvas.coords.update(composite_canvas.translate_coords(col, 0)) for shortcut in composite_canvas.shortcuts: joined_canvas.shortcuts[shortcut] = pos shard_lists.append(composite_canvas.shards) children.append((col, 0, composite_canvas, pos)) col += composite_canvas.cols() if focus_item: children = [children[focus_item]] + children[:focus_item] + children[focus_item + 1 :] joined_canvas.shards = shards_join(shard_lists) joined_canvas.children = children return joined_canvas @dataclasses.dataclass class _AttrWalk: counter: int = 0 # counter for moving through elements of a offset: int = 0 # current offset into text of attr[ak] def apply_text_layout( text: str | bytes, attr: list[tuple[Hashable, int]], ls: list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]], maxcol: int, ) -> TextCanvas: t: list[bytes] = [] a: list[list[tuple[Hashable | None, int]]] = [] c: list[list[tuple[Literal["0", "U"] | None, int]]] = [] aw = _AttrWalk() def arange(start_offs: int, end_offs: int) -> list[tuple[Hashable | None, int]]: """Return an attribute list for the range of text specified.""" if start_offs < aw.offset: aw.counter = 0 aw.offset = 0 o = [] # the loop should run at least once, the '=' part ensures that while aw.offset <= end_offs: if len(attr) <= aw.counter: # run out of attributes o.append((None, end_offs - max(start_offs, aw.offset))) break at, run = attr[aw.counter] if aw.offset + run <= start_offs: # move forward through attr to find start_offs aw.counter += 1 aw.offset += run continue if end_offs <= aw.offset + run: o.append((at, end_offs - max(start_offs, aw.offset))) break o.append((at, aw.offset + run - max(start_offs, aw.offset))) aw.counter += 1 aw.offset += run return o for line_layout in ls: # trim the line to fit within maxcol line_layout = trim_line(line_layout, text, 0, maxcol) # noqa: PLW2901 line = [] linea = [] linec = [] def attrrange(start_offs: int, end_offs: int, destw: int) -> None: """ Add attributes based on attributes between start_offs and end_offs. """ # pylint: disable=cell-var-from-loop if start_offs == end_offs: [(at, run)] = arange(start_offs, end_offs) # pylint: disable=unbalanced-tuple-unpacking rle_append_modify(linea, (at, destw)) # noqa: B023 return if destw == end_offs - start_offs: for at, run in arange(start_offs, end_offs): rle_append_modify(linea, (at, run)) # noqa: B023 return # encoded version has different width o = start_offs for at, run in arange(start_offs, end_offs): if o + run == end_offs: rle_append_modify(linea, (at, destw)) # noqa: B023 return tseg = text[o : o + run] tseg, cs = apply_target_encoding(tseg) segw = rle_len(cs) rle_append_modify(linea, (at, segw)) # noqa: B023 o += run destw -= segw for seg in line_layout: # if seg is None: assert 0, ls s = LayoutSegment(seg) if s.end: tseg, cs = apply_target_encoding(text[s.offs : s.end]) line.append(tseg) attrrange(s.offs, s.end, rle_len(cs)) rle_join_modify(linec, cs) elif s.text: tseg, cs = apply_target_encoding(s.text) line.append(tseg) attrrange(s.offs, s.offs, len(tseg)) rle_join_modify(linec, cs) elif s.offs: if s.sc: line.append(b"".rjust(s.sc)) attrrange(s.offs, s.offs, s.sc) else: line.append(b"".rjust(s.sc)) linea.append((None, s.sc)) linec.append((None, s.sc)) t.append(b"".join(line)) a.append(linea) c.append(linec) return TextCanvas(t, a, c, maxcol=maxcol)
46,743
Python
.py
1,189
29.389403
116
0.563399
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,239
decoration.py
urwid_urwid/urwid/decoration.py
# Urwid widget decoration classes # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import warnings from urwid.widget import ( AttrMap, AttrMapError, AttrWrap, BoxAdapter, BoxAdapterError, Filler, FillerError, Padding, PaddingError, WidgetDecoration, WidgetDisable, WidgetPlaceholder, calculate_top_bottom_filler, normalize_valign, ) __all__ = ( "AttrMap", "AttrMapError", "AttrWrap", "BoxAdapter", "BoxAdapterError", "Filler", "FillerError", "Padding", "PaddingError", "WidgetDecoration", "WidgetDisable", "WidgetPlaceholder", "calculate_top_bottom_filler", "normalize_valign", ) warnings.warn( f"{__name__!r} is not expected to be imported directly. " 'Please use public access from "urwid" package. ' f"Module {__name__!r} is deprecated and will be removed in the future.", DeprecationWarning, stacklevel=3, )
1,772
Python
.py
59
26.694915
78
0.711189
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,240
graphics.py
urwid_urwid/urwid/graphics.py
# Urwid graphics widgets # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations from urwid.display import AttrSpec from urwid.widget import ( BarGraph, BarGraphError, BarGraphMeta, BigText, GraphVScale, LineBox, ProgressBar, Sizing, Text, Widget, fixed_size, scale_bar_values, ) __all__ = ( "BarGraph", "BarGraphError", "BarGraphMeta", "BigText", "GraphVScale", "LineBox", "ProgressBar", "scale_bar_values", ) class PythonLogo(Widget): _sizing = frozenset([Sizing.FIXED]) def __init__(self) -> None: """ Create canvas containing an ASCII version of the Python Logo and store it. """ super().__init__() blu = AttrSpec("light blue", "default") yel = AttrSpec("yellow", "default") width = 17 # fmt: off self._canvas = Text( [ (blu, " ______\n"), (blu, " _|_o__ |"), (yel, "__\n"), (blu, " | _____|"), (yel, " |\n"), (blu, " |__| "), (yel, "______|\n"), (yel, " |____o_|"), ] ).render((width,)) # fmt: on def pack(self, size=None, focus: bool = False): """ Return the size from our pre-rendered canvas. """ return self._canvas.cols(), self._canvas.rows() def render(self, size, focus: bool = False): """ Return the pre-rendered canvas. """ fixed_size(size) return self._canvas def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
2,481
Python
.py
82
24.45122
78
0.584067
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,241
text_layout.py
urwid_urwid/urwid/text_layout.py
# Urwid Text Layout classes # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import functools import typing from urwid.str_util import calc_text_pos, calc_width, get_char_width, is_wide_char, move_next_char, move_prev_char from urwid.util import calc_trim_text, get_encoding if typing.TYPE_CHECKING: from typing_extensions import Literal from urwid.widget import Align, WrapMode @functools.lru_cache(maxsize=4) def get_ellipsis_string(encoding: str) -> str: """Get ellipsis character for given encoding.""" try: return "…".encode(encoding).decode(encoding) except UnicodeEncodeError: return "..." @functools.lru_cache(maxsize=4) def _get_width(string) -> int: """Get ellipsis character width for given encoding.""" return sum(get_char_width(char) for char in string) class TextLayout: def supports_align_mode(self, align: Literal["left", "center", "right"] | Align) -> bool: """Return True if align is a supported align mode.""" return True def supports_wrap_mode(self, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode) -> bool: """Return True if wrap is a supported wrap mode.""" return True def layout( self, text: str | bytes, width: int, align: Literal["left", "center", "right"] | Align, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """ Return a layout structure for text. :param text: string in current encoding or unicode string :param width: number of screen columns available :param align: align mode for text :param wrap: wrap mode for text Layout structure is a list of line layouts, one per output line. Line layouts are lists than may contain the following tuples: * (column width of text segment, start offset, end offset) * (number of space characters to insert, offset or None) * (column width of insert text, offset, "insert text") The offset in the last two tuples is used to determine the attribute used for the inserted spaces or text respectively. The attribute used will be the same as the attribute at that text offset. If the offset is None when inserting spaces then no attribute will be used. """ raise NotImplementedError( "This function must be overridden by a real text layout class. (see StandardTextLayout)" ) class CanNotDisplayText(Exception): pass class StandardTextLayout(TextLayout): def __init__(self) -> None: # , tab_stops=(), tab_stop_every=8): pass # """ # tab_stops -- list of screen column indexes for tab stops # tab_stop_every -- repeated interval for following tab stops # """ # assert tab_stop_every is None or type(tab_stop_every)==int # if not tab_stops and tab_stop_every: # self.tab_stops = (tab_stop_every,) # self.tab_stops = tab_stops # self.tab_stop_every = tab_stop_every def supports_align_mode(self, align: Literal["left", "center", "right"] | Align) -> bool: """Return True if align is 'left', 'center' or 'right'.""" return align in {"left", "center", "right"} def supports_wrap_mode(self, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode) -> bool: """Return True if wrap is 'any', 'space', 'clip' or 'ellipsis'.""" return wrap in {"any", "space", "clip", "ellipsis"} def layout( self, text: str | bytes, width: int, align: Literal["left", "center", "right"] | Align, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """Return a layout structure for text.""" try: segs = self.calculate_text_segments(text, width, wrap) return self.align_layout(text, width, segs, wrap, align) except CanNotDisplayText: return [[]] def pack( self, maxcol: int, layout: list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]], ) -> int: """Return a minimal maxcol value that would result in the same number of lines for layout. layout must be a layout structure returned by self.layout(). """ maxwidth = 0 if not layout: raise ValueError(f"huh? empty layout?: {layout!r}") for lines in layout: lw = line_width(lines) if lw >= maxcol: return maxcol maxwidth = max(maxwidth, lw) return maxwidth def align_layout( self, text: str | bytes, width: int, segs: list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]], wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode, align: Literal["left", "center", "right"] | Align, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """Convert the layout segments to an aligned layout.""" out = [] for lines in segs: sc = line_width(lines) if sc == width or align == "left": out.append(lines) continue if align == "right": out.append([(width - sc, None), *lines]) continue if align != "center": raise ValueError(align) pad_trim_left = (width - sc + 1) // 2 out.append([(pad_trim_left, None), *lines] if pad_trim_left else lines) return out def _calculate_trimmed_segments( self, text: str | bytes, width: int, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """Calculate text segments for cases of a text trimmed (wrap is clip or ellipsis).""" segments = [] nl: str | bytes = "\n" if isinstance(text, str) else b"\n" encoding = get_encoding() ellipsis_string = get_ellipsis_string(encoding) ellipsis_width = _get_width(ellipsis_string) while width - 1 < ellipsis_width and ellipsis_string: ellipsis_string = ellipsis_string[:-1] ellipsis_width = _get_width(ellipsis_string) ellipsis_char = ellipsis_string.encode(encoding) idx = 0 while idx <= len(text): nl_pos = text.find(nl, idx) if nl_pos == -1: nl_pos = len(text) screen_columns = calc_width(text, idx, nl_pos) # trim line to max width if needed, add ellipsis if trimmed if wrap == "ellipsis" and screen_columns > width and ellipsis_width: trimmed = True start_off, end_off, pad_left, pad_right = calc_trim_text(text, idx, nl_pos, 0, width - ellipsis_width) # pad_left should be 0, because the start_col parameter was 0 (no trimming on the left) # similarly spos should not be changed from p if pad_left != 0: raise ValueError(f"Invalid padding for start column==0: {pad_left!r}") if start_off != idx: raise ValueError(f"Invalid start offset for start column==0 and position={idx!r}: {start_off!r}") screen_columns = width - 1 - pad_right else: trimmed = False end_off = nl_pos pad_right = 0 line = [] if idx != end_off: line += [(screen_columns, idx, end_off)] if trimmed: line += [(ellipsis_width, end_off, ellipsis_char)] line += [(pad_right, end_off)] segments.append(line) idx = nl_pos + 1 return segments def calculate_text_segments( self, text: str | bytes, width: int, wrap: Literal["any", "space", "clip", "ellipsis"] | WrapMode, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """ Calculate the segments of text to display given width screen columns to display them. text - unicode text or byte string to display width - number of available screen columns wrap - wrapping mode used Returns a layout structure without an alignment applied. """ if wrap in {"clip", "ellipsis"}: return self._calculate_trimmed_segments(text, width, wrap) nl, nl_o, sp_o = "\n", "\n", " " if isinstance(text, bytes): nl = b"\n" # can only find bytes in python3 bytestrings nl_o = ord(nl_o) # + an item of a bytestring is the ordinal value sp_o = ord(sp_o) segments = [] idx = 0 while idx <= len(text): # look for the next eligible line break nl_pos = text.find(nl, idx) if nl_pos == -1: nl_pos = len(text) screen_columns = calc_width(text, idx, nl_pos) if screen_columns == 0: # removed character hint segments.append([(0, nl_pos)]) idx = nl_pos + 1 continue if screen_columns <= width: # this segment fits segments.append([(screen_columns, idx, nl_pos), (0, nl_pos)]) # removed character hint idx = nl_pos + 1 continue pos, screen_columns = calc_text_pos(text, idx, nl_pos, width) if pos == idx: # pathological width=1 double-byte case raise CanNotDisplayText("Wide character will not fit in 1-column width") if wrap == "any": segments.append([(screen_columns, idx, pos)]) idx = pos continue if wrap != "space": raise ValueError(wrap) if text[pos] == sp_o: # perfect space wrap segments.append([(screen_columns, idx, pos), (0, pos)]) # removed character hint idx = pos + 1 continue if is_wide_char(text, pos): # perfect next wide segments.append([(screen_columns, idx, pos)]) idx = pos continue prev = pos while prev > idx: prev = move_prev_char(text, idx, prev) if text[prev] == sp_o: screen_columns = calc_width(text, idx, prev) line = [(0, prev)] if idx != prev: line = [(screen_columns, idx, prev), *line] segments.append(line) idx = prev + 1 break if is_wide_char(text, prev): # wrap after wide char next_char = move_next_char(text, prev, pos) screen_columns = calc_width(text, idx, next_char) segments.append([(screen_columns, idx, next_char)]) idx = next_char break else: # unwrap previous line space if possible to # fit more text (we're breaking a word anyway) if segments and (len(segments[-1]) == 2 or (len(segments[-1]) == 1 and len(segments[-1][0]) == 2)): # look for the removed space above if len(segments[-1]) == 1: [(h_sc, h_off)] = segments[-1] p_sc = 0 p_off = _p_end = h_off else: [(p_sc, p_off, _p_end), (h_sc, h_off)] = segments[-1] if p_sc < width and h_sc == 0 and text[h_off] == sp_o: # combine with the previous line del segments[-1] idx = p_off pos, screen_columns = calc_text_pos(text, idx, nl_pos, width) segments.append([(screen_columns, idx, pos)]) # check for trailing " " or "\n" idx = pos if idx < len(text) and (text[idx] in {sp_o, nl_o}): # removed character hint segments[-1].append((0, idx)) idx += 1 continue # force any char wrap segments.append([(screen_columns, idx, pos)]) idx = pos return segments ###################################### # default layout object to use default_layout = StandardTextLayout() ###################################### class LayoutSegment: def __init__(self, seg: tuple[int, int, int | bytes] | tuple[int, int | None]) -> None: """Create object from line layout segment structure""" if not isinstance(seg, tuple): raise TypeError(seg) if len(seg) not in {2, 3}: raise ValueError(seg) self.sc, self.offs = seg[:2] if not isinstance(self.sc, int): raise TypeError(self.sc) if len(seg) == 3: if not isinstance(self.offs, int): raise TypeError(self.offs) if self.sc <= 0: raise ValueError(seg) t = seg[2] if isinstance(t, bytes): self.text: bytes | None = t self.end = None else: if not isinstance(t, int): raise TypeError(t) self.text = None self.end = t else: if len(seg) != 2: raise ValueError(seg) if self.offs is not None: if self.sc < 0: raise ValueError(seg) if not isinstance(self.offs, int): raise TypeError(self.offs) self.text = self.end = None def subseg(self, text: str | bytes, start: int, end: int) -> list[tuple[int, int] | tuple[int, int, int | bytes]]: """ Return a "sub-segment" list containing segment structures that make up a portion of this segment. A list is returned to handle cases where wide characters need to be replaced with a space character at either edge so two or three segments will be returned. """ start = max(start, 0) end = min(end, self.sc) if start >= end: return [] # completely gone if self.text: # use text stored in segment (self.text) spos, epos, pad_left, pad_right = calc_trim_text(self.text, 0, len(self.text), start, end) return [(end - start, self.offs, b"".ljust(pad_left) + self.text[spos:epos] + b"".ljust(pad_right))] if self.end: # use text passed as parameter (text) spos, epos, pad_left, pad_right = calc_trim_text(text, self.offs, self.end, start, end) lines = [] if pad_left: lines.append((1, spos - 1)) lines.append((end - start - pad_left - pad_right, spos, epos)) if pad_right: lines.append((1, epos)) return lines return [(end - start, self.offs)] def line_width(segs: list[tuple[int, int, int | bytes] | tuple[int, int | None]]) -> int: """ Return the screen column width of one line of a text layout structure. This function ignores any existing shift applied to the line, represented by an (amount, None) tuple at the start of the line. """ sc = 0 seglist = segs if segs and len(segs[0]) == 2 and segs[0][1] is None: seglist = segs[1:] for s in seglist: sc += s[0] return sc def shift_line( segs: list[tuple[int, int, int | bytes] | tuple[int, int | None]], amount: int, ) -> list[tuple[int, int, int | bytes] | tuple[int, int | None]]: """ Return a shifted line from a layout structure to the left or right. segs -- line of a layout structure amount -- screen columns to shift right (+ve) or left (-ve) """ if not isinstance(amount, int): raise TypeError(amount) if segs and len(segs[0]) == 2 and segs[0][1] is None: # existing shift amount += segs[0][0] if amount: return [(amount, None)] + segs[1:] return segs[1:] if amount: return [(amount, None), *segs] return segs def trim_line( segs: list[tuple[int, int, int | bytes] | tuple[int, int | None]], text: str | bytes, start: int, end: int, ) -> list[tuple[int, int, int | bytes] | tuple[int, int | None]]: """ Return a trimmed line of a text layout structure. text -- text to which this layout structure applies start -- starting screen column end -- ending screen column """ result = [] x = 0 for seg in segs: sc = seg[0] if start or sc < 0: if start >= sc: start -= sc x += sc continue s = LayoutSegment(seg) if x + sc >= end: # can all be done at once return s.subseg(text, start, end - x) result += s.subseg(text, start, sc) start = 0 x += sc continue if x >= end: break if x + sc > end: s = LayoutSegment(seg) result += s.subseg(text, 0, end - x) break result.append(seg) return result def calc_line_pos( text: str | bytes, line_layout, pref_col: Literal["left", "right", Align.LEFT, Align.RIGHT] | int, ): """ Calculate the closest linear position to pref_col given a line layout structure. Returns None if no position found. """ closest_sc = None closest_pos = None current_sc = 0 if pref_col == "left": for seg in line_layout: s = LayoutSegment(seg) if s.offs is not None: return s.offs return None if pref_col == "right": for seg in line_layout: s = LayoutSegment(seg) if s.offs is not None: closest_pos = s s = closest_pos if s is None: return None if s.end is None: return s.offs return calc_text_pos(text, s.offs, s.end, s.sc - 1)[0] for seg in line_layout: s = LayoutSegment(seg) if s.offs is not None: if s.end is not None: if current_sc <= pref_col < current_sc + s.sc: # exact match within this segment return calc_text_pos(text, s.offs, s.end, pref_col - current_sc)[0] if current_sc <= pref_col: closest_sc = current_sc + s.sc - 1 closest_pos = s if closest_sc is None or (abs(pref_col - current_sc) < abs(pref_col - closest_sc)): # this screen column is closer closest_sc = current_sc closest_pos = s.offs if current_sc > closest_sc: # we're moving past break current_sc += s.sc if closest_pos is None or isinstance(closest_pos, int): return closest_pos # return the last positions in the segment "closest_pos" s = closest_pos return calc_text_pos(text, s.offs, s.end, s.sc - 1)[0] def calc_pos( text: str | bytes, layout: list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]], pref_col: Literal["left", "right", Align.LEFT, Align.RIGHT] | int, row: int, ) -> int: """ Calculate the closest linear position to pref_col and row given a layout structure. """ if row < 0 or row >= len(layout): raise ValueError("calculate_pos: out of layout row range") pos = calc_line_pos(text, layout[row], pref_col) if pos is not None: return pos rows_above = list(range(row - 1, -1, -1)) rows_below = list(range(row + 1, len(layout))) while rows_above and rows_below: if rows_above: r = rows_above.pop(0) pos = calc_line_pos(text, layout[r], pref_col) if pos is not None: return pos if rows_below: r = rows_below.pop(0) pos = calc_line_pos(text, layout[r], pref_col) if pos is not None: return pos return 0 def calc_coords( text: str | bytes, layout: list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]], pos: int, clamp: int = 1, ) -> tuple[int, int]: """ Calculate the coordinates closest to position pos in text with layout. text -- raw string or unicode string layout -- layout structure applied to text pos -- integer position into text clamp -- ignored right now """ closest: tuple[int, tuple[int, int]] | None = None y = 0 for line_layout in layout: x = 0 for seg in line_layout: s = LayoutSegment(seg) if s.offs is None: x += s.sc continue if s.offs == pos: return x, y if s.end is not None and s.offs <= pos < s.end: x += calc_width(text, s.offs, pos) return x, y distance = abs(s.offs - pos) if s.end is not None and s.end < pos: distance = pos - (s.end - 1) if closest is None or distance < closest[0]: # pylint: disable=unsubscriptable-object closest = distance, (x, y) x += s.sc y += 1 if closest: return closest[1] return 0, 0
22,821
Python
.py
547
30.937843
118
0.546914
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,242
str_util.py
urwid_urwid/urwid/str_util.py
# Urwid unicode character processing tables # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import re import typing import warnings import wcwidth if typing.TYPE_CHECKING: from typing_extensions import Literal SAFE_ASCII_RE = re.compile("^[ -~]*$") SAFE_ASCII_BYTES_RE = re.compile(b"^[ -~]*$") _byte_encoding: Literal["utf8", "narrow", "wide"] = "narrow" def get_char_width(char: str) -> Literal[0, 1, 2]: width = wcwidth.wcwidth(char) if width < 0: return 0 return width def get_width(o: int) -> Literal[0, 1, 2]: """Return the screen column width for unicode ordinal o.""" return get_char_width(chr(o)) def decode_one(text: bytes | str, pos: int) -> tuple[int, int]: """ Return (ordinal at pos, next position) for UTF-8 encoded text. """ lt = len(text) - pos b2 = 0 # Fallback, not changing anything b3 = 0 # Fallback, not changing anything b4 = 0 # Fallback, not changing anything try: if isinstance(text, str): b1 = ord(text[pos]) if lt > 1: b2 = ord(text[pos + 1]) if lt > 2: b3 = ord(text[pos + 2]) if lt > 3: b4 = ord(text[pos + 3]) else: b1 = text[pos] if lt > 1: b2 = text[pos + 1] if lt > 2: b3 = text[pos + 2] if lt > 3: b4 = text[pos + 3] except Exception as e: raise ValueError(f"{e}: text={text!r}, pos={pos!r}, lt={lt!r}").with_traceback(e.__traceback__) from e if not b1 & 0x80: return b1, pos + 1 error = ord("?"), pos + 1 if lt < 2: return error if b1 & 0xE0 == 0xC0: if b2 & 0xC0 != 0x80: return error o = ((b1 & 0x1F) << 6) | (b2 & 0x3F) if o < 0x80: return error return o, pos + 2 if lt < 3: return error if b1 & 0xF0 == 0xE0: if b2 & 0xC0 != 0x80: return error if b3 & 0xC0 != 0x80: return error o = ((b1 & 0x0F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F) if o < 0x800: return error return o, pos + 3 if lt < 4: return error if b1 & 0xF8 == 0xF0: if b2 & 0xC0 != 0x80: return error if b3 & 0xC0 != 0x80: return error if b4 & 0xC0 != 0x80: return error o = ((b1 & 0x07) << 18) | ((b2 & 0x3F) << 12) | ((b3 & 0x3F) << 6) | (b4 & 0x3F) if o < 0x10000: return error return o, pos + 4 return error def decode_one_uni(text: str, i: int) -> tuple[int, int]: """ decode_one implementation for unicode strings """ return ord(text[i]), i + 1 def decode_one_right(text: bytes, pos: int) -> tuple[int, int] | None: """ Return (ordinal at pos, next position) for UTF-8 encoded text. pos is assumed to be on the trailing byte of a utf-8 sequence. """ if not isinstance(text, bytes): raise TypeError(text) error = ord("?"), pos - 1 p = pos while p >= 0: if text[p] & 0xC0 != 0x80: o, _next_pos = decode_one(text, p) return o, p - 1 p -= 1 if p == p - 4: return error return None def set_byte_encoding(enc: Literal["utf8", "narrow", "wide"]) -> None: if enc not in {"utf8", "narrow", "wide"}: raise ValueError(enc) global _byte_encoding # noqa: PLW0603 # pylint: disable=global-statement _byte_encoding = enc def get_byte_encoding() -> Literal["utf8", "narrow", "wide"]: return _byte_encoding def calc_string_text_pos(text: str, start_offs: int, end_offs: int, pref_col: int) -> tuple[int, int]: """ Calculate the closest position to the screen column pref_col in text where start_offs is the offset into text assumed to be screen column 0 and end_offs is the end of the range to search. :param text: string :param start_offs: starting text position :param end_offs: ending text position :param pref_col: target column :returns: (position, actual_col) ..note:: this method is a simplified version of `wcwidth.wcswidth` and ideally should be in wcwidth package. """ if start_offs > end_offs: raise ValueError((start_offs, end_offs)) cols = 0 for idx in range(start_offs, end_offs): width = get_char_width(text[idx]) if width + cols > pref_col: return idx, cols cols += width return end_offs, cols def calc_text_pos(text: str | bytes, start_offs: int, end_offs: int, pref_col: int) -> tuple[int, int]: """ Calculate the closest position to the screen column pref_col in text where start_offs is the offset into text assumed to be screen column 0 and end_offs is the end of the range to search. text may be unicode or a byte string in the target _byte_encoding Returns (position, actual_col). """ if start_offs > end_offs: raise ValueError((start_offs, end_offs)) if isinstance(text, str): return calc_string_text_pos(text, start_offs, end_offs, pref_col) if not isinstance(text, bytes): raise TypeError(text) if _byte_encoding == "utf8": i = start_offs sc = 0 while i < end_offs: o, n = decode_one(text, i) w = get_width(o) if w + sc > pref_col: return i, sc i = n sc += w return i, sc # "wide" and "narrow" i = start_offs + pref_col if i >= end_offs: return end_offs, end_offs - start_offs if _byte_encoding == "wide" and within_double_byte(text, start_offs, i) == 2: i -= 1 return i, i - start_offs def calc_width(text: str | bytes, start_offs: int, end_offs: int) -> int: """ Return the screen column width of text between start_offs and end_offs. text may be unicode or a byte string in the target _byte_encoding Some characters are wide (take two columns) and others affect the previous character (take zero columns). Use the widths table above to calculate the screen column width of text[start_offs:end_offs] """ if start_offs > end_offs: raise ValueError((start_offs, end_offs)) if isinstance(text, str): return sum(get_char_width(char) for char in text[start_offs:end_offs]) if _byte_encoding == "utf8": try: return sum(get_char_width(char) for char in text[start_offs:end_offs].decode("utf-8")) except UnicodeDecodeError as exc: warnings.warn( "`calc_width` with text encoded to bytes can produce incorrect results" f"due to possible offset in the middle of character: {exc}", UnicodeWarning, stacklevel=2, ) i = start_offs sc = 0 while i < end_offs: o, i = decode_one(text, i) w = get_width(o) sc += w return sc # "wide", "narrow" or all printable ASCII, just return the character count return end_offs - start_offs def is_wide_char(text: str | bytes, offs: int) -> bool: """ Test if the character at offs within text is wide. text may be unicode or a byte string in the target _byte_encoding """ if isinstance(text, str): return get_char_width(text[offs]) == 2 if not isinstance(text, bytes): raise TypeError(text) if _byte_encoding == "utf8": o, _n = decode_one(text, offs) return get_width(o) == 2 if _byte_encoding == "wide": return within_double_byte(text, offs, offs) == 1 return False def move_prev_char(text: str | bytes, start_offs: int, end_offs: int) -> int: """ Return the position of the character before end_offs. """ if start_offs >= end_offs: raise ValueError((start_offs, end_offs)) if isinstance(text, str): return end_offs - 1 if not isinstance(text, bytes): raise TypeError(text) if _byte_encoding == "utf8": o = end_offs - 1 while text[o] & 0xC0 == 0x80: o -= 1 return o if _byte_encoding == "wide" and within_double_byte(text, start_offs, end_offs - 1) == 2: return end_offs - 2 return end_offs - 1 def move_next_char(text: str | bytes, start_offs: int, end_offs: int) -> int: """ Return the position of the character after start_offs. """ if start_offs >= end_offs: raise ValueError((start_offs, end_offs)) if isinstance(text, str): return start_offs + 1 if not isinstance(text, bytes): raise TypeError(text) if _byte_encoding == "utf8": o = start_offs + 1 while o < end_offs and text[o] & 0xC0 == 0x80: o += 1 return o if _byte_encoding == "wide" and within_double_byte(text, start_offs, start_offs) == 1: return start_offs + 2 return start_offs + 1 def within_double_byte(text: bytes, line_start: int, pos: int) -> Literal[0, 1, 2]: """Return whether pos is within a double-byte encoded character. text -- byte string in question line_start -- offset of beginning of line (< pos) pos -- offset in question Return values: 0 -- not within dbe char, or double_byte_encoding == False 1 -- pos is on the 1st half of a dbe char 2 -- pos is on the 2nd half of a dbe char """ if not isinstance(text, bytes): raise TypeError(text) v = text[pos] if 0x40 <= v < 0x7F: # might be second half of big5, uhc or gbk encoding if pos == line_start: return 0 if text[pos - 1] >= 0x81 and within_double_byte(text, line_start, pos - 1) == 1: return 2 return 0 if v < 0x80: return 0 i = pos - 1 while i >= line_start: if text[i] < 0x80: break i -= 1 if (pos - i) & 1: return 1 return 2
10,844
Python
.py
294
29.72449
112
0.593783
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,243
command_map.py
urwid_urwid/urwid/command_map.py
# Urwid CommandMap class # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import enum import typing if typing.TYPE_CHECKING: from collections.abc import Iterator from typing_extensions import Self class Command(str, enum.Enum): REDRAW_SCREEN = "redraw screen" UP = "cursor up" DOWN = "cursor down" LEFT = "cursor left" RIGHT = "cursor right" PAGE_UP = "cursor page up" PAGE_DOWN = "cursor page down" MAX_LEFT = "cursor max left" MAX_RIGHT = "cursor max right" ACTIVATE = "activate" MENU = "menu" SELECT_NEXT = "next selectable" SELECT_PREVIOUS = "prev selectable" REDRAW_SCREEN = Command.REDRAW_SCREEN CURSOR_UP = Command.UP CURSOR_DOWN = Command.DOWN CURSOR_LEFT = Command.LEFT CURSOR_RIGHT = Command.RIGHT CURSOR_PAGE_UP = Command.PAGE_UP CURSOR_PAGE_DOWN = Command.PAGE_DOWN CURSOR_MAX_LEFT = Command.MAX_LEFT CURSOR_MAX_RIGHT = Command.MAX_RIGHT ACTIVATE = Command.ACTIVATE class CommandMap(typing.Mapping[str, typing.Union[str, Command, None]]): """ dict-like object for looking up commands from keystrokes Default values (key: command):: 'tab': 'next selectable', 'ctrl n': 'next selectable', 'shift tab': 'prev selectable', 'ctrl p': 'prev selectable', 'ctrl l': 'redraw screen', 'esc': 'menu', 'up': 'cursor up', 'down': 'cursor down', 'left': 'cursor left', 'right': 'cursor right', 'page up': 'cursor page up', 'page down': 'cursor page down', 'home': 'cursor max left', 'end': 'cursor max right', ' ': 'activate', 'enter': 'activate', """ def __iter__(self) -> Iterator[str]: return iter(self._command) def __len__(self) -> int: return len(self._command) _command_defaults: typing.ClassVar[dict[str, str | Command]] = { "tab": Command.SELECT_NEXT, "ctrl n": Command.SELECT_NEXT, "shift tab": Command.SELECT_PREVIOUS, "ctrl p": Command.SELECT_PREVIOUS, "ctrl l": Command.REDRAW_SCREEN, "esc": Command.MENU, "up": Command.UP, "down": Command.DOWN, "left": Command.LEFT, "right": Command.RIGHT, "page up": Command.PAGE_UP, "page down": Command.PAGE_DOWN, "home": Command.MAX_LEFT, "end": Command.MAX_RIGHT, " ": Command.ACTIVATE, "enter": Command.ACTIVATE, } def __init__(self) -> None: self._command = dict(self._command_defaults) def restore_defaults(self) -> None: self._command = dict(self._command_defaults) def __getitem__(self, key: str) -> str | Command | None: return self._command.get(key, None) def __setitem__(self, key, command: str | Command) -> None: self._command[key] = command def __delitem__(self, key: str) -> None: del self._command[key] def clear_command(self, command: str | Command) -> None: dk = [k for k, v in self._command.items() if v == command] for k in dk: del self._command[k] def copy(self) -> Self: """ Return a new copy of this CommandMap, likely so we can modify it separate from a shared one. """ c = self.__class__() c._command = dict(self._command) # pylint: disable=protected-access return c command_map = CommandMap() # shared command mappings
4,324
Python
.py
114
32.192982
78
0.62924
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,244
wimp.py
urwid_urwid/urwid/wimp.py
from __future__ import annotations import warnings from urwid.widget import Button, CheckBox, CheckBoxError, PopUpLauncher, PopUpTarget, RadioButton, SelectableIcon __all__ = ( "Button", "CheckBox", "CheckBoxError", "PopUpLauncher", "PopUpTarget", "RadioButton", "SelectableIcon", ) warnings.warn( f"{__name__!r} is not expected to be imported directly. " 'Please use public access from "urwid" package. ' f"Module {__name__!r} is deprecated and will be removed in the future.", DeprecationWarning, stacklevel=3, )
567
Python
.py
19
26.105263
113
0.707721
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,245
edit.py
urwid_urwid/urwid/widget/edit.py
from __future__ import annotations import string import typing from urwid import text_layout from urwid.canvas import CompositeCanvas from urwid.command_map import Command from urwid.split_repr import remove_defaults from urwid.str_util import is_wide_char, move_next_char, move_prev_char from urwid.util import decompose_tagmarkup from .constants import Align, Sizing, WrapMode from .text import Text, TextError if typing.TYPE_CHECKING: from collections.abc import Hashable from typing_extensions import Literal from urwid.canvas import TextCanvas class EditError(TextError): pass class Edit(Text): """ Text editing widget implements cursor movement, text insertion and deletion. A caption may prefix the editing area. Uses text class for text layout. Users of this class may listen for ``"change"`` or ``"postchange"`` events. See :func:``connect_signal``. * ``"change"`` is sent just before the value of edit_text changes. It receives the new text as an argument. Note that ``"change"`` cannot change the text in question as edit_text changes the text afterwards. * ``"postchange"`` is sent after the value of edit_text changes. It receives the old value of the text as an argument and thus is appropriate for changing the text. It is possible for a ``"postchange"`` event handler to get into a loop of changing the text and then being called when the event is re-emitted. It is up to the event handler to guard against this case (for instance, by not changing the text if it is signaled for text that it has already changed once). """ _sizing = frozenset([Sizing.FLOW]) _selectable = True ignore_focus = False # (this variable is picked up by the MetaSignals metaclass) signals: typing.ClassVar[list[str]] = ["change", "postchange"] def valid_char(self, ch: str) -> bool: """ Filter for text that may be entered into this widget by the user :param ch: character to be inserted :type ch: str This implementation returns True for all printable characters. """ return is_wide_char(ch, 0) or (len(ch) == 1 and ord(ch) >= 32) def __init__( self, caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]] = "", edit_text: str = "", multiline: bool = False, align: Literal["left", "center", "right"] | Align = Align.LEFT, wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE, allow_tab: bool = False, edit_pos: int | None = None, layout: text_layout.TextLayout = None, mask: str | None = None, ) -> None: """ :param caption: markup for caption preceding edit_text, see :class:`Text` for description of text markup. :type caption: text markup :param edit_text: initial text for editing, type (bytes or unicode) must match the text in the caption :type edit_text: bytes or unicode :param multiline: True: 'enter' inserts newline False: return it :type multiline: bool :param align: typically 'left', 'center' or 'right' :type align: text alignment mode :param wrap: typically 'space', 'any' or 'clip' :type wrap: text wrapping mode :param allow_tab: True: 'tab' inserts 1-8 spaces False: return it :type allow_tab: bool :param edit_pos: initial position for cursor, None:end of edit_text :type edit_pos: int :param layout: defaults to a shared :class:`StandardTextLayout` instance :type layout: text layout instance :param mask: hide text entered with this character, None:disable mask :type mask: bytes or unicode >>> Edit() <Edit selectable flow widget '' edit_pos=0> >>> Edit(u"Y/n? ", u"yes") <Edit selectable flow widget 'yes' caption='Y/n? ' edit_pos=3> >>> Edit(u"Name ", u"Smith", edit_pos=1) <Edit selectable flow widget 'Smith' caption='Name ' edit_pos=1> >>> Edit(u"", u"3.14", align='right') <Edit selectable flow widget '3.14' align='right' edit_pos=4> """ super().__init__("", align, wrap, layout) self.multiline = multiline self.allow_tab = allow_tab self._edit_pos = 0 self._caption, self._attrib = decompose_tagmarkup(caption) self._edit_text = "" self.highlight: tuple[int, int] | None = None self.set_edit_text(edit_text) if edit_pos is None: edit_pos = len(edit_text) self.set_edit_pos(edit_pos) self.set_mask(mask) self._shift_view_to_cursor = False def _repr_words(self) -> list[str]: return ( super()._repr_words()[:-1] + [repr(self._edit_text)] + [f"caption={self._caption!r}"] * bool(self._caption) + ["multiline"] * (self.multiline is True) ) def _repr_attrs(self) -> dict[str, typing.Any]: attrs = {**super()._repr_attrs(), "edit_pos": self._edit_pos} return remove_defaults(attrs, Edit.__init__) def get_text(self) -> tuple[str | bytes, list[tuple[Hashable, int]]]: """ Returns ``(text, display attributes)``. See :meth:`Text.get_text` for details. Text returned includes the caption and edit_text, possibly masked. >>> Edit(u"What? ","oh, nothing.").get_text() ('What? oh, nothing.', []) >>> Edit(('bright',u"user@host:~$ "),"ls").get_text() ('user@host:~$ ls', [('bright', 13)]) >>> Edit(u"password:", u"seekrit", mask=u"*").get_text() ('password:*******', []) """ if self._mask is None: return self._caption + self._edit_text, self._attrib return self._caption + (self._mask * len(self._edit_text)), self._attrib def set_text(self, markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None: """ Not supported by Edit widget. >>> Edit().set_text("test") Traceback (most recent call last): EditError: set_text() not supported. Use set_caption() or set_edit_text() instead. """ # FIXME: this smells. reimplement Edit as a WidgetWrap subclass to # clean this up # hack to let Text.__init__() work if not hasattr(self, "_text") and markup == "": # noqa: PLC1901,RUF100 self._text = None return raise EditError("set_text() not supported. Use set_caption() or set_edit_text() instead.") def get_pref_col(self, size: tuple[int]) -> int: """ Return the preferred column for the cursor, or the current cursor x value. May also return ``'left'`` or ``'right'`` to indicate the leftmost or rightmost column available. This method is used internally and by other widgets when moving the cursor up or down between widgets so that the column selected is one that the user would expect. >>> size = (10,) >>> Edit().get_pref_col(size) 0 >>> e = Edit(u"", u"word") >>> e.get_pref_col(size) 4 >>> e.keypress(size, 'left') >>> e.get_pref_col(size) 3 >>> e.keypress(size, 'end') >>> e.get_pref_col(size) <Align.RIGHT: 'right'> >>> e = Edit(u"", u"2\\nwords") >>> e.keypress(size, 'left') >>> e.keypress(size, 'up') >>> e.get_pref_col(size) 4 >>> e.keypress(size, 'left') >>> e.get_pref_col(size) 0 """ (maxcol,) = size pref_col, then_maxcol = self.pref_col_maxcol if then_maxcol != maxcol: return self.get_cursor_coords((maxcol,))[0] return pref_col def set_caption(self, caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None: """ Set the caption markup for this widget. :param caption: markup for caption preceding edit_text, see :meth:`Text.__init__` for description of text markup. >>> e = Edit("") >>> e.set_caption("cap1") >>> print(e.caption) cap1 >>> e.set_caption(('bold', "cap2")) >>> print(e.caption) cap2 >>> e.attrib [('bold', 4)] >>> e.caption = "cap3" # not supported because caption stores text but set_caption() takes markup Traceback (most recent call last): AttributeError: can't set attribute """ self._caption, self._attrib = decompose_tagmarkup(caption) self._invalidate() @property def caption(self) -> str: """ Read-only property returning the caption for this widget. """ return self._caption def set_edit_pos(self, pos: int) -> None: """ Set the cursor position with a self.edit_text offset. Clips pos to [0, len(edit_text)]. :param pos: cursor position :type pos: int >>> e = Edit(u"", u"word") >>> e.edit_pos 4 >>> e.set_edit_pos(2) >>> e.edit_pos 2 >>> e.edit_pos = -1 # Urwid 0.9.9 or later >>> e.edit_pos 0 >>> e.edit_pos = 20 >>> e.edit_pos 4 """ pos = min(max(pos, 0), len(self._edit_text)) self.highlight = None self.pref_col_maxcol = None, None self._edit_pos = pos self._invalidate() edit_pos = property( lambda self: self._edit_pos, set_edit_pos, doc=""" Property controlling the edit position for this widget. """, ) def set_mask(self, mask: str | None) -> None: """ Set the character for masking text away. :param mask: hide text entered with this character, None:disable mask :type mask: bytes or unicode """ self._mask = mask self._invalidate() def set_edit_text(self, text: str) -> None: """ Set the edit text for this widget. :param text: text for editing, type (bytes or unicode) must match the text in the caption :type text: bytes or unicode >>> e = Edit() >>> e.set_edit_text(u"yes") >>> print(e.edit_text) yes >>> e <Edit selectable flow widget 'yes' edit_pos=0> >>> e.edit_text = u"no" # Urwid 0.9.9 or later >>> print(e.edit_text) no """ text = self._normalize_to_caption(text) self.highlight = None self._emit("change", text) old_text = self._edit_text self._edit_text = text self.edit_pos = min(self.edit_pos, len(text)) self._emit("postchange", old_text) self._invalidate() def get_edit_text(self) -> str: """ Return the edit text for this widget. >>> e = Edit(u"What? ", u"oh, nothing.") >>> print(e.get_edit_text()) oh, nothing. >>> print(e.edit_text) oh, nothing. """ return self._edit_text edit_text = property( get_edit_text, set_edit_text, doc=""" Property controlling the edit text for this widget. """, ) def insert_text(self, text: str) -> None: """ Insert text at the cursor position and update cursor. This method is used by the keypress() method when inserting one or more characters into edit_text. :param text: text for inserting, type (bytes or unicode) must match the text in the caption :type text: bytes or unicode >>> e = Edit(u"", u"42") >>> e.insert_text(u".5") >>> e <Edit selectable flow widget '42.5' edit_pos=4> >>> e.set_edit_pos(2) >>> e.insert_text(u"a") >>> print(e.edit_text) 42a.5 """ text = self._normalize_to_caption(text) result_text, result_pos = self.insert_text_result(text) self.set_edit_text(result_text) self.set_edit_pos(result_pos) self.highlight = None def _normalize_to_caption(self, text: str | bytes) -> str | bytes: """Return text converted to the same type as self.caption (bytes or unicode)""" tu = isinstance(text, str) cu = isinstance(self._caption, str) if tu == cu: return text if tu: return text.encode("ascii") # follow python2's implicit conversion return text.decode("ascii") def insert_text_result(self, text: str) -> tuple[str | bytes, int]: """ Return result of insert_text(text) without actually performing the insertion. Handy for pre-validation. :param text: text for inserting, type (bytes or unicode) must match the text in the caption :type text: bytes or unicode """ # if there's highlighted text, it'll get replaced by the new text text = self._normalize_to_caption(text) if self.highlight: start, stop = self.highlight # pylint: disable=unpacking-non-sequence # already checked btext, etext = self.edit_text[:start], self.edit_text[stop:] result_text = btext + etext result_pos = start else: result_text = self.edit_text result_pos = self.edit_pos try: result_text = result_text[:result_pos] + text + result_text[result_pos:] except (IndexError, TypeError) as exc: raise ValueError(repr((self.edit_text, result_text, text))).with_traceback(exc.__traceback__) from exc result_pos += len(text) return (result_text, result_pos) def keypress( self, size: tuple[int], # type: ignore[override] key: str, ) -> str | None: """ Handle editing keystrokes, return others. >>> e, size = Edit(), (20,) >>> e.keypress(size, 'x') >>> e.keypress(size, 'left') >>> e.keypress(size, '1') >>> print(e.edit_text) 1x >>> e.keypress(size, 'backspace') >>> e.keypress(size, 'end') >>> e.keypress(size, '2') >>> print(e.edit_text) x2 >>> e.keypress(size, 'shift f1') 'shift f1' """ pos = self.edit_pos if self.valid_char(key): if isinstance(key, str) and not isinstance(self._caption, str): key = key.encode("utf-8") self.insert_text(key) return None if key == "tab" and self.allow_tab: key = " " * (8 - (self.edit_pos % 8)) self.insert_text(key) return None if key == "enter" and self.multiline: key = "\n" self.insert_text(key) return None if self._command_map[key] == Command.LEFT: if pos == 0: return key pos = move_prev_char(self.edit_text, 0, pos) self.set_edit_pos(pos) return None if self._command_map[key] == Command.RIGHT: if pos >= len(self.edit_text): return key pos = move_next_char(self.edit_text, pos, len(self.edit_text)) self.set_edit_pos(pos) return None if self._command_map[key] in {Command.UP, Command.DOWN}: self.highlight = None _x, y = self.get_cursor_coords(size) pref_col = self.get_pref_col(size) if pref_col is None: raise ValueError(pref_col) # if pref_col is None: # pref_col = x if self._command_map[key] == Command.UP: y -= 1 else: y += 1 if not self.move_cursor_to_coords(size, pref_col, y): return key return None if key == "backspace": self.pref_col_maxcol = None, None if not self._delete_highlighted(): if pos == 0: return key pos = move_prev_char(self.edit_text, 0, pos) self.set_edit_text(self.edit_text[:pos] + self.edit_text[self.edit_pos :]) self.set_edit_pos(pos) return None return None if key == "delete": self.pref_col_maxcol = None, None if not self._delete_highlighted(): if pos >= len(self.edit_text): return key pos = move_next_char(self.edit_text, pos, len(self.edit_text)) self.set_edit_text(self.edit_text[: self.edit_pos] + self.edit_text[pos:]) return None return None if self._command_map[key] in {Command.MAX_LEFT, Command.MAX_RIGHT}: self.highlight = None self.pref_col_maxcol = None, None _x, y = self.get_cursor_coords(size) if self._command_map[key] == Command.MAX_LEFT: self.move_cursor_to_coords(size, Align.LEFT, y) else: self.move_cursor_to_coords(size, Align.RIGHT, y) return None # key wasn't handled return key def move_cursor_to_coords( self, size: tuple[int], x: int | Literal[Align.LEFT, Align.RIGHT], y: int, ) -> bool: """ Set the cursor position with (x,y) coordinates. Returns True if move succeeded, False otherwise. >>> size = (10,) >>> e = Edit("","edit\\ntext") >>> e.move_cursor_to_coords(size, 5, 0) True >>> e.edit_pos 4 >>> e.move_cursor_to_coords(size, 5, 3) False >>> e.move_cursor_to_coords(size, 0, 1) True >>> e.edit_pos 5 """ (maxcol,) = size trans = self.get_line_translation(maxcol) _top_x, top_y = self.position_coords(maxcol, 0) if y < top_y or y >= len(trans): return False pos = text_layout.calc_pos(self.get_text()[0], trans, x, y) e_pos = min(max(pos - len(self.caption), 0), len(self.edit_text)) self.edit_pos = e_pos self.pref_col_maxcol = x, maxcol self._invalidate() return True def mouse_event( self, size: tuple[int], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """ Move the cursor to the location clicked for button 1. >>> size = (20,) >>> e = Edit("","words here") >>> e.mouse_event(size, 'mouse press', 1, 2, 0, True) True >>> e.edit_pos 2 """ if button == 1: return self.move_cursor_to_coords(size, col, row) return False def _delete_highlighted(self) -> bool: """ Delete all highlighted text and update cursor position, if any text is highlighted. """ if not self.highlight: return False start, stop = self.highlight # pylint: disable=unpacking-non-sequence # already checked btext, etext = self.edit_text[:start], self.edit_text[stop:] self.set_edit_text(btext + etext) self.edit_pos = start self.highlight = None return True def render( self, size: tuple[int], # type: ignore[override] focus: bool = False, ) -> TextCanvas | CompositeCanvas: """ Render edit widget and return canvas. Include cursor when in focus. >>> edit = Edit("? ","yes") >>> c = edit.render((10,), focus=True) >>> c.text [b'? yes '] >>> c.cursor (5, 0) """ self._shift_view_to_cursor = bool(focus) # noqa: FURB123,RUF100 canv: TextCanvas | CompositeCanvas = super().render(size, focus) if focus: canv = CompositeCanvas(canv) canv.cursor = self.get_cursor_coords(size) # .. will need to FIXME if I want highlight to work again # if self.highlight: # hstart, hstop = self.highlight_coords() # d.coords['highlight'] = [ hstart, hstop ] return canv def get_line_translation( self, maxcol: int, ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None = None, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: trans = super().get_line_translation(maxcol, ta) if not self._shift_view_to_cursor: return trans text, _ignore = self.get_text() x, y = text_layout.calc_coords(text, trans, self.edit_pos + len(self.caption)) if x < 0: return [ *trans[:y], *[text_layout.shift_line(trans[y], -x)], *trans[y + 1 :], ] if x >= maxcol: return [ *trans[:y], *[text_layout.shift_line(trans[y], -(x - maxcol + 1))], *trans[y + 1 :], ] return trans def get_cursor_coords(self, size: tuple[int]) -> tuple[int, int]: """ Return the (*x*, *y*) coordinates of cursor within widget. >>> Edit("? ","yes").get_cursor_coords((10,)) (5, 0) """ (maxcol,) = size self._shift_view_to_cursor = True return self.position_coords(maxcol, self.edit_pos) def position_coords(self, maxcol: int, pos: int) -> tuple[int, int]: """ Return (*x*, *y*) coordinates for an offset into self.edit_text. """ p = pos + len(self.caption) trans = self.get_line_translation(maxcol) x, y = text_layout.calc_coords(self.get_text()[0], trans, p) return x, y class IntEdit(Edit): """Edit widget for integer values""" def valid_char(self, ch: str) -> bool: """ Return true for decimal digits. """ return len(ch) == 1 and ch in string.digits def __init__(self, caption="", default: int | str | None = None) -> None: """ caption -- caption markup default -- default edit value >>> IntEdit(u"", 42) <IntEdit selectable flow widget '42' edit_pos=2> """ if default is not None: val = str(default) else: val = "" super().__init__(caption, val) def keypress( self, size: tuple[int], # type: ignore[override] key: str, ) -> str | None: """ Handle editing keystrokes. Remove leading zeros. >>> e, size = IntEdit(u"", 5002), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> print(e.edit_text) 002 >>> e.keypress(size, 'end') >>> print(e.edit_text) 2 """ unhandled = super().keypress(size, key) if not unhandled: # trim leading zeros while self.edit_pos > 0 and self.edit_text[:1] == "0": self.set_edit_pos(self.edit_pos - 1) self.set_edit_text(self.edit_text[1:]) return unhandled def value(self) -> int: """ Return the numeric value of self.edit_text. >>> e, size = IntEdit(), (10,) >>> e.keypress(size, '5') >>> e.keypress(size, '1') >>> e.value() == 51 True """ if self.edit_text: return int(self.edit_text) return 0
23,732
Python
.py
615
29.019512
114
0.55359
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,246
solid_fill.py
urwid_urwid/urwid/widget/solid_fill.py
from __future__ import annotations from urwid.canvas import SolidCanvas from .constants import SHADE_SYMBOLS, Sizing from .widget import Widget class SolidFill(Widget): """ A box widget that fills an area with a single character """ _selectable = False ignore_focus = True _sizing = frozenset([Sizing.BOX]) Symbols = SHADE_SYMBOLS def __init__(self, fill_char: str = " ") -> None: """ :param fill_char: character to fill area with :type fill_char: bytes or unicode >>> SolidFill(u'8') <SolidFill box widget '8'> """ super().__init__() self.fill_char = fill_char def _repr_words(self) -> list[str]: return [*super()._repr_words(), repr(self.fill_char)] def render( self, size: tuple[int, int], # type: ignore[override] focus: bool = False, ) -> SolidCanvas: """ Render the Fill as a canvas and return it. >>> SolidFill().render((4,2)).text # ... = b in Python 3 [...' ', ...' '] >>> SolidFill('#').render((5,3)).text [...'#####', ...'#####', ...'#####'] """ maxcol, maxrow = size return SolidCanvas(self.fill_char, maxcol, maxrow)
1,260
Python
.py
37
27.027027
64
0.556931
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,247
filler.py
urwid_urwid/urwid/widget/filler.py
from __future__ import annotations import typing import warnings from urwid.canvas import CompositeCanvas from urwid.split_repr import remove_defaults from urwid.util import int_scale from .constants import ( RELATIVE_100, Sizing, VAlign, WHSettings, normalize_height, normalize_valign, simplify_height, simplify_valign, ) from .widget_decoration import WidgetDecoration, WidgetError if typing.TYPE_CHECKING: from typing_extensions import Literal WrappedWidget = typing.TypeVar("WrappedWidget") class FillerError(WidgetError): pass class Filler(WidgetDecoration[WrappedWidget]): def __init__( self, body: WrappedWidget, valign: ( Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int] ) = VAlign.MIDDLE, height: ( int | Literal["pack", WHSettings.PACK] | tuple[Literal["relative", WHSettings.RELATIVE], int] | None ) = WHSettings.PACK, min_height: int | None = None, top: int = 0, bottom: int = 0, ) -> None: """ :param body: a flow widget or box widget to be filled around (stored as self.original_widget) :type body: Widget :param valign: one of: ``'top'``, ``'middle'``, ``'bottom'``, (``'relative'``, *percentage* 0=top 100=bottom) :param height: one of: ``'pack'`` if body is a flow widget *given height* integer number of rows for self.original_widget (``'relative'``, *percentage of total height*) make height depend on container's height :param min_height: one of: ``None`` if no minimum or if body is a flow widget *minimum height* integer number of rows for the widget when height not fixed :param top: a fixed number of rows to fill at the top :type top: int :param bottom: a fixed number of rows to fill at the bottom :type bottom: int If body is a flow widget, then height must be ``'pack'`` and *min_height* will be ignored. Sizing of the filler will be BOX/FLOW in this case. If height is integer, *min_height* will be ignored and sizing of filler will be BOX/FLOW. Filler widgets will try to satisfy height argument first by reducing the valign amount when necessary. If height still cannot be satisfied it will also be reduced. """ super().__init__(body) # convert old parameters to the new top/bottom values if isinstance(height, tuple): if height[0] == "fixed top": if not isinstance(valign, tuple) or valign[0] != "fixed bottom": raise FillerError("fixed top height may only be used with fixed bottom valign") top = height[1] height = RELATIVE_100 elif height[0] == "fixed bottom": if not isinstance(valign, tuple) or valign[0] != "fixed top": raise FillerError("fixed bottom height may only be used with fixed top valign") bottom = height[1] height = RELATIVE_100 if isinstance(valign, tuple): if valign[0] == "fixed top": top = valign[1] normalized_valign = VAlign.TOP elif valign[0] == "fixed bottom": bottom = valign[1] normalized_valign = VAlign.BOTTOM else: normalized_valign = valign elif not isinstance(valign, (VAlign, str)): raise FillerError(f"invalid valign: {valign!r}") else: normalized_valign = VAlign(valign) # convert old flow mode parameter height=None to height='flow' if height is None or height == Sizing.FLOW: height = WHSettings.PACK self.top = top self.bottom = bottom self.valign_type, self.valign_amount = normalize_valign(normalized_valign, FillerError) self.height_type, self.height_amount = normalize_height(height, FillerError) if self.height_type not in {WHSettings.GIVEN, WHSettings.PACK}: self.min_height = min_height else: self.min_height = None def sizing(self) -> frozenset[Sizing]: """Widget sizing. Sizing BOX is always supported. Sizing FLOW is supported if: FLOW widget (a height type is PACK) or BOX widget with height GIVEN """ sizing: set[Sizing] = {Sizing.BOX} if self.height_type in {WHSettings.PACK, WHSettings.GIVEN}: sizing.add(Sizing.FLOW) return frozenset(sizing) def rows(self, size: tuple[int], focus: bool = False) -> int: """Flow pack support if FLOW sizing supported.""" if self.height_type == WHSettings.PACK: return self.original_widget.rows(size, focus) + self.top + self.bottom if self.height_type == WHSettings.GIVEN: return self.height_amount + self.top + self.bottom raise FillerError("Method 'rows' not supported for BOX widgets") # pragma: no cover def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "valign": simplify_valign(self.valign_type, self.valign_amount), "height": simplify_height(self.height_type, self.height_amount), "top": self.top, "bottom": self.bottom, "min_height": self.min_height, } return remove_defaults(attrs, Filler.__init__) @property def body(self) -> WrappedWidget: """backwards compatibility, widget used to be stored as body""" warnings.warn( "backwards compatibility, widget used to be stored as body", PendingDeprecationWarning, stacklevel=2, ) return self.original_widget @body.setter def body(self, new_body: WrappedWidget) -> None: warnings.warn( "backwards compatibility, widget used to be stored as body", PendingDeprecationWarning, stacklevel=2, ) self.original_widget = new_body def get_body(self) -> WrappedWidget: """backwards compatibility, widget used to be stored as body""" warnings.warn( "backwards compatibility, widget used to be stored as body", DeprecationWarning, stacklevel=2, ) return self.original_widget def set_body(self, new_body: WrappedWidget) -> None: warnings.warn( "backwards compatibility, widget used to be stored as body", DeprecationWarning, stacklevel=2, ) self.original_widget = new_body def selectable(self) -> bool: """Return selectable from body.""" return self._original_widget.selectable() def filler_values(self, size: tuple[int, int] | tuple[int], focus: bool) -> tuple[int, int]: """ Return the number of rows to pad on the top and bottom. Override this method to define custom padding behaviour. """ maxcol, maxrow = self.pack(size, focus) if self.height_type == WHSettings.PACK: height = self._original_widget.rows((maxcol,), focus=focus) return calculate_top_bottom_filler( maxrow, self.valign_type, self.valign_amount, WHSettings.GIVEN, height, None, self.top, self.bottom, ) return calculate_top_bottom_filler( maxrow, self.valign_type, self.valign_amount, self.height_type, self.height_amount, self.min_height, self.top, self.bottom, ) def render( self, size: tuple[int, int] | tuple[int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: """Render self.original_widget with space above and/or below.""" maxcol, maxrow = self.pack(size, focus) top, bottom = self.filler_values(size, focus) if self.height_type == WHSettings.PACK: canv = self._original_widget.render((maxcol,), focus) else: canv = self._original_widget.render((maxcol, maxrow - top - bottom), focus) canv = CompositeCanvas(canv) if maxrow and canv.rows() > maxrow and canv.cursor is not None: _cx, cy = canv.cursor if cy >= maxrow: canv.trim(cy - maxrow + 1, maxrow - top - bottom) if canv.rows() > maxrow: canv.trim(0, maxrow) return canv canv.pad_trim_top_bottom(top, bottom) return canv def keypress( self, size: tuple[int, int] | tuple[()], # type: ignore[override] key: str, ) -> str | None: """Pass keypress to self.original_widget.""" maxcol, maxrow = self.pack(size, True) if self.height_type == WHSettings.PACK: return self._original_widget.keypress((maxcol,), key) top, bottom = self.filler_values((maxcol, maxrow), True) return self._original_widget.keypress((maxcol, maxrow - top - bottom), key) def get_cursor_coords(self, size: tuple[int, int] | tuple[int]) -> tuple[int, int] | None: """Return cursor coords from self.original_widget if any.""" maxcol, maxrow = self.pack(size, True) if not hasattr(self._original_widget, "get_cursor_coords"): return None top, bottom = self.filler_values(size, True) if self.height_type == WHSettings.PACK: coords = self._original_widget.get_cursor_coords((maxcol,)) else: coords = self._original_widget.get_cursor_coords((maxcol, maxrow - top - bottom)) if not coords: return None x, y = coords if y >= maxrow: y = maxrow - 1 return x, y + top def get_pref_col(self, size: tuple[int, int] | tuple[int]) -> int | None: """Return pref_col from self.original_widget if any.""" maxcol, maxrow = self.pack(size, True) if not hasattr(self._original_widget, "get_pref_col"): return None if self.height_type == WHSettings.PACK: x = self._original_widget.get_pref_col((maxcol,)) else: top, bottom = self.filler_values(size, True) x = self._original_widget.get_pref_col((maxcol, maxrow - top - bottom)) return x def move_cursor_to_coords(self, size: tuple[int, int] | tuple[int], col: int, row: int) -> bool: """Pass to self.original_widget.""" maxcol, maxrow = self.pack(size, True) if not hasattr(self._original_widget, "move_cursor_to_coords"): return True top, bottom = self.filler_values(size, True) if row < top or row >= maxcol - bottom: return False if self.height_type == WHSettings.PACK: return self._original_widget.move_cursor_to_coords((maxcol,), col, row - top) return self._original_widget.move_cursor_to_coords((maxcol, maxrow - top - bottom), col, row - top) def mouse_event( self, size: tuple[int, int] | tuple[int], # type: ignore[override] event, button: int, col: int, row: int, focus: bool, ) -> bool | None: """Pass to self.original_widget.""" maxcol, maxrow = self.pack(size, focus) if not hasattr(self._original_widget, "mouse_event"): return False top, bottom = self.filler_values(size, True) if row < top or row >= maxrow - bottom: return False if self.height_type == WHSettings.PACK: return self._original_widget.mouse_event((maxcol,), event, button, col, row - top, focus) return self._original_widget.mouse_event((maxcol, maxrow - top - bottom), event, button, col, row - top, focus) def calculate_top_bottom_filler( maxrow: int, valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign, valign_amount: int, height_type: Literal["given", "relative", "clip", WHSettings.GIVEN, WHSettings.RELATIVE, WHSettings.CLIP], height_amount: int, min_height: int | None, top: int, bottom: int, ) -> tuple[int, int]: """ Return the amount of filler (or clipping) on the top and bottom part of maxrow rows to satisfy the following: valign_type -- 'top', 'middle', 'bottom', 'relative' valign_amount -- a percentage when align_type=='relative' height_type -- 'given', 'relative', 'clip' height_amount -- a percentage when width_type=='relative' otherwise equal to the height of the widget min_height -- a desired minimum width for the widget or None top -- a fixed number of rows to fill on the top bottom -- a fixed number of rows to fill on the bottom >>> ctbf = calculate_top_bottom_filler >>> ctbf(15, 'top', 0, 'given', 10, None, 2, 0) (2, 3) >>> ctbf(15, 'relative', 0, 'given', 10, None, 2, 0) (2, 3) >>> ctbf(15, 'relative', 100, 'given', 10, None, 2, 0) (5, 0) >>> ctbf(15, 'middle', 0, 'given', 4, None, 2, 0) (6, 5) >>> ctbf(15, 'middle', 0, 'given', 18, None, 2, 0) (0, 0) >>> ctbf(20, 'top', 0, 'relative', 60, None, 0, 0) (0, 8) >>> ctbf(20, 'relative', 30, 'relative', 60, None, 0, 0) (2, 6) >>> ctbf(20, 'relative', 30, 'relative', 60, 14, 0, 0) (2, 4) """ if height_type == WHSettings.RELATIVE: maxheight = max(maxrow - top - bottom, 0) height = int_scale(height_amount, 101, maxheight + 1) if min_height is not None: height = max(height, min_height) else: height = height_amount valign = {VAlign.TOP: 0, VAlign.MIDDLE: 50, VAlign.BOTTOM: 100}.get(valign_type, valign_amount) # add the remainder of top/bottom to the filler filler = maxrow - height - top - bottom bottom += int_scale(100 - valign, 101, filler + 1) top = maxrow - height - bottom # reduce filler if we are clipping an edge if bottom < 0 < top: shift = min(top, -bottom) top -= shift bottom += shift elif top < 0 < bottom: shift = min(bottom, -top) bottom -= shift top += shift # no negative values for filler at the moment top = max(top, 0) bottom = max(bottom, 0) return top, bottom
14,665
Python
.py
344
33.258721
119
0.597475
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,248
listbox.py
urwid_urwid/urwid/widget/listbox.py
# Urwid listbox class # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import operator import typing import warnings from collections.abc import Iterable, Sized from contextlib import suppress from typing_extensions import Protocol, runtime_checkable from urwid import signals from urwid.canvas import CanvasCombine, SolidCanvas from .constants import Sizing, VAlign, WHSettings, normalize_valign from .container import WidgetContainerMixin from .filler import calculate_top_bottom_filler from .monitored_list import MonitoredFocusList, MonitoredList from .widget import Widget, nocache_widget_render_instance if typing.TYPE_CHECKING: from collections.abc import Callable, Hashable from typing_extensions import Literal, Self from urwid.canvas import Canvas, CompositeCanvas __all__ = ( "ListBox", "ListBoxError", "ListWalker", "ListWalkerError", "SimpleFocusListWalker", "SimpleListWalker", "VisibleInfo", "VisibleInfoFillItem", "VisibleInfoMiddle", "VisibleInfoTopBottom", ) _T = typing.TypeVar("_T") _K = typing.TypeVar("_K") class ListWalkerError(Exception): pass @runtime_checkable class ScrollSupportingBody(Protocol): """Protocol for ListWalkers.""" def get_focus(self) -> tuple[Widget, _K]: ... def set_focus(self, position: _K) -> None: ... def get_next(self, position: _K) -> tuple[Widget, _K] | tuple[None, None]: ... def get_prev(self, position: _K) -> tuple[Widget, _K] | tuple[None, None]: ... @runtime_checkable class EstimatedSized(Protocol): """Widget can estimate it's size. PEP 424 defines API for memory-efficiency. For the ListBox it's a sign of the limited body length. The main use-case is lazy-load, where real length calculation is expensive. """ def __length_hint__(self) -> int: ... class ListWalker(metaclass=signals.MetaSignals): # pylint: disable=no-member, unsubscriptable-object # mixin not named as mixin signals: typing.ClassVar[list[str]] = ["modified"] def _modified(self) -> None: signals.emit_signal(self, "modified") def get_focus(self): """ This default implementation relies on a focus attribute and a __getitem__() method defined in a subclass. Override and don't call this method if these are not defined. """ try: focus = self.focus return self[focus], focus except (IndexError, KeyError, TypeError): return None, None def get_next(self, position): """ This default implementation relies on a next_position() method and a __getitem__() method defined in a subclass. Override and don't call this method if these are not defined. """ try: position = self.next_position(position) return self[position], position except (IndexError, KeyError): return None, None def get_prev(self, position): """ This default implementation relies on a prev_position() method and a __getitem__() method defined in a subclass. Override and don't call this method if these are not defined. """ try: position = self.prev_position(position) return self[position], position except (IndexError, KeyError): return None, None class SimpleListWalker(MonitoredList[_T], ListWalker): def __init__(self, contents: Iterable[_T], wrap_around: bool = False) -> None: """ contents -- list to copy into this object wrap_around -- if true, jumps to beginning/end of list on move This class inherits :class:`MonitoredList` which means it can be treated as a list. Changes made to this object (when it is treated as a list) are detected automatically and will cause ListBox objects using this list walker to be updated. """ if not isinstance(contents, Iterable): raise ListWalkerError(f"SimpleListWalker expecting list like object, got: {contents!r}") MonitoredList.__init__(self, contents) self.focus = 0 self.wrap_around = wrap_around @property def contents(self) -> Self: """ Return self. Provides compatibility with old SimpleListWalker class. """ return self def _get_contents(self) -> Self: warnings.warn( f"Method `{self.__class__.__name__}._get_contents` is deprecated, " f"please use property`{self.__class__.__name__}.contents`", DeprecationWarning, stacklevel=3, ) return self def _modified(self) -> None: if self.focus >= len(self): self.focus = max(0, len(self) - 1) ListWalker._modified(self) def set_modified_callback(self, callback: Callable[[], typing.Any]) -> typing.NoReturn: """ This function inherited from MonitoredList is not implemented in SimpleListWalker. Use connect_signal(list_walker, "modified", ...) instead. """ raise NotImplementedError('Use connect_signal(list_walker, "modified", ...) instead.') def set_focus(self, position: int) -> None: """Set focus position.""" if not 0 <= position < len(self): raise IndexError(f"No widget at position {position}") self.focus = position self._modified() def next_position(self, position: int) -> int: """ Return position after start_from. """ if len(self) - 1 <= position: if self.wrap_around: return 0 raise IndexError return position + 1 def prev_position(self, position: int) -> int: """ Return position before start_from. """ if position <= 0: if self.wrap_around: return len(self) - 1 raise IndexError return position - 1 def positions(self, reverse: bool = False) -> Iterable[int]: """ Optional method for returning an iterable of positions. """ if reverse: return range(len(self) - 1, -1, -1) return range(len(self)) class SimpleFocusListWalker(ListWalker, MonitoredFocusList[_T]): def __init__(self, contents: Iterable[_T], wrap_around: bool = False) -> None: """ contents -- list to copy into this object wrap_around -- if true, jumps to beginning/end of list on move This class inherits :class:`MonitoredList` which means it can be treated as a list. Changes made to this object (when it is treated as a list) are detected automatically and will cause ListBox objects using this list walker to be updated. Also, items added or removed before the widget in focus with normal list methods will cause the focus to be updated intelligently. """ if not isinstance(contents, Iterable): raise ListWalkerError(f"SimpleFocusListWalker expecting iterable object, got: {contents!r}") MonitoredFocusList.__init__(self, contents) self.wrap_around = wrap_around def set_modified_callback(self, callback: typing.Any) -> typing.NoReturn: """ This function inherited from MonitoredList is not implemented in SimpleFocusListWalker. Use connect_signal(list_walker, "modified", ...) instead. """ raise NotImplementedError('Use connect_signal(list_walker, "modified", ...) instead.') def set_focus(self, position: int) -> None: """Set focus position.""" self.focus = position self._modified() def next_position(self, position: int) -> int: """ Return position after start_from. """ if len(self) - 1 <= position: if self.wrap_around: return 0 raise IndexError return position + 1 def prev_position(self, position: int) -> int: """ Return position before start_from. """ if position <= 0: if self.wrap_around: return len(self) - 1 raise IndexError return position - 1 def positions(self, reverse: bool = False) -> Iterable[int]: """ Optional method for returning an iterable of positions. """ if reverse: return range(len(self) - 1, -1, -1) return range(len(self)) class ListBoxError(Exception): pass class VisibleInfoMiddle(typing.NamedTuple): """Named tuple for ListBox internals.""" offset: int focus_widget: Widget focus_pos: Hashable focus_rows: int cursor: tuple[int, int] | tuple[int] | None class VisibleInfoFillItem(typing.NamedTuple): """Named tuple for ListBox internals.""" widget: Widget position: Hashable rows: int class VisibleInfoTopBottom(typing.NamedTuple): """Named tuple for ListBox internals.""" trim: int fill: list[VisibleInfoFillItem] @classmethod def from_raw_data( cls, trim: int, fill: Iterable[tuple[Widget, Hashable, int]], ) -> Self: """Construct from not typed data. Useful for overridden cases.""" return cls(trim=trim, fill=[VisibleInfoFillItem(*item) for item in fill]) # pragma: no cover class VisibleInfo(typing.NamedTuple): middle: VisibleInfoMiddle top: VisibleInfoTopBottom bottom: VisibleInfoTopBottom @classmethod def from_raw_data( cls, middle: tuple[int, Widget, Hashable, int, tuple[int, int] | tuple[int] | None], top: tuple[int, Iterable[tuple[Widget, Hashable, int]]], bottom: tuple[int, Iterable[tuple[Widget, Hashable, int]]], ) -> Self: """Construct from not typed data. Useful for overridden cases. """ return cls( # pragma: no cover middle=VisibleInfoMiddle(*middle), top=VisibleInfoTopBottom.from_raw_data(*top), bottom=VisibleInfoTopBottom.from_raw_data(*bottom), ) class ListBox(Widget, WidgetContainerMixin): """ Vertically stacked list of widgets """ _selectable = True _sizing = frozenset([Sizing.BOX]) def __init__(self, body: ListWalker | Iterable[Widget]) -> None: """ :param body: a ListWalker subclass such as :class:`SimpleFocusListWalker` that contains widgets to be displayed inside the list box :type body: ListWalker """ super().__init__() if getattr(body, "get_focus", None): self._body: ListWalker = body else: self._body = SimpleListWalker(body) self.body = self._body # Initialization hack # offset_rows is the number of rows between the top of the view # and the top of the focused item self.offset_rows = 0 # inset_fraction is used when the focused widget is off the # top of the view. it is the fraction of the widget cut off # at the top. (numerator, denominator) self.inset_fraction = (0, 1) # pref_col is the preferred column for the cursor when moving # between widgets that use the cursor (edit boxes etc.) self.pref_col = "left" # variable for delayed focus change used by set_focus self.set_focus_pending = "first selectable" # variable for delayed valign change used by set_focus_valign self.set_focus_valign_pending = None # used for scrollable protocol self._rows_max_cached = 0 self._rendered_size = 0, 0 @property def body(self) -> ListWalker: """ a ListWalker subclass such as :class:`SimpleFocusListWalker` that contains widgets to be displayed inside the list box """ return self._body @body.setter def body(self, body: Iterable[Widget] | ListWalker) -> None: with suppress(AttributeError): signals.disconnect_signal(self._body, "modified", self._invalidate) # _body may be not yet assigned if getattr(body, "get_focus", None): self._body = body else: self._body = SimpleListWalker(body) try: signals.connect_signal(self._body, "modified", self._invalidate) except NameError: # our list walker has no modified signal so we must not # cache our canvases because we don't know when our # content has changed self.render = nocache_widget_render_instance(self) self._invalidate() def _get_body(self): warnings.warn( f"Method `{self.__class__.__name__}._get_body` is deprecated, " f"please use property `{self.__class__.__name__}.body`", DeprecationWarning, stacklevel=3, ) return self.body def _set_body(self, body): warnings.warn( f"Method `{self.__class__.__name__}._set_body` is deprecated, " f"please use property `{self.__class__.__name__}.body`", DeprecationWarning, stacklevel=3, ) self.body = body @property def __len__(self) -> Callable[[], int]: if isinstance(self._body, Sized): return self._body.__len__ raise AttributeError(f"{self._body.__class__.__name__} is not Sized") @property def __length_hint__(self) -> Callable[[], int]: # pylint: disable=invalid-length-hint-returned if isinstance(self._body, (Sized, EstimatedSized)): return lambda: operator.length_hint(self._body) raise AttributeError(f'{self._body.__class__.__name__} is not Sized and do not implement "__length_hint__"') def calculate_visible( self, size: tuple[int, int], focus: bool = False, ) -> VisibleInfo | tuple[None, None, None]: """ Returns the widgets that would be displayed in the ListBox given the current *size* and *focus*. see :meth:`Widget.render` for parameter details :returns: (*middle*, *top*, *bottom*) or (``None``, ``None``, ``None``) *middle* (*row offset*(when +ve) or *inset*(when -ve), *focus widget*, *focus position*, *focus rows*, *cursor coords* or ``None``) *top* (*# lines to trim off top*, list of (*widget*, *position*, *rows*) tuples above focus in order from bottom to top) *bottom* (*# lines to trim off bottom*, list of (*widget*, *position*, *rows*) tuples below focus in order from top to bottom) """ (maxcol, maxrow) = size # 0. set the focus if a change is pending if self.set_focus_pending or self.set_focus_valign_pending: self._set_focus_complete((maxcol, maxrow), focus) # 1. start with the focus widget focus_widget, focus_pos = self._body.get_focus() if focus_widget is None: # list box is empty? return None, None, None top_pos = focus_pos offset_rows, inset_rows = self.get_focus_offset_inset((maxcol, maxrow)) # force at least one line of focus to be visible if maxrow and offset_rows >= maxrow: offset_rows = maxrow - 1 # adjust position so cursor remains visible cursor = None if maxrow and focus_widget.selectable() and focus and hasattr(focus_widget, "get_cursor_coords"): cursor = focus_widget.get_cursor_coords((maxcol,)) if cursor is not None: _cx, cy = cursor effective_cy = cy + offset_rows - inset_rows if effective_cy < 0: # cursor above top? inset_rows = cy elif effective_cy >= maxrow: # cursor below bottom? offset_rows = maxrow - cy - 1 if offset_rows < 0: # need to trim the top inset_rows, offset_rows = -offset_rows, 0 # set trim_top by focus trimmimg trim_top = inset_rows focus_rows = focus_widget.rows((maxcol,), True) # 2. collect the widgets above the focus pos = focus_pos fill_lines = offset_rows fill_above = [] top_pos = pos while fill_lines > 0: prev, pos = self._body.get_prev(pos) if prev is None: # run out of widgets above? offset_rows -= fill_lines break top_pos = pos p_rows = prev.rows((maxcol,)) if p_rows: # filter out 0-height widgets fill_above.append(VisibleInfoFillItem(prev, pos, p_rows)) if p_rows > fill_lines: # crosses top edge? trim_top = p_rows - fill_lines break fill_lines -= p_rows trim_bottom = max(focus_rows + offset_rows - inset_rows - maxrow, 0) # 3. collect the widgets below the focus pos = focus_pos fill_lines = maxrow - focus_rows - offset_rows + inset_rows fill_below = [] while fill_lines > 0: next_pos, pos = self._body.get_next(pos) if next_pos is None: # run out of widgets below? break n_rows = next_pos.rows((maxcol,)) if n_rows: # filter out 0-height widgets fill_below.append(VisibleInfoFillItem(next_pos, pos, n_rows)) if n_rows > fill_lines: # crosses bottom edge? trim_bottom = n_rows - fill_lines fill_lines -= n_rows break fill_lines -= n_rows # 4. fill from top again if necessary & possible fill_lines = max(0, fill_lines) if fill_lines > 0 and trim_top > 0: if fill_lines <= trim_top: trim_top -= fill_lines offset_rows += fill_lines fill_lines = 0 else: fill_lines -= trim_top offset_rows += trim_top trim_top = 0 pos = top_pos while fill_lines > 0: prev, pos = self._body.get_prev(pos) if prev is None: break p_rows = prev.rows((maxcol,)) fill_above.append(VisibleInfoFillItem(prev, pos, p_rows)) if p_rows > fill_lines: # more than required trim_top = p_rows - fill_lines offset_rows += fill_lines break fill_lines -= p_rows offset_rows += p_rows # 5. return the interesting bits return VisibleInfo( VisibleInfoMiddle(offset_rows - inset_rows, focus_widget, focus_pos, focus_rows, cursor), VisibleInfoTopBottom(trim_top, fill_above), VisibleInfoTopBottom(trim_bottom, fill_below), ) def _check_support_scrolling(self) -> None: from .treetools import TreeWalker if not isinstance(self._body, ScrollSupportingBody): raise ListBoxError(f"{self} body do not implement methods required for scrolling protocol") if not isinstance(self._body, (Sized, EstimatedSized, TreeWalker)): raise ListBoxError( f"{self} body is not a Sized, can not estimate it's size and not a TreeWalker." f"Scroll is not allowed due to risk of infinite cycle of widgets load." ) if getattr(self._body, "wrap_around", False): raise ListBoxError("Body is wrapped around. Scroll position calculation is undefined.") def get_scrollpos(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: """Current scrolling position.""" self._check_support_scrolling() if not self._body: return 0 if size is not None: self._rendered_size = size mid, top, _bottom = self.calculate_visible(self._rendered_size, focus) start_row = top.trim maxcol = self._rendered_size[0] if top.fill: pos = top.fill[-1].position else: pos = mid.focus_pos prev, pos = self._body.get_prev(pos) while prev is not None: start_row += prev.rows((maxcol,)) prev, pos = self._body.get_prev(pos) return start_row def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: """Scrollable protocol for sized iterable and not wrapped around contents.""" self._check_support_scrolling() if size is not None: self._rendered_size = size if size or not self._rows_max_cached: cols = self._rendered_size[0] rows = 0 focused_w, idx = self.body.get_focus() if focused_w: rows += focused_w.rows((cols,), focus) prev, pos = self._body.get_prev(idx) while prev is not None: rows += prev.rows((cols,), False) prev, pos = self._body.get_prev(pos) next_, pos = self.body.get_next(idx) while next_ is not None: rows += next_.rows((cols,), True) next_, pos = self._body.get_next(pos) self._rows_max_cached = rows return self._rows_max_cached def require_relative_scroll(self, size: tuple[int, int], focus: bool = False) -> bool: """Widget require relative scroll due to performance limitations of real lines count calculation.""" return isinstance(self._body, (Sized, EstimatedSized)) and (size[1] * 3 < operator.length_hint(self.body)) def get_first_visible_pos(self, size: tuple[int, int], focus: bool = False) -> int: self._check_support_scrolling() if not self._body: return 0 _mid, top, _bottom = self.calculate_visible(size, focus) if top.fill: first_pos = top.fill[-1].position else: first_pos = self.focus_position over = 0 _widget, first_pos = self.body.get_prev(first_pos) while first_pos is not None: over += 1 _widget, first_pos = self.body.get_prev(first_pos) return over def get_visible_amount(self, size: tuple[int, int], focus: bool = False) -> int: self._check_support_scrolling() if not self._body: return 1 _mid, top, bottom = self.calculate_visible(size, focus) return 1 + len(top.fill) + len(bottom.fill) def render( self, size: tuple[int, int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas | SolidCanvas: """ Render ListBox and return canvas. see :meth:`Widget.render` for details """ (maxcol, maxrow) = size self._rendered_size = size middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus) if middle is None: return SolidCanvas(" ", maxcol, maxrow) _ignore, focus_widget, focus_pos, focus_rows, cursor = middle # pylint: disable=unpacking-non-sequence trim_top, fill_above = top # pylint: disable=unpacking-non-sequence trim_bottom, fill_below = bottom # pylint: disable=unpacking-non-sequence combinelist: list[tuple[Canvas, int, bool]] = [] rows = 0 fill_above.reverse() # fill_above is in bottom-up order for widget, w_pos, w_rows in fill_above: canvas = widget.render((maxcol,)) if w_rows != canvas.rows(): raise ListBoxError( f"Widget {widget!r} at position {w_pos!r} " f"within listbox calculated {w_rows:d} rows " f"but rendered {canvas.rows():d}!" ) rows += w_rows combinelist.append((canvas, w_pos, False)) focus_canvas = focus_widget.render((maxcol,), focus=focus) if focus_canvas.rows() != focus_rows: raise ListBoxError( f"Focus Widget {focus_widget!r} at position {focus_pos!r} " f"within listbox calculated {focus_rows:d} rows " f"but rendered {focus_canvas.rows():d}!" ) c_cursor = focus_canvas.cursor if cursor is not None and cursor != c_cursor: raise ListBoxError( f"Focus Widget {focus_widget!r} at position {focus_pos!r} " f"within listbox calculated cursor coords {cursor!r} " f"but rendered cursor coords {c_cursor!r}!" ) rows += focus_rows combinelist.append((focus_canvas, focus_pos, True)) for widget, w_pos, w_rows in fill_below: canvas = widget.render((maxcol,)) if w_rows != canvas.rows(): raise ListBoxError( f"Widget {widget!r} at position {w_pos!r} " f"within listbox calculated {w_rows:d} " f"rows but rendered {canvas.rows():d}!" ) rows += w_rows combinelist.append((canvas, w_pos, False)) final_canvas = CanvasCombine(combinelist) if trim_top: final_canvas.trim(trim_top) rows -= trim_top if trim_bottom: final_canvas.trim_end(trim_bottom) rows -= trim_bottom if rows > maxrow: raise ListBoxError( f"Listbox contents too long!\nRender top={top!r}, middle={middle!r}, bottom={bottom!r}\n" ) if rows < maxrow: if trim_bottom != 0: raise ListBoxError( f"Listbox contents too short!\n" f"Render top={top!r}, middle={middle!r}, bottom={bottom!r}\n" f"Trim bottom={trim_bottom!r}" ) bottom_pos = focus_pos if fill_below: bottom_pos = fill_below[-1][1] rendered_positions = frozenset(idx for _, idx, _ in combinelist) widget, next_pos = self._body.get_next(bottom_pos) while all( ( widget is not None, next_pos is not None, next_pos not in rendered_positions, ) ): if widget.rows((maxcol,), False): raise ListBoxError( f"Listbox contents too short!\n" f"Render top={top!r}, middle={middle!r}, bottom={bottom!r}\n" f"Not rendered not empty widgets available (first is {widget!r} with position {next_pos!r})" ) widget, next_next_pos = self._body.get_next(next_pos) if next_pos == next_next_pos: raise ListBoxError( f"Next position after {next_pos!r} is invalid (points to itself)\n" f"Looks like bug with {self._body!r}" ) next_pos = next_next_pos final_canvas.pad_trim_top_bottom(0, maxrow - rows) return final_canvas def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None: """ See :meth:`Widget.get_cursor_coords` for details """ (maxcol, maxrow) = size middle, _top, _bottom = self.calculate_visible((maxcol, maxrow), True) if middle is None: return None offset_inset, _ignore1, _ignore2, _ignore3, cursor = middle # pylint: disable=unpacking-non-sequence if not cursor: return None x, y = cursor y += offset_inset if y < 0 or y >= maxrow: return None return (x, y) def set_focus_valign( self, valign: Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int], ): """Set the focus widget's display offset and inset. :param valign: one of: 'top', 'middle', 'bottom' ('relative', percentage 0=top 100=bottom) """ vt, va = normalize_valign(valign, ListBoxError) self.set_focus_valign_pending = vt, va def set_focus(self, position, coming_from: Literal["above", "below"] | None = None) -> None: """ Set the focus position and try to keep the old focus in view. :param position: a position compatible with :meth:`self._body.set_focus` :param coming_from: set to 'above' or 'below' if you know that old position is above or below the new position. :type coming_from: str """ if coming_from not in {"above", "below", None}: raise ListBoxError(f"coming_from value invalid: {coming_from!r}") focus_widget, focus_pos = self._body.get_focus() if focus_widget is None: raise IndexError("Can't set focus, ListBox is empty") self.set_focus_pending = coming_from, focus_widget, focus_pos self._body.set_focus(position) def get_focus(self): """ Return a `(focus widget, focus position)` tuple, for backwards compatibility. You may also use the new standard container properties :attr:`focus` and :attr:`focus_position` to read these values. """ warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus` to get the focus " "and property `focus_position` to read these values.", PendingDeprecationWarning, stacklevel=2, ) return self._body.get_focus() @property def focus(self) -> Widget | None: """ the child widget in focus or None when ListBox is empty. Return the widget in focus according to our :obj:`list walker <ListWalker>`. """ return self._body.get_focus()[0] def _get_focus(self) -> Widget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) return self.focus def _get_focus_position(self): """ Return the list walker position of the widget in focus. The type of value returned depends on the :obj:`list walker <ListWalker>`. """ w, pos = self._body.get_focus() if w is None: raise IndexError("No focus_position, ListBox is empty") return pos focus_position = property( _get_focus_position, set_focus, doc=""" the position of child widget in focus. The valid values for this position depend on the list walker in use. :exc:`IndexError` will be raised by reading this property when the ListBox is empty or setting this property to an invalid position. """, ) def _contents(self): # noinspection PyMethodParameters class ListBoxContents: # pylint: disable=no-self-argument __getitem__ = self._contents__getitem__ __len__ = self.__len__ def __repr__(inner_self) -> str: return f"<{inner_self.__class__.__name__} for {self!r} at 0x{id(inner_self):X}>" def __call__(inner_self) -> Self: warnings.warn( "ListBox.contents is a property, not a method", DeprecationWarning, stacklevel=3, ) return inner_self return ListBoxContents() def _contents__getitem__(self, key): # try list walker protocol v2 first if hasattr(self._body, "__getitem__"): try: return (self._body[key], None) except (IndexError, KeyError) as exc: raise KeyError(f"ListBox.contents key not found: {key!r}").with_traceback(exc.__traceback__) from exc # fall back to v1 _w, old_focus = self._body.get_focus() try: self._body.set_focus(key) return self._body.get_focus()[0] except (IndexError, KeyError) as exc: raise KeyError(f"ListBox.contents key not found: {key!r}").with_traceback(exc.__traceback__) from exc finally: self._body.set_focus(old_focus) @property def contents(self): """ An object that allows reading widgets from the ListBox's list walker as a `(widget, options)` tuple. `None` is currently the only value for options. .. warning:: This object may not be used to set or iterate over contents. You must use the list walker stored as :attr:`.body` to perform manipulation and iteration, if supported. """ return self._contents() def options(self): """ There are currently no options for ListBox contents. Return None as a placeholder for future options. """ def _set_focus_valign_complete(self, size: tuple[int, int], focus: bool) -> None: """Finish setting the offset and inset now that we have have a maxcol & maxrow.""" (maxcol, maxrow) = size vt, va = self.set_focus_valign_pending self.set_focus_valign_pending = None self.set_focus_pending = None focus_widget, _focus_pos = self._body.get_focus() if focus_widget is None: return rows = focus_widget.rows((maxcol,), focus) rtop, _rbot = calculate_top_bottom_filler( maxrow, vt, va, WHSettings.GIVEN, rows, None, 0, 0, ) self.shift_focus((maxcol, maxrow), rtop) def _set_focus_first_selectable(self, size: tuple[int, int], focus: bool) -> None: """Choose the first visible, selectable widget below the current focus as the focus widget.""" (maxcol, maxrow) = size self.set_focus_valign_pending = None self.set_focus_pending = None middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus) if middle is None: return row_offset, focus_widget, _focus_pos, focus_rows, _cursor = middle # pylint: disable=unpacking-non-sequence _trim_top, _fill_above = top # pylint: disable=unpacking-non-sequence trim_bottom, fill_below = bottom # pylint: disable=unpacking-non-sequence if focus_widget.selectable(): return if trim_bottom: fill_below = fill_below[:-1] new_row_offset = row_offset + focus_rows for widget, pos, rows in fill_below: if widget.selectable(): self._body.set_focus(pos) self.shift_focus((maxcol, maxrow), new_row_offset) return new_row_offset += rows def _set_focus_complete(self, size: tuple[int, int], focus: bool) -> None: """Finish setting the position now that we have maxcol & maxrow.""" (maxcol, maxrow) = size self._invalidate() if self.set_focus_pending == "first selectable": return self._set_focus_first_selectable((maxcol, maxrow), focus) if self.set_focus_valign_pending is not None: return self._set_focus_valign_complete((maxcol, maxrow), focus) coming_from, _focus_widget, focus_pos = self.set_focus_pending self.set_focus_pending = None # new position _new_focus_widget, position = self._body.get_focus() if focus_pos == position: # do nothing return None # restore old focus temporarily self._body.set_focus(focus_pos) middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus) focus_offset, _focus_widget, focus_pos, focus_rows, _cursor = middle # pylint: disable=unpacking-non-sequence _trim_top, fill_above = top # pylint: disable=unpacking-non-sequence _trim_bottom, fill_below = bottom # pylint: disable=unpacking-non-sequence offset = focus_offset for _widget, pos, rows in fill_above: offset -= rows if pos == position: self.change_focus((maxcol, maxrow), pos, offset, "below") return None offset = focus_offset + focus_rows for _widget, pos, rows in fill_below: if pos == position: self.change_focus((maxcol, maxrow), pos, offset, "above") return None offset += rows # failed to find widget among visible widgets self._body.set_focus(position) widget, position = self._body.get_focus() rows = widget.rows((maxcol,), focus) if coming_from == "below": offset = 0 elif coming_from == "above": offset = maxrow - rows else: offset = (maxrow - rows) // 2 self.shift_focus((maxcol, maxrow), offset) return None def shift_focus(self, size: tuple[int, int], offset_inset: int) -> None: """ Move the location of the current focus relative to the top. This is used internally by methods that know the widget's *size*. See also :meth:`.set_focus_valign`. :param size: see :meth:`Widget.render` for details :param offset_inset: either the number of rows between the top of the listbox and the start of the focus widget (+ve value) or the number of lines of the focus widget hidden off the top edge of the listbox (-ve value) or ``0`` if the top edge of the focus widget is aligned with the top edge of the listbox. :type offset_inset: int """ (maxcol, maxrow) = size if offset_inset >= 0: if offset_inset >= maxrow: raise ListBoxError(f"Invalid offset_inset: {offset_inset!r}, only {maxrow!r} rows in list box") self.offset_rows = offset_inset self.inset_fraction = (0, 1) else: target, _ignore = self._body.get_focus() tgt_rows = target.rows((maxcol,), True) if offset_inset + tgt_rows <= 0: raise ListBoxError(f"Invalid offset_inset: {offset_inset!r}, only {tgt_rows!r} rows in target!") self.offset_rows = 0 self.inset_fraction = (-offset_inset, tgt_rows) self._invalidate() def update_pref_col_from_focus(self, size: tuple[int, int]) -> None: """Update self.pref_col from the focus widget.""" # TODO: should this not be private? (maxcol, _maxrow) = size widget, _old_pos = self._body.get_focus() if widget is None: return pref_col = None if hasattr(widget, "get_pref_col"): pref_col = widget.get_pref_col((maxcol,)) if pref_col is None and hasattr(widget, "get_cursor_coords"): coords = widget.get_cursor_coords((maxcol,)) if isinstance(coords, tuple): pref_col, _y = coords if pref_col is not None: self.pref_col = pref_col def change_focus( self, size: tuple[int, int], position, offset_inset: int = 0, coming_from: Literal["above", "below"] | None = None, cursor_coords: tuple[int, int] | None = None, snap_rows: int | None = None, ) -> None: """ Change the current focus widget. This is used internally by methods that know the widget's *size*. See also :meth:`.set_focus`. :param size: see :meth:`Widget.render` for details :param position: a position compatible with :meth:`self._body.set_focus` :param offset_inset: either the number of rows between the top of the listbox and the start of the focus widget (+ve value) or the number of lines of the focus widget hidden off the top edge of the listbox (-ve value) or 0 if the top edge of the focus widget is aligned with the top edge of the listbox (default if unspecified) :type offset_inset: int :param coming_from: either 'above', 'below' or unspecified `None` :type coming_from: str :param cursor_coords: (x, y) tuple indicating the desired column and row for the cursor, a (x,) tuple indicating only the column for the cursor, or unspecified :type cursor_coords: (int, int) :param snap_rows: the maximum number of extra rows to scroll when trying to "snap" a selectable focus into the view :type snap_rows: int """ (maxcol, maxrow) = size # update pref_col before change if cursor_coords: self.pref_col = cursor_coords[0] else: self.update_pref_col_from_focus((maxcol, maxrow)) self._invalidate() self._body.set_focus(position) target, _ignore = self._body.get_focus() tgt_rows = target.rows((maxcol,), True) if snap_rows is None: snap_rows = maxrow - 1 # "snap" to selectable widgets align_top = 0 align_bottom = maxrow - tgt_rows if coming_from == "above" and target.selectable() and offset_inset > align_bottom: if snap_rows >= offset_inset - align_bottom: offset_inset = align_bottom elif snap_rows >= offset_inset - align_top: offset_inset = align_top else: offset_inset -= snap_rows if coming_from == "below" and target.selectable() and offset_inset < align_top: if snap_rows >= align_top - offset_inset: offset_inset = align_top elif snap_rows >= align_bottom - offset_inset: offset_inset = align_bottom else: offset_inset += snap_rows # convert offset_inset to offset_rows or inset_fraction if offset_inset >= 0: self.offset_rows = offset_inset self.inset_fraction = (0, 1) else: if offset_inset + tgt_rows <= 0: raise ListBoxError(f"Invalid offset_inset: {offset_inset}, only {tgt_rows} rows in target!") self.offset_rows = 0 self.inset_fraction = (-offset_inset, tgt_rows) if cursor_coords is None: if coming_from is None: return # must either know row or coming_from cursor_coords = (self.pref_col,) if not hasattr(target, "move_cursor_to_coords"): return attempt_rows = [] if len(cursor_coords) == 1: # only column (not row) specified # start from closest edge and move inwards (pref_col,) = cursor_coords if coming_from == "above": attempt_rows = range(0, tgt_rows) else: if coming_from != "below": raise ValueError("must specify coming_from ('above' or 'below') if cursor row is not specified") attempt_rows = range(tgt_rows, -1, -1) else: # both column and row specified # start from preferred row and move back to closest edge (pref_col, pref_row) = cursor_coords if pref_row < 0 or pref_row >= tgt_rows: raise ListBoxError( f"cursor_coords row outside valid range for target. pref_row:{pref_row!r} target_rows:{tgt_rows!r}" ) if coming_from == "above": attempt_rows = range(pref_row, -1, -1) elif coming_from == "below": attempt_rows = range(pref_row, tgt_rows) else: attempt_rows = [pref_row] for row in attempt_rows: if target.move_cursor_to_coords((maxcol,), pref_col, row): break def get_focus_offset_inset(self, size: tuple[int, int]) -> tuple[int, int]: """Return (offset rows, inset rows) for focus widget.""" (maxcol, _maxrow) = size focus_widget, _pos = self._body.get_focus() focus_rows = focus_widget.rows((maxcol,), True) offset_rows = self.offset_rows inset_rows = 0 if offset_rows == 0: inum, iden = self.inset_fraction if inum < 0 or iden < 0 or inum >= iden: raise ListBoxError(f"Invalid inset_fraction: {self.inset_fraction!r}") inset_rows = focus_rows * inum // iden if inset_rows and inset_rows >= focus_rows: raise ListBoxError("urwid inset_fraction error (please report)") return offset_rows, inset_rows def make_cursor_visible(self, size: tuple[int, int]) -> None: """Shift the focus widget so that its cursor is visible.""" (maxcol, maxrow) = size focus_widget, _pos = self._body.get_focus() if focus_widget is None: return if not focus_widget.selectable(): return if not hasattr(focus_widget, "get_cursor_coords"): return cursor = focus_widget.get_cursor_coords((maxcol,)) if cursor is None: return _cx, cy = cursor offset_rows, inset_rows = self.get_focus_offset_inset((maxcol, maxrow)) if cy < inset_rows: self.shift_focus((maxcol, maxrow), -(cy)) return if offset_rows - inset_rows + cy >= maxrow: self.shift_focus((maxcol, maxrow), maxrow - cy - 1) return def keypress( self, size: tuple[int, int], # type: ignore[override] key: str, ) -> str | None: """Move selection through the list elements scrolling when necessary. Keystrokes are first passed to widget in focus in case that widget can handle them. Keystrokes handled by this widget are: 'up' up one line (or widget) 'down' down one line (or widget) 'page up' move cursor up one listbox length (or widget) 'page down' move cursor down one listbox length (or widget) """ from urwid.command_map import Command (maxcol, maxrow) = size if self.set_focus_pending or self.set_focus_valign_pending: self._set_focus_complete((maxcol, maxrow), focus=True) focus_widget, _pos = self._body.get_focus() if focus_widget is None: # empty listbox, can't do anything return key if focus_widget.selectable(): key = focus_widget.keypress((maxcol,), key) if key is None: self.make_cursor_visible((maxcol, maxrow)) return None def actual_key(unhandled) -> str | None: if unhandled: return key return None # pass off the heavy lifting if self._command_map[key] == Command.UP: return actual_key(self._keypress_up((maxcol, maxrow))) if self._command_map[key] == Command.DOWN: return actual_key(self._keypress_down((maxcol, maxrow))) if self._command_map[key] == Command.PAGE_UP: return actual_key(self._keypress_page_up((maxcol, maxrow))) if self._command_map[key] == Command.PAGE_DOWN: return actual_key(self._keypress_page_down((maxcol, maxrow))) if self._command_map[key] == Command.MAX_LEFT: return actual_key(self._keypress_max_left((maxcol, maxrow))) if self._command_map[key] == Command.MAX_RIGHT: return actual_key(self._keypress_max_right((maxcol, maxrow))) return key def _keypress_max_left(self, size: tuple[int, int]) -> None: self.focus_position = next(iter(self.body.positions())) self.set_focus_valign(VAlign.TOP) def _keypress_max_right(self, size: tuple[int, int]) -> None: self.focus_position = next(iter(self.body.positions(reverse=True))) self.set_focus_valign(VAlign.BOTTOM) def _keypress_up(self, size: tuple[int, int]) -> bool | None: (maxcol, maxrow) = size middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True) if middle is None: return True focus_row_offset, focus_widget, focus_pos, _ignore, cursor = middle # pylint: disable=unpacking-non-sequence _trim_top, fill_above = top # pylint: disable=unpacking-non-sequence row_offset = focus_row_offset # look for selectable widget above pos = focus_pos widget = None for widget, pos, rows in fill_above: row_offset -= rows if rows and widget.selectable(): # this one will do self.change_focus((maxcol, maxrow), pos, row_offset, "below") return None # at this point we must scroll row_offset += 1 self._invalidate() while row_offset > 0: # need to scroll in another candidate widget widget, pos = self._body.get_prev(pos) if widget is None: # cannot scroll any further return True # keypress not handled rows = widget.rows((maxcol,), True) row_offset -= rows if rows and widget.selectable(): # this one will do self.change_focus((maxcol, maxrow), pos, row_offset, "below") return None if not focus_widget.selectable() or focus_row_offset + 1 >= maxrow: # just take top one if focus is not selectable # or if focus has moved out of view if widget is None: self.shift_focus((maxcol, maxrow), row_offset) return None self.change_focus((maxcol, maxrow), pos, row_offset, "below") return None # check if cursor will stop scroll from taking effect if cursor is not None: _x, y = cursor if y + focus_row_offset + 1 >= maxrow: # cursor position is a problem, # choose another focus if widget is None: # try harder to get prev widget widget, pos = self._body.get_prev(pos) if widget is None: return None # can't do anything rows = widget.rows((maxcol,), True) row_offset -= rows if -row_offset >= rows: # must scroll further than 1 line row_offset = -(rows - 1) self.change_focus((maxcol, maxrow), pos, row_offset, "below") return None # if all else fails, just shift the current focus. self.shift_focus((maxcol, maxrow), focus_row_offset + 1) return None def _keypress_down(self, size: tuple[int, int]) -> bool | None: (maxcol, maxrow) = size middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True) if middle is None: return True focus_row_offset, focus_widget, focus_pos, focus_rows, cursor = middle # pylint: disable=unpacking-non-sequence _trim_bottom, fill_below = bottom # pylint: disable=unpacking-non-sequence row_offset = focus_row_offset + focus_rows rows = focus_rows # look for selectable widget below pos = focus_pos widget = None for widget, pos, rows in fill_below: if rows and widget.selectable(): # this one will do self.change_focus((maxcol, maxrow), pos, row_offset, "above") return None row_offset += rows # at this point we must scroll row_offset -= 1 self._invalidate() while row_offset < maxrow: # need to scroll in another candidate widget widget, pos = self._body.get_next(pos) if widget is None: # cannot scroll any further return True # keypress not handled rows = widget.rows((maxcol,)) if rows and widget.selectable(): # this one will do self.change_focus((maxcol, maxrow), pos, row_offset, "above") return None row_offset += rows if not focus_widget.selectable() or focus_row_offset + focus_rows - 1 <= 0: # just take bottom one if current is not selectable # or if focus has moved out of view if widget is None: self.shift_focus((maxcol, maxrow), row_offset - rows) return None self.change_focus((maxcol, maxrow), pos, row_offset - rows, "above") return None # check if cursor will stop scroll from taking effect if cursor is not None: _x, y = cursor if y + focus_row_offset - 1 < 0: # cursor position is a problem, # choose another focus if widget is None: # try harder to get next widget widget, pos = self._body.get_next(pos) if widget is None: return None # can't do anything else: row_offset -= rows if row_offset >= maxrow: # must scroll further than 1 line row_offset = maxrow - 1 self.change_focus( (maxcol, maxrow), pos, row_offset, "above", ) return None # if all else fails, keep the current focus. self.shift_focus((maxcol, maxrow), focus_row_offset - 1) return None def _keypress_page_up(self, size: tuple[int, int]) -> bool | None: (maxcol, maxrow) = size middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True) if middle is None: return True row_offset, focus_widget, focus_pos, focus_rows, cursor = middle # pylint: disable=unpacking-non-sequence _trim_top, fill_above = top # pylint: disable=unpacking-non-sequence # topmost_visible is row_offset rows above top row of # focus (+ve) or -row_offset rows below top row of focus (-ve) topmost_visible = row_offset # scroll_from_row is (first match) # 1. topmost visible row if focus is not selectable # 2. row containing cursor if focus has a cursor # 3. top row of focus widget if it is visible # 4. topmost visible row otherwise if not focus_widget.selectable(): scroll_from_row = topmost_visible elif cursor is not None: _x, y = cursor scroll_from_row = -y elif row_offset >= 0: scroll_from_row = 0 else: scroll_from_row = topmost_visible # snap_rows is maximum extra rows to scroll when # snapping to new a focus snap_rows = topmost_visible - scroll_from_row # move row_offset to the new desired value (1 "page" up) row_offset = scroll_from_row + maxrow # not used below: scroll_from_row = topmost_visible = None # gather potential target widgets and add current focus t = [(row_offset, focus_widget, focus_pos, focus_rows)] pos = focus_pos # include widgets from calculate_visible(..) for widget, pos, rows in fill_above: row_offset -= rows t.append((row_offset, widget, pos, rows)) # add newly visible ones, including within snap_rows snap_region_start = len(t) while row_offset > -snap_rows: widget, pos = self._body.get_prev(pos) if widget is None: break rows = widget.rows((maxcol,)) row_offset -= rows # determine if one below puts current one into snap rgn if row_offset > 0: snap_region_start += 1 t.append((row_offset, widget, pos, rows)) # if we can't fill the top we need to adjust the row offsets row_offset, _w, _p, _r = t[-1] if row_offset > 0: adjust = -row_offset t = [(ro + adjust, w, p, r) for (ro, w, p, r) in t] # if focus_widget (first in t) is off edge, remove it row_offset, _w, _p, _r = t[0] if row_offset >= maxrow: del t[0] snap_region_start -= 1 # we'll need this soon self.update_pref_col_from_focus((maxcol, maxrow)) # choose the topmost selectable and (newly) visible widget # search within snap_rows then visible region search_order = list(range(snap_region_start, len(t))) + list(range(snap_region_start - 1, -1, -1)) # assert 0, repr((t, search_order)) bad_choices = [] cut_off_selectable_chosen = 0 for i in search_order: row_offset, widget, pos, rows = t[i] if not widget.selectable(): continue if not rows: continue # try selecting this widget pref_row = max(0, -row_offset) # if completely within snap region, adjust row_offset if rows + row_offset <= 0: self.change_focus( (maxcol, maxrow), pos, -(rows - 1), "below", (self.pref_col, rows - 1), snap_rows - ((-row_offset) - (rows - 1)), ) else: self.change_focus( (maxcol, maxrow), pos, row_offset, "below", (self.pref_col, pref_row), snap_rows, ) # if we're as far up as we can scroll, take this one if fill_above and self._body.get_prev(fill_above[-1][1]) == (None, None): pass # return # find out where that actually puts us middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True) act_row_offset, _ign1, _ign2, _ign3, _ign4 = middle # pylint: disable=unpacking-non-sequence # discard chosen widget if it will reduce scroll amount # because of a fixed cursor (absolute last resort) if act_row_offset > row_offset + snap_rows: bad_choices.append(i) continue if act_row_offset < row_offset: bad_choices.append(i) continue # also discard if off top edge (second last resort) if act_row_offset < 0: bad_choices.append(i) cut_off_selectable_chosen = 1 continue return None # anything selectable is better than what follows: if cut_off_selectable_chosen: return None if fill_above and focus_widget.selectable() and self._body.get_prev(fill_above[-1][1]) == (None, None): # if we're at the top and have a selectable, return pass # return # if still none found choose the topmost widget good_choices = [j for j in search_order if j not in bad_choices] for i in good_choices + search_order: row_offset, widget, pos, rows = t[i] if pos == focus_pos: continue if not rows: # never focus a 0-height widget continue # if completely within snap region, adjust row_offset if rows + row_offset <= 0: snap_rows -= (-row_offset) - (rows - 1) row_offset = -(rows - 1) self.change_focus((maxcol, maxrow), pos, row_offset, "below", None, snap_rows) return None # no choices available, just shift current one self.shift_focus((maxcol, maxrow), min(maxrow - 1, row_offset)) # final check for pathological case where we may fall short middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True) act_row_offset, _ign1, pos, _ign2, _ign3 = middle # pylint: disable=unpacking-non-sequence if act_row_offset >= row_offset: # no problem return None # fell short, try to select anything else above if not t: return None _ign1, _ign2, pos, _ign3 = t[-1] widget, pos = self._body.get_prev(pos) if widget is None: # no dice, we're stuck here return None # bring in only one row if possible rows = widget.rows((maxcol,), True) self.change_focus( (maxcol, maxrow), pos, -(rows - 1), "below", (self.pref_col, rows - 1), 0, ) return None def _keypress_page_down(self, size: tuple[int, int]) -> bool | None: (maxcol, maxrow) = size middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True) if middle is None: return True row_offset, focus_widget, focus_pos, focus_rows, cursor = middle # pylint: disable=unpacking-non-sequence _trim_bottom, fill_below = bottom # pylint: disable=unpacking-non-sequence # bottom_edge is maxrow-focus_pos rows below top row of focus bottom_edge = maxrow - row_offset # scroll_from_row is (first match) # 1. bottom edge if focus is not selectable # 2. row containing cursor + 1 if focus has a cursor # 3. bottom edge of focus widget if it is visible # 4. bottom edge otherwise if not focus_widget.selectable(): scroll_from_row = bottom_edge elif cursor is not None: _x, y = cursor scroll_from_row = y + 1 elif bottom_edge >= focus_rows: scroll_from_row = focus_rows else: scroll_from_row = bottom_edge # snap_rows is maximum extra rows to scroll when # snapping to new a focus snap_rows = bottom_edge - scroll_from_row # move row_offset to the new desired value (1 "page" down) row_offset = -scroll_from_row # not used below: scroll_from_row = bottom_edge = None # gather potential target widgets and add current focus t = [(row_offset, focus_widget, focus_pos, focus_rows)] pos = focus_pos row_offset += focus_rows # include widgets from calculate_visible(..) for widget, pos, rows in fill_below: t.append((row_offset, widget, pos, rows)) row_offset += rows # add newly visible ones, including within snap_rows snap_region_start = len(t) while row_offset < maxrow + snap_rows: widget, pos = self._body.get_next(pos) if widget is None: break rows = widget.rows((maxcol,)) t.append((row_offset, widget, pos, rows)) row_offset += rows # determine if one above puts current one into snap rgn if row_offset < maxrow: snap_region_start += 1 # if we can't fill the bottom we need to adjust the row offsets row_offset, _w, _p, rows = t[-1] if row_offset + rows < maxrow: adjust = maxrow - (row_offset + rows) t = [(ro + adjust, w, p, r) for (ro, w, p, r) in t] # if focus_widget (first in t) is off edge, remove it row_offset, _w, _p, rows = t[0] if row_offset + rows <= 0: del t[0] snap_region_start -= 1 # we'll need this soon self.update_pref_col_from_focus((maxcol, maxrow)) # choose the bottommost selectable and (newly) visible widget # search within snap_rows then visible region search_order = list(range(snap_region_start, len(t))) + list(range(snap_region_start - 1, -1, -1)) # assert 0, repr((t, search_order)) bad_choices = [] cut_off_selectable_chosen = 0 for i in search_order: row_offset, widget, pos, rows = t[i] if not widget.selectable(): continue if not rows: continue # try selecting this widget pref_row = min(maxrow - row_offset - 1, rows - 1) # if completely within snap region, adjust row_offset if row_offset >= maxrow: self.change_focus( (maxcol, maxrow), pos, maxrow - 1, "above", (self.pref_col, 0), snap_rows + maxrow - row_offset - 1, ) else: self.change_focus( (maxcol, maxrow), pos, row_offset, "above", (self.pref_col, pref_row), snap_rows, ) # find out where that actually puts us middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True) act_row_offset, _ign1, _ign2, _ign3, _ign4 = middle # pylint: disable=unpacking-non-sequence # discard chosen widget if it will reduce scroll amount # because of a fixed cursor (absolute last resort) if act_row_offset < row_offset - snap_rows: bad_choices.append(i) continue if act_row_offset > row_offset: bad_choices.append(i) continue # also discard if off top edge (second last resort) if act_row_offset + rows > maxrow: bad_choices.append(i) cut_off_selectable_chosen = 1 continue return None # anything selectable is better than what follows: if cut_off_selectable_chosen: return None # if still none found choose the bottommost widget good_choices = [j for j in search_order if j not in bad_choices] for i in good_choices + search_order: row_offset, widget, pos, rows = t[i] if pos == focus_pos: continue if not rows: # never focus a 0-height widget continue # if completely within snap region, adjust row_offset if row_offset >= maxrow: snap_rows -= snap_rows + maxrow - row_offset - 1 row_offset = maxrow - 1 self.change_focus((maxcol, maxrow), pos, row_offset, "above", None, snap_rows) return None # no choices available, just shift current one self.shift_focus((maxcol, maxrow), max(1 - focus_rows, row_offset)) # final check for pathological case where we may fall short middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True) act_row_offset, _ign1, pos, _ign2, _ign3 = middle # pylint: disable=unpacking-non-sequence if act_row_offset <= row_offset: # no problem return None # fell short, try to select anything else below if not t: return None _ign1, _ign2, pos, _ign3 = t[-1] widget, pos = self._body.get_next(pos) if widget is None: # no dice, we're stuck here return None # bring in only one row if possible rows = widget.rows((maxcol,), True) self.change_focus( (maxcol, maxrow), pos, maxrow - 1, "above", (self.pref_col, 0), 0, ) return None def mouse_event( self, size: tuple[int, int], # type: ignore[override] event, button: int, col: int, row: int, focus: bool, ) -> bool | None: """ Pass the event to the contained widgets. May change focus on button 1 press. """ from urwid.util import is_mouse_press (maxcol, maxrow) = size middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=True) if middle is None: return False _ignore, focus_widget, focus_pos, focus_rows, _cursor = middle # pylint: disable=unpacking-non-sequence trim_top, fill_above = top # pylint: disable=unpacking-non-sequence _ignore, fill_below = bottom # pylint: disable=unpacking-non-sequence fill_above.reverse() # fill_above is in bottom-up order w_list = [*fill_above, (focus_widget, focus_pos, focus_rows), *fill_below] wrow = -trim_top for w, w_pos, w_rows in w_list: # noqa: B007 # magic with scope if wrow + w_rows > row: break wrow += w_rows else: return False focus = focus and w == focus_widget if is_mouse_press(event) and button == 1 and w.selectable(): self.change_focus((maxcol, maxrow), w_pos, wrow) if not hasattr(w, "mouse_event"): warnings.warn( f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget", DeprecationWarning, stacklevel=2, ) return False handled = w.mouse_event((maxcol,), event, button, col, row - wrow, focus) if handled: return True if is_mouse_press(event): if button == 4: return not self._keypress_up((maxcol, maxrow)) if button == 5: return not self._keypress_down((maxcol, maxrow)) return False def ends_visible(self, size: tuple[int, int], focus: bool = False) -> list[Literal["top", "bottom"]]: """ Return a list that may contain ``'top'`` and/or ``'bottom'``. i.e. this function will return one of: [], [``'top'``], [``'bottom'``] or [``'top'``, ``'bottom'``]. convenience function for checking whether the top and bottom of the list are visible """ (maxcol, maxrow) = size result = [] middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus) if middle is None: # empty listbox return ["top", "bottom"] trim_top, above = top # pylint: disable=unpacking-non-sequence trim_bottom, below = bottom # pylint: disable=unpacking-non-sequence if trim_bottom == 0: row_offset, _w, pos, rows, _c = middle # pylint: disable=unpacking-non-sequence row_offset += rows for _w, pos, rows in below: # noqa: B007 # magic with scope row_offset += rows if row_offset < maxrow or (self._body.get_next(pos) == (None, None)): result.append("bottom") if trim_top == 0: row_offset, _w, pos, _rows, _c = middle # pylint: disable=unpacking-non-sequence for _w, pos, rows in above: # noqa: B007 # magic with scope row_offset -= rows if self._body.get_prev(pos) == (None, None): result.insert(0, "top") return result def __iter__(self): """ Return an iterator over the positions in this ListBox. If self._body does not implement positions() then iterate from the focus widget down to the bottom, then from above the focus up to the top. This is the best we can do with a minimal list walker implementation. """ positions_fn = getattr(self._body, "positions", None) if positions_fn: yield from positions_fn() return focus_widget, focus_pos = self._body.get_focus() if focus_widget is None: return pos = focus_pos while True: yield pos w, pos = self._body.get_next(pos) if not w: break pos = focus_pos while True: w, pos = self._body.get_prev(pos) if not w: break yield pos def __reversed__(self): """ Return a reversed iterator over the positions in this ListBox. If :attr:`body` does not implement :meth:`positions` then iterate from above the focus widget up to the top, then from the focus widget down to the bottom. Note that this is not actually the reverse of what `__iter__()` produces, but this is the best we can do with a minimal list walker implementation. """ positions_fn = getattr(self._body, "positions", None) if positions_fn: yield from positions_fn(reverse=True) return focus_widget, focus_pos = self._body.get_focus() if focus_widget is None: return pos = focus_pos while True: w, pos = self._body.get_prev(pos) if not w: break yield pos pos = focus_pos while True: yield pos w, pos = self._body.get_next(pos) if not w: break
74,454
Python
.py
1,691
32.885866
120
0.574345
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,249
widget_decoration.py
urwid_urwid/urwid/widget/widget_decoration.py
from __future__ import annotations import typing import warnings from urwid.canvas import CompositeCanvas from .widget import Widget, WidgetError, WidgetWarning, delegate_to_widget_mixin if typing.TYPE_CHECKING: from typing_extensions import Literal from .constants import Sizing __all__ = ( "WidgetDecoration", "WidgetDisable", "WidgetError", "WidgetPlaceholder", "WidgetWarning", "delegate_to_widget_mixin", ) WrappedWidget = typing.TypeVar("WrappedWidget") class WidgetDecoration(Widget, typing.Generic[WrappedWidget]): # pylint: disable=abstract-method """ original_widget -- the widget being decorated This is a base class for decoration widgets, widgets that contain one or more widgets and only ever have a single focus. This type of widget will affect the display or behaviour of the original_widget, but it is not part of determining a chain of focus. Don't actually do this -- use a WidgetDecoration subclass instead, these are not real widgets: >>> from urwid import Text >>> WidgetDecoration(Text(u"hi")) <WidgetDecoration fixed/flow widget <Text fixed/flow widget 'hi'>> .. Warning: WidgetDecoration do not implement ``render`` method. Implement it or forward to the widget in the subclass. """ def __init__(self, original_widget: WrappedWidget) -> None: # TODO(Aleksei): reduce amount of multiple inheritance usage # Special case: subclasses with multiple inheritance causes `super` call wrong way # Call parent __init__ explicit Widget.__init__(self) if not isinstance(original_widget, Widget): obj_class_path = f"{original_widget.__class__.__module__}.{original_widget.__class__.__name__}" warnings.warn( f"{obj_class_path} is not subclass of Widget", DeprecationWarning, stacklevel=2, ) self._original_widget = original_widget def _repr_words(self) -> list[str]: return [*super()._repr_words(), repr(self._original_widget)] @property def original_widget(self) -> WrappedWidget: return self._original_widget @original_widget.setter def original_widget(self, original_widget: WrappedWidget) -> None: self._original_widget = original_widget self._invalidate() def _get_original_widget(self) -> WrappedWidget: warnings.warn( f"Method `{self.__class__.__name__}._get_original_widget` is deprecated, " f"please use property `{self.__class__.__name__}.original_widget`", DeprecationWarning, stacklevel=2, ) return self.original_widget def _set_original_widget(self, original_widget: WrappedWidget) -> None: warnings.warn( f"Method `{self.__class__.__name__}._set_original_widget` is deprecated, " f"please use property `{self.__class__.__name__}.original_widget`", DeprecationWarning, stacklevel=2, ) self.original_widget = original_widget @property def base_widget(self) -> Widget: """ Return the widget without decorations. If there is only one Decoration then this is the same as original_widget. >>> from urwid import Text >>> t = Text('hello') >>> wd1 = WidgetDecoration(t) >>> wd2 = WidgetDecoration(wd1) >>> wd3 = WidgetDecoration(wd2) >>> wd3.original_widget is wd2 True >>> wd3.base_widget is t True """ visited = {self} w = self while hasattr(w, "_original_widget"): w = w._original_widget if w in visited: break visited.add(w) return w def _get_base_widget(self) -> Widget: warnings.warn( f"Method `{self.__class__.__name__}._get_base_widget` is deprecated, " f"please use property `{self.__class__.__name__}.base_widget`", DeprecationWarning, stacklevel=2, ) return self.base_widget def selectable(self) -> bool: return self._original_widget.selectable() def sizing(self) -> frozenset[Sizing]: return self._original_widget.sizing() class WidgetPlaceholder(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]): """ This is a do-nothing decoration widget that can be used for swapping between widgets without modifying the container of this widget. This can be useful for making an interface with a number of distinct pages or for showing and hiding menu or status bars. The widget displayed is stored as the self.original_widget property and can be changed by assigning a new widget to it. """ class WidgetDisable(WidgetDecoration[WrappedWidget]): """ A decoration widget that disables interaction with the widget it wraps. This widget always passes focus=False to the wrapped widget, even if it somehow does become the focus. """ no_cache: typing.ClassVar[list[str]] = ["rows"] ignore_focus = True def selectable(self) -> Literal[False]: return False def rows(self, size: tuple[int], focus: bool = False) -> int: return self._original_widget.rows(size, False) def sizing(self) -> frozenset[Sizing]: return self._original_widget.sizing() def pack(self, size, focus: bool = False) -> tuple[int, int]: return self._original_widget.pack(size, False) def render(self, size, focus: bool = False) -> CompositeCanvas: canv = self._original_widget.render(size, False) return CompositeCanvas(canv)
5,736
Python
.py
133
35.383459
107
0.65451
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,250
scrollable.py
urwid_urwid/urwid/widget/scrollable.py
# Copyright (C) 2024 Urwid developers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ # # Copyright (C) 2017-2024 rndusr (https://github.com/rndusr) # Re-licensed from gpl-3.0 with author permission. # Permission comment link: https://github.com/markqvist/NomadNet/pull/46#issuecomment-1892712616 from __future__ import annotations import contextlib import enum import typing from typing_extensions import Protocol, runtime_checkable from .constants import BOX_SYMBOLS, SHADE_SYMBOLS, Sizing from .widget_decoration import WidgetDecoration, WidgetError if typing.TYPE_CHECKING: from collections.abc import Iterator from typing_extensions import Literal from urwid import Canvas, CompositeCanvas from .widget import Widget __all__ = ("ScrollBar", "Scrollable", "ScrollableError", "ScrollbarSymbols") WrappedWidget = typing.TypeVar("WrappedWidget", bound="SupportsScroll") class ScrollableError(WidgetError): """Scrollable specific widget errors.""" # Scroll actions SCROLL_LINE_UP = "line up" SCROLL_LINE_DOWN = "line down" SCROLL_PAGE_UP = "page up" SCROLL_PAGE_DOWN = "page down" SCROLL_TO_TOP = "to top" SCROLL_TO_END = "to end" # Scrollbar positions SCROLLBAR_LEFT = "left" SCROLLBAR_RIGHT = "right" class ScrollbarSymbols(str, enum.Enum): """Common symbols suitable for scrollbar.""" FULL_BLOCK = SHADE_SYMBOLS.FULL_BLOCK DARK_SHADE = SHADE_SYMBOLS.DARK_SHADE MEDIUM_SHADE = SHADE_SYMBOLS.MEDIUM_SHADE LITE_SHADE = SHADE_SYMBOLS.LITE_SHADE DRAWING_LIGHT = BOX_SYMBOLS.LIGHT.VERTICAL DRAWING_LIGHT_2_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_2_DASH DRAWING_LIGHT_3_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_3_DASH DRAWING_LIGHT_4_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_4_DASH DRAWING_HEAVY = BOX_SYMBOLS.HEAVY.VERTICAL DRAWING_HEAVY_2_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_2_DASH DRAWING_HEAVY_3_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_3_DASH DRAWING_HEAVY_4_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_4_DASH DRAWING_DOUBLE = BOX_SYMBOLS.DOUBLE.VERTICAL @runtime_checkable class WidgetProto(Protocol): """Protocol for widget. Due to protocol cannot inherit non-protocol bases, define several obligatory Widget methods. """ # Base widget methods (from Widget) def sizing(self) -> frozenset[Sizing]: ... def selectable(self) -> bool: ... def pack(self, size: tuple[int, int], focus: bool = False) -> tuple[int, int]: ... @property def base_widget(self) -> Widget: raise NotImplementedError def keypress(self, size: tuple[int, int], key: str) -> str | None: ... def mouse_event( self, size: tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: ... def render(self, size: tuple[int, int], focus: bool = False) -> Canvas: ... @runtime_checkable class SupportsScroll(WidgetProto, Protocol): """Scroll specific methods.""" def get_scrollpos(self, size: tuple[int, int], focus: bool = False) -> int: ... def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: ... @runtime_checkable class SupportsRelativeScroll(WidgetProto, Protocol): """Relative scroll-specific methods.""" def require_relative_scroll(self, size: tuple[int, int], focus: bool = False) -> bool: ... def get_first_visible_pos(self, size: tuple[int, int], focus: bool = False) -> int: ... def get_visible_amount(self, size: tuple[int, int], focus: bool = False) -> int: ... def orig_iter(w: Widget) -> Iterator[Widget]: visited = {w} yield w while hasattr(w, "original_widget"): w = w.original_widget if w in visited: break visited.add(w) yield w class Scrollable(WidgetDecoration[WrappedWidget]): def sizing(self) -> frozenset[Sizing]: return frozenset((Sizing.BOX,)) def selectable(self) -> bool: return True def __init__(self, widget: WrappedWidget, force_forward_keypress: bool = False) -> None: """Box widget that makes a fixed or flow widget vertically scrollable .. note:: Focusable widgets are handled, including switching focus, but possibly not intuitively, depending on the arrangement of widgets. When switching focus to a widget that is ouside of the visible part of the original widget, the canvas scrolls up/down to the focused widget. It would be better to scroll until the next focusable widget is in sight first. But for that to work we must somehow obtain a list of focusable rows in the original canvas. """ if not widget.sizing() & frozenset((Sizing.FIXED, Sizing.FLOW)): raise ValueError(f"Not a fixed or flow widget: {widget!r}") self._trim_top = 0 self._scroll_action = None self._forward_keypress = None self._old_cursor_coords = None self._rows_max_cached = 0 self.force_forward_keypress = force_forward_keypress super().__init__(widget) def render( self, size: tuple[int, int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: from urwid import canvas maxcol, maxrow = size def automove_cursor() -> None: ch = 0 last_hidden = False first_visible = False for pwi, (w, _o) in enumerate(ow.contents): wcanv = w.render((maxcol,)) wh = wcanv.rows() if wh: ch += wh if not last_hidden and ch >= self._trim_top: last_hidden = True elif last_hidden: if not first_visible: first_visible = True if not w.selectable(): continue ow.focus_item = pwi st = None nf = ow.get_focus() if hasattr(nf, "key_timeout"): st = nf elif hasattr(nf, "original_widget"): no = nf.original_widget if hasattr(no, "original_widget"): st = no.original_widget elif hasattr(no, "key_timeout"): st = no if st and hasattr(st, "key_timeout") and callable(getattr(st, "keypress", None)): st.keypress(None, None) break # Render complete original widget ow = self._original_widget ow_size = self._get_original_widget_size(size) canv_full = ow.render(ow_size, focus) # Make full canvas editable canv = canvas.CompositeCanvas(canv_full) canv_cols, canv_rows = canv.cols(), canv.rows() if canv_cols <= maxcol: pad_width = maxcol - canv_cols if pad_width > 0: # Canvas is narrower than available horizontal space canv.pad_trim_left_right(0, pad_width) if canv_rows <= maxrow: fill_height = maxrow - canv_rows if fill_height > 0: # Canvas is lower than available vertical space canv.pad_trim_top_bottom(0, fill_height) if canv_cols <= maxcol and canv_rows <= maxrow: # Canvas is small enough to fit without trimming return canv self._adjust_trim_top(canv, size) # Trim canvas if necessary trim_top = self._trim_top trim_end = canv_rows - maxrow - trim_top trim_right = canv_cols - maxcol if trim_top > 0: canv.trim(trim_top) if trim_end > 0: canv.trim_end(trim_end) if trim_right > 0: canv.pad_trim_left_right(0, -trim_right) # Disable cursor display if cursor is outside of visible canvas parts if canv.cursor is not None: # Pylint check acts here a bit weird. _curscol, cursrow = canv.cursor # pylint: disable=unpacking-non-sequence,useless-suppression if cursrow >= maxrow or cursrow < 0: canv.cursor = None # Figure out whether we should forward keypresses to original widget if canv.cursor is not None: # Trimmed canvas contains the cursor, e.g. in an Edit widget self._forward_keypress = True elif canv_full.cursor is not None: # Full canvas contains the cursor, but scrolled out of view self._forward_keypress = False # Reset cursor position on page/up down scrolling if getattr(ow, "automove_cursor_on_scroll", False): with contextlib.suppress(Exception): automove_cursor() else: # Original widget does not have a cursor, but may be selectable # FIXME: Using ow.selectable() is bad because the original # widget may be selectable because it's a container widget with # a key-grabbing widget that is scrolled out of view. # ow.selectable() returns True anyway because it doesn't know # how we trimmed our canvas. # # To fix this, we need to resolve ow.focus and somehow # ask canv whether it contains bits of the focused widget. I # can't see a way to do that. self._forward_keypress = ow.selectable() return canv def keypress( self, size: tuple[int, int], # type: ignore[override] key: str, ) -> str | None: from urwid.command_map import Command # Maybe offer key to original widget if self._forward_keypress or self.force_forward_keypress: ow = self._original_widget ow_size = self._get_original_widget_size(size) # Remember the previous cursor position if possible if hasattr(ow, "get_cursor_coords"): self._old_cursor_coords = ow.get_cursor_coords(ow_size) key = ow.keypress(ow_size, key) if key is None: return None # Handle up/down, page up/down, etc. command_map = self._command_map if command_map[key] == Command.UP: self._scroll_action = SCROLL_LINE_UP elif command_map[key] == Command.DOWN: self._scroll_action = SCROLL_LINE_DOWN elif command_map[key] == Command.PAGE_UP: self._scroll_action = SCROLL_PAGE_UP elif command_map[key] == Command.PAGE_DOWN: self._scroll_action = SCROLL_PAGE_DOWN elif command_map[key] == Command.MAX_LEFT: # 'home' self._scroll_action = SCROLL_TO_TOP elif command_map[key] == Command.MAX_RIGHT: # 'end' self._scroll_action = SCROLL_TO_END else: return key self._invalidate() return None def mouse_event( self, size: tuple[int, int], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: ow = self._original_widget if hasattr(ow, "mouse_event"): ow_size = self._get_original_widget_size(size) row += self._trim_top return ow.mouse_event(ow_size, event, button, col, row, focus) return False def _adjust_trim_top(self, canv: Canvas, size: tuple[int, int]) -> None: """Adjust self._trim_top according to self._scroll_action""" action = self._scroll_action self._scroll_action = None _maxcol, maxrow = size trim_top = self._trim_top canv_rows = canv.rows() if trim_top < 0: # Negative trim_top values use bottom of canvas as reference trim_top = canv_rows - maxrow + trim_top + 1 if canv_rows <= maxrow: self._trim_top = 0 # Reset scroll position return def ensure_bounds(new_trim_top: int) -> int: return max(0, min(canv_rows - maxrow, new_trim_top)) if action == SCROLL_LINE_UP: self._trim_top = ensure_bounds(trim_top - 1) elif action == SCROLL_LINE_DOWN: self._trim_top = ensure_bounds(trim_top + 1) elif action == SCROLL_PAGE_UP: self._trim_top = ensure_bounds(trim_top - maxrow + 1) elif action == SCROLL_PAGE_DOWN: self._trim_top = ensure_bounds(trim_top + maxrow - 1) elif action == SCROLL_TO_TOP: self._trim_top = 0 elif action == SCROLL_TO_END: self._trim_top = canv_rows - maxrow else: self._trim_top = ensure_bounds(trim_top) # If the cursor was moved by the most recent keypress, adjust trim_top # so that the new cursor position is within the displayed canvas part. # But don't do this if the cursor is at the top/bottom edge so we can still scroll out if self._old_cursor_coords is not None and self._old_cursor_coords != canv.cursor and canv.cursor is not None: self._old_cursor_coords = None _curscol, cursrow = canv.cursor if cursrow < self._trim_top: self._trim_top = cursrow elif cursrow >= self._trim_top + maxrow: self._trim_top = max(0, cursrow - maxrow + 1) def _get_original_widget_size( self, size: tuple[int, int], # type: ignore[override] ) -> tuple[int] | tuple[()]: ow = self._original_widget sizing = ow.sizing() if Sizing.FLOW in sizing: return (size[0],) if Sizing.FIXED in sizing: return () raise ScrollableError(f"{ow!r} sizing is not supported") def get_scrollpos(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: """Current scrolling position. Lower limit is 0, upper limit is the maximum number of rows with the given maxcol minus maxrow. ..note:: The returned value may be too low or too high if the position has changed but the widget wasn't rendered yet. """ return self._trim_top def set_scrollpos(self, position: typing.SupportsInt) -> None: """Set scrolling position If `position` is positive it is interpreted as lines from the top. If `position` is negative it is interpreted as lines from the bottom. Values that are too high or too low values are automatically adjusted during rendering. """ self._trim_top = int(position) self._invalidate() def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: """Return the number of rows for `size` If `size` is not given, the currently rendered number of rows is returned. """ if size is not None: ow = self._original_widget ow_size = self._get_original_widget_size(size) sizing = ow.sizing() if Sizing.FIXED in sizing: self._rows_max_cached = ow.pack(ow_size, focus)[1] elif Sizing.FLOW in sizing: self._rows_max_cached = ow.rows(ow_size, focus) else: raise ScrollableError(f"Not a flow/box widget: {self._original_widget!r}") return self._rows_max_cached class ScrollBar(WidgetDecoration[WrappedWidget]): Symbols = ScrollbarSymbols def sizing(self) -> frozenset[Sizing]: return frozenset((Sizing.BOX,)) def selectable(self) -> bool: return True def __init__( self, widget: WrappedWidget, thumb_char: str = ScrollbarSymbols.FULL_BLOCK, trough_char: str = " ", side: Literal["left", "right"] = SCROLLBAR_RIGHT, width: int = 1, ) -> None: """Box widget that adds a scrollbar to `widget` `widget` must be a box widget with the following methods: - `get_scrollpos` takes the arguments `size` and `focus` and returns the index of the first visible row. - `set_scrollpos` (optional; needed for mouse click support) takes the index of the first visible row. - `rows_max` takes `size` and `focus` and returns the total number of rows `widget` can render. `thumb_char` is the character used for the scrollbar handle. `trough_char` is used for the space above and below the handle. `side` must be 'left' or 'right'. `width` specifies the number of columns the scrollbar uses. """ if Sizing.BOX not in widget.sizing(): raise ValueError(f"Not a box widget: {widget!r}") if not any(isinstance(w, SupportsScroll) for w in orig_iter(widget)): raise TypeError(f"Not a scrollable widget: {widget!r}") super().__init__(widget) self._thumb_char = thumb_char self._trough_char = trough_char self.scrollbar_side = side self.scrollbar_width = max(1, width) self._original_widget_size = (0, 0) def render( self, size: tuple[int, int], # type: ignore[override] focus: bool = False, ) -> Canvas: from urwid import canvas def render_no_scrollbar() -> Canvas: self._original_widget_size = size return ow.render(size, focus) def render_for_scrollbar() -> Canvas: self._original_widget_size = ow_size return ow.render(ow_size, focus) maxcol, maxrow = size ow_size = (max(0, maxcol - self._scrollbar_width), maxrow) sb_width = maxcol - ow_size[0] ow = self._original_widget ow_base = self.scrolling_base_widget # Use hasattr instead of protocol: hasattr will return False in case of getattr raise AttributeError # Use __length_hint__ first since it's less resource intensive use_relative = ( isinstance(ow_base, SupportsRelativeScroll) and any(hasattr(ow_base, attrib) for attrib in ("__length_hint__", "__len__")) and ow_base.require_relative_scroll(size, focus) ) if use_relative: # `operator.length_hint` is Protocol (Spec) over class based and can end false-negative on the instance # use length_hint-like approach with safe `AttributeError` handling ow_len = getattr(ow_base, "__len__", getattr(ow_base, "__length_hint__", int))() ow_canv = render_for_scrollbar() visible_amount = ow_base.get_visible_amount(ow_size, focus) pos = ow_base.get_first_visible_pos(ow_size, focus) # in the case of estimated length, it can be smaller than real widget length ow_len = max(ow_len, visible_amount, pos) posmax = ow_len - visible_amount thumb_weight = min(1.0, visible_amount / max(1, ow_len)) if ow_len == visible_amount: # Corner case: formally all contents indexes should be visible, but this does not mean all rows use_relative = False if not use_relative: ow_rows_max = ow_base.rows_max(size, focus) if ow_rows_max <= maxrow: # Canvas fits without scrolling - no scrollbar needed return render_no_scrollbar() ow_canv = render_for_scrollbar() ow_rows_max = ow_base.rows_max(ow_size, focus) pos = ow_base.get_scrollpos(ow_size, focus) posmax = ow_rows_max - maxrow thumb_weight = min(1.0, maxrow / max(1, ow_rows_max)) # Thumb shrinks/grows according to the ratio of <number of visible lines> / <number of total lines> thumb_height = max(1, round(thumb_weight * maxrow)) # pylint: disable=possibly-used-before-assignment # Thumb may only touch top/bottom if the first/last row is visible top_weight = float(pos) / max(1, posmax) # pylint: disable=possibly-used-before-assignment top_height = int((maxrow - thumb_height) * top_weight) if top_height == 0 and top_weight > 0: top_height = 1 # Bottom part is remaining space bottom_height = maxrow - thumb_height - top_height # Create scrollbar canvas # Creating SolidCanvases of correct height may result in # "cviews do not fill gaps in shard_tail!" or "cviews overflow gaps in shard_tail!" exceptions. # Stacking the same SolidCanvas is a workaround. # https://github.com/urwid/urwid/issues/226#issuecomment-437176837 top = canvas.SolidCanvas(self._trough_char, sb_width, 1) thumb = canvas.SolidCanvas(self._thumb_char, sb_width, 1) bottom = canvas.SolidCanvas(self._trough_char, sb_width, 1) sb_canv = canvas.CanvasCombine( ( *((top, None, False) for _ in range(top_height)), *((thumb, None, False) for _ in range(thumb_height)), *((bottom, None, False) for _ in range(bottom_height)), ), ) combinelist = [ (ow_canv, None, True, ow_size[0]), # pylint: disable=possibly-used-before-assignment (sb_canv, None, False, sb_width), ] if self._scrollbar_side != SCROLLBAR_LEFT: return canvas.CanvasJoin(combinelist) return canvas.CanvasJoin(reversed(combinelist)) @property def scrollbar_width(self) -> int: """Columns the scrollbar uses""" return max(1, self._scrollbar_width) @scrollbar_width.setter def scrollbar_width(self, width: typing.SupportsInt) -> None: self._scrollbar_width = max(1, int(width)) self._invalidate() @property def scrollbar_side(self) -> Literal["left", "right"]: """Where to display the scrollbar; must be 'left' or 'right'""" return self._scrollbar_side @scrollbar_side.setter def scrollbar_side(self, side: Literal["left", "right"]) -> None: if side not in {SCROLLBAR_LEFT, SCROLLBAR_RIGHT}: raise ValueError(f'scrollbar_side must be "left" or "right", not {side!r}') self._scrollbar_side = side self._invalidate() @property def scrolling_base_widget(self) -> SupportsScroll | SupportsRelativeScroll: """Nearest `original_widget` that is compatible with the scrolling API""" w = self for w in orig_iter(self): if isinstance(w, SupportsScroll): return w raise ScrollableError(f"Not compatible to be wrapped by ScrollBar: {w!r}") def keypress( self, size: tuple[int, int], # type: ignore[override] key: str, ) -> str | None: return self._original_widget.keypress(self._original_widget_size, key) def mouse_event( self, size: tuple[int, int], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: ow = self._original_widget ow_size = self._original_widget_size handled: bool | None = False if hasattr(ow, "mouse_event"): handled = ow.mouse_event(ow_size, event, button, col, row, focus) if not handled and hasattr(ow, "set_scrollpos"): if button == 4: # scroll wheel up pos = ow.get_scrollpos(ow_size) newpos = max(pos - 1, 0) ow.set_scrollpos(newpos) return True if button == 5: # scroll wheel down pos = ow.get_scrollpos(ow_size) ow.set_scrollpos(pos + 1) return True return handled
24,536
Python
.py
526
36.743346
118
0.611146
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,251
pile.py
urwid_urwid/urwid/widget/pile.py
from __future__ import annotations import typing import warnings from itertools import chain, repeat from urwid.canvas import CanvasCombine, CompositeCanvas, SolidCanvas from urwid.command_map import Command from urwid.split_repr import remove_defaults from urwid.util import is_mouse_press from .constants import Sizing, WHSettings from .container import WidgetContainerListContentsMixin, WidgetContainerMixin, _ContainerElementSizingFlag from .monitored_list import MonitoredFocusList, MonitoredList from .widget import Widget, WidgetError, WidgetWarning if typing.TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence from typing_extensions import Literal class PileError(WidgetError): """Pile related errors.""" class PileWarning(WidgetWarning): """Pile related warnings.""" class Pile(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin): """ A pile of widgets stacked vertically from top to bottom """ def sizing(self) -> frozenset[Sizing]: """Sizing supported by widget. :return: Calculated widget sizing :rtype: frozenset[Sizing] Due to the nature of container with mutable contents, this method cannot be cached. Rules: * WEIGHT BOX -> BOX * GIVEN BOX -> FLOW (height is known) & BOX (can be shrinked/padded) * PACK BOX -> Unsupported * WEIGHT FLOW -> FLOW * GIVEN FLOW -> Unsupported * PACK FLOW -> FLOW * WEIGHT FIXED -> Need also FLOW or/and BOX to properly render due to width calculation * GIVEN FIXED -> Unsupported * PACK FIXED -> FIXED (widget knows its size) >>> from urwid import BigText, ProgressBar, SolidFill, Text, Thin3x3Font >>> font = Thin3x3Font() # BOX-only widget >>> Pile((SolidFill("#"),)) <Pile box widget (1 item)> # GIVEN BOX -> BOX/FLOW >>> Pile(((10, SolidFill("#")),)) <Pile box/flow widget (1 item)> # FLOW-only >>> Pile((ProgressBar(None, None),)) <Pile flow widget (1 item)> # FIXED -> FIXED >>> Pile(((WHSettings.PACK, BigText("0", font)),)) <Pile fixed widget (1 item)> # FLOW/FIXED -> FLOW/FIXED >>> Pile(((WHSettings.PACK, Text("text")),)) <Pile fixed/flow widget (1 item)> # FLOW + FIXED widgets -> FLOW/FIXED >>> Pile((ProgressBar(None, None), (WHSettings.PACK, BigText("0", font)))) <Pile fixed/flow widget (2 items) focus_item=0> # GIVEN BOX + FIXED widgets -> BOX/FLOW/FIXED (GIVEN BOX allows overriding its height & allows any width) >>> Pile(((10, SolidFill("#")), (WHSettings.PACK, BigText("0", font)))) <Pile widget (2 items) focus_item=0> # Invalid sizing combination -> use fallback settings (and produce warning) >>> Pile(((WHSettings.WEIGHT, 1, BigText("0", font)),)) <Pile box/flow widget (1 item)> # Special case: empty pile widget sizing is impossible to calculate >>> Pile(()) <Pile box/flow widget ()> """ if not self.contents: return frozenset((Sizing.BOX, Sizing.FLOW)) strict_box = False has_flow = False has_fixed = False supported: set[Sizing] = set() box_flow_fixed = ( _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED ) flow_fixed = _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED for idx, (widget, (size_kind, _size_weight)) in enumerate(self.contents): w_sizing = widget.sizing() flag = _ContainerElementSizingFlag.NONE if size_kind == WHSettings.WEIGHT: flag |= _ContainerElementSizingFlag.WH_WEIGHT if Sizing.BOX in w_sizing: flag |= _ContainerElementSizingFlag.BOX if Sizing.FLOW in w_sizing: flag |= _ContainerElementSizingFlag.FLOW if Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}: flag |= _ContainerElementSizingFlag.FIXED elif size_kind == WHSettings.GIVEN: flag |= _ContainerElementSizingFlag.WH_GIVEN if Sizing.BOX in w_sizing: flag |= _ContainerElementSizingFlag.BOX flag |= _ContainerElementSizingFlag.FLOW else: flag = _ContainerElementSizingFlag.WH_PACK if Sizing.FLOW in w_sizing: flag |= _ContainerElementSizingFlag.FLOW if Sizing.FIXED in w_sizing: flag |= _ContainerElementSizingFlag.FIXED if not flag & box_flow_fixed: warnings.warn( f"Sizing combination of widget {idx} not supported: " f"{size_kind.name} {'|'.join(w_sizing).upper()}", PileWarning, stacklevel=3, ) return frozenset((Sizing.BOX, Sizing.FLOW)) if flag & _ContainerElementSizingFlag.BOX: supported.add(Sizing.BOX) if not flag & flow_fixed: strict_box = True break if flag & _ContainerElementSizingFlag.FLOW: has_flow = True if flag & _ContainerElementSizingFlag.FIXED: has_fixed = True if not strict_box: if has_flow: supported.add(Sizing.FLOW) if has_fixed: supported.add(Sizing.FIXED) return frozenset(supported) def __init__( self, widget_list: Iterable[ Widget | tuple[Literal["pack", WHSettings.PACK] | int, Widget] | tuple[Literal["given", WHSettings.GIVEN], int, Widget] | tuple[Literal["weight", WHSettings.WEIGHT], int | float, Widget] ], focus_item: Widget | int | None = None, ) -> None: """ :param widget_list: child widgets :type widget_list: iterable :param focus_item: child widget that gets the focus initially. Chooses the first selectable widget if unset. :type focus_item: Widget or int *widget_list* may also contain tuples such as: (*given_height*, *widget*) always treat *widget* as a box widget and give it *given_height* rows, where given_height is an int (``'pack'``, *widget*) allow *widget* to calculate its own height by calling its :meth:`rows` method, i.e. treat it as a flow widget. (``'weight'``, *weight*, *widget*) if the pile is treated as a box widget then treat widget as a box widget with a height based on its relative weight value, otherwise treat the same as (``'pack'``, *widget*). Widgets not in a tuple are the same as (``'weight'``, ``1``, *widget*)` .. note:: If the Pile is treated as a box widget there must be at least one ``'weight'`` tuple in :attr:`widget_list`. """ self._selectable = False super().__init__() self._contents: MonitoredFocusList[ Widget, tuple[Literal[WHSettings.PACK], None] | tuple[Literal[WHSettings.GIVEN], int] | tuple[Literal[WHSettings.WEIGHT], int | float], ] = MonitoredFocusList() self._contents.set_modified_callback(self._contents_modified) self._contents.set_focus_changed_callback(lambda f: self._invalidate()) self._contents.set_validate_contents_modified(self._validate_contents_modified) for i, original in enumerate(widget_list): w = original if not isinstance(w, tuple): self.contents.append((w, (WHSettings.WEIGHT, 1))) elif w[0] in {Sizing.FLOW, WHSettings.PACK}: # 'pack' used to be called 'flow' f, w = w self.contents.append((w, (WHSettings.PACK, None))) elif len(w) == 2 or w[0] in {Sizing.FIXED, WHSettings.GIVEN}: # backwards compatibility height, w = w[-2:] self.contents.append((w, (WHSettings.GIVEN, height))) elif w[0] == WHSettings.WEIGHT: f, height, w = w self.contents.append((w, (f, height))) else: raise PileError(f"initial widget list item invalid {original!r}") if focus_item is None and w.selectable(): focus_item = i if not isinstance(w, Widget): warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3) if self.contents and focus_item is not None: self.focus = focus_item self.pref_col = 0 def _repr_words(self) -> list[str]: if len(self.contents) > 1: contents_string = f"({len(self.contents)} items)" elif self.contents: contents_string = "(1 item)" else: contents_string = "()" return [*super()._repr_words(), contents_string] def _repr_attrs(self) -> dict[str, typing.Any]: attrs = {**super()._repr_attrs(), "focus_item": self.focus_position if len(self._contents) > 1 else None} return remove_defaults(attrs, Pile.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: widget_list: list[ Widget | tuple[Literal[WHSettings.PACK] | int, Widget] | tuple[Literal[WHSettings.WEIGHT], int | float, Widget] ] = [] for w_instance, (sizing, amount) in self._contents: if sizing == WHSettings.GIVEN: widget_list.append((amount, w_instance)) elif sizing == WHSettings.PACK: widget_list.append((WHSettings.PACK, w_instance)) elif sizing == WHSettings.WEIGHT: if amount == 1: widget_list.append(w_instance) else: widget_list.append((WHSettings.WEIGHT, amount, w_instance)) yield "widget_list", widget_list yield "focus_item", self.focus_position if self._contents else None def __len__(self) -> int: return len(self._contents) def _contents_modified(self) -> None: """Recalculate whether this widget should be selectable whenever the contents has been changed.""" self._selectable = any(w.selectable() for w, o in self.contents) self._invalidate() def _validate_contents_modified(self, slc, new_items) -> None: invalid_items: list[tuple[Widget, tuple[typing.Any, typing.Any]]] = [] try: for item in new_items: _w, (t, n) = item if any( ( t not in {WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT}, (n is not None and (not isinstance(n, (int, float)) or n < 0)), ) ): invalid_items.append(item) except (TypeError, ValueError) as exc: raise PileError(f"added content invalid: {exc}").with_traceback(exc.__traceback__) from exc if invalid_items: raise PileError(f"added content invalid: {invalid_items!r}") @property def widget_list(self): """ A list of the widgets in this Pile .. note:: only for backwards compatibility. You should use the new standard container property :attr:`contents`. """ warnings.warn( "only for backwards compatibility. You should use the new standard container property `contents`", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList(w for w, t in self.contents) def user_modified(): self.widget_list = ml ml.set_modified_callback(user_modified) return ml @widget_list.setter def widget_list(self, widgets): focus_position = self.focus_position self.contents = [ (new, options) for (new, (w, options)) in zip( widgets, # need to grow contents list if widgets is longer chain(self.contents, repeat((None, (WHSettings.WEIGHT, 1)))), ) ] if focus_position < len(widgets): self.focus_position = focus_position @property def item_types(self): """ A list of the options values for widgets in this Pile. .. note:: only for backwards compatibility. You should use the new standard container property :attr:`contents`. """ warnings.warn( "only for backwards compatibility. You should use the new standard container property `contents`", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList( # return the old item type names ({WHSettings.GIVEN: Sizing.FIXED, WHSettings.PACK: Sizing.FLOW}.get(f, f), height) for w, (f, height) in self.contents ) def user_modified(): self.item_types = ml ml.set_modified_callback(user_modified) return ml @item_types.setter def item_types(self, item_types): warnings.warn( "only for backwards compatibility. You should use the new standard container property `contents`", PendingDeprecationWarning, stacklevel=2, ) focus_position = self.focus_position self.contents = [ (w, ({Sizing.FIXED: WHSettings.GIVEN, Sizing.FLOW: WHSettings.PACK}.get(new_t, new_t), new_height)) for ((new_t, new_height), (w, options)) in zip(item_types, self.contents) ] if focus_position < len(item_types): self.focus_position = focus_position @property def contents( self, ) -> MonitoredFocusList[ Widget, tuple[Literal[WHSettings.PACK], None] | tuple[Literal[WHSettings.GIVEN], int] | tuple[Literal[WHSettings.WEIGHT], int | float], ]: """ The contents of this Pile as a list of (widget, options) tuples. options currently may be one of (``'pack'``, ``None``) allow widget to calculate its own height by calling its :meth:`rows <Widget.rows>` method, i.e. treat it as a flow widget. (``'given'``, *n*) Always treat widget as a box widget with a given height of *n* rows. (``'weight'``, *w*) If the Pile itself is treated as a box widget then the value *w* will be used as a relative weight for assigning rows to this box widget. If the Pile is being treated as a flow widget then this is the same as (``'pack'``, ``None``) and the *w* value is ignored. If the Pile itself is treated as a box widget then at least one widget must have a (``'weight'``, *w*) options value, or the Pile will not be able to grow to fill the required number of rows. This list may be modified like a normal list and the Pile widget will updated automatically. .. seealso:: Create new options tuples with the :meth:`options` method """ return self._contents @contents.setter def contents( self, c: Sequence[ Widget, tuple[Literal[WHSettings.PACK], None] | tuple[Literal[WHSettings.GIVEN], int] | tuple[Literal[WHSettings.WEIGHT], int | float], ], ) -> None: self._contents[:] = c @staticmethod def options( height_type: Literal["pack", "given", "weight"] | WHSettings = WHSettings.WEIGHT, height_amount: int | float | None = 1, # noqa: PYI041 # provide explicit for IDEs ) -> ( tuple[Literal[WHSettings.PACK], None] | tuple[Literal[WHSettings.GIVEN], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): """ Return a new options tuple for use in a Pile's :attr:`contents` list. :param height_type: ``'pack'``, ``'given'`` or ``'weight'`` :param height_amount: ``None`` for ``'pack'``, a number of rows for ``'fixed'`` or a weight value (number) for ``'weight'`` """ if height_type == WHSettings.PACK: return (WHSettings.PACK, None) if height_type in {WHSettings.GIVEN, WHSettings.WEIGHT} and height_amount is not None: return (height_type, height_amount) raise PileError(f"invalid combination: height_type={height_type!r}, height_amount={height_amount!r}") @property def focus(self) -> Widget | None: """the child widget in focus or None when Pile is empty""" if not self.contents: return None return self.contents[self.focus_position][0] @focus.setter def focus(self, item: Widget | int) -> None: """ Set the item in focus, for backwards compatibility. .. note:: only for backwards compatibility. You should use the new standard container property :attr:`focus_position`. to set the position by integer index instead. :param item: element to focus :type item: Widget or int """ if isinstance(item, int): self.focus_position = item return for i, (w, _options) in enumerate(self.contents): if item == w: self.focus_position = i return raise ValueError(f"Widget not found in Pile contents: {item!r}") def _get_focus(self) -> Widget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) if not self.contents: return None return self.contents[self.focus_position][0] def get_focus(self) -> Widget | None: """ Return the widget in focus, for backwards compatibility. You may also use the new standard container property .focus to get the child widget in focus. """ warnings.warn( "for backwards compatibility." "You may also use the new standard container property .focus to get the child widget in focus.", PendingDeprecationWarning, stacklevel=2, ) if not self.contents: return None return self.contents[self.focus_position][0] def set_focus(self, item: Widget | int) -> None: warnings.warn( "for backwards compatibility." "You may also use the new standard container property .focus to get the child widget in focus.", PendingDeprecationWarning, stacklevel=2, ) if isinstance(item, int): self.focus_position = item return for i, (w, _options) in enumerate(self.contents): if item == w: self.focus_position = i return raise ValueError(f"Widget not found in Pile contents: {item!r}") @property def focus_item(self): warnings.warn( "only for backwards compatibility." "You should use the new standard container properties " "`focus` and `focus_position` to get the child widget in focus or modify the focus position.", DeprecationWarning, stacklevel=2, ) return self.focus @focus_item.setter def focus_item(self, new_item): warnings.warn( "only for backwards compatibility." "You should use the new standard container properties " "`focus` and `focus_position` to get the child widget in focus or modify the focus position.", DeprecationWarning, stacklevel=2, ) self.focus = new_item @property def focus_position(self) -> int: """ index of child widget in focus. Raises :exc:`IndexError` if read when Pile is empty, or when set to an invalid index. """ if not self.contents: raise IndexError("No focus_position, Pile is empty") return self.contents.focus @focus_position.setter def focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ try: if position < 0 or position >= len(self.contents): raise IndexError(f"No Pile child widget at position {position}") except TypeError as exc: raise IndexError(f"No Pile child widget at position {position}").with_traceback(exc.__traceback__) from exc self.contents.focus = position def _get_focus_position(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) if not self.contents: raise IndexError("No focus_position, Pile is empty") return self.contents.focus def _set_focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ warnings.warn( f"method `{self.__class__.__name__}._set_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) try: if position < 0 or position >= len(self.contents): raise IndexError(f"No Pile child widget at position {position}") except TypeError as exc: raise IndexError(f"No Pile child widget at position {position}").with_traceback(exc.__traceback__) from exc self.contents.focus = position def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int | None: """Return the preferred column for the cursor, or None.""" if not self.selectable(): return None if not self.contents: return None _, _, size_args = self.get_rows_sizes(size, focus=self.selectable()) self._update_pref_col_from_focus(size_args[self.focus_position]) return self.pref_col def get_item_size( self, size: tuple[()] | tuple[int] | tuple[int, int], i: int, focus: bool, item_rows: list[int] | None = None, ) -> tuple[()] | tuple[int] | tuple[int, int]: """ Return a size appropriate for passing to self.contents[i][0].render """ _w, (f, height) = self.contents[i] if f == WHSettings.PACK: if not size: return () return (size[0],) if not size: raise PileError(f"Element {i} using parameters {f} and do not have full size information") maxcol = size[0] if f == WHSettings.GIVEN: return (maxcol, height) if f == WHSettings.WEIGHT: if len(size) == 2: if not item_rows: item_rows = self.get_item_rows(size, focus) return (maxcol, item_rows[i]) return (maxcol,) raise PileError(f"Unsupported item height rules: {f}") def _get_fixed_rows_sizes( self, focus: bool = False, ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int] | tuple[()]]]: if not self.contents: return (), (), () widths: dict[int, int] = {} heights: dict[int, int] = {} w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {} flow: list[tuple[Widget, int, bool]] = [] box: list[int] = [] weighted: dict[int, list[int]] = {} weights: list[int] = [] weight_max_sizes: dict[int, int] = {} for idx, (widget, (size_kind, size_weight)) in enumerate(self.contents): w_sizing = widget.sizing() focused = focus and self.focus == widget if size_kind == WHSettings.PACK: if Sizing.FIXED in w_sizing: widths[idx], heights[idx] = widget.pack((), focused) w_h_args[idx] = () if Sizing.FLOW in w_sizing: # re-calculate height at the end flow.append((widget, idx, focused)) if not w_sizing & {Sizing.FIXED, Sizing.FLOW}: raise PileError(f"Unsupported sizing {w_sizing} for {size_kind.upper()}") elif size_kind == WHSettings.GIVEN: heights[idx] = size_weight if Sizing.BOX in w_sizing: box.append(idx) else: raise PileError(f"Unsupported sizing {w_sizing} for {size_kind.upper()}") elif size_weight <= 0: widths[idx] = 0 heights[idx] = 0 if Sizing.FLOW in w_sizing: w_h_args[idx] = (0,) else: w_sizing[idx] = (0, 0) elif Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}: width, height = widget.pack((), focused) widths[idx] = width # We're fitting everything in case of FIXED if Sizing.BOX in w_sizing: weighted.setdefault(size_weight, []).append(idx) weights.append(size_weight) weight_max_sizes.setdefault(size_weight, height) weight_max_sizes[size_weight] = max(weight_max_sizes[size_weight], height) else: # width replace is allowed flow.append((widget, idx, focused)) elif Sizing.FLOW in w_sizing: # FLOW WEIGHT widgets are rendered the same as PACK WEIGHT flow.append((widget, idx, focused)) else: raise PileError(f"Unsupported combination of {size_kind}, {w_sizing}") if not widths: raise PileError("No widgets providing width information") max_width = max(widths.values()) for widget, idx, focused in flow: widths[idx] = max_width heights[idx] = widget.rows((max_width,), focused) w_h_args[idx] = (max_width,) if weight_max_sizes: max_weighted_coefficient = max(height / weight for weight, height in weight_max_sizes.items()) for weight in weight_max_sizes: height = max(int(max_weighted_coefficient * weight + 0.5), 1) for idx in weighted[weight]: heights[idx] = height w_h_args[idx] = (max_width, height) for idx in box: widths[idx] = max_width w_h_args[idx] = (max_width, heights[idx]) return ( tuple(widths[idx] for idx in range(len(widths))), tuple(heights[idx] for idx in range(len(heights))), tuple(w_h_args[idx] for idx in range(len(w_h_args))), ) def get_rows_sizes( self, size: tuple[int, int] | tuple[int] | tuple[()], focus: bool = False, ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int, int] | tuple[int] | tuple[()]]]: """Get rows widths, heights and render size parameters""" if not size: return self._get_fixed_rows_sizes(focus=focus) maxcol = size[0] item_rows = None widths: list[int] = [] heights: list[int] = [] w_h_args: list[tuple[int, int] | tuple[int] | tuple[()]] = [] for i, (w, (f, height)) in enumerate(self.contents): if isinstance(w, Widget): w_sizing = w.sizing() else: warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3) w_sizing = frozenset((Sizing.FLOW, Sizing.BOX)) item_focus = focus and self.focus == w widths.append(maxcol) if f == WHSettings.GIVEN: heights.append(height) w_h_args.append((maxcol, height)) elif f == WHSettings.PACK or len(size) == 1: if Sizing.FLOW in w_sizing: w_h_arg: tuple[int] | tuple[()] = (maxcol,) elif Sizing.FIXED in w_sizing and f == WHSettings.PACK: w_h_arg = () else: warnings.warn( f"Unusual widget {i} sizing {w_sizing} for {f.upper()}). " f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for height calculation", PileWarning, stacklevel=3, ) w_h_arg = (maxcol,) heights.append(w.pack(w_h_arg, item_focus)[1]) w_h_args.append(w_h_arg) else: if item_rows is None: item_rows = self.get_item_rows(size, focus) rows = item_rows[i] heights.append(rows) w_h_args.append((maxcol, rows)) return (tuple(widths), tuple(heights), tuple(w_h_args)) def pack(self, size: tuple[()] | tuple[int] | tuple[int, int] = (), focus: bool = False) -> tuple[int, int]: """Get packed sized for widget.""" if size: return super().pack(size, focus) widths, heights, _ = self.get_rows_sizes(size, focus) return (max(widths), sum(heights)) def get_item_rows(self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool) -> list[int]: """ Return a list of the number of rows used by each widget in self.contents """ remaining = None maxcol = size[0] if len(size) == 2: remaining = size[1] rows_numbers = [] if remaining is None: # pile is a flow widget for i, (w, (f, height)) in enumerate(self.contents): if isinstance(w, Widget): w_sizing = w.sizing() else: warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3) w_sizing = frozenset((Sizing.FLOW, Sizing.BOX)) focused = focus and self.focus == w if f == WHSettings.GIVEN: rows_numbers.append(height) elif Sizing.FLOW in w_sizing: rows_numbers.append(w.rows((maxcol,), focus=focused)) elif Sizing.FIXED in w_sizing and f == WHSettings.PACK: rows_numbers.append(w.pack((), focused)[0]) else: warnings.warn( f"Unusual widget {i} sizing {w_sizing} for {f.upper()}). " f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for height calculation", PileWarning, stacklevel=3, ) rows_numbers.append(w.rows((maxcol,), focus=focused)) return rows_numbers # pile is a box widget # do an extra pass to calculate rows for each widget wtotal = 0 for w, (f, height) in self.contents: if f == WHSettings.PACK: rows = w.rows((maxcol,), focus=focus and self.focus == w) rows_numbers.append(rows) remaining -= rows elif f == WHSettings.GIVEN: rows_numbers.append(height) remaining -= height elif height: rows_numbers.append(None) wtotal += height else: rows_numbers.append(0) # zero-weighted items treated as ('given', 0) if wtotal == 0: raise PileError("No weighted widgets found for Pile treated as a box widget") remaining = max(remaining, 0) for i, (_w, (_f, height)) in enumerate(self.contents): li = rows_numbers[i] if li is None: rows = int(float(remaining) * height / wtotal + 0.5) rows_numbers[i] = rows remaining -= rows wtotal -= height return rows_numbers def render( self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False, ) -> SolidCanvas | CompositeCanvas: _widths, heights, size_args = self.get_rows_sizes(size, focus) combinelist = [] for i, (height, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)): item_focus = self.focus == w canv = None if height > 0: canv = w.render(w_size, focus=focus and item_focus) if canv: combinelist.append((canv, i, item_focus)) if not combinelist: return SolidCanvas(" ", size[0], (size[1:] + (0,))[0]) out = CanvasCombine(combinelist) if len(size) == 2 and size[1] != out.rows(): # flow/fixed widgets rendered too large/small out = CompositeCanvas(out) out.pad_trim_top_bottom(0, size[1] - out.rows()) return out def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None: """Return the cursor coordinates of the focus widget.""" if not self.selectable(): return None if not hasattr(self.focus, "get_cursor_coords"): return None i = self.focus_position _widths, heights, size_args = self.get_rows_sizes(size, focus=True) coords = self.focus.get_cursor_coords(size_args[i]) if coords is None: return None x, y = coords if i > 0: for r in heights[:i]: y += r return x, y def rows(self, size: tuple[int] | tuple[int, int], focus: bool = False) -> int: return sum(self.get_item_rows(size, focus)) def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None: """Pass the keypress to the widget in focus. Unhandled 'up' and 'down' keys may cause a focus change. """ if not self.contents: return key i = self.focus_position _widths, heights, size_args = self.get_rows_sizes(size, focus=self.selectable()) if self.selectable(): key = self.focus.keypress(size_args[i], key) if self._command_map[key] not in {Command.UP, Command.DOWN}: return key if self._command_map[key] == Command.UP: candidates = tuple(range(i - 1, -1, -1)) # count backwards to 0 else: # self._command_map[key] == 'cursor down' candidates = tuple(range(i + 1, len(self.contents))) for j in candidates: if not self.contents[j][0].selectable(): continue self._update_pref_col_from_focus(size_args[self.focus_position]) self.focus_position = j if not hasattr(self.focus, "move_cursor_to_coords"): return None rows = heights[j] if self._command_map[key] == Command.UP: rowlist = tuple(range(rows - 1, -1, -1)) else: # self._command_map[key] == 'cursor down' rowlist = tuple(range(rows)) for row in rowlist: if self.focus.move_cursor_to_coords(size_args[self.focus_position], self.pref_col, row): break return None # nothing to select return key def _update_pref_col_from_focus(self, w_size: tuple[()] | tuple[int] | tuple[int, int]) -> None: """Update self.pref_col from the focus widget.""" if not hasattr(self.focus, "get_pref_col"): return pref_col = self.focus.get_pref_col(w_size) if pref_col is not None: self.pref_col = pref_col def move_cursor_to_coords( self, size: tuple[()] | tuple[int] | tuple[int, int], col: int, row: int, ) -> bool: """Capture pref col and set new focus.""" self.pref_col = col # FIXME guessing focus==True focus = True wrow = 0 _widths, heights, size_args = self.get_rows_sizes(size, focus=focus) for i, (r, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)): # noqa: B007 if wrow + r > row: break wrow += r else: return False if not w.selectable(): return False if hasattr(w, "move_cursor_to_coords"): rval = w.move_cursor_to_coords(w_size, col, row - wrow) if rval is False: return False self.focus_position = i return True def mouse_event( self, size: tuple[()] | tuple[int] | tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """Pass the event to the contained widget. May change focus on button 1 press. """ wrow = 0 _widths, heights, size_args = self.get_rows_sizes(size, focus=focus) for i, (height, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)): # noqa: B007 if wrow + height > row: target_row = row - wrow break wrow += height else: return False if is_mouse_press(event) and button == 1 and w.selectable(): self.focus_position = i if not hasattr(w, "mouse_event"): warnings.warn( f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget", DeprecationWarning, stacklevel=2, ) return False return w.mouse_event(w_size, event, button, col, target_row, focus and self.focus == w)
38,508
Python
.py
858
33.137529
120
0.563394
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,252
bar_graph.py
urwid_urwid/urwid/widget/bar_graph.py
from __future__ import annotations import typing from urwid.canvas import CanvasCombine, CompositeCanvas, SolidCanvas from urwid.util import get_encoding_mode from .constants import BAR_SYMBOLS, Sizing from .text import Text from .widget import Widget, WidgetError, WidgetMeta, nocache_widget_render, nocache_widget_render_instance if typing.TYPE_CHECKING: from typing_extensions import Literal class BarGraphMeta(WidgetMeta): """ Detect subclass get_data() method and dynamic change to get_data() method and disable caching in these cases. This is for backwards compatibility only, new programs should use set_data() instead of overriding get_data(). """ def __init__(cls, name, bases, d): # pylint: disable=protected-access super().__init__(name, bases, d) if "get_data" in d: cls.render = nocache_widget_render(cls) cls._get_data = cls.get_data cls.get_data = property(lambda self: self._get_data, nocache_bargraph_get_data) def nocache_bargraph_get_data(self, get_data_fn): """ Disable caching on this bargraph because get_data_fn needs to be polled to get the latest data. """ self.render = nocache_widget_render_instance(self) self._get_data = get_data_fn # pylint: disable=protected-access class BarGraphError(WidgetError): pass class BarGraph(Widget, metaclass=BarGraphMeta): _sizing = frozenset([Sizing.BOX]) ignore_focus = True eighths = BAR_SYMBOLS.VERTICAL[:8] # Full height is done by style hlines = "_⎺⎻─⎼⎽" def __init__(self, attlist, hatt=None, satt=None) -> None: """ Create a bar graph with the passed display characteristics. see set_segment_attributes for a description of the parameters. """ super().__init__() self.set_segment_attributes(attlist, hatt, satt) self.set_data([], 1, None) self.set_bar_width(None) def set_segment_attributes(self, attlist, hatt=None, satt=None): """ :param attlist: list containing display attribute or (display attribute, character) tuple for background, first segment, and optionally following segments. ie. len(attlist) == num segments+1 character defaults to ' ' if not specified. :param hatt: list containing attributes for horizontal lines. First element is for lines on background, second is for lines on first segment, third is for lines on second segment etc. :param satt: dictionary containing attributes for smoothed transitions of bars in UTF-8 display mode. The values are in the form: (fg,bg) : attr fg and bg are integers where 0 is the graph background, 1 is the first segment, 2 is the second, ... fg > bg in all values. attr is an attribute with a foreground corresponding to fg and a background corresponding to bg. If satt is not None and the bar graph is being displayed in a terminal using the UTF-8 encoding then the character cell that is shared between the segments specified will be smoothed with using the UTF-8 vertical eighth characters. eg: set_segment_attributes( ['no', ('unsure',"?"), 'yes'] ) will use the attribute 'no' for the background (the area from the top of the graph to the top of the bar), question marks with the attribute 'unsure' will be used for the topmost segment of the bar, and the attribute 'yes' will be used for the bottom segment of the bar. """ self.attr = [] self.char = [] if len(attlist) < 2: raise BarGraphError(f"attlist must include at least background and seg1: {attlist!r}") if len(attlist) < 2: raise BarGraphError("must at least specify bg and fg!") for a in attlist: if not isinstance(a, tuple): self.attr.append(a) self.char.append(" ") else: attr, ch = a self.attr.append(attr) self.char.append(ch) self.hatt = [] if hatt is None: hatt = [self.attr[0]] elif not isinstance(hatt, list): hatt = [hatt] self.hatt = hatt if satt is None: satt = {} for i in satt.items(): try: (fg, bg), attr = i except ValueError as exc: raise BarGraphError(f"satt not in (fg,bg:attr) form: {i!r}").with_traceback(exc.__traceback__) from exc if not isinstance(fg, int) or fg >= len(attlist): raise BarGraphError(f"fg not valid integer: {fg!r}") if not isinstance(bg, int) or bg >= len(attlist): raise BarGraphError(f"bg not valid integer: {fg!r}") if fg <= bg: raise BarGraphError(f"fg ({fg}) not > bg ({bg})") self.satt = satt def set_data(self, bardata, top: float, hlines=None) -> None: """ Store bar data, bargraph top and horizontal line positions. bardata -- a list of bar values. top -- maximum value for segments within bardata hlines -- None or a bar value marking horizontal line positions bar values are [ segment1, segment2, ... ] lists where top is the maximal value corresponding to the top of the bar graph and segment1, segment2, ... are the values for the top of each segment of this bar. Simple bar graphs will only have one segment in each bar value. Eg: if top is 100 and there is a bar value of [ 80, 30 ] then the top of this bar will be at 80% of full height of the graph and it will have a second segment that starts at 30%. """ if hlines is not None: hlines = sorted(hlines[:], reverse=True) # shallow copy self.data = bardata, top, hlines self._invalidate() def _get_data(self, size: tuple[int, int]): """ Return (bardata, top, hlines) This function is called by render to retrieve the data for the graph. It may be overloaded to create a dynamic bar graph. This implementation will truncate the bardata list returned if not all bars will fit within maxcol. """ (maxcol, maxrow) = size bardata, top, hlines = self.data widths = self.calculate_bar_widths((maxcol, maxrow), bardata) if len(bardata) > len(widths): return bardata[: len(widths)], top, hlines return bardata, top, hlines def set_bar_width(self, width: int | None): """ Set a preferred bar width for calculate_bar_widths to use. width -- width of bar or None for automatic width adjustment """ if width is not None and width <= 0: raise ValueError(width) self.bar_width = width self._invalidate() def calculate_bar_widths(self, size: tuple[int, int], bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, _maxrow) = size if self.bar_width is not None: return [self.bar_width] * min(len(bardata), maxcol // self.bar_width) if len(bardata) >= maxcol: return [1] * maxcol widths = [] grow = maxcol remain = len(bardata) for _row in bardata: w = int(float(grow) / remain + 0.5) widths.append(w) grow -= w remain -= 1 return widths def selectable(self) -> Literal[False]: """ Return False. """ return False def use_smoothed(self) -> bool: return self.satt and get_encoding_mode() == "utf8" def calculate_display(self, size: tuple[int, int]): """ Calculate display data. """ (maxcol, maxrow) = size bardata, top, hlines = self.get_data((maxcol, maxrow)) # pylint: disable=no-member # metaclass defined widths = self.calculate_bar_widths((maxcol, maxrow), bardata) if self.use_smoothed(): disp = calculate_bargraph_display(bardata, top, widths, maxrow * 8) disp = self.smooth_display(disp) else: disp = calculate_bargraph_display(bardata, top, widths, maxrow) if hlines: disp = self.hlines_display(disp, top, hlines, maxrow) return disp def hlines_display(self, disp, top: int, hlines, maxrow: int): """ Add hlines to display structure represented as bar_type tuple values: (bg, 0-5) bg is the segment that has the hline on it 0-5 is the hline graphic to use where 0 is a regular underscore and 1-5 are the UTF-8 horizontal scan line characters. """ if self.use_smoothed(): shiftr = 0 r = [ (0.2, 1), (0.4, 2), (0.6, 3), (0.8, 4), (1.0, 5), ] else: shiftr = 0.5 r = [ (1.0, 0), ] # reverse the hlines to match screen ordering rhl = [] for h in hlines: rh = float(top - h) * maxrow / top - shiftr if rh < 0: continue rhl.append(rh) # build a list of rows that will have hlines hrows = [] last_i = -1 for rh in rhl: i = int(rh) if i == last_i: continue f = rh - i for spl, chnum in r: if f < spl: hrows.append((i, chnum)) break last_i = i # fill hlines into disp data def fill_row(row, chnum): rout = [] for bar_type, width in row: if isinstance(bar_type, int) and len(self.hatt) > bar_type: rout.append(((bar_type, chnum), width)) continue rout.append((bar_type, width)) return rout o = [] k = 0 rnum = 0 for y_count, row in disp: if k >= len(hrows): o.append((y_count, row)) continue end_block = rnum + y_count while k < len(hrows) and hrows[k][0] < end_block: i, chnum = hrows[k] if i - rnum > 0: o.append((i - rnum, row)) o.append((1, fill_row(row, chnum))) rnum = i + 1 k += 1 if rnum < end_block: o.append((end_block - rnum, row)) rnum = end_block # assert 0, o return o def smooth_display(self, disp): """ smooth (col, row*8) display into (col, row) display using UTF vertical eighth characters represented as bar_type tuple values: ( fg, bg, 1-7 ) where fg is the lower segment, bg is the upper segment and 1-7 is the vertical eighth character to use. """ o = [] r = 0 # row remainder def seg_combine(a, b): (bt1, w1), (bt2, w2) = a, b if (bt1, w1) == (bt2, w2): return (bt1, w1), None, None wmin = min(w1, w2) l1 = l2 = None if w1 > w2: l1 = (bt1, w1 - w2) elif w2 > w1: l2 = (bt2, w2 - w1) if isinstance(bt1, tuple): return (bt1, wmin), l1, l2 if (bt2, bt1) not in self.satt: if r < 4: return (bt2, wmin), l1, l2 return (bt1, wmin), l1, l2 return ((bt2, bt1, 8 - r), wmin), l1, l2 def row_combine_last(count: int, row): o_count, o_row = o[-1] row = row[:] # shallow copy, so we don't destroy orig. o_row = o_row[:] widget_list = [] while row: (bt, w), l1, l2 = seg_combine(o_row.pop(0), row.pop(0)) if widget_list and widget_list[-1][0] == bt: widget_list[-1] = (bt, widget_list[-1][1] + w) else: widget_list.append((bt, w)) if l1: o_row = [l1, *o_row] if l2: row = [l2, *row] if o_row: raise BarGraphError(o_row) o[-1] = (o_count + count, widget_list) # regroup into actual rows (8 disp rows == 1 actual row) for y_count, row in disp: if r: count = min(8 - r, y_count) row_combine_last(count, row) y_count -= count # noqa: PLW2901 r += count r %= 8 if not y_count: continue if r != 0: raise BarGraphError # copy whole blocks if y_count > 7: o.append((y_count // 8 * 8, row)) y_count %= 8 # noqa: PLW2901 if not y_count: continue o.append((y_count, row)) r = y_count return [(y // 8, row) for (y, row) in o] def render(self, size: tuple[int, int], focus: bool = False) -> CompositeCanvas: """ Render BarGraph. """ (maxcol, maxrow) = size disp = self.calculate_display((maxcol, maxrow)) combinelist = [] for y_count, row in disp: widget_list = [] for bar_type, width in row: if isinstance(bar_type, tuple): if len(bar_type) == 3: # vertical eighths fg, bg, k = bar_type a = self.satt[fg, bg] t = self.eighths[k] * width else: # horizontal lines bg, k = bar_type a = self.hatt[bg] t = self.hlines[k] * width else: a = self.attr[bar_type] t = self.char[bar_type] * width widget_list.append((a, t)) c = Text(widget_list).render((maxcol,)) if c.rows() != 1: raise BarGraphError("Invalid characters in BarGraph!") combinelist += [(c, None, False)] * y_count canv = CanvasCombine(combinelist) return canv def calculate_bargraph_display(bardata, top: float, bar_widths: list[int], maxrow: int): """ Calculate a rendering of the bar graph described by data, bar_widths and height. bardata -- bar information with same structure as BarGraph.data top -- maximal value for bardata segments bar_widths -- list of integer column widths for each bar maxrow -- rows for display of bargraph Returns a structure as follows: [ ( y_count, [ ( bar_type, width), ... ] ), ... ] The outer tuples represent a set of identical rows. y_count is the number of rows in this set, the list contains the data to be displayed in the row repeated through the set. The inner tuple describes a run of width characters of bar_type. bar_type is an integer starting from 0 for the background, 1 for the 1st segment, 2 for the 2nd segment etc.. This function should complete in approximately O(n+m) time, where n is the number of bars displayed and m is the number of rows. """ if len(bardata) != len(bar_widths): raise BarGraphError maxcol = sum(bar_widths) # build intermediate data structure rows = [None] * maxrow def add_segment(seg_num: int, col: int, row: int, width: int, rows=rows) -> None: if rows[row]: last_seg, last_col, last_end = rows[row][-1] if last_end > col: if last_col >= col: del rows[row][-1] else: rows[row][-1] = (last_seg, last_col, col) elif last_seg == seg_num and last_end == col: rows[row][-1] = (last_seg, last_col, last_end + width) return elif rows[row] is None: rows[row] = [] rows[row].append((seg_num, col, col + width)) col = 0 barnum = 0 for bar in bardata: width = bar_widths[barnum] if width < 1: continue # loop through in reverse order tallest = maxrow segments = scale_bar_values(bar, top, maxrow) for k in range(len(bar) - 1, -1, -1): s = segments[k] if s >= maxrow: continue s = max(s, 0) if s < tallest: # add only properly-overlapped bars tallest = s add_segment(k + 1, col, s, width) col += width barnum += 1 # print(repr(rows)) # build rowsets data structure rowsets = [] y_count = 0 last = [(0, maxcol)] for r in rows: if r is None: y_count += 1 continue if y_count: rowsets.append((y_count, last)) y_count = 0 i = 0 # index into "last" la, ln = last[i] # last attribute, last run length c = 0 # current column o = [] # output list to be added to rowsets for seg_num, start, end in r: while start > c + ln: o.append((la, ln)) i += 1 c += ln la, ln = last[i] if la == seg_num: # same attribute, can combine o.append((la, end - c)) else: if start - c > 0: o.append((la, start - c)) o.append((seg_num, end - start)) if end == maxcol: i = len(last) break # skip past old segments covered by new one while end >= c + ln: i += 1 c += ln la, ln = last[i] if la != seg_num: ln = c + ln - end c = end continue # same attribute, can extend oa, on = o[-1] on += c + ln - end o[-1] = oa, on i += 1 c += ln if c == maxcol: break if i >= len(last): raise ValueError(repr((on, maxcol))) la, ln = last[i] if i < len(last): o += [(la, ln)] + last[i + 1 :] last = o y_count += 1 if y_count: rowsets.append((y_count, last)) return rowsets class GraphVScale(Widget): _sizing = frozenset([Sizing.BOX]) def __init__(self, labels, top: float) -> None: """ GraphVScale( [(label1 position, label1 markup),...], top ) label position -- 0 < position < top for the y position label markup -- text markup for this label top -- top y position This widget is a vertical scale for the BarGraph widget that can correspond to the BarGraph's horizontal lines """ super().__init__() self.set_scale(labels, top) def set_scale(self, labels, top: float) -> None: """ set_scale( [(label1 position, label1 markup),...], top ) label position -- 0 < position < top for the y position label markup -- text markup for this label top -- top y position """ labels = sorted(labels[:], reverse=True) # shallow copy self.pos = [] self.txt = [] for y, markup in labels: self.pos.append(y) self.txt.append(Text(markup)) self.top = top def selectable(self) -> Literal[False]: """ Return False. """ return False def render( self, size: tuple[int, int], focus: bool = False, ) -> SolidCanvas | CompositeCanvas: """ Render GraphVScale. """ (maxcol, maxrow) = size pl = scale_bar_values(self.pos, self.top, maxrow) combinelist = [] rows = 0 for p, t in zip(pl, self.txt): p -= 1 # noqa: PLW2901 if p >= maxrow: break if p < rows: continue c = t.render((maxcol,)) if p > rows: run = p - rows c = CompositeCanvas(c) c.pad_trim_top_bottom(run, 0) rows += c.rows() combinelist.append((c, None, False)) if not combinelist: return SolidCanvas(" ", size[0], size[1]) canvas = CanvasCombine(combinelist) if maxrow - rows: canvas.pad_trim_top_bottom(0, maxrow - rows) return canvas def scale_bar_values(bar, top: float, maxrow: int) -> list[int]: """ Return a list of bar values aliased to integer values of maxrow. """ return [maxrow - int(float(v) * maxrow / top + 0.5) for v in bar]
21,601
Python
.py
550
27.692727
119
0.526173
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,253
overlay.py
urwid_urwid/urwid/widget/overlay.py
from __future__ import annotations import typing import warnings from urwid.canvas import CanvasOverlay, CompositeCanvas from urwid.split_repr import remove_defaults from .constants import ( RELATIVE_100, Align, Sizing, VAlign, WHSettings, WrapMode, normalize_align, normalize_height, normalize_valign, normalize_width, simplify_align, simplify_height, simplify_valign, simplify_width, ) from .container import WidgetContainerListContentsMixin, WidgetContainerMixin from .filler import calculate_top_bottom_filler from .padding import calculate_left_right_padding from .widget import Widget, WidgetError, WidgetWarning if typing.TYPE_CHECKING: from collections.abc import Iterator, MutableSequence, Sequence from typing_extensions import Literal TopWidget = typing.TypeVar("TopWidget") BottomWidget = typing.TypeVar("BottomWidget") class OverlayError(WidgetError): """Overlay specific errors.""" class OverlayWarning(WidgetWarning): """Overlay specific warnings.""" def _check_widget_subclass(widget: Widget) -> None: if not isinstance(widget, Widget): obj_class_path = f"{widget.__class__.__module__}.{widget.__class__.__name__}" warnings.warn( f"{obj_class_path} is not subclass of Widget", DeprecationWarning, stacklevel=3, ) class OverlayOptions(typing.NamedTuple): align: Align | Literal[WHSettings.RELATIVE] align_amount: int | None width_type: WHSettings width_amount: int | None min_width: int | None left: int right: int valign_type: VAlign | Literal[WHSettings.RELATIVE] valign_amount: int | None height_type: WHSettings height_amount: int | None min_height: int | None top: int bottom: int class Overlay(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin, typing.Generic[TopWidget, BottomWidget]): """Overlay contains two widgets and renders one on top of the other. Top widget can be Box, Flow or Fixed. Bottom widget should be Box. """ _selectable = True _DEFAULT_BOTTOM_OPTIONS = OverlayOptions( align=Align.LEFT, align_amount=None, width_type=WHSettings.RELATIVE, width_amount=100, min_width=None, left=0, right=0, valign_type=VAlign.TOP, valign_amount=None, height_type=WHSettings.RELATIVE, height_amount=100, min_height=None, top=0, bottom=0, ) def __init__( self, top_w: TopWidget, bottom_w: BottomWidget, align: ( Literal["left", "center", "right"] | Align | tuple[Literal["relative", "fixed left", "fixed right", WHSettings.RELATIVE], int] ), width: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None, valign: ( Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", "fixed top", "fixed bottom", WHSettings.RELATIVE], int] ), height: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None, min_width: int | None = None, min_height: int | None = None, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0, ) -> None: """ :param top_w: a flow, box or fixed widget to overlay "on top". :type top_w: Widget :param bottom_w: a box widget to appear "below" previous widget. :type bottom_w: Widget :param align: alignment, one of ``'left'``, ``'center'``, ``'right'`` or (``'relative'``, *percentage* 0=left 100=right) :type align: Literal["left", "center", "right"] | tuple[Literal["relative"], int] :param width: width type, one of: ``'pack'`` if *top_w* is a fixed widget *given width* integer number of columns wide (``'relative'``, *percentage of total width*) make *top_w* width related to container width :type width: Literal["pack"] | int | tuple[Literal["relative"], int] :param valign: alignment mode, one of ``'top'``, ``'middle'``, ``'bottom'`` or (``'relative'``, *percentage* 0=top 100=bottom) :type valign: Literal["top", "middle", "bottom"] | tuple[Literal["relative"], int] :param height: one of: ``'pack'`` if *top_w* is a flow or fixed widget *given height* integer number of rows high (``'relative'``, *percentage of total height*) make *top_w* height related to container height :type height: Literal["pack"] | int | tuple[Literal["relative"], int] :param min_width: the minimum number of columns for *top_w* when width is not fixed. :type min_width: int :param min_height: minimum number of rows for *top_w* when height is not fixed. :type min_height: int :param left: a fixed number of columns to add on the left. :type left: int :param right: a fixed number of columns to add on the right. :type right: int :param top: a fixed number of rows to add on the top. :type top: int :param bottom: a fixed number of rows to add on the bottom. :type bottom: int Overlay widgets behave similarly to :class:`Padding` and :class:`Filler` widgets when determining the size and position of *top_w*. *bottom_w* is always rendered the full size available "below" *top_w*. """ super().__init__() self.top_w = top_w self.bottom_w = bottom_w self.set_overlay_parameters(align, width, valign, height, min_width, min_height, left, right, top, bottom) _check_widget_subclass(top_w) _check_widget_subclass(bottom_w) def sizing(self) -> frozenset[Sizing]: """Actual widget sizing. :returns: Sizing information depends on the top widget sizing and sizing parameters. :rtype: frozenset[Sizing] Rules: * BOX sizing is always supported provided by the bottom widget * FLOW sizing is supported if top widget has: * * PACK height type and FLOW supported by the TOP widget * * BOX supported by TOP widget AND height amount AND height type GIVEN of min_height * FIXED sizing is supported if top widget has: * * PACK width type and FIXED supported by the TOP widget * * width amount and GIVEN width or min_width AND: * * * FLOW supported by the TOP widget AND PACK height type * * * BOX supported by the TOP widget AND height_amount and GIVEN height or min height """ sizing = {Sizing.BOX} top_sizing = self.top_w.sizing() if self.width_type == WHSettings.PACK: if Sizing.FIXED in top_sizing: sizing.add(Sizing.FIXED) else: warnings.warn( f"Top widget {self.top_w} should support sizing {Sizing.FIXED.upper()} " f"for width type {WHSettings.PACK.upper()}", OverlayWarning, stacklevel=3, ) elif self.height_type == WHSettings.PACK: if Sizing.FLOW in top_sizing: sizing.add(Sizing.FLOW) if self.width_amount and (self.width_type == WHSettings.GIVEN or self.min_width): sizing.add(Sizing.FIXED) else: warnings.warn( f"Top widget {self.top_w} should support sizing {Sizing.FLOW.upper()} " f"for height type {self.height_type.upper()}", OverlayWarning, stacklevel=3, ) elif self.height_amount and (self.height_type == WHSettings.GIVEN or self.min_height): if Sizing.BOX in top_sizing: sizing.add(Sizing.FLOW) if self.width_amount and (self.width_type == WHSettings.GIVEN or self.min_width): sizing.add(Sizing.FIXED) else: warnings.warn( f"Top widget {self.top_w} should support sizing {Sizing.BOX.upper()} " f"for height type {self.height_type.upper()}", OverlayWarning, stacklevel=3, ) return frozenset(sizing) def pack( self, size: tuple[()] | tuple[int] | tuple[int, int] = (), focus: bool = False, ) -> tuple[int, int]: if size: return super().pack(size, focus) extra_cols = (self.left or 0) + (self.right or 0) extra_rows = (self.top or 0) + (self.bottom or 0) if self.width_type == WHSettings.PACK: cols, rows = self.top_w.pack((), focus) return cols + extra_cols, rows + extra_rows if not self.width_amount: raise OverlayError( f"Requested FIXED render for {self.top_w} with " f"width_type={self.width_type.upper()}, " f"width_amount={self.width_amount!r}, " f"height_type={self.height_type.upper()}, " f"height_amount={self.height_amount!r}" f"min_width={self.min_width!r}, " f"min_height={self.min_height!r}" ) if self.width_type == WHSettings.GIVEN: w_cols = self.width_amount cols = w_cols + extra_cols elif self.width_type == WHSettings.RELATIVE and self.min_width: w_cols = self.min_width cols = int(w_cols * 100 / self.width_amount + 0.5) else: raise OverlayError( f"Requested FIXED render for {self.top_w} with " f"width_type={self.width_type.upper()}, " f"width_amount={self.width_amount!r}, " f"height_type={self.height_type.upper()}, " f"height_amount={self.height_amount!r}" f"min_width={self.min_width!r}, " f"min_height={self.min_height!r}" ) if self.height_type == WHSettings.PACK: return cols, self.top_w.rows((w_cols,), focus) + extra_rows if not self.height_amount: raise OverlayError( f"Requested FIXED render for {self.top_w} with " f"width_type={self.width_type.upper()}, " f"width_amount={self.width_amount!r}, " f"height_type={self.height_type.upper()}, " f"height_amount={self.height_amount!r}" f"min_width={self.min_width!r}, " f"min_height={self.min_height!r}" ) if self.height_type == WHSettings.GIVEN: return cols, self.height_amount + extra_rows if self.height_type == WHSettings.RELATIVE and self.min_height: return cols, int(self.min_height * 100 / self.height_amount + 0.5) raise OverlayError( f"Requested FIXED render for {self.top_w} with " f"width_type={self.width_type.upper()}, " f"width_amount={self.width_amount!r}, " f"height_type={self.height_type.upper()}, " f"height_amount={self.height_amount!r}" f"min_width={self.min_width!r}, " f"min_height={self.min_height!r}" ) def rows(self, size: tuple[int], focus: bool = False) -> int: """Widget rows amount for FLOW sizing.""" extra_height = (self.top or 0) + (self.bottom or 0) if self.height_type == WHSettings.GIVEN: return self.height_amount + extra_height if self.height_type == WHSettings.RELATIVE and self.min_height: return int(self.min_height * 100 / self.height_amount + 0.5) if self.height_type == WHSettings.PACK: extra_height = (self.top or 0) + (self.bottom or 0) if self.width_type == WHSettings.GIVEN and self.width_amount: return self.top_w.rows((self.width_amount,), focus) + extra_height if self.width_type == WHSettings.RELATIVE: width = max(int(size[0] * self.width_amount / 100 + 0.5), (self.min_width or 0)) return self.top_w.rows((width,), focus) + extra_height raise OverlayError( f"Requested rows for {self.top_w} with size {size!r}" f"width_type={self.width_type.upper()}, " f"width_amount={self.width_amount!r}, " f"height_type={self.height_type.upper()}, " f"height_amount={self.height_amount!r}" f"min_width={self.min_width!r}, " f"min_height={self.min_height!r}" ) def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "top_w": self.top_w, "bottom_w": self.bottom_w, "align": self.align, "width": self.width, "valign": self.valign, "height": self.height, "min_width": self.min_width, "min_height": self.min_height, "left": self.left, "right": self.right, "top": self.top, "bottom": self.bottom, } return remove_defaults(attrs, Overlay.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: yield "top", self.top_w yield "bottom", self.bottom_w yield "align", self.align yield "width", self.width yield "valign", self.valign yield "height", self.height yield "min_width", self.min_width yield "min_height", self.min_height yield "left", self.left yield "right", self.right yield "top", self.top yield "bottom", self.bottom @property def align(self) -> Align | tuple[Literal[WHSettings.RELATIVE], int]: return simplify_align(self.align_type, self.align_amount) @property def width( self, ) -> ( Literal[WHSettings.CLIP, WHSettings.PACK] | int | tuple[Literal[WHSettings.RELATIVE], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): return simplify_width(self.width_type, self.width_amount) @property def valign(self) -> VAlign | tuple[Literal[WHSettings.RELATIVE], int]: return simplify_valign(self.valign_type, self.valign_amount) @property def height( self, ) -> ( int | Literal[WHSettings.FLOW, WHSettings.PACK] | tuple[Literal[WHSettings.RELATIVE], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): return simplify_height(self.height_type, self.height_amount) @staticmethod def options( align_type: Literal["left", "center", "right", "relative", WHSettings.RELATIVE] | Align, align_amount: int | None, width_type: Literal["clip", "pack", "relative", "given"] | WHSettings, width_amount: int | None, valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign, valign_amount: int | None, height_type: Literal["flow", "pack", "relative", "given"] | WHSettings, height_amount: int | None, min_width: int | None = None, min_height: int | None = None, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0, ) -> OverlayOptions: """ Return a new options tuple for use in this Overlay's .contents mapping. This is the common container API to create options for replacing the top widget of this Overlay. It is provided for completeness but is not necessarily the easiest way to change the overlay parameters. See also :meth:`.set_overlay_parameters` """ if align_type in {Align.LEFT, Align.CENTER, Align.RIGHT}: align = Align(align_type) elif align_type == WHSettings.RELATIVE: align = WHSettings.RELATIVE else: raise ValueError(f"Unknown alignment type {align_type!r}") if valign_type in {VAlign.TOP, VAlign.MIDDLE, VAlign.BOTTOM}: valign = VAlign(valign_type) elif valign_type == WHSettings.RELATIVE: valign = WHSettings.RELATIVE else: raise ValueError(f"Unknown vertical alignment type {valign_type!r}") return OverlayOptions( align, align_amount, WHSettings(width_type), width_amount, min_width, left, right, valign, valign_amount, WHSettings(height_type), height_amount, min_height, top, bottom, ) def set_overlay_parameters( self, align: ( Literal["left", "center", "right"] | Align | tuple[Literal["relative", "fixed left", "fixed right", WHSettings.RELATIVE], int] ), width: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None, valign: ( Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", "fixed top", "fixed bottom", WHSettings.RELATIVE], int] ), height: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None, min_width: int | None = None, min_height: int | None = None, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0, ) -> None: """ Adjust the overlay size and position parameters. See :class:`__init__() <Overlay>` for a description of the parameters. """ # convert obsolete parameters 'fixed ...': if isinstance(align, tuple): if align[0] == "fixed left": left = align[1] normalized_align = Align.LEFT elif align[0] == "fixed right": right = align[1] normalized_align = Align.RIGHT else: normalized_align = align else: normalized_align = Align(align) if isinstance(width, tuple): if width[0] == "fixed left": left = width[1] width = RELATIVE_100 elif width[0] == "fixed right": right = width[1] width = RELATIVE_100 if isinstance(valign, tuple): if valign[0] == "fixed top": top = valign[1] normalized_valign = VAlign.TOP elif valign[0] == "fixed bottom": bottom = valign[1] normalized_valign = VAlign.BOTTOM else: normalized_valign = valign elif not isinstance(valign, (VAlign, str)): raise OverlayError(f"invalid valign: {valign!r}") else: normalized_valign = VAlign(valign) if isinstance(height, tuple): if height[0] == "fixed bottom": bottom = height[1] height = RELATIVE_100 elif height[0] == "fixed top": top = height[1] height = RELATIVE_100 if width is None: # more obsolete values accepted width = WHSettings.PACK if height is None: height = WHSettings.PACK align_type, align_amount = normalize_align(normalized_align, OverlayError) width_type, width_amount = normalize_width(width, OverlayError) valign_type, valign_amount = normalize_valign(normalized_valign, OverlayError) height_type, height_amount = normalize_height(height, OverlayError) if height_type in {WHSettings.GIVEN, WHSettings.PACK}: min_height = None # use container API to set the parameters self.contents[1] = ( self.top_w, self.options( align_type, align_amount, width_type, width_amount, valign_type, valign_amount, height_type, height_amount, min_width, min_height, left, right, top, bottom, ), ) def selectable(self) -> bool: """Return selectable from top_w.""" return self.top_w.selectable() def keypress( self, size: tuple[()] | tuple[int] | tuple[int, int], key: str, ) -> str | None: """Pass keypress to top_w.""" real_size = self.pack(size, True) return self.top_w.keypress( self.top_w_size(real_size, *self.calculate_padding_filler(real_size, True)), key, ) @property def focus(self) -> TopWidget: """ Read-only property returning the child widget in focus for container widgets. This default implementation always returns ``None``, indicating that this widget has no children. """ return self.top_w def _get_focus(self) -> TopWidget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) return self.top_w @property def focus_position(self) -> Literal[1]: """ Return the top widget position (currently always 1). """ return 1 @focus_position.setter def focus_position(self, position: int) -> None: """ Set the widget in focus. Currently only position 0 is accepted. position -- index of child widget to be made focus """ if position != 1: raise IndexError(f"Overlay widget focus_position currently must always be set to 1, not {position}") def _get_focus_position(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) return 1 def _set_focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ warnings.warn( f"method `{self.__class__.__name__}._set_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) if position != 1: raise IndexError(f"Overlay widget focus_position currently must always be set to 1, not {position}") @property def contents(self) -> MutableSequence[tuple[TopWidget | BottomWidget, OverlayOptions]]: """ a list-like object similar to:: [(bottom_w, bottom_options)), (top_w, top_options)] This object may be used to read or update top and bottom widgets and top widgets's options, but no widgets may be added or removed. `top_options` takes the form `(align_type, align_amount, width_type, width_amount, min_width, left, right, valign_type, valign_amount, height_type, height_amount, min_height, top, bottom)` bottom_options is always `('left', None, 'relative', 100, None, 0, 0, 'top', None, 'relative', 100, None, 0, 0)` which means that bottom widget always covers the full area of the Overlay. writing a different value for `bottom_options` raises an :exc:`OverlayError`. """ # noinspection PyMethodParameters class OverlayContents( typing.MutableSequence[ typing.Tuple[ typing.Union[TopWidget, BottomWidget], OverlayOptions, ] ] ): # pylint: disable=no-self-argument def __len__(inner_self) -> int: return 2 __getitem__ = self._contents__getitem__ __setitem__ = self._contents__setitem__ def __delitem__(self, index: int | slice) -> typing.NoReturn: raise TypeError("OverlayContents is fixed-sized sequence") def insert(self, index: int | slice, value: typing.Any) -> typing.NoReturn: raise TypeError("OverlayContents is fixed-sized sequence") def __repr__(inner_self) -> str: return repr(f"<{inner_self.__class__.__name__}({[inner_self[0], inner_self[1]]})> for {self}") def __rich_repr__(inner_self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: for val in inner_self: yield None, val def __iter__(inner_self) -> Iterator[tuple[Widget, OverlayOptions]]: for idx in range(2): yield inner_self[idx] return OverlayContents() @contents.setter def contents(self, new_contents: Sequence[tuple[width, OverlayOptions]]) -> None: if len(new_contents) != 2: raise ValueError("Contents length for overlay should be only 2") self.contents[0] = new_contents[0] self.contents[1] = new_contents[1] def _contents__getitem__( self, index: Literal[0, 1], ) -> tuple[TopWidget | BottomWidget, OverlayOptions]: if index == 0: return (self.bottom_w, self._DEFAULT_BOTTOM_OPTIONS) if index == 1: return ( self.top_w, OverlayOptions( self.align_type, self.align_amount, self.width_type, self.width_amount, self.min_width, self.left, self.right, self.valign_type, self.valign_amount, self.height_type, self.height_amount, self.min_height, self.top, self.bottom, ), ) raise IndexError(f"Overlay.contents has no position {index!r}") def _contents__setitem__( self, index: Literal[0, 1], value: tuple[TopWidget | BottomWidget, OverlayOptions], ) -> None: try: value_w, value_options = value except (ValueError, TypeError) as exc: raise OverlayError(f"added content invalid: {value!r}").with_traceback(exc.__traceback__) from exc if index == 0: if value_options != self._DEFAULT_BOTTOM_OPTIONS: raise OverlayError(f"bottom_options must be set to {self._DEFAULT_BOTTOM_OPTIONS!r}") self.bottom_w = value_w elif index == 1: try: ( align_type, align_amount, width_type, width_amount, min_width, left, right, valign_type, valign_amount, height_type, height_amount, min_height, top, bottom, ) = value_options except (ValueError, TypeError) as exc: raise OverlayError(f"top_options is invalid: {value_options!r}").with_traceback( exc.__traceback__ ) from exc # normalize first, this is where errors are raised align_type, align_amount = normalize_align(simplify_align(align_type, align_amount), OverlayError) width_type, width_amount = normalize_width(simplify_width(width_type, width_amount), OverlayError) valign_type, valign_amount = normalize_valign(simplify_valign(valign_type, valign_amount), OverlayError) height_type, height_amount = normalize_height(simplify_height(height_type, height_amount), OverlayError) self.align_type = align_type self.align_amount = align_amount self.width_type = width_type self.width_amount = width_amount self.valign_type = valign_type self.valign_amount = valign_amount self.height_type = height_type self.height_amount = height_amount self.left = left self.right = right self.top = top self.bottom = bottom self.min_width = min_width self.min_height = min_height else: raise IndexError(f"Overlay.contents has no position {index!r}") self._invalidate() def get_cursor_coords( self, size: tuple[()] | tuple[int] | tuple[int, int], ) -> tuple[int, int] | None: """Return cursor coords from top_w, if any.""" if not hasattr(self.top_w, "get_cursor_coords"): return None real_size = self.pack(size, True) (maxcol, maxrow) = real_size left, right, top, bottom = self.calculate_padding_filler(real_size, True) x, y = self.top_w.get_cursor_coords((maxcol - left - right, maxrow - top - bottom)) if y >= maxrow: # required?? y = maxrow - 1 return x + left, y + top def calculate_padding_filler( self, size: tuple[int, int], focus: bool, ) -> tuple[int, int, int, int]: """Return (padding left, right, filler top, bottom).""" (maxcol, maxrow) = size height = None if self.width_type == WHSettings.PACK: width, height = self.top_w.pack((), focus=focus) if not height: raise OverlayError("fixed widget must have a height") left, right = calculate_left_right_padding( maxcol, self.align_type, self.align_amount, WrapMode.CLIP, width, None, self.left, self.right, ) else: left, right = calculate_left_right_padding( maxcol, self.align_type, self.align_amount, self.width_type, self.width_amount, self.min_width, self.left, self.right, ) if height: # top_w is a fixed widget top, bottom = calculate_top_bottom_filler( maxrow, self.valign_type, self.valign_amount, WHSettings.GIVEN, height, None, self.top, self.bottom, ) if maxrow - top - bottom < height: bottom = maxrow - top - height elif self.height_type == WHSettings.PACK: # top_w is a flow widget height = self.top_w.rows((maxcol,), focus=focus) top, bottom = calculate_top_bottom_filler( maxrow, self.valign_type, self.valign_amount, WHSettings.GIVEN, height, None, self.top, self.bottom, ) if height > maxrow: # flow widget rendered too large bottom = maxrow - height else: top, bottom = calculate_top_bottom_filler( maxrow, self.valign_type, self.valign_amount, self.height_type, self.height_amount, self.min_height, self.top, self.bottom, ) return left, right, top, bottom def top_w_size( self, size: tuple[int, int], left: int, right: int, top: int, bottom: int, ) -> tuple[()] | tuple[int] | tuple[int, int]: """Return the size to pass to top_w.""" if self.width_type == WHSettings.PACK: # top_w is a fixed widget return () maxcol, maxrow = size if self.width_type != WHSettings.PACK and self.height_type == WHSettings.PACK: # top_w is a flow widget return (maxcol - left - right,) return (maxcol - left - right, maxrow - top - bottom) def render(self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False) -> CompositeCanvas: """Render top_w overlayed on bottom_w.""" real_size = self.pack(size, focus) left, right, top, bottom = self.calculate_padding_filler(real_size, focus) bottom_c = self.bottom_w.render(real_size) if not bottom_c.cols() or not bottom_c.rows(): return CompositeCanvas(bottom_c) top_c = self.top_w.render(self.top_w_size(real_size, left, right, top, bottom), focus) top_c = CompositeCanvas(top_c) if left < 0 or right < 0: top_c.pad_trim_left_right(min(0, left), min(0, right)) if top < 0 or bottom < 0: top_c.pad_trim_top_bottom(min(0, top), min(0, bottom)) return CanvasOverlay(top_c, bottom_c, left, top) def mouse_event( self, size: tuple[()] | tuple[int] | tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """Pass event to top_w, ignore if outside of top_w.""" if not hasattr(self.top_w, "mouse_event"): return False real_size = self.pack(size, focus) left, right, top, bottom = self.calculate_padding_filler(real_size, focus) maxcol, maxrow = real_size if col < left or col >= maxcol - right or row < top or row >= maxrow - bottom: return False return self.top_w.mouse_event( self.top_w_size(real_size, left, right, top, bottom), event, button, col - left, row - top, focus, )
34,505
Python
.py
836
29.852871
119
0.557267
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,254
container.py
urwid_urwid/urwid/widget/container.py
from __future__ import annotations import abc import enum import typing import warnings from .constants import Sizing, WHSettings if typing.TYPE_CHECKING: from collections.abc import Iterable, Iterator from .widget import Widget class _ContainerElementSizingFlag(enum.IntFlag): NONE = 0 BOX = enum.auto() FLOW = enum.auto() FIXED = enum.auto() WH_WEIGHT = enum.auto() WH_PACK = enum.auto() WH_GIVEN = enum.auto() @property def reverse_flag(self) -> tuple[frozenset[Sizing], WHSettings | None]: """Get flag in public API format.""" sizing: set[Sizing] = set() if self & self.BOX: sizing.add(Sizing.BOX) if self & self.FLOW: sizing.add(Sizing.FLOW) if self & self.FIXED: sizing.add(Sizing.FIXED) if self & self.WH_WEIGHT: return frozenset(sizing), WHSettings.WEIGHT if self & self.WH_PACK: return frozenset(sizing), WHSettings.PACK if self & self.WH_GIVEN: return frozenset(sizing), WHSettings.GIVEN return frozenset(sizing), None @property def log_string(self) -> str: """Get desctiprion in public API format.""" sizing, render = self.reverse_flag render_string = f" {render.upper()}" if render else "" return "|".join(sorted(mode.upper() for mode in sizing)) + render_string class WidgetContainerMixin: """ Mixin class for widget containers implementing common container methods """ def __getitem__(self, position) -> Widget: """ Container short-cut for self.contents[position][0].base_widget which means "give me the child widget at position without any widget decorations". This allows for concise traversal of nested container widgets such as: my_widget[position0][position1][position2] ... """ return self.contents[position][0].base_widget def get_focus_path(self) -> list[int | str]: """ Return the .focus_position values starting from this container and proceeding along each child widget until reaching a leaf (non-container) widget. """ out = [] w = self while True: try: p = w.focus_position except IndexError: return out out.append(p) w = w.focus.base_widget def set_focus_path(self, positions: Iterable[int | str]) -> None: """ Set the .focus_position property starting from this container widget and proceeding along newly focused child widgets. Any failed assignment due do incompatible position types or invalid positions will raise an IndexError. This method may be used to restore a particular widget to the focus by passing in the value returned from an earlier call to get_focus_path(). positions -- sequence of positions """ w: Widget = self for p in positions: if p != w.focus_position: w.focus_position = p # modifies w.focus w = w.focus.base_widget # type: ignore[assignment] def get_focus_widgets(self) -> list[Widget]: """ Return the .focus values starting from this container and proceeding along each child widget until reaching a leaf (non-container) widget. Note that the list does not contain the topmost container widget (i.e., on which this method is called), but does include the lowest leaf widget. """ out = [] w = self while True: w = w.base_widget.focus if w is None: return out out.append(w) @property @abc.abstractmethod def focus(self) -> Widget: """ Read-only property returning the child widget in focus for container widgets. This default implementation always returns ``None``, indicating that this widget has no children. """ def _get_focus(self) -> Widget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) return self.focus class WidgetContainerListContentsMixin: """ Mixin class for widget containers whose positions are indexes into a list available as self.contents. """ def __iter__(self) -> Iterator[int]: """ Return an iterable of positions for this container from first to last. """ return iter(range(len(self.contents))) def __reversed__(self) -> Iterator[int]: """ Return an iterable of positions for this container from last to first. """ return iter(range(len(self.contents) - 1, -1, -1)) def __len__(self) -> int: return len(self.contents) @property @abc.abstractmethod def contents(self) -> list[tuple[Widget, typing.Any]]: """The contents of container as a list of (widget, options)""" @contents.setter def contents(self, new_contents: list[tuple[Widget, typing.Any]]) -> None: """The contents of container as a list of (widget, options)""" def _get_contents(self) -> list[tuple[Widget, typing.Any]]: warnings.warn( f"method `{self.__class__.__name__}._get_contents` is deprecated, " f"please use `{self.__class__.__name__}.contents` property", DeprecationWarning, stacklevel=2, ) return self.contents def _set_contents(self, c: list[tuple[Widget, typing.Any]]) -> None: warnings.warn( f"method `{self.__class__.__name__}._set_contents` is deprecated, " f"please use `{self.__class__.__name__}.contents` property", DeprecationWarning, stacklevel=2, ) self.contents = c @property @abc.abstractmethod def focus_position(self) -> int | None: """ index of child widget in focus. """ @focus_position.setter def focus_position(self, position: int) -> None: """ index of child widget in focus. """ def _get_focus_position(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) return self.focus_position def _set_focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ warnings.warn( f"method `{self.__class__.__name__}._set_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) self.focus_position = position
7,177
Python
.py
190
29.021053
85
0.602734
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,255
widget.py
urwid_urwid/urwid/widget/widget.py
# Urwid basic widget classes # Copyright (C) 2004-2012 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import functools import logging import typing import warnings from operator import attrgetter from urwid import signals from urwid.canvas import Canvas, CanvasCache, CompositeCanvas from urwid.command_map import command_map from urwid.split_repr import split_repr from urwid.util import MetaSuper from .constants import Sizing if typing.TYPE_CHECKING: from collections.abc import Callable, Hashable WrappedWidget = typing.TypeVar("WrappedWidget") LOGGER = logging.getLogger(__name__) class WidgetMeta(MetaSuper, signals.MetaSignals): """ Bases: :class:`MetaSuper`, :class:`MetaSignals` Automatic caching of render and rows methods. Class variable *no_cache* is a list of names of methods to not cache automatically. Valid method names for *no_cache* are ``'render'`` and ``'rows'``. Class variable *ignore_focus* if defined and set to ``True`` indicates that the canvas this widget renders is not affected by the focus parameter, so it may be ignored when caching. """ def __init__(cls, name, bases, d): no_cache = d.get("no_cache", []) super().__init__(name, bases, d) if "render" in d: if "render" not in no_cache: render_fn = cache_widget_render(cls) else: render_fn = nocache_widget_render(cls) cls.render = render_fn if "rows" in d and "rows" not in no_cache: cls.rows = cache_widget_rows(cls) if "no_cache" in d: del cls.no_cache if "ignore_focus" in d: del cls.ignore_focus class WidgetError(Exception): """Widget specific errors.""" class WidgetWarning(Warning): """Widget specific warnings.""" def validate_size(widget, size, canv): """ Raise a WidgetError if a canv does not match size. """ if (size and size[1:] != (0,) and size[0] != canv.cols()) or (len(size) > 1 and size[1] != canv.rows()): raise WidgetError( f"Widget {widget!r} rendered ({canv.cols():d} x {canv.rows():d}) canvas when passed size {size!r}!" ) def cache_widget_render(cls): """ Return a function that wraps the cls.render() method and fetches and stores canvases with CanvasCache. """ ignore_focus = bool(getattr(cls, "ignore_focus", False)) fn = cls.render @functools.wraps(fn) def cached_render(self, size, focus=False): focus = focus and not ignore_focus canv = CanvasCache.fetch(self, cls, size, focus) if canv: return canv canv = fn(self, size, focus=focus) validate_size(self, size, canv) if canv.widget_info: canv = CompositeCanvas(canv) canv.finalize(self, size, focus) CanvasCache.store(cls, canv) return canv cached_render.original_fn = fn return cached_render def nocache_widget_render(cls): """ Return a function that wraps the cls.render() method and finalizes the canvas that it returns. """ fn = cls.render if hasattr(fn, "original_fn"): fn = fn.original_fn @functools.wraps(fn) def finalize_render(self, size, focus=False): canv = fn(self, size, focus=focus) if canv.widget_info: canv = CompositeCanvas(canv) validate_size(self, size, canv) canv.finalize(self, size, focus) return canv finalize_render.original_fn = fn return finalize_render def nocache_widget_render_instance(self): """ Return a function that wraps the cls.render() method and finalizes the canvas that it returns, but does not cache the canvas. """ fn = self.render.original_fn @functools.wraps(fn) def finalize_render(size, focus=False): canv = fn(self, size, focus=focus) if canv.widget_info: canv = CompositeCanvas(canv) canv.finalize(self, size, focus) return canv finalize_render.original_fn = fn return finalize_render def cache_widget_rows(cls): """ Return a function that wraps the cls.rows() method and returns rows from the CanvasCache if available. """ ignore_focus = bool(getattr(cls, "ignore_focus", False)) fn = cls.rows @functools.wraps(fn) def cached_rows(self, size: tuple[int], focus: bool = False) -> int: focus = focus and not ignore_focus canv = CanvasCache.fetch(self, cls, size, focus) if canv: return canv.rows() return fn(self, size, focus) return cached_rows class Widget(metaclass=WidgetMeta): """ Widget base class .. attribute:: _selectable :annotation: = False The default :meth:`.selectable` method returns this value. .. attribute:: _sizing :annotation: = frozenset(['flow', 'box', 'fixed']) The default :meth:`.sizing` method returns this value. .. attribute:: _command_map :annotation: = urwid.command_map A shared :class:`CommandMap` instance. May be redefined in subclasses or widget instances. .. method:: rows(size, focus=False) .. note:: This method is not implemented in :class:`.Widget` but must be implemented by any flow widget. See :meth:`.sizing`. See :meth:`Widget.render` for parameter details. :returns: The number of rows required for this widget given a number of columns in *size* This is the method flow widgets use to communicate their size to other widgets without having to render a canvas. This should be a quick calculation as this function may be called a number of times in normal operation. If your implementation may take a long time you should add your own caching here. There is some metaclass magic defined in the :class:`Widget` metaclass :class:`WidgetMeta` that causes the result of this function to be retrieved from any canvas cached by :class:`CanvasCache`, so if your widget has been rendered you may not receive calls to this function. The class variable :attr:`ignore_focus` may be defined and set to ``True`` if this widget renders the same size regardless of the value of the *focus* parameter. .. method:: get_cursor_coords(size) .. note:: This method is not implemented in :class:`.Widget` but must be implemented by any widget that may return cursor coordinates as part of the canvas that :meth:`render` returns. :param size: See :meth:`Widget.render` for details. :type size: widget size :returns: (*col*, *row*) if this widget has a cursor, ``None`` otherwise Return the cursor coordinates (*col*, *row*) of a cursor that will appear as part of the canvas rendered by this widget when in focus, or ``None`` if no cursor is displayed. The :class:`ListBox` widget uses this method to make sure a cursor in the focus widget is not scrolled out of view. It is a separate method to avoid having to render the whole widget while calculating layout. Container widgets will typically call the :meth:`.get_cursor_coords` method on their focus widget. .. method:: get_pref_col(size) .. note:: This method is not implemented in :class:`.Widget` but may be implemented by a subclass. :param size: See :meth:`Widget.render` for details. :type size: widget size :returns: a column number or ``'left'`` for the leftmost available column or ``'right'`` for the rightmost available column Return the preferred column for the cursor to be displayed in this widget. This value might not be the same as the column returned from :meth:`get_cursor_coords`. The :class:`ListBox` and :class:`Pile` widgets call this method on a widget losing focus and use the value returned to call :meth:`.move_cursor_to_coords` on the widget becoming the focus. This allows the focus to move up and down through widgets while keeping the cursor in approximately the same column on screen. .. method:: move_cursor_to_coords(size, col, row) .. note:: This method is not implemented in :class:`.Widget` but may be implemented by a subclass. Not implementing this method is equivalent to having a method that always returns ``False``. :param size: See :meth:`Widget.render` for details. :type size: widget size :param col: new column for the cursor, 0 is the left edge of this widget :type col: int :param row: new row for the cursor, 0 it the top row of this widget :type row: int :returns: ``True`` if the position was set successfully anywhere on *row*, ``False`` otherwise """ _selectable = False _sizing = frozenset([Sizing.FLOW, Sizing.BOX, Sizing.FIXED]) _command_map = command_map def __init__(self) -> None: self.logger = logging.getLogger(f"{self.__class__.__module__}.{self.__class__.__name__}") def _invalidate(self) -> None: """Mark cached canvases rendered by this widget as dirty so that they will not be used again.""" CanvasCache.invalidate(self) def _emit(self, name: Hashable, *args) -> None: """Convenience function to emit signals with self as first argument.""" signals.emit_signal(self, name, self, *args) def selectable(self) -> bool: """ :returns: ``True`` if this is a widget that is designed to take the focus, i.e. it contains something the user might want to interact with, ``False`` otherwise, This default implementation returns :attr:`._selectable`. Subclasses may leave these is if the are not selectable, or if they are always selectable they may set the :attr:`_selectable` class variable to ``True``. If this method returns ``True`` then the :meth:`.keypress` method must be implemented. Returning ``False`` does not guarantee that this widget will never be in focus, only that this widget will usually be skipped over when changing focus. It is still possible for non selectable widgets to have the focus (typically when there are no other selectable widgets visible). """ return self._selectable def sizing(self) -> frozenset[Sizing]: """ :returns: A frozenset including one or more of ``'box'``, ``'flow'`` and ``'fixed'``. Default implementation returns the value of :attr:`._sizing`, which for this class includes all three. The sizing modes returned indicate the modes that may be supported by this widget, but is not sufficient to know that using that sizing mode will work. Subclasses should make an effort to remove sizing modes they know will not work given the state of the widget, but many do not yet do this. If a sizing mode is missing from the set then the widget should fail when used in that mode. If ``'flow'`` is among the values returned then the other methods in this widget must be able to accept a single-element tuple (*maxcol*,) to their ``size`` parameter, and the :meth:`rows` method must be defined. If ``'box'`` is among the values returned then the other methods must be able to accept a two-element tuple (*maxcol*, *maxrow*) to their size parameter. If ``'fixed'`` is among the values returned then the other methods must be able to accept an empty tuple () to their size parameter, and the :meth:`pack` method must be defined. """ return self._sizing def pack(self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False) -> tuple[int, int]: """ See :meth:`Widget.render` for parameter details. :returns: A "packed" size (*maxcol*, *maxrow*) for this widget Calculate and return a minimum size where all content could still be displayed. Fixed widgets must implement this method and return their size when ``()`` is passed as the *size* parameter. This default implementation returns the *size* passed, or the *maxcol* passed and the value of :meth:`rows` as the *maxrow* when (*maxcol*,) is passed as the *size* parameter. .. note:: This is a new method that hasn't been fully implemented across the standard widget types. In particular it has not yet been implemented for container widgets. :class:`Text` widgets have implemented this method. You can use :meth:`Text.pack` to calculate the minimum columns and rows required to display a text widget without wrapping, or call it iteratively to calculate the minimum number of columns required to display the text wrapped into a target number of rows. """ if not size: if Sizing.FIXED in self.sizing(): raise NotImplementedError(f"{self!r} must override Widget.pack()") raise WidgetError(f"Cannot pack () size, this is not a fixed widget: {self!r}") if len(size) == 1: if Sizing.FLOW in self.sizing(): return (*size, self.rows(size, focus)) # pylint: disable=no-member # can not announce abstract raise WidgetError(f"Cannot pack (maxcol,) size, this is not a flow widget: {self!r}") return size @property def base_widget(self) -> Widget: """Read-only property that steps through decoration widgets and returns the one at the base. This default implementation returns self. """ return self @property def focus(self) -> Widget | None: """ Read-only property returning the child widget in focus for container widgets. This default implementation always returns ``None``, indicating that this widget has no children. """ return None def _not_a_container(self, val=None): raise IndexError(f"No focus_position, {self!r} is not a container widget") focus_position = property( _not_a_container, _not_a_container, doc=""" Property for reading and setting the focus position for container widgets. This default implementation raises :exc:`IndexError`, making normal widgets fail the same way accessing :attr:`.focus_position` on an empty container widget would. """, ) def __repr__(self): """A friendly __repr__ for widgets. Designed to be extended by subclasses with _repr_words and _repr_attr methods. """ return split_repr(self) def _repr_words(self) -> list[str]: words = [] if self.selectable(): words = ["selectable", *words] if self.sizing() and self.sizing() != frozenset([Sizing.FLOW, Sizing.BOX, Sizing.FIXED]): words.append("/".join(sorted(self.sizing()))) return [*words, "widget"] def _repr_attrs(self) -> dict[str, typing.Any]: return {} def keypress( self, size: tuple[()] | tuple[int] | tuple[int, int], key: str, ) -> str | None: """Keyboard input handler. :param size: See :meth:`Widget.render` for details :type size: tuple[()] | tuple[int] | tuple[int, int] :param key: a single keystroke value; see :ref:`keyboard-input` :type key: str :return: ``None`` if *key* was handled by *key* (the same value passed) if *key* was not handled :rtype: str | None """ if not self.selectable(): if hasattr(self, "logger"): self.logger.debug(f"keypress sent to non selectable widget {self!r}") else: warnings.warn( f"Widget {self.__class__.__name__} did not call 'super().__init__()", WidgetWarning, stacklevel=3, ) LOGGER.debug(f"Widget {self!r} is not selectable") return key def mouse_event( self, size: tuple[()] | tuple[int] | tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """Mouse event handler. :param size: See :meth:`Widget.render` for details. :type size: tuple[()] | tuple[int] | tuple[int, int] :param event: Values such as ``'mouse press'``, ``'ctrl mouse press'``, ``'mouse release'``, ``'meta mouse release'``, ``'mouse drag'``; see :ref:`mouse-input` :type event: str :param button: 1 through 5 for press events, often 0 for release events (which button was released is often not known) :type button: int :param col: Column of the event, 0 is the left edge of this widget :type col: int :param row: Row of the event, 0 it the top row of this widget :type row: int :param focus: Set to ``True`` if this widget or one of its children is in focus :type focus: bool :return: ``True`` if the event was handled by this widget, ``False`` otherwise :rtype: bool | None """ if not self.selectable(): if hasattr(self, "logger"): self.logger.debug(f"Widget {self!r} is not selectable") else: warnings.warn( f"Widget {self.__class__.__name__} not called 'super().__init__()", WidgetWarning, stacklevel=3, ) LOGGER.debug(f"Widget {self!r} is not selectable") return False def render( self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False, ) -> Canvas: """Render widget and produce canvas :param size: One of the following, *maxcol* and *maxrow* are integers > 0: (*maxcol*, *maxrow*) for box sizing -- the parent chooses the exact size of this widget (*maxcol*,) for flow sizing -- the parent chooses only the number of columns for this widget () for fixed sizing -- this widget is a fixed size which can't be adjusted by the parent :type size: widget size :param focus: set to ``True`` if this widget or one of its children is in focus :type focus: bool :returns: A :class:`Canvas` subclass instance containing the rendered content of this widget :class:`Text` widgets return a :class:`TextCanvas` (arbitrary text and display attributes), :class:`SolidFill` widgets return a :class:`SolidCanvas` (a single character repeated across the whole surface) and container widgets return a :class:`CompositeCanvas` (one or more other canvases arranged arbitrarily). If *focus* is ``False``, the returned canvas may not have a cursor position set. There is some metaclass magic defined in the :class:`Widget` metaclass :class:`WidgetMeta` that causes the result of this method to be cached by :class:`CanvasCache`. Later calls will automatically look up the value in the cache first. As a small optimization the class variable :attr:`ignore_focus` may be defined and set to ``True`` if this widget renders the same canvas regardless of the value of the *focus* parameter. Any time the content of a widget changes it should call :meth:`_invalidate` to remove any cached canvases, or the widget may render the cached canvas instead of creating a new one. """ raise NotImplementedError class FlowWidget(Widget): """ Deprecated. Inherit from Widget and add: _sizing = frozenset(['flow']) at the top of your class definition instead. Base class of widgets that determine their rows from the number of columns available. """ _sizing = frozenset([Sizing.FLOW]) def __init__(self, *args, **kwargs): warnings.warn( """ FlowWidget is deprecated. Inherit from Widget and add: _sizing = frozenset(['flow']) at the top of your class definition instead.""", DeprecationWarning, stacklevel=3, ) super().__init__() def rows(self, size: tuple[int], focus: bool = False) -> int: """ All flow widgets must implement this function. """ raise NotImplementedError() def render(self, size: tuple[int], focus: bool = False) -> Canvas: # type: ignore[override] """ All widgets must implement this function. """ raise NotImplementedError() class BoxWidget(Widget): """ Deprecated. Inherit from Widget and add: _sizing = frozenset(['box']) _selectable = True at the top of your class definition instead. Base class of width and height constrained widgets such as the top level widget attached to the display object """ _selectable = True _sizing = frozenset([Sizing.BOX]) def __init__(self, *args, **kwargs): warnings.warn( """ BoxWidget is deprecated. Inherit from Widget and add: _sizing = frozenset(['box']) _selectable = True at the top of your class definition instead.""", DeprecationWarning, stacklevel=3, ) super().__init__() def render(self, size: tuple[int, int], focus: bool = False) -> Canvas: # type: ignore[override] """ All widgets must implement this function. """ raise NotImplementedError() def fixed_size(size: tuple[()]) -> None: """ raise ValueError if size != (). Used by FixedWidgets to test size parameter. """ if size != (): raise ValueError(f"FixedWidget takes only () for size.passed: {size!r}") class FixedWidget(Widget): """ Deprecated. Inherit from Widget and add: _sizing = frozenset(['fixed']) at the top of your class definition instead. Base class of widgets that know their width and height and cannot be resized """ _sizing = frozenset([Sizing.FIXED]) def __init__(self, *args, **kwargs): warnings.warn( """ FixedWidget is deprecated. Inherit from Widget and add: _sizing = frozenset(['fixed']) at the top of your class definition instead.""", DeprecationWarning, stacklevel=3, ) super().__init__() def render(self, size: tuple[()], focus: bool = False) -> Canvas: # type: ignore[override] """ All widgets must implement this function. """ raise NotImplementedError() def pack(self, size: tuple[()] = (), focus: bool = False) -> tuple[int, int]: # type: ignore[override] """ All fixed widgets must implement this function. """ raise NotImplementedError() def delegate_to_widget_mixin(attribute_name: str) -> type[Widget]: """ Return a mixin class that delegates all standard widget methods to an attribute given by attribute_name. This mixin is designed to be used as a superclass of another widget. """ # FIXME: this is so common, let's add proper support for it # when layout and rendering are separated get_delegate = attrgetter(attribute_name) class DelegateToWidgetMixin(Widget): no_cache: typing.ClassVar[list[str]] = ["rows"] # crufty metaclass work-around def render(self, size, focus: bool = False) -> CompositeCanvas: canv = get_delegate(self).render(size, focus=focus) return CompositeCanvas(canv) @property def selectable(self) -> Callable[[], bool]: return get_delegate(self).selectable @property def get_cursor_coords(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int]], tuple[int, int] | None]: # TODO(Aleksei): Get rid of property usage after getting rid of "if getattr" return get_delegate(self).get_cursor_coords @property def get_pref_col(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int]], int | None]: # TODO(Aleksei): Get rid of property usage after getting rid of "if getattr" return get_delegate(self).get_pref_col def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None: return get_delegate(self).keypress(size, key) @property def move_cursor_to_coords(self) -> Callable[[[tuple[()] | tuple[int] | tuple[int, int], int, int]], bool]: # TODO(Aleksei): Get rid of property usage after getting rid of "if getattr" return get_delegate(self).move_cursor_to_coords @property def rows(self) -> Callable[[tuple[int], bool], int]: return get_delegate(self).rows @property def mouse_event( self, ) -> Callable[[tuple[()] | tuple[int] | tuple[int, int], str, int, int, int, bool], bool | None]: # TODO(Aleksei): Get rid of property usage after getting rid of "if getattr" return get_delegate(self).mouse_event @property def sizing(self) -> Callable[[], frozenset[Sizing]]: return get_delegate(self).sizing @property def pack(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int], bool], tuple[int, int]]: return get_delegate(self).pack return DelegateToWidgetMixin class WidgetWrapError(Exception): pass class WidgetWrap(delegate_to_widget_mixin("_wrapped_widget"), typing.Generic[WrappedWidget]): def __init__(self, w: WrappedWidget) -> None: """ w -- widget to wrap, stored as self._w This object will pass the functions defined in Widget interface definition to self._w. The purpose of this widget is to provide a base class for widgets that compose other widgets for their display and behaviour. The details of that composition should not affect users of the subclass. The subclass may decide to expose some of the wrapped widgets by behaving like a ContainerWidget or WidgetDecoration, or it may hide them from outside access. """ super().__init__() if not isinstance(w, Widget): obj_class_path = f"{w.__class__.__module__}.{w.__class__.__name__}" warnings.warn( f"{obj_class_path} is not subclass of Widget", DeprecationWarning, stacklevel=2, ) self._wrapped_widget = w @property def _w(self) -> WrappedWidget: return self._wrapped_widget @_w.setter def _w(self, new_widget: WrappedWidget) -> None: """ Change the wrapped widget. This is meant to be called only by subclasses. >>> size = (10,) >>> ww = WidgetWrap(Edit("hello? ","hi")) >>> ww.render(size).text # ... = b in Python 3 [...'hello? hi '] >>> ww.selectable() True >>> ww._w = Text("goodbye") # calls _set_w() >>> ww.render(size).text [...'goodbye '] >>> ww.selectable() False """ self._wrapped_widget = new_widget self._invalidate() def _set_w(self, w: WrappedWidget) -> None: """ Change the wrapped widget. This is meant to be called only by subclasses. >>> from urwid import Edit, Text >>> size = (10,) >>> ww = WidgetWrap(Edit("hello? ","hi")) >>> ww.render(size).text # ... = b in Python 3 [...'hello? hi '] >>> ww.selectable() True >>> ww._w = Text("goodbye") # calls _set_w() >>> ww.render(size).text [...'goodbye '] >>> ww.selectable() False """ warnings.warn( "_set_w is deprecated. Please use 'WidgetWrap._w' property directly", DeprecationWarning, stacklevel=2, ) self._wrapped_widget = w self._invalidate() def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
29,557
Python
.py
652
36.68865
119
0.626811
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,256
constants.py
urwid_urwid/urwid/widget/constants.py
from __future__ import annotations import dataclasses import enum import typing if typing.TYPE_CHECKING: from typing_extensions import Literal # define some names for these constants to avoid misspellings in the source # and to document the constant strings we are using class Sizing(str, enum.Enum): """Widget sizing methods.""" FLOW = "flow" BOX = "box" FIXED = "fixed" class Align(str, enum.Enum): """Text alignment modes""" LEFT = "left" RIGHT = "right" CENTER = "center" class VAlign(str, enum.Enum): """Filler alignment""" TOP = "top" MIDDLE = "middle" BOTTOM = "bottom" class WrapMode(str, enum.Enum): """Text wrapping modes""" SPACE = "space" ANY = "any" CLIP = "clip" ELLIPSIS = "ellipsis" class WHSettings(str, enum.Enum): """Width and Height settings""" PACK = "pack" GIVEN = "given" RELATIVE = "relative" WEIGHT = "weight" CLIP = "clip" # Used as "given" for widgets with fixed width (with clipping part of it) FLOW = "flow" # Used as pack for flow widgets RELATIVE_100 = (WHSettings.RELATIVE, 100) @typing.overload def normalize_align( align: Literal["left", "center", "right"] | Align, err: type[BaseException], ) -> tuple[Align, None]: ... @typing.overload def normalize_align( align: tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... def normalize_align( align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[Align, None] | tuple[Literal[WHSettings.RELATIVE], int]: """ Split align into (align_type, align_amount). Raise exception err if align doesn't match a valid alignment. """ if align in {Align.LEFT, Align.CENTER, Align.RIGHT}: return (Align(align), None) if isinstance(align, tuple) and len(align) == 2 and align[0] == WHSettings.RELATIVE: _align_type, align_amount = align return (WHSettings.RELATIVE, align_amount) raise err( f"align value {align!r} is not one of 'left', 'center', 'right', ('relative', percentage 0=left 100=right)" ) @typing.overload def simplify_align( align_type: Literal["relative", WHSettings.RELATIVE], align_amount: int, ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def simplify_align( align_type: Literal["relative", WHSettings.RELATIVE], align_amount: None, ) -> typing.NoReturn: ... @typing.overload def simplify_align( align_type: Literal["left", "center", "right"] | Align, align_amount: int | None, ) -> Align: ... def simplify_align( align_type: Literal["left", "center", "right", "relative", WHSettings.RELATIVE] | Align, align_amount: int | None, ) -> Align | tuple[Literal[WHSettings.RELATIVE], int]: """ Recombine (align_type, align_amount) into an align value. Inverse of normalize_align. """ if align_type == WHSettings.RELATIVE: if not isinstance(align_amount, int): raise TypeError(align_amount) return (WHSettings.RELATIVE, align_amount) return Align(align_type) @typing.overload def normalize_valign( valign: Literal["top", "middle", "bottom"] | VAlign, err: type[BaseException], ) -> tuple[VAlign, None]: ... @typing.overload def normalize_valign( valign: tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... def normalize_valign( valign: Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[VAlign, None] | tuple[Literal[WHSettings.RELATIVE], int]: """ Split align into (valign_type, valign_amount). Raise exception err if align doesn't match a valid alignment. """ if valign in {VAlign.TOP, VAlign.MIDDLE, VAlign.BOTTOM}: return (VAlign(valign), None) if isinstance(valign, tuple) and len(valign) == 2 and valign[0] == WHSettings.RELATIVE: _valign_type, valign_amount = valign return (WHSettings.RELATIVE, valign_amount) raise err( f"valign value {valign!r} is not one of 'top', 'middle', 'bottom', ('relative', percentage 0=left 100=right)" ) @typing.overload def simplify_valign( valign_type: Literal["top", "middle", "bottom"] | VAlign, valign_amount: int | None, ) -> VAlign: ... @typing.overload def simplify_valign( valign_type: Literal["relative", WHSettings.RELATIVE], valign_amount: int, ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def simplify_valign( valign_type: Literal["relative", WHSettings.RELATIVE], valign_amount: None, ) -> typing.NoReturn: ... def simplify_valign( valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign, valign_amount: int | None, ) -> VAlign | tuple[Literal[WHSettings.RELATIVE], int]: """ Recombine (valign_type, valign_amount) into an valign value. Inverse of normalize_valign. """ if valign_type == WHSettings.RELATIVE: if not isinstance(valign_amount, int): raise TypeError(valign_amount) return (WHSettings.RELATIVE, valign_amount) return VAlign(valign_type) @typing.overload def normalize_width( width: Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK], err: type[BaseException], ) -> tuple[Literal[WHSettings.CLIP, WHSettings.PACK], None]: ... @typing.overload def normalize_width( width: int, err: type[BaseException], ) -> tuple[Literal[WHSettings.GIVEN], int]: ... @typing.overload def normalize_width( width: tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def normalize_width( width: tuple[Literal["weight", WHSettings.WEIGHT], int | float], err: type[BaseException], ) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ... def normalize_width( width: ( Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | tuple[Literal["weight", WHSettings.WEIGHT], int | float] ), err: type[BaseException], ) -> ( tuple[Literal[WHSettings.CLIP, WHSettings.PACK], None] | tuple[Literal[WHSettings.GIVEN, WHSettings.RELATIVE], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): """ Split width into (width_type, width_amount). Raise exception err if width doesn't match a valid alignment. """ if width in {WHSettings.CLIP, WHSettings.PACK}: return (WHSettings(width), None) if isinstance(width, int): return (WHSettings.GIVEN, width) if isinstance(width, tuple) and len(width) == 2 and width[0] in {WHSettings.RELATIVE, WHSettings.WEIGHT}: width_type, width_amount = width return (WHSettings(width_type), width_amount) raise err( f"width value {width!r} is not one of" f"fixed number of columns, 'pack', ('relative', percentage of total width), 'clip'" ) @typing.overload def simplify_width( width_type: Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK], width_amount: int | None, ) -> Literal[WHSettings.CLIP, WHSettings.PACK]: ... @typing.overload def simplify_width( width_type: Literal["given", WHSettings.GIVEN], width_amount: int, ) -> int: ... @typing.overload def simplify_width( width_type: Literal["relative", WHSettings.RELATIVE], width_amount: int, ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def simplify_width( width_type: Literal["weight", WHSettings.WEIGHT], width_amount: int | float, # noqa: PYI041 # provide explicit for IDEs ) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ... @typing.overload def simplify_width( width_type: Literal["given", "relative", "weight", WHSettings.GIVEN, WHSettings.RELATIVE, WHSettings.WEIGHT], width_amount: None, ) -> typing.NoReturn: ... def simplify_width( width_type: Literal["clip", "pack", "given", "relative", "weight"] | WHSettings, width_amount: int | float | None, # noqa: PYI041 # provide explicit for IDEs ) -> ( Literal[WHSettings.CLIP, WHSettings.PACK] | int | tuple[Literal[WHSettings.RELATIVE], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): """ Recombine (width_type, width_amount) into an width value. Inverse of normalize_width. """ if width_type in {WHSettings.CLIP, WHSettings.PACK}: return WHSettings(width_type) if not isinstance(width_amount, int): raise TypeError(width_amount) if width_type == WHSettings.GIVEN: return width_amount return (WHSettings(width_type), width_amount) @typing.overload def normalize_height( height: int, err: type[BaseException], ) -> tuple[Literal[WHSettings.GIVEN], int]: ... @typing.overload def normalize_height( height: Literal["flow", "pack", Sizing.FLOW, WHSettings.PACK], err: type[BaseException], ) -> tuple[Literal[Sizing.FLOW, WHSettings.PACK], None]: ... @typing.overload def normalize_height( height: tuple[Literal["relative", WHSettings.RELATIVE], int], err: type[BaseException], ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def normalize_height( height: tuple[Literal["weight", WHSettings.WEIGHT], int | float], err: type[BaseException], ) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ... def normalize_height( height: ( int | Literal["flow", "pack", Sizing.FLOW, WHSettings.PACK] | tuple[Literal["relative", WHSettings.RELATIVE], int] | tuple[Literal["weight", WHSettings.WEIGHT], int | float] ), err: type[BaseException], ) -> ( tuple[Literal[Sizing.FLOW, WHSettings.PACK], None] | tuple[Literal[WHSettings.RELATIVE, WHSettings.GIVEN], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): """ Split height into (height_type, height_amount). Raise exception err if height isn't valid. """ if height == Sizing.FLOW: return (Sizing.FLOW, None) if height == WHSettings.PACK: return (WHSettings.PACK, None) if isinstance(height, tuple) and len(height) == 2 and height[0] in {WHSettings.RELATIVE, WHSettings.WEIGHT}: return (WHSettings(height[0]), height[1]) if isinstance(height, int): return (WHSettings.GIVEN, height) raise err( f"height value {height!r} is not one of " f"fixed number of columns, 'pack', ('relative', percentage of total height)" ) @typing.overload def simplify_height( height_type: Literal["flow", "pack", WHSettings.FLOW, WHSettings.PACK], height_amount: int | None, ) -> Literal[WHSettings.FLOW, WHSettings.PACK]: ... @typing.overload def simplify_height( height_type: Literal["given", WHSettings.GIVEN], height_amount: int, ) -> int: ... @typing.overload def simplify_height( height_type: Literal["relative", WHSettings.RELATIVE], height_amount: int | None, ) -> tuple[Literal[WHSettings.RELATIVE], int]: ... @typing.overload def simplify_height( height_type: Literal["weight", WHSettings.WEIGHT], height_amount: int | float | None, # noqa: PYI041 # provide explicit for IDEs ) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ... @typing.overload def simplify_height( height_type: Literal["relative", "given", "weight", WHSettings.RELATIVE, WHSettings.GIVEN, WHSettings.WEIGHT], height_amount: None, ) -> typing.NoReturn: ... def simplify_height( height_type: Literal[ "flow", "pack", "relative", "given", "weight", WHSettings.FLOW, WHSettings.PACK, WHSettings.RELATIVE, WHSettings.GIVEN, WHSettings.WEIGHT, ], height_amount: int | float | None, # noqa: PYI041 # provide explicit for IDEs ) -> ( int | Literal[WHSettings.FLOW, WHSettings.PACK] | tuple[Literal[WHSettings.RELATIVE], int] | tuple[Literal[WHSettings.WEIGHT], int | float] ): """ Recombine (height_type, height_amount) into a height value. Inverse of normalize_height. """ if height_type in {WHSettings.FLOW, WHSettings.PACK}: return WHSettings(height_type) if not isinstance(height_amount, int): raise TypeError(height_amount) if height_type == WHSettings.GIVEN: return height_amount return (WHSettings(height_type), height_amount) @dataclasses.dataclass(frozen=True) class _BoxSymbols: """Box symbols for drawing.""" HORIZONTAL: str VERTICAL: str TOP_LEFT: str TOP_RIGHT: str BOTTOM_LEFT: str BOTTOM_RIGHT: str # Joints for tables making LEFT_T: str RIGHT_T: str TOP_T: str BOTTOM_T: str CROSS: str @dataclasses.dataclass(frozen=True) class _BoxSymbolsWithDashes(_BoxSymbols): """Box symbols for drawing. Extra dashes symbols. """ HORIZONTAL_4_DASHES: str HORIZONTAL_3_DASHES: str HORIZONTAL_2_DASHES: str VERTICAL_2_DASH: str VERTICAL_3_DASH: str VERTICAL_4_DASH: str @dataclasses.dataclass(frozen=True) class _LightBoxSymbols(_BoxSymbolsWithDashes): """Box symbols for drawing. The Thin version includes extra symbols. Symbols are ordered as in Unicode except dashes. """ TOP_LEFT_ROUNDED: str TOP_RIGHT_ROUNDED: str BOTTOM_LEFT_ROUNDED: str BOTTOM_RIGHT_ROUNDED: str class _BoxSymbolsCollection(typing.NamedTuple): """Standard Unicode box symbols for basic tables drawing. .. note:: Transitions are not included: depends on line types, different kinds of transitions are available. Please check Unicode table for transitions symbols if required. """ # fmt: off LIGHT: _LightBoxSymbols = _LightBoxSymbols( "─", "│", "┌", "┐", "└", "┘", "├", "┤", "┬", "┴", "┼", "┈", "┄", "╌", "╎", "┆", "┊", "╭", "╮", "╰", "╯" ) HEAVY: _BoxSymbolsWithDashes = _BoxSymbolsWithDashes( "━", "┃", "┏", "┓", "┗", "┛", "┣", "┫", "┳", "┻", "╋", "┉", "┅", "╍", "╏", "┇", "┋" ) DOUBLE: _BoxSymbols = _BoxSymbols( "═", "║", "╔", "╗", "╚", "╝", "╠", "╣", "╦", "╩", "╬" ) BOX_SYMBOLS = _BoxSymbolsCollection() class BAR_SYMBOLS(str, enum.Enum): """Standard Unicode bar symbols excluding empty space. Start from space (0), then 1/8 till full block (1/1). Typically used only 8 from this symbol collection depends on use-case: * empty - 7/8 and styles for BG different on both sides (like standard `ProgressBar` and `BarGraph`) * 1/8 - full block and single style for BG on the right side """ # fmt: off HORISONTAL = " ▏▎▍▌▋▊▉█" VERTICAL = " ▁▂▃▄▅▆▇█" class _SHADE_SYMBOLS(typing.NamedTuple): """Standard shade symbols excluding empty space.""" # fmt: off FULL_BLOCK: str = "█" DARK_SHADE: str = "▓" MEDIUM_SHADE: str = "▒" LITE_SHADE: str = "░" SHADE_SYMBOLS = _SHADE_SYMBOLS()
15,313
Python
.py
415
31.913253
117
0.670383
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,257
treetools.py
urwid_urwid/urwid/widget/treetools.py
# Generic TreeWidget/TreeWalker class # Copyright (c) 2010 Rob Lanphier # Copyright (C) 2004-2010 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Urwid tree view Features: - custom selectable widgets for trees - custom list walker for displaying widgets in a tree fashion """ from __future__ import annotations import typing from .columns import Columns from .constants import WHSettings from .listbox import ListBox, ListWalker from .padding import Padding from .text import Text from .widget import WidgetWrap from .wimp import SelectableIcon if typing.TYPE_CHECKING: from collections.abc import Hashable, Sequence __all__ = ("ParentNode", "TreeListBox", "TreeNode", "TreeWalker", "TreeWidget", "TreeWidgetError") class TreeWidgetError(RuntimeError): pass class TreeWidget(WidgetWrap[Padding[typing.Union[Text, Columns]]]): """A widget representing something in a nested tree display.""" indent_cols = 3 unexpanded_icon = SelectableIcon("+", 0) expanded_icon = SelectableIcon("-", 0) def __init__(self, node: TreeNode) -> None: self._node = node self._innerwidget: Text | None = None self.is_leaf = not hasattr(node, "get_first_child") self.expanded = True widget = self.get_indented_widget() super().__init__(widget) def selectable(self) -> bool: """ Allow selection of non-leaf nodes so children may be (un)expanded """ return not self.is_leaf def get_indented_widget(self) -> Padding[Text | Columns]: widget = self.get_inner_widget() if not self.is_leaf: widget = Columns( [(1, [self.unexpanded_icon, self.expanded_icon][self.expanded]), widget], dividechars=1, ) indent_cols = self.get_indent_cols() return Padding(widget, width=(WHSettings.RELATIVE, 100), left=indent_cols) def update_expanded_icon(self) -> None: """Update display widget text for parent widgets""" # icon is first element in columns indented widget icon = [self.unexpanded_icon, self.expanded_icon][self.expanded] self._w.base_widget.contents[0] = (icon, (WHSettings.GIVEN, 1, False)) def get_indent_cols(self) -> int: return self.indent_cols * self.get_node().get_depth() def get_inner_widget(self) -> Text: if self._innerwidget is None: self._innerwidget = self.load_inner_widget() return self._innerwidget def load_inner_widget(self) -> Text: return Text(self.get_display_text()) def get_node(self) -> TreeNode: return self._node def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]: return f"{self.get_node().get_key()}: {self.get_node().get_value()!s}" def next_inorder(self) -> TreeWidget | None: """Return the next TreeWidget depth first from this one.""" # first check if there's a child widget first_child = self.first_child() if first_child is not None: return first_child # now we need to hunt for the next sibling this_node = self.get_node() next_node = this_node.next_sibling() depth = this_node.get_depth() while next_node is None and depth > 0: # keep going up the tree until we find an ancestor next sibling this_node = this_node.get_parent() next_node = this_node.next_sibling() depth -= 1 if depth != this_node.get_depth(): raise ValueError(depth) if next_node is None: # we're at the end of the tree return None return next_node.get_widget() def prev_inorder(self) -> TreeWidget | None: """Return the previous TreeWidget depth first from this one.""" this_node = self._node prev_node = this_node.prev_sibling() if prev_node is not None: # we need to find the last child of the previous widget if its # expanded prev_widget = prev_node.get_widget() last_child = prev_widget.last_child() if last_child is None: return prev_widget return last_child # need to hunt for the parent depth = this_node.get_depth() if prev_node is None and depth == 0: return None if prev_node is None: prev_node = this_node.get_parent() return prev_node.get_widget() def keypress( self, size: tuple[int] | tuple[()], key: str, ) -> str | None: """Handle expand & collapse requests (non-leaf nodes)""" if self.is_leaf: return key if key in {"+", "right"}: self.expanded = True self.update_expanded_icon() return None if key == "-": self.expanded = False self.update_expanded_icon() return None if self._w.selectable(): return super().keypress(size, key) return key def mouse_event( self, size: tuple[int] | tuple[()], event: str, button: int, col: int, row: int, focus: bool, ) -> bool: if self.is_leaf or event != "mouse press" or button != 1: return False if row == 0 and col == self.get_indent_cols(): self.expanded = not self.expanded self.update_expanded_icon() return True return False def first_child(self) -> TreeWidget | None: """Return first child if expanded.""" if self.is_leaf or not self.expanded: return None if self._node.has_children(): first_node = self._node.get_first_child() return first_node.get_widget() return None def last_child(self) -> TreeWidget | None: """Return last child if expanded.""" if self.is_leaf or not self.expanded: return None if self._node.has_children(): last_child = self._node.get_last_child().get_widget() else: return None # recursively search down for the last descendant last_descendant = last_child.last_child() if last_descendant is None: return last_child return last_descendant class TreeNode: """ Store tree contents and cache TreeWidget objects. A TreeNode consists of the following elements: * key: accessor token for parent nodes * value: subclass-specific data * parent: a TreeNode which contains a pointer back to this object * widget: The widget used to render the object """ def __init__( self, value: typing.Any, parent: ParentNode | None = None, key: Hashable | None = None, depth: int | None = None, ) -> None: self._key = key self._parent = parent self._value = value self._depth = depth self._widget: TreeWidget | None = None def get_widget(self, reload: bool = False) -> TreeWidget: """Return the widget for this node.""" if self._widget is None or reload: self._widget = self.load_widget() return self._widget def load_widget(self) -> TreeWidget: return TreeWidget(self) def get_depth(self) -> int: if self._depth is self._parent is None: self._depth = 0 elif self._depth is None: self._depth = self._parent.get_depth() + 1 return self._depth def get_index(self) -> int | None: if self.get_depth() == 0: return None return self.get_parent().get_child_index(self.get_key()) def get_key(self) -> Hashable | None: return self._key def set_key(self, key: Hashable | None) -> None: self._key = key def change_key(self, key: Hashable | None) -> None: self.get_parent().change_child_key(self._key, key) def get_parent(self) -> ParentNode: if self._parent is None and self.get_depth() > 0: self._parent = self.load_parent() return self._parent def load_parent(self): """Provide TreeNode with a parent for the current node. This function is only required if the tree was instantiated from a child node (virtual function)""" raise TreeWidgetError("virtual function. Implement in subclass") def get_value(self): return self._value def is_root(self) -> bool: return self.get_depth() == 0 def next_sibling(self) -> TreeNode | None: if self.get_depth() > 0: return self.get_parent().next_child(self.get_key()) return None def prev_sibling(self) -> TreeNode | None: if self.get_depth() > 0: return self.get_parent().prev_child(self.get_key()) return None def get_root(self) -> ParentNode: root = self while root.get_parent() is not None: root = root.get_parent() return root class ParentNode(TreeNode): """Maintain sort order for TreeNodes.""" def __init__( self, value: typing.Any, parent: ParentNode | None = None, key: Hashable = None, depth: int | None = None, ) -> None: super().__init__(value, parent=parent, key=key, depth=depth) self._child_keys: Sequence[Hashable] | None = None self._children: dict[Hashable, TreeNode] = {} def get_child_keys(self, reload: bool = False) -> Sequence[Hashable]: """Return a possibly ordered list of child keys""" if self._child_keys is None or reload: self._child_keys = self.load_child_keys() return self._child_keys def load_child_keys(self) -> Sequence[Hashable]: """Provide ParentNode with an ordered list of child keys (virtual function)""" raise TreeWidgetError("virtual function. Implement in subclass") def get_child_widget(self, key) -> TreeWidget: """Return the widget for a given key. Create if necessary.""" return self.get_child_node(key).get_widget() def get_child_node(self, key, reload: bool = False) -> TreeNode: """Return the child node for a given key. Create if necessary.""" if key not in self._children or reload: self._children[key] = self.load_child_node(key) return self._children[key] def load_child_node(self, key: Hashable) -> TreeNode: """Load the child node for a given key (virtual function)""" raise TreeWidgetError("virtual function. Implement in subclass") def set_child_node(self, key: Hashable, node: TreeNode) -> None: """Set the child node for a given key. Useful for bottom-up, lazy population of a tree. """ self._children[key] = node def change_child_key(self, oldkey: Hashable, newkey: Hashable) -> None: if newkey in self._children: raise TreeWidgetError(f"{newkey} is already in use") self._children[newkey] = self._children.pop(oldkey) self._children[newkey].set_key(newkey) def get_child_index(self, key: Hashable) -> int: try: return self.get_child_keys().index(key) except ValueError as exc: raise TreeWidgetError( f"Can't find key {key} in ParentNode {self.get_key()}\nParentNode items: {self.get_child_keys()!s}" ).with_traceback(exc.__traceback__) from exc def next_child(self, key: Hashable) -> TreeNode | None: """Return the next child node in index order from the given key.""" index = self.get_child_index(key) # the given node may have just been deleted if index is None: return None index += 1 child_keys = self.get_child_keys() if index < len(child_keys): # get the next item at same level return self.get_child_node(child_keys[index]) return None def prev_child(self, key: Hashable) -> TreeNode | None: """Return the previous child node in index order from the given key.""" index = self.get_child_index(key) if index is None: return None child_keys = self.get_child_keys() index -= 1 if index >= 0: # get the previous item at same level return self.get_child_node(child_keys[index]) return None def get_first_child(self) -> TreeNode: """Return the first TreeNode in the directory.""" child_keys = self.get_child_keys() return self.get_child_node(child_keys[0]) def get_last_child(self) -> TreeNode: """Return the last TreeNode in the directory.""" child_keys = self.get_child_keys() return self.get_child_node(child_keys[-1]) def has_children(self) -> bool: """Does this node have any children?""" return len(self.get_child_keys()) > 0 class TreeWalker(ListWalker): """ListWalker-compatible class for displaying TreeWidgets positions are TreeNodes.""" def __init__(self, start_from) -> None: """start_from: TreeNode with the initial focus.""" self.focus = start_from def get_focus(self): widget = self.focus.get_widget() return widget, self.focus def set_focus(self, focus) -> None: self.focus = focus self._modified() # pylint: disable=arguments-renamed # its bad, but we should not change API def get_next(self, start_from) -> tuple[TreeWidget, TreeNode] | tuple[None, None]: target = start_from.get_widget().next_inorder() if target is None: return None, None return target, target.get_node() def get_prev(self, start_from) -> tuple[TreeWidget, TreeNode] | tuple[None, None]: target = start_from.get_widget().prev_inorder() if target is None: return None, None return target, target.get_node() # pylint: enable=arguments-renamed class TreeListBox(ListBox): """A ListBox with special handling for navigation and collapsing of TreeWidgets""" def keypress( self, size: tuple[int, int], # type: ignore[override] key: str, ) -> str | None: key: str | None = super().keypress(size, key) return self.unhandled_input(size, key) def unhandled_input(self, size: tuple[int, int], data: str) -> str | None: """Handle macro-navigation keys""" if data == "left": self.move_focus_to_parent(size) return None if data == "-": self.collapse_focus_parent(size) return None return data def collapse_focus_parent(self, size: tuple[int, int]) -> None: """Collapse parent directory.""" _widget, pos = self.body.get_focus() self.move_focus_to_parent(size) _pwidget, ppos = self.body.get_focus() if pos != ppos: self.keypress(size, "-") def move_focus_to_parent(self, size: tuple[int, int]) -> None: """Move focus to parent of widget in focus.""" _widget, pos = self.body.get_focus() parentpos = pos.get_parent() if parentpos is None: return middle, top, _bottom = self.calculate_visible(size) row_offset, _focus_widget, _focus_pos, _focus_rows, _cursor = middle # pylint: disable=unpacking-non-sequence _trim_top, fill_above = top # pylint: disable=unpacking-non-sequence for _widget, pos, rows in fill_above: row_offset -= rows if pos == parentpos: self.change_focus(size, pos, row_offset) return self.change_focus(size, pos.get_parent()) def _keypress_max_left(self, size: tuple[int, int]) -> None: self.focus_home(size) def _keypress_max_right(self, size: tuple[int, int]) -> None: self.focus_end(size) def focus_home(self, size: tuple[int, int]) -> None: """Move focus to very top.""" _widget, pos = self.body.get_focus() rootnode = pos.get_root() self.change_focus(size, rootnode) def focus_end(self, size: tuple[int, int]) -> None: """Move focus to far bottom.""" maxrow, _maxcol = size _widget, pos = self.body.get_focus() lastwidget = pos.get_root().get_widget().last_child() if lastwidget: lastnode = lastwidget.get_node() self.change_focus(size, lastnode, maxrow - 1)
17,387
Python
.py
412
33.716019
118
0.615307
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,258
attr_wrap.py
urwid_urwid/urwid/widget/attr_wrap.py
from __future__ import annotations import typing import warnings from .attr_map import AttrMap if typing.TYPE_CHECKING: from collections.abc import Hashable from .constants import Sizing from .widget import Widget class AttrWrap(AttrMap): def __init__(self, w: Widget, attr, focus_attr=None): """ w -- widget to wrap (stored as self.original_widget) attr -- attribute to apply to w focus_attr -- attribute to apply when in focus, if None use attr This widget is a special case of the new AttrMap widget, and it will pass all function calls and variable references to the wrapped widget. This class is maintained for backwards compatibility only, new code should use AttrMap instead. >>> from urwid import Divider, Edit, Text >>> AttrWrap(Divider(u"!"), 'bright') <AttrWrap flow widget <Divider flow widget '!'> attr='bright'> >>> AttrWrap(Edit(), 'notfocus', 'focus') <AttrWrap selectable flow widget <Edit selectable flow widget '' edit_pos=0> attr='notfocus' focus_attr='focus'> >>> size = (5,) >>> aw = AttrWrap(Text(u"hi"), 'greeting', 'fgreet') >>> next(aw.render(size, focus=False).content()) [('greeting', None, ...'hi ')] >>> next(aw.render(size, focus=True).content()) [('fgreet', None, ...'hi ')] """ warnings.warn( "AttrWrap is maintained for backwards compatibility only, new code should use AttrMap instead.", PendingDeprecationWarning, stacklevel=2, ) super().__init__(w, attr, focus_attr) def _repr_attrs(self) -> dict[str, typing.Any]: # only include the focus_attr when it takes effect (not None) d = {**super()._repr_attrs(), "attr": self.attr} del d["attr_map"] if "focus_map" in d: del d["focus_map"] if self.focus_attr is not None: d["focus_attr"] = self.focus_attr return d @property def w(self) -> Widget: """backwards compatibility, widget used to be stored as w""" warnings.warn( "backwards compatibility, widget used to be stored as original_widget", PendingDeprecationWarning, stacklevel=2, ) return self.original_widget @w.setter def w(self, new_widget: Widget) -> None: warnings.warn( "backwards compatibility, widget used to be stored as original_widget", PendingDeprecationWarning, stacklevel=2, ) self.original_widget = new_widget def get_w(self): warnings.warn( "backwards compatibility, widget used to be stored as original_widget", DeprecationWarning, stacklevel=2, ) return self.original_widget def set_w(self, new_widget: Widget) -> None: warnings.warn( "backwards compatibility, widget used to be stored as original_widget", DeprecationWarning, stacklevel=2, ) self.original_widget = new_widget def get_attr(self) -> Hashable: return self.attr_map[None] def set_attr(self, attr: Hashable) -> None: """ Set the attribute to apply to the wrapped widget >> w = AttrWrap(Divider("-"), None) >> w.set_attr('new_attr') >> w <AttrWrap flow widget <Divider flow widget '-'> attr='new_attr'> """ self.set_attr_map({None: attr}) attr = property(get_attr, set_attr) def get_focus_attr(self) -> Hashable | None: focus_map = self.focus_map if focus_map: return focus_map[None] return None def set_focus_attr(self, focus_attr: Hashable) -> None: """ Set the attribute to apply to the wapped widget when it is in focus If None this widget will use the attr instead (no change when in focus). >> w = AttrWrap(Divider("-"), 'old') >> w.set_focus_attr('new_attr') >> w <AttrWrap flow widget <Divider flow widget '-'> attr='old' focus_attr='new_attr'> >> w.set_focus_attr(None) >> w <AttrWrap flow widget <Divider flow widget '-'> attr='old'> """ self.set_focus_map({None: focus_attr}) focus_attr = property(get_focus_attr, set_focus_attr) def __getattr__(self, name: str): """ Call getattr on wrapped widget. This has been the longstanding behaviour of AttrWrap, but is discouraged. New code should be using AttrMap and .base_widget or .original_widget instead. """ return getattr(self._original_widget, name) def sizing(self) -> frozenset[Sizing]: return self._original_widget.sizing()
4,830
Python
.py
118
32.169492
120
0.606442
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,259
line_box.py
urwid_urwid/urwid/widget/line_box.py
from __future__ import annotations import typing from .columns import Columns from .constants import BOX_SYMBOLS, Align, WHSettings from .divider import Divider from .pile import Pile from .solid_fill import SolidFill from .text import Text from .widget_decoration import WidgetDecoration, delegate_to_widget_mixin if typing.TYPE_CHECKING: from typing_extensions import Literal from .widget import Widget WrappedWidget = typing.TypeVar("WrappedWidget") class LineBox(WidgetDecoration[WrappedWidget], delegate_to_widget_mixin("_wrapped_widget")): Symbols = BOX_SYMBOLS def __init__( self, original_widget: WrappedWidget, title: str = "", title_align: Literal["left", "center", "right"] | Align = Align.CENTER, title_attr=None, tlcorner: str = BOX_SYMBOLS.LIGHT.TOP_LEFT, tline: str = BOX_SYMBOLS.LIGHT.HORIZONTAL, lline: str = BOX_SYMBOLS.LIGHT.VERTICAL, trcorner: str = BOX_SYMBOLS.LIGHT.TOP_RIGHT, blcorner: str = BOX_SYMBOLS.LIGHT.BOTTOM_LEFT, rline: str = BOX_SYMBOLS.LIGHT.VERTICAL, bline: str = BOX_SYMBOLS.LIGHT.HORIZONTAL, brcorner: str = BOX_SYMBOLS.LIGHT.BOTTOM_RIGHT, ) -> None: """ Draw a line around original_widget. Use 'title' to set an initial title text with will be centered on top of the box. Use `title_attr` to apply a specific attribute to the title text. Use `title_align` to align the title to the 'left', 'right', or 'center'. The default is 'center'. You can also override the widgets used for the lines/corners: tline: top line bline: bottom line lline: left line rline: right line tlcorner: top left corner trcorner: top right corner blcorner: bottom left corner brcorner: bottom right corner If empty string is specified for one of the lines/corners, then no character will be output there. If no top/bottom/left/right lines - whole lines will be omitted. This allows for seamless use of adjoining LineBoxes. Class attribute `Symbols` can be used as source for standard lines: >>> print(LineBox(Text("Some text")).render(())) ┌─────────┐ │Some text│ └─────────┘ >>> print( ... LineBox( ... Text("Some text"), ... tlcorner=LineBox.Symbols.LIGHT.TOP_LEFT_ROUNDED, ... trcorner=LineBox.Symbols.LIGHT.TOP_RIGHT_ROUNDED, ... blcorner=LineBox.Symbols.LIGHT.BOTTOM_LEFT_ROUNDED, ... brcorner=LineBox.Symbols.LIGHT.BOTTOM_RIGHT_ROUNDED, ... ).render(()) ... ) ╭─────────╮ │Some text│ ╰─────────╯ >>> print( ... LineBox( ... Text("Some text"), ... tline=LineBox.Symbols.HEAVY.HORIZONTAL, ... bline=LineBox.Symbols.HEAVY.HORIZONTAL, ... lline=LineBox.Symbols.HEAVY.VERTICAL, ... rline=LineBox.Symbols.HEAVY.VERTICAL, ... tlcorner=LineBox.Symbols.HEAVY.TOP_LEFT, ... trcorner=LineBox.Symbols.HEAVY.TOP_RIGHT, ... blcorner=LineBox.Symbols.HEAVY.BOTTOM_LEFT, ... brcorner=LineBox.Symbols.HEAVY.BOTTOM_RIGHT, ... ).render(()) ... ) ┏━━━━━━━━━┓ ┃Some text┃ ┗━━━━━━━━━┛ To make Table constructions, some lineboxes need to be drawn without sides and T or CROSS symbols used for corners of cells. """ w_lline = SolidFill(lline) w_rline = SolidFill(rline) w_tlcorner, w_tline, w_trcorner = Text(tlcorner), Divider(tline), Text(trcorner) w_blcorner, w_bline, w_brcorner = Text(blcorner), Divider(bline), Text(brcorner) if not tline and title: raise ValueError("Cannot have a title when tline is empty string") if title_attr: self.title_widget = Text((title_attr, self.format_title(title))) else: self.title_widget = Text(self.format_title(title)) if tline: if title_align not in {Align.LEFT, Align.CENTER, Align.RIGHT}: raise ValueError('title_align must be one of "left", "right", or "center"') if title_align == Align.LEFT: tline_widgets = [(WHSettings.PACK, self.title_widget), w_tline] else: tline_widgets = [w_tline, (WHSettings.PACK, self.title_widget)] if title_align == Align.CENTER: tline_widgets.append(w_tline) self.tline_widget = Columns(tline_widgets) top = Columns( ( (int(bool(tlcorner and lline)), w_tlcorner), self.tline_widget, (int(bool(trcorner and rline)), w_trcorner), ) ) else: self.tline_widget = None top = None # Note: We need to define a fixed first widget (even if it's 0 width) so that the other # widgets have something to anchor onto middle = Columns( ((int(bool(lline)), w_lline), original_widget, (int(bool(rline)), w_rline)), box_columns=[0, 2], focus_column=original_widget, ) if bline: bottom = Columns( ( (int(bool(blcorner and lline)), w_blcorner), w_bline, (int(bool(brcorner and rline)), w_brcorner), ) ) else: bottom = None pile_widgets = [] if top: pile_widgets.append((WHSettings.PACK, top)) pile_widgets.append(middle) if bottom: pile_widgets.append((WHSettings.PACK, bottom)) self._wrapped_widget = Pile(pile_widgets, focus_item=middle) super().__init__(original_widget) @property def _w(self) -> Pile: return self._wrapped_widget def format_title(self, text: str) -> str: if text: return f" {text} " return "" def set_title(self, text: str) -> None: if not self.tline_widget: raise ValueError("Cannot set title when tline is unset") self.title_widget.set_text(self.format_title(text)) self.tline_widget._invalidate() @property def focus(self) -> Widget | None: """LineBox is partially container. While focus position is a bit hacky (formally it's not container and only position 0 available), focus widget is always provided by original widget. """ return self._original_widget.focus
6,884
Python
.py
160
32.1375
106
0.587076
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,260
grid_flow.py
urwid_urwid/urwid/widget/grid_flow.py
from __future__ import annotations import typing import warnings from urwid.split_repr import remove_defaults from .columns import Columns from .constants import Align, Sizing, WHSettings from .container import WidgetContainerListContentsMixin, WidgetContainerMixin from .divider import Divider from .monitored_list import MonitoredFocusList, MonitoredList from .padding import Padding from .pile import Pile from .widget import Widget, WidgetError, WidgetWarning, WidgetWrap if typing.TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence from typing_extensions import Literal class GridFlowError(WidgetError): """GridFlow specific error.""" class GridFlowWarning(WidgetWarning): """GridFlow specific warning.""" class GridFlow(WidgetWrap[Pile], WidgetContainerMixin, WidgetContainerListContentsMixin): """ The GridFlow widget is a flow widget that renders all the widgets it contains the same width, and it arranges them from left to right and top to bottom. """ def sizing(self) -> frozenset[Sizing]: """Widget sizing. ..note:: Empty widget sizing is limited to the FLOW due to no data for width. """ if self: return frozenset((Sizing.FLOW, Sizing.FIXED)) return frozenset((Sizing.FLOW,)) def __init__( self, cells: Iterable[Widget], cell_width: int, h_sep: int, v_sep: int, align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int], focus: int | Widget | None = None, ) -> None: """ :param cells: iterable of flow widgets to display :param cell_width: column width for each cell :param h_sep: blank columns between each cell horizontally :param v_sep: blank rows between cells vertically (if more than one row is required to display all the cells) :param align: horizontal alignment of cells, one of: 'left', 'center', 'right', ('relative', percentage 0=left 100=right) :param focus: widget index or widget instance to focus on """ prepared_contents: list[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]] = [] focus_position: int = -1 for idx, widget in enumerate(cells): prepared_contents.append((widget, (WHSettings.GIVEN, cell_width))) if focus_position < 0 and (focus in {widget, idx} or (focus is None and widget.selectable())): focus_position = idx focus_position = max(focus_position, 0) self._contents: MonitoredFocusList[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]] = MonitoredFocusList( prepared_contents, focus=focus_position ) self._contents.set_modified_callback(self._invalidate) self._contents.set_focus_changed_callback(lambda f: self._invalidate()) self._contents.set_validate_contents_modified(self._contents_modified) self._cell_width = cell_width self.h_sep = h_sep self.v_sep = v_sep self.align = align self._cache_maxcol = self._get_maxcol(()) super().__init__(self.generate_display_widget((self._cache_maxcol,))) def _repr_words(self) -> list[str]: if len(self.contents) > 1: contents_string = f"({len(self.contents)} items)" elif self.contents: contents_string = "(1 item)" else: contents_string = "()" return [*super()._repr_words(), contents_string] def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "cell_width": self.cell_width, "h_sep": self.h_sep, "v_sep": self.v_sep, "align": self.align, "focus": self.focus_position if len(self._contents) > 1 else None, } return remove_defaults(attrs, GridFlow.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: yield "cells", [widget for widget, _ in self.contents] yield "cell_width", self.cell_width yield "h_sep", self.h_sep yield "v_sep", self.v_sep yield "align", self.align yield "focus", self.focus_position def __len__(self) -> int: return len(self._contents) def _invalidate(self) -> None: self._cache_maxcol = None super()._invalidate() def _contents_modified( self, _slc: tuple[int, int, int], new_items: Iterable[tuple[Widget, tuple[Literal["given", WHSettings.GIVEN], int]]], ) -> None: for item in new_items: try: _w, (t, _n) = item if t != WHSettings.GIVEN: raise GridFlowError(f"added content invalid {item!r}") except (TypeError, ValueError) as exc: # noqa: PERF203 raise GridFlowError(f"added content invalid {item!r}").with_traceback(exc.__traceback__) from exc @property def cells(self): """ A list of the widgets in this GridFlow .. note:: only for backwards compatibility. You should use the new standard container property :attr:`contents` to modify GridFlow contents. """ warnings.warn( "only for backwards compatibility." "You should use the new standard container property `contents` to modify GridFlow", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList(w for w, t in self.contents) def user_modified(): self.cells = ml ml.set_modified_callback(user_modified) return ml @cells.setter def cells(self, widgets: Sequence[Widget]): warnings.warn( "only for backwards compatibility." "You should use the new standard container property `contents` to modify GridFlow", PendingDeprecationWarning, stacklevel=2, ) focus_position = self.focus_position self.contents = [(new, (WHSettings.GIVEN, self._cell_width)) for new in widgets] if focus_position < len(widgets): self.focus_position = focus_position def _get_cells(self): warnings.warn( "only for backwards compatibility." "You should use the new standard container property `contents` to modify GridFlow", DeprecationWarning, stacklevel=3, ) return self.cells def _set_cells(self, widgets: Sequence[Widget]): warnings.warn( "only for backwards compatibility." "You should use the new standard container property `contents` to modify GridFlow", DeprecationWarning, stacklevel=3, ) self.cells = widgets @property def cell_width(self) -> int: """ The width of each cell in the GridFlow. Setting this value affects all cells. """ return self._cell_width @cell_width.setter def cell_width(self, width: int) -> None: focus_position = self.focus_position self.contents = [(w, (WHSettings.GIVEN, width)) for (w, options) in self.contents] self.focus_position = focus_position self._cell_width = width def _get_cell_width(self) -> int: warnings.warn( f"Method `{self.__class__.__name__}._get_cell_width` is deprecated, " f"please use property `{self.__class__.__name__}.cell_width`", DeprecationWarning, stacklevel=3, ) return self.cell_width def _set_cell_width(self, width: int) -> None: warnings.warn( f"Method `{self.__class__.__name__}._set_cell_width` is deprecated, " f"please use property `{self.__class__.__name__}.cell_width`", DeprecationWarning, stacklevel=3, ) self.cell_width = width @property def contents(self) -> MonitoredFocusList[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]]: """ The contents of this GridFlow as a list of (widget, options) tuples. options is currently a tuple in the form `('fixed', number)`. number is the number of screen columns to allocate to this cell. 'fixed' is the only type accepted at this time. This list may be modified like a normal list and the GridFlow widget will update automatically. .. seealso:: Create new options tuples with the :meth:`options` method. """ return self._contents @contents.setter def contents(self, c): self._contents[:] = c def options( self, width_type: Literal["given", WHSettings.GIVEN] = WHSettings.GIVEN, width_amount: int | None = None, ) -> tuple[Literal[WHSettings.GIVEN], int]: """ Return a new options tuple for use in a GridFlow's .contents list. width_type -- 'given' is the only value accepted width_amount -- None to use the default cell_width for this GridFlow """ if width_type != WHSettings.GIVEN: raise GridFlowError(f"invalid width_type: {width_type!r}") if width_amount is None: width_amount = self._cell_width return (WHSettings(width_type), width_amount) def set_focus(self, cell: Widget | int) -> None: """ Set the cell in focus, for backwards compatibility. .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus_position` to get the focus. :param cell: contained element to focus :type cell: Widget or int """ warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus_position` to set the focus.", PendingDeprecationWarning, stacklevel=2, ) if isinstance(cell, int): try: if cell < 0 or cell >= len(self.contents): raise IndexError(f"No GridFlow child widget at position {cell}") except TypeError as exc: raise IndexError(f"No GridFlow child widget at position {cell}").with_traceback( exc.__traceback__ ) from exc self.contents.focus = cell return for i, (w, _options) in enumerate(self.contents): if cell == w: self.focus_position = i return raise ValueError(f"Widget not found in GridFlow contents: {cell!r}") @property def focus(self) -> Widget | None: """the child widget in focus or None when GridFlow is empty""" if not self.contents: return None return self.contents[self.focus_position][0] def _get_focus(self) -> Widget | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) if not self.contents: return None return self.contents[self.focus_position][0] def get_focus(self): """ Return the widget in focus, for backwards compatibility. .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus` to get the focus. """ warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus` to get the focus.", PendingDeprecationWarning, stacklevel=2, ) if not self.contents: return None return self.contents[self.focus_position][0] @property def focus_cell(self): warnings.warn( "only for backwards compatibility." "You may also use the new standard container property" "`focus` to get the focus and `focus_position` to get/set the cell in focus by index", PendingDeprecationWarning, stacklevel=2, ) return self.focus @focus_cell.setter def focus_cell(self, cell: Widget) -> None: warnings.warn( "only for backwards compatibility." "You may also use the new standard container property" "`focus` to get the focus and `focus_position` to get/set the cell in focus by index", PendingDeprecationWarning, stacklevel=2, ) for i, (w, _options) in enumerate(self.contents): if cell == w: self.focus_position = i return raise ValueError(f"Widget not found in GridFlow contents: {cell!r}") def _set_focus_cell(self, cell: Widget) -> None: warnings.warn( "only for backwards compatibility." "You may also use the new standard container property" "`focus` to get the focus and `focus_position` to get/set the cell in focus by index", DeprecationWarning, stacklevel=3, ) for i, (w, _options) in enumerate(self.contents): if cell == w: self.focus_position = i return raise ValueError(f"Widget not found in GridFlow contents: {cell!r}") @property def focus_position(self) -> int | None: """ index of child widget in focus. Raises :exc:`IndexError` if read when GridFlow is empty, or when set to an invalid index. """ if not self.contents: raise IndexError("No focus_position, GridFlow is empty") return self.contents.focus @focus_position.setter def focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ try: if position < 0 or position >= len(self.contents): raise IndexError(f"No GridFlow child widget at position {position}") except TypeError as exc: raise IndexError(f"No GridFlow child widget at position {position}").with_traceback( exc.__traceback__ ) from exc self.contents.focus = position def _get_focus_position(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) if not self.contents: raise IndexError("No focus_position, GridFlow is empty") return self.contents.focus def _set_focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ warnings.warn( f"method `{self.__class__.__name__}._set_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) try: if position < 0 or position >= len(self.contents): raise IndexError(f"No GridFlow child widget at position {position}") except TypeError as exc: raise IndexError(f"No GridFlow child widget at position {position}").with_traceback( exc.__traceback__ ) from exc self.contents.focus = position def _get_maxcol(self, size: tuple[int] | tuple[()]) -> int: if size: (maxcol,) = size if self and maxcol < self.cell_width: warnings.warn( f"Size is smaller than cell width ({maxcol!r} < {self.cell_width!r})", GridFlowWarning, stacklevel=3, ) elif self: maxcol = len(self) * self.cell_width + (len(self) - 1) * self.h_sep else: maxcol = 0 return maxcol def get_display_widget(self, size: tuple[int] | tuple[()]) -> Divider | Pile: """ Arrange the cells into columns (and possibly a pile) for display, input or to calculate rows, and update the display widget. """ maxcol = self._get_maxcol(size) # use cache if possible if self._cache_maxcol == maxcol: return self._w self._cache_maxcol = maxcol self._w = self.generate_display_widget((maxcol,)) return self._w def generate_display_widget(self, size: tuple[int] | tuple[()]) -> Divider | Pile: """ Actually generate display widget (ignoring cache) """ maxcol = self._get_maxcol(size) divider = Divider() if not self.contents: return divider if self.v_sep > 1: # increase size of divider divider.top = self.v_sep - 1 c = None p = Pile([]) used_space = 0 for i, (w, (_width_type, width_amount)) in enumerate(self.contents): if c is None or maxcol - used_space < width_amount: # starting a new row if self.v_sep: p.contents.append((divider, p.options())) c = Columns([], self.h_sep) column_focused = False pad = Padding(c, self.align) # extra attribute to reference contents position pad.first_position = i p.contents.append((pad, p.options())) # Use width == maxcol in case of maxcol < width amount # Columns will use empty widget in case of GIVEN width > maxcol c.contents.append((w, c.options(WHSettings.GIVEN, min(width_amount, maxcol)))) if (i == self.focus_position) or (not column_focused and w.selectable()): c.focus_position = len(c.contents) - 1 column_focused = True if i == self.focus_position: p.focus_position = len(p.contents) - 1 used_space = sum(x[1][1] for x in c.contents) + self.h_sep * len(c.contents) pad.width = used_space - self.h_sep if self.v_sep: # remove first divider del p.contents[:1] else: # Ensure p __selectable is updated p._contents_modified() # pylint: disable=protected-access return p def _set_focus_from_display_widget(self) -> None: """ Set the focus to the item in focus in the display widget. """ # display widget (self._w) is always built as: # # Pile([ # Padding( # Columns([ # possibly # cell, ...])), # Divider(), # possibly # ...]) pile_focus = self._w.focus if not pile_focus: return c = pile_focus.base_widget if c.focus: col_focus_position = c.focus_position else: col_focus_position = 0 # pad.first_position was set by generate_display_widget() above self.focus_position = pile_focus.first_position + col_focus_position def keypress( self, size: tuple[int] | tuple[()], # type: ignore[override] key: str, ) -> str | None: """ Pass keypress to display widget for handling. Captures focus changes. """ self.get_display_widget(size) key = super().keypress(size, key) if key is None: self._set_focus_from_display_widget() return key def pack( self, size: tuple[int] | tuple[()] = (), # type: ignore[override] focus: bool = False, ) -> tuple[int, int]: if size: return super().pack(size, focus) if self: cols = len(self) * self.cell_width + (len(self) - 1) * self.h_sep else: cols = 0 return cols, self.rows((cols,), focus) def rows(self, size: tuple[int], focus: bool = False) -> int: self.get_display_widget(size) return super().rows(size, focus=focus) def render( self, size: tuple[int] | tuple[()], # type: ignore[override] focus: bool = False, ): self.get_display_widget(size) return super().render(size, focus) def get_cursor_coords(self, size: tuple[int] | tuple[()]) -> tuple[int, int]: """Get cursor from display widget.""" self.get_display_widget(size) return super().get_cursor_coords(size) def move_cursor_to_coords(self, size: tuple[int] | tuple[()], col: int, row: int): """Set the widget in focus based on the col + row.""" self.get_display_widget(size) rval = super().move_cursor_to_coords(size, col, row) self._set_focus_from_display_widget() return rval def mouse_event( self, size: tuple[int] | tuple[()], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> Literal[True]: self.get_display_widget(size) super().mouse_event(size, event, button, col, row, focus) self._set_focus_from_display_widget() return True # at a minimum we adjusted our focus def get_pref_col(self, size: tuple[int] | tuple[()]): """Return pref col from display widget.""" self.get_display_widget(size) return super().get_pref_col(size)
21,757
Python
.py
521
31.760077
118
0.590404
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,261
popup.py
urwid_urwid/urwid/widget/popup.py
# Urwid Window-Icon-Menu-Pointer-style widget classes # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import typing from urwid.canvas import CompositeCanvas from .constants import Align, Sizing, VAlign from .overlay import Overlay from .widget import delegate_to_widget_mixin from .widget_decoration import WidgetDecoration if typing.TYPE_CHECKING: from typing_extensions import TypedDict from urwid.canvas import Canvas from .widget import Widget class PopUpParametersModel(TypedDict): left: int top: int overlay_width: int overlay_height: int WrappedWidget = typing.TypeVar("WrappedWidget") class PopUpLauncher(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]): def __init__(self, original_widget: [WrappedWidget]) -> None: super().__init__(original_widget) self._pop_up_widget = None def create_pop_up(self) -> Widget: """ Subclass must override this method and return a widget to be used for the pop-up. This method is called once each time the pop-up is opened. """ raise NotImplementedError("Subclass must override this method") def get_pop_up_parameters(self) -> PopUpParametersModel: """ Subclass must override this method and have it return a dict, eg: {'left':0, 'top':1, 'overlay_width':30, 'overlay_height':4} This method is called each time this widget is rendered. """ raise NotImplementedError("Subclass must override this method") def open_pop_up(self) -> None: self._pop_up_widget = self.create_pop_up() self._invalidate() def close_pop_up(self) -> None: self._pop_up_widget = None self._invalidate() def render(self, size, focus: bool = False) -> CompositeCanvas | Canvas: canv = super().render(size, focus) if self._pop_up_widget: canv = CompositeCanvas(canv) canv.set_pop_up(self._pop_up_widget, **self.get_pop_up_parameters()) return canv class PopUpTarget(WidgetDecoration[WrappedWidget]): # FIXME: this whole class is a terrible hack and must be fixed when layout and rendering are separated _sizing = frozenset((Sizing.BOX,)) _selectable = True def __init__(self, original_widget: WrappedWidget) -> None: super().__init__(original_widget) self._pop_up = None self._current_widget = self._original_widget def _update_overlay(self, size: tuple[int, int], focus: bool) -> None: canv = self._original_widget.render(size, focus=focus) self._cache_original_canvas = canv # imperfect performance hack pop_up = canv.get_pop_up() if pop_up: left, top, (w, overlay_width, overlay_height) = pop_up if self._pop_up != w: self._pop_up = w self._current_widget = Overlay( top_w=w, bottom_w=self._original_widget, align=Align.LEFT, width=overlay_width, valign=VAlign.TOP, height=overlay_height, left=left, top=top, ) else: self._current_widget.set_overlay_parameters( align=Align.LEFT, width=overlay_width, valign=VAlign.TOP, height=overlay_height, left=left, top=top, ) else: self._pop_up = None self._current_widget = self._original_widget def render(self, size: tuple[int, int], focus: bool = False) -> Canvas: self._update_overlay(size, focus) return self._current_widget.render(size, focus=focus) def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None: self._update_overlay(size, True) return self._current_widget.get_cursor_coords(size) def get_pref_col(self, size: tuple[int, int]) -> int: self._update_overlay(size, True) return self._current_widget.get_pref_col(size) def keypress(self, size: tuple[int, int], key: str) -> str | None: self._update_overlay(size, True) return self._current_widget.keypress(size, key) def move_cursor_to_coords(self, size: tuple[int, int], x: int, y: int): self._update_overlay(size, True) return self._current_widget.move_cursor_to_coords(size, x, y) def mouse_event( self, size: tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: self._update_overlay(size, focus) return self._current_widget.mouse_event(size, event, button, col, row, focus) def pack(self, size: tuple[int, int] | None = None, focus: bool = False) -> tuple[int, int]: self._update_overlay(size, focus) return self._current_widget.pack(size) def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
5,974
Python
.py
137
35.189781
106
0.63127
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,262
text.py
urwid_urwid/urwid/widget/text.py
from __future__ import annotations import typing from urwid import text_layout from urwid.canvas import apply_text_layout from urwid.split_repr import remove_defaults from urwid.str_util import calc_width from urwid.util import decompose_tagmarkup, get_encoding from .constants import Align, Sizing, WrapMode from .widget import Widget, WidgetError if typing.TYPE_CHECKING: from collections.abc import Hashable from typing_extensions import Literal from urwid.canvas import TextCanvas class TextError(WidgetError): pass class Text(Widget): """ a horizontally resizeable text widget """ _sizing = frozenset([Sizing.FLOW, Sizing.FIXED]) ignore_focus = True _repr_content_length_max = 140 def __init__( self, markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], align: Literal["left", "center", "right"] | Align = Align.LEFT, wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE, layout: text_layout.TextLayout | None = None, ) -> None: """ :param markup: content of text widget, one of: bytes or unicode text to be displayed (*display attribute*, *text markup*) *text markup* with *display attribute* applied to all parts of *text markup* with no display attribute already applied [*text markup*, *text markup*, ... ] all *text markup* in the list joined together :type markup: :ref:`text-markup` :param align: typically ``'left'``, ``'center'`` or ``'right'`` :type align: text alignment mode :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'`` :type wrap: text wrapping mode :param layout: defaults to a shared :class:`StandardTextLayout` instance :type layout: text layout instance >>> Text(u"Hello") <Text fixed/flow widget 'Hello'> >>> t = Text(('bold', u"stuff"), 'right', 'any') >>> t <Text fixed/flow widget 'stuff' align='right' wrap='any'> >>> print(t.text) stuff >>> t.attrib [('bold', 5)] """ super().__init__() self._cache_maxcol: int | None = None self.set_text(markup) self.set_layout(align, wrap, layout) def _repr_words(self) -> list[str]: """ Show the text in the repr in python3 format (b prefix for byte strings) and truncate if it's too long """ first = super()._repr_words() text = self.get_text()[0] rest = repr(text) if len(rest) > self._repr_content_length_max: rest = ( rest[: self._repr_content_length_max * 2 // 3 - 3] + "..." + rest[-self._repr_content_length_max // 3 :] ) return [*first, rest] def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "align": self._align_mode, "wrap": self._wrap_mode, } return remove_defaults(attrs, Text.__init__) def _invalidate(self) -> None: self._cache_maxcol = None super()._invalidate() def set_text(self, markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None: """ Set content of text widget. :param markup: see :class:`Text` for description. :type markup: text markup >>> t = Text(u"foo") >>> print(t.text) foo >>> t.set_text(u"bar") >>> print(t.text) bar >>> t.text = u"baz" # not supported because text stores text but set_text() takes markup Traceback (most recent call last): AttributeError: can't set attribute """ self._text, self._attrib = decompose_tagmarkup(markup) self._invalidate() def get_text(self) -> tuple[str | bytes, list[tuple[Hashable, int]]]: """ :returns: (*text*, *display attributes*) *text* complete bytes/unicode content of text widget *display attributes* run length encoded display attributes for *text*, eg. ``[('attr1', 10), ('attr2', 5)]`` >>> Text(u"Hello").get_text() # ... = u in Python 2 (...'Hello', []) >>> Text(('bright', u"Headline")).get_text() (...'Headline', [('bright', 8)]) >>> Text([('a', u"one"), u"two", ('b', u"three")]).get_text() (...'onetwothree', [('a', 3), (None, 3), ('b', 5)]) """ return self._text, self._attrib @property def text(self) -> str | bytes: """ Read-only property returning the complete bytes/unicode content of this widget """ return self.get_text()[0] @property def attrib(self) -> list[tuple[Hashable, int]]: """ Read-only property returning the run-length encoded display attributes of this widget """ return self.get_text()[1] def set_align_mode(self, mode: Literal["left", "center", "right"] | Align) -> None: """ Set text alignment mode. Supported modes depend on text layout object in use but defaults to a :class:`StandardTextLayout` instance :param mode: typically ``'left'``, ``'center'`` or ``'right'`` :type mode: text alignment mode >>> t = Text(u"word") >>> t.set_align_mode('right') >>> t.align 'right' >>> t.render((10,)).text # ... = b in Python 3 [...' word'] >>> t.align = 'center' >>> t.render((10,)).text [...' word '] >>> t.align = 'somewhere' Traceback (most recent call last): TextError: Alignment mode 'somewhere' not supported. """ if not self.layout.supports_align_mode(mode): raise TextError(f"Alignment mode {mode!r} not supported.") self._align_mode = mode self._invalidate() def set_wrap_mode(self, mode: Literal["space", "any", "clip", "ellipsis"] | WrapMode) -> None: """ Set text wrapping mode. Supported modes depend on text layout object in use but defaults to a :class:`StandardTextLayout` instance :param mode: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'`` :type mode: text wrapping mode >>> t = Text(u"some words") >>> t.render((6,)).text # ... = b in Python 3 [...'some ', ...'words '] >>> t.set_wrap_mode('clip') >>> t.wrap 'clip' >>> t.render((6,)).text [...'some w'] >>> t.wrap = 'any' # Urwid 0.9.9 or later >>> t.render((6,)).text [...'some w', ...'ords '] >>> t.wrap = 'somehow' Traceback (most recent call last): TextError: Wrap mode 'somehow' not supported. """ if not self.layout.supports_wrap_mode(mode): raise TextError(f"Wrap mode {mode!r} not supported.") self._wrap_mode = mode self._invalidate() def set_layout( self, align: Literal["left", "center", "right"] | Align, wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode, layout: text_layout.TextLayout | None = None, ) -> None: """ Set the text layout object, alignment and wrapping modes at the same time. :type align: text alignment mode :param wrap: typically 'space', 'any', 'clip' or 'ellipsis' :type wrap: text wrapping mode :param layout: defaults to a shared :class:`StandardTextLayout` instance :type layout: text layout instance >>> t = Text(u"hi") >>> t.set_layout('right', 'clip') >>> t <Text fixed/flow widget 'hi' align='right' wrap='clip'> """ if layout is None: layout = text_layout.default_layout self._layout = layout self.set_align_mode(align) self.set_wrap_mode(wrap) align = property(lambda self: self._align_mode, set_align_mode) wrap = property(lambda self: self._wrap_mode, set_wrap_mode) @property def layout(self): return self._layout def render( self, size: tuple[int] | tuple[()], # type: ignore[override] focus: bool = False, ) -> TextCanvas: """ Render contents with wrapping and alignment. Return canvas. See :meth:`Widget.render` for parameter details. >>> Text(u"important things").render((18,)).text [b'important things '] >>> Text(u"important things").render((11,)).text [b'important ', b'things '] >>> Text("demo text").render(()).text [b'demo text'] """ text, attr = self.get_text() if size: (maxcol,) = size else: maxcol, _ = self.pack(focus=focus) trans = self.get_line_translation(maxcol, (text, attr)) return apply_text_layout(text, attr, trans, maxcol) def rows(self, size: tuple[int], focus: bool = False) -> int: """ Return the number of rows the rendered text requires. See :meth:`Widget.rows` for parameter details. >>> Text(u"important things").rows((18,)) 1 >>> Text(u"important things").rows((11,)) 2 """ (maxcol,) = size return len(self.get_line_translation(maxcol)) def get_line_translation( self, maxcol: int, ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None = None, ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]: """ Return layout structure used to map self.text to a canvas. This method is used internally, but may be useful for debugging custom layout classes. :param maxcol: columns available for display :type maxcol: int :param ta: ``None`` or the (*text*, *display attributes*) tuple returned from :meth:`.get_text` :type ta: text and display attributes """ if not self._cache_maxcol or self._cache_maxcol != maxcol: self._update_cache_translation(maxcol, ta) return self._cache_translation def _update_cache_translation( self, maxcol: int, ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None, ) -> None: if ta: text, _attr = ta else: text, _attr = self.get_text() self._cache_maxcol = maxcol self._cache_translation = self.layout.layout(text, maxcol, self._align_mode, self._wrap_mode) def pack( self, size: tuple[()] | tuple[int] | None = None, # type: ignore[override] focus: bool = False, ) -> tuple[int, int]: """ Return the number of screen columns and rows required for this Text widget to be displayed without wrapping or clipping, as a single element tuple. :param size: ``None`` or ``()`` for unlimited screen columns (like FIXED sizing) or (*maxcol*,) to specify a maximum column size :type size: widget size :param focus: widget is focused on :type focus: bool >>> Text(u"important things").pack() (16, 1) >>> Text(u"important things").pack((15,)) (9, 2) >>> Text(u"important things").pack((8,)) (8, 2) >>> Text(u"important things").pack(()) (16, 1) """ text, attr = self.get_text() if size: (maxcol,) = size if not hasattr(self.layout, "pack"): return maxcol, self.rows(size, focus) trans = self.get_line_translation(maxcol, (text, attr)) cols = self.layout.pack(maxcol, trans) return (cols, len(trans)) if text: if isinstance(text, bytes): text = text.decode(get_encoding()) return ( max(calc_width(line, 0, len(line)) for line in text.splitlines(keepends=False)), text.count("\n") + 1, ) return 0, 1
12,187
Python
.py
305
30.891803
120
0.562077
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,263
__init__.py
urwid_urwid/urwid/widget/__init__.py
from __future__ import annotations from .attr_map import AttrMap, AttrMapError from .attr_wrap import AttrWrap from .bar_graph import BarGraph, BarGraphError, BarGraphMeta, GraphVScale, scale_bar_values from .big_text import BigText from .box_adapter import BoxAdapter, BoxAdapterError from .columns import Columns, ColumnsError, ColumnsWarning from .constants import ( RELATIVE_100, Align, Sizing, VAlign, WHSettings, WrapMode, normalize_align, normalize_height, normalize_valign, normalize_width, simplify_align, simplify_height, simplify_valign, simplify_width, ) from .container import WidgetContainerListContentsMixin, WidgetContainerMixin from .divider import Divider from .edit import Edit, EditError, IntEdit from .filler import Filler, FillerError, calculate_top_bottom_filler from .frame import Frame, FrameError from .grid_flow import GridFlow, GridFlowError, GridFlowWarning from .line_box import LineBox from .listbox import ListBox, ListBoxError, ListWalker, ListWalkerError, SimpleFocusListWalker, SimpleListWalker from .monitored_list import MonitoredFocusList, MonitoredList from .overlay import Overlay, OverlayError, OverlayWarning from .padding import Padding, PaddingError, PaddingWarning, calculate_left_right_padding from .pile import Pile, PileError, PileWarning from .popup import PopUpLauncher, PopUpTarget from .progress_bar import ProgressBar from .scrollable import Scrollable, ScrollableError, ScrollBar from .solid_fill import SolidFill from .text import Text, TextError from .treetools import ParentNode, TreeListBox, TreeNode, TreeWalker, TreeWidget, TreeWidgetError from .widget import ( BoxWidget, FixedWidget, FlowWidget, Widget, WidgetError, WidgetMeta, WidgetWarning, WidgetWrap, WidgetWrapError, delegate_to_widget_mixin, fixed_size, nocache_widget_render, nocache_widget_render_instance, ) from .widget_decoration import WidgetDecoration, WidgetDisable, WidgetPlaceholder from .wimp import Button, CheckBox, CheckBoxError, RadioButton, SelectableIcon __all__ = ( "ANY", "BOTTOM", "BOX", "CENTER", "CLIP", "ELLIPSIS", "FIXED", "FLOW", "GIVEN", "LEFT", "MIDDLE", "PACK", "RELATIVE", "RELATIVE_100", "RIGHT", "SPACE", "TOP", "WEIGHT", "Align", "AttrMap", "AttrMapError", "AttrWrap", "BarGraph", "BarGraphError", "BarGraphMeta", "BigText", "BoxAdapter", "BoxAdapterError", "BoxWidget", "Button", "CheckBox", "CheckBoxError", "Columns", "ColumnsError", "ColumnsWarning", "Divider", "Edit", "EditError", "Filler", "FillerError", "FixedWidget", "FlowWidget", "Frame", "FrameError", "GraphVScale", "GridFlow", "GridFlowError", "GridFlowWarning", "IntEdit", "LineBox", "ListBox", "ListBoxError", "ListWalker", "ListWalkerError", "MonitoredFocusList", "MonitoredList", "Overlay", "OverlayError", "OverlayWarning", "Padding", "PaddingError", "PaddingWarning", "ParentNode", "Pile", "PileError", "PileWarning", "PopUpLauncher", "PopUpTarget", "ProgressBar", "RadioButton", "ScrollBar", "Scrollable", "ScrollableError", "SelectableIcon", "SimpleFocusListWalker", "SimpleListWalker", "Sizing", "SolidFill", "Text", "TextError", "TreeListBox", "TreeNode", "TreeWalker", "TreeWidget", "TreeWidgetError", "VAlign", "WHSettings", "Widget", "WidgetContainerListContentsMixin", "WidgetContainerMixin", "WidgetDecoration", "WidgetDisable", "WidgetError", "WidgetMeta", "WidgetPlaceholder", "WidgetWarning", "WidgetWrap", "WidgetWrapError", "WrapMode", "calculate_left_right_padding", "calculate_top_bottom_filler", "delegate_to_widget_mixin", "fixed_size", "nocache_widget_render", "nocache_widget_render_instance", "normalize_align", "normalize_height", "normalize_valign", "normalize_width", "scale_bar_values", "simplify_align", "simplify_height", "simplify_valign", "simplify_width", ) # Backward compatibility FLOW = Sizing.FLOW BOX = Sizing.BOX FIXED = Sizing.FIXED LEFT = Align.LEFT RIGHT = Align.RIGHT CENTER = Align.CENTER TOP = VAlign.TOP MIDDLE = VAlign.MIDDLE BOTTOM = VAlign.BOTTOM SPACE = WrapMode.SPACE ANY = WrapMode.ANY CLIP = WrapMode.CLIP ELLIPSIS = WrapMode.ELLIPSIS PACK = WHSettings.PACK GIVEN = WHSettings.GIVEN RELATIVE = WHSettings.RELATIVE WEIGHT = WHSettings.WEIGHT
4,683
Python
.py
192
20.416667
112
0.712979
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,264
box_adapter.py
urwid_urwid/urwid/widget/box_adapter.py
from __future__ import annotations import typing import warnings from urwid.canvas import CompositeCanvas from .constants import Sizing from .widget_decoration import WidgetDecoration, WidgetError WrappedWidget = typing.TypeVar("WrappedWidget") class BoxAdapterError(WidgetError): pass class BoxAdapter(WidgetDecoration[WrappedWidget]): """ Adapter for using a box widget where a flow widget would usually go """ no_cache: typing.ClassVar[list[str]] = ["rows"] def __init__(self, box_widget: WrappedWidget, height: int) -> None: """ Create a flow widget that contains a box widget :param box_widget: box widget to wrap :type box_widget: Widget :param height: number of rows for box widget :type height: int >>> from urwid import SolidFill >>> BoxAdapter(SolidFill(u"x"), 5) # 5-rows of x's <BoxAdapter flow widget <SolidFill box widget 'x'> height=5> """ if hasattr(box_widget, "sizing") and Sizing.BOX not in box_widget.sizing(): raise BoxAdapterError(f"{box_widget!r} is not a box widget") super().__init__(box_widget) self.height = height def _repr_attrs(self) -> dict[str, typing.Any]: return {**super()._repr_attrs(), "height": self.height} # originally stored as box_widget, keep for compatibility @property def box_widget(self) -> WrappedWidget: warnings.warn( "original stored as original_widget, keep for compatibility", PendingDeprecationWarning, stacklevel=2, ) return self.original_widget @box_widget.setter def box_widget(self, widget: WrappedWidget) -> None: warnings.warn( "original stored as original_widget, keep for compatibility", PendingDeprecationWarning, stacklevel=2, ) self.original_widget = widget def sizing(self) -> frozenset[Sizing]: return frozenset((Sizing.FLOW,)) def rows(self, size: tuple[int], focus: bool = False) -> int: """ Return the predetermined height (behave like a flow widget) >>> from urwid import SolidFill >>> BoxAdapter(SolidFill(u"x"), 5).rows((20,)) 5 """ return self.height # The next few functions simply tack-on our height and pass through # to self._original_widget def get_cursor_coords(self, size: tuple[int]) -> int | None: (maxcol,) = size if not hasattr(self._original_widget, "get_cursor_coords"): return None return self._original_widget.get_cursor_coords((maxcol, self.height)) def get_pref_col(self, size: tuple[int]) -> int | None: (maxcol,) = size if not hasattr(self._original_widget, "get_pref_col"): return None return self._original_widget.get_pref_col((maxcol, self.height)) def keypress( self, size: tuple[int], # type: ignore[override] key: str, ) -> str | None: (maxcol,) = size return self._original_widget.keypress((maxcol, self.height), key) def move_cursor_to_coords(self, size: tuple[int], col: int, row: int): (maxcol,) = size if not hasattr(self._original_widget, "move_cursor_to_coords"): return True return self._original_widget.move_cursor_to_coords((maxcol, self.height), col, row) def mouse_event( self, size: tuple[int], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: (maxcol,) = size if not hasattr(self._original_widget, "mouse_event"): return False return self._original_widget.mouse_event((maxcol, self.height), event, button, col, row, focus) def render( self, size: tuple[int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: (maxcol,) = size canv = CompositeCanvas(self._original_widget.render((maxcol, self.height), focus)) return canv def __getattr__(self, name: str): """ Pass calls to box widget. """ return getattr(self.original_widget, name)
4,276
Python
.py
108
31.574074
103
0.625302
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,265
frame.py
urwid_urwid/urwid/widget/frame.py
from __future__ import annotations import typing import warnings from urwid.canvas import CanvasCombine, CompositeCanvas from urwid.split_repr import remove_defaults from urwid.util import is_mouse_press from .constants import Sizing, VAlign from .container import WidgetContainerMixin from .filler import Filler from .widget import Widget, WidgetError if typing.TYPE_CHECKING: from collections.abc import Iterator, MutableMapping from typing_extensions import Literal BodyWidget = typing.TypeVar("BodyWidget") HeaderWidget = typing.TypeVar("HeaderWidget") FooterWidget = typing.TypeVar("FooterWidget") class FrameError(WidgetError): pass def _check_widget_subclass(widget: Widget | None) -> None: if widget is None: return if not isinstance(widget, Widget): obj_class_path = f"{widget.__class__.__module__}.{widget.__class__.__name__}" warnings.warn( f"{obj_class_path} is not subclass of Widget", DeprecationWarning, stacklevel=3, ) class Frame(Widget, WidgetContainerMixin, typing.Generic[BodyWidget, HeaderWidget, FooterWidget]): """ Frame widget is a box widget with optional header and footer flow widgets placed above and below the box widget. .. note:: The main difference between a Frame and a :class:`Pile` widget defined as: `Pile([('pack', header), body, ('pack', footer)])` is that the Frame will not automatically change focus up and down in response to keystrokes. """ _selectable = True _sizing = frozenset([Sizing.BOX]) def __init__( self, body: BodyWidget, header: HeaderWidget = None, footer: FooterWidget = None, focus_part: Literal["header", "footer", "body"] | Widget = "body", ): """ :param body: a box widget for the body of the frame :type body: Widget :param header: a flow widget for above the body (or None) :type header: Widget :param footer: a flow widget for below the body (or None) :type footer: Widget :param focus_part: 'header', 'footer' or 'body' :type focus_part: str | Widget """ super().__init__() self._header = header self._body = body self._footer = footer if focus_part in {"header", "footer", "body"}: self.focus_part = focus_part elif focus_part == header: self.focus_part = "header" elif focus_part == footer: self.focus_part = "footer" elif focus_part == body: self.focus_part = "body" else: raise ValueError(f"Invalid focus part {focus_part!r}") _check_widget_subclass(header) _check_widget_subclass(body) _check_widget_subclass(footer) def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "body": self._body, "header": self._header, "footer": self._footer, "focus_part": self.focus_part, } return remove_defaults(attrs, Frame.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: yield "body", self._body yield "header", self._header yield "footer", self._footer yield "focus_part", self.focus_part @property def header(self) -> HeaderWidget: return self._header @header.setter def header(self, header: HeaderWidget) -> None: _check_widget_subclass(header) self._header = header if header is None and self.focus_part == "header": self.focus_part = "body" self._invalidate() def get_header(self) -> HeaderWidget: warnings.warn( f"method `{self.__class__.__name__}.get_header` is deprecated, " f"standard property `{self.__class__.__name__}.header` should be used instead", PendingDeprecationWarning, stacklevel=2, ) return self.header def set_header(self, header: HeaderWidget) -> None: warnings.warn( f"method `{self.__class__.__name__}.set_header` is deprecated, " f"standard property `{self.__class__.__name__}.header` should be used instead", PendingDeprecationWarning, stacklevel=2, ) self.header = header @property def body(self) -> BodyWidget: return self._body @body.setter def body(self, body: BodyWidget) -> None: _check_widget_subclass(body) self._body = body self._invalidate() def get_body(self) -> BodyWidget: warnings.warn( f"method `{self.__class__.__name__}.get_body` is deprecated, " f"standard property {self.__class__.__name__}.body should be used instead", PendingDeprecationWarning, stacklevel=2, ) return self.body def set_body(self, body: BodyWidget) -> None: warnings.warn( f"method `{self.__class__.__name__}.set_body` is deprecated, " f"standard property `{self.__class__.__name__}.body` should be used instead", PendingDeprecationWarning, stacklevel=2, ) self.body = body @property def footer(self) -> FooterWidget: return self._footer @footer.setter def footer(self, footer: FooterWidget) -> None: _check_widget_subclass(footer) self._footer = footer if footer is None and self.focus_part == "footer": self.focus_part = "body" self._invalidate() def get_footer(self) -> FooterWidget: warnings.warn( f"method `{self.__class__.__name__}.get_footer` is deprecated, " f"standard property `{self.__class__.__name__}.footer` should be used instead", PendingDeprecationWarning, stacklevel=2, ) return self.footer def set_footer(self, footer: FooterWidget) -> None: warnings.warn( f"method `{self.__class__.__name__}.set_footer` is deprecated, " f"standard property `{self.__class__.__name__}.footer` should be used instead", PendingDeprecationWarning, stacklevel=2, ) self.footer = footer @property def focus_position(self) -> Literal["header", "footer", "body"]: """ writeable property containing an indicator which part of the frame that is in focus: `'body', 'header'` or `'footer'`. :returns: one of 'header', 'footer' or 'body'. :rtype: str """ return self.focus_part @focus_position.setter def focus_position(self, part: Literal["header", "footer", "body"]) -> None: """ Determine which part of the frame is in focus. :param part: 'header', 'footer' or 'body' :type part: str """ if part not in {"header", "footer", "body"}: raise IndexError(f"Invalid position for Frame: {part}") if (part == "header" and self._header is None) or (part == "footer" and self._footer is None): raise IndexError(f"This Frame has no {part}") self.focus_part = part self._invalidate() def get_focus(self) -> Literal["header", "footer", "body"]: """ writeable property containing an indicator which part of the frame that is in focus: `'body', 'header'` or `'footer'`. .. note:: included for backwards compatibility. You should rather use the container property :attr:`.focus_position` to get this value. :returns: one of 'header', 'footer' or 'body'. :rtype: str """ warnings.warn( "included for backwards compatibility." "You should rather use the container property `.focus_position` to get this value.", PendingDeprecationWarning, stacklevel=2, ) return self.focus_position def set_focus(self, part: Literal["header", "footer", "body"]) -> None: warnings.warn( "included for backwards compatibility." "You should rather use the container property `.focus_position` to set this value.", PendingDeprecationWarning, stacklevel=2, ) self.focus_position = part @property def focus(self) -> BodyWidget | HeaderWidget | FooterWidget: """ child :class:`Widget` in focus: the body, header or footer widget. This is a read-only property.""" return {"header": self._header, "footer": self._footer, "body": self._body}[self.focus_part] def _get_focus(self) -> BodyWidget | HeaderWidget | FooterWidget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) return {"header": self._header, "footer": self._footer, "body": self._body}[self.focus_part] @property def contents( self, ) -> MutableMapping[ Literal["header", "footer", "body"], tuple[BodyWidget | HeaderWidget | FooterWidget, None], ]: """ a dict-like object similar to:: { 'body': (body_widget, None), 'header': (header_widget, None), # if frame has a header 'footer': (footer_widget, None) # if frame has a footer } This object may be used to read or update the contents of the Frame. The values are similar to the list-like .contents objects used in other containers with (:class:`Widget`, options) tuples, but are constrained to keys for each of the three usual parts of a Frame. When other keys are used a :exc:`KeyError` will be raised. Currently, all options are `None`, but using the :meth:`options` method to create the options value is recommended for forwards compatibility. """ # noinspection PyMethodParameters class FrameContents( typing.MutableMapping[ str, typing.Tuple[typing.Union[BodyWidget, HeaderWidget, FooterWidget], None], ] ): # pylint: disable=no-self-argument __slots__ = () def __len__(inner_self) -> int: return len(inner_self.keys()) __getitem__ = self._contents__getitem__ __setitem__ = self._contents__setitem__ __delitem__ = self._contents__delitem__ def __iter__(inner_self) -> Iterator[str]: yield from inner_self.keys() def __repr__(inner_self) -> str: return f"<{inner_self.__class__.__name__}({dict(inner_self)}) for {self}>" def __rich_repr__(inner_self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: yield from inner_self.items() return FrameContents() def _contents_keys(self) -> list[Literal["header", "footer", "body"]]: keys = ["body"] if self._header: keys.append("header") if self._footer: keys.append("footer") return keys @typing.overload def _contents__getitem__(self, key: Literal["body"]) -> tuple[BodyWidget, None]: ... @typing.overload def _contents__getitem__(self, key: Literal["header"]) -> tuple[HeaderWidget, None]: ... @typing.overload def _contents__getitem__(self, key: Literal["footer"]) -> tuple[FooterWidget, None]: ... def _contents__getitem__( self, key: Literal["body", "header", "footer"] ) -> tuple[BodyWidget | HeaderWidget | FooterWidget, None]: if key == "body": return (self._body, None) if key == "header" and self._header: return (self._header, None) if key == "footer" and self._footer: return (self._footer, None) raise KeyError(f"Frame.contents has no key: {key!r}") @typing.overload def _contents__setitem__(self, key: Literal["body"], value: tuple[BodyWidget, None]) -> None: ... @typing.overload def _contents__setitem__(self, key: Literal["header"], value: tuple[HeaderWidget, None]) -> None: ... @typing.overload def _contents__setitem__(self, key: Literal["footer"], value: tuple[FooterWidget, None]) -> None: ... def _contents__setitem__( self, key: Literal["body", "header", "footer"], value: tuple[BodyWidget | HeaderWidget | FooterWidget, None], ) -> None: if key not in {"body", "header", "footer"}: raise KeyError(f"Frame.contents has no key: {key!r}") try: value_w, value_options = value if value_options is not None: raise FrameError(f"added content invalid: {value!r}") except (ValueError, TypeError) as exc: raise FrameError(f"added content invalid: {value!r}").with_traceback(exc.__traceback__) from exc if key == "body": self.body = value_w elif key == "footer": self.footer = value_w else: self.header = value_w def _contents__delitem__(self, key: Literal["header", "footer"]) -> None: if key not in {"header", "footer"}: raise KeyError(f"Frame.contents can't remove key: {key!r}") if (key == "header" and self._header is None) or (key == "footer" and self._footer is None): raise KeyError(f"Frame.contents has no key: {key!r}") if key == "header": self.header = None else: self.footer = None def _contents(self): warnings.warn( f"method `{self.__class__.__name__}._contents` is deprecated, " f"please use property `{self.__class__.__name__}.contents`", DeprecationWarning, stacklevel=3, ) return self.contents def options(self) -> None: """ There are currently no options for Frame contents. Return None as a placeholder for future options. """ def frame_top_bottom(self, size: tuple[int, int], focus: bool) -> tuple[tuple[int, int], tuple[int, int]]: """ Calculate the number of rows for the header and footer. :param size: See :meth:`Widget.render` for details :type size: widget size :param focus: ``True`` if this widget is in focus :type focus: bool :returns: `(head rows, foot rows),(orig head, orig foot)` orig head/foot are from rows() calls. :rtype: (int, int), (int, int) """ (maxcol, maxrow) = size frows = hrows = 0 if self.header: hrows = self.header.rows((maxcol,), self.focus_part == "header" and focus) if self.footer: frows = self.footer.rows((maxcol,), self.focus_part == "footer" and focus) remaining = maxrow if self.focus_part == "footer": if frows >= remaining: return (0, remaining), (hrows, frows) remaining -= frows if hrows >= remaining: return (remaining, frows), (hrows, frows) elif self.focus_part == "header": if hrows >= maxrow: return (remaining, 0), (hrows, frows) remaining -= hrows if frows >= remaining: return (hrows, remaining), (hrows, frows) elif hrows + frows >= remaining: # self.focus_part == 'body' rless1 = max(0, remaining - 1) if frows >= remaining - 1: return (0, rless1), (hrows, frows) remaining -= frows rless1 = max(0, remaining - 1) return (rless1, frows), (hrows, frows) return (hrows, frows), (hrows, frows) def render( self, size: tuple[int, int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: (maxcol, maxrow) = size (htrim, ftrim), (hrows, frows) = self.frame_top_bottom((maxcol, maxrow), focus) combinelist = [] depends_on = [] head = None if htrim and htrim < hrows: head = Filler(self.header, VAlign.TOP).render((maxcol, htrim), focus and self.focus_part == "header") elif htrim: head = self.header.render((maxcol,), focus and self.focus_part == "header") if head.rows() != hrows: raise RuntimeError("rows, render mismatch") if head: combinelist.append((head, "header", self.focus_part == "header")) depends_on.append(self.header) if ftrim + htrim < maxrow: body = self.body.render((maxcol, maxrow - ftrim - htrim), focus and self.focus_part == "body") combinelist.append((body, "body", self.focus_part == "body")) depends_on.append(self.body) foot = None if ftrim and ftrim < frows: foot = Filler(self.footer, VAlign.BOTTOM).render((maxcol, ftrim), focus and self.focus_part == "footer") elif ftrim: foot = self.footer.render((maxcol,), focus and self.focus_part == "footer") if foot.rows() != frows: raise RuntimeError("rows, render mismatch") if foot: combinelist.append((foot, "footer", self.focus_part == "footer")) depends_on.append(self.footer) return CanvasCombine(combinelist) def keypress( self, size: tuple[int, int], # type: ignore[override] key: str, ) -> str | None: """Pass keypress to widget in focus.""" (maxcol, maxrow) = size if self.focus_part == "header" and self.header is not None: if not self.header.selectable(): return key return self.header.keypress((maxcol,), key) if self.focus_part == "footer" and self.footer is not None: if not self.footer.selectable(): return key return self.footer.keypress((maxcol,), key) if self.focus_part != "body": return key remaining = maxrow if self.header is not None: remaining -= self.header.rows((maxcol,)) if self.footer is not None: remaining -= self.footer.rows((maxcol,)) if remaining <= 0: return key if not self.body.selectable(): return key return self.body.keypress((maxcol, remaining), key) def mouse_event( self, size: tuple[int, int], # type: ignore[override] event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """ Pass mouse event to appropriate part of frame. Focus may be changed on button 1 press. """ (maxcol, maxrow) = size (htrim, ftrim), (_hrows, _frows) = self.frame_top_bottom((maxcol, maxrow), focus) if row < htrim: # within header focus = focus and self.focus_part == "header" if is_mouse_press(event) and button == 1 and self.header.selectable(): self.focus_position = "header" if not hasattr(self.header, "mouse_event"): return False return self.header.mouse_event((maxcol,), event, button, col, row, focus) if row >= maxrow - ftrim: # within footer focus = focus and self.focus_part == "footer" if is_mouse_press(event) and button == 1 and self.footer.selectable(): self.focus_position = "footer" if not hasattr(self.footer, "mouse_event"): return False return self.footer.mouse_event((maxcol,), event, button, col, row - maxrow + ftrim, focus) # within body focus = focus and self.focus_part == "body" if is_mouse_press(event) and button == 1 and self.body.selectable(): self.focus_position = "body" if not hasattr(self.body, "mouse_event"): return False return self.body.mouse_event((maxcol, maxrow - htrim - ftrim), event, button, col, row - htrim, focus) def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None: """Return the cursor coordinates of the focus widget.""" if not self.focus.selectable(): return None if not hasattr(self.focus, "get_cursor_coords"): return None fp = self.focus_position (maxcol, maxrow) = size (hrows, frows), _ = self.frame_top_bottom(size, True) if fp == "header": row_adjust = 0 coords = self.header.get_cursor_coords((maxcol,)) elif fp == "body": row_adjust = hrows coords = self.body.get_cursor_coords((maxcol, maxrow - hrows - frows)) else: row_adjust = maxrow - frows coords = self.footer.get_cursor_coords((maxcol,)) if coords is None: return None x, y = coords return x, y + row_adjust def __iter__(self) -> Iterator[Literal["header", "body", "footer"]]: """ Return an iterator over the positions in this Frame top to bottom. """ if self._header: yield "header" yield "body" if self._footer: yield "footer" def __reversed__(self) -> Iterator[Literal["footer", "body", "header"]]: """ Return an iterator over the positions in this Frame bottom to top. """ if self._footer: yield "footer" yield "body" if self._header: yield "header"
21,834
Python
.py
512
32.792969
116
0.580679
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,266
columns.py
urwid_urwid/urwid/widget/columns.py
from __future__ import annotations import typing import warnings from itertools import chain, repeat import urwid from urwid.canvas import Canvas, CanvasJoin, CompositeCanvas, SolidCanvas from urwid.command_map import Command from urwid.split_repr import remove_defaults from urwid.util import is_mouse_press from .constants import Align, Sizing, WHSettings from .container import WidgetContainerListContentsMixin, WidgetContainerMixin, _ContainerElementSizingFlag from .monitored_list import MonitoredFocusList, MonitoredList from .widget import Widget, WidgetError, WidgetWarning if typing.TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence from typing_extensions import Literal class ColumnsError(WidgetError): """Columns related errors.""" class ColumnsWarning(WidgetWarning): """Columns related warnings.""" class Columns(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin): """ Widgets arranged horizontally in columns from left to right """ def sizing(self) -> frozenset[Sizing]: """Sizing supported by widget. :return: Calculated widget sizing :rtype: frozenset[Sizing] Due to the nature of container with mutable contents, this method cannot be cached. Rules: * WEIGHT BOX -> BOX * GIVEN BOX -> Can be included in FIXED and FLOW depends on the other columns * PACK BOX -> Unsupported * BOX-only widget without `box_columns` disallow FLOW render * WEIGHT FLOW -> FLOW * GIVEN FLOW -> FIXED (known width and widget knows its height) + FLOW (historic) * PACK FLOW -> FLOW (widget fit in provided size) * WEIGHT FIXED -> Need also FLOW or/and BOX to properly render due to width calculation * GIVEN FIXED -> Unsupported * PACK FIXED -> FIXED (widget knows its size) Backward compatibility rules: * GIVEN BOX -> Allow BOX BOX can be only if ALL widgets support BOX. FIXED can be only if no BOX without "box_columns" flag and no strict FLOW. >>> from urwid import BigText, Edit, SolidFill, Text, Thin3x3Font >>> font = Thin3x3Font() # BOX-only widget >>> Columns((SolidFill("#"),)) <Columns box widget (1 item)> # BOX-only widget with "get height from max" >>> Columns((SolidFill("#"),), box_columns=(0,)) <Columns box widget (1 item)> # FLOW-only >>> Columns((Edit(),)) <Columns selectable flow widget (1 item)> # FLOW allowed by "box_columns" >>> Columns((Edit(), SolidFill("#")), box_columns=(1,)) <Columns selectable flow widget (2 items) focus_column=0> # FLOW/FIXED >>> Columns((Text("T"),)) <Columns fixed/flow widget (1 item)> # GIVEN BOX only -> BOX only >>> Columns(((5, SolidFill("#")),), box_columns=(0,)) <Columns box widget (1 item)> # No FLOW - BOX only >>> Columns(((5, SolidFill("#")), SolidFill("*")), box_columns=(0, 1)) <Columns box widget (2 items) focus_column=0> # FIXED only -> FIXED (and FLOW via drop/expand) >>> Columns(((WHSettings.PACK, BigText("1", font)),)) <Columns fixed/flow widget (1 item)> # Invalid sizing combination -> use fallback settings (and produce warning) >>> Columns(((WHSettings.PACK, SolidFill("#")),)) <Columns box/flow widget (1 item)> # Special case: empty columns widget sizing is impossible to calculate >>> Columns(()) <Columns box/flow widget ()> """ if not self.contents: return frozenset((urwid.BOX, urwid.FLOW)) strict_box = False has_flow = False block_fixed = False has_fixed = False supported: set[Sizing] = set() box_flow_fixed = ( _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED ) flow_fixed = _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED given_box = _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.WH_GIVEN flags: set[_ContainerElementSizingFlag] = set() for idx, (widget, (size_kind, _size_weight, is_box)) in enumerate(self.contents): w_sizing = widget.sizing() flag = _ContainerElementSizingFlag.NONE if size_kind == WHSettings.WEIGHT: flag |= _ContainerElementSizingFlag.WH_WEIGHT if Sizing.BOX in w_sizing: flag |= _ContainerElementSizingFlag.BOX if Sizing.FLOW in w_sizing: flag |= _ContainerElementSizingFlag.FLOW if Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}: flag |= _ContainerElementSizingFlag.FIXED elif size_kind == WHSettings.GIVEN: flag |= _ContainerElementSizingFlag.WH_GIVEN if Sizing.BOX in w_sizing: flag |= _ContainerElementSizingFlag.BOX if Sizing.FLOW in w_sizing: flag |= _ContainerElementSizingFlag.FIXED flag |= _ContainerElementSizingFlag.FLOW else: flag |= _ContainerElementSizingFlag.WH_PACK if Sizing.FIXED in w_sizing: flag |= _ContainerElementSizingFlag.FIXED if Sizing.FLOW in w_sizing: flag |= _ContainerElementSizingFlag.FLOW if not flag & box_flow_fixed: warnings.warn( f"Sizing combination of widget {widget} (position={idx}) not supported: " f"{size_kind.name} box={is_box}", ColumnsWarning, stacklevel=3, ) return frozenset((Sizing.BOX, Sizing.FLOW)) flags.add(flag) if flag & _ContainerElementSizingFlag.BOX and not (is_box or flag & flow_fixed): strict_box = True if flag & _ContainerElementSizingFlag.FLOW: has_flow = True if flag & _ContainerElementSizingFlag.FIXED: has_fixed = True elif flag & given_box != given_box: block_fixed = True if all(flag & _ContainerElementSizingFlag.BOX for flag in flags): # Only if ALL widgets can be rendered as BOX, widget can be rendered as BOX. # Hacky "BOX" render for FLOW-only is still present, # due to incorrected implementation can be used by downstream supported.add(Sizing.BOX) if not strict_box: if has_flow: supported.add(Sizing.FLOW) if has_fixed and not block_fixed: supported.add(Sizing.FLOW) supported.add(Sizing.FIXED) if not supported: warnings.warn( f"Columns widget contents flags not allow to determine supported render kind:\n" f"{', '.join(sorted(flag.log_string for flag in flags))}\n" f"Using fallback hardcoded BOX|FLOW sizing kind.", ColumnsWarning, stacklevel=3, ) return frozenset((Sizing.BOX, Sizing.FLOW)) return frozenset(supported) def __init__( self, widget_list: Iterable[ Widget | tuple[Literal["pack", WHSettings.PACK] | int, Widget] | tuple[Literal["given", WHSettings.GIVEN], int, Widget] | tuple[Literal["weight", WHSettings.WEIGHT], int | float, Widget] ], dividechars: int = 0, focus_column: int | Widget | None = None, min_width: int = 1, box_columns: Iterable[int] | None = None, ): """ :param widget_list: iterable of flow or box widgets :param dividechars: number of blank characters between columns :param focus_column: index into widget_list of column in focus or focused widget instance, if ``None`` the first selectable widget will be chosen. :param min_width: minimum width for each column which is not calling widget.pack() in *widget_list*. :param box_columns: a list of column indexes containing box widgets whose height is set to the maximum of the rows required by columns not listed in *box_columns*. *widget_list* may also contain tuples such as: (*given_width*, *widget*) make this column *given_width* screen columns wide, where *given_width* is an int (``'pack'``, *widget*) call :meth:`pack() <Widget.pack>` to calculate the width of this column (``'weight'``, *weight*, *widget*) give this column a relative *weight* (number) to calculate its width from th screen columns remaining Widgets not in a tuple are the same as (``'weight'``, ``1``, *widget*) If the Columns widget is treated as a box widget then all children are treated as box widgets, and *box_columns* is ignored. If the Columns widget is treated as a flow widget then the rows are calculated as the largest rows() returned from all columns except the ones listed in *box_columns*. The box widgets in *box_columns* will be displayed with this calculated number of rows, filling the full height. """ self._selectable = False self._cache_column_widths: list[int] = [] super().__init__() self._contents: MonitoredFocusList[ tuple[ Widget, tuple[Literal[WHSettings.PACK], None, bool] | tuple[Literal[WHSettings.GIVEN], int, bool] | tuple[Literal[WHSettings.WEIGHT], int | float, bool], ], ] = MonitoredFocusList() self._contents.set_modified_callback(self._contents_modified) self._contents.set_focus_changed_callback(lambda f: self._invalidate()) self._contents.set_validate_contents_modified(self._validate_contents_modified) box_columns = set(box_columns or ()) for i, original in enumerate(widget_list): w = original if not isinstance(w, tuple): self.contents.append((w, (WHSettings.WEIGHT, 1, i in box_columns))) elif w[0] in {Sizing.FLOW, WHSettings.PACK}: # 'pack' used to be called 'flow' _ignored, w = w self.contents.append((w, (WHSettings.PACK, None, i in box_columns))) elif len(w) == 2 or w[0] in {Sizing.FIXED, WHSettings.GIVEN}: # backwards compatibility: FIXED -> GIVEN width, w = w[-2:] self.contents.append((w, (WHSettings.GIVEN, width, i in box_columns))) elif w[0] == WHSettings.WEIGHT: _ignored, width, w = w self.contents.append((w, (WHSettings.WEIGHT, width, i in box_columns))) else: raise ColumnsError(f"initial widget list item invalid: {original!r}") if focus_column == w or (focus_column is None and w.selectable()): focus_column = i if not isinstance(w, Widget): warnings.warn(f"{w!r} is not a Widget", ColumnsWarning, stacklevel=3) self.dividechars = dividechars if self.contents and focus_column is not None: self.focus_position = focus_column self.pref_col = None self.min_width = min_width self._cache_maxcol = None def _repr_words(self) -> list[str]: if len(self.contents) > 1: contents_string = f"({len(self.contents)} items)" elif self.contents: contents_string = "(1 item)" else: contents_string = "()" return [*super()._repr_words(), contents_string] def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "dividechars": self.dividechars, "focus_column": self.focus_position if len(self._contents) > 1 else None, "min_width": self.min_width, } return remove_defaults(attrs, Columns.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: widget_list: list[ Widget | tuple[Literal[WHSettings.PACK] | int, Widget] | tuple[Literal[WHSettings.WEIGHT], int | float, Widget] ] = [] box_columns: list[int] = [] for idx, (w_instance, (sizing, amount, is_box)) in enumerate(self._contents): if sizing == WHSettings.GIVEN: widget_list.append((amount, w_instance)) elif sizing == WHSettings.PACK: widget_list.append((WHSettings.PACK, w_instance)) elif amount == 1: widget_list.append(w_instance) else: widget_list.append((WHSettings.WEIGHT, amount, w_instance)) if is_box: box_columns.append(idx) yield "widget_list", widget_list yield "dividechars", self.dividechars yield "focus_column", self.focus_position if self._contents else None yield "min_width", self.min_width yield "box_columns", box_columns def __len__(self) -> int: return len(self._contents) def _contents_modified(self) -> None: """ Recalculate whether this widget should be selectable whenever the contents has been changed. """ self._selectable = any(w.selectable() for w, o in self.contents) self._invalidate() def _validate_contents_modified(self, slc, new_items) -> None: invalid_items: list[tuple[Widget, tuple[typing.Any, typing.Any, typing.Any]]] = [] try: for item in new_items: _w, (t, n, b) = item if any( ( t not in {WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT}, (n is not None and (not isinstance(n, (int, float)) or n < 0)), not isinstance(b, bool), ) ): invalid_items.append(item) except (TypeError, ValueError) as exc: raise ColumnsError(f"added content invalid {exc}").with_traceback(exc.__traceback__) from exc if invalid_items: raise ColumnsError(f"added content invalid: {invalid_items!r}") @property def widget_list(self) -> MonitoredList: """ A list of the widgets in this Columns .. note:: only for backwards compatibility. You should use the new standard container property :attr:`contents`. """ warnings.warn( "only for backwards compatibility. You should use the new standard container `contents`", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList(w for w, t in self.contents) def user_modified(): self.widget_list = ml ml.set_modified_callback(user_modified) return ml @widget_list.setter def widget_list(self, widgets): warnings.warn( "only for backwards compatibility. You should use the new standard container `contents`", PendingDeprecationWarning, stacklevel=2, ) focus_position = self.focus_position self.contents = [ # need to grow contents list if widgets is longer (new, options) for (new, (w, options)) in zip( widgets, chain(self.contents, repeat((None, (WHSettings.WEIGHT, 1, False)))), ) ] if focus_position < len(widgets): self.focus_position = focus_position @property def column_types(self) -> MonitoredList: """ A list of the old partial options values for widgets in this Pile, for backwards compatibility only. You should use the new standard container property .contents to modify Pile contents. """ warnings.warn( "for backwards compatibility only." "You should use the new standard container property .contents to modify Pile contents.", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList( # return the old column type names ({WHSettings.GIVEN: Sizing.FIXED, WHSettings.PACK: Sizing.FLOW}.get(t, t), n) for w, (t, n, b) in self.contents ) def user_modified(): self.column_types = ml ml.set_modified_callback(user_modified) return ml @column_types.setter def column_types(self, column_types): warnings.warn( "for backwards compatibility only." "You should use the new standard container property .contents to modify Pile contents.", PendingDeprecationWarning, stacklevel=2, ) focus_position = self.focus_position self.contents = [ (w, ({Sizing.FIXED: WHSettings.GIVEN, Sizing.FLOW: WHSettings.PACK}.get(new_t, new_t), new_n, b)) for ((new_t, new_n), (w, (t, n, b))) in zip(column_types, self.contents) ] if focus_position < len(column_types): self.focus_position = focus_position @property def box_columns(self) -> MonitoredList: """ A list of the indexes of the columns that are to be treated as box widgets when the Columns is treated as a flow widget. .. note:: only for backwards compatibility. You should use the new standard container property :attr:`contents`. """ warnings.warn( "only for backwards compatibility.You should use the new standard container property `contents`", PendingDeprecationWarning, stacklevel=2, ) ml = MonitoredList(i for i, (w, (t, n, b)) in enumerate(self.contents) if b) def user_modified(): self.box_columns = ml ml.set_modified_callback(user_modified) return ml @box_columns.setter def box_columns(self, box_columns): warnings.warn( "only for backwards compatibility.You should use the new standard container property `contents`", PendingDeprecationWarning, stacklevel=2, ) box_columns = set(box_columns) self.contents = [(w, (t, n, i in box_columns)) for (i, (w, (t, n, b))) in enumerate(self.contents)] @property def has_flow_type(self) -> bool: """ .. deprecated:: 1.0 Read values from :attr:`contents` instead. """ warnings.warn( ".has_flow_type is deprecated, read values from .contents instead.", DeprecationWarning, stacklevel=2, ) return WHSettings.PACK in self.column_types @has_flow_type.setter def has_flow_type(self, value): warnings.warn( ".has_flow_type is deprecated, read values from .contents instead.", DeprecationWarning, stacklevel=2, ) @property def contents( self, ) -> MonitoredFocusList[ tuple[ Widget, tuple[Literal[WHSettings.PACK], None, bool] | tuple[Literal[WHSettings.GIVEN], int, bool] | tuple[Literal[WHSettings.WEIGHT], int | float, bool], ], ]: """ The contents of this Columns as a list of `(widget, options)` tuples. This list may be modified like a normal list and the Columns widget will update automatically. .. seealso:: Create new options tuples with the :meth:`options` method """ return self._contents @contents.setter def contents( self, c: Sequence[ Widget, tuple[Literal[WHSettings.PACK], None, bool] | tuple[Literal[WHSettings.GIVEN], int, bool] | tuple[Literal[WHSettings.WEIGHT], int | float, bool], ], ) -> None: self._contents[:] = c @staticmethod def options( width_type: Literal[ "pack", "given", "weight", WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT ] = WHSettings.WEIGHT, width_amount: int | float | None = 1, # noqa: PYI041 # provide explicit for IDEs box_widget: bool = False, ) -> ( tuple[Literal[WHSettings.PACK], None, bool] | tuple[Literal[WHSettings.GIVEN], int, bool] | tuple[Literal[WHSettings.WEIGHT], int | float, bool] ): """ Return a new options tuple for use in a Pile's .contents list. This sets an entry's width type: one of the following: ``'pack'`` Call the widget's :meth:`Widget.pack` method to determine how wide this column should be. *width_amount* is ignored. ``'given'`` Make column exactly width_amount screen-columns wide. ``'weight'`` Allocate the remaining space to this column by using *width_amount* as a weight value. :param width_type: ``'pack'``, ``'given'`` or ``'weight'`` :param width_amount: ``None`` for ``'pack'``, a number of screen columns for ``'given'`` or a weight value (number) for ``'weight'`` :param box_widget: set to `True` if this widget is to be treated as a box widget when the Columns widget itself is treated as a flow widget. :type box_widget: bool """ if width_type == WHSettings.PACK: return (WHSettings.PACK, None, box_widget) if width_type in {WHSettings.GIVEN, WHSettings.WEIGHT} and width_amount is not None: return (WHSettings(width_type), width_amount, box_widget) raise ColumnsError(f"invalid combination: width_type={width_type!r}, width_amount={width_amount!r}") def _invalidate(self) -> None: self._cache_maxcol = None super()._invalidate() def set_focus_column(self, num: int) -> None: """ Set the column in focus by its index in :attr:`widget_list`. :param num: index of focus-to-be entry :type num: int .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus_position` to set the focus. """ warnings.warn( "only for backwards compatibility.You may also use the new standard container property `focus_position`", PendingDeprecationWarning, stacklevel=2, ) self.focus_position = num def get_focus_column(self) -> int: """ Return the focus column index. .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus_position` to get the focus. """ warnings.warn( "only for backwards compatibility.You may also use the new standard container property `focus_position`", PendingDeprecationWarning, stacklevel=2, ) return self.focus_position def set_focus(self, item: Widget | int) -> None: """ Set the item in focus .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus_position` to get the focus. :param item: widget or integer index""" warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus_position` to get the focus.", PendingDeprecationWarning, stacklevel=2, ) if isinstance(item, int): self.focus_position = item return for i, (w, _options) in enumerate(self.contents): if item == w: self.focus_position = i return raise ValueError(f"Widget not found in Columns contents: {item!r}") @property def focus(self) -> Widget | None: """ the child widget in focus or None when Columns is empty Return the widget in focus, for backwards compatibility. You may also use the new standard container property .focus to get the child widget in focus. """ if not self.contents: return None return self.contents[self.focus_position][0] def _get_focus(self) -> Widget: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) if not self.contents: return None return self.contents[self.focus_position][0] def get_focus(self): """ Return the widget in focus, for backwards compatibility. .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus` to get the focus. """ warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus` to get the focus.", PendingDeprecationWarning, stacklevel=2, ) if not self.contents: return None return self.contents[self.focus_position][0] @property def focus_position(self) -> int | None: """ index of child widget in focus. Raises :exc:`IndexError` if read when Columns is empty, or when set to an invalid index. """ if not self.contents: raise IndexError("No focus_position, Columns is empty") return self.contents.focus @focus_position.setter def focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ try: if position < 0 or position >= len(self.contents): raise IndexError(f"No Columns child widget at position {position}") except TypeError as exc: raise IndexError(f"No Columns child widget at position {position}").with_traceback( exc.__traceback__ ) from exc self.contents.focus = position def _get_focus_position(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) if not self.contents: raise IndexError("No focus_position, Columns is empty") return self.contents.focus def _set_focus_position(self, position: int) -> None: """ Set the widget in focus. position -- index of child widget to be made focus """ warnings.warn( f"method `{self.__class__.__name__}._set_focus_position` is deprecated, " f"please use `{self.__class__.__name__}.focus_position` property", DeprecationWarning, stacklevel=3, ) try: if position < 0 or position >= len(self.contents): raise IndexError(f"No Columns child widget at position {position}") except TypeError as exc: raise IndexError(f"No Columns child widget at position {position}").with_traceback( exc.__traceback__ ) from exc self.contents.focus = position @property def focus_col(self): """ A property for reading and setting the index of the column in focus. .. note:: only for backwards compatibility. You may also use the new standard container property :attr:`focus_position` to get the focus. """ warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus_position` to get the focus.", PendingDeprecationWarning, stacklevel=2, ) return self.focus_position @focus_col.setter def focus_col(self, new_position) -> None: warnings.warn( "only for backwards compatibility." "You may also use the new standard container property `focus_position` to get the focus.", PendingDeprecationWarning, stacklevel=2, ) self.focus_position = new_position def column_widths(self, size: tuple[int] | tuple[int, int], focus: bool = False) -> list[int]: """ Return a list of column widths. 0 values in the list means hide the corresponding column completely """ maxcol = size[0] # FIXME: get rid of this check and recalculate only when a 'pack' widget has been modified. if maxcol == self._cache_maxcol and not any(t == WHSettings.PACK for w, (t, n, b) in self.contents): return self._cache_column_widths widths = [] weighted = [] shared = maxcol + self.dividechars for i, (w, (t, width, b)) in enumerate(self.contents): if t == WHSettings.GIVEN: static_w = width elif t == WHSettings.PACK: if isinstance(w, Widget): w_sizing = w.sizing() else: warnings.warn(f"{w!r} is not a Widget", ColumnsWarning, stacklevel=3) w_sizing = frozenset((urwid.BOX, urwid.FLOW)) if w_sizing & frozenset((Sizing.FIXED, Sizing.FLOW)): candidate_size = 0 if Sizing.FIXED in w_sizing: candidate_size = w.pack((), focus and i == self.focus_position)[0] if Sizing.FLOW in w_sizing and (not candidate_size or candidate_size > maxcol): # FIXME: should be able to pack with a different maxcol value candidate_size = w.pack((maxcol,), focus and i == self.focus_position)[0] static_w = candidate_size else: warnings.warn( f"Unusual widget {w} sizing for {t} (box={b}). " f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for width calculation", ColumnsWarning, stacklevel=3, ) static_w = w.pack((maxcol,), focus and i == self.focus_position)[0] else: static_w = self.min_width if shared < static_w + self.dividechars and i > self.focus_position: break widths.append(static_w) shared -= static_w + self.dividechars if t not in {WHSettings.GIVEN, WHSettings.PACK}: weighted.append((width, i)) # drop columns on the left until we fit for i, width_ in enumerate(widths): if shared >= 0: break shared += width_ + self.dividechars widths[i] = 0 if weighted and weighted[0][1] == i: del weighted[0] if shared: # divide up the remaining space between weighted cols wtotal = sum(weight for weight, i in weighted) grow = shared + len(weighted) * self.min_width for weight, i in sorted(weighted): width = max(int(grow * weight / wtotal + 0.5), self.min_width) widths[i] = width grow -= width wtotal -= weight self._cache_maxcol = maxcol self._cache_column_widths = widths return widths def _get_fixed_column_sizes( self, focus: bool = False, ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int] | tuple[()]]]: """Get column widths, heights and render size parameters""" widths: dict[int, int] = {} heights: dict[int, int] = {} w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {} box: list[int] = [] weighted: dict[int, list[tuple[Widget, int, bool, bool]]] = {} weights: list[int] = [] weight_max_sizes: dict[int, int] = {} for i, (widget, (size_kind, size_weight, is_box)) in enumerate(self.contents): w_sizing = widget.sizing() focused = focus and i == self.focus_position if size_kind == WHSettings.GIVEN: widths[i] = size_weight if is_box: box.append(i) elif Sizing.FLOW in w_sizing: heights[i] = widget.rows((size_weight,), focused) w_h_args[i] = (size_weight,) else: raise ColumnsError(f"Unsupported combination of {size_kind} box={is_box!r} for {widget}") elif size_kind == WHSettings.PACK and Sizing.FIXED in w_sizing and not is_box: width, height = widget.pack((), focused) widths[i] = width heights[i] = height w_h_args[i] = () elif size_weight <= 0: widths[i] = 0 heights[i] = 1 if is_box: box.append(i) else: w_h_args[i] = (0,) elif Sizing.FLOW in w_sizing or is_box: if Sizing.FIXED in w_sizing: width, height = widget.pack((), focused) else: width = self.min_width weighted.setdefault(size_weight, []).append((widget, i, is_box, focused)) weights.append(size_weight) weight_max_sizes.setdefault(size_weight, width) weight_max_sizes[size_weight] = max(weight_max_sizes[size_weight], width) else: raise ColumnsError(f"Unsupported combination of {size_kind} box={is_box!r} for {widget}") if weight_max_sizes: max_weighted_coefficient = max(width / weight for weight, width in weight_max_sizes.items()) for weight in weight_max_sizes: width = max(int(max_weighted_coefficient * weight + 0.5), self.min_width) for widget, i, is_box, focused in weighted[weight]: widths[i] = width if not is_box: heights[i] = widget.rows((width,), focused) w_h_args[i] = (width,) else: box.append(i) if not heights: raise ColumnsError(f"No height information for pack {self!r} as FIXED") max_height = max(heights.values()) for idx in box: heights[idx] = max_height w_h_args[idx] = (widths[idx], max_height) return ( tuple(widths[idx] for idx in range(len(widths))), tuple(heights[idx] for idx in range(len(heights))), tuple(w_h_args[idx] for idx in range(len(w_h_args))), ) def get_column_sizes( self, size: tuple[int, int] | tuple[int] | tuple[()], focus: bool = False, ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int, int] | tuple[int] | tuple[()]]]: """Get column widths, heights and render size parameters""" if not size: return self._get_fixed_column_sizes(focus=focus) widths = tuple(self.column_widths(size=size, focus=focus)) heights: dict[int, int] = {} w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {} box: list[int] = [] box_need_height: list[int] = [] for i, (width, (widget, (size_kind, _size_weight, is_box))) in enumerate(zip(widths, self.contents)): if isinstance(widget, Widget): w_sizing = widget.sizing() else: warnings.warn(f"{widget!r} is not Widget.", ColumnsWarning, stacklevel=3) # This branch should be fully deleted later. w_sizing = frozenset((Sizing.FLOW, Sizing.BOX)) if len(size) == 2 and Sizing.BOX in w_sizing: heights[i] = size[1] w_h_args[i] = (width, size[1]) elif is_box: box.append(i) elif Sizing.FLOW in w_sizing: if width > 0: heights[i] = widget.rows((width,), focus and i == self.focus_position) else: heights[i] = 0 w_h_args[i] = (width,) elif size_kind == WHSettings.PACK: if width > 0: heights[i] = widget.pack((), focus and i == self.focus_position)[1] else: heights[i] = 0 w_h_args[i] = () else: box_need_height.append(i) if len(size) == 1: if heights: max_height = max(heights.values()) if box_need_height: warnings.warn( f"Widgets in columns {box_need_height} " f"({[self.contents[i][0] for i in box_need_height]}) " f'are BOX widgets not marked "box_columns" while FLOW render is requested (size={size!r})', ColumnsWarning, stacklevel=3, ) else: max_height = 1 else: max_height = size[1] for idx in (*box, *box_need_height): heights[idx] = max_height w_h_args[idx] = (widths[idx], max_height) return ( widths, tuple(heights[idx] for idx in range(len(heights))), tuple(w_h_args[idx] for idx in range(len(w_h_args))), ) def pack( self, size: tuple[()] | tuple[int] | tuple[int, int] = (), focus: bool = False, ) -> tuple[int, int]: """Get packed sized for widget.""" if size: return super().pack(size, focus) widths, heights, _ = self.get_column_sizes(size, focus) return (sum(widths) + self.dividechars * max(len(widths) - 1, 0), max(heights)) def render( self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False, ) -> SolidCanvas | CompositeCanvas: """ Render columns and return canvas. :param size: see :meth:`Widget.render` for details :param focus: ``True`` if this widget is in focus :type focus: bool """ widths, _, size_args = self.get_column_sizes(size, focus) data: list[tuple[Canvas, int, bool, int]] = [] for i, (width, w_size, (w, _)) in enumerate(zip(widths, size_args, self.contents)): # if the widget has a width of 0, hide it if width <= 0: continue if i < len(widths) - 1: width += self.dividechars # noqa: PLW2901 data.append( ( w.render(w_size, focus=focus and self.focus_position == i), i, self.focus_position == i, width, ) ) if not data: if size: return SolidCanvas(" ", size[0], (size[1:] + (1,))[0]) raise ColumnsError("No data to render") canvas = CanvasJoin(data) if size and canvas.cols() < size[0]: canvas.pad_trim_left_right(0, size[0] - canvas.cols()) return canvas def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None: """Return the cursor coordinates from the focus widget.""" w, _ = self.contents[self.focus_position] if not w.selectable(): return None if not hasattr(w, "get_cursor_coords"): return None widths, _, size_args = self.get_column_sizes(size, focus=True) if len(widths) <= self.focus_position: return None coords = w.get_cursor_coords(size_args[self.focus_position]) if coords is None: return None x, y = coords x += sum(self.dividechars + wc for wc in widths[: self.focus_position] if wc > 0) return x, y def move_cursor_to_coords( self, size: tuple[()] | tuple[int] | tuple[int, int], col: int | Literal["left", "right"], row: int, ) -> bool: """ Choose a selectable column to focus based on the coords. see :meth:`Widget.move_cursor_coords` for details """ try: widths, _, size_args = self.get_column_sizes(size, focus=True) except Exception as exc: raise ValueError(self.contents, size, col, row) from exc best = None x = 0 for i, (width, (w, _options)) in enumerate(zip(widths, self.contents)): end = x + width if w.selectable(): if col != Align.RIGHT and (col == Align.LEFT or x > col) and best is None: # no other choice best = i, x, end, w break if col != Align.RIGHT and x > col and col - best[2] < x - col: # choose one on left break best = i, x, end, w if col != Align.RIGHT and col < end: # choose this one break x = end + self.dividechars if best is None: return False i, x, end, w = best if hasattr(w, "move_cursor_to_coords"): if isinstance(col, int): move_x = min(max(0, col - x), end - x - 1) else: move_x = col rval = w.move_cursor_to_coords(size_args[i], move_x, row) if rval is False: return False self.focus_position = i self.pref_col = col return True def mouse_event( self, size: tuple[()] | tuple[int] | tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """ Send event to appropriate column. May change focus on button 1 press. """ widths, _, size_args = self.get_column_sizes(size, focus=focus) x = 0 for i, (width, w_size, (w, _)) in enumerate(zip(widths, size_args, self.contents)): if col < x: return False w = self.contents[i][0] # noqa: PLW2901 end = x + width if col >= end: x = end + self.dividechars continue focus = focus and self.focus_position == i if is_mouse_press(event) and button == 1 and w.selectable(): self.focus_position = i if not hasattr(w, "mouse_event"): warnings.warn( f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget", DeprecationWarning, stacklevel=2, ) return False return w.mouse_event(w_size, event, button, col - x, row, focus) return False def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int: """Return the pref col from the column in focus.""" widths, _, size_args = self.get_column_sizes(size, focus=True) w, _ = self.contents[self.focus_position] if len(widths) <= self.focus_position: return 0 col = None cwidth = widths[self.focus_position] if hasattr(w, "get_pref_col"): col = w.get_pref_col(size_args[self.focus_position]) if isinstance(col, int): col += self.focus_position * self.dividechars col += sum(widths[: self.focus_position]) if col is None: col = self.pref_col if col is None and w.selectable(): col = cwidth // 2 col += self.focus_position * self.dividechars col += sum(widths[: self.focus_position]) return col def rows(self, size: tuple[int] | tuple[int, int], focus: bool = False) -> int: """ Return the number of rows required by the columns. This only makes sense if :attr:`widget_list` contains flow widgets. see :meth:`Widget.rows` for details """ _, heights, _ = self.get_column_sizes(size, focus) if heights: return max(1, *heights) return 1 def keypress( self, size: tuple[()] | tuple[int] | tuple[int, int], key: str, ) -> str | None: """ Pass keypress to the focus column. :param size: Widget size correct for the supported sizing :type size: tuple[()] | tuple[int] | tuple[int, int] :param key: a single keystroke value :type key: str """ if self.focus_position is None: return key widths, _, size_args = self.get_column_sizes(size, focus=True) if self.focus_position >= len(widths): return key i = self.focus_position w, _ = self.contents[i] if self._command_map[key] not in {Command.UP, Command.DOWN, Command.PAGE_UP, Command.PAGE_DOWN}: self.pref_col = None if w.selectable(): key = w.keypress(size_args[i], key) if self._command_map[key] not in {Command.LEFT, Command.RIGHT}: return key if self._command_map[key] == Command.LEFT: candidates = list(range(i - 1, -1, -1)) # count backwards to 0 else: # key == 'right' candidates = list(range(i + 1, len(self.contents))) for j in candidates: if not self.contents[j][0].selectable(): continue self.focus_position = j return None return key
46,388
Python
.py
1,040
32.896154
117
0.567544
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,267
divider.py
urwid_urwid/urwid/widget/divider.py
from __future__ import annotations import enum import typing from urwid.canvas import CompositeCanvas, SolidCanvas from .constants import BOX_SYMBOLS, SHADE_SYMBOLS, Sizing from .widget import Widget class DividerSymbols(str, enum.Enum): """Common symbols for divider widgets.""" # Lines LIGHT_HL = BOX_SYMBOLS.LIGHT.HORIZONTAL LIGHT_4_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_4_DASHES LIGHT_3_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_3_DASHES LIGHT_2_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_2_DASHES HEAVY_HL = BOX_SYMBOLS.HEAVY.HORIZONTAL HEAVY_4_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_4_DASHES HEAVY_3_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_3_DASHES HEAVY_2_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_2_DASHES DOUBLE_HL = BOX_SYMBOLS.DOUBLE.HORIZONTAL # Full block FULL_BLOCK = SHADE_SYMBOLS.FULL_BLOCK DARK_SHADE = SHADE_SYMBOLS.DARK_SHADE MEDIUM_SHADE = SHADE_SYMBOLS.MEDIUM_SHADE LITE_SHADE = SHADE_SYMBOLS.LITE_SHADE class Divider(Widget): """ Horizontal divider widget """ Symbols = DividerSymbols _sizing = frozenset([Sizing.FLOW]) ignore_focus = True def __init__( self, div_char: str | bytes = " ", top: int = 0, bottom: int = 0, ) -> None: """ :param div_char: character to repeat across line :type div_char: bytes or unicode :param top: number of blank lines above :type top: int :param bottom: number of blank lines below :type bottom: int >>> Divider() <Divider flow widget> >>> Divider(u'-') <Divider flow widget '-'> >>> Divider(u'x', 1, 2) <Divider flow widget 'x' bottom=2 top=1> """ super().__init__() self.div_char = div_char self.top = top self.bottom = bottom def _repr_words(self) -> list[str]: return super()._repr_words() + [repr(self.div_char)] * (self.div_char != " ") def _repr_attrs(self) -> dict[str, typing.Any]: attrs = dict(super()._repr_attrs()) if self.top: attrs["top"] = self.top if self.bottom: attrs["bottom"] = self.bottom return attrs def rows(self, size: tuple[int], focus: bool = False) -> int: """ Return the number of lines that will be rendered. >>> Divider().rows((10,)) 1 >>> Divider(u'x', 1, 2).rows((10,)) 4 """ (_maxcol,) = size return self.top + 1 + self.bottom def render( self, size: tuple[int], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: """ Render the divider as a canvas and return it. >>> Divider().render((10,)).text # ... = b in Python 3 [...' '] >>> Divider(u'-', top=1).render((10,)).text [...' ', ...'----------'] >>> Divider(u'x', bottom=2).render((5,)).text [...'xxxxx', ...' ', ...' '] """ (maxcol,) = size canv = CompositeCanvas(SolidCanvas(self.div_char, maxcol, 1)) if self.top or self.bottom: canv.pad_trim_top_bottom(self.top, self.bottom) return canv
3,251
Python
.py
92
27.923913
85
0.581766
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,268
monitored_list.py
urwid_urwid/urwid/widget/monitored_list.py
# Urwid MonitoredList class # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import functools import typing import warnings if typing.TYPE_CHECKING: from collections.abc import Callable, Collection, Iterable, Iterator from typing_extensions import Concatenate, ParamSpec, Self ArgSpec = ParamSpec("ArgSpec") Ret = typing.TypeVar("Ret") __all__ = ("MonitoredFocusList", "MonitoredList") _T = typing.TypeVar("_T") def _call_modified( fn: Callable[Concatenate[MonitoredList, ArgSpec], Ret] ) -> Callable[Concatenate[MonitoredList, ArgSpec], Ret]: @functools.wraps(fn) def call_modified_wrapper(self: MonitoredList, *args: ArgSpec.args, **kwargs: ArgSpec.kwargs) -> Ret: rval = fn(self, *args, **kwargs) self._modified() # pylint: disable=protected-access return rval return call_modified_wrapper class MonitoredList(typing.List[_T], typing.Generic[_T]): """ This class can trigger a callback any time its contents are changed with the usual list operations append, extend, etc. """ def _modified(self) -> None: # pylint: disable=method-hidden # monkeypatch used pass def set_modified_callback(self, callback: Callable[[], typing.Any]) -> None: """ Assign a callback function with no parameters that is called any time the list is modified. Callback's return value is ignored. >>> import sys >>> ml = MonitoredList([1,2,3]) >>> ml.set_modified_callback(lambda: sys.stdout.write("modified\\n")) >>> ml MonitoredList([1, 2, 3]) >>> ml.append(10) modified >>> len(ml) 4 >>> ml += [11, 12, 13] modified >>> ml[:] = ml[:2] + ml[-2:] modified >>> ml MonitoredList([1, 2, 12, 13]) """ self._modified = callback # monkeypatch def __repr__(self) -> str: return f"{self.__class__.__name__}({list(self)!r})" # noinspection PyMethodParameters def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: for item in self: yield None, item @_call_modified def __add__(self, __value: list[_T]) -> Self: return super().__add__(__value) @_call_modified def __delitem__(self, __key: typing.SupportsIndex | slice) -> None: super().__delitem__(__key) @_call_modified def __iadd__(self, __value: Iterable[_T]) -> Self: return super().__iadd__(__value) @_call_modified def __rmul__(self, __value: typing.SupportsIndex) -> Self: return super().__rmul__(__value) @_call_modified def __imul__(self, __value: typing.SupportsIndex) -> Self: return super().__imul__(__value) @typing.overload @_call_modified def __setitem__(self, __key: typing.SupportsIndex, __value: _T) -> None: ... @typing.overload @_call_modified def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ... @_call_modified def __setitem__(self, __key: typing.SupportsIndex | slice, __value: _T | Iterable[_T]) -> None: super().__setitem__(__key, __value) @_call_modified def append(self, __object: _T) -> None: super().append(__object) @_call_modified def extend(self, __iterable: Iterable[_T]) -> None: super().extend(__iterable) @_call_modified def pop(self, __index: typing.SupportsIndex = -1) -> _T: return super().pop(__index) @_call_modified def insert(self, __index: typing.SupportsIndex, __object: _T) -> None: super().insert(__index, __object) @_call_modified def remove(self, __value: _T) -> None: super().remove(__value) @_call_modified def reverse(self) -> None: super().reverse() @_call_modified def sort(self, *, key: Callable[[_T], typing.Any] | None = None, reverse: bool = False) -> None: super().sort(key=key, reverse=reverse) @_call_modified def clear(self) -> None: super().clear() class MonitoredFocusList(MonitoredList[_T], typing.Generic[_T]): """ This class can trigger a callback any time its contents are modified, before and/or after modification, and any time the focus index is changed. """ def __init__(self, *args, focus: int = 0, **kwargs) -> None: """ This is a list that tracks one item as the focus item. If items are inserted or removed it will update the focus. >>> ml = MonitoredFocusList([10, 11, 12, 13, 14], focus=3) >>> ml MonitoredFocusList([10, 11, 12, 13, 14], focus=3) >>> del(ml[1]) >>> ml MonitoredFocusList([10, 12, 13, 14], focus=2) >>> ml[:2] = [50, 51, 52, 53] >>> ml MonitoredFocusList([50, 51, 52, 53, 13, 14], focus=4) >>> ml[4] = 99 >>> ml MonitoredFocusList([50, 51, 52, 53, 99, 14], focus=4) >>> ml[:] = [] >>> ml MonitoredFocusList([], focus=None) """ super().__init__(*args, **kwargs) self._focus = focus self._focus_modified = lambda ml, indices, new_items: None def __repr__(self) -> str: return f"{self.__class__.__name__}({list(self)!r}, focus={self.focus!r})" @property def focus(self) -> int | None: """ Get/set the focus index. This value is read as None when the list is empty, and may only be set to a value between 0 and len(self)-1 or an IndexError will be raised. Return the index of the item "in focus" or None if the list is empty. >>> MonitoredFocusList([1,2,3], focus=2).focus 2 >>> MonitoredFocusList().focus """ if not self: return None return self._focus @focus.setter def focus(self, index: int) -> None: """ index -- index into this list, any index out of range will raise an IndexError, except when the list is empty and the index passed is ignored. This function may call self._focus_changed when the focus is modified, passing the new focus position to the callback just before changing the old focus setting. That method may be overridden on the instance with set_focus_changed_callback(). >>> ml = MonitoredFocusList([9, 10, 11]) >>> ml.focus = 2; ml.focus 2 >>> ml.focus = 0; ml.focus 0 >>> ml.focus = -2 Traceback (most recent call last): ... IndexError: focus index is out of range: -2 """ if not self: self._focus = 0 return if not isinstance(index, int): raise TypeError("index must be an integer") if index < 0 or index >= len(self): raise IndexError(f"focus index is out of range: {index}") if index != self._focus: self._focus_changed(index) self._focus = index def _get_focus(self) -> int | None: warnings.warn( f"method `{self.__class__.__name__}._get_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) return self.focus def _set_focus(self, index: int) -> None: warnings.warn( f"method `{self.__class__.__name__}._set_focus` is deprecated, " f"please use `{self.__class__.__name__}.focus` property", DeprecationWarning, stacklevel=3, ) self.focus = index def _focus_changed(self, new_focus: int) -> None: # pylint: disable=method-hidden # monkeypatch used pass def set_focus_changed_callback(self, callback: Callable[[int], typing.Any]) -> None: """ Assign a callback to be called when the focus index changes for any reason. The callback is in the form: callback(new_focus) new_focus -- new focus index >>> import sys >>> ml = MonitoredFocusList([1,2,3], focus=1) >>> ml.set_focus_changed_callback(lambda f: sys.stdout.write("focus: %d\\n" % (f,))) >>> ml MonitoredFocusList([1, 2, 3], focus=1) >>> ml.append(10) >>> ml.insert(1, 11) focus: 2 >>> ml MonitoredFocusList([1, 11, 2, 3, 10], focus=2) >>> del ml[:2] focus: 0 >>> ml[:0] = [12, 13, 14] focus: 3 >>> ml.focus = 5 focus: 5 >>> ml MonitoredFocusList([12, 13, 14, 2, 3, 10], focus=5) """ self._focus_changed = callback # Monkeypatch def _validate_contents_modified( # pylint: disable=method-hidden # monkeypatch used self, indices: tuple[int, int, int], new_items: Collection[_T], ) -> int | None: return None def set_validate_contents_modified(self, callback: Callable[[tuple[int, int, int], Collection[_T]], int | None]): """ Assign a callback function to handle validating changes to the list. This may raise an exception if the change should not be performed. It may also return an integer position to be the new focus after the list is modified, or None to use the default behaviour. The callback is in the form: callback(indices, new_items) indices -- a (start, stop, step) tuple whose range covers the items being modified new_items -- an iterable of items replacing those at range(*indices), empty if items are being removed, if step==1 this list may contain any number of items """ self._validate_contents_modified = callback # Monkeypatch def _adjust_focus_on_contents_modified(self, slc: slice, new_items: Collection[_T] = ()) -> int: """ Default behaviour is to move the focus to the item following any removed items, unless that item was simply replaced. Failing that choose the last item in the list. returns focus position for after change is applied """ num_new_items = len(new_items) start, stop, step = indices = slc.indices(len(self)) num_removed = len(list(range(*indices))) focus = self._validate_contents_modified(indices, new_items) if focus is not None: return focus focus = self._focus if step == 1: if start + num_new_items <= focus < stop: focus = stop # adjust for added/removed items if stop <= focus: focus += num_new_items - (stop - start) else: # noqa: PLR5501 # pylint: disable=else-if-used # readability if not num_new_items: # extended slice being removed if focus in range(start, stop, step): focus += 1 # adjust for removed items focus -= len(list(range(start, min(focus, stop), step))) return min(focus, len(self) + num_new_items - num_removed - 1) # override all the list methods that modify the list def __delitem__(self, y: int | slice) -> None: """ >>> ml = MonitoredFocusList([0,1,2,3,4], focus=2) >>> del ml[3]; ml MonitoredFocusList([0, 1, 2, 4], focus=2) >>> del ml[-1]; ml MonitoredFocusList([0, 1, 2], focus=2) >>> del ml[0]; ml MonitoredFocusList([1, 2], focus=1) >>> del ml[1]; ml MonitoredFocusList([1], focus=0) >>> del ml[0]; ml MonitoredFocusList([], focus=None) >>> ml = MonitoredFocusList([5,4,6,4,5,4,6,4,5], focus=4) >>> del ml[1::2]; ml MonitoredFocusList([5, 6, 5, 6, 5], focus=2) >>> del ml[::2]; ml MonitoredFocusList([6, 6], focus=1) >>> ml = MonitoredFocusList([0,1,2,3,4,6,7], focus=2) >>> del ml[-2:]; ml MonitoredFocusList([0, 1, 2, 3, 4], focus=2) >>> del ml[-4:-2]; ml MonitoredFocusList([0, 3, 4], focus=1) >>> del ml[:]; ml MonitoredFocusList([], focus=None) """ if isinstance(y, slice): focus = self._adjust_focus_on_contents_modified(y) else: focus = self._adjust_focus_on_contents_modified(slice(y, y + 1 or None)) super().__delitem__(y) self.focus = focus @typing.overload def __setitem__(self, i: int, y: _T) -> None: ... @typing.overload def __setitem__(self, i: slice, y: Collection[_T]) -> None: ... def __setitem__(self, i: int | slice, y: _T | Collection[_T]) -> None: """ >>> def modified(indices, new_items): ... print(f"range{indices!r} <- {new_items!r}" ) >>> ml = MonitoredFocusList([0,1,2,3], focus=2) >>> ml.set_validate_contents_modified(modified) >>> ml[0] = 9 range(0, 1, 1) <- [9] >>> ml[2] = 6 range(2, 3, 1) <- [6] >>> ml.focus 2 >>> ml[-1] = 8 range(3, 4, 1) <- [8] >>> ml MonitoredFocusList([9, 1, 6, 8], focus=2) >>> ml[1::2] = [12, 13] range(1, 4, 2) <- [12, 13] >>> ml[::2] = [10, 11] range(0, 4, 2) <- [10, 11] >>> ml[-3:-1] = [21, 22, 23] range(1, 3, 1) <- [21, 22, 23] >>> ml MonitoredFocusList([10, 21, 22, 23, 13], focus=2) >>> ml[:] = [] range(0, 5, 1) <- [] >>> ml MonitoredFocusList([], focus=None) """ if isinstance(i, slice): focus = self._adjust_focus_on_contents_modified(i, y) else: focus = self._adjust_focus_on_contents_modified(slice(i, i + 1 or None), [y]) super().__setitem__(i, y) self.focus = focus def __imul__(self, n: int): """ >>> def modified(indices, new_items): ... print(f"range{indices!r} <- {list(new_items)!r}" ) >>> ml = MonitoredFocusList([0,1,2], focus=2) >>> ml.set_validate_contents_modified(modified) >>> ml *= 3 range(3, 3, 1) <- [0, 1, 2, 0, 1, 2] >>> ml MonitoredFocusList([0, 1, 2, 0, 1, 2, 0, 1, 2], focus=2) >>> ml *= 0 range(0, 9, 1) <- [] >>> print(ml.focus) None """ if n > 0: focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), list(self) * (n - 1)) else: # all contents are being removed focus = self._adjust_focus_on_contents_modified(slice(0, len(self))) rval = super().__imul__(n) self.focus = focus return rval def append(self, item: _T) -> None: """ >>> def modified(indices, new_items): ... print(f"range{indices!r} <- {new_items!r}" ) >>> ml = MonitoredFocusList([0,1,2], focus=2) >>> ml.set_validate_contents_modified(modified) >>> ml.append(6) range(3, 3, 1) <- [6] """ focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), [item]) super().append(item) self.focus = focus def extend(self, items: Collection[_T]) -> None: """ >>> def modified(indices, new_items): ... print(f"range{indices!r} <- {list(new_items)!r}" ) >>> ml = MonitoredFocusList([0,1,2], focus=2) >>> ml.set_validate_contents_modified(modified) >>> ml.extend((6,7,8)) range(3, 3, 1) <- [6, 7, 8] """ focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), items) super().extend(items) self.focus = focus def insert(self, index: int, item: _T) -> None: """ >>> ml = MonitoredFocusList([0,1,2,3], focus=2) >>> ml.insert(-1, -1); ml MonitoredFocusList([0, 1, 2, -1, 3], focus=2) >>> ml.insert(0, -2); ml MonitoredFocusList([-2, 0, 1, 2, -1, 3], focus=3) >>> ml.insert(3, -3); ml MonitoredFocusList([-2, 0, 1, -3, 2, -1, 3], focus=4) """ focus = self._adjust_focus_on_contents_modified(slice(index, index), [item]) super().insert(index, item) self.focus = focus def pop(self, index: int = -1) -> _T: """ >>> ml = MonitoredFocusList([-2,0,1,-3,2,3], focus=4) >>> ml.pop(3); ml -3 MonitoredFocusList([-2, 0, 1, 2, 3], focus=3) >>> ml.pop(0); ml -2 MonitoredFocusList([0, 1, 2, 3], focus=2) >>> ml.pop(-1); ml 3 MonitoredFocusList([0, 1, 2], focus=2) >>> ml.pop(2); ml 2 MonitoredFocusList([0, 1], focus=1) """ focus = self._adjust_focus_on_contents_modified(slice(index, index + 1 or None)) rval = super().pop(index) self.focus = focus return rval def remove(self, value: _T) -> None: """ >>> ml = MonitoredFocusList([-2,0,1,-3,2,-1,3], focus=4) >>> ml.remove(-3); ml MonitoredFocusList([-2, 0, 1, 2, -1, 3], focus=3) >>> ml.remove(-2); ml MonitoredFocusList([0, 1, 2, -1, 3], focus=2) >>> ml.remove(3); ml MonitoredFocusList([0, 1, 2, -1], focus=2) """ index = self.index(value) focus = self._adjust_focus_on_contents_modified(slice(index, index + 1 or None)) super().remove(value) self.focus = focus def reverse(self) -> None: """ >>> ml = MonitoredFocusList([0,1,2,3,4], focus=1) >>> ml.reverse(); ml MonitoredFocusList([4, 3, 2, 1, 0], focus=3) """ rval = super().reverse() self.focus = max(0, len(self) - self._focus - 1) return rval def sort(self, **kwargs) -> None: """ >>> ml = MonitoredFocusList([-2,0,1,-3,2,-1,3], focus=4) >>> ml.sort(); ml MonitoredFocusList([-3, -2, -1, 0, 1, 2, 3], focus=5) """ if not self: return None value = self[self._focus] rval = super().sort(**kwargs) self.focus = self.index(value) return rval if hasattr(list, "clear"): def clear(self) -> None: focus = self._adjust_focus_on_contents_modified(slice(0, 0)) super().clear() self.focus = focus def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
19,264
Python
.py
485
31.369072
117
0.558896
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,269
padding.py
urwid_urwid/urwid/widget/padding.py
from __future__ import annotations import typing import warnings from urwid.canvas import CompositeCanvas, SolidCanvas from urwid.split_repr import remove_defaults from urwid.util import int_scale from .constants import ( RELATIVE_100, Align, Sizing, WHSettings, normalize_align, normalize_width, simplify_align, simplify_width, ) from .widget_decoration import WidgetDecoration, WidgetError, WidgetWarning if typing.TYPE_CHECKING: from collections.abc import Iterator from typing_extensions import Literal WrappedWidget = typing.TypeVar("WrappedWidget") class PaddingError(WidgetError): """Padding related errors.""" class PaddingWarning(WidgetWarning): """Padding related warnings.""" class Padding(WidgetDecoration[WrappedWidget], typing.Generic[WrappedWidget]): def __init__( self, w: WrappedWidget, align: ( Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE, "fixed left", "fixed right"], int] ) = Align.LEFT, width: ( int | Literal["pack", "clip", WHSettings.PACK, WHSettings.CLIP] | tuple[Literal["relative", WHSettings.RELATIVE, "fixed left", "fixed right"], int] ) = RELATIVE_100, min_width: int | None = None, left: int = 0, right: int = 0, ) -> None: """ :param w: a box, flow or fixed widget to pad on the left and/or right this widget is stored as self.original_widget :type w: Widget :param align: one of: ``'left'``, ``'center'``, ``'right'`` (``'relative'``, *percentage* 0=left 100=right) :param width: one of: *given width* integer number of columns for self.original_widget ``'pack'`` try to pack self.original_widget to its ideal size (``'relative'``, *percentage of total width*) make width depend on the container's width ``'clip'`` to enable clipping mode for a fixed widget :param min_width: the minimum number of columns for self.original_widget or ``None`` :type min_width: int | None :param left: a fixed number of columns to pad on the left :type left: int :param right: a fixed number of columns to pad on the right :type right: int Clipping Mode: (width= ``'clip'``) In clipping mode this padding widget will behave as a flow widget and self.original_widget will be treated as a fixed widget. self.original_widget will be clipped to fit the available number of columns. For example if align is ``'left'`` then self.original_widget may be clipped on the right. Pack Mode: (width= ``'pack'``) In pack mode is supported FIXED operation if it is supported by the original widget. >>> from urwid import Divider, Text, BigText, FontRegistry >>> from urwid.util import set_temporary_encoding >>> size = (7,) >>> def pr(w): ... with set_temporary_encoding("utf-8"): ... for t in w.render(size).text: ... print(f"|{t.decode('utf-8')}|" ) >>> pr(Padding(Text(u"Head"), ('relative', 20), 'pack')) | Head | >>> pr(Padding(Divider(u"-"), left=2, right=1)) | ---- | >>> pr(Padding(Divider(u"*"), 'center', 3)) | *** | >>> p=Padding(Text(u"1234"), 'left', 2, None, 1, 1) >>> p <Padding fixed/flow widget <Text fixed/flow widget '1234'> left=1 right=1 width=2> >>> pr(p) # align against left | 12 | | 34 | >>> p.align = 'right' >>> pr(p) # align against right | 12 | | 34 | >>> pr(Padding(Text(u"hi\\nthere"), 'right', 'pack')) # pack text first | hi | | there| >>> pr(Padding(BigText("1,2,3", FontRegistry['Thin 3x3']()), width="clip")) | ┐ ┌─┐| | │ ┌─┘| | ┴ ,└─ | """ super().__init__(w) # convert obsolete parameters 'fixed left' and 'fixed right': if isinstance(align, tuple) and align[0] in {"fixed left", "fixed right"}: if align[0] == "fixed left": left = align[1] align = Align.LEFT else: right = align[1] align = Align.RIGHT if isinstance(width, tuple) and width[0] in {"fixed left", "fixed right"}: if width[0] == "fixed left": left = width[1] else: right = width[1] width = RELATIVE_100 # convert old clipping mode width=None to width='clip' if width is None: width = WHSettings.CLIP self.left = left self.right = right self._align_type, self._align_amount = normalize_align(align, PaddingError) self._width_type, self._width_amount = normalize_width(width, PaddingError) self.min_width = min_width def sizing(self) -> frozenset[Sizing]: """Widget sizing. Rules: * width == CLIP: only FLOW is supported, and wrapped widget should support FIXED * width == GIVEN: FIXED is supported, and wrapped widget should support FLOW * All other cases: use sizing of target widget """ if self._width_type == WHSettings.CLIP: return frozenset((Sizing.FLOW,)) sizing = set(self.original_widget.sizing()) if self._width_type == WHSettings.GIVEN: if Sizing.FLOW in sizing: sizing.add(Sizing.FIXED) elif Sizing.BOX not in sizing: warnings.warn( f"WHSettings.GIVEN expect BOX or FLOW widget to be used, but received {self.original_widget}", PaddingWarning, stacklevel=3, ) return frozenset(sizing) def _repr_attrs(self) -> dict[str, typing.Any]: attrs = { **super()._repr_attrs(), "align": self.align, "width": self.width, "left": self.left, "right": self.right, "min_width": self.min_width, } return remove_defaults(attrs, Padding.__init__) def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]: yield "w", self.original_widget yield "align", self.align yield "width", self.width yield "min_width", self.min_width yield "left", self.left yield "right", self.right @property def align( self, ) -> Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int]: """ Return the padding alignment setting. """ return simplify_align(self._align_type, self._align_amount) @align.setter def align( self, align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int] ) -> None: """ Set the padding alignment. """ self._align_type, self._align_amount = normalize_align(align, PaddingError) self._invalidate() def _get_align(self) -> Literal["left", "center", "right"] | tuple[Literal["relative"], int]: warnings.warn( f"Method `{self.__class__.__name__}._get_align` is deprecated, " f"please use property `{self.__class__.__name__}.align`", DeprecationWarning, stacklevel=2, ) return self.align def _set_align(self, align: Literal["left", "center", "right"] | tuple[Literal["relative"], int]) -> None: warnings.warn( f"Method `{self.__class__.__name__}._set_align` is deprecated, " f"please use property `{self.__class__.__name__}.align`", DeprecationWarning, stacklevel=2, ) self.align = align @property def width( self, ) -> ( Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] ): """ Return the padding width. """ return simplify_width(self._width_type, self._width_amount) @width.setter def width( self, width: ( Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] ), ) -> None: """ Set the padding width. """ self._width_type, self._width_amount = normalize_width(width, PaddingError) self._invalidate() def _get_width(self) -> Literal["clip", "pack"] | int | tuple[Literal["relative"], int]: warnings.warn( f"Method `{self.__class__.__name__}._get_width` is deprecated, " f"please use property `{self.__class__.__name__}.width`", DeprecationWarning, stacklevel=2, ) return self.width def _set_width(self, width: Literal["clip", "pack"] | int | tuple[Literal["relative"], int]) -> None: warnings.warn( f"Method `{self.__class__.__name__}._set_width` is deprecated, " f"please use property `{self.__class__.__name__}.width`", DeprecationWarning, stacklevel=2, ) self.width = width def pack( self, size: tuple[()] | tuple[int] | tuple[int, int] = (), focus: bool = False, ) -> tuple[int, int]: if size: return super().pack(size, focus) if self._width_type == WHSettings.CLIP: raise PaddingError("WHSettings.CLIP makes Padding FLOW-only widget") expand = self.left + self.right w_sizing = self.original_widget.sizing() if self._width_type == WHSettings.GIVEN: if Sizing.FLOW not in w_sizing: warnings.warn( f"WHSettings.GIVEN expect FLOW widget to be used for FIXED pack/render, " f"but received {self.original_widget}", PaddingWarning, stacklevel=3, ) return ( max(self._width_amount, self.min_width or 1) + expand, self.original_widget.rows((self._width_amount,), focus), ) if Sizing.FIXED not in w_sizing: warnings.warn( f"Padded widget should support FIXED sizing for FIXED render, but received {self.original_widget}", PaddingWarning, stacklevel=3, ) width, height = self.original_widget.pack(size, focus) if self._width_type == WHSettings.PACK: return max(width, self.min_width or 1) + expand, height if self._width_type == WHSettings.RELATIVE: return max(int(width * 100 / self._width_amount + 0.5), self.min_width or 1) + expand, height raise PaddingError(f"Unexpected width type: {self._width_type.upper()})") def render( self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False, ) -> CompositeCanvas: left, right = self.padding_values(size, focus) if self._width_type == WHSettings.CLIP: canv = self._original_widget.render((), focus) elif size: maxcol = size[0] - (left + right) if self._width_type == WHSettings.GIVEN and maxcol < self._width_amount: warnings.warn( f"{self}.render(size={size}, focus={focus}): too narrow size ({maxcol!r} < {self._width_amount!r})", PaddingWarning, stacklevel=3, ) canv = self._original_widget.render((maxcol,) + size[1:], focus) elif self._width_type == WHSettings.GIVEN: canv = self._original_widget.render((self._width_amount,) + size[1:], focus) else: canv = self._original_widget.render((), focus) if canv.cols() == 0: canv = SolidCanvas(" ", size[0], canv.rows()) canv = CompositeCanvas(canv) canv.set_depends([self._original_widget]) return canv canv = CompositeCanvas(canv) canv.set_depends([self._original_widget]) if left != 0 or right != 0: canv.pad_trim_left_right(left, right) return canv def padding_values( self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool, ) -> tuple[int, int]: """Return the number of columns to pad on the left and right. Override this method to define custom padding behaviour.""" if self._width_type == WHSettings.CLIP: width, _ignore = self._original_widget.pack((), focus=focus) if not size: raise PaddingError("WHSettings.CLIP makes Padding FLOW-only widget") return calculate_left_right_padding( size[0], self._align_type, self._align_amount, WHSettings.CLIP, width, None, self.left, self.right, ) if self._width_type == WHSettings.PACK: if size: maxcol = size[0] maxwidth = max(maxcol - self.left - self.right, self.min_width or 0) (width, _ignore) = self._original_widget.pack((maxwidth,), focus=focus) else: (width, _ignore) = self._original_widget.pack((), focus=focus) maxcol = width + self.left + self.right return calculate_left_right_padding( maxcol, self._align_type, self._align_amount, WHSettings.GIVEN, width, self.min_width, self.left, self.right, ) if size: maxcol = size[0] elif self._width_type == WHSettings.GIVEN: maxcol = self._width_amount + self.left + self.right else: maxcol = ( max(self._original_widget.pack((), focus=focus)[0] * 100 // self._width_amount, self.min_width or 1) + self.left + self.right ) return calculate_left_right_padding( maxcol, self._align_type, self._align_amount, self._width_type, self._width_amount, self.min_width, self.left, self.right, ) def rows(self, size: tuple[int], focus: bool = False) -> int: """Return the rows needed for self.original_widget.""" (maxcol,) = size left, right = self.padding_values(size, focus) if self._width_type == WHSettings.PACK: _pcols, prows = self._original_widget.pack((maxcol - left - right,), focus) return prows if self._width_type == WHSettings.CLIP: _fcols, frows = self._original_widget.pack((), focus) return frows return self._original_widget.rows((maxcol - left - right,), focus=focus) def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None: """Pass keypress to self._original_widget.""" left, right = self.padding_values(size, True) if size: maxvals = (size[0] - left - right,) + size[1:] return self._original_widget.keypress(maxvals, key) return self._original_widget.keypress((), key) def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None: """Return the (x,y) coordinates of cursor within self._original_widget.""" if not hasattr(self._original_widget, "get_cursor_coords"): return None left, right = self.padding_values(size, True) if size: maxvals = (size[0] - left - right,) + size[1:] if maxvals[0] == 0: return None else: maxvals = () coords = self._original_widget.get_cursor_coords(maxvals) if coords is None: return None x, y = coords return x + left, y def move_cursor_to_coords( self, size: tuple[()] | tuple[int] | tuple[int, int], x: int, y: int, ) -> bool: """Set the cursor position with (x,y) coordinates of self._original_widget. Returns True if move succeeded, False otherwise. """ if not hasattr(self._original_widget, "move_cursor_to_coords"): return True left, right = self.padding_values(size, True) if size: maxcol = size[0] maxvals = (maxcol - left - right,) + size[1:] else: maxcol = self.pack((), True)[0] maxvals = () if isinstance(x, int): if x < left: x = left elif x >= maxcol - right: x = maxcol - right - 1 x -= left return self._original_widget.move_cursor_to_coords(maxvals, x, y) def mouse_event( self, size: tuple[()] | tuple[int] | tuple[int, int], event: str, button: int, col: int, row: int, focus: bool, ) -> bool | None: """Send mouse event if position is within self._original_widget.""" if not hasattr(self._original_widget, "mouse_event"): return False left, right = self.padding_values(size, focus) if size: maxcol = size[0] if col < left or col >= maxcol - right: return False maxvals = (maxcol - left - right,) + size[1:] else: maxvals = () return self._original_widget.mouse_event(maxvals, event, button, col - left, row, focus) def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int | None: """Return the preferred column from self._original_widget, or None.""" if not hasattr(self._original_widget, "get_pref_col"): return None left, right = self.padding_values(size, True) if size: maxvals = (size[0] - left - right,) + size[1:] else: maxvals = () x = self._original_widget.get_pref_col(maxvals) if isinstance(x, int): return x + left return x def calculate_left_right_padding( maxcol: int, align_type: Literal["left", "center", "right"] | Align, align_amount: int, width_type: Literal["fixed", "relative", "clip", "given", WHSettings.RELATIVE, WHSettings.CLIP, WHSettings.GIVEN], width_amount: int, min_width: int | None, left: int, right: int, ) -> tuple[int, int]: """ Return the amount of padding (or clipping) on the left and right part of maxcol columns to satisfy the following: align_type -- 'left', 'center', 'right', 'relative' align_amount -- a percentage when align_type=='relative' width_type -- 'fixed', 'relative', 'clip' width_amount -- a percentage when width_type=='relative' otherwise equal to the width of the widget min_width -- a desired minimum width for the widget or None left -- a fixed number of columns to pad on the left right -- a fixed number of columns to pad on the right >>> clrp = calculate_left_right_padding >>> clrp(15, 'left', 0, 'given', 10, None, 2, 0) (2, 3) >>> clrp(15, 'relative', 0, 'given', 10, None, 2, 0) (2, 3) >>> clrp(15, 'relative', 100, 'given', 10, None, 2, 0) (5, 0) >>> clrp(15, 'center', 0, 'given', 4, None, 2, 0) (6, 5) >>> clrp(15, 'left', 0, 'clip', 18, None, 0, 0) (0, -3) >>> clrp(15, 'right', 0, 'clip', 18, None, 0, -1) (-2, -1) >>> clrp(15, 'center', 0, 'given', 18, None, 2, 0) (0, 0) >>> clrp(20, 'left', 0, 'relative', 60, None, 0, 0) (0, 8) >>> clrp(20, 'relative', 30, 'relative', 60, None, 0, 0) (2, 6) >>> clrp(20, 'relative', 30, 'relative', 60, 14, 0, 0) (2, 4) """ if width_type == WHSettings.RELATIVE: maxwidth = max(maxcol - left - right, 0) width = int(maxwidth * width_amount / 100 + 0.5) if min_width is not None: width = max(width, min_width) else: width = width_amount align = {Align.LEFT: 0, Align.CENTER: 50, Align.RIGHT: 100}.get(align_type, align_amount) # add the remainder of left/right the padding padding = maxcol - width - left - right right += int_scale(100 - align, 101, padding + 1) left = maxcol - width - right # reduce padding if we are clipping an edge if right < 0 < left: shift = min(left, -right) left -= shift right += shift elif left < 0 < right: shift = min(right, -left) right -= shift left += shift # only clip if width_type == 'clip' if width_type != WHSettings.CLIP and (left < 0 or right < 0): left = max(left, 0) right = max(right, 0) return left, right
21,334
Python
.py
525
30.567619
120
0.554686
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,270
progress_bar.py
urwid_urwid/urwid/widget/progress_bar.py
from __future__ import annotations import typing import warnings from .constants import BAR_SYMBOLS, Align, Sizing, WrapMode from .text import Text from .widget import Widget if typing.TYPE_CHECKING: from collections.abc import Hashable from urwid.canvas import TextCanvas class ProgressBar(Widget): _sizing = frozenset([Sizing.FLOW]) eighths = BAR_SYMBOLS.HORISONTAL[:8] # Full width line is made by style text_align = Align.CENTER def __init__( self, normal: Hashable | None, complete: Hashable | None, current: int = 0, done: int = 100, satt: Hashable | None = None, ) -> None: """ :param normal: display attribute for incomplete part of progress bar :param complete: display attribute for complete part of progress bar :param current: current progress :param done: progress amount at 100% :param satt: display attribute for smoothed part of bar where the foreground of satt corresponds to the normal part and the background corresponds to the complete part. If satt is ``None`` then no smoothing will be done. >>> from urwid import LineBox >>> pb = ProgressBar('a', 'b') >>> pb <ProgressBar flow widget> >>> print(pb.get_text()) 0 % >>> pb.set_completion(34.42) >>> print(pb.get_text()) 34 % >>> class CustomProgressBar(ProgressBar): ... def get_text(self): ... return u'Foobar' >>> cpb = CustomProgressBar('a', 'b') >>> print(cpb.get_text()) Foobar >>> for x in range(101): ... cpb.set_completion(x) ... s = cpb.render((10, )) >>> cpb2 = CustomProgressBar('a', 'b', satt='c') >>> for x in range(101): ... cpb2.set_completion(x) ... s = cpb2.render((10, )) >>> pb = ProgressBar('a', 'b', satt='c') >>> pb.set_completion(34.56) >>> print(LineBox(pb).render((20,))) ┌──────────────────┐ │ ▏34 % │ └──────────────────┘ """ super().__init__() self.normal = normal self.complete = complete self._current = current self._done = done self.satt = satt def set_completion(self, current: int) -> None: """ current -- current progress """ self._current = current self._invalidate() current = property(lambda self: self._current, set_completion) @property def done(self): return self._done @done.setter def done(self, done): """ done -- progress amount at 100% """ self._done = done self._invalidate() def _set_done(self, done): warnings.warn( f"Method `{self.__class__.__name__}._set_done` is deprecated, " f"please use property `{self.__class__.__name__}.done`", DeprecationWarning, stacklevel=2, ) self.done = done def rows(self, size: tuple[int], focus: bool = False) -> int: return 1 def get_text(self) -> str: """ Return the progress bar percentage text. You can override this method to display custom text. """ percent = min(100, max(0, int(self.current * 100 / self.done))) return f"{percent!s} %" def render( self, size: tuple[int], # type: ignore[override] focus: bool = False, ) -> TextCanvas: """ Render the progress bar. """ # pylint: disable=protected-access (maxcol,) = size c = Text(self.get_text(), self.text_align, WrapMode.CLIP).render((maxcol,)) cf = float(self.current) * maxcol / self.done ccol_dirty = int(cf) ccol = len(c._text[0][:ccol_dirty].decode("utf-8", "ignore").encode("utf-8")) cs = 0 if self.satt is not None: cs = int((cf - ccol) * 8) if ccol < 0 or (ccol == cs == 0): c._attr = [[(self.normal, maxcol)]] elif ccol >= maxcol: c._attr = [[(self.complete, maxcol)]] elif cs and c._text[0][ccol] == 32: t = c._text[0] cenc = self.eighths[cs].encode("utf-8") c._text[0] = t[:ccol] + cenc + t[ccol + 1 :] a = [] if ccol > 0: a.append((self.complete, ccol)) a.append((self.satt, len(cenc))) if maxcol - ccol - 1 > 0: a.append((self.normal, maxcol - ccol - 1)) c._attr = [a] c._cs = [[(None, len(c._text[0]))]] else: c._attr = [[(self.complete, ccol), (self.normal, maxcol - ccol)]] return c
4,925
Python
.py
135
26.8
85
0.528282
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,271
wimp.py
urwid_urwid/urwid/widget/wimp.py
# Urwid Window-Icon-Menu-Pointer-style widget classes # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import typing from urwid.canvas import CompositeCanvas from urwid.command_map import Command from urwid.signals import connect_signal from urwid.text_layout import calc_coords from urwid.util import is_mouse_press from .columns import Columns from .constants import Align, WrapMode from .text import Text from .widget import WidgetError, WidgetWrap if typing.TYPE_CHECKING: from collections.abc import Callable, Hashable, MutableSequence from typing_extensions import Literal, Self from urwid.canvas import TextCanvas from urwid.text_layout import TextLayout _T = typing.TypeVar("_T") class SelectableIcon(Text): ignore_focus = False _selectable = True def __init__( self, text: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], cursor_position: int = 0, align: Literal["left", "center", "right"] | Align = Align.LEFT, wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE, layout: TextLayout | None = None, ) -> None: """ :param text: markup for this widget; see :class:`Text` for description of text markup :param cursor_position: position the cursor will appear in the text when this widget is in focus :param align: typically ``'left'``, ``'center'`` or ``'right'`` :type align: text alignment mode :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'`` :type wrap: text wrapping mode :param layout: defaults to a shared :class:`StandardTextLayout` instance :type layout: text layout instance This is a text widget that is selectable. A cursor displayed at a fixed location in the text when in focus. This widget has no special handling of keyboard or mouse input. """ super().__init__(text, align=align, wrap=wrap, layout=layout) self._cursor_position = cursor_position def render( # type: ignore[override] self, size: tuple[int] | tuple[()], # type: ignore[override] focus: bool = False, ) -> TextCanvas | CompositeCanvas: # type: ignore[override] """ Render the text content of this widget with a cursor when in focus. >>> si = SelectableIcon(u"[!]") >>> si <SelectableIcon selectable fixed/flow widget '[!]'> >>> si.render((4,), focus=True).cursor (0, 0) >>> si = SelectableIcon("((*))", 2) >>> si.render((8,), focus=True).cursor (2, 0) >>> si.render((2,), focus=True).cursor (0, 1) >>> si.render(()).cursor >>> si.render(()).text [b'((*))'] >>> si.render((), focus=True).cursor (2, 0) """ c: TextCanvas | CompositeCanvas = super().render(size, focus) if focus: # create a new canvas so we can add a cursor c = CompositeCanvas(c) c.cursor = self.get_cursor_coords(size) return c def get_cursor_coords(self, size: tuple[int] | tuple[()]) -> tuple[int, int] | None: """ Return the position of the cursor if visible. This method is required for widgets that display a cursor. """ if self._cursor_position > len(self.text): return None # find out where the cursor will be displayed based on # the text layout if size: (maxcol,) = size else: maxcol, _ = self.pack() trans = self.get_line_translation(maxcol) x, y = calc_coords(self.text, trans, self._cursor_position) if maxcol <= x: return None return x, y def keypress( self, size: tuple[int] | tuple[()], # type: ignore[override] key: str, ) -> str: """ No keys are handled by this widget. This method is required for selectable widgets. """ return key class CheckBoxError(WidgetError): pass class CheckBox(WidgetWrap[Columns]): states: typing.ClassVar[dict[bool | Literal["mixed"], SelectableIcon]] = { True: SelectableIcon("[X]", 1), False: SelectableIcon("[ ]", 1), "mixed": SelectableIcon("[#]", 1), } reserve_columns = 4 # allow users of this class to listen for change events # sent when the state of this widget is modified # (this variable is picked up by the MetaSignals metaclass) signals: typing.ClassVar[list[str]] = ["change", "postchange"] @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool = False, has_mixed: typing.Literal[False] = False, on_state_change: Callable[[Self, bool, _T], typing.Any] | None = None, user_data: _T = ..., checked_symbol: str | None = ..., ) -> None: ... @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool = False, has_mixed: typing.Literal[False] = False, on_state_change: Callable[[Self, bool], typing.Any] | None = None, user_data: None = None, checked_symbol: str | None = ..., ) -> None: ... @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: typing.Literal["mixed"] | bool = False, has_mixed: typing.Literal[True] = True, on_state_change: Callable[[Self, bool | typing.Literal["mixed"], _T], typing.Any] | None = None, user_data: _T = ..., checked_symbol: str | None = ..., ) -> None: ... @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: typing.Literal["mixed"] | bool = False, has_mixed: typing.Literal[True] = True, on_state_change: Callable[[Self, bool | typing.Literal["mixed"]], typing.Any] | None = None, user_data: None = None, checked_symbol: str | None = ..., ) -> None: ... def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool | Literal["mixed"] = False, has_mixed: typing.Literal[False, True] = False, # MyPy issue: Literal[True, False] is not equal `bool` on_state_change: ( Callable[[Self, bool, _T], typing.Any] | Callable[[Self, bool], typing.Any] | Callable[[Self, bool | typing.Literal["mixed"], _T], typing.Any] | Callable[[Self, bool | typing.Literal["mixed"]], typing.Any] | None ) = None, user_data: _T | None = None, checked_symbol: str | None = None, ): """ :param label: markup for check box label :param state: False, True or "mixed" :param has_mixed: True if "mixed" is a state to cycle through :param on_state_change: shorthand for connect_signal() function call for a single callback :param user_data: user_data for on_state_change ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside Signals supported: ``'change'``, ``"postchange"`` Register signal handler with:: urwid.connect_signal(check_box, 'change', callback, user_data) where callback is callback(check_box, new_state [,user_data]) Unregister signal handlers with:: urwid.disconnect_signal(check_box, 'change', callback, user_data) >>> CheckBox("Confirm") <CheckBox selectable fixed/flow widget 'Confirm' state=False> >>> CheckBox("Yogourt", "mixed", True) <CheckBox selectable fixed/flow widget 'Yogourt' state='mixed'> >>> cb = CheckBox("Extra onions", True) >>> cb <CheckBox selectable fixed/flow widget 'Extra onions' state=True> >>> cb.render((20,), focus=True).text [b'[X] Extra onions '] >>> CheckBox("Test", None) Traceback (most recent call last): ... ValueError: None not in (True, False, 'mixed') """ if state not in self.states: raise ValueError(f"{state!r} not in {tuple(self.states.keys())}") self._label = Text(label) self.has_mixed = has_mixed self._state = state if checked_symbol: self.states[True] = SelectableIcon(f"[{checked_symbol}]", 1) # The old way of listening for a change was to pass the callback # in to the constructor. Just convert it to the new way: if on_state_change: connect_signal(self, "change", on_state_change, user_data) # Initial create expect no callbacks call, create explicit super().__init__( Columns( [(self.reserve_columns, self.states[state]), self._label], focus_column=0, ), ) def pack(self, size: tuple[()] | tuple[int] | None = None, focus: bool = False) -> tuple[str, str]: """Pack for widget. :param size: size data. Special case: None - get minimal widget size to fit :param focus: widget is focused >>> cb = CheckBox("test") >>> cb.pack((10,)) (10, 1) >>> cb.pack() (8, 1) >>> ml_cb = CheckBox("Multi\\nline\\ncheckbox") >>> ml_cb.pack() (12, 3) >>> ml_cb.pack((), True) (12, 3) """ return super().pack(size or (), focus) def _repr_words(self) -> list[str]: return [*super()._repr_words(), repr(self.label)] def _repr_attrs(self) -> dict[str, typing.Any]: return {**super()._repr_attrs(), "state": self.state} def set_label(self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]): """ Change the check box label. label -- markup for label. See Text widget for description of text markup. >>> cb = CheckBox(u"foo") >>> cb <CheckBox selectable fixed/flow widget 'foo' state=False> >>> cb.set_label(('bright_attr', u"bar")) >>> cb <CheckBox selectable fixed/flow widget 'bar' state=False> """ self._label.set_text(label) # no need to call self._invalidate(). WidgetWrap takes care of # that when self.w changes def get_label(self): """ Return label text. >>> cb = CheckBox(u"Seriously") >>> print(cb.get_label()) Seriously >>> print(cb.label) Seriously >>> cb.set_label([('bright_attr', u"flashy"), u" normal"]) >>> print(cb.label) # only text is returned flashy normal """ return self._label.text label = property(get_label) def set_state( self, state: bool | Literal["mixed"], do_callback: bool = True, ) -> None: """ Set the CheckBox state. state -- True, False or "mixed" do_callback -- False to suppress signal from this change >>> from urwid import disconnect_signal >>> changes = [] >>> def callback_a(user_data, cb, state): ... changes.append("A %r %r" % (state, user_data)) >>> def callback_b(cb, state): ... changes.append("B %r" % state) >>> cb = CheckBox('test', False, False) >>> key1 = connect_signal(cb, 'change', callback_a, user_args=("user_a",)) >>> key2 = connect_signal(cb, 'change', callback_b) >>> cb.set_state(True) # both callbacks will be triggered >>> cb.state True >>> disconnect_signal(cb, 'change', callback_a, user_args=("user_a",)) >>> cb.state = False >>> cb.state False >>> cb.set_state(True) >>> cb.state True >>> cb.set_state(False, False) # don't send signal >>> changes ["A True 'user_a'", 'B True', 'B False', 'B True'] """ if self._state == state: return if state not in self.states: raise CheckBoxError(f"{self!r} Invalid state: {state!r}") # self._state is None is a special case when the CheckBox # has just been created old_state = self._state if do_callback: self._emit("change", state) self._state = state # rebuild the display widget with the new state self._w = Columns([(self.reserve_columns, self.states[state]), self._label], focus_column=0) if do_callback: self._emit("postchange", old_state) def get_state(self) -> bool | Literal["mixed"]: """Return the state of the checkbox.""" return self._state state = property(get_state, set_state) def keypress(self, size: tuple[int], key: str) -> str | None: """ Toggle state on 'activate' command. >>> assert CheckBox._command_map[' '] == 'activate' >>> assert CheckBox._command_map['enter'] == 'activate' >>> size = (10,) >>> cb = CheckBox('press me') >>> cb.state False >>> cb.keypress(size, ' ') >>> cb.state True >>> cb.keypress(size, ' ') >>> cb.state False """ if self._command_map[key] != Command.ACTIVATE: return key self.toggle_state() return None def toggle_state(self) -> None: """ Cycle to the next valid state. >>> cb = CheckBox("3-state", has_mixed=True) >>> cb.state False >>> cb.toggle_state() >>> cb.state True >>> cb.toggle_state() >>> cb.state 'mixed' >>> cb.toggle_state() >>> cb.state False """ if self.state is False: self.set_state(True) elif self.state is True: if self.has_mixed: self.set_state("mixed") else: self.set_state(False) elif self.state == "mixed": self.set_state(False) def mouse_event(self, size: tuple[int], event: str, button: int, x: int, y: int, focus: bool) -> bool: """ Toggle state on button 1 press. >>> size = (20,) >>> cb = CheckBox("clickme") >>> cb.state False >>> cb.mouse_event(size, 'mouse press', 1, 2, 0, True) True >>> cb.state True """ if button != 1 or not is_mouse_press(event): return False self.toggle_state() return True class RadioButton(CheckBox): states: typing.ClassVar[dict[bool | Literal["mixed"], SelectableIcon]] = { True: SelectableIcon("(X)", 1), False: SelectableIcon("( )", 1), "mixed": SelectableIcon("(#)", 1), } reserve_columns = 4 @typing.overload def __init__( self, group: MutableSequence[RadioButton], label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool | Literal["first True"] = ..., on_state_change: Callable[[Self, bool, _T], typing.Any] | None = None, user_data: _T = ..., ) -> None: ... @typing.overload def __init__( self, group: MutableSequence[RadioButton], label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool | Literal["first True"] = ..., on_state_change: Callable[[Self, bool], typing.Any] | None = None, user_data: None = None, ) -> None: ... def __init__( self, group: MutableSequence[RadioButton], label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], state: bool | Literal["first True"] = "first True", on_state_change: Callable[[Self, bool, _T], typing.Any] | Callable[[Self, bool], typing.Any] | None = None, user_data: _T | None = None, ) -> None: """ :param group: list for radio buttons in same group :param label: markup for radio button label :param state: False, True, "mixed" or "first True" :param on_state_change: shorthand for connect_signal() function call for a single 'change' callback :param user_data: user_data for on_state_change ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside This function will append the new radio button to group. "first True" will set to True if group is empty. Signals supported: ``'change'``, ``"postchange"`` Register signal handler with:: urwid.connect_signal(radio_button, 'change', callback, user_data) where callback is callback(radio_button, new_state [,user_data]) Unregister signal handlers with:: urwid.disconnect_signal(radio_button, 'change', callback, user_data) >>> bgroup = [] # button group >>> b1 = RadioButton(bgroup, u"Agree") >>> b2 = RadioButton(bgroup, u"Disagree") >>> len(bgroup) 2 >>> b1 <RadioButton selectable fixed/flow widget 'Agree' state=True> >>> b2 <RadioButton selectable fixed/flow widget 'Disagree' state=False> >>> b2.render((15,), focus=True).text # ... = b in Python 3 [...'( ) Disagree '] """ if state == "first True": state = not group self.group = group super().__init__(label, state, False, on_state_change, user_data) # type: ignore[call-overload] group.append(self) def set_state(self, state: bool | Literal["mixed"], do_callback: bool = True) -> None: """ Set the RadioButton state. state -- True, False or "mixed" do_callback -- False to suppress signal from this change If state is True all other radio buttons in the same button group will be set to False. >>> bgroup = [] # button group >>> b1 = RadioButton(bgroup, u"Agree") >>> b2 = RadioButton(bgroup, u"Disagree") >>> b3 = RadioButton(bgroup, u"Unsure") >>> b1.state, b2.state, b3.state (True, False, False) >>> b2.set_state(True) >>> b1.state, b2.state, b3.state (False, True, False) >>> def relabel_button(radio_button, new_state): ... radio_button.set_label(u"Think Harder!") >>> key = connect_signal(b3, 'change', relabel_button) >>> b3 <RadioButton selectable fixed/flow widget 'Unsure' state=False> >>> b3.set_state(True) # this will trigger the callback >>> b3 <RadioButton selectable fixed/flow widget 'Think Harder!' state=True> """ if self._state == state: return super().set_state(state, do_callback) # if we're clearing the state we don't have to worry about # other buttons in the button group if state is not True: return # clear the state of each other radio button for cb in self.group: if cb is self: continue if cb.state: cb.state = False def toggle_state(self) -> None: """ Set state to True. >>> bgroup = [] # button group >>> b1 = RadioButton(bgroup, "Agree") >>> b2 = RadioButton(bgroup, "Disagree") >>> b1.state, b2.state (True, False) >>> b2.toggle_state() >>> b1.state, b2.state (False, True) >>> b2.toggle_state() >>> b1.state, b2.state (False, True) """ self.set_state(True) class Button(WidgetWrap[Columns]): button_left = Text("<") button_right = Text(">") signals: typing.ClassVar[list[str]] = ["click"] @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], on_press: Callable[[Self, _T], typing.Any] | None = None, user_data: _T = ..., *, align: Literal["left", "center", "right"] | Align = ..., wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = ..., layout: TextLayout | None = ..., ) -> None: ... @typing.overload def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], on_press: Callable[[Self], typing.Any] | None = None, user_data: None = None, *, align: Literal["left", "center", "right"] | Align = ..., wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = ..., layout: TextLayout | None = ..., ) -> None: ... def __init__( self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]], on_press: Callable[[Self, _T], typing.Any] | Callable[[Self], typing.Any] | None = None, user_data: _T | None = None, *, align: Literal["left", "center", "right"] | Align = Align.LEFT, wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE, layout: TextLayout | None = None, ) -> None: """ :param label: markup for button label :param on_press: shorthand for connect_signal() function call for a single callback :param user_data: user_data for on_press :param align: typically ``'left'``, ``'center'`` or ``'right'`` :type align: label alignment mode :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'`` :type wrap: label wrapping mode :param layout: defaults to a shared :class:`StandardTextLayout` instance :type layout: text layout instance ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside Signals supported: ``'click'`` Register signal handler with:: urwid.connect_signal(button, 'click', callback, user_data) where callback is callback(button [,user_data]) Unregister signal handlers with:: urwid.disconnect_signal(button, 'click', callback, user_data) >>> from urwid.util import set_temporary_encoding >>> Button(u"Ok") <Button selectable fixed/flow widget 'Ok'> >>> b = Button("Cancel") >>> b.render((15,), focus=True).text # ... = b in Python 3 [b'< Cancel >'] >>> aligned_button = Button("Test", align=Align.CENTER) >>> aligned_button.render((10,), focus=True).text [b'< Test >'] >>> wrapped_button = Button("Long label", wrap=WrapMode.ELLIPSIS) >>> with set_temporary_encoding("utf-8"): ... wrapped_button.render((7,), focus=False).text[0].decode('utf-8') '< Lo… >' """ self._label = SelectableIcon(label, 0, align=align, wrap=wrap, layout=layout) cols = Columns( [(1, self.button_left), self._label, (1, self.button_right)], dividechars=1, ) super().__init__(cols) # The old way of listening for a change was to pass the callback # in to the constructor. Just convert it to the new way: if on_press: connect_signal(self, "click", on_press, user_data) def pack(self, size: tuple[()] | tuple[int] | None = None, focus: bool = False) -> tuple[int, int]: """Pack for widget. :param size: size data. Special case: None - get minimal widget size to fit :param focus: widget is focused >>> btn = Button("Some button") >>> btn.pack((10,)) (10, 2) >>> btn.pack() (15, 1) >>> btn.pack((), True) (15, 1) """ return super().pack(size or (), focus) def _repr_words(self) -> list[str]: # include button.label in repr(button) return [*super()._repr_words(), repr(self.label)] def set_label(self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None: """ Change the button label. label -- markup for button label >>> b = Button("Ok") >>> b.set_label(u"Yup yup") >>> b <Button selectable fixed/flow widget 'Yup yup'> """ self._label.set_text(label) def get_label(self) -> str | bytes: """ Return label text. >>> b = Button(u"Ok") >>> print(b.get_label()) Ok >>> print(b.label) Ok """ return self._label.text label = property(get_label) def keypress(self, size: tuple[int], key: str) -> str | None: """ Send 'click' signal on 'activate' command. >>> assert Button._command_map[' '] == 'activate' >>> assert Button._command_map['enter'] == 'activate' >>> size = (15,) >>> b = Button(u"Cancel") >>> clicked_buttons = [] >>> def handle_click(button): ... clicked_buttons.append(button.label) >>> key = connect_signal(b, 'click', handle_click) >>> b.keypress(size, 'enter') >>> b.keypress(size, ' ') >>> clicked_buttons # ... = u in Python 2 [...'Cancel', ...'Cancel'] """ if self._command_map[key] != Command.ACTIVATE: return key self._emit("click") return None def mouse_event(self, size: tuple[int], event: str, button: int, x: int, y: int, focus: bool) -> bool: """ Send 'click' signal on button 1 press. >>> size = (15,) >>> b = Button(u"Ok") >>> clicked_buttons = [] >>> def handle_click(button): ... clicked_buttons.append(button.label) >>> key = connect_signal(b, 'click', handle_click) >>> b.mouse_event(size, 'mouse press', 1, 4, 0, True) True >>> b.mouse_event(size, 'mouse press', 2, 4, 0, True) # ignored False >>> clicked_buttons # ... = u in Python 2 [...'Ok'] """ if button != 1 or not is_mouse_press(event): return False self._emit("click") return True def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
27,305
Python
.py
675
31.743704
115
0.566487
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,272
attr_map.py
urwid_urwid/urwid/widget/attr_map.py
from __future__ import annotations import typing from collections.abc import Hashable, Mapping from urwid.canvas import CompositeCanvas from .widget import WidgetError, delegate_to_widget_mixin from .widget_decoration import WidgetDecoration WrappedWidget = typing.TypeVar("WrappedWidget") class AttrMapError(WidgetError): pass class AttrMap(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]): """ AttrMap is a decoration that maps one set of attributes to another. This object will pass all function calls and variable references to the wrapped widget. """ def __init__( self, w: WrappedWidget, attr_map: Hashable | Mapping[Hashable | None, Hashable] | None, focus_map: Hashable | Mapping[Hashable | None, Hashable] | None = None, ) -> None: """ :param w: widget to wrap (stored as self.original_widget) :type w: widget :param attr_map: attribute to apply to *w*, or dict of old display attribute: new display attribute mappings :type attr_map: display attribute or dict :param focus_map: attribute to apply when in focus or dict of old display attribute: new display attribute mappings; if ``None`` use *attr* :type focus_map: display attribute or dict >>> from urwid import Divider, Edit, Text >>> AttrMap(Divider(u"!"), 'bright') <AttrMap flow widget <Divider flow widget '!'> attr_map={None: 'bright'}> >>> AttrMap(Edit(), 'notfocus', 'focus').attr_map {None: 'notfocus'} >>> AttrMap(Edit(), 'notfocus', 'focus').focus_map {None: 'focus'} >>> size = (5,) >>> am = AttrMap(Text(u"hi"), 'greeting', 'fgreet') >>> next(am.render(size, focus=False).content()) # ... = b in Python 3 [('greeting', None, ...'hi ')] >>> next(am.render(size, focus=True).content()) [('fgreet', None, ...'hi ')] >>> am2 = AttrMap(Text(('word', u"hi")), {'word':'greeting', None:'bg'}) >>> am2 <AttrMap fixed/flow widget <Text fixed/flow widget 'hi'> attr_map={'word': 'greeting', None: 'bg'}> >>> next(am2.render(size).content()) [('greeting', None, ...'hi'), ('bg', None, ...' ')] """ super().__init__(w) if isinstance(attr_map, Mapping): self.attr_map = dict(attr_map) else: self.attr_map = {None: attr_map} if isinstance(focus_map, Mapping): self.focus_map = dict(focus_map) elif focus_map is None: self.focus_map = focus_map else: self.focus_map = {None: focus_map} def _repr_attrs(self) -> dict[str, typing.Any]: # only include the focus_attr when it takes effect (not None) d = {**super()._repr_attrs(), "attr_map": self._attr_map} if self._focus_map is not None: d["focus_map"] = self._focus_map return d def get_attr_map(self) -> dict[Hashable | None, Hashable]: # make a copy so ours is not accidentally modified # FIXME: a dictionary that detects modifications would be better return dict(self._attr_map) def set_attr_map(self, attr_map: dict[Hashable | None, Hashable] | None) -> None: """ Set the attribute mapping dictionary {from_attr: to_attr, ...} Note this function does not accept a single attribute the way the constructor does. You must specify {None: attribute} instead. >>> from urwid import Text >>> w = AttrMap(Text(u"hi"), None) >>> w.set_attr_map({'a':'b'}) >>> w <AttrMap fixed/flow widget <Text fixed/flow widget 'hi'> attr_map={'a': 'b'}> """ for from_attr, to_attr in attr_map.items(): if not isinstance(from_attr, Hashable) or not isinstance(to_attr, Hashable): raise AttrMapError( f"{from_attr!r}:{to_attr!r} attribute mapping is invalid. Attributes must be hashable" ) self._attr_map = attr_map self._invalidate() attr_map = property(get_attr_map, set_attr_map) def get_focus_map(self) -> dict[Hashable | None, Hashable] | None: # make a copy so ours is not accidentally modified # FIXME: a dictionary that detects modifications would be better if self._focus_map: return dict(self._focus_map) return None def set_focus_map(self, focus_map: dict[Hashable | None, Hashable] | None) -> None: """ Set the focus attribute mapping dictionary {from_attr: to_attr, ...} If None this widget will use the attr mapping instead (no change when in focus). Note this function does not accept a single attribute the way the constructor does. You must specify {None: attribute} instead. >>> from urwid import Text >>> w = AttrMap(Text(u"hi"), {}) >>> w.set_focus_map({'a':'b'}) >>> w <AttrMap fixed/flow widget <Text fixed/flow widget 'hi'> attr_map={} focus_map={'a': 'b'}> >>> w.set_focus_map(None) >>> w <AttrMap fixed/flow widget <Text fixed/flow widget 'hi'> attr_map={}> """ if focus_map is not None: for from_attr, to_attr in focus_map.items(): if not isinstance(from_attr, Hashable) or not isinstance(to_attr, Hashable): raise AttrMapError( f"{from_attr!r}:{to_attr!r} attribute mapping is invalid. Attributes must be hashable" ) self._focus_map = focus_map self._invalidate() focus_map = property(get_focus_map, set_focus_map) def render(self, size, focus: bool = False) -> CompositeCanvas: """ Render wrapped widget and apply attribute. Return canvas. """ attr_map = self._attr_map if focus and self._focus_map is not None: attr_map = self._focus_map canv = self._original_widget.render(size, focus=focus) canv = CompositeCanvas(canv) canv.fill_attr_apply(attr_map) return canv
6,205
Python
.py
133
37.503759
110
0.600099
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,273
big_text.py
urwid_urwid/urwid/widget/big_text.py
from __future__ import annotations import typing from urwid.canvas import CanvasJoin, CompositeCanvas, TextCanvas from urwid.util import decompose_tagmarkup from .constants import Sizing from .widget import Widget, fixed_size if typing.TYPE_CHECKING: from collections.abc import Hashable from urwid import Font class BigText(Widget): _sizing = frozenset([Sizing.FIXED]) def __init__(self, markup, font: Font) -> None: """ markup -- same as Text widget markup font -- instance of a Font class """ super().__init__() self.text: str = "" self.attrib = [] self.font: Font = font self.set_font(font) self.set_text(markup) def set_text(self, markup): self.text, self.attrib = decompose_tagmarkup(markup) self._invalidate() def get_text(self): """ Returns (text, attributes). """ return self.text, self.attrib def set_font(self, font: Font) -> None: self.font = font self._invalidate() def pack( self, size: tuple[()] | None = (), # type: ignore[override] focus: bool = False, ) -> tuple[int, int]: rows = self.font.height cols = 0 for c in self.text: cols += self.font.char_width(c) return cols, rows def render( self, size: tuple[()], # type: ignore[override] focus: bool = False, ) -> CompositeCanvas: fixed_size(size) # complain if parameter is wrong a: Hashable | None = None ai = ak = 0 o = [] rows = self.font.height attrib = [*self.attrib, (None, len(self.text))] for ch in self.text: if not ak: a, ak = attrib[ai] ai += 1 ak -= 1 width = self.font.char_width(ch) if not width: # ignore invalid characters continue c: TextCanvas | CompositeCanvas = self.font.render(ch) if a is not None: c = CompositeCanvas(c) c.fill_attr(a) o.append((c, None, False, width)) if o: canv = CanvasJoin(o) else: canv = CompositeCanvas(TextCanvas([b""] * rows, maxcol=0, check_width=False)) canv.set_depends([]) return canv
2,393
Python
.py
74
23.432432
89
0.554206
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,274
curses.py
urwid_urwid/urwid/display/curses.py
# Urwid curses output wrapper.. the horror.. # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Curses-based UI implementation """ from __future__ import annotations import curses import sys import typing from contextlib import suppress from urwid import util from . import escape from .common import UNPRINTABLE_TRANS_TABLE, AttrSpec, BaseScreen, RealTerminal if typing.TYPE_CHECKING: from typing_extensions import Literal from urwid import Canvas IS_WINDOWS = sys.platform == "win32" # curses.KEY_RESIZE (sometimes not defined) if IS_WINDOWS: KEY_MOUSE = 539 # under Windows key mouse is different KEY_RESIZE = 546 COLOR_CORRECTION: dict[int, int] = dict( enumerate( ( curses.COLOR_BLACK, curses.COLOR_RED, curses.COLOR_GREEN, curses.COLOR_YELLOW, curses.COLOR_BLUE, curses.COLOR_MAGENTA, curses.COLOR_CYAN, curses.COLOR_WHITE, ) ) ) def initscr(): import curses # noqa: I001 # pylint: disable=redefined-outer-name,reimported # special case for monkeypatch import _curses stdscr = _curses.initscr() for key, value in _curses.__dict__.items(): if key[:4] == "ACS_" or key in {"LINES", "COLS"}: setattr(curses, key, value) return stdscr curses.initscr = initscr else: KEY_MOUSE = 409 # curses.KEY_MOUSE KEY_RESIZE = 410 COLOR_CORRECTION = {} _curses_colours = { # pylint: disable=consider-using-namedtuple-or-dataclass # historic test/debug data "default": (-1, 0), "black": (curses.COLOR_BLACK, 0), "dark red": (curses.COLOR_RED, 0), "dark green": (curses.COLOR_GREEN, 0), "brown": (curses.COLOR_YELLOW, 0), "dark blue": (curses.COLOR_BLUE, 0), "dark magenta": (curses.COLOR_MAGENTA, 0), "dark cyan": (curses.COLOR_CYAN, 0), "light gray": (curses.COLOR_WHITE, 0), "dark gray": (curses.COLOR_BLACK, 1), "light red": (curses.COLOR_RED, 1), "light green": (curses.COLOR_GREEN, 1), "yellow": (curses.COLOR_YELLOW, 1), "light blue": (curses.COLOR_BLUE, 1), "light magenta": (curses.COLOR_MAGENTA, 1), "light cyan": (curses.COLOR_CYAN, 1), "white": (curses.COLOR_WHITE, 1), } class Screen(BaseScreen, RealTerminal): def __init__(self) -> None: super().__init__() self.curses_pairs = [(None, None)] # Can't be sure what pair 0 will default to self.palette = {} self.has_color = False self.s = None self.cursor_state = None self.prev_input_resize = 0 self.set_input_timeouts() self.last_bstate = 0 self._mouse_tracking_enabled = False self.register_palette_entry(None, "default", "default") def set_mouse_tracking(self, enable: bool = True) -> None: """ Enable mouse tracking. After calling this function get_input will include mouse click events along with keystrokes. """ enable = bool(enable) # noqa: FURB123,RUF100 if enable == self._mouse_tracking_enabled: return if enable: curses.mousemask( 0 | curses.BUTTON1_PRESSED | curses.BUTTON1_RELEASED | curses.BUTTON2_PRESSED | curses.BUTTON2_RELEASED | curses.BUTTON3_PRESSED | curses.BUTTON3_RELEASED | curses.BUTTON4_PRESSED | curses.BUTTON4_RELEASED | curses.BUTTON1_DOUBLE_CLICKED | curses.BUTTON1_TRIPLE_CLICKED | curses.BUTTON2_DOUBLE_CLICKED | curses.BUTTON2_TRIPLE_CLICKED | curses.BUTTON3_DOUBLE_CLICKED | curses.BUTTON3_TRIPLE_CLICKED | curses.BUTTON4_DOUBLE_CLICKED | curses.BUTTON4_TRIPLE_CLICKED | curses.BUTTON_SHIFT | curses.BUTTON_ALT | curses.BUTTON_CTRL ) else: raise NotImplementedError() self._mouse_tracking_enabled = enable def _start(self) -> None: """ Initialize the screen and input mode. """ self.s = curses.initscr() self.has_color = curses.has_colors() if self.has_color: curses.start_color() if curses.COLORS < 8: # not colourful enough self.has_color = False if self.has_color: try: curses.use_default_colors() self.has_default_colors = True except curses.error: self.has_default_colors = False self._setup_colour_pairs() curses.noecho() curses.meta(True) curses.halfdelay(10) # use set_input_timeouts to adjust self.s.keypad(False) if not self._signal_keys_set: self._old_signal_keys = self.tty_signal_keys() super()._start() if IS_WINDOWS: # halfdelay() seems unnecessary and causes everything to slow down a lot. curses.nocbreak() # exits halfdelay mode # keypad(1) is needed, or we get no special keys (cursor keys, etc.) self.s.keypad(True) def _stop(self) -> None: """ Restore the screen. """ curses.echo() self._curs_set(1) with suppress(curses.error): curses.endwin() # don't block original error with curses error if self._old_signal_keys: self.tty_signal_keys(*self._old_signal_keys) super()._stop() def _setup_colour_pairs(self) -> None: """ Initialize all 63 color pairs based on the term: bg * 8 + 7 - fg So to get a color, we just need to use that term and get the right color pair number. """ if not self.has_color: return if IS_WINDOWS: self.has_default_colors = False for fg in range(8): for bg in range(8): # leave out white on black if fg == curses.COLOR_WHITE and bg == curses.COLOR_BLACK: continue curses.init_pair(bg * 8 + 7 - fg, COLOR_CORRECTION.get(fg, fg), COLOR_CORRECTION.get(bg, bg)) def _curs_set(self, x: int): if self.cursor_state in {"fixed", x}: return try: curses.curs_set(x) self.cursor_state = x except curses.error: self.cursor_state = "fixed" def _clear(self) -> None: self.s.clear() self.s.refresh() def _getch(self, wait_tenths: int | None) -> int: if wait_tenths == 0: return self._getch_nodelay() if not IS_WINDOWS: if wait_tenths is None: curses.cbreak() else: curses.halfdelay(wait_tenths) self.s.nodelay(False) return self.s.getch() def _getch_nodelay(self) -> int: self.s.nodelay(True) if not IS_WINDOWS: while True: # this call fails sometimes, but seems to work when I try again with suppress(curses.error): curses.cbreak() break return self.s.getch() def set_input_timeouts( self, max_wait: float | None = None, complete_wait: float = 0.1, resize_wait: float = 0.1, ): """ Set the get_input timeout values. All values have a granularity of 0.1s, ie. any value between 0.15 and 0.05 will be treated as 0.1 and any value less than 0.05 will be treated as 0. The maximum timeout value for this module is 25.5 seconds. max_wait -- amount of time in seconds to wait for input when there is no input pending, wait forever if None complete_wait -- amount of time in seconds to wait when get_input detects an incomplete escape sequence at the end of the available input resize_wait -- amount of time in seconds to wait for more input after receiving two screen resize requests in a row to stop urwid from consuming 100% cpu during a gradual window resize operation """ def convert_to_tenths(s): if s is None: return None return int((s + 0.05) * 10) self.max_tenths = convert_to_tenths(max_wait) self.complete_tenths = convert_to_tenths(complete_wait) self.resize_tenths = convert_to_tenths(resize_wait) @typing.overload def get_input(self, raw_keys: Literal[False]) -> list[str]: ... @typing.overload def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: """Return pending input as a list. raw_keys -- return raw keycodes as well as translated versions This function will immediately return all the input since the last time it was called. If there is no input pending it will wait before returning an empty list. The wait time may be configured with the set_input_timeouts function. If raw_keys is False (default) this function will return a list of keys pressed. If raw_keys is True this function will return a ( keys pressed, raw keycodes ) tuple instead. Examples of keys returned: * ASCII printable characters: " ", "a", "0", "A", "-", "/" * ASCII control characters: "tab", "enter" * Escape sequences: "up", "page up", "home", "insert", "f1" * Key combinations: "shift f1", "meta a", "ctrl b" * Window events: "window resize" When a narrow encoding is not enabled: * "Extended ASCII" characters: "\\xa1", "\\xb2", "\\xfe" When a wide encoding is enabled: * Double-byte characters: "\\xa1\\xea", "\\xb2\\xd4" When utf8 encoding is enabled: * Unicode characters: u"\\u00a5", u'\\u253c" Examples of mouse events returned: * Mouse button press: ('mouse press', 1, 15, 13), ('meta mouse press', 2, 17, 23) * Mouse button release: ('mouse release', 0, 18, 13), ('ctrl mouse release', 0, 17, 23) """ if not self._started: raise RuntimeError keys, raw = self._get_input(self.max_tenths) # Avoid pegging CPU at 100% when slowly resizing, and work # around a bug with some braindead curses implementations that # return "no key" between "window resize" commands if keys == ["window resize"] and self.prev_input_resize: for _ in range(2): new_keys, new_raw = self._get_input(self.resize_tenths) raw += new_raw if new_keys and new_keys != ["window resize"]: if "window resize" in new_keys: keys = new_keys else: keys.extend(new_keys) break if keys == ["window resize"]: self.prev_input_resize = 2 elif self.prev_input_resize == 2 and not keys: self.prev_input_resize = 1 else: self.prev_input_resize = 0 if raw_keys: return keys, raw return keys def _get_input(self, wait_tenths: int | None) -> tuple[list[str], list[int]]: # this works around a strange curses bug with window resizing # not being reported correctly with repeated calls to this # function without a doupdate call in between curses.doupdate() key = self._getch(wait_tenths) resize = False raw = [] keys = [] while key >= 0: raw.append(key) if key == KEY_RESIZE: resize = True elif key == KEY_MOUSE: keys += self._encode_mouse_event() else: keys.append(key) key = self._getch_nodelay() processed = [] try: while keys: run, keys = escape.process_keyqueue(keys, True) processed += run except escape.MoreInputRequired: key = self._getch(self.complete_tenths) while key >= 0: raw.append(key) if key == KEY_RESIZE: resize = True elif key == KEY_MOUSE: keys += self._encode_mouse_event() else: keys.append(key) key = self._getch_nodelay() while keys: run, keys = escape.process_keyqueue(keys, False) processed += run if resize: processed.append("window resize") return processed, raw def _encode_mouse_event(self) -> list[int]: # convert to escape sequence last_state = next_state = self.last_bstate (_id, x, y, _z, bstate) = curses.getmouse() mod = 0 if bstate & curses.BUTTON_SHIFT: mod |= 4 if bstate & curses.BUTTON_ALT: mod |= 8 if bstate & curses.BUTTON_CTRL: mod |= 16 result = [] def append_button(b: int) -> None: b |= mod result.extend([27, ord("["), ord("M"), b + 32, x + 33, y + 33]) if bstate & curses.BUTTON1_PRESSED and last_state & 1 == 0: append_button(0) next_state |= 1 if bstate & curses.BUTTON2_PRESSED and last_state & 2 == 0: append_button(1) next_state |= 2 if bstate & curses.BUTTON3_PRESSED and last_state & 4 == 0: append_button(2) next_state |= 4 if bstate & curses.BUTTON4_PRESSED and last_state & 8 == 0: append_button(64) next_state |= 8 if bstate & curses.BUTTON1_RELEASED and last_state & 1: append_button(0 + escape.MOUSE_RELEASE_FLAG) next_state &= ~1 if bstate & curses.BUTTON2_RELEASED and last_state & 2: append_button(1 + escape.MOUSE_RELEASE_FLAG) next_state &= ~2 if bstate & curses.BUTTON3_RELEASED and last_state & 4: append_button(2 + escape.MOUSE_RELEASE_FLAG) next_state &= ~4 if bstate & curses.BUTTON4_RELEASED and last_state & 8: append_button(64 + escape.MOUSE_RELEASE_FLAG) next_state &= ~8 if bstate & curses.BUTTON1_DOUBLE_CLICKED: append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if bstate & curses.BUTTON2_DOUBLE_CLICKED: append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if bstate & curses.BUTTON3_DOUBLE_CLICKED: append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if bstate & curses.BUTTON4_DOUBLE_CLICKED: append_button(64 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if bstate & curses.BUTTON1_TRIPLE_CLICKED: append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) if bstate & curses.BUTTON2_TRIPLE_CLICKED: append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) if bstate & curses.BUTTON3_TRIPLE_CLICKED: append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) if bstate & curses.BUTTON4_TRIPLE_CLICKED: append_button(64 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) self.last_bstate = next_state return result def _dbg_instr(self): # messy input string (intended for debugging) curses.echo() self.s.nodelay(0) curses.halfdelay(100) string = self.s.getstr() curses.noecho() return string def _dbg_out(self, string) -> None: # messy output function (intended for debugging) self.s.clrtoeol() self.s.addstr(string) self.s.refresh() self._curs_set(1) def _dbg_query(self, question): # messy query (intended for debugging) self._dbg_out(question) return self._dbg_instr() def _dbg_refresh(self) -> None: self.s.refresh() def get_cols_rows(self) -> tuple[int, int]: """Return the terminal dimensions (num columns, num rows).""" rows, cols = self.s.getmaxyx() return cols, rows def _setattr(self, a): if a is None: self.s.attrset(0) return if not isinstance(a, AttrSpec): p = self._palette.get(a, (AttrSpec("default", "default"),)) a = p[0] if self.has_color: if a.foreground_basic: if a.foreground_number >= 8: fg = a.foreground_number - 8 else: fg = a.foreground_number else: fg = 7 if a.background_basic: bg = a.background_number else: bg = 0 attr = curses.color_pair(bg * 8 + 7 - fg) else: attr = 0 if a.bold: attr |= curses.A_BOLD if a.standout: attr |= curses.A_STANDOUT if a.underline: attr |= curses.A_UNDERLINE if a.blink: attr |= curses.A_BLINK self.s.attrset(attr) def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: """Paint screen with rendered canvas.""" logger = self.logger.getChild("draw_screen") if not self._started: raise RuntimeError _cols, rows = size if canvas.rows() != rows: raise ValueError("canvas size and passed size don't match") logger.debug(f"Drawing screen with size {size!r}") y = -1 for row in canvas.content(): y += 1 try: self.s.move(y, 0) except curses.error: # terminal shrunk? # move failed so stop rendering. return first = True lasta = None for nr, (a, cs, seg) in enumerate(row): if cs != "U": seg = seg.translate(UNPRINTABLE_TRANS_TABLE) # noqa: PLW2901 if not isinstance(seg, bytes): raise TypeError(seg) if first or lasta != a: self._setattr(a) lasta = a try: if cs in {"0", "U"}: for segment in seg: self.s.addch(0x400000 + segment) else: if cs is not None: raise ValueError(f"cs not in ('0', 'U' ,'None'): {cs!r}") if not isinstance(seg, bytes): raise TypeError(seg) self.s.addstr(seg.decode(util.get_encoding())) except curses.error: # it's ok to get out of the # screen on the lower right if y != rows - 1 or nr != len(row) - 1: # perhaps screen size changed # quietly abort. return if canvas.cursor is not None: x, y = canvas.cursor self._curs_set(1) with suppress(curses.error): self.s.move(y, x) else: self._curs_set(0) self.s.move(0, 0) self.s.refresh() self.keep_cache_alive_link = canvas def clear(self) -> None: """ Force the screen to be completely repainted on the next call to draw_screen(). """ self.s.clear() class _test: def __init__(self): self.ui = Screen() self.l = sorted(_curses_colours) for c in self.l: self.ui.register_palette( [ (f"{c} on black", c, "black", "underline"), (f"{c} on dark blue", c, "dark blue", "bold"), (f"{c} on light gray", c, "light gray", "standout"), ] ) with self.ui.start(): self.run() def run(self) -> None: class FakeRender: pass r = FakeRender() text = [f" has_color = {self.ui.has_color!r}", ""] attr = [[], []] r.coords = {} r.cursor = None for c in self.l: t = "" a = [] for p in f"{c} on black", f"{c} on dark blue", f"{c} on light gray": a.append((p, 27)) t += (p + 27 * " ")[:27] text.append(t) attr.append(a) text += ["", "return values from get_input(): (q exits)", ""] attr += [[], [], []] cols, rows = self.ui.get_cols_rows() keys = None while keys != ["q"]: r.text = ([t.ljust(cols) for t in text] + [""] * rows)[:rows] r.attr = (attr + [[] for _ in range(rows)])[:rows] self.ui.draw_screen((cols, rows), r) keys, raw = self.ui.get_input(raw_keys=True) if "window resize" in keys: cols, rows = self.ui.get_cols_rows() if not keys: continue t = "" a = [] for k in keys: if isinstance(k, str): k = k.encode(util.get_encoding()) # noqa: PLW2901 t += f"'{k}' " a += [(None, 1), ("yellow on dark blue", len(k)), (None, 2)] text.append(f"{t}: {raw!r}") attr.append(a) text = text[-rows:] attr = attr[-rows:] if __name__ == "__main__": _test()
22,772
Python
.py
570
28.673684
118
0.544063
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,275
raw.py
urwid_urwid/urwid/display/raw.py
# Urwid raw display module # Copyright (C) 2004-2009 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Direct terminal UI implementation """ from __future__ import annotations import sys __all__ = ("Screen",) IS_WINDOWS = sys.platform == "win32" if IS_WINDOWS: from ._win32_raw_display import Screen else: from ._posix_raw_display import Screen
1,125
Python
.py
29
37.241379
78
0.73989
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,276
escape.py
urwid_urwid/urwid/display/escape.py
# Urwid escape sequences common to curses_display and raw_display # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Terminal Escape Sequences for input and display """ from __future__ import annotations import re import sys import typing from collections.abc import MutableMapping, Sequence from urwid import str_util if typing.TYPE_CHECKING: from collections.abc import Iterable # NOTE: because of circular imports (urwid.util -> urwid.escape -> urwid.util) # from urwid.util import is_mouse_event -- will not work here import urwid.util # isort: skip # pylint: disable=wrong-import-position IS_WINDOWS = sys.platform == "win32" within_double_byte = str_util.within_double_byte SO = "\x0e" SI = "\x0f" IBMPC_ON = "\x1b[11m" IBMPC_OFF = "\x1b[10m" DEC_TAG = "0" DEC_SPECIAL_CHARS = "▮◆▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·" ALT_DEC_SPECIAL_CHARS = "_`abcdefghijklmnopqrstuvwxyz{|}~" DEC_SPECIAL_CHARMAP = {} if len(DEC_SPECIAL_CHARS) != len(ALT_DEC_SPECIAL_CHARS): raise RuntimeError(repr((DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS))) for c, alt in zip(DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS): DEC_SPECIAL_CHARMAP[ord(c)] = SO + alt + SI SAFE_ASCII_DEC_SPECIAL_RE = re.compile(f"^[ -~{DEC_SPECIAL_CHARS}]*$") DEC_SPECIAL_RE = re.compile(f"[{DEC_SPECIAL_CHARS}]") ################### # Input sequences ################### class MoreInputRequired(Exception): pass def escape_modifier(digit: str) -> str: mode = ord(digit) - ord("1") return "shift " * (mode & 1) + "meta " * ((mode & 2) // 2) + "ctrl " * ((mode & 4) // 4) input_sequences = [ ("[A", "up"), ("[B", "down"), ("[C", "right"), ("[D", "left"), ("[E", "5"), ("[F", "end"), ("[G", "5"), ("[H", "home"), ("[I", "focus in"), ("[O", "focus out"), ("[1~", "home"), ("[2~", "insert"), ("[3~", "delete"), ("[4~", "end"), ("[5~", "page up"), ("[6~", "page down"), ("[7~", "home"), ("[8~", "end"), ("[[A", "f1"), ("[[B", "f2"), ("[[C", "f3"), ("[[D", "f4"), ("[[E", "f5"), ("[11~", "f1"), ("[12~", "f2"), ("[13~", "f3"), ("[14~", "f4"), ("[15~", "f5"), ("[17~", "f6"), ("[18~", "f7"), ("[19~", "f8"), ("[20~", "f9"), ("[21~", "f10"), ("[23~", "f11"), ("[24~", "f12"), ("[25~", "f13"), ("[26~", "f14"), ("[28~", "f15"), ("[29~", "f16"), ("[31~", "f17"), ("[32~", "f18"), ("[33~", "f19"), ("[34~", "f20"), ("OA", "up"), ("OB", "down"), ("OC", "right"), ("OD", "left"), ("OH", "home"), ("OF", "end"), ("OP", "f1"), ("OQ", "f2"), ("OR", "f3"), ("OS", "f4"), ("Oo", "/"), ("Oj", "*"), ("Om", "-"), ("Ok", "+"), ("[Z", "shift tab"), ("On", "."), ("[200~", "begin paste"), ("[201~", "end paste"), *( (prefix + letter, modifier + key) for prefix, modifier in zip("O[", ("meta ", "shift ")) for letter, key in zip("abcd", ("up", "down", "right", "left")) ), *( (f"[{digit}{symbol}", modifier + key) for modifier, symbol in zip(("shift ", "meta "), "$^") for digit, key in zip("235678", ("insert", "delete", "page up", "page down", "home", "end")) ), *((f"O{ord('p') + n:c}", str(n)) for n in range(10)), *( # modified cursor keys + home, end, 5 -- [#X and [1;#X forms (prefix + digit + letter, escape_modifier(digit) + key) for prefix in ("[", "[1;") for digit in "12345678" for letter, key in zip("ABCDEFGH", ("up", "down", "right", "left", "5", "end", "5", "home")) ), *( # modified F1-F4 keys - O#X form and [1;#X form (prefix + digit + letter, escape_modifier(digit) + f"f{number}") for prefix in ("O", "[1;") for digit in "12345678" for number, letter in enumerate("PQRS", start=1) ), *( # modified F1-F13 keys -- [XX;#~ form (f"[{num!s};{digit}~", escape_modifier(digit) + key) for digit in "12345678" for num, key in zip( (3, 5, 6, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 31, 32, 33, 34), ( "delete", "page up", "page down", *(f"f{idx}" for idx in range(1, 21)), ), ) ), # mouse reporting (special handling done in KeyqueueTrie) ("[M", "mouse"), # mouse reporting for SGR 1006 ("[<", "sgrmouse"), # report status response ("[0n", "status ok"), ] class KeyqueueTrie: __slots__ = ("data",) def __init__(self, sequences: Iterable[tuple[str, str]]) -> None: self.data: dict[int, str | dict[int, str | dict[int, str]]] = {} for s, result in sequences: if isinstance(result, dict): raise TypeError(result) self.add(self.data, s, result) def add( self, root: MutableMapping[int, str | MutableMapping[int, str | MutableMapping[int, str]]], s: str, result: str, ) -> None: if not isinstance(root, MutableMapping) or not s: raise RuntimeError("trie conflict detected") if ord(s[0]) in root: self.add(root[ord(s[0])], s[1:], result) return if len(s) > 1: d = {} root[ord(s[0])] = d self.add(d, s[1:], result) return root[ord(s)] = result def get(self, keys, more_available: bool): result = self.get_recurse(self.data, keys, more_available) if not result: result = self.read_cursor_position(keys, more_available) return result def get_recurse( self, root: ( MutableMapping[int, str | MutableMapping[int, str | MutableMapping[int, str]]] | typing.Literal["mouse", "sgrmouse"] ), keys: Sequence[int], more_available: bool, ): if not isinstance(root, MutableMapping): if root == "mouse": return self.read_mouse_info(keys, more_available) if root == "sgrmouse": return self.read_sgrmouse_info(keys, more_available) return (root, keys) if not keys: # get more keys if more_available: raise MoreInputRequired() return None if keys[0] not in root: return None return self.get_recurse(root[keys[0]], keys[1:], more_available) def read_mouse_info(self, keys: Sequence[int], more_available: bool): if len(keys) < 3: if more_available: raise MoreInputRequired() return None b = keys[0] - 32 x, y = (keys[1] - 33) % 256, (keys[2] - 33) % 256 # supports 0-255 prefixes = [] if b & 4: prefixes.append("shift ") if b & 8: prefixes.append("meta ") if b & 16: prefixes.append("ctrl ") if (b & MOUSE_MULTIPLE_CLICK_MASK) >> 9 == 1: prefixes.append("double ") if (b & MOUSE_MULTIPLE_CLICK_MASK) >> 9 == 2: prefixes.append("triple ") prefix = "".join(prefixes) # 0->1, 1->2, 2->3, 64->4, 65->5 button = ((b & 64) // 64 * 3) + (b & 3) + 1 if b & 3 == 3: action = "release" button = 0 elif b & MOUSE_RELEASE_FLAG: action = "release" elif b & MOUSE_DRAG_FLAG: action = "drag" elif b & MOUSE_MULTIPLE_CLICK_MASK: action = "click" else: action = "press" return ((f"{prefix}mouse {action}", button, x, y), keys[3:]) def read_sgrmouse_info(self, keys: Sequence[int], more_available: bool): # Helpful links: # https://stackoverflow.com/questions/5966903/how-to-get-mousemove-and-mouseclick-in-bash # http://invisible-island.net/xterm/ctlseqs/ctlseqs.pdf if not keys: if more_available: raise MoreInputRequired() return None value = "" pos_m = 0 found_m = False for k in keys: value += chr(k) if k in {ord("M"), ord("m")}: found_m = True break pos_m += 1 if not found_m: if more_available: raise MoreInputRequired() return None (b, x, y) = (int(val) for val in value[:-1].split(";")) action = value[-1] # Double and triple clicks are not supported. # They can be implemented by using a timer. # This timer can check if the last registered click is below a certain threshold. # This threshold is normally set in the operating system itself, # so setting one here will cause an inconsistent behaviour. prefixes = [] if b & 4: prefixes.append("shift ") if b & 8: prefixes.append("meta ") if b & 16: prefixes.append("ctrl ") prefix = "".join(prefixes) wheel_used: typing.Literal[0, 1] = (b & 64) >> 6 button = (wheel_used * 3) + (b & 3) + 1 x -= 1 y -= 1 if action == "M": if b & MOUSE_DRAG_FLAG: action = "drag" else: action = "press" elif action == "m": action = "release" else: raise ValueError(f"Unknown mouse action: {action!r}") return ((f"{prefix}mouse {action}", button, x, y), keys[pos_m + 1 :]) def read_cursor_position(self, keys, more_available: bool): """ Interpret cursor position information being sent by the user's terminal. Returned as ('cursor position', x, y) where (x, y) == (0, 0) is the top left of the screen. """ if not keys: if more_available: raise MoreInputRequired() return None if keys[0] != ord("["): return None # read y value y = 0 i = 1 for k in keys[i:]: i += 1 if k == ord(";"): if not y: return None break if k < ord("0") or k > ord("9"): return None if not y and k == ord("0"): return None y = y * 10 + k - ord("0") if not keys[i:]: if more_available: raise MoreInputRequired() return None # read x value x = 0 for k in keys[i:]: i += 1 if k == ord("R"): if not x: return None return (("cursor position", x - 1, y - 1), keys[i:]) if k < ord("0") or k > ord("9"): return None if not x and k == ord("0"): return None x = x * 10 + k - ord("0") if not keys[i:] and more_available: raise MoreInputRequired() return None # This is added to button value to signal mouse release by curses_display # and raw_display when we know which button was released. NON-STANDARD MOUSE_RELEASE_FLAG = 2048 # This 2-bit mask is used to check if the mouse release from curses or gpm # is a double or triple release. 00 means single click, 01 double, # 10 triple. NON-STANDARD MOUSE_MULTIPLE_CLICK_MASK = 1536 # This is added to button value at mouse release to differentiate between # single, double and triple press. Double release adds this times one, # triple release adds this times two. NON-STANDARD MOUSE_MULTIPLE_CLICK_FLAG = 512 # xterm adds this to the button value to signal a mouse drag event MOUSE_DRAG_FLAG = 32 ################################################# # Build the input trie from input_sequences list input_trie = KeyqueueTrie(input_sequences) ################################################# _keyconv = { -1: None, 8: "backspace", 9: "tab", 10: "enter", 13: "enter", 127: "backspace", # curses-only keycodes follow.. (XXX: are these used anymore?) 258: "down", 259: "up", 260: "left", 261: "right", 262: "home", 263: "backspace", 265: "f1", 266: "f2", 267: "f3", 268: "f4", 269: "f5", 270: "f6", 271: "f7", 272: "f8", 273: "f9", 274: "f10", 275: "f11", 276: "f12", 277: "shift f1", 278: "shift f2", 279: "shift f3", 280: "shift f4", 281: "shift f5", 282: "shift f6", 283: "shift f7", 284: "shift f8", 285: "shift f9", 286: "shift f10", 287: "shift f11", 288: "shift f12", 330: "delete", 331: "insert", 338: "page down", 339: "page up", 343: "enter", # on numpad 350: "5", # on numpad 360: "end", } if IS_WINDOWS: _keyconv[351] = "shift tab" _keyconv[358] = "end" def process_keyqueue(codes: Sequence[int], more_available: bool) -> tuple[list[str], Sequence[int]]: """ codes -- list of key codes more_available -- if True then raise MoreInputRequired when in the middle of a character sequence (escape/utf8/wide) and caller will attempt to send more key codes on the next call. returns (list of input, list of remaining key codes). """ code = codes[0] if 32 <= code <= 126: key = chr(code) return [key], codes[1:] if code in _keyconv: return [_keyconv[code]], codes[1:] if 0 < code < 27: return [f"ctrl {ord('a') + code - 1:c}"], codes[1:] if 27 < code < 32: return [f"ctrl {ord('A') + code - 1:c}"], codes[1:] em = str_util.get_byte_encoding() if ( em == "wide" and code < 256 and within_double_byte( code.to_bytes(1, "little"), 0, 0, ) ): if not codes[1:] and more_available: raise MoreInputRequired() if codes[1:] and codes[1] < 256: db = chr(code) + chr(codes[1]) if within_double_byte(db, 0, 1): return [db], codes[2:] if em == "utf8" and 127 < code < 256: if code & 0xE0 == 0xC0: # 2-byte form need_more = 1 elif code & 0xF0 == 0xE0: # 3-byte form need_more = 2 elif code & 0xF8 == 0xF0: # 4-byte form need_more = 3 else: return [f"<{code:d}>"], codes[1:] for i in range(1, need_more + 1): if len(codes) <= i: if more_available: raise MoreInputRequired() return [f"<{code:d}>"], codes[1:] k = codes[i] if k > 256 or k & 0xC0 != 0x80: return [f"<{code:d}>"], codes[1:] s = bytes(codes[: need_more + 1]) try: return [s.decode("utf-8")], codes[need_more + 1 :] except UnicodeDecodeError: return [f"<{code:d}>"], codes[1:] if 127 < code < 256: key = chr(code) return [key], codes[1:] if code != 27: return [f"<{code:d}>"], codes[1:] result = input_trie.get(codes[1:], more_available) if result is not None: result, remaining_codes = result return [result], remaining_codes if codes[1:]: # Meta keys -- ESC+Key form run, remaining_codes = process_keyqueue(codes[1:], more_available) if urwid.util.is_mouse_event(run[0]): return ["esc", *run], remaining_codes if run[0] == "esc" or run[0].find("meta ") >= 0: return ["esc", *run], remaining_codes return [f"meta {run[0]}"] + run[1:], remaining_codes return ["esc"], codes[1:] #################### # Output sequences #################### ESC = "\x1b" CURSOR_HOME = f"{ESC}[H" CURSOR_HOME_COL = "\r" APP_KEYPAD_MODE = f"{ESC}=" NUM_KEYPAD_MODE = f"{ESC}>" SWITCH_TO_ALTERNATE_BUFFER = f"{ESC}[?1049h" RESTORE_NORMAL_BUFFER = f"{ESC}[?1049l" ENABLE_BRACKETED_PASTE_MODE = f"{ESC}[?2004h" DISABLE_BRACKETED_PASTE_MODE = f"{ESC}[?2004l" ENABLE_FOCUS_REPORTING = f"{ESC}[?1004h" DISABLE_FOCUS_REPORTING = f"{ESC}[?1004l" # RESET_SCROLL_REGION = ESC+"[;r" # RESET = ESC+"c" REPORT_STATUS = f"{ESC}[5n" REPORT_CURSOR_POSITION = f"{ESC}[6n" INSERT_ON = f"{ESC}[4h" INSERT_OFF = f"{ESC}[4l" def set_cursor_position(x: int, y: int) -> str: if not isinstance(x, int): raise TypeError(x) if not isinstance(y, int): raise TypeError(y) return ESC + f"[{y + 1:d};{x + 1:d}H" def move_cursor_right(x: int) -> str: if x < 1: return "" return ESC + f"[{x:d}C" def move_cursor_up(x: int) -> str: if x < 1: return "" return ESC + f"[{x:d}A" def move_cursor_down(x: int) -> str: if x < 1: return "" return ESC + f"[{x:d}B" HIDE_CURSOR = f"{ESC}[?25l" SHOW_CURSOR = f"{ESC}[?25h" MOUSE_TRACKING_ON = f"{ESC}[?1000h{ESC}[?1002h{ESC}[?1006h" MOUSE_TRACKING_OFF = f"{ESC}[?1006l{ESC}[?1002l{ESC}[?1000l" DESIGNATE_G1_SPECIAL = f"{ESC})0" ERASE_IN_LINE_RIGHT = f"{ESC}[K"
17,941
Python
.py
530
26.277358
102
0.526978
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,277
_raw_display_base.py
urwid_urwid/urwid/display/_raw_display_base.py
# Urwid raw display module # Copyright (C) 2004-2009 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Direct terminal UI implementation """ from __future__ import annotations import abc import contextlib import functools import os import platform import selectors import signal import socket import sys import typing from urwid import signals, str_util, util from . import escape from .common import UNPRINTABLE_TRANS_TABLE, UPDATE_PALETTE_ENTRY, AttrSpec, BaseScreen, RealTerminal if typing.TYPE_CHECKING: from collections.abc import Callable, Iterable from types import FrameType from typing_extensions import Literal from urwid import Canvas, EventLoop IS_WINDOWS = sys.platform == "win32" IS_WSL = (sys.platform == "linux") and ("wsl" in platform.platform().lower()) class Screen(BaseScreen, RealTerminal): def __init__(self, input: typing.IO, output: typing.IO) -> None: # noqa: A002 # pylint: disable=redefined-builtin """Initialize a screen that directly prints escape codes to an output terminal. """ super().__init__() self._partial_codes: list[int] = [] self._pal_escape: dict[str | None, str] = {} self._pal_attrspec: dict[str | None, AttrSpec] = {} self._alternate_buffer: bool = False signals.connect_signal(self, UPDATE_PALETTE_ENTRY, self._on_update_palette_entry) self.colors: Literal[1, 16, 88, 256, 16777216] = 16 # FIXME: detect this self.has_underline = True # FIXME: detect this self.prev_input_resize = 0 self.set_input_timeouts() self.screen_buf = None self._screen_buf_canvas = None self._resized = False self.maxrow = None self._mouse_tracking_enabled = False self.last_bstate = 0 self._setup_G1_done = False self._rows_used = None self._cy = 0 self.term = os.environ.get("TERM", "") self.fg_bright_is_bold = not self.term.startswith("xterm") self.bg_bright_is_blink = self.term == "linux" self.back_color_erase = not self.term.startswith("screen") self.register_palette_entry(None, "default", "default") self._next_timeout = None self.signal_handler_setter = signal.signal # Our connections to the world self._term_output_file = output self._term_input_file = input # pipe for signalling external event loops about resize events self._resize_pipe_rd, self._resize_pipe_wr = socket.socketpair() self._resize_pipe_rd.setblocking(False) def __del__(self) -> None: self._resize_pipe_rd.close() self._resize_pipe_wr.close() def __repr__(self) -> str: return f"<{self.__class__.__name__}(input={self._term_input_file}, output={self._term_output_file})>" def _sigwinch_handler(self, signum: int = 28, frame: FrameType | None = None) -> None: """ frame -- will always be None when the GLib event loop is being used. """ logger = self.logger.getChild("signal_handlers") logger.debug(f"SIGWINCH handler called with signum={signum!r}, frame={frame!r}") if IS_WINDOWS or not self._resized: self._resize_pipe_wr.send(b"R") logger.debug("Sent fake resize input to the pipe") self._resized = True self.screen_buf = None @property def _term_input_io(self) -> typing.IO | None: if hasattr(self._term_input_file, "fileno"): return self._term_input_file return None def _input_fileno(self) -> int | None: """Returns the fileno of the input stream, or None if it doesn't have one. A stream without a fileno can't participate in whatever. """ if hasattr(self._term_input_file, "fileno"): return self._term_input_file.fileno() return None def _on_update_palette_entry(self, name: str | None, *attrspecs: AttrSpec): # copy the attribute to a dictionary containing the escape seqences a: AttrSpec = attrspecs[{16: 0, 1: 1, 88: 2, 256: 3, 2**24: 4}[self.colors]] self._pal_attrspec[name] = a self._pal_escape[name] = self._attrspec_to_escape(a) def set_input_timeouts( self, max_wait: float | None = None, complete_wait: float = 0.125, resize_wait: float = 0.125, ) -> None: """ Set the get_input timeout values. All values are in floating point numbers of seconds. max_wait -- amount of time in seconds to wait for input when there is no input pending, wait forever if None complete_wait -- amount of time in seconds to wait when get_input detects an incomplete escape sequence at the end of the available input resize_wait -- amount of time in seconds to wait for more input after receiving two screen resize requests in a row to stop Urwid from consuming 100% cpu during a gradual window resize operation """ self.max_wait = max_wait if max_wait is not None: if self._next_timeout is None: self._next_timeout = max_wait else: self._next_timeout = min(self._next_timeout, self.max_wait) self.complete_wait = complete_wait self.resize_wait = resize_wait def set_mouse_tracking(self, enable: bool = True) -> None: """ Enable (or disable) mouse tracking. After calling this function get_input will include mouse click events along with keystrokes. """ enable = bool(enable) # noqa: FURB123,RUF100 if enable == self._mouse_tracking_enabled: return self._mouse_tracking(enable) self._mouse_tracking_enabled = enable def _mouse_tracking(self, enable: bool) -> None: if enable: self.write(escape.MOUSE_TRACKING_ON) else: self.write(escape.MOUSE_TRACKING_OFF) @abc.abstractmethod def _start(self, alternate_buffer: bool = True) -> None: """ Initialize the screen and input mode. alternate_buffer -- use alternate screen buffer """ def _stop_mouse_restore_buffer(self) -> None: """Stop mouse tracking and restore the screen.""" self._mouse_tracking(False) move_cursor = "" if self._alternate_buffer: move_cursor = escape.RESTORE_NORMAL_BUFFER elif self.maxrow is not None: move_cursor = escape.set_cursor_position(0, self.maxrow) self.write(self._attrspec_to_escape(AttrSpec("", "")) + escape.SI + move_cursor + escape.SHOW_CURSOR) self.flush() @abc.abstractmethod def _stop(self) -> None: """ Restore the screen. """ def write(self, data): """Write some data to the terminal. You may wish to override this if you're using something other than regular files for input and output. """ self._term_output_file.write(data) def flush(self): """Flush the output buffer. You may wish to override this if you're using something other than regular files for input and output. """ self._term_output_file.flush() @typing.overload def get_input(self, raw_keys: Literal[False]) -> list[str]: ... @typing.overload def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: """Return pending input as a list. raw_keys -- return raw keycodes as well as translated versions This function will immediately return all the input since the last time it was called. If there is no input pending it will wait before returning an empty list. The wait time may be configured with the set_input_timeouts function. If raw_keys is False (default) this function will return a list of keys pressed. If raw_keys is True this function will return a ( keys pressed, raw keycodes ) tuple instead. Examples of keys returned: * ASCII printable characters: " ", "a", "0", "A", "-", "/" * ASCII control characters: "tab", "enter" * Escape sequences: "up", "page up", "home", "insert", "f1" * Key combinations: "shift f1", "meta a", "ctrl b" * Window events: "window resize" When a narrow encoding is not enabled: * "Extended ASCII" characters: "\\xa1", "\\xb2", "\\xfe" When a wide encoding is enabled: * Double-byte characters: "\\xa1\\xea", "\\xb2\\xd4" When utf8 encoding is enabled: * Unicode characters: u"\\u00a5", u'\\u253c" Examples of mouse events returned: * Mouse button press: ('mouse press', 1, 15, 13), ('meta mouse press', 2, 17, 23) * Mouse drag: ('mouse drag', 1, 16, 13), ('mouse drag', 1, 17, 13), ('ctrl mouse drag', 1, 18, 13) * Mouse button release: ('mouse release', 0, 18, 13), ('ctrl mouse release', 0, 17, 23) """ logger = self.logger.getChild("get_input") if not self._started: raise RuntimeError self._wait_for_input_ready(self._next_timeout) keys, raw = self.parse_input(None, None, self.get_available_raw_input()) # Avoid pegging CPU at 100% when slowly resizing if keys == ["window resize"] and self.prev_input_resize: logger.debug('get_input: got "window resize" > 1 times. Enable throttling for resize.') for _ in range(2): self._wait_for_input_ready(self.resize_wait) new_keys, new_raw = self.parse_input(None, None, self.get_available_raw_input()) raw += new_raw if new_keys and new_keys != ["window resize"]: if "window resize" in new_keys: keys = new_keys else: keys.extend(new_keys) break if keys == ["window resize"]: self.prev_input_resize = 2 elif self.prev_input_resize == 2 and not keys: self.prev_input_resize = 1 else: self.prev_input_resize = 0 if raw_keys: return keys, raw return keys def get_input_descriptors(self) -> list[socket.socket | typing.IO | int]: """ Return a list of integer file descriptors that should be polled in external event loops to check for user input. Use this method if you are implementing your own event loop. This method is only called by `hook_event_loop`, so if you override that, you can safely ignore this. """ if not self._started: return [] fd_list: list[socket.socket | typing.IO | int] = [self._resize_pipe_rd] input_io = self._term_input_io if input_io is not None: fd_list.append(input_io) return fd_list _current_event_loop_handles = () @abc.abstractmethod def unhook_event_loop(self, event_loop: EventLoop) -> None: """ Remove any hooks added by hook_event_loop. """ @abc.abstractmethod def hook_event_loop( self, event_loop: EventLoop, callback: Callable[[list[str], list[int]], typing.Any], ) -> None: """ Register the given callback with the event loop, to be called with new input whenever it's available. The callback should be passed a list of processed keys and a list of unprocessed keycodes. Subclasses may wish to use parse_input to wrap the callback. """ _input_timeout = None def _make_legacy_input_wrapper(self, event_loop, callback): """ Support old Screen classes that still have a get_input_nonblocking and expect it to work. """ @functools.wraps(callback) def wrapper(): if self._input_timeout: event_loop.remove_alarm(self._input_timeout) self._input_timeout = None timeout, keys, raw = self.get_input_nonblocking() # pylint: disable=no-member # should we deprecate? if timeout is not None: self._input_timeout = event_loop.alarm(timeout, wrapper) callback(keys, raw) return wrapper def _get_input_codes(self) -> list[int]: return list(self._get_keyboard_codes()) def get_available_raw_input(self) -> list[int]: """ Return any currently available input. Does not block. This method is only used by the default `hook_event_loop` implementation; you can safely ignore it if you implement your own. """ logger = self.logger.getChild("get_available_raw_input") codes = [*self._partial_codes, *self._get_input_codes()] self._partial_codes = [] # clean out the pipe used to signal external event loops # that a resize has occurred with selectors.DefaultSelector() as selector: selector.register(self._resize_pipe_rd, selectors.EVENT_READ) present_resize_flag = selector.select(0) # nonblocking while present_resize_flag: logger.debug("Resize signal received. Cleaning socket.") # Argument "size" is maximum buffer size to read. Since we're emptying, set it reasonably big. self._resize_pipe_rd.recv(128) present_resize_flag = selector.select(0) return codes @typing.overload def parse_input( self, event_loop: None, callback: None, codes: list[int], wait_for_more: bool = ..., ) -> tuple[list[str], list[int]]: ... @typing.overload def parse_input( self, event_loop: EventLoop, callback: None, codes: list[int], wait_for_more: bool = ..., ) -> tuple[list[str], list[int]]: ... @typing.overload def parse_input( self, event_loop: EventLoop, callback: Callable[[list[str], list[int]], typing.Any], codes: list[int], wait_for_more: bool = ..., ) -> None: ... def parse_input( self, event_loop: EventLoop | None, callback: Callable[[list[str], list[int]], typing.Any] | None, codes: list[int], wait_for_more: bool = True, ) -> tuple[list[str], list[int]] | None: """ Read any available input from get_available_raw_input, parses it into keys, and calls the given callback. The current implementation tries to avoid any assumptions about what the screen or event loop look like; it only deals with parsing keycodes and setting a timeout when an incomplete one is detected. `codes` should be a sequence of keycodes, i.e. bytes. A bytearray is appropriate, but beware of using bytes, which only iterates as integers on Python 3. """ logger = self.logger.getChild("parse_input") # Note: event_loop may be None for 100% synchronous support, only used # by get_input. Not documented because you shouldn't be doing it. if self._input_timeout and event_loop: event_loop.remove_alarm(self._input_timeout) self._input_timeout = None original_codes = codes decoded_codes = [] try: while codes: run, codes = escape.process_keyqueue(codes, wait_for_more) decoded_codes.extend(run) except escape.MoreInputRequired: # Set a timer to wait for the rest of the input; if it goes off # without any new input having come in, use the partial input k = len(original_codes) - len(codes) raw_codes = original_codes[:k] self._partial_codes = codes def _parse_incomplete_input(): self._input_timeout = None self._partial_codes = [] self.parse_input(event_loop, callback, codes, wait_for_more=False) if event_loop: self._input_timeout = event_loop.alarm(self.complete_wait, _parse_incomplete_input) else: raw_codes = original_codes self._partial_codes = [] logger.debug(f"Decoded codes: {decoded_codes!r}, raw codes: {raw_codes!r}") if self._resized: decoded_codes.append("window resize") logger.debug('Added "window resize" to the codes') self._resized = False if callback: callback(decoded_codes, raw_codes) return None # For get_input return decoded_codes, raw_codes def _wait_for_input_ready(self, timeout: float | None) -> list[int]: logger = self.logger.getChild("wait_for_input_ready") fd_list = self.get_input_descriptors() logger.debug(f"Waiting for input: descriptors={fd_list!r}, timeout={timeout!r}") with selectors.DefaultSelector() as selector: for fd in fd_list: selector.register(fd, selectors.EVENT_READ) ready = selector.select(timeout) logger.debug(f"Input ready: {ready}") return [event.fd for event, _ in ready] @abc.abstractmethod def _read_raw_input(self, timeout: int) -> Iterable[int]: ... def _get_keyboard_codes(self) -> Iterable[int]: return self._read_raw_input(0) def _setup_G1(self) -> None: """ Initialize the G1 character set to graphics mode if required. """ if self._setup_G1_done: return while True: with contextlib.suppress(OSError): self.write(escape.DESIGNATE_G1_SPECIAL) self.flush() break self._setup_G1_done = True def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: """Paint screen with rendered canvas.""" def set_cursor_home() -> str: if not partial_display(): return escape.set_cursor_position(0, 0) return escape.CURSOR_HOME_COL + escape.move_cursor_up(cy) def set_cursor_position(x: int, y: int) -> str: if not partial_display(): return escape.set_cursor_position(x, y) if cy > y: return "\b" + escape.CURSOR_HOME_COL + escape.move_cursor_up(cy - y) + escape.move_cursor_right(x) return "\b" + escape.CURSOR_HOME_COL + escape.move_cursor_down(y - cy) + escape.move_cursor_right(x) def is_blank_row(row: list[tuple[object, Literal["0", "U"] | None], bytes]) -> bool: if len(row) > 1: return False return not row[0][2].strip() def attr_to_escape(a: AttrSpec | str | None) -> str: if a in self._pal_escape: return self._pal_escape[a] if isinstance(a, AttrSpec): return self._attrspec_to_escape(a) if a is None: return self._attrspec_to_escape(AttrSpec("default", "default")) # undefined attributes use default/default self.logger.debug(f"Undefined attribute: {a!r}") return self._attrspec_to_escape(AttrSpec("default", "default")) def using_standout_or_underline(a: AttrSpec | str) -> bool: a = self._pal_attrspec.get(a, a) return isinstance(a, AttrSpec) and (a.standout or a.underline) encoding = util.get_encoding() logger = self.logger.getChild("draw_screen") (maxcol, maxrow) = size if not self._started: raise RuntimeError if maxrow != canvas.rows(): raise ValueError(maxrow) # quick return if nothing has changed if self.screen_buf and canvas is self._screen_buf_canvas: return self._setup_G1() if self._resized: # handle resize before trying to draw screen logger.debug("Not drawing screen: screen resized and resize was not handled") return logger.debug(f"Drawing screen with size {size!r}") last_attributes = None # Default = empty output: list[str] = [escape.HIDE_CURSOR, attr_to_escape(last_attributes)] def partial_display() -> bool: # returns True if the screen is in partial display mode ie. only some rows belong to the display return self._rows_used is not None if not partial_display(): output.append(escape.CURSOR_HOME) if self.screen_buf: osb = self.screen_buf else: osb = [] sb: list[list[tuple[object, Literal["0", "U"] | None, bytes]]] = [] cy = self._cy y = -1 ins = None output.append(set_cursor_home()) cy = 0 first = True last_charset_flag = None for row in canvas.content(): y += 1 if osb and y < len(osb) and osb[y] == row: # this row of the screen buffer matches what is # currently displayed, so we can skip this line sb.append(osb[y]) continue sb.append(row) # leave blank lines off display when we are using # the default screen buffer (allows partial screen) if partial_display() and y > self._rows_used: if is_blank_row(row): continue self._rows_used = y if y or partial_display(): output.append(set_cursor_position(0, y)) # after updating the line we will be just over the # edge, but terminals still treat this as being # on the same line cy = y whitespace_at_end = False if row: a, cs, run = row[-1] if run[-1:] == b" " and self.back_color_erase and not using_standout_or_underline(a): whitespace_at_end = True row = row[:-1] + [(a, cs, run.rstrip(b" "))] # noqa: PLW2901 elif y == maxrow - 1 and maxcol > 1: row, back, ins = self._last_row(row) # noqa: PLW2901 for a, cs, run in row: if not isinstance(run, bytes): # canvases render with bytes raise TypeError(run) if cs != "U": run = run.translate(UNPRINTABLE_TRANS_TABLE) # noqa: PLW2901 if last_attributes != a: output.append(attr_to_escape(a)) last_attributes = a if encoding != "utf-8" and (first or last_charset_flag != cs): if cs not in {None, "0", "U"}: raise ValueError(cs) if last_charset_flag == "U": output.append(escape.IBMPC_OFF) if cs is None: output.append(escape.SI) elif cs == "U": output.append(escape.IBMPC_ON) else: output.append(escape.SO) last_charset_flag = cs output.append(run.decode(encoding, "replace")) first = False if ins: (inserta, insertcs, inserttext) = ins ias = attr_to_escape(inserta) if insertcs not in {None, "0", "U"}: raise ValueError(insertcs) if isinstance(inserttext, bytes): inserttext = inserttext.decode(encoding) output.extend(("\x08" * back, ias)) # pylint: disable=used-before-assignment # defined in `if row` if encoding != "utf-8": if cs is None: icss = escape.SI elif cs == "U": icss = escape.IBMPC_ON else: icss = escape.SO output.append(icss) if not IS_WINDOWS: output += [escape.INSERT_ON, inserttext, escape.INSERT_OFF] else: output += [f"{escape.ESC}[{str_util.calc_width(inserttext, 0, len(inserttext))}@", inserttext] if encoding != "utf-8" and cs == "U": output.append(escape.IBMPC_OFF) if whitespace_at_end: output.append(escape.ERASE_IN_LINE_RIGHT) if canvas.cursor is not None: x, y = canvas.cursor output += [set_cursor_position(x, y), escape.SHOW_CURSOR] self._cy = y if self._resized: # handle resize before trying to draw screen return try: for line in output: if isinstance(line, bytes): line = line.decode(encoding, "replace") # noqa: PLW2901 self.write(line) self.flush() except OSError as e: # ignore interrupted syscall if e.args[0] != 4: raise self.screen_buf = sb self._screen_buf_canvas = canvas def _last_row(self, row: list[tuple[object, Literal["0", "U"] | None, bytes]]) -> tuple[ list[tuple[object, Literal["0", "U"] | None, bytes]], int, tuple[object, Literal["0", "U"] | None, bytes], ]: """On the last row we need to slide the bottom right character into place. Calculate the new line, attr and an insert sequence to do that. eg. last row: XXXXXXXXXXXXXXXXXXXXYZ Y will be drawn after Z, shifting Z into position. """ new_row = row[:-1] z_attr, z_cs, last_text = row[-1] last_cols = str_util.calc_width(last_text, 0, len(last_text)) last_offs, z_col = str_util.calc_text_pos(last_text, 0, len(last_text), last_cols - 1) if last_offs == 0: z_text = last_text del new_row[-1] # we need another segment y_attr, y_cs, nlast_text = row[-2] nlast_cols = str_util.calc_width(nlast_text, 0, len(nlast_text)) z_col += nlast_cols nlast_offs, y_col = str_util.calc_text_pos(nlast_text, 0, len(nlast_text), nlast_cols - 1) y_text = nlast_text[nlast_offs:] if nlast_offs: new_row.append((y_attr, y_cs, nlast_text[:nlast_offs])) else: z_text = last_text[last_offs:] y_attr, y_cs = z_attr, z_cs nlast_cols = str_util.calc_width(last_text, 0, last_offs) nlast_offs, y_col = str_util.calc_text_pos(last_text, 0, last_offs, nlast_cols - 1) y_text = last_text[nlast_offs:last_offs] if nlast_offs: new_row.append((y_attr, y_cs, last_text[:nlast_offs])) new_row.append((z_attr, z_cs, z_text)) return new_row, z_col - y_col, (y_attr, y_cs, y_text) def clear(self) -> None: """ Force the screen to be completely repainted on the next call to draw_screen(). """ self.screen_buf = None def _attrspec_to_escape(self, a: AttrSpec) -> str: """ Convert AttrSpec instance a to an escape sequence for the terminal >>> s = Screen() >>> s.set_terminal_properties(colors=256) >>> a2e = s._attrspec_to_escape >>> a2e(s.AttrSpec('brown', 'dark green')) '\\x1b[0;33;42m' >>> a2e(s.AttrSpec('#fea,underline', '#d0d')) '\\x1b[0;38;5;229;4;48;5;164m' """ if self.term == "fbterm": fg = escape.ESC + f"[1;{a.foreground_number:d}}}" bg = escape.ESC + f"[2;{a.background_number:d}}}" return fg + bg if a.foreground_true: fg = f"38;2;{';'.join(str(part) for part in a.get_rgb_values()[0:3])}" elif a.foreground_high: fg = f"38;5;{a.foreground_number:d}" elif a.foreground_basic: if a.foreground_number > 7: if self.fg_bright_is_bold: fg = f"1;{a.foreground_number - 8 + 30:d}" else: fg = f"{a.foreground_number - 8 + 90:d}" else: fg = f"{a.foreground_number + 30:d}" else: fg = "39" st = ( "1;" * a.bold + "3;" * a.italics + "4;" * a.underline + "5;" * a.blink + "7;" * a.standout + "9;" * a.strikethrough ) if a.background_true: bg = f"48;2;{';'.join(str(part) for part in a.get_rgb_values()[3:6])}" elif a.background_high: bg = f"48;5;{a.background_number:d}" elif a.background_basic: if a.background_number > 7: if self.bg_bright_is_blink: bg = f"5;{a.background_number - 8 + 40:d}" else: # this doesn't work on most terminals bg = f"{a.background_number - 8 + 100:d}" else: bg = f"{a.background_number + 40:d}" else: bg = "49" return f"{escape.ESC}[0;{fg};{st}{bg}m" def set_terminal_properties( self, colors: Literal[1, 16, 88, 256, 16777216] | None = None, bright_is_bold: bool | None = None, has_underline: bool | None = None, ) -> None: """ colors -- number of colors terminal supports (1, 16, 88, 256, or 2**24) or None to leave unchanged bright_is_bold -- set to True if this terminal uses the bold setting to create bright colors (numbers 8-15), set to False if this Terminal can create bright colors without bold or None to leave unchanged has_underline -- set to True if this terminal can use the underline setting, False if it cannot or None to leave unchanged """ if colors is None: colors = self.colors if bright_is_bold is None: bright_is_bold = self.fg_bright_is_bold if has_underline is None: has_underline = self.has_underline if colors == self.colors and bright_is_bold == self.fg_bright_is_bold and has_underline == self.has_underline: return self.colors = colors self.fg_bright_is_bold = bright_is_bold self.has_underline = has_underline self.clear() self._pal_escape = {} for p, v in self._palette.items(): self._on_update_palette_entry(p, *v) def reset_default_terminal_palette(self) -> None: """ Attempt to set the terminal palette to default values as taken from xterm. Uses number of colors from current set_terminal_properties() screen setting. """ if self.colors == 1: return if self.colors == 2**24: colors = 256 else: colors = self.colors def rgb_values(n) -> tuple[int | None, int | None, int | None]: if colors == 16: aspec = AttrSpec(f"h{n:d}", "", 256) else: aspec = AttrSpec(f"h{n:d}", "", colors) return aspec.get_rgb_values()[:3] entries = [(n, *rgb_values(n)) for n in range(min(colors, 256))] self.modify_terminal_palette(entries) def modify_terminal_palette(self, entries: list[tuple[int, int | None, int | None, int | None]]): """ entries - list of (index, red, green, blue) tuples. Attempt to set part of the terminal palette (this does not work on all terminals.) The changes are sent as a single escape sequence so they should all take effect at the same time. 0 <= index < 256 (some terminals will only have 16 or 88 colors) 0 <= red, green, blue < 256 """ if self.term == "fbterm": modify = [f"{index:d};{red:d};{green:d};{blue:d}" for index, red, green, blue in entries] self.write(f"\x1b[3;{';'.join(modify)}}}") else: modify = [f"{index:d};rgb:{red:02x}/{green:02x}/{blue:02x}" for index, red, green, blue in entries] self.write(f"\x1b]4;{';'.join(modify)}\x1b\\") self.flush() # shortcut for creating an AttrSpec with this screen object's # number of colors def AttrSpec(self, fg, bg) -> AttrSpec: return AttrSpec(fg, bg, self.colors)
33,600
Python
.py
749
33.993324
119
0.576202
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,278
__init__.py
urwid_urwid/urwid/display/__init__.py
"""Package with Display implementations for urwid.""" from __future__ import annotations import importlib import typing __all__ = ( "BLACK", "BROWN", "DARK_BLUE", "DARK_CYAN", "DARK_GRAY", "DARK_GREEN", "DARK_MAGENTA", "DARK_RED", "DEFAULT", "LIGHT_BLUE", "LIGHT_CYAN", "LIGHT_GRAY", "LIGHT_GREEN", "LIGHT_MAGENTA", "LIGHT_RED", "UPDATE_PALETTE_ENTRY", "WHITE", "YELLOW", "AttrSpec", "AttrSpecError", "BaseScreen", "RealTerminal", "ScreenError", # Lazy imported "html_fragment", "lcd", "raw", "web", ) from . import raw from .common import ( BLACK, BROWN, DARK_BLUE, DARK_CYAN, DARK_GRAY, DARK_GREEN, DARK_MAGENTA, DARK_RED, DEFAULT, LIGHT_BLUE, LIGHT_CYAN, LIGHT_GRAY, LIGHT_GREEN, LIGHT_MAGENTA, LIGHT_RED, UPDATE_PALETTE_ENTRY, WHITE, YELLOW, AttrSpec, AttrSpecError, BaseScreen, RealTerminal, ScreenError, ) try: from . import curses __all__ += ("curses",) except ImportError: pass # Moved modules handling __locals: dict[str, typing.Any] = locals() # use mutable access for pure lazy loading # Lazy load modules _lazy_load: frozenset[str] = frozenset( ( "html_fragment", "lcd", "web", ) ) def __getattr__(name: str) -> typing.Any: """Get attributes lazy. :return: attribute by name :raises AttributeError: attribute is not defined for lazy load """ if name in _lazy_load: mod = importlib.import_module(f"{__package__}.{name}") __locals[name] = mod return mod raise AttributeError(f"{name} not found in {__package__}")
1,732
Python
.py
85
15.752941
86
0.611621
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,279
lcd.py
urwid_urwid/urwid/display/lcd.py
# Urwid LCD display module # Copyright (C) 2010 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import abc import time import typing from .common import BaseScreen if typing.TYPE_CHECKING: from collections.abc import Iterable, Sequence from typing_extensions import Literal from urwid import Canvas class LCDScreen(BaseScreen, abc.ABC): """Base class for LCD-based screens.""" DISPLAY_SIZE: tuple[int, int] def set_terminal_properties( self, colors: Literal[1, 16, 88, 256, 16777216] | None = None, bright_is_bold: bool | None = None, has_underline: bool | None = None, ) -> None: pass def set_input_timeouts(self, *args): pass def reset_default_terminal_palette(self, *args): pass def get_cols_rows(self): return self.DISPLAY_SIZE class CFLCDScreen(LCDScreen, abc.ABC): """ Common methods for Crystal Fonts LCD displays """ KEYS: typing.ClassVar[list[str | None]] = [ None, # no key with code 0 "up_press", "down_press", "left_press", "right_press", "enter_press", "exit_press", "up_release", "down_release", "left_release", "right_release", "enter_release", "exit_release", "ul_press", "ur_press", "ll_press", "lr_press", "ul_release", "ur_release", "ll_release", "lr_release", ] CMD_PING = 0 CMD_VERSION = 1 CMD_CLEAR = 6 CMD_CGRAM = 9 CMD_CURSOR_POSITION = 11 # data = [col, row] CMD_CURSOR_STYLE = 12 # data = [style (0-4)] CMD_LCD_CONTRAST = 13 # data = [contrast (0-255)] CMD_BACKLIGHT = 14 # data = [power (0-100)] CMD_LCD_DATA = 31 # data = [col, row] + text CMD_GPO = 34 # data = [pin(0-12), value(0-100)] # sent from device CMD_KEY_ACTIVITY = 0x80 CMD_ACK = 0x40 # in high two bits ie. & 0xc0 CURSOR_NONE = 0 CURSOR_BLINKING_BLOCK = 1 CURSOR_UNDERSCORE = 2 CURSOR_BLINKING_BLOCK_UNDERSCORE = 3 CURSOR_INVERTING_BLINKING_BLOCK = 4 MAX_PACKET_DATA_LENGTH = 22 colors = 1 has_underline = False def __init__(self, device_path: str, baud: int) -> None: """ device_path -- eg. '/dev/ttyUSB0' baud -- baud rate """ super().__init__() self.device_path = device_path from serial import Serial self._device = Serial(device_path, baud, timeout=0) self._unprocessed = bytearray() @classmethod def get_crc(cls, buf: Iterable[int]) -> bytes: # This seed makes the output of this shift based algorithm match # the table based algorithm. The center 16 bits of the 32-bit # "newCRC" are used for the CRC. The MSB of the lower byte is used # to see what bit was shifted out of the center 16 bit CRC # accumulator ("carry flag analog"); new_crc = 0x00F32100 for byte in buf: # Push this byte's bits through a software # implementation of a hardware shift & xor. for bit_count in range(8): # Shift the CRC accumulator new_crc >>= 1 # The new MSB of the CRC accumulator comes # from the LSB of the current data byte. if byte & (0x01 << bit_count): new_crc |= 0x00800000 # If the low bit of the current CRC accumulator was set # before the shift, then we need to XOR the accumulator # with the polynomial (center 16 bits of 0x00840800) if new_crc & 0x00000080: new_crc ^= 0x00840800 # All the data has been done. Do 16 more bits of 0 data. for _bit_count in range(16): # Shift the CRC accumulator new_crc >>= 1 # If the low bit of the current CRC accumulator was set # before the shift we need to XOR the accumulator with # 0x00840800. if new_crc & 0x00000080: new_crc ^= 0x00840800 # Return the center 16 bits, making this CRC match the one's # complement that is sent in the packet. return (((~new_crc) >> 8) & 0xFFFF).to_bytes(2, "little") def _send_packet(self, command: int, data: bytes) -> None: """ low-level packet sending. Following the protocol requires waiting for ack packet between sending each packet to the device. """ buf = bytearray([command, len(data)]) buf.extend(data) buf.extend(self.get_crc(buf)) self._device.write(buf) def _read_packet(self) -> tuple[int, bytearray] | None: """ low-level packet reading. returns (command/report code, data) or None This method stored data read and tries to resync when bad data is received. """ # pull in any new data available self._unprocessed += self._device.read() while True: try: command, data, unprocessed = self._parse_data(self._unprocessed) self._unprocessed = unprocessed except self.MoreDataRequired: # noqa: PERF203 return None except self.InvalidPacket: # throw out a byte and try to parse again self._unprocessed = self._unprocessed[1:] else: return command, data class InvalidPacket(Exception): pass class MoreDataRequired(Exception): pass @classmethod def _parse_data(cls, data: bytearray) -> tuple[int, bytearray, bytearray]: """ Try to read a packet from the start of data, returning (command/report code, packet_data, remaining_data) or raising InvalidPacket or MoreDataRequired """ if len(data) < 2: raise cls.MoreDataRequired command: int = data[0] packet_len: int = data[1] if packet_len > cls.MAX_PACKET_DATA_LENGTH: raise cls.InvalidPacket("length value too large") if len(data) < packet_len + 4: raise cls.MoreDataRequired data_end = 2 + packet_len crc = cls.get_crc(data[:data_end]) pcrc = data[data_end : data_end + 2] if crc != pcrc: raise cls.InvalidPacket("CRC doesn't match") return command, data[2:data_end], data[data_end + 2 :] class KeyRepeatSimulator: """ Provide simulated repeat key events when given press and release events. If two or more keys are pressed disable repeating until all keys are released. """ def __init__(self, repeat_delay: float, repeat_next: float) -> None: """ repeat_delay -- seconds to wait before starting to repeat keys repeat_next -- time between each repeated key """ self.repeat_delay = repeat_delay self.repeat_next = repeat_next self.pressed: dict[str, float] = {} self.multiple_pressed = False def press(self, key: str) -> None: if self.pressed: self.multiple_pressed = True self.pressed[key] = time.time() def release(self, key: str) -> None: if key not in self.pressed: return # ignore extra release events del self.pressed[key] if not self.pressed: self.multiple_pressed = False def next_event(self) -> tuple[float, str] | None: """ Return (remaining, key) where remaining is the number of seconds (float) until the key repeat event should be sent, or None if no events are pending. """ if len(self.pressed) != 1 or self.multiple_pressed: return None for key, val in self.pressed.items(): return max(0.0, val + self.repeat_delay - time.time()), key return None def sent_event(self) -> None: """ Cakk this method when you have sent a key repeat event so the timer will be reset for the next event """ if len(self.pressed) != 1: return # ignore event that shouldn't have been sent for key in self.pressed: self.pressed[key] = time.time() - self.repeat_delay + self.repeat_next return class CF635Screen(CFLCDScreen): """ Crystal Fontz 635 display 20x4 character display + cursor no foreground/background colors or settings supported see CGROM for list of close unicode matches to characters available 6 button input up, down, left, right, enter (check mark), exit (cross) """ DISPLAY_SIZE = (20, 4) # ① through ⑧ are programmable CGRAM (chars 0-7, repeated at 8-15) # double arrows (⇑⇓) appear as double arrowheads (chars 18, 19) # ⑴ resembles a bell # ⑵ resembles a filled-in "Y" # ⑶ is the letters "Pt" together # partial blocks (▇▆▄▃▁) are actually shorter versions of (▉▋▌▍▏) # both groups are intended to draw horizontal bars with pixel # precision, use ▇*[▆▄▃▁]? for a thin bar or ▉*[▋▌▍▏]? for a thick bar CGROM = ( "①②③④⑤⑥⑦⑧①②③④⑤⑥⑦⑧" "►◄⇑⇓«»↖↗↙↘▲▼↲^ˇ█" " !\"#¤%&'()*+,-./" "0123456789:;<=>?" "¡ABCDEFGHIJKLMNO" "PQRSTUVWXYZÄÖÑܧ" "¿abcdefghijklmno" "pqrstuvwxyzäöñüà" "⁰¹²³⁴⁵⁶⁷⁸⁹½¼±≥≤μ" "♪♫⑴♥♦⑵⌜⌟“”()αɛδ∞" "@£$¥èéùìòÇᴾØøʳÅå" "⌂¢ΦτλΩπΨΣθΞ♈ÆæßÉ" "ΓΛΠϒ_ÈÊêçğŞşİι~◊" "▇▆▄▃▁ƒ▉▋▌▍▏⑶◽▪↑→" "↓←ÁÍÓÚÝáíóúýÔôŮů" r"ČĔŘŠŽčĕřšž[\]{|}" ) cursor_style = CFLCDScreen.CURSOR_INVERTING_BLINKING_BLOCK def __init__( self, device_path: str, baud: int = 115200, repeat_delay: float = 0.5, repeat_next: float = 0.125, key_map: Iterable[str] = ("up", "down", "left", "right", "enter", "esc"), ): """ device_path -- eg. '/dev/ttyUSB0' baud -- baud rate repeat_delay -- seconds to wait before starting to repeat keys repeat_next -- time between each repeated key key_map -- the keys to send for this device's buttons """ super().__init__(device_path, baud) self.repeat_delay = repeat_delay self.repeat_next = repeat_next self.key_repeat = KeyRepeatSimulator(repeat_delay, repeat_next) self.key_map = tuple(key_map) self._last_command = None self._last_command_time = 0 self._command_queue: list[tuple[int, bytearray]] = [] self._screen_buf = None self._previous_canvas = None self._update_cursor = False def get_input_descriptors(self) -> list[int]: """ return the fd from our serial device so we get called on input and responses """ return [self._device.fd] def get_input_nonblocking(self) -> tuple[None, list[str], list[int]]: """ Return a (next_input_timeout, keys_pressed, raw_keycodes) tuple. The protocol for our device requires waiting for acks between each command, so this method responds to those as well as key press and release events. Key repeat events are simulated here as the device doesn't send any for us. raw_keycodes are the bytes of messages we received, which might not seem to have any correspondence to keys_pressed. """ data_input: list[str] = [] raw_data_input: list[int] = [] timeout = None packet = self._read_packet() while packet: command, data = packet if command == self.CMD_KEY_ACTIVITY and data: d0 = data[0] if 1 <= d0 <= 12: release = d0 > 6 keycode = d0 - (release * 6) - 1 key = self.key_map[keycode] if release: self.key_repeat.release(key) else: data_input.append(key) self.key_repeat.press(key) raw_data_input.append(d0) elif command & 0xC0 == 0x40 and command & 0x3F == self._last_command: # "ACK" self._send_next_command() packet = self._read_packet() next_repeat = self.key_repeat.next_event() if next_repeat: timeout, key = next_repeat if not timeout: data_input.append(key) self.key_repeat.sent_event() timeout = None return timeout, data_input, raw_data_input def _send_next_command(self) -> None: """ send out the next command in the queue """ if not self._command_queue: self._last_command = None return command, data = self._command_queue.pop(0) self._send_packet(command, data) self._last_command = command # record command for ACK self._last_command_time = time.time() def queue_command(self, command: int, data: bytearray) -> None: self._command_queue.append((command, data)) # not waiting? send away! if self._last_command is None: self._send_next_command() def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: if size != self.DISPLAY_SIZE: raise ValueError(size) if self._screen_buf: osb = self._screen_buf else: osb = [] sb = [] for y, row in enumerate(canvas.content()): text = [run for _a, _cs, run in row] if not osb or osb[y] != text: data = bytearray([0, y]) for elem in text: data.extend(elem) self.queue_command(self.CMD_LCD_DATA, data) sb.append(text) if ( self._previous_canvas and self._previous_canvas.cursor == canvas.cursor and (not self._update_cursor or not canvas.cursor) ): pass elif canvas.cursor is None: self.queue_command(self.CMD_CURSOR_STYLE, bytearray([self.CURSOR_NONE])) else: x, y = canvas.cursor self.queue_command(self.CMD_CURSOR_POSITION, bytearray([x, y])) self.queue_command(self.CMD_CURSOR_STYLE, bytearray([self.cursor_style])) self._update_cursor = False self._screen_buf = sb self._previous_canvas = canvas def program_cgram(self, index: int, data: Sequence[int]) -> None: """ Program character data. Characters available as chr(0) through chr(7), and repeated as chr(8) through chr(15). index -- 0 to 7 index of character to program data -- list of 8, 6-bit integer values top to bottom with MSB on the left side of the character. """ if not 0 <= index <= 7: raise ValueError(index) if len(data) != 8: raise ValueError(data) self.queue_command(self.CMD_CGRAM, bytearray([index]) + bytearray(data)) def set_cursor_style(self, style: Literal[1, 2, 3, 4]) -> None: """ style -- CURSOR_BLINKING_BLOCK, CURSOR_UNDERSCORE, CURSOR_BLINKING_BLOCK_UNDERSCORE or CURSOR_INVERTING_BLINKING_BLOCK """ if not 1 <= style <= 4: raise ValueError(style) self.cursor_style = style self._update_cursor = True def set_backlight(self, value: int) -> None: """ Set backlight brightness value -- 0 to 100 """ if not 0 <= value <= 100: raise ValueError(value) self.queue_command(self.CMD_BACKLIGHT, bytearray([value])) def set_lcd_contrast(self, value: int) -> None: """ value -- 0 to 255 """ if not 0 <= value <= 255: raise ValueError(value) self.queue_command(self.CMD_LCD_CONTRAST, bytearray([value])) def set_led_pin(self, led: Literal[0, 1, 2, 3], rg: Literal[0, 1], value: int) -> None: """ led -- 0 to 3 rg -- 0 for red, 1 for green value -- 0 to 100 """ if not 0 <= led <= 3: raise ValueError(led) if rg not in {0, 1}: raise ValueError(rg) if not 0 <= value <= 100: raise ValueError(value) self.queue_command(self.CMD_GPO, bytearray([12 - 2 * led - rg, value]))
17,607
Python
.py
445
29.721348
105
0.58251
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,280
_win32_raw_display.py
urwid_urwid/urwid/display/_win32_raw_display.py
# Urwid raw display module # Copyright (C) 2004-2009 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Direct terminal UI implementation """ from __future__ import annotations import contextlib import functools import logging import selectors import socket import sys import threading import typing from ctypes import byref from ctypes.wintypes import DWORD from urwid import signals from . import _raw_display_base, _win32, escape from .common import INPUT_DESCRIPTORS_CHANGED if typing.TYPE_CHECKING: from collections.abc import Callable from urwid.event_loop import EventLoop class Screen(_raw_display_base.Screen): _term_input_file: socket.socket def __init__( self, input: socket.socket | None = None, # noqa: A002 # pylint: disable=redefined-builtin output: typing.TextIO = sys.stdout, ) -> None: """Initialize a screen that directly prints escape codes to an output terminal. """ if input is None: input, self._send_input = socket.socketpair() # noqa: A001 super().__init__(input, output) _dwOriginalOutMode = None _dwOriginalInMode = None def _start(self, alternate_buffer: bool = True) -> None: """ Initialize the screen and input mode. alternate_buffer -- use alternate screen buffer """ if alternate_buffer: self.write(escape.SWITCH_TO_ALTERNATE_BUFFER) self._rows_used = None else: self._rows_used = 0 handle_out = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) handle_in = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) self._dwOriginalOutMode = DWORD() self._dwOriginalInMode = DWORD() _win32.GetConsoleMode(handle_out, byref(self._dwOriginalOutMode)) _win32.GetConsoleMode(handle_in, byref(self._dwOriginalInMode)) # TODO: Restore on exit dword_out_mode = DWORD( self._dwOriginalOutMode.value | _win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING | _win32.DISABLE_NEWLINE_AUTO_RETURN ) dword_in_mode = DWORD( self._dwOriginalInMode.value | _win32.ENABLE_WINDOW_INPUT | _win32.ENABLE_VIRTUAL_TERMINAL_INPUT ) ok = _win32.SetConsoleMode(handle_out, dword_out_mode) if not ok: raise RuntimeError(f"ConsoleMode set failed for output. Err: {ok!r}") ok = _win32.SetConsoleMode(handle_in, dword_in_mode) if not ok: raise RuntimeError(f"ConsoleMode set failed for input. Err: {ok!r}") self._alternate_buffer = alternate_buffer self._next_timeout = self.max_wait signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) # restore mouse tracking to previous state self._mouse_tracking(self._mouse_tracking_enabled) return super()._start() def _stop(self) -> None: """ Restore the screen. """ self.clear() signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) self._stop_mouse_restore_buffer() handle_out = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) handle_in = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) ok = _win32.SetConsoleMode(handle_out, self._dwOriginalOutMode) if not ok: raise RuntimeError(f"ConsoleMode set failed for output. Err: {ok!r}") ok = _win32.SetConsoleMode(handle_in, self._dwOriginalInMode) if not ok: raise RuntimeError(f"ConsoleMode set failed for input. Err: {ok!r}") super()._stop() def unhook_event_loop(self, event_loop: EventLoop) -> None: """ Remove any hooks added by hook_event_loop. """ if self._input_thread is not None: self._input_thread.should_exit = True with contextlib.suppress(RuntimeError): self._input_thread.join(5) self._input_thread = None for handle in self._current_event_loop_handles: event_loop.remove_watch_file(handle) if self._input_timeout: event_loop.remove_alarm(self._input_timeout) self._input_timeout = None def hook_event_loop( self, event_loop: EventLoop, callback: Callable[[list[str], list[int]], typing.Any], ) -> None: """ Register the given callback with the event loop, to be called with new input whenever it's available. The callback should be passed a list of processed keys and a list of unprocessed keycodes. Subclasses may wish to use parse_input to wrap the callback. """ self._input_thread = ReadInputThread(self._send_input, lambda: self._sigwinch_handler(28)) self._input_thread.start() if hasattr(self, "get_input_nonblocking"): wrapper = self._make_legacy_input_wrapper(event_loop, callback) else: @functools.wraps(callback) def wrapper() -> tuple[list[str], typing.Any] | None: return self.parse_input(event_loop, callback, self.get_available_raw_input()) fds = self.get_input_descriptors() handles = [event_loop.watch_file(fd if isinstance(fd, int) else fd.fileno(), wrapper) for fd in fds] self._current_event_loop_handles = handles _input_thread: ReadInputThread | None = None def _read_raw_input(self, timeout: int) -> bytearray: ready = self._wait_for_input_ready(timeout) fd = self._input_fileno() chars = bytearray() if fd is None or fd not in ready: return chars with selectors.DefaultSelector() as selector: selector.register(fd, selectors.EVENT_READ) input_ready = selector.select(0) while input_ready: chars.extend(self._term_input_file.recv(1024)) input_ready = selector.select(0) return chars def get_cols_rows(self) -> tuple[int, int]: """Return the terminal dimensions (num columns, num rows).""" y, x = super().get_cols_rows() with contextlib.suppress(OSError): # Term size could not be determined if hasattr(self._term_output_file, "fileno"): if self._term_output_file != sys.stdout: raise RuntimeError("Unexpected terminal output file") handle = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) info = _win32.CONSOLE_SCREEN_BUFFER_INFO() ok = _win32.GetConsoleScreenBufferInfo(handle, byref(info)) if ok: # Fallback will be used in case of term size could not be determined y, x = info.dwSize.Y, info.dwSize.X self.maxrow = y return x, y class ReadInputThread(threading.Thread): name = "urwid Windows input reader" daemon = True should_exit: bool = False def __init__( self, input_socket: socket.socket, resize: Callable[[], typing.Any], ) -> None: self._input = input_socket self._resize = resize self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) super().__init__() def run(self) -> None: hIn = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) MAX = 2048 read = DWORD(0) arrtype = _win32.INPUT_RECORD * MAX input_records = arrtype() while True: _win32.ReadConsoleInputW(hIn, byref(input_records), MAX, byref(read)) if self.should_exit: return for i in range(read.value): inp = input_records[i] if inp.EventType == _win32.EventType.KEY_EVENT: if not inp.Event.KeyEvent.bKeyDown: continue input_data = inp.Event.KeyEvent.uChar.UnicodeChar # On Windows atomic press/release of modifier keys produce phantom input with code NULL. # This input cannot be decoded and should be handled as garbage. input_bytes = input_data.encode("utf-8") if input_bytes != b"\x00": self._input.send(input_bytes) elif inp.EventType == _win32.EventType.WINDOW_BUFFER_SIZE_EVENT: self._resize() else: pass # TODO: handle mouse events def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
9,314
Python
.py
214
34.359813
108
0.627418
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,281
_win32.py
urwid_urwid/urwid/display/_win32.py
from __future__ import annotations import enum import typing from ctypes import POINTER, Structure, Union, windll from ctypes.wintypes import BOOL, CHAR, DWORD, HANDLE, LPDWORD, SHORT, UINT, WCHAR, WORD # https://docs.microsoft.com/de-de/windows/console/getstdhandle STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 # https://docs.microsoft.com/de-de/windows/console/setconsolemode ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 DISABLE_NEWLINE_AUTO_RETURN = 0x0008 ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 ENABLE_WINDOW_INPUT = 0x0008 class COORD(Structure): """https://docs.microsoft.com/en-us/windows/console/coord-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("X", SHORT), ("Y", SHORT), ] class SMALL_RECT(Structure): """https://docs.microsoft.com/en-us/windows/console/small-rect-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("Left", SHORT), ("Top", SHORT), ("Right", SHORT), ("Bottom", SHORT), ] class CONSOLE_SCREEN_BUFFER_INFO(Structure): """https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", COORD), ] class uChar(Union): """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("AsciiChar", CHAR), ("UnicodeChar", WCHAR), ] class KEY_EVENT_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("bKeyDown", BOOL), ("wRepeatCount", WORD), ("wVirtualKeyCode", WORD), ("wVirtualScanCode", WORD), ("uChar", uChar), ("dwControlKeyState", DWORD), ] class MOUSE_EVENT_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("dwMousePosition", COORD), ("dwButtonState", DWORD), ("dwControlKeyState", DWORD), ("dwEventFlags", DWORD), ] class MouseButtonState(enum.IntFlag): """https://learn.microsoft.com/en-us/windows/console/mouse-event-record-str""" FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001 RIGHTMOST_BUTTON_PRESSED = 0x0002 FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004 FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008 FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010 class MouseEventFlags(enum.IntFlag): """https://learn.microsoft.com/en-us/windows/console/mouse-event-record-str""" BUTTON_PRESSED = 0x0000 # Default action, used in examples, but not in official enum MOUSE_MOVED = 0x0001 DOUBLE_CLICK = 0x0002 MOUSE_WHEELED = 0x0004 MOUSE_HWHEELED = 0x0008 class WINDOW_BUFFER_SIZE_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/window-buffer-size-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [("dwSize", COORD)] class MENU_EVENT_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/menu-event-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [("dwCommandId", UINT)] class FOCUS_EVENT_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/focus-event-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [("bSetFocus", BOOL)] class Event(Union): """https://docs.microsoft.com/en-us/windows/console/input-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [ ("KeyEvent", KEY_EVENT_RECORD), ("MouseEvent", MOUSE_EVENT_RECORD), ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD), ("MenuEvent", MENU_EVENT_RECORD), ("FocusEvent", FOCUS_EVENT_RECORD), ] class INPUT_RECORD(Structure): """https://docs.microsoft.com/en-us/windows/console/input-record-str""" _fields_: typing.ClassVar[list[tuple[str, type]]] = [("EventType", WORD), ("Event", Event)] class EventType(enum.IntFlag): KEY_EVENT = 0x0001 MOUSE_EVENT = 0x0002 WINDOW_BUFFER_SIZE_EVENT = 0x0004 MENU_EVENT = 0x0008 FOCUS_EVENT = 0x0010 # https://docs.microsoft.com/de-de/windows/console/getstdhandle GetStdHandle = windll.kernel32.GetStdHandle GetStdHandle.argtypes = [DWORD] GetStdHandle.restype = HANDLE # https://docs.microsoft.com/de-de/windows/console/getconsolemode GetConsoleMode = windll.kernel32.GetConsoleMode GetConsoleMode.argtypes = [HANDLE, LPDWORD] GetConsoleMode.restype = BOOL # https://docs.microsoft.com/de-de/windows/console/setconsolemode SetConsoleMode = windll.kernel32.SetConsoleMode SetConsoleMode.argtypes = [HANDLE, DWORD] SetConsoleMode.restype = BOOL # https://docs.microsoft.com/de-de/windows/console/readconsoleinput ReadConsoleInputW = windll.kernel32.ReadConsoleInputW # ReadConsoleInputW.argtypes = [HANDLE, POINTER(INPUT_RECORD), DWORD, LPDWORD] ReadConsoleInputW.restype = BOOL # https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo GetConsoleScreenBufferInfo.argtypes = [HANDLE, POINTER(CONSOLE_SCREEN_BUFFER_INFO)] GetConsoleScreenBufferInfo.restype = BOOL
5,401
Python
.py
121
39.85124
95
0.711472
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,282
html_fragment.py
urwid_urwid/urwid/display/html_fragment.py
# Urwid html fragment output wrapper for "screen shots" # Copyright (C) 2004-2007 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ HTML PRE-based UI implementation """ from __future__ import annotations import html import typing from urwid import str_util from urwid.event_loop import ExitMainLoop from urwid.util import get_encoding from .common import AttrSpec, BaseScreen if typing.TYPE_CHECKING: from typing_extensions import Literal from urwid import Canvas # replace control characters with ?'s _trans_table = "?" * 32 + "".join(chr(x) for x in range(32, 256)) _default_foreground = "black" _default_background = "light gray" class HtmlGeneratorSimulationError(Exception): pass class HtmlGenerator(BaseScreen): # class variables fragments: typing.ClassVar[list[str]] = [] sizes: typing.ClassVar[list[tuple[int, int]]] = [] keys: typing.ClassVar[list[list[str]]] = [] started = True def __init__(self) -> None: super().__init__() self.colors = 16 self.bright_is_bold = False # ignored self.has_underline = True # ignored self.register_palette_entry(None, _default_foreground, _default_background) def set_terminal_properties( self, colors: int | None = None, bright_is_bold: bool | None = None, has_underline: bool | None = None, ) -> None: if colors is None: colors = self.colors if bright_is_bold is None: bright_is_bold = self.bright_is_bold if has_underline is None: has_underline = self.has_underline self.colors = colors self.bright_is_bold = bright_is_bold self.has_underline = has_underline def set_input_timeouts(self, *args: typing.Any) -> None: pass def reset_default_terminal_palette(self, *args: typing.Any) -> None: pass def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: """Create an html fragment from the render object. Append it to HtmlGenerator.fragments list. """ # collect output in l lines = [] _cols, rows = size if canvas.rows() != rows: raise ValueError(rows) if canvas.cursor is not None: cx, cy = canvas.cursor else: cx = cy = None for y, row in enumerate(canvas.content()): col = 0 for a, _cs, run in row: t_run = run.decode(get_encoding()).translate(_trans_table) if isinstance(a, AttrSpec): aspec = a else: aspec = self._palette[a][{1: 1, 16: 0, 88: 2, 256: 3}[self.colors]] if y == cy and col <= cx: run_width = str_util.calc_width(t_run, 0, len(t_run)) if col + run_width > cx: lines.append(html_span(t_run, aspec, cx - col)) else: lines.append(html_span(t_run, aspec)) col += run_width else: lines.append(html_span(t_run, aspec)) lines.append("\n") # add the fragment to the list self.fragments.append(f"<pre>{''.join(lines)}</pre>") def get_cols_rows(self): """Return the next screen size in HtmlGenerator.sizes.""" if not self.sizes: raise HtmlGeneratorSimulationError("Ran out of screen sizes to return!") return self.sizes.pop(0) @typing.overload def get_input(self, raw_keys: Literal[False]) -> list[str]: ... @typing.overload def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: """Return the next list of keypresses in HtmlGenerator.keys.""" if not self.keys: raise ExitMainLoop() if raw_keys: return (self.keys.pop(0), []) return self.keys.pop(0) _default_aspec = AttrSpec(_default_foreground, _default_background) (_d_fg_r, _d_fg_g, _d_fg_b, _d_bg_r, _d_bg_g, _d_bg_b) = _default_aspec.get_rgb_values() def html_span(s: str, aspec: AttrSpec, cursor: int = -1) -> str: fg_r, fg_g, fg_b, bg_r, bg_g, bg_b = aspec.get_rgb_values() # use real colours instead of default fg/bg if fg_r is None: fg_r, fg_g, fg_b = _d_fg_r, _d_fg_g, _d_fg_b if bg_r is None: bg_r, bg_g, bg_b = _d_bg_r, _d_bg_g, _d_bg_b html_fg = f"#{fg_r:02x}{fg_g:02x}{fg_b:02x}" html_bg = f"#{bg_r:02x}{bg_g:02x}{bg_b:02x}" if aspec.standout: html_fg, html_bg = html_bg, html_fg extra = ";text-decoration:underline" * aspec.underline + ";font-weight:bold" * aspec.bold def _span(fg: str, bg: str, string: str) -> str: if not s: return "" return f'<span style="color:{fg};background:{bg}{extra}">{html.escape(string)}</span>' if cursor >= 0: c_off, _ign = str_util.calc_text_pos(s, 0, len(s), cursor) c2_off = str_util.move_next_char(s, c_off, len(s)) return ( _span(html_fg, html_bg, s[:c_off]) + _span(html_bg, html_fg, s[c_off:c2_off]) + _span(html_fg, html_bg, s[c2_off:]) ) return _span(html_fg, html_bg, s) def screenshot_init(sizes: list[tuple[int, int]], keys: list[list[str]]) -> None: """ Replace curses_display.Screen and raw_display.Screen class with HtmlGenerator. Call this function before executing an application that uses curses_display.Screen to have that code use HtmlGenerator instead. sizes -- list of ( columns, rows ) tuples to be returned by each call to HtmlGenerator.get_cols_rows() keys -- list of lists of keys to be returned by each call to HtmlGenerator.get_input() Lists of keys may include "window resize" to force the application to call get_cols_rows and read a new screen size. For example, the following call will prepare an application to: 1. start in 80x25 with its first call to get_cols_rows() 2. take a screenshot when it calls draw_screen(..) 3. simulate 5 "down" keys from get_input() 4. take a screenshot when it calls draw_screen(..) 5. simulate keys "a", "b", "c" and a "window resize" 6. resize to 20x10 on its second call to get_cols_rows() 7. take a screenshot when it calls draw_screen(..) 8. simulate a "Q" keypress to quit the application screenshot_init( [ (80,25), (20,10) ], [ ["down"]*5, ["a","b","c","window resize"], ["Q"] ] ) """ for row, col in sizes: if not isinstance(row, int): raise TypeError(f"sizes must be list[tuple[int, int]], with values >0 : {row!r}") if row <= 0: raise ValueError(f"sizes must be list[tuple[int, int]], with values >0 : {row!r}") if not isinstance(col, int): raise TypeError(f"sizes must be list[tuple[int, int]], with values >0 : {col!r}") if col <= 0: raise ValueError(f"sizes must be list[tuple[int, int]], with values >0 : {col!r}") for line in keys: if not isinstance(line, list): raise TypeError(f"keys must be list[list[str]]: {line!r}") for k in line: if not isinstance(k, str): raise TypeError(f"keys must be list[list[str]]: {k!r}") from . import curses, raw curses.Screen = HtmlGenerator raw.Screen = HtmlGenerator HtmlGenerator.sizes = sizes HtmlGenerator.keys = keys def screenshot_collect() -> list[str]: """Return screenshots as a list of HTML fragments.""" fragments, HtmlGenerator.fragments = HtmlGenerator.fragments, [] return fragments
8,547
Python
.py
192
36.78125
94
0.617247
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,283
_posix_raw_display.py
urwid_urwid/urwid/display/_posix_raw_display.py
# Urwid raw display module # Copyright (C) 2004-2009 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Direct terminal UI implementation """ from __future__ import annotations import contextlib import fcntl import functools import os import selectors import signal import struct import sys import termios import tty import typing from subprocess import PIPE, Popen from urwid import signals from . import _raw_display_base, escape from .common import INPUT_DESCRIPTORS_CHANGED if typing.TYPE_CHECKING: import socket from collections.abc import Callable from types import FrameType from urwid.event_loop import EventLoop class Screen(_raw_display_base.Screen): def __init__( self, input: typing.TextIO = sys.stdin, # noqa: A002 # pylint: disable=redefined-builtin output: typing.TextIO = sys.stdout, bracketed_paste_mode=False, focus_reporting=False, ) -> None: """Initialize a screen that directly prints escape codes to an output terminal. bracketed_paste_mode -- enable bracketed paste mode in the host terminal. If the host terminal supports it, the application will receive `begin paste` and `end paste` keystrokes when the user pastes text. focus_reporting -- enable focus reporting in the host terminal. If the host terminal supports it, the application will receive `focus in` and `focus out` keystrokes when the application gains and loses focus. """ super().__init__(input, output) self.gpm_mev: Popen | None = None self.gpm_event_pending: bool = False self.bracketed_paste_mode = bracketed_paste_mode self.focus_reporting = focus_reporting # These store the previous signal handlers after setting ours self._prev_sigcont_handler = None self._prev_sigtstp_handler = None self._prev_sigwinch_handler = None def __repr__(self) -> str: return ( f"<{self.__class__.__name__}(" f"input={self._term_input_file}, " f"output={self._term_output_file}, " f"bracketed_paste_mode={self.bracketed_paste_mode}, " f"focus_reporting={self.focus_reporting})>" ) def _sigwinch_handler(self, signum: int = 28, frame: FrameType | None = None) -> None: """ frame -- will always be None when the GLib event loop is being used. """ super()._sigwinch_handler(signum, frame) if callable(self._prev_sigwinch_handler): self._prev_sigwinch_handler(signum, frame) def _sigtstp_handler(self, signum: int, frame: FrameType | None = None) -> None: self.stop() # Restores the previous signal handlers self._prev_sigcont_handler = self.signal_handler_setter(signal.SIGCONT, self._sigcont_handler) # Handled by the previous handler. # If non-default, it may set its own SIGCONT handler which should hopefully call our own. os.kill(os.getpid(), signal.SIGTSTP) def _sigcont_handler(self, signum: int, frame: FrameType | None = None) -> None: """ frame -- will always be None when the GLib event loop is being used. """ self.signal_restore() if callable(self._prev_sigcont_handler): # May set its own SIGTSTP handler which would be stored and replaced in # `signal_init()` (via `start()`). self._prev_sigcont_handler(signum, frame) self.start() self._sigwinch_handler(28, None) def signal_init(self) -> None: """ Called in the startup of run wrapper to set the SIGWINCH and SIGTSTP signal handlers. Override this function to call from main thread in threaded applications. """ self._prev_sigwinch_handler = self.signal_handler_setter(signal.SIGWINCH, self._sigwinch_handler) self._prev_sigtstp_handler = self.signal_handler_setter(signal.SIGTSTP, self._sigtstp_handler) def signal_restore(self) -> None: """ Called in the finally block of run wrapper to restore the SIGTSTP, SIGCONT and SIGWINCH signal handlers. Override this function to call from main thread in threaded applications. """ self.signal_handler_setter(signal.SIGTSTP, self._prev_sigtstp_handler or signal.SIG_DFL) self.signal_handler_setter(signal.SIGCONT, self._prev_sigcont_handler or signal.SIG_DFL) self.signal_handler_setter(signal.SIGWINCH, self._prev_sigwinch_handler or signal.SIG_DFL) def _mouse_tracking(self, enable: bool) -> None: super()._mouse_tracking(enable) if enable: self._start_gpm_tracking() else: self._stop_gpm_tracking() def _start_gpm_tracking(self) -> None: if not os.path.isfile("/usr/bin/mev"): return if not os.environ.get("TERM", "").lower().startswith("linux"): return m = Popen( # noqa: S603 # pylint: disable=consider-using-with ["/usr/bin/mev", "-e", "158"], stdin=PIPE, stdout=PIPE, close_fds=True, encoding="ascii", ) fcntl.fcntl(m.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) self.gpm_mev = m def _stop_gpm_tracking(self) -> None: if not self.gpm_mev: return os.kill(self.gpm_mev.pid, signal.SIGINT) os.waitpid(self.gpm_mev.pid, 0) self.gpm_mev = None def _start(self, alternate_buffer: bool = True) -> None: """ Initialize the screen and input mode. alternate_buffer -- use alternate screen buffer """ if alternate_buffer: self.write(escape.SWITCH_TO_ALTERNATE_BUFFER) self._rows_used = None else: self._rows_used = 0 if self.bracketed_paste_mode: self.write(escape.ENABLE_BRACKETED_PASTE_MODE) if self.focus_reporting: self.write(escape.ENABLE_FOCUS_REPORTING) fd = self._input_fileno() if fd is not None and os.isatty(fd): self._old_termios_settings = termios.tcgetattr(fd) tty.setcbreak(fd) self.signal_init() self._alternate_buffer = alternate_buffer self._next_timeout = self.max_wait if not self._signal_keys_set: self._old_signal_keys = self.tty_signal_keys(fileno=fd) signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) # restore mouse tracking to previous state self._mouse_tracking(self._mouse_tracking_enabled) return super()._start() def _stop(self) -> None: """ Restore the screen. """ self.clear() if self.bracketed_paste_mode: self.write(escape.DISABLE_BRACKETED_PASTE_MODE) if self.focus_reporting: self.write(escape.DISABLE_FOCUS_REPORTING) signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) self.signal_restore() self._stop_mouse_restore_buffer() fd = self._input_fileno() if fd is not None and os.isatty(fd): termios.tcsetattr(fd, termios.TCSAFLUSH, self._old_termios_settings) if self._old_signal_keys: self.tty_signal_keys(*self._old_signal_keys, fd) super()._stop() def get_input_descriptors(self) -> list[socket.socket | typing.IO | int]: """ Return a list of integer file descriptors that should be polled in external event loops to check for user input. Use this method if you are implementing your own event loop. This method is only called by `hook_event_loop`, so if you override that, you can safely ignore this. """ if not self._started: return [] fd_list = super().get_input_descriptors() if self.gpm_mev is not None and self.gpm_mev.stdout is not None: fd_list.append(self.gpm_mev.stdout) return fd_list def unhook_event_loop(self, event_loop: EventLoop) -> None: """ Remove any hooks added by hook_event_loop. """ for handle in self._current_event_loop_handles: event_loop.remove_watch_file(handle) if self._input_timeout: event_loop.remove_alarm(self._input_timeout) self._input_timeout = None def hook_event_loop( self, event_loop: EventLoop, callback: Callable[[list[str], list[int]], typing.Any], ) -> None: """ Register the given callback with the event loop, to be called with new input whenever it's available. The callback should be passed a list of processed keys and a list of unprocessed keycodes. Subclasses may wish to use parse_input to wrap the callback. """ if hasattr(self, "get_input_nonblocking"): wrapper = self._make_legacy_input_wrapper(event_loop, callback) else: @functools.wraps(callback) def wrapper() -> tuple[list[str], typing.Any] | None: self.logger.debug('Calling callback for "watch file"') return self.parse_input(event_loop, callback, self.get_available_raw_input()) fds = self.get_input_descriptors() handles = [event_loop.watch_file(fd if isinstance(fd, int) else fd.fileno(), wrapper) for fd in fds] self._current_event_loop_handles = handles def _get_input_codes(self) -> list[int]: return super()._get_input_codes() + self._get_gpm_codes() def _get_gpm_codes(self) -> list[int]: codes = [] try: while self.gpm_mev is not None and self.gpm_event_pending: codes.extend(self._encode_gpm_event()) except OSError as e: if e.args[0] != 11: raise return codes def _read_raw_input(self, timeout: int) -> bytearray: ready = self._wait_for_input_ready(timeout) if self.gpm_mev is not None and self.gpm_mev.stdout.fileno() in ready: self.gpm_event_pending = True fd = self._input_fileno() chars = bytearray() if fd is None or fd not in ready: return chars with selectors.DefaultSelector() as selector: selector.register(fd, selectors.EVENT_READ) input_ready = selector.select(0) while input_ready: chars.extend(os.read(fd, 1024)) input_ready = selector.select(0) return chars def _encode_gpm_event(self) -> list[int]: self.gpm_event_pending = False s = self.gpm_mev.stdout.readline() result = s.split(", ") if len(result) != 6: # unexpected output, stop tracking self._stop_gpm_tracking() signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) return [] ev, x, y, _ign, b, m = s.split(",") ev = int(ev.split("x")[-1], 16) x = int(x.split(" ")[-1]) y = int(y.lstrip().split(" ")[0]) b = int(b.split(" ")[-1]) m = int(m.split("x")[-1].rstrip(), 16) # convert to xterm-like escape sequence last_state = next_state = self.last_bstate result = [] mod = 0 if m & 1: mod |= 4 # shift if m & 10: mod |= 8 # alt if m & 4: mod |= 16 # ctrl def append_button(b: int) -> None: b |= mod result.extend([27, ord("["), ord("M"), b + 32, x + 32, y + 32]) if ev in {20, 36, 52}: # press if b & 4 and last_state & 1 == 0: append_button(0) next_state |= 1 if b & 2 and last_state & 2 == 0: append_button(1) next_state |= 2 if b & 1 and last_state & 4 == 0: append_button(2) next_state |= 4 elif ev == 146: # drag if b & 4: append_button(0 + escape.MOUSE_DRAG_FLAG) elif b & 2: append_button(1 + escape.MOUSE_DRAG_FLAG) elif b & 1: append_button(2 + escape.MOUSE_DRAG_FLAG) else: # release if b & 4 and last_state & 1: append_button(0 + escape.MOUSE_RELEASE_FLAG) next_state &= ~1 if b & 2 and last_state & 2: append_button(1 + escape.MOUSE_RELEASE_FLAG) next_state &= ~2 if b & 1 and last_state & 4: append_button(2 + escape.MOUSE_RELEASE_FLAG) next_state &= ~4 if ev == 40: # double click (release) if b & 4 and last_state & 1: append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if b & 2 and last_state & 2: append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG) if b & 1 and last_state & 4: append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG) elif ev == 52: if b & 4 and last_state & 1: append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) if b & 2 and last_state & 2: append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) if b & 1 and last_state & 4: append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) self.last_bstate = next_state return result def get_cols_rows(self) -> tuple[int, int]: """Return the terminal dimensions (num columns, num rows).""" y, x = super().get_cols_rows() with contextlib.suppress(OSError): # Term size could not be determined if hasattr(self._term_output_file, "fileno"): buf = fcntl.ioctl(self._term_output_file.fileno(), termios.TIOCGWINSZ, b" " * 4) y, x = struct.unpack("hh", buf) # Provide some lightweight fallbacks in case the TIOCWINSZ doesn't # give sane answers if (x <= 0 or y <= 0) and self.term in {"ansi", "vt100"}: y, x = 24, 80 self.maxrow = y return x, y def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
15,053
Python
.py
349
33.641834
108
0.602228
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,284
web.py
urwid_urwid/urwid/display/web.py
# Urwid web (CGI/Asynchronous Javascript) display module # Copyright (C) 2004-2007 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ Urwid web application display module """ from __future__ import annotations import dataclasses import glob import html import os import pathlib import random import selectors import signal import socket import string import sys import tempfile import typing from contextlib import suppress from urwid.str_util import calc_text_pos, calc_width, move_next_char from urwid.util import StoppingContext, get_encoding from .common import BaseScreen if typing.TYPE_CHECKING: from typing_extensions import Literal from urwid import Canvas TEMP_DIR = tempfile.gettempdir() CURRENT_DIR = pathlib.Path(__file__).parent _js_code = CURRENT_DIR.joinpath("_web.js").read_text("utf-8") ALARM_DELAY = 60 POLL_CONNECT = 3 MAX_COLS = 200 MAX_ROWS = 100 MAX_READ = 4096 BUF_SZ = 16384 _code_colours = { "black": "0", "dark red": "1", "dark green": "2", "brown": "3", "dark blue": "4", "dark magenta": "5", "dark cyan": "6", "light gray": "7", "dark gray": "8", "light red": "9", "light green": "A", "yellow": "B", "light blue": "C", "light magenta": "D", "light cyan": "E", "white": "F", } # replace control characters with ?'s _trans_table = "?" * 32 + "".join([chr(x) for x in range(32, 256)]) _css_style = CURRENT_DIR.joinpath("_web.css").read_text("utf-8") # HTML Initial Page _html_page = [ """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Urwid Web Display - """, """</title> <style type="text/css"> """ + _css_style + r""" </style> </head> <body id="body" onload="load_web_display()"> <div style="position:absolute; visibility:hidden;"> <br id="br"\> <pre>The quick brown fox jumps over the lazy dog.<span id="testchar">X</span> <span id="testchar2">Y</span></pre> </div> Urwid Web Display - <b>""", """</b> - Status: <span id="status">Set up</span> <script type="text/javascript"> //<![CDATA[ """ + _js_code + """ //]]> </script> <pre id="text"></pre> </body> </html> """, ] class Screen(BaseScreen): def __init__(self) -> None: super().__init__() self.palette = {} self.has_color = True self._started = False @property def started(self) -> bool: return self._started def register_palette(self, palette) -> None: """Register a list of palette entries. palette -- list of (name, foreground, background) or (name, same_as_other_name) palette entries. calls self.register_palette_entry for each item in l """ for item in palette: if len(item) in {3, 4}: self.register_palette_entry(*item) continue if len(item) != 2: raise ValueError(f"Invalid register_palette usage: {item!r}") name, like_name = item if like_name not in self.palette: raise KeyError(f"palette entry '{like_name}' doesn't exist") self.palette[name] = self.palette[like_name] def register_palette_entry( self, name: str | None, foreground: str, background: str, mono: str | None = None, foreground_high: str | None = None, background_high: str | None = None, ) -> None: """Register a single palette entry. name -- new entry/attribute name foreground -- foreground colour background -- background colour mono -- monochrome terminal attribute See curses_display.register_palette_entry for more info. """ if foreground == "default": foreground = "black" if background == "default": background = "light gray" self.palette[name] = (foreground, background, mono) def set_mouse_tracking(self, enable: bool = True) -> None: """Not yet implemented""" def tty_signal_keys(self, *args, **vargs): """Do nothing.""" def start(self) -> StoppingContext: """ This function reads the initial screen size, generates a unique id and handles cleanup when fn exits. web_display.set_preferences(..) must be called before calling this function for the preferences to take effect """ if self._started: return StoppingContext(self) client_init = sys.stdin.read(50) if not client_init.startswith("window resize "): raise ValueError(client_init) _ignore1, _ignore2, x, y = client_init.split(" ", 3) x = int(x) y = int(y) self._set_screen_size(x, y) self.last_screen = {} self.last_screen_width = 0 self.update_method = os.environ["HTTP_X_URWID_METHOD"] if self.update_method not in {"multipart", "polling"}: raise ValueError(self.update_method) if self.update_method == "polling" and not _prefs.allow_polling: sys.stdout.write("Status: 403 Forbidden\r\n\r\n") sys.exit(0) clients = glob.glob(os.path.join(_prefs.pipe_dir, "urwid*.in")) if len(clients) >= _prefs.max_clients: sys.stdout.write("Status: 503 Sever Busy\r\n\r\n") sys.exit(0) urwid_id = f"{random.randrange(10 ** 9):09d}{random.randrange(10 ** 9):09d}" # noqa: S311 self.pipe_name = os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}") os.mkfifo(f"{self.pipe_name}.in", 0o600) signal.signal(signal.SIGTERM, self._cleanup_pipe) self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY) self.input_tail = "" self.content_head = ( "Content-type: " "multipart/x-mixed-replace;boundary=ZZ\r\n" "X-Urwid-ID: " + urwid_id + "\r\n" "\r\n\r\n" "--ZZ\r\n" ) if self.update_method == "polling": self.content_head = f"Content-type: text/plain\r\nX-Urwid-ID: {urwid_id}\r\n\r\n\r\n" signal.signal(signal.SIGALRM, self._handle_alarm) signal.alarm(ALARM_DELAY) self._started = True return StoppingContext(self) def stop(self) -> None: """ Restore settings and clean up. """ if not self._started: return # XXX which exceptions does this actually raise? EnvironmentError? with suppress(Exception): self._close_connection() signal.signal(signal.SIGTERM, signal.SIG_DFL) self._cleanup_pipe() self._started = False def set_input_timeouts(self, *args: typing.Any) -> None: pass def _close_connection(self) -> None: if self.update_method == "polling child": self.server_socket.settimeout(0) sock, _addr = self.server_socket.accept() sock.sendall(b"Z") sock.close() if self.update_method == "multipart": sys.stdout.write("\r\nZ\r\n--ZZ--\r\n") sys.stdout.flush() def _cleanup_pipe(self, *args) -> None: if not self.pipe_name: return # XXX which exceptions does this actually raise? EnvironmentError? with suppress(Exception): os.remove(f"{self.pipe_name}.in") os.remove(f"{self.pipe_name}.update") def _set_screen_size(self, cols: int, rows: int) -> None: """Set the screen size (within max size).""" cols = min(cols, MAX_COLS) rows = min(rows, MAX_ROWS) self.screen_size = cols, rows def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: """Send a screen update to the client.""" (cols, rows) = size if cols != self.last_screen_width: self.last_screen = {} sendq = [self.content_head] if self.update_method == "polling": send = sendq.append elif self.update_method == "polling child": signal.alarm(0) try: s, _addr = self.server_socket.accept() except socket.timeout: sys.exit(0) send = s.sendall else: signal.alarm(0) send = sendq.append send("\r\n") self.content_head = "" if canvas.rows() != rows: raise ValueError(rows) if canvas.cursor is not None: cx, cy = canvas.cursor else: cx = cy = None new_screen = {} y = -1 for row in canvas.content(): y += 1 l_row = tuple((attr_, line.decode(get_encoding())) for attr_, _, line in row) line = [] sig = l_row if y == cy: sig = (*sig, cx) new_screen[sig] = [*new_screen.get(sig, []), y] old_line_numbers = self.last_screen.get(sig, None) if old_line_numbers is not None: if y in old_line_numbers: old_line = y else: old_line = old_line_numbers[0] send(f"<{old_line:d}\n") continue col = 0 for a, run in l_row: t_run = run.translate(_trans_table) if a is None: fg, bg, _mono = "black", "light gray", None else: fg, bg, _mono = self.palette[a] if y == cy and col <= cx: run_width = calc_width(t_run, 0, len(t_run)) if col + run_width > cx: line.append(code_span(t_run, fg, bg, cx - col)) else: line.append(code_span(t_run, fg, bg)) col += run_width else: line.append(code_span(t_run, fg, bg)) send(f"{''.join(line)}\n") self.last_screen = new_screen self.last_screen_width = cols if self.update_method == "polling": sys.stdout.write("".join(sendq)) sys.stdout.flush() sys.stdout.close() self._fork_child() elif self.update_method == "polling child": s.close() else: # update_method == "multipart" send("\r\n--ZZ\r\n") sys.stdout.write("".join(sendq)) sys.stdout.flush() signal.alarm(ALARM_DELAY) def clear(self) -> None: """ Force the screen to be completely repainted on the next call to draw_screen(). (does nothing for web_display) """ def _fork_child(self) -> None: """ Fork a child to run CGI disconnected for polling update method. Force parent process to exit. """ daemonize(f"{self.pipe_name}.err") self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY) self.update_method = "polling child" s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.bind(f"{self.pipe_name}.update") s.listen(1) s.settimeout(POLL_CONNECT) self.server_socket = s def _handle_alarm(self, sig, frame) -> None: if self.update_method not in {"multipart", "polling child"}: raise ValueError(self.update_method) if self.update_method == "polling child": # send empty update try: s, _addr = self.server_socket.accept() s.close() except socket.timeout: sys.exit(0) else: # send empty update sys.stdout.write("\r\n\r\n--ZZ\r\n") sys.stdout.flush() signal.alarm(ALARM_DELAY) def get_cols_rows(self) -> tuple[int, int]: """Return the screen size.""" return self.screen_size @typing.overload def get_input(self, raw_keys: Literal[False]) -> list[str]: ... @typing.overload def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: """Return pending input as a list.""" pending_input = [] resized = False with selectors.DefaultSelector() as selector: selector.register(self.input_fd, selectors.EVENT_READ) iready = [event.fd for event, _ in selector.select(0.5)] if not iready: if raw_keys: return [], [] return [] keydata = os.read(self.input_fd, MAX_READ).decode(get_encoding()) os.close(self.input_fd) self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY) # sys.stderr.write( repr((keydata,self.input_tail))+"\n" ) keys = keydata.split("\n") keys[0] = self.input_tail + keys[0] self.input_tail = keys[-1] for k in keys[:-1]: if k.startswith("window resize "): _ign1, _ign2, x, y = k.split(" ", 3) x = int(x) y = int(y) self._set_screen_size(x, y) resized = True else: pending_input.append(k) if resized: pending_input.append("window resize") if raw_keys: return pending_input, [] return pending_input def code_span(s, fg, bg, cursor=-1) -> str: code_fg = _code_colours[fg] code_bg = _code_colours[bg] if cursor >= 0: c_off, _ign = calc_text_pos(s, 0, len(s), cursor) c2_off = move_next_char(s, c_off, len(s)) return ( code_fg + code_bg + s[:c_off] + "\n" + code_bg + code_fg + s[c_off:c2_off] + "\n" + code_fg + code_bg + s[c2_off:] + "\n" ) return f"{code_fg + code_bg + s}\n" def is_web_request() -> bool: """ Return True if this is a CGI web request. """ return "REQUEST_METHOD" in os.environ def handle_short_request() -> bool: """ Handle short requests such as passing keystrokes to the application or sending the initial html page. If returns True, then this function recognised and handled a short request, and the calling script should immediately exit. web_display.set_preferences(..) should be called before calling this function for the preferences to take effect """ if not is_web_request(): return False if os.environ["REQUEST_METHOD"] == "GET": # Initial request, send the HTML and javascript. sys.stdout.write("Content-type: text/html\r\n\r\n" + html.escape(_prefs.app_name).join(_html_page)) return True if os.environ["REQUEST_METHOD"] != "POST": # Don't know what to do with head requests etc. return False if "HTTP_X_URWID_ID" not in os.environ: # If no urwid id, then the application should be started. return False urwid_id = os.environ["HTTP_X_URWID_ID"] if len(urwid_id) > 20: # invalid. handle by ignoring # assert 0, "urwid id too long!" sys.stdout.write("Status: 414 URI Too Long\r\n\r\n") return True for c in urwid_id: if c not in string.digits: # invald. handle by ignoring # assert 0, "invalid chars in id!" sys.stdout.write("Status: 403 Forbidden\r\n\r\n") return True if os.environ.get("HTTP_X_URWID_METHOD", None) == "polling": # this is a screen update request s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: s.connect(os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}.update")) data = f"Content-type: text/plain\r\n\r\n{s.recv(BUF_SZ)}" while data: sys.stdout.write(data) data = s.recv(BUF_SZ) except OSError: sys.stdout.write("Status: 404 Not Found\r\n\r\n") return True return True # this is a keyboard input request try: fd = os.open((os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}.in")), os.O_WRONLY) except OSError: sys.stdout.write("Status: 404 Not Found\r\n\r\n") return True # FIXME: use the correct encoding based on the request keydata = sys.stdin.read(MAX_READ) os.write(fd, keydata.encode("ascii")) os.close(fd) sys.stdout.write("Content-type: text/plain\r\n\r\n") return True @dataclasses.dataclass class _Preferences: app_name: str = "Unnamed Application" pipe_dir: str = TEMP_DIR allow_polling: bool = True max_clients: int = 20 _prefs = _Preferences() def set_preferences( app_name: str, pipe_dir: str = TEMP_DIR, allow_polling: bool = True, max_clients: int = 20, ) -> None: """ Set web_display preferences. app_name -- application name to appear in html interface pipe_dir -- directory for input pipes, daemon update sockets and daemon error logs allow_polling -- allow creation of daemon processes for browsers without multipart support max_clients -- maximum concurrent client connections. This pool is shared by all urwid applications using the same pipe_dir """ _prefs.app_name = app_name _prefs.pipe_dir = pipe_dir _prefs.allow_polling = allow_polling _prefs.max_clients = max_clients class ErrorLog: def __init__(self, errfile: str | pathlib.PurePath) -> None: self.errfile = errfile def write(self, err: str) -> None: with open(self.errfile, "a", encoding="utf-8") as f: f.write(err) def daemonize(errfile: str) -> None: """ Detach process and become a daemon. """ pid = os.fork() if pid: os._exit(0) os.setsid() signal.signal(signal.SIGHUP, signal.SIG_IGN) os.umask(0) pid = os.fork() if pid: os._exit(0) os.chdir("/") for fd in range(0, 20): with suppress(OSError): os.close(fd) sys.stdin = open("/dev/null", encoding="utf-8") # noqa: SIM115 # pylint: disable=consider-using-with sys.stdout = open("/dev/null", "w", encoding="utf-8") # noqa: SIM115 # pylint: disable=consider-using-with sys.stderr = ErrorLog(errfile)
19,250
Python
.py
525
28.228571
112
0.578441
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,285
common.py
urwid_urwid/urwid/display/common.py
# Urwid common display code # Copyright (C) 2004-2011 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import abc import logging import os import sys import typing import warnings from urwid import signals from urwid.util import StoppingContext, int_scale if typing.TYPE_CHECKING: from collections.abc import Iterable, Sequence from typing_extensions import Literal, Self from urwid import Canvas IS_WINDOWS = sys.platform == "win32" # for replacing unprintable bytes with '?' UNPRINTABLE_TRANS_TABLE = b"?" * 32 + bytes(range(32, 256)) # signals sent by BaseScreen UPDATE_PALETTE_ENTRY = "update palette entry" INPUT_DESCRIPTORS_CHANGED = "input descriptors changed" # AttrSpec internal values _BASIC_START = 0 # first index of basic color aliases _CUBE_START = 16 # first index of color cube _CUBE_SIZE_256 = 6 # one side of the color cube _GRAY_SIZE_256 = 24 _GRAY_START_256 = _CUBE_SIZE_256**3 + _CUBE_START _CUBE_WHITE_256 = _GRAY_START_256 - 1 _CUBE_SIZE_88 = 4 _GRAY_SIZE_88 = 8 _GRAY_START_88 = _CUBE_SIZE_88**3 + _CUBE_START _CUBE_WHITE_88 = _GRAY_START_88 - 1 _CUBE_BLACK = _CUBE_START # values copied from xterm 256colres.h: _CUBE_STEPS_256 = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF] _GRAY_STEPS_256 = [ 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76, 0x80, 0x84, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE, ] # values copied from xterm 88colres.h: _CUBE_STEPS_88 = [0x00, 0x8B, 0xCD, 0xFF] _GRAY_STEPS_88 = [0x2E, 0x5C, 0x73, 0x8B, 0xA2, 0xB9, 0xD0, 0xE7] # values copied from X11/rgb.txt and XTerm-col.ad: _BASIC_COLOR_VALUES = [ (0, 0, 0), (205, 0, 0), (0, 205, 0), (205, 205, 0), (0, 0, 238), (205, 0, 205), (0, 205, 205), (229, 229, 229), (127, 127, 127), (255, 0, 0), (0, 255, 0), (255, 255, 0), (0x5C, 0x5C, 0xFF), (255, 0, 255), (0, 255, 255), (255, 255, 255), ] _COLOR_VALUES_256 = ( _BASIC_COLOR_VALUES + [(r, g, b) for r in _CUBE_STEPS_256 for g in _CUBE_STEPS_256 for b in _CUBE_STEPS_256] + [(gr, gr, gr) for gr in _GRAY_STEPS_256] ) _COLOR_VALUES_88 = ( _BASIC_COLOR_VALUES + [(r, g, b) for r in _CUBE_STEPS_88 for g in _CUBE_STEPS_88 for b in _CUBE_STEPS_88] + [(gr, gr, gr) for gr in _GRAY_STEPS_88] ) if len(_COLOR_VALUES_256) != 256: raise RuntimeError(_COLOR_VALUES_256) if len(_COLOR_VALUES_88) != 88: raise RuntimeError(_COLOR_VALUES_88) # fmt: off _FG_COLOR_MASK = 0x000000ffffff _BG_COLOR_MASK = 0xffffff000000 _FG_BASIC_COLOR = 0x1000000000000 _FG_HIGH_COLOR = 0x2000000000000 _FG_TRUE_COLOR = 0x4000000000000 _BG_BASIC_COLOR = 0x8000000000000 _BG_HIGH_COLOR = 0x10000000000000 _BG_TRUE_COLOR = 0x20000000000000 _BG_SHIFT = 24 _HIGH_88_COLOR = 0x40000000000000 _HIGH_TRUE_COLOR = 0x80000000000000 _STANDOUT = 0x100000000000000 _UNDERLINE = 0x200000000000000 _BOLD = 0x400000000000000 _BLINK = 0x800000000000000 _ITALICS = 0x1000000000000000 _STRIKETHROUGH = 0x2000000000000000 # fmt: on _FG_MASK = ( _FG_COLOR_MASK | _FG_BASIC_COLOR | _FG_HIGH_COLOR | _STANDOUT | _UNDERLINE | _BLINK | _BOLD | _ITALICS | _STRIKETHROUGH ) _BG_MASK = _BG_COLOR_MASK | _BG_BASIC_COLOR | _BG_HIGH_COLOR DEFAULT = "default" BLACK = "black" DARK_RED = "dark red" DARK_GREEN = "dark green" BROWN = "brown" DARK_BLUE = "dark blue" DARK_MAGENTA = "dark magenta" DARK_CYAN = "dark cyan" LIGHT_GRAY = "light gray" DARK_GRAY = "dark gray" LIGHT_RED = "light red" LIGHT_GREEN = "light green" YELLOW = "yellow" LIGHT_BLUE = "light blue" LIGHT_MAGENTA = "light magenta" LIGHT_CYAN = "light cyan" WHITE = "white" _BASIC_COLORS = [ BLACK, DARK_RED, DARK_GREEN, BROWN, DARK_BLUE, DARK_MAGENTA, DARK_CYAN, LIGHT_GRAY, DARK_GRAY, LIGHT_RED, LIGHT_GREEN, YELLOW, LIGHT_BLUE, LIGHT_MAGENTA, LIGHT_CYAN, WHITE, ] _ATTRIBUTES = { "bold": _BOLD, "italics": _ITALICS, "underline": _UNDERLINE, "blink": _BLINK, "standout": _STANDOUT, "strikethrough": _STRIKETHROUGH, } def _value_lookup_table(values: Sequence[int], size: int) -> list[int]: """ Generate a lookup table for finding the closest item in values. Lookup returns (index into values)+1 values -- list of values in ascending order, all < size size -- size of lookup table and maximum value >>> _value_lookup_table([0, 7, 9], 10) [0, 0, 0, 0, 1, 1, 1, 1, 2, 2] """ middle_values = [0] + [(values[i] + values[i + 1] + 1) // 2 for i in range(len(values) - 1)] + [size] lookup_table = [] for i in range(len(middle_values) - 1): count = middle_values[i + 1] - middle_values[i] lookup_table.extend([i] * count) return lookup_table _CUBE_256_LOOKUP = _value_lookup_table(_CUBE_STEPS_256, 256) _GRAY_256_LOOKUP = _value_lookup_table([0, *_GRAY_STEPS_256, 255], 256) _CUBE_88_LOOKUP = _value_lookup_table(_CUBE_STEPS_88, 256) _GRAY_88_LOOKUP = _value_lookup_table([0, *_GRAY_STEPS_88, 255], 256) # convert steps to values that will be used by string versions of the colors # 1 hex digit for rgb and 0..100 for grayscale _CUBE_STEPS_256_16 = [int_scale(n, 0x100, 0x10) for n in _CUBE_STEPS_256] _GRAY_STEPS_256_101 = [int_scale(n, 0x100, 101) for n in _GRAY_STEPS_256] _CUBE_STEPS_88_16 = [int_scale(n, 0x100, 0x10) for n in _CUBE_STEPS_88] _GRAY_STEPS_88_101 = [int_scale(n, 0x100, 101) for n in _GRAY_STEPS_88] # create lookup tables for 1 hex digit rgb and 0..100 for grayscale values _CUBE_256_LOOKUP_16 = [_CUBE_256_LOOKUP[int_scale(n, 16, 0x100)] for n in range(16)] _GRAY_256_LOOKUP_101 = [_GRAY_256_LOOKUP[int_scale(n, 101, 0x100)] for n in range(101)] _CUBE_88_LOOKUP_16 = [_CUBE_88_LOOKUP[int_scale(n, 16, 0x100)] for n in range(16)] _GRAY_88_LOOKUP_101 = [_GRAY_88_LOOKUP[int_scale(n, 101, 0x100)] for n in range(101)] # The functions _gray_num_256() and _gray_num_88() do not include the gray # values from the color cube so that the gray steps are an even width. # The color cube grays are available by using the rgb functions. Pure # white and black are taken from the color cube, since the gray range does # not include them, and the basic colors are more likely to have been # customized by an end-user. def _gray_num_256(gnum: int) -> int: """Return ths color number for gray number gnum. Color cube black and white are returned for 0 and 25 respectively since those values aren't included in the gray scale. """ # grays start from index 1 gnum -= 1 if gnum < 0: return _CUBE_BLACK if gnum >= _GRAY_SIZE_256: return _CUBE_WHITE_256 return _GRAY_START_256 + gnum def _gray_num_88(gnum: int) -> int: """Return ths color number for gray number gnum. Color cube black and white are returned for 0 and 9 respectively since those values aren't included in the gray scale. """ # gnums start from index 1 gnum -= 1 if gnum < 0: return _CUBE_BLACK if gnum >= _GRAY_SIZE_88: return _CUBE_WHITE_88 return _GRAY_START_88 + gnum def _color_desc_true(num: int) -> str: return f"#{num:06x}" def _color_desc_256(num: int) -> str: """ Return a string description of color number num. 0..15 -> 'h0'..'h15' basic colors (as high-colors) 16..231 -> '#000'..'#fff' color cube colors 232..255 -> 'g3'..'g93' grays >>> _color_desc_256(15) 'h15' >>> _color_desc_256(16) '#000' >>> _color_desc_256(17) '#006' >>> _color_desc_256(230) '#ffd' >>> _color_desc_256(233) 'g7' >>> _color_desc_256(234) 'g11' """ if not 0 <= num < 256: raise ValueError(num) if num < _CUBE_START: return f"h{num:d}" if num < _GRAY_START_256: num -= _CUBE_START b, num = num % _CUBE_SIZE_256, num // _CUBE_SIZE_256 g, num = num % _CUBE_SIZE_256, num // _CUBE_SIZE_256 r = num % _CUBE_SIZE_256 return f"#{_CUBE_STEPS_256_16[r]:x}{_CUBE_STEPS_256_16[g]:x}{_CUBE_STEPS_256_16[b]:x}" return f"g{_GRAY_STEPS_256_101[num - _GRAY_START_256]:d}" def _color_desc_88(num: int) -> str: """ Return a string description of color number num. 0..15 -> 'h0'..'h15' basic colors (as high-colors) 16..79 -> '#000'..'#fff' color cube colors 80..87 -> 'g18'..'g90' grays >>> _color_desc_88(15) 'h15' >>> _color_desc_88(16) '#000' >>> _color_desc_88(17) '#008' >>> _color_desc_88(78) '#ffc' >>> _color_desc_88(81) 'g36' >>> _color_desc_88(82) 'g45' """ if not 0 < num < 88: raise ValueError(num) if num < _CUBE_START: return f"h{num:d}" if num < _GRAY_START_88: num -= _CUBE_START b, num = num % _CUBE_SIZE_88, num // _CUBE_SIZE_88 g, r = num % _CUBE_SIZE_88, num // _CUBE_SIZE_88 return f"#{_CUBE_STEPS_88_16[r]:x}{_CUBE_STEPS_88_16[g]:x}{_CUBE_STEPS_88_16[b]:x}" return f"g{_GRAY_STEPS_88_101[num - _GRAY_START_88]:d}" def _parse_color_true(desc: str) -> int | None: c = _parse_color_256(desc) if c is not None: (r, g, b) = _COLOR_VALUES_256[c] return (r << 16) + (g << 8) + b if not desc.startswith("#"): return None if len(desc) == 7: h = desc[1:] return int(h, 16) if len(desc) == 4: h = f"0x{desc[1]}0{desc[2]}0{desc[3]}" return int(h, 16) return None def _parse_color_256(desc: str) -> int | None: """ Return a color number for the description desc. 'h0'..'h255' -> 0..255 actual color number '#000'..'#fff' -> 16..231 color cube colors 'g0'..'g100' -> 16, 232..255, 231 grays and color cube black/white 'g#00'..'g#ff' -> 16, 232...255, 231 gray and color cube black/white Returns None if desc is invalid. >>> _parse_color_256('h142') 142 >>> _parse_color_256('#f00') 196 >>> _parse_color_256('g100') 231 >>> _parse_color_256('g#80') 244 """ if len(desc) > 4: # keep the length within reason before parsing return None try: if desc.startswith("h"): # high-color number num = int(desc[1:], 10) if num < 0 or num > 255: return None return num if desc.startswith("#") and len(desc) == 4: # color-cube coordinates rgb = int(desc[1:], 16) if rgb < 0: return None b, rgb = rgb % 16, rgb // 16 g, r = rgb % 16, rgb // 16 # find the closest rgb values r = _CUBE_256_LOOKUP_16[r] g = _CUBE_256_LOOKUP_16[g] b = _CUBE_256_LOOKUP_16[b] return _CUBE_START + (r * _CUBE_SIZE_256 + g) * _CUBE_SIZE_256 + b # Only remaining possibility is gray value if desc.startswith("g#"): # hex value 00..ff gray = int(desc[2:], 16) if gray < 0 or gray > 255: return None gray = _GRAY_256_LOOKUP[gray] elif desc.startswith("g"): # decimal value 0..100 gray = int(desc[1:], 10) if gray < 0 or gray > 100: return None gray = _GRAY_256_LOOKUP_101[gray] else: return None if gray == 0: return _CUBE_BLACK gray -= 1 if gray == _GRAY_SIZE_256: return _CUBE_WHITE_256 return _GRAY_START_256 + gray except ValueError: return None def _true_to_256(desc: str) -> str | None: if not (desc.startswith("#") and len(desc) == 7): return None c256 = _parse_color_256("#" + "".join(format(int(x, 16) // 16, "x") for x in (desc[1:3], desc[3:5], desc[5:7]))) return _color_desc_256(c256) def _parse_color_88(desc: str) -> int | None: """ Return a color number for the description desc. 'h0'..'h87' -> 0..87 actual color number '#000'..'#fff' -> 16..79 color cube colors 'g0'..'g100' -> 16, 80..87, 79 grays and color cube black/white 'g#00'..'g#ff' -> 16, 80...87, 79 gray and color cube black/white Returns None if desc is invalid. >>> _parse_color_88('h142') >>> _parse_color_88('h42') 42 >>> _parse_color_88('#f00') 64 >>> _parse_color_88('g100') 79 >>> _parse_color_88('g#80') 83 """ if len(desc) == 7: desc = desc[0:2] + desc[3] + desc[5] if len(desc) > 4: # keep the length within reason before parsing return None try: if desc.startswith("h"): # high-color number num = int(desc[1:], 10) if num < 0 or num > 87: return None return num if desc.startswith("#") and len(desc) == 4: # color-cube coordinates rgb = int(desc[1:], 16) if rgb < 0: return None b, rgb = rgb % 16, rgb // 16 g, r = rgb % 16, rgb // 16 # find the closest rgb values r = _CUBE_88_LOOKUP_16[r] g = _CUBE_88_LOOKUP_16[g] b = _CUBE_88_LOOKUP_16[b] return _CUBE_START + (r * _CUBE_SIZE_88 + g) * _CUBE_SIZE_88 + b # Only remaining possibility is gray value if desc.startswith("g#"): # hex value 00..ff gray = int(desc[2:], 16) if gray < 0 or gray > 255: return None gray = _GRAY_88_LOOKUP[gray] elif desc.startswith("g"): # decimal value 0..100 gray = int(desc[1:], 10) if gray < 0 or gray > 100: return None gray = _GRAY_88_LOOKUP_101[gray] else: return None if gray == 0: return _CUBE_BLACK gray -= 1 if gray == _GRAY_SIZE_88: return _CUBE_WHITE_88 return _GRAY_START_88 + gray except ValueError: return None class AttrSpecError(Exception): pass class AttrSpec: __slots__ = ("__value",) def __init__(self, fg: str, bg: str, colors: Literal[1, 16, 88, 256, 16777216] = 256) -> None: """ fg -- a string containing a comma-separated foreground color and settings Color values: 'default' (use the terminal's default foreground), 'black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray', 'dark gray', 'light red', 'light green', 'yellow', 'light blue', 'light magenta', 'light cyan', 'white' High-color example values: '#009' (0% red, 0% green, 60% red, like HTML colors) '#23facc' (RRGGBB hex color code) '#fcc' (100% red, 80% green, 80% blue) 'g40' (40% gray, decimal), 'g#cc' (80% gray, hex), '#000', 'g0', 'g#00' (black), '#fff', 'g100', 'g#ff' (white) 'h8' (color number 8), 'h255' (color number 255) Setting: 'bold', 'italics', 'underline', 'blink', 'standout', 'strikethrough' Some terminals use 'bold' for bright colors. Most terminals ignore the 'blink' setting. If the color is not given then 'default' will be assumed. bg -- a string containing the background color Color values: 'default' (use the terminal's default background), 'black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray' High-color exaples: see fg examples above An empty string will be treated the same as 'default'. colors -- the maximum colors available for the specification Valid values include: 1, 16, 88, 256, and 2**24. High-color values are only usable with 88, 256, or 2**24 colors. With 1 color only the foreground settings may be used. >>> AttrSpec('dark red', 'light gray', 16) AttrSpec('dark red', 'light gray') >>> AttrSpec('yellow, underline, bold', 'dark blue') AttrSpec('yellow,bold,underline', 'dark blue') >>> AttrSpec('#ddb', '#004', 256) # closest colors will be found AttrSpec('#dda', '#006') >>> AttrSpec('#ddb', '#004', 88) AttrSpec('#ccc', '#000', colors=88) """ if colors not in {1, 16, 88, 256, 2**24}: raise AttrSpecError(f"invalid number of colors ({colors:d}).") self.__value = 0 | _HIGH_88_COLOR * (colors == 88) | _HIGH_TRUE_COLOR * (colors == 2**24) self.__set_foreground(fg) self.__set_background(bg) if self.colors > colors: raise AttrSpecError( f"foreground/background ({fg!r}/{bg!r}) require more colors than have been specified ({colors:d})." ) def copy_modified( self, fg: str | None = None, bg: str | None = None, colors: Literal[1, 16, 88, 256, 16777216] | None = None, ) -> Self: if fg is None: foreground = self.foreground else: foreground = fg if bg is None: background = self.background else: background = bg if colors is None: new_colors = self.colors else: new_colors = colors return self.__class__(foreground, background, new_colors) def __hash__(self) -> int: """Instance is immutable and hashable.""" return hash((self.__class__, self.__value)) @property def _value(self) -> int: """Read-only value access.""" return self.__value @property def foreground_basic(self) -> bool: return self.__value & _FG_BASIC_COLOR != 0 @property def foreground_high(self) -> bool: return self.__value & _FG_HIGH_COLOR != 0 @property def foreground_true(self) -> bool: return self.__value & _FG_TRUE_COLOR != 0 @property def foreground_number(self) -> int: return self.__value & _FG_COLOR_MASK @property def background_basic(self) -> bool: return self.__value & _BG_BASIC_COLOR != 0 @property def background_high(self) -> bool: return self.__value & _BG_HIGH_COLOR != 0 @property def background_true(self) -> bool: return self.__value & _BG_TRUE_COLOR != 0 @property def background_number(self) -> int: return (self.__value & _BG_COLOR_MASK) >> _BG_SHIFT @property def italics(self) -> bool: return self.__value & _ITALICS != 0 @property def bold(self) -> bool: return self.__value & _BOLD != 0 @property def underline(self) -> bool: return self.__value & _UNDERLINE != 0 @property def blink(self) -> bool: return self.__value & _BLINK != 0 @property def standout(self) -> bool: return self.__value & _STANDOUT != 0 @property def strikethrough(self) -> bool: return self.__value & _STRIKETHROUGH != 0 @property def colors(self) -> int: """ Return the maximum colors required for this object. Returns 256, 88, 16 or 1. """ if self.__value & _HIGH_88_COLOR: return 88 if self.__value & (_BG_HIGH_COLOR | _FG_HIGH_COLOR): return 256 if self.__value & (_BG_TRUE_COLOR | _FG_TRUE_COLOR): return 2**24 if self.__value & (_BG_BASIC_COLOR | _FG_BASIC_COLOR): return 16 return 1 def _colors(self) -> int: warnings.warn( f"Method `{self.__class__.__name__}._colors` is deprecated, " f"please use property `{self.__class__.__name__}.colors`", DeprecationWarning, stacklevel=2, ) return self.colors def __repr__(self) -> str: """ Return an executable python representation of the AttrSpec object. """ args = f"{self.foreground!r}, {self.background!r}" if self.colors == 88: # 88-color mode is the only one that is handled differently args = f"{args}, colors=88" return f"{self.__class__.__name__}({args})" def _foreground_color(self) -> str: """Return only the color component of the foreground.""" if not (self.foreground_basic or self.foreground_high or self.foreground_true): return "default" if self.foreground_basic: return _BASIC_COLORS[self.foreground_number] if self.colors == 88: return _color_desc_88(self.foreground_number) if self.colors == 2**24: return _color_desc_true(self.foreground_number) return _color_desc_256(self.foreground_number) @property def foreground(self) -> str: return ( self._foreground_color() + ",bold" * self.bold + ",italics" * self.italics + ",standout" * self.standout + ",blink" * self.blink + ",underline" * self.underline + ",strikethrough" * self.strikethrough ) def __set_foreground(self, foreground: str) -> None: color = None flags = 0 # handle comma-separated foreground for part in foreground.split(","): part = part.strip() # noqa: PLW2901 if part in _ATTRIBUTES: # parse and store "settings"/attributes in flags if flags & _ATTRIBUTES[part]: raise AttrSpecError(f"Setting {part!r} specified more than once in foreground ({foreground!r})") flags |= _ATTRIBUTES[part] continue # past this point we must be specifying a color if part in {"", "default"}: scolor = 0 elif part in _BASIC_COLORS: scolor = _BASIC_COLORS.index(part) flags |= _FG_BASIC_COLOR elif self.__value & _HIGH_88_COLOR: scolor = _parse_color_88(part) flags |= _FG_HIGH_COLOR elif self.__value & _HIGH_TRUE_COLOR: scolor = _parse_color_true(part) flags |= _FG_TRUE_COLOR else: scolor = _parse_color_256(_true_to_256(part) or part) flags |= _FG_HIGH_COLOR # _parse_color_*() return None for unrecognised colors if scolor is None: raise AttrSpecError(f"Unrecognised color specification {part!r} in foreground ({foreground!r})") if color is not None: raise AttrSpecError(f"More than one color given for foreground ({foreground!r})") color = scolor if color is None: color = 0 self.__value = (self.__value & ~_FG_MASK) | color | flags def _foreground(self) -> str: warnings.warn( f"Method `{self.__class__.__name__}._foreground` is deprecated, " f"please use property `{self.__class__.__name__}.foreground`", DeprecationWarning, stacklevel=2, ) return self.foreground @property def background(self) -> str: """Return the background color.""" if not (self.background_basic or self.background_high or self.background_true): return "default" if self.background_basic: return _BASIC_COLORS[self.background_number] if self.__value & _HIGH_88_COLOR: return _color_desc_88(self.background_number) if self.colors == 2**24: return _color_desc_true(self.background_number) return _color_desc_256(self.background_number) def __set_background(self, background: str) -> None: flags = 0 if background in {"", "default"}: color = 0 elif background in _BASIC_COLORS: color = _BASIC_COLORS.index(background) flags |= _BG_BASIC_COLOR elif self.__value & _HIGH_88_COLOR: color = _parse_color_88(background) flags |= _BG_HIGH_COLOR elif self.__value & _HIGH_TRUE_COLOR: color = _parse_color_true(background) flags |= _BG_TRUE_COLOR else: color = _parse_color_256(_true_to_256(background) or background) flags |= _BG_HIGH_COLOR if color is None: raise AttrSpecError(f"Unrecognised color specification in background ({background!r})") self.__value = (self.__value & ~_BG_MASK) | (color << _BG_SHIFT) | flags def _background(self) -> str: warnings.warn( f"Method `{self.__class__.__name__}._background` is deprecated, " f"please use property `{self.__class__.__name__}.background`", DeprecationWarning, stacklevel=2, ) return self.background def get_rgb_values(self) -> tuple[int | None, int | None, int | None, int | None, int | None, int | None]: """ Return (fg_red, fg_green, fg_blue, bg_red, bg_green, bg_blue) color components. Each component is in the range 0-255. Values are taken from the XTerm defaults and may not exactly match the user's terminal. If the foreground or background is 'default' then all their compenents will be returned as None. >>> AttrSpec('yellow', '#ccf', colors=88).get_rgb_values() (255, 255, 0, 205, 205, 255) >>> AttrSpec('default', 'g92').get_rgb_values() (None, None, None, 238, 238, 238) """ if not (self.foreground_basic or self.foreground_high or self.foreground_true): vals = (None, None, None) elif self.colors == 88: if self.foreground_number >= 88: raise ValueError(f"Invalid AttrSpec _value: {self.foreground_number!r}") vals = _COLOR_VALUES_88[self.foreground_number] elif self.colors == 2**24: h = f"{self.foreground_number:06x}" vals = tuple(int(x, 16) for x in (h[0:2], h[2:4], h[4:6])) else: vals = _COLOR_VALUES_256[self.foreground_number] if not (self.background_basic or self.background_high or self.background_true): return (*vals, None, None, None) if self.colors == 88: if self.background_number >= 88: raise ValueError(f"Invalid AttrSpec _value: {self.background_number!r}") return vals + _COLOR_VALUES_88[self.background_number] if self.colors == 2**24: h = f"{self.background_number:06x}" return vals + tuple(int(x, 16) for x in (h[0:2], h[2:4], h[4:6])) return vals + _COLOR_VALUES_256[self.background_number] def __eq__(self, other: object) -> bool: return isinstance(other, AttrSpec) and self.__value == other._value def __ne__(self, other: object) -> bool: return not self == other class RealTerminal: def __init__(self) -> None: super().__init__() self._signal_keys_set = False self._old_signal_keys = None if IS_WINDOWS: def tty_signal_keys( self, intr: Literal["undefined"] | int | None = None, quit: Literal["undefined"] | int | None = None, # noqa: A002 # pylint: disable=redefined-builtin start: Literal["undefined"] | int | None = None, stop: Literal["undefined"] | int | None = None, susp: Literal["undefined"] | int | None = None, fileno: int | None = None, ): """ Read and/or set the tty's signal character settings. This function returns the current settings as a tuple. Use the string 'undefined' to unmap keys from their signals. The value None is used when no change is being made. Setting signal keys is done using the integer ascii code for the key, eg. 3 for CTRL+C. If this function is called after start() has been called then the original settings will be restored when stop() is called. """ return () else: def tty_signal_keys( self, intr: Literal["undefined"] | int | None = None, quit: Literal["undefined"] | int | None = None, # noqa: A002 # pylint: disable=redefined-builtin start: Literal["undefined"] | int | None = None, stop: Literal["undefined"] | int | None = None, susp: Literal["undefined"] | int | None = None, fileno: int | None = None, ): """ Read and/or set the tty's signal character settings. This function returns the current settings as a tuple. Use the string 'undefined' to unmap keys from their signals. The value None is used when no change is being made. Setting signal keys is done using the integer ascii code for the key, eg. 3 for CTRL+C. If this function is called after start() has been called then the original settings will be restored when stop() is called. """ import termios if fileno is None: fileno = sys.stdin.fileno() if not os.isatty(fileno): return None tattr = termios.tcgetattr(fileno) sattr = tattr[6] skeys = ( sattr[termios.VINTR], sattr[termios.VQUIT], sattr[termios.VSTART], sattr[termios.VSTOP], sattr[termios.VSUSP], ) if intr == "undefined": intr = 0 if quit == "undefined": quit = 0 # noqa: A001 if start == "undefined": start = 0 if stop == "undefined": stop = 0 if susp == "undefined": susp = 0 if intr is not None: tattr[6][termios.VINTR] = intr if quit is not None: tattr[6][termios.VQUIT] = quit if start is not None: tattr[6][termios.VSTART] = start if stop is not None: tattr[6][termios.VSTOP] = stop if susp is not None: tattr[6][termios.VSUSP] = susp if any(item is not None for item in (intr, quit, start, stop, susp)): termios.tcsetattr(fileno, termios.TCSADRAIN, tattr) self._signal_keys_set = True return skeys class ScreenError(Exception): pass class BaseMeta(signals.MetaSignals, abc.ABCMeta): """Base metaclass for abstra""" class BaseScreen(metaclass=BaseMeta): """ Base class for Screen classes (raw_display.Screen, .. etc) """ signals: typing.ClassVar[list[str]] = [UPDATE_PALETTE_ENTRY, INPUT_DESCRIPTORS_CHANGED] def __init__(self) -> None: super().__init__() self.logger = logging.getLogger(f"{self.__class__.__module__}.{self.__class__.__name__}") self._palette: dict[str | None, tuple[AttrSpec, AttrSpec, AttrSpec, AttrSpec, AttrSpec]] = {} self._started: bool = False @property def started(self) -> bool: return self._started def start(self, *args, **kwargs) -> StoppingContext: """Set up the screen. If the screen has already been started, does nothing. May be used as a context manager, in which case :meth:`stop` will automatically be called at the end of the block: with screen.start(): ... You shouldn't override this method in a subclass; instead, override :meth:`_start`. """ if not self._started: self._started = True self._start(*args, **kwargs) return StoppingContext(self) def _start(self) -> None: pass def stop(self) -> None: if self._started: self._stop() self._started = False def _stop(self) -> None: pass def run_wrapper(self, fn, *args, **kwargs): """Start the screen, call a function, then stop the screen. Extra arguments are passed to `start`. Deprecated in favor of calling `start` as a context manager. """ warnings.warn( "run_wrapper is deprecated in favor of calling `start` as a context manager.", DeprecationWarning, stacklevel=3, ) with self.start(*args, **kwargs): return fn() def set_mouse_tracking(self, enable: bool = True) -> None: pass @abc.abstractmethod def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: pass def clear(self) -> None: """Clear the screen if possible. Force the screen to be completely repainted on the next call to draw_screen(). """ def get_cols_rows(self) -> tuple[int, int]: """Return the terminal dimensions (num columns, num rows). Default (fallback) is 80x24. """ return 80, 24 def register_palette( self, palette: Iterable[ tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str] ], ) -> None: """Register a set of palette entries. palette -- a list of (name, like_other_name) or (name, foreground, background, mono, foreground_high, background_high) tuples The (name, like_other_name) format will copy the settings from the palette entry like_other_name, which must appear before this tuple in the list. The mono and foreground/background_high values are optional ie. the second tuple format may have 3, 4 or 6 values. See register_palette_entry() for a description of the tuple values. """ for item in palette: if len(item) in {3, 4, 6}: self.register_palette_entry(*item) continue if len(item) != 2: raise ScreenError(f"Invalid register_palette entry: {item!r}") name, like_name = item if like_name not in self._palette: raise ScreenError(f"palette entry '{like_name}' doesn't exist") self._palette[name] = self._palette[like_name] def register_palette_entry( self, name: str | None, foreground: str, background: str, mono: str | None = None, foreground_high: str | None = None, background_high: str | None = None, ) -> None: """Register a single palette entry. name -- new entry/attribute name foreground -- a string containing a comma-separated foreground color and settings Color values: 'default' (use the terminal's default foreground), 'black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray', 'dark gray', 'light red', 'light green', 'yellow', 'light blue', 'light magenta', 'light cyan', 'white' Settings: 'bold', 'underline', 'blink', 'standout', 'strikethrough' Some terminals use 'bold' for bright colors. Most terminals ignore the 'blink' setting. If the color is not given then 'default' will be assumed. background -- a string containing the background color Background color values: 'default' (use the terminal's default background), 'black', 'dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray' mono -- a comma-separated string containing monochrome terminal settings (see "Settings" above.) None = no terminal settings (same as 'default') foreground_high -- a string containing a comma-separated foreground color and settings, standard foreground colors (see "Color values" above) or high-colors may be used High-color example values: '#009' (0% red, 0% green, 60% red, like HTML colors) '#fcc' (100% red, 80% green, 80% blue) 'g40' (40% gray, decimal), 'g#cc' (80% gray, hex), '#000', 'g0', 'g#00' (black), '#fff', 'g100', 'g#ff' (white) 'h8' (color number 8), 'h255' (color number 255) None = use foreground parameter value background_high -- a string containing the background color, standard background colors (see "Background colors" above) or high-colors (see "High-color example values" above) may be used None = use background parameter value """ basic = AttrSpec(foreground, background, 16) if isinstance(mono, tuple): # old style of specifying mono attributes was to put them # in a tuple. convert to comma-separated string mono = ",".join(mono) if mono is None: mono = DEFAULT mono_spec = AttrSpec(mono, DEFAULT, 1) if foreground_high is None: foreground_high = foreground if background_high is None: background_high = background high_256 = AttrSpec(foreground_high, background_high, 256) high_true = AttrSpec(foreground_high, background_high, 2**24) # 'hX' where X > 15 are different in 88/256 color, use # basic colors for 88-color mode if high colors are specified # in this way (also avoids crash when X > 87) def large_h(desc: str) -> bool: if not desc.startswith("h"): return False if "," in desc: desc = desc.split(",", 1)[0] num = int(desc[1:], 10) return num > 15 if large_h(foreground_high) or large_h(background_high): high_88 = basic else: high_88 = AttrSpec(foreground_high, background_high, 88) signals.emit_signal(self, UPDATE_PALETTE_ENTRY, name, basic, mono_spec, high_88, high_256, high_true) self._palette[name] = (basic, mono_spec, high_88, high_256, high_true) def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
39,517
Python
.py
1,018
30.320236
116
0.576725
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,286
asyncio_loop.py
urwid_urwid/urwid/event_loop/asyncio_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Asyncio based urwid EventLoop implementation.""" from __future__ import annotations import asyncio import functools import logging import sys import typing from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: from collections.abc import Callable from concurrent.futures import Executor from typing_extensions import ParamSpec _Spec = ParamSpec("_Spec") _T = typing.TypeVar("_T") __all__ = ("AsyncioEventLoop",) IS_WINDOWS = sys.platform == "win32" class AsyncioEventLoop(EventLoop): """ Event loop based on the standard library ``asyncio`` module. .. warning:: Under Windows, AsyncioEventLoop globally enforces WindowsSelectorEventLoopPolicy as a side-effect of creating a class instance. Original event loop policy is restored in destructor method. .. note:: If you make any changes to the urwid state outside of it handling input or responding to alarms (for example, from asyncio.Task running in background), and wish the screen to be redrawn, you must call :meth:`MainLoop.draw_screen` method of the main loop manually. A good way to do this: asyncio.get_event_loop().call_soon(main_loop.draw_screen) """ def __init__(self, *, loop: asyncio.AbstractEventLoop | None = None, **kwargs) -> None: super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) if loop: self._loop: asyncio.AbstractEventLoop = loop self._event_loop_policy_altered: bool = False self._original_event_loop_policy: asyncio.AbstractEventLoopPolicy | None = None else: self._original_event_loop_policy = asyncio.get_event_loop_policy() if IS_WINDOWS and not isinstance(self._original_event_loop_policy, asyncio.WindowsSelectorEventLoopPolicy): self.logger.debug("Set WindowsSelectorEventLoopPolicy as asyncio event loop policy") asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) self._event_loop_policy_altered = True else: self._event_loop_policy_altered = False self._loop = asyncio.get_event_loop() self._exc: BaseException | None = None self._idle_asyncio_handle: asyncio.TimerHandle | None = None self._idle_handle: int = 0 self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} def __del__(self) -> None: if self._event_loop_policy_altered: asyncio.set_event_loop_policy(self._original_event_loop_policy) # Restore default event loop policy def _also_call_idle(self, callback: Callable[_Spec, _T]) -> Callable[_Spec, _T]: """ Wrap the callback to also call _entering_idle. """ @functools.wraps(callback) def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T: if not self._idle_asyncio_handle: self._idle_asyncio_handle = self._loop.call_later(0, self._entering_idle) return callback(*args, **kwargs) return wrapper def _entering_idle(self) -> None: """ Call all the registered idle callbacks. """ try: for callback in self._idle_callbacks.values(): callback() finally: self._idle_asyncio_handle = None def run_in_executor( self, executor: Executor | None, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> asyncio.Future[_T]: """Run callable in executor. :param executor: Executor to use for running the function. Default asyncio executor is used if None. :type executor: concurrent.futures.Executor | None :param func: function to call :type func: Callable :param args: arguments to function (positional only) :type args: object :param kwargs: keyword arguments to function (keyword only) :type kwargs: object :return: future object for the function call outcome. :rtype: asyncio.Future """ return self._loop.run_in_executor(executor, functools.partial(func, *args, **kwargs)) def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> asyncio.TimerHandle: """ Call callback() a given time from now. No parameters are passed to callback. Returns a handle that may be passed to remove_alarm() seconds -- time in seconds to wait before calling callback callback -- function to call from event loop """ return self._loop.call_later(seconds, self._also_call_idle(callback)) def remove_alarm(self, handle) -> bool: """ Remove an alarm. Returns True if the alarm exists, False otherwise """ existed = not handle.cancelled() handle.cancel() return existed def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int: """ Call callback() when fd has some data to read. No parameters are passed to callback. Returns a handle that may be passed to remove_watch_file() fd -- file descriptor to watch for input callback -- function to call when input is available """ self._loop.add_reader(fd, self._also_call_idle(callback)) return fd def remove_watch_file(self, handle: int) -> bool: """ Remove an input file. Returns True if the input file exists, False otherwise """ return self._loop.remove_reader(handle) def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a callback for entering idle. Returns a handle that may be passed to remove_enter_idle() """ # XXX there's no such thing as "idle" in most event loops; this fakes # it by adding extra callback to the timer and file watch callbacks. self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def remove_enter_idle(self, handle: int) -> bool: """ Remove an idle callback. Returns True if the handle was removed. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def _exception_handler(self, loop: asyncio.AbstractEventLoop, context): exc = context.get("exception") if exc: loop.stop() if self._idle_asyncio_handle: # clean it up to prevent old callbacks # from messing things up if loop is restarted self._idle_asyncio_handle.cancel() self._idle_asyncio_handle = None if not isinstance(exc, ExitMainLoop): # Store the exc_info so we can re-raise after the loop stops self._exc = exc else: loop.default_exception_handler(context) def run(self) -> None: """Start the event loop. Exit the loop when any callback raises an exception. If ExitMainLoop is raised, exit cleanly. """ self._loop.set_exception_handler(self._exception_handler) self._loop.run_forever() if self._exc: exc = self._exc self._exc = None raise exc.with_traceback(exc.__traceback__)
8,471
Python
.py
192
35.770833
119
0.640724
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,287
select_loop.py
urwid_urwid/urwid/event_loop/select_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Select based urwid EventLoop implementation.""" from __future__ import annotations import contextlib import heapq import logging import selectors import time import typing from contextlib import suppress from itertools import count from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: from collections.abc import Callable, Iterator from concurrent.futures import Executor, Future from typing_extensions import Literal, ParamSpec _T = typing.TypeVar("_T") _Spec = ParamSpec("_Spec") __all__ = ("SelectEventLoop",) class SelectEventLoop(EventLoop): """ Event loop based on :func:`selectors.DefaultSelector.select` """ def __init__(self) -> None: super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) self._alarms: list[tuple[float, int, Callable[[], typing.Any]]] = [] self._watch_files: dict[int, Callable[[], typing.Any]] = {} self._idle_handle: int = 0 self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} self._tie_break: Iterator[int] = count() self._did_something: bool = False def run_in_executor( self, executor: Executor, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> Future[_T]: """Run callable in executor. :param executor: Executor to use for running the function :type executor: concurrent.futures.Executor :param func: function to call :type func: Callable :param args: positional arguments to function :type args: object :param kwargs: keyword arguments to function :type kwargs: object :return: future object for the function call outcome. :rtype: concurrent.futures.Future """ return executor.submit(func, *args, **kwargs) def alarm( self, seconds: float, callback: Callable[[], typing.Any], ) -> tuple[float, int, Callable[[], typing.Any]]: """ Call callback() a given time from now. No parameters are passed to callback. Returns a handle that may be passed to remove_alarm() seconds -- floating point time to wait before calling callback callback -- function to call from event loop """ tm = time.time() + seconds handle = (tm, next(self._tie_break), callback) heapq.heappush(self._alarms, handle) return handle def remove_alarm(self, handle: tuple[float, int, Callable[[], typing.Any]]) -> bool: """ Remove an alarm. Returns True if the alarm exists, False otherwise """ try: self._alarms.remove(handle) heapq.heapify(self._alarms) except ValueError: return False return True def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int: """ Call callback() when fd has some data to read. No parameters are passed to callback. Returns a handle that may be passed to remove_watch_file() fd -- file descriptor to watch for input callback -- function to call when input is available """ self._watch_files[fd] = callback return fd def remove_watch_file(self, handle: int) -> bool: """ Remove an input file. Returns True if the input file exists, False otherwise """ if handle in self._watch_files: del self._watch_files[handle] return True return False def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a callback for entering idle. Returns a handle that may be passed to remove_idle() """ self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def remove_enter_idle(self, handle: int) -> bool: """ Remove an idle callback. Returns True if the handle was removed. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def _entering_idle(self) -> None: """ Call all the registered idle callbacks. """ for callback in self._idle_callbacks.values(): callback() def run(self) -> None: """ Start the event loop. Exit the loop when any callback raises an exception. If ExitMainLoop is raised, exit cleanly. """ with contextlib.suppress(ExitMainLoop): self._did_something = True while True: with suppress(InterruptedError): self._loop() def _loop(self) -> None: """ A single iteration of the event loop """ tm: float | Literal["idle"] | None = None with selectors.DefaultSelector() as selector: for fd, callback in self._watch_files.items(): selector.register(fd, selectors.EVENT_READ, callback) if self._alarms or self._did_something: timeout = 0.0 if self._alarms: timeout_ = self._alarms[0][0] tm = timeout_ timeout = max(timeout, timeout_ - time.time()) if self._did_something and (not self._alarms or (self._alarms and timeout > 0)): timeout = 0.0 tm = "idle" self.logger.debug(f"Waiting for input: timeout={timeout!r}") ready = [event for event, _ in selector.select(timeout)] elif self._watch_files: self.logger.debug("Waiting for input: timeout") ready = [event for event, _ in selector.select()] else: ready = [] if not ready: if tm == "idle": self.logger.debug("No input, entering IDLE") self._entering_idle() self._did_something = False elif tm is not None: # must have been a timeout tm, _tie_break, alarm_callback = heapq.heappop(self._alarms) self.logger.debug(f"No input in timeout, calling scheduled {alarm_callback!r}") alarm_callback() self._did_something = True self.logger.debug("Processing input") for record in ready: record.data() self._did_something = True
7,534
Python
.py
190
30.8
96
0.605011
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,288
abstract_loop.py
urwid_urwid/urwid/event_loop/abstract_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Abstract shared code for urwid EventLoop implementation.""" from __future__ import annotations import abc import logging import signal import typing if typing.TYPE_CHECKING: import asyncio from collections.abc import Callable from concurrent.futures import Executor, Future from types import FrameType from typing_extensions import ParamSpec _T = typing.TypeVar("_T") _Spec = ParamSpec("_Spec") __all__ = ("EventLoop", "ExitMainLoop") class ExitMainLoop(Exception): """ When this exception is raised within a main loop the main loop will exit cleanly. """ class EventLoop(abc.ABC): """ Abstract class representing an event loop to be used by :class:`MainLoop`. """ __slots__ = ("logger",) def __init__(self) -> None: self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) def run_in_executor( self, executor: Executor, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> Future[_T] | asyncio.Future[_T]: """Run callable in executor if supported. :param executor: Executor to use for running the function :type executor: concurrent.futures.Executor :param func: function to call :type func: Callable :param args: arguments to function (positional only) :type args: object :param kwargs: keyword arguments to function (keyword only) :type kwargs: object :return: future object for the function call outcome. (exact future type depends on the event loop type) :rtype: concurrent.futures.Future | asyncio.Future """ raise NotImplementedError @abc.abstractmethod def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> typing.Any: """ Call callback() a given time from now. No parameters are passed to callback. This method has no default implementation. Returns a handle that may be passed to remove_alarm() seconds -- floating point time to wait before calling callback callback -- function to call from event loop """ @abc.abstractmethod def enter_idle(self, callback): """ Add a callback for entering idle. This method has no default implementation. Returns a handle that may be passed to remove_idle() """ @abc.abstractmethod def remove_alarm(self, handle) -> bool: """ Remove an alarm. This method has no default implementation. Returns True if the alarm exists, False otherwise """ @abc.abstractmethod def remove_enter_idle(self, handle) -> bool: """ Remove an idle callback. This method has no default implementation. Returns True if the handle was removed. """ @abc.abstractmethod def remove_watch_file(self, handle) -> bool: """ Remove an input file. This method has no default implementation. Returns True if the input file exists, False otherwise """ @abc.abstractmethod def run(self) -> None: """ Start the event loop. Exit the loop when any callback raises an exception. If ExitMainLoop is raised, exit cleanly. This method has no default implementation. """ @abc.abstractmethod def watch_file(self, fd: int, callback: Callable[[], typing.Any]): """ Call callback() when fd has some data to read. No parameters are passed to callback. This method has no default implementation. Returns a handle that may be passed to remove_watch_file() fd -- file descriptor to watch for input callback -- function to call when input is available """ def set_signal_handler( self, signum: int, handler: Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers, ) -> Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers | None: """ Sets the signal handler for signal signum. The default implementation of :meth:`set_signal_handler` is simply a proxy function that calls :func:`signal.signal()` and returns the resulting value. signum -- signal number handler -- function (taking signum as its single argument), or `signal.SIG_IGN`, or `signal.SIG_DFL` """ return signal.signal(signum, handler)
5,494
Python
.py
138
33.181159
87
0.662152
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,289
tornado_loop.py
urwid_urwid/urwid/event_loop/tornado_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Tornado IOLoop based urwid EventLoop implementation. Tornado library is required. """ from __future__ import annotations import asyncio import functools import logging import typing from contextlib import suppress from tornado import ioloop from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: from collections.abc import Callable from concurrent.futures import Executor from typing_extensions import Literal, ParamSpec _Spec = ParamSpec("_Spec") _T = typing.TypeVar("_T") __all__ = ("TornadoEventLoop",) class TornadoEventLoop(EventLoop): """This is an Urwid-specific event loop to plug into its MainLoop. It acts as an adaptor for Tornado's IOLoop which does all heavy lifting except idle-callbacks. """ def __init__(self, loop: ioloop.IOLoop | None = None) -> None: super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) if loop: self._loop: ioloop.IOLoop = loop else: try: asyncio.get_running_loop() except RuntimeError: asyncio.set_event_loop(asyncio.new_event_loop()) self._loop = ioloop.IOLoop.current() self._pending_alarms: dict[object, int] = {} self._watch_handles: dict[int, int] = {} # {<watch_handle> : <file_descriptor>} self._max_watch_handle: int = 0 self._exc: BaseException | None = None self._idle_asyncio_handle: object | None = None self._idle_handle: int = 0 self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} def _also_call_idle(self, callback: Callable[_Spec, _T]) -> Callable[_Spec, _T]: """ Wrap the callback to also call _entering_idle. """ @functools.wraps(callback) def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T: if not self._idle_asyncio_handle: self._idle_asyncio_handle = self._loop.call_later(0, self._entering_idle) return callback(*args, **kwargs) return wrapper def _entering_idle(self) -> None: """ Call all the registered idle callbacks. """ try: for callback in self._idle_callbacks.values(): callback() finally: self._idle_asyncio_handle = None def run_in_executor( self, executor: Executor, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> asyncio.Future[_T]: """Run callable in executor. :param executor: Executor to use for running the function :type executor: concurrent.futures.Executor :param func: function to call :type func: Callable :param args: arguments to function (positional only) :type args: object :param kwargs: keyword arguments to function (keyword only) :type kwargs: object :return: future object for the function call outcome. :rtype: asyncio.Future """ return self._loop.run_in_executor(executor, functools.partial(func, *args, **kwargs)) def alarm(self, seconds: float, callback: Callable[[], typing.Any]): @self._also_call_idle @functools.wraps(callback) def wrapped() -> None: with suppress(KeyError): del self._pending_alarms[handle] self.handle_exit(callback)() handle = self._loop.add_timeout(self._loop.time() + seconds, wrapped) self._pending_alarms[handle] = 1 return handle def remove_alarm(self, handle: object) -> bool: self._loop.remove_timeout(handle) try: del self._pending_alarms[handle] except KeyError: return False return True def watch_file(self, fd: int, callback: Callable[[], _T]) -> int: @self._also_call_idle def handler(_fd: int, _events: int) -> None: self.handle_exit(callback)() self._loop.add_handler(fd, handler, ioloop.IOLoop.READ) self._max_watch_handle += 1 handle = self._max_watch_handle self._watch_handles[handle] = fd return handle def remove_watch_file(self, handle: int) -> bool: fd = self._watch_handles.pop(handle, None) if fd is None: return False self._loop.remove_handler(fd) return True def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a callback for entering idle. Returns a handle that may be passed to remove_idle() """ # XXX there's no such thing as "idle" in most event loops; this fakes # it by adding extra callback to the timer and file watch callbacks. self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def remove_enter_idle(self, handle: int) -> bool: """ Remove an idle callback. Returns True if the handle was removed. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def handle_exit(self, f: Callable[_Spec, _T]) -> Callable[_Spec, _T | Literal[False]]: @functools.wraps(f) def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | Literal[False]: try: return f(*args, **kwargs) except ExitMainLoop: pass # handled later except Exception as exc: self._exc = exc if self._idle_asyncio_handle: # clean it up to prevent old callbacks # from messing things up if loop is restarted self._loop.remove_timeout(self._idle_asyncio_handle) self._idle_asyncio_handle = None self._loop.stop() return False return wrapper def run(self) -> None: self._loop.start() if self._exc: exc, self._exc = self._exc, None raise exc.with_traceback(exc.__traceback__)
7,100
Python
.py
174
32.54023
93
0.620244
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,290
trio_loop.py
urwid_urwid/urwid/event_loop/trio_loop.py
# Urwid main loop code using Python-3.5 features (Trio, Curio, etc) # Copyright (C) 2018 Toshio Kuratomi # Copyright (C) 2019 Tamas Nepusz # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Trio Runner based urwid EventLoop implementation. Trio library is required. """ from __future__ import annotations import logging import sys import typing import trio from .abstract_loop import EventLoop, ExitMainLoop if sys.version_info < (3, 11): from exceptiongroup import BaseExceptionGroup # pylint: disable=redefined-builtin # backport if typing.TYPE_CHECKING: import io from collections.abc import Awaitable, Callable, Hashable, Mapping from typing_extensions import Concatenate, ParamSpec _Spec = ParamSpec("_Spec") __all__ = ("TrioEventLoop",) class _TrioIdleCallbackInstrument(trio.abc.Instrument): """IDLE callbacks emulation helper.""" __slots__ = ("idle_callbacks",) def __init__(self, idle_callbacks: Mapping[Hashable, Callable[[], typing.Any]]): self.idle_callbacks = idle_callbacks def before_io_wait(self, timeout: float) -> None: if timeout > 0: for idle_callback in self.idle_callbacks.values(): idle_callback() class TrioEventLoop(EventLoop): """ Event loop based on the ``trio`` module. ``trio`` is an async library for Python 3.5 and later. """ def __init__(self) -> None: """Constructor.""" super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) self._idle_handle = 0 self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} self._pending_tasks: list[tuple[Callable[_Spec, Awaitable], trio.CancelScope, _Spec.args]] = [] self._nursery: trio.Nursery | None = None self._sleep = trio.sleep self._wait_readable = trio.lowlevel.wait_readable def alarm( self, seconds: float, callback: Callable[[], typing.Any], ) -> trio.CancelScope: """Calls `callback()` a given time from now. :param seconds: time in seconds to wait before calling the callback :type seconds: float :param callback: function to call from the event loop :type callback: Callable[[], typing.Any] :return: a handle that may be passed to `remove_alarm()` :rtype: trio.CancelScope No parameters are passed to the callback. """ return self._start_task(self._alarm_task, seconds, callback) def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """Calls `callback()` when the event loop enters the idle state. There is no such thing as being idle in a Trio event loop so we simulate it by repeatedly calling `callback()` with a short delay. """ self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def remove_alarm(self, handle: trio.CancelScope) -> bool: """Removes an alarm. Parameters: handle: the handle of the alarm to remove """ return self._cancel_scope(handle) def remove_enter_idle(self, handle: int) -> bool: """Removes an idle callback. Parameters: handle: the handle of the idle callback to remove """ try: del self._idle_callbacks[handle] except KeyError: return False return True def remove_watch_file(self, handle: trio.CancelScope) -> bool: """Removes a file descriptor being watched for input. Parameters: handle: the handle of the file descriptor callback to remove Returns: True if the file descriptor was watched, False otherwise """ return self._cancel_scope(handle) def _cancel_scope(self, scope: trio.CancelScope) -> bool: """Cancels the given Trio cancellation scope. Returns: True if the scope was cancelled, False if it was cancelled already before invoking this function """ existed = not scope.cancel_called scope.cancel() return existed def run(self) -> None: """Starts the event loop. Exits the loop when any callback raises an exception. If ExitMainLoop is raised, exits cleanly. """ emulate_idle_callbacks = _TrioIdleCallbackInstrument(self._idle_callbacks) try: trio.run(self._main_task, instruments=[emulate_idle_callbacks]) except BaseException as exc: self._handle_main_loop_exception(exc) async def run_async(self) -> None: """Starts the main loop and blocks asynchronously until the main loop exits. This allows one to embed an urwid app in a Trio app even if the Trio event loop is already running. Example:: with trio.open_nursery() as nursery: event_loop = urwid.TrioEventLoop() # [...launch other async tasks in the nursery...] loop = urwid.MainLoop(widget, event_loop=event_loop) with loop.start(): await event_loop.run_async() nursery.cancel_scope.cancel() """ emulate_idle_callbacks = _TrioIdleCallbackInstrument(self._idle_callbacks) try: trio.lowlevel.add_instrument(emulate_idle_callbacks) try: await self._main_task() finally: trio.lowlevel.remove_instrument(emulate_idle_callbacks) except BaseException as exc: self._handle_main_loop_exception(exc) def watch_file( self, fd: int | io.IOBase, callback: Callable[[], typing.Any], ) -> trio.CancelScope: """Calls `callback()` when the given file descriptor has some data to read. No parameters are passed to the callback. Parameters: fd: file descriptor to watch for input callback: function to call when some input is available Returns: a handle that may be passed to `remove_watch_file()` """ return self._start_task(self._watch_task, fd, callback) async def _alarm_task( self, scope: trio.CancelScope, seconds: float, callback: Callable[[], typing.Any], ) -> None: """Asynchronous task that sleeps for a given number of seconds and then calls the given callback. Parameters: scope: the cancellation scope that can be used to cancel the task seconds: the number of seconds to wait callback: the callback to call """ with scope: await self._sleep(seconds) callback() def _handle_main_loop_exception(self, exc: BaseException) -> None: """Handles exceptions raised from the main loop, catching ExitMainLoop instead of letting it propagate through. Note that since Trio may collect multiple exceptions from tasks into an ExceptionGroup, we cannot simply use a try..catch clause, we need a helper function like this. """ self._idle_callbacks.clear() if isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1: exc = exc.exceptions[0] if isinstance(exc, ExitMainLoop): return raise exc.with_traceback(exc.__traceback__) from None async def _main_task(self) -> None: """Main Trio task that opens a nursery and then sleeps until the user exits the app by raising ExitMainLoop. """ try: async with trio.open_nursery() as self._nursery: self._schedule_pending_tasks() await trio.sleep_forever() finally: self._nursery = None def _schedule_pending_tasks(self) -> None: """Schedules all pending asynchronous tasks that were created before the nursery to be executed on the nursery soon. """ for task, scope, args in self._pending_tasks: self._nursery.start_soon(task, scope, *args) del self._pending_tasks[:] def _start_task( self, task: Callable[Concatenate[trio.CancelScope, _Spec], Awaitable], *args: _Spec.args, ) -> trio.CancelScope: """Starts an asynchronous task in the Trio nursery managed by the main loop. If the nursery has not started yet, store a reference to the task and the arguments so we can start the task when the nursery is open. Parameters: task: a Trio task to run Returns: a cancellation scope for the Trio task """ scope = trio.CancelScope() if self._nursery: self._nursery.start_soon(task, scope, *args) else: self._pending_tasks.append((task, scope, args)) return scope async def _watch_task( self, scope: trio.CancelScope, fd: int | io.IOBase, callback: Callable[[], typing.Any], ) -> None: """Asynchronous task that watches the given file descriptor and calls the given callback whenever the file descriptor becomes readable. Parameters: scope: the cancellation scope that can be used to cancel the task fd: the file descriptor to watch callback: the callback to call """ with scope: # We check for the scope being cancelled before calling # wait_readable because if callback cancels the scope, fd might be # closed and calling wait_readable with a closed fd does not work. while not scope.cancel_called: await self._wait_readable(fd) callback()
10,593
Python
.py
245
34.514286
107
0.637106
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,291
twisted_loop.py
urwid_urwid/urwid/event_loop/twisted_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """Twisted Reactor based urwid EventLoop implementation. Twisted library is required. """ from __future__ import annotations import functools import logging import sys import typing from twisted.internet.abstract import FileDescriptor from twisted.internet.error import AlreadyCalled, AlreadyCancelled from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: from collections.abc import Callable from concurrent.futures import Executor, Future from twisted.internet.base import DelayedCall, ReactorBase from typing_extensions import ParamSpec _Spec = ParamSpec("_Spec") _T = typing.TypeVar("_T") __all__ = ("TwistedEventLoop",) class _TwistedInputDescriptor(FileDescriptor): def __init__(self, reactor: ReactorBase, fd: int, cb: Callable[[], typing.Any]) -> None: self._fileno = fd self.cb = cb super().__init__(reactor) # ReactorBase implement full API as required in interfaces def fileno(self) -> int: return self._fileno def doRead(self): return self.cb() def getHost(self): raise NotImplementedError("No network operation expected") def getPeer(self): raise NotImplementedError("No network operation expected") def writeSomeData(self, data: bytes) -> None: raise NotImplementedError("Reduced functionality: read-only") class TwistedEventLoop(EventLoop): """ Event loop based on Twisted_ """ _idle_emulation_delay = 1.0 / 256 # a short time (in seconds) def __init__(self, reactor: ReactorBase | None = None, manage_reactor: bool = True) -> None: """ :param reactor: reactor to use :type reactor: :class:`twisted.internet.reactor`. :param: manage_reactor: `True` if you want this event loop to run and stop the reactor. :type manage_reactor: boolean .. WARNING:: Twisted's reactor doesn't like to be stopped and run again. If you need to stop and run your :class:`MainLoop`, consider setting ``manage_reactor=False`` and take care of running/stopping the reactor at the beginning/ending of your program yourself. You can also forego using :class:`MainLoop`'s run() entirely, and instead call start() and stop() before and after starting the reactor. .. _Twisted: https://twisted.org/ """ super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) if reactor is None: import twisted.internet.reactor reactor = twisted.internet.reactor self.reactor: ReactorBase = reactor self._watch_files: dict[int, _TwistedInputDescriptor] = {} self._idle_handle: int = 0 self._twisted_idle_enabled = False self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} self._exc: BaseException | None = None self.manage_reactor = manage_reactor self._enable_twisted_idle() def run_in_executor( self, executor: Executor, func: Callable[..., _T], *args: object, **kwargs: object, ) -> Future[_T]: raise NotImplementedError( "Twisted implement it's own ThreadPool executor. Please use native API for call:\n" "'threads.deferToThread(Callable[..., Any], *args, **kwargs)'\n" "And use 'addCallback' api for callbacks:\n" "'threads.deferToThread(Callable[..., T], *args, **kwargs).addCallback(Callable[[T], None])'" ) def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> DelayedCall: """ Call callback() a given time from now. No parameters are passed to callback. Returns a handle that may be passed to remove_alarm() seconds -- floating point time to wait before calling callback callback -- function to call from event loop """ handle = self.reactor.callLater(seconds, self.handle_exit(callback)) return handle def remove_alarm(self, handle: DelayedCall) -> bool: """ Remove an alarm. Returns True if the alarm exists, False otherwise """ try: handle.cancel() except (AlreadyCancelled, AlreadyCalled): return False return True def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int: """ Call callback() when fd has some data to read. No parameters are passed to callback. Returns a handle that may be passed to remove_watch_file() fd -- file descriptor to watch for input callback -- function to call when input is available """ ind = _TwistedInputDescriptor(self.reactor, fd, self.handle_exit(callback)) self._watch_files[fd] = ind self.reactor.addReader(ind) return fd def remove_watch_file(self, handle: int) -> bool: """ Remove an input file. Returns True if the input file exists, False otherwise """ if handle in self._watch_files: self.reactor.removeReader(self._watch_files[handle]) del self._watch_files[handle] return True return False def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a callback for entering idle. Returns a handle that may be passed to remove_enter_idle() """ self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def _enable_twisted_idle(self) -> None: """ Twisted's reactors don't have an idle or enter-idle callback so the best we can do for now is to set a timer event in a very short time to approximate an enter-idle callback. .. WARNING:: This will perform worse than the other event loops until we can find a fix or workaround """ if self._twisted_idle_enabled: return self.reactor.callLater( self._idle_emulation_delay, self.handle_exit(self._twisted_idle_callback, enable_idle=False), ) self._twisted_idle_enabled = True def _twisted_idle_callback(self) -> None: for callback in self._idle_callbacks.values(): callback() self._twisted_idle_enabled = False def remove_enter_idle(self, handle: int) -> bool: """ Remove an idle callback. Returns True if the handle was removed. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def run(self) -> None: """ Start the event loop. Exit the loop when any callback raises an exception. If ExitMainLoop is raised, exit cleanly. """ if not self.manage_reactor: return self.reactor.run() if self._exc: # An exception caused us to exit, raise it now exc = self._exc self._exc = None raise exc.with_traceback(exc.__traceback__) def handle_exit(self, f: Callable[_Spec, _T], enable_idle: bool = True) -> Callable[_Spec, _T | None]: """ Decorator that cleanly exits the :class:`TwistedEventLoop` if :class:`ExitMainLoop` is thrown inside of the wrapped function. Store the exception info if some other exception occurs, it will be reraised after the loop quits. *f* -- function to be wrapped """ @functools.wraps(f) def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | None: rval = None try: rval = f(*args, **kwargs) except ExitMainLoop: if self.manage_reactor: self.reactor.stop() except BaseException as exc: print(sys.exc_info()) self._exc = exc if self.manage_reactor: self.reactor.crash() if enable_idle: self._enable_twisted_idle() return rval return wrapper
9,219
Python
.py
220
33.409091
106
0.628897
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,292
zmq_loop.py
urwid_urwid/urwid/event_loop/zmq_loop.py
# Urwid main loop code using ZeroMQ queues # Copyright (C) 2019 Dave Jones # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """ZeroMQ based urwid EventLoop implementation. `ZeroMQ <https://zeromq.org>`_ library is required. """ from __future__ import annotations import contextlib import errno import heapq import logging import os import time import typing from itertools import count import zmq from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: import io from collections.abc import Callable from concurrent.futures import Executor, Future from typing_extensions import ParamSpec ZMQAlarmHandle = typing.TypeVar("ZMQAlarmHandle") _T = typing.TypeVar("_T") _Spec = ParamSpec("_Spec") class ZMQEventLoop(EventLoop): """ This class is an urwid event loop for `ZeroMQ`_ applications. It is very similar to :class:`SelectEventLoop`, supporting the usual :meth:`alarm` events and file watching (:meth:`watch_file`) capabilities, but also incorporates the ability to watch zmq queues for events (:meth:`watch_queue`). .. _ZeroMQ: https://zeromq.org/ """ _alarm_break = count() def __init__(self) -> None: super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) self._did_something = True self._alarms: list[tuple[float, int, Callable[[], typing.Any]]] = [] self._poller = zmq.Poller() self._queue_callbacks: dict[int, Callable[[], typing.Any]] = {} self._idle_handle = 0 self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} def run_in_executor( self, executor: Executor, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> Future[_T]: """Run callable in executor. :param executor: Executor to use for running the function :type executor: concurrent.futures.Executor :param func: function to call :type func: Callable :param args: positional arguments to function :type args: object :param kwargs: keyword arguments to function :type kwargs: object :return: future object for the function call outcome. :rtype: concurrent.futures.Future """ return executor.submit(func, *args, **kwargs) def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> ZMQAlarmHandle: """ Call *callback* a given time from now. No parameters are passed to callback. Returns a handle that may be passed to :meth:`remove_alarm`. :param float seconds: floating point time to wait before calling callback. :param callback: function to call from event loop. """ handle = (time.time() + seconds, next(self._alarm_break), callback) heapq.heappush(self._alarms, handle) return handle def remove_alarm(self, handle: ZMQAlarmHandle) -> bool: """ Remove an alarm. Returns ``True`` if the alarm exists, ``False`` otherwise. """ try: self._alarms.remove(handle) heapq.heapify(self._alarms) except ValueError: return False return True def watch_queue( self, queue: zmq.Socket, callback: Callable[[], typing.Any], flags: int = zmq.POLLIN, ) -> zmq.Socket: """ Call *callback* when zmq *queue* has something to read (when *flags* is set to ``POLLIN``, the default) or is available to write (when *flags* is set to ``POLLOUT``). No parameters are passed to the callback. Returns a handle that may be passed to :meth:`remove_watch_queue`. :param queue: The zmq queue to poll. :param callback: The function to call when the poll is successful. :param int flags: The condition to monitor on the queue (defaults to ``POLLIN``). """ if queue in self._queue_callbacks: raise ValueError(f"already watching {queue!r}") self._poller.register(queue, flags) self._queue_callbacks[queue] = callback return queue def watch_file( self, fd: int | io.TextIOWrapper, callback: Callable[[], typing.Any], flags: int = zmq.POLLIN, ) -> io.TextIOWrapper: """ Call *callback* when *fd* has some data to read. No parameters are passed to the callback. The *flags* are as for :meth:`watch_queue`. Returns a handle that may be passed to :meth:`remove_watch_file`. :param fd: The file-like object, or fileno to monitor. :param callback: The function to call when the file has data available. :param int flags: The condition to monitor on the file (defaults to ``POLLIN``). """ if isinstance(fd, int): fd = os.fdopen(fd) self._poller.register(fd, flags) self._queue_callbacks[fd.fileno()] = callback return fd def remove_watch_queue(self, handle: zmq.Socket) -> bool: """ Remove a queue from background polling. Returns ``True`` if the queue was being monitored, ``False`` otherwise. """ try: try: self._poller.unregister(handle) finally: self._queue_callbacks.pop(handle, None) except KeyError: return False return True def remove_watch_file(self, handle: io.TextIOWrapper) -> bool: """ Remove a file from background polling. Returns ``True`` if the file was being monitored, ``False`` otherwise. """ try: try: self._poller.unregister(handle) finally: self._queue_callbacks.pop(handle.fileno(), None) except KeyError: return False return True def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a *callback* to be executed when the event loop detects it is idle. Returns a handle that may be passed to :meth:`remove_enter_idle`. """ self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def remove_enter_idle(self, handle: int) -> bool: """ Remove an idle callback. Returns ``True`` if *handle* was removed, ``False`` otherwise. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def _entering_idle(self) -> None: for callback in list(self._idle_callbacks.values()): callback() def run(self) -> None: """ Start the event loop. Exit the loop when any callback raises an exception. If :exc:`ExitMainLoop` is raised, exit cleanly. """ with contextlib.suppress(ExitMainLoop): while True: try: self._loop() except zmq.error.ZMQError as exc: # noqa: PERF203 if exc.errno != errno.EINTR: raise def _loop(self) -> None: """ A single iteration of the event loop. """ state = "wait" # default state not expecting any action if self._alarms or self._did_something: timeout = 0 if self._alarms: state = "alarm" timeout = max(0.0, self._alarms[0][0] - time.time()) if self._did_something and (not self._alarms or (self._alarms and timeout > 0)): state = "idle" timeout = 0 ready = dict(self._poller.poll(timeout * 1000)) else: ready = dict(self._poller.poll()) if not ready: if state == "idle": self._entering_idle() self._did_something = False elif state == "alarm": _due, _tie_break, callback = heapq.heappop(self._alarms) callback() self._did_something = True for queue in ready: self._queue_callbacks[queue]() self._did_something = True
9,114
Python
.py
233
30.407725
92
0.605749
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,293
__init__.py
urwid_urwid/urwid/event_loop/__init__.py
"""Package with EventLoop implementations for urwid.""" from __future__ import annotations import sys from .abstract_loop import EventLoop, ExitMainLoop from .asyncio_loop import AsyncioEventLoop from .main_loop import MainLoop from .select_loop import SelectEventLoop __all__ = ( "AsyncioEventLoop", "EventLoop", "ExitMainLoop", "MainLoop", "SelectEventLoop", ) try: from .twisted_loop import TwistedEventLoop __all__ += ("TwistedEventLoop",) # type: ignore[assignment] except ImportError: pass try: from .tornado_loop import TornadoEventLoop __all__ += ("TornadoEventLoop",) # type: ignore[assignment] except ImportError: pass try: from .glib_loop import GLibEventLoop __all__ += ("GLibEventLoop",) # type: ignore[assignment] except ImportError: pass try: from .trio_loop import TrioEventLoop __all__ += ("TrioEventLoop",) # type: ignore[assignment] except ImportError: pass if sys.platform != "win32": # ZMQEventLoop cause interpreter crash on windows try: from .zmq_loop import ZMQEventLoop __all__ += ("ZMQEventLoop",) # type: ignore[assignment] except ImportError: pass
1,199
Python
.py
41
25.365854
64
0.710664
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,294
glib_loop.py
urwid_urwid/urwid/event_loop/glib_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ """GLib based urwid EventLoop implementation. PyGObject library is required. """ from __future__ import annotations import functools import logging import signal import typing from gi.repository import GLib from .abstract_loop import EventLoop, ExitMainLoop if typing.TYPE_CHECKING: from collections.abc import Callable from concurrent.futures import Executor, Future from types import FrameType from typing_extensions import Literal, ParamSpec _Spec = ParamSpec("_Spec") _T = typing.TypeVar("_T") __all__ = ("GLibEventLoop",) def _ignore_handler(_sig: int, _frame: FrameType | None = None) -> None: return None class GLibEventLoop(EventLoop): """ Event loop based on GLib.MainLoop """ def __init__(self) -> None: super().__init__() self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) self._alarms: list[int] = [] self._watch_files: dict[int, int] = {} self._idle_handle: int = 0 self._glib_idle_enabled = False # have we called glib.idle_add? self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {} self._loop = GLib.MainLoop() self._exc: BaseException | None = None self._enable_glib_idle() self._signal_handlers: dict[int, int] = {} def run_in_executor( self, executor: Executor, func: Callable[_Spec, _T], *args: _Spec.args, **kwargs: _Spec.kwargs, ) -> Future[_T]: """Run callable in executor. :param executor: Executor to use for running the function :type executor: concurrent.futures.Executor :param func: function to call :type func: Callable :param args: positional arguments to function :type args: object :param kwargs: keyword arguments to function :type kwargs: object :return: future object for the function call outcome. :rtype: concurrent.futures.Future """ return executor.submit(func, *args, **kwargs) def alarm( self, seconds: float, callback: Callable[[], typing.Any], ) -> tuple[int, Callable[[], typing.Any]]: """ Call callback() a given time from now. No parameters are passed to callback. Returns a handle that may be passed to remove_alarm() seconds -- floating point time to wait before calling callback callback -- function to call from event loop """ @self.handle_exit def ret_false() -> Literal[False]: callback() self._enable_glib_idle() return False fd = GLib.timeout_add(int(seconds * 1000), ret_false) self._alarms.append(fd) return (fd, callback) def set_signal_handler( self, signum: int, handler: Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers, ) -> None: """ Sets the signal handler for signal signum. .. WARNING:: Because this method uses the `GLib`-specific `unix_signal_add` function, its behaviour is different than `signal.signal().` If `signum` is not `SIGHUP`, `SIGINT`, `SIGTERM`, `SIGUSR1`, `SIGUSR2` or `SIGWINCH`, this method performs no actions and immediately returns None. Returns None in all cases (unlike :func:`signal.signal()`). .. signum -- signal number handler -- function (taking signum as its single argument), or `signal.SIG_IGN`, or `signal.SIG_DFL` """ glib_signals = [ signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2, ] # GLib supports SIGWINCH as of version 2.54. if not GLib.check_version(2, 54, 0): glib_signals.append(signal.SIGWINCH) if signum not in glib_signals: # The GLib event loop supports only the signals listed above return if signum in self._signal_handlers: GLib.source_remove(self._signal_handlers.pop(signum)) if handler == signal.Handlers.SIG_IGN: handler = _ignore_handler elif handler == signal.Handlers.SIG_DFL: return def final_handler(signal_number: int): # MyPy False-negative: signal.Handlers casted handler(signal_number, None) # type: ignore[operator] return GLib.SOURCE_CONTINUE source = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signum, final_handler, signum) self._signal_handlers[signum] = source def remove_alarm(self, handle) -> bool: """ Remove an alarm. Returns True if the alarm exists, False otherwise """ try: self._alarms.remove(handle[0]) GLib.source_remove(handle[0]) except ValueError: return False return True def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int: """ Call callback() when fd has some data to read. No parameters are passed to callback. Returns a handle that may be passed to remove_watch_file() fd -- file descriptor to watch for input callback -- function to call when input is available """ @self.handle_exit def io_callback(source, cb_condition) -> Literal[True]: callback() self._enable_glib_idle() return True self._watch_files[fd] = GLib.io_add_watch(fd, GLib.IO_IN, io_callback) return fd def remove_watch_file(self, handle: int) -> bool: """ Remove an input file. Returns True if the input file exists, False otherwise """ if handle in self._watch_files: GLib.source_remove(self._watch_files[handle]) del self._watch_files[handle] return True return False def enter_idle(self, callback: Callable[[], typing.Any]) -> int: """ Add a callback for entering idle. Returns a handle that may be passed to remove_enter_idle() """ self._idle_handle += 1 self._idle_callbacks[self._idle_handle] = callback return self._idle_handle def _enable_glib_idle(self) -> None: if self._glib_idle_enabled: return GLib.idle_add(self._glib_idle_callback) self._glib_idle_enabled = True def _glib_idle_callback(self): for callback in self._idle_callbacks.values(): callback() self._glib_idle_enabled = False return False # ask glib not to call again (or we would be called def remove_enter_idle(self, handle) -> bool: """ Remove an idle callback. Returns True if the handle was removed. """ try: del self._idle_callbacks[handle] except KeyError: return False return True def run(self) -> None: """ Start the event loop. Exit the loop when any callback raises an exception. If ExitMainLoop is raised, exit cleanly. """ try: self._loop.run() finally: if self._loop.is_running(): self._loop.quit() if self._exc: # An exception caused us to exit, raise it now exc = self._exc self._exc = None raise exc.with_traceback(exc.__traceback__) def handle_exit(self, f: Callable[_Spec, _T]) -> Callable[_Spec, _T | Literal[False]]: """ Decorator that cleanly exits the :class:`GLibEventLoop` if :exc:`ExitMainLoop` is thrown inside of the wrapped function. Store the exception info if some other exception occurs, it will be reraised after the loop quits. *f* -- function to be wrapped """ @functools.wraps(f) def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | Literal[False]: try: return f(*args, **kwargs) except ExitMainLoop: self._loop.quit() except BaseException as exc: self._exc = exc if self._loop.is_running(): self._loop.quit() return False return wrapper
9,351
Python
.py
239
30.481172
91
0.610246
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,295
main_loop.py
urwid_urwid/urwid/event_loop/main_loop.py
# Urwid main loop code # Copyright (C) 2004-2012 Ian Ward # Copyright (C) 2008 Walter Mundt # Copyright (C) 2009 Andrew Psaltis # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Urwid web site: https://urwid.org/ from __future__ import annotations import heapq import logging import os import sys import time import typing import warnings from contextlib import suppress from urwid import display, signals from urwid.command_map import Command, command_map from urwid.display.common import INPUT_DESCRIPTORS_CHANGED from urwid.util import StoppingContext, is_mouse_event from urwid.widget import PopUpTarget from .abstract_loop import ExitMainLoop from .select_loop import SelectEventLoop if typing.TYPE_CHECKING: from collections.abc import Callable, Iterable from typing_extensions import Self from urwid.display import BaseScreen from urwid.widget import Widget from .abstract_loop import EventLoop _T = typing.TypeVar("_T") IS_WINDOWS = sys.platform == "win32" PIPE_BUFFER_READ_SIZE = 4096 # can expect this much on Linux, so try for that __all__ = ("CantUseExternalLoop", "MainLoop") class CantUseExternalLoop(Exception): pass class MainLoop: """ This is the standard main loop implementation for a single interactive session. :param widget: the topmost widget used for painting the screen, stored as :attr:`widget` and may be modified. Must be a box widget. :type widget: widget instance :param palette: initial palette for screen :type palette: iterable of palette entries :param screen: screen to use, default is a new :class:`raw_display.Screen` instance; stored as :attr:`screen` :type screen: display module screen instance :param handle_mouse: ``True`` to ask :attr:`.screen` to process mouse events :type handle_mouse: bool :param input_filter: a function to filter input before sending it to :attr:`.widget`, called from :meth:`.input_filter` :type input_filter: callable :param unhandled_input: a function called when input is not handled by :attr:`.widget`, called from :meth:`.unhandled_input` :type unhandled_input: callable :param event_loop: if :attr:`.screen` supports external an event loop it may be given here, default is a new :class:`SelectEventLoop` instance; stored as :attr:`.event_loop` :type event_loop: event loop instance :param pop_ups: `True` to wrap :attr:`.widget` with a :class:`PopUpTarget` instance to allow any widget to open a pop-up anywhere on the screen :type pop_ups: boolean .. attribute:: screen The screen object this main loop uses for screen updates and reading input .. attribute:: event_loop The event loop object this main loop uses for waiting on alarms and IO """ def __init__( self, widget: Widget, palette: Iterable[ tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str] ] = (), screen: BaseScreen | None = None, handle_mouse: bool = True, input_filter: Callable[[list[str], list[int]], list[str]] | None = None, unhandled_input: Callable[[str | tuple[str, int, int, int]], bool | None] | None = None, event_loop: EventLoop | None = None, pop_ups: bool = False, ): self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) self._widget = widget self.handle_mouse = handle_mouse self._pop_ups = False # only initialize placeholder self.pop_ups = pop_ups # triggers property setting side-effect if not screen: screen = display.raw.Screen() if palette: screen.register_palette(palette) self.screen: BaseScreen = screen self.screen_size: tuple[int, int] | None = None self._unhandled_input = unhandled_input self._input_filter = input_filter if not hasattr(screen, "hook_event_loop") and event_loop is not None: raise NotImplementedError(f"screen object passed {screen!r} does not support external event loops") if event_loop is None: event_loop = SelectEventLoop() self.event_loop: EventLoop = event_loop if hasattr(self.screen, "signal_handler_setter"): # Tell the screen what function it must use to set # signal handlers self.screen.signal_handler_setter = self.event_loop.set_signal_handler self._watch_pipes: dict[int, tuple[Callable[[], typing.Any], int]] = {} @property def widget(self) -> Widget: """ Property for the topmost widget used to draw the screen. This must be a box widget. """ return self._widget @widget.setter def widget(self, widget: Widget) -> None: self._widget = widget if self.pop_ups: self._topmost_widget.original_widget = self._widget else: self._topmost_widget = self._widget def _set_widget(self, widget: Widget) -> None: warnings.warn( f"method `{self.__class__.__name__}._set_widget` is deprecated, " f"please use `{self.__class__.__name__}.widget` property", DeprecationWarning, stacklevel=2, ) self.widget = widget @property def pop_ups(self) -> bool: return self._pop_ups @pop_ups.setter def pop_ups(self, pop_ups: bool) -> None: self._pop_ups = pop_ups if pop_ups: self._topmost_widget = PopUpTarget(self._widget) else: self._topmost_widget = self._widget def _set_pop_ups(self, pop_ups: bool) -> None: warnings.warn( f"method `{self.__class__.__name__}._set_pop_ups` is deprecated, " f"please use `{self.__class__.__name__}.pop_ups` property", DeprecationWarning, stacklevel=2, ) self.pop_ups = pop_ups def set_alarm_in(self, sec: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None): """ Schedule an alarm in *sec* seconds that will call *callback* from the within the :meth:`run` method. :param sec: seconds until alarm :type sec: float :param callback: function to call with two parameters: this main loop object and *user_data* :type callback: callable :param user_data: optional user data to pass to the callback :type user_data: object """ self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}") def cb() -> None: callback(self, user_data) return self.event_loop.alarm(sec, cb) def set_alarm_at(self, tm: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None): """ Schedule an alarm at *tm* time that will call *callback* from the within the :meth:`run` function. Returns a handle that may be passed to :meth:`remove_alarm`. :param tm: time to call callback e.g. ``time.time() + 5`` :type tm: float :param callback: function to call with two parameters: this main loop object and *user_data* :type callback: callable :param user_data: optional user data to pass to the callback :type user_data: object """ sec = tm - time.time() self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}") def cb() -> None: callback(self, user_data) return self.event_loop.alarm(sec, cb) def remove_alarm(self, handle) -> bool: """ Remove an alarm. Return ``True`` if *handle* was found, ``False`` otherwise. """ return self.event_loop.remove_alarm(handle) if not IS_WINDOWS: def watch_pipe(self, callback: Callable[[bytes], bool | None]) -> int: """ Create a pipe for use by a subprocess or thread to trigger a callback in the process/thread running the main loop. :param callback: function taking one parameter to call from within the process/thread running the main loop :type callback: callable This method returns a file descriptor attached to the write end of a pipe. The read end of the pipe is added to the list of files :attr:`event_loop` is watching. When data is written to the pipe the callback function will be called and passed a single value containing data read from the pipe. This method may be used any time you want to update widgets from another thread or subprocess. Data may be written to the returned file descriptor with ``os.write(fd, data)``. Ensure that data is less than 512 bytes (or 4K on Linux) so that the callback will be triggered just once with the complete value of data passed in. If the callback returns ``False`` then the watch will be removed from :attr:`event_loop` and the read end of the pipe will be closed. You are responsible for closing the write end of the pipe with ``os.close(fd)``. """ import fcntl pipe_rd, pipe_wr = os.pipe() fcntl.fcntl(pipe_rd, fcntl.F_SETFL, os.O_NONBLOCK) watch_handle = None def cb() -> None: data = os.read(pipe_rd, PIPE_BUFFER_READ_SIZE) if callback(data) is False: self.event_loop.remove_watch_file(watch_handle) os.close(pipe_rd) watch_handle = self.event_loop.watch_file(pipe_rd, cb) self._watch_pipes[pipe_wr] = (watch_handle, pipe_rd) return pipe_wr def remove_watch_pipe(self, write_fd: int) -> bool: """ Close the read end of the pipe and remove the watch created by :meth:`watch_pipe`. ..note:: You are responsible for closing the write end of the pipe. Returns ``True`` if the watch pipe exists, ``False`` otherwise """ try: watch_handle, pipe_rd = self._watch_pipes.pop(write_fd) except KeyError: return False if not self.event_loop.remove_watch_file(watch_handle): return False os.close(pipe_rd) return True def watch_file(self, fd: int, callback: Callable[[], typing.Any]): """ Call *callback* when *fd* has some data to read. No parameters are passed to callback. Returns a handle that may be passed to :meth:`remove_watch_file`. """ self.logger.debug(f"Setting watch file descriptor {fd!r} with {callback!r}") return self.event_loop.watch_file(fd, callback) def remove_watch_file(self, handle): """ Remove a watch file. Returns ``True`` if the watch file exists, ``False`` otherwise. """ return self.event_loop.remove_watch_file(handle) def run(self) -> None: """ Start the main loop handling input events and updating the screen. The loop will continue until an :exc:`ExitMainLoop` exception is raised. If you would prefer to manage the event loop yourself, don't use this method. Instead, call :meth:`start` before starting the event loop, and :meth:`stop` once it's finished. """ with suppress(ExitMainLoop): self._run() def _test_run(self): """ >>> w = _refl("widget") # _refl prints out function calls >>> w.render_rval = "fake canvas" # *_rval is used for return values >>> scr = _refl("screen") >>> scr.get_input_descriptors_rval = [42] >>> scr.get_cols_rows_rval = (20, 10) >>> scr.started = True >>> scr._urwid_signals = {} >>> evl = _refl("event_loop") >>> evl.enter_idle_rval = 1 >>> evl.watch_file_rval = 2 >>> ml = MainLoop(w, [], scr, event_loop=evl) >>> ml.run() # doctest:+ELLIPSIS screen.start() screen.set_mouse_tracking() screen.unhook_event_loop(...) screen.hook_event_loop(...) event_loop.enter_idle(<bound method MainLoop.entering_idle...>) event_loop.run() event_loop.remove_enter_idle(1) screen.unhook_event_loop(...) screen.stop() >>> ml.draw_screen() # doctest:+ELLIPSIS screen.get_cols_rows() widget.render((20, 10), focus=True) screen.draw_screen((20, 10), 'fake canvas') """ def start(self) -> StoppingContext: """ Sets up the main loop, hooking into the event loop where necessary. Starts the :attr:`screen` if it hasn't already been started. If you want to control starting and stopping the event loop yourself, you should call this method before starting, and call `stop` once the loop has finished. You may also use this method as a context manager, which will stop the loop automatically at the end of the block: with main_loop.start(): ... Note that some event loop implementations don't handle exceptions specially if you manage the event loop yourself. In particular, the Twisted and asyncio loops won't stop automatically when :exc:`ExitMainLoop` (or anything else) is raised. """ self.logger.debug(f"Starting event loop {self.event_loop.__class__.__name__!r} to manage display.") self.screen.start() if self.handle_mouse: self.screen.set_mouse_tracking() if not hasattr(self.screen, "hook_event_loop"): raise CantUseExternalLoop(f"Screen {self.screen!r} doesn't support external event loops") with suppress(NameError): signals.connect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors) # watch our input descriptors self._reset_input_descriptors() self.idle_handle = self.event_loop.enter_idle(self.entering_idle) # the screen is redrawn automatically after input and alarms, # however, there can be none of those at the start, # so draw the initial screen here unconditionally self.event_loop.alarm(0, self.entering_idle) return StoppingContext(self) def stop(self) -> None: """ Cleans up any hooks added to the event loop. Only call this if you're managing the event loop yourself, after the loop stops. """ self.event_loop.remove_enter_idle(self.idle_handle) del self.idle_handle signals.disconnect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors) self.screen.unhook_event_loop(self.event_loop) self.screen.stop() def _reset_input_descriptors(self) -> None: self.screen.unhook_event_loop(self.event_loop) self.screen.hook_event_loop(self.event_loop, self._update) def _run(self) -> None: try: self.start() except CantUseExternalLoop: try: self._run_screen_event_loop() return finally: self.screen.stop() try: self.event_loop.run() except: self.screen.stop() # clean up screen control raise self.stop() def _update(self, keys: list[str], raw: list[int]) -> None: """ >>> w = _refl("widget") >>> w.selectable_rval = True >>> w.mouse_event_rval = True >>> scr = _refl("screen") >>> scr.get_cols_rows_rval = (15, 5) >>> evl = _refl("event_loop") >>> ml = MainLoop(w, [], scr, event_loop=evl) >>> ml._input_timeout = "old timeout" >>> ml._update(['y'], [121]) # doctest:+ELLIPSIS screen.get_cols_rows() widget.selectable() widget.keypress((15, 5), 'y') >>> ml._update([("mouse press", 1, 5, 4)], []) widget.mouse_event((15, 5), 'mouse press', 1, 5, 4, focus=True) >>> ml._update([], []) """ keys = self.input_filter(keys, raw) if keys: self.process_input(keys) if "window resize" in keys: self.screen_size = None def _run_screen_event_loop(self) -> None: """ This method is used when the screen does not support using external event loops. The alarms stored in the SelectEventLoop in :attr:`event_loop` are modified by this method. """ # pylint: disable=protected-access # special case for alarms handling self.logger.debug(f"Starting screen {self.screen!r} event loop") next_alarm = None while True: self.draw_screen() if not next_alarm and self.event_loop._alarms: next_alarm = heapq.heappop(self.event_loop._alarms) keys: list[str] = [] raw: list[int] = [] while not keys: if next_alarm: sec = max(0.0, next_alarm[0] - time.time()) self.screen.set_input_timeouts(sec) else: self.screen.set_input_timeouts(None) keys, raw = self.screen.get_input(True) if not keys and next_alarm: sec = next_alarm[0] - time.time() if sec <= 0: break keys = self.input_filter(keys, raw) if keys: self.process_input(keys) while next_alarm: sec = next_alarm[0] - time.time() if sec > 0: break _tm, _tie_break, callback = next_alarm callback() if self.event_loop._alarms: next_alarm = heapq.heappop(self.event_loop._alarms) else: next_alarm = None if "window resize" in keys: self.screen_size = None def _test_run_screen_event_loop(self): """ >>> w = _refl("widget") >>> scr = _refl("screen") >>> scr.get_cols_rows_rval = (10, 5) >>> scr.get_input_rval = [], [] >>> ml = MainLoop(w, screen=scr) >>> def stop_now(loop, data): ... raise ExitMainLoop() >>> handle = ml.set_alarm_in(0, stop_now) >>> try: ... ml._run_screen_event_loop() ... except ExitMainLoop: ... pass screen.get_cols_rows() widget.render((10, 5), focus=True) screen.draw_screen((10, 5), None) screen.set_input_timeouts(0.0) screen.get_input(True) """ def process_input(self, keys: Iterable[str | tuple[str, int, int, int]]) -> bool: """ This method will pass keyboard input and mouse events to :attr:`widget`. This method is called automatically from the :meth:`run` method when there is input, but may also be called to simulate input from the user. *keys* is a list of input returned from :attr:`screen`'s get_input() or get_input_nonblocking() methods. Returns ``True`` if any key was handled by a widget or the :meth:`unhandled_input` method. """ self.logger.debug(f"Processing input: keys={keys!r}") if not self.screen_size: self.screen_size = self.screen.get_cols_rows() something_handled = False for key in keys: if key == "window resize": continue if isinstance(key, str): if self._topmost_widget.selectable(): handled_key = self._topmost_widget.keypress(self.screen_size, key) if not handled_key: something_handled = True continue key = handled_key # noqa: PLW2901 elif is_mouse_event(key): event, button, col, row = key if hasattr(self._topmost_widget, "mouse_event") and self._topmost_widget.mouse_event( self.screen_size, event, button, col, row, focus=True, ): something_handled = True continue else: raise TypeError(f"{key!r} is not str | tuple[str, int, int, int]") if key: if command_map[key] == Command.REDRAW_SCREEN: self.screen.clear() something_handled = True else: something_handled |= bool(self.unhandled_input(key)) else: something_handled = True return something_handled def _test_process_input(self): """ >>> w = _refl("widget") >>> w.selectable_rval = True >>> scr = _refl("screen") >>> scr.get_cols_rows_rval = (10, 5) >>> ml = MainLoop(w, [], scr) >>> ml.process_input(['enter', ('mouse drag', 1, 14, 20)]) screen.get_cols_rows() widget.selectable() widget.keypress((10, 5), 'enter') widget.mouse_event((10, 5), 'mouse drag', 1, 14, 20, focus=True) True """ def input_filter(self, keys: list[str], raw: list[int]) -> list[str]: """ This function is passed each all the input events and raw keystroke values. These values are passed to the *input_filter* function passed to the constructor. That function must return a list of keys to be passed to the widgets to handle. If no *input_filter* was defined this implementation will return all the input events. """ if self._input_filter: return self._input_filter(keys, raw) return keys def unhandled_input(self, data: str | tuple[str, int, int, int]) -> bool | None: """ This function is called with any input that was not handled by the widgets, and calls the *unhandled_input* function passed to the constructor. If no *unhandled_input* was defined then the input will be ignored. *input* is the keyboard or mouse input. The *unhandled_input* function should return ``True`` if it handled the input. """ if self._unhandled_input: return self._unhandled_input(data) return False def entering_idle(self) -> None: """ This method is called whenever the event loop is about to enter the idle state. :meth:`draw_screen` is called here to update the screen when anything has changed. """ if self.screen.started: self.draw_screen() else: self.logger.debug(f"No redrawing screen: {self.screen!r} is not started.") def draw_screen(self) -> None: """ Render the widgets and paint the screen. This method is called automatically from :meth:`entering_idle`. If you modify the widgets displayed outside of handling input or responding to an alarm you will need to call this method yourself to repaint the screen. """ if not self.screen_size: self.screen_size = self.screen.get_cols_rows() self.logger.debug(f"Screen size recalculated: {self.screen_size!r}") canvas = self._topmost_widget.render(self.screen_size, focus=True) self.screen.draw_screen(self.screen_size, canvas) def _refl(name: str, rval=None, loop_exit=False): """ This function is used to test the main loop classes. >>> scr = _refl("screen") >>> scr.function("argument") screen.function('argument') >>> scr.callme(when="now") screen.callme(when='now') >>> scr.want_something_rval = 42 >>> x = scr.want_something() screen.want_something() >>> x 42 """ class Reflect: def __init__(self, name: str, rval=None): self._name = name self._rval = rval def __call__(self, *argl, **argd): args = ", ".join([repr(a) for a in argl]) if args and argd: args = f"{args}, " args += ", ".join([f"{k}={v!r}" for k, v in argd.items()]) print(f"{self._name}({args})") if loop_exit: raise ExitMainLoop() return self._rval def __getattr__(self, attr): if attr.endswith("_rval"): raise AttributeError() # print(self._name+"."+attr) if hasattr(self, f"{attr}_rval"): return Reflect(f"{self._name}.{attr}", getattr(self, f"{attr}_rval")) return Reflect(f"{self._name}.{attr}") return Reflect(name) def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
26,000
Python
.py
583
34.521441
119
0.594762
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,296
twisted_serve_ssh.tac
urwid_urwid/examples/twisted_serve_ssh.tac
# encoding: utf-8 """ Example application for integrating serving a Urwid application remotely. Run this application with:: twistd -ny twisted_serve_ssh.tac Then in another terminal run:: ssh -p 6022 user@localhost (The password is 'pw' without the quotes.) Note: To use this in real life, you must use some real checker. """ from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse import urwid from twisted_serve_ssh import UrwidMind, UrwidUi, create_application class HelloUi(UrwidUi): def create_urwid_toplevel(self): txt = urwid.Edit('Hello World?\n ') txt2 = urwid.Edit('Hello World?\n ') fill = urwid.Filler(urwid.Pile([txt, txt2]), 'top') return fill class HelloMind(UrwidMind): ui_factory = HelloUi cred_checkers = [InMemoryUsernamePasswordDatabaseDontUse(user='pw')] application = create_application('TXUrwid Demo', HelloMind, 6022) # vim: ft=python
946
Python
.tac
24
35.541667
73
0.751381
urwid/urwid
2,793
312
124
LGPL-2.1
9/5/2024, 5:08:50 PM (Europe/Amsterdam)
1,297
SickBeard.py
midgetspy_Sick-Beard/SickBeard.py
#!/usr/bin/env python # Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. # Check needed software dependencies to nudge users to fix their setup import sys if sys.version_info < (2, 5): sys.exit("Sorry, requires Python 2.5, 2.6 or 2.7.") try: import Cheetah if Cheetah.Version[0] != '2': raise ValueError except ValueError: sys.exit("Sorry, requires Python module Cheetah 2.1.0 or newer.") except: sys.exit("The Python module Cheetah is required") # We only need this for compiling an EXE and I will just always do that on 2.6+ if sys.hexversion >= 0x020600F0: from multiprocessing import freeze_support # @UnresolvedImport import locale import os import threading import time import signal import traceback import getopt import sickbeard from sickbeard import db from sickbeard.tv import TVShow from sickbeard import logger from sickbeard.version import SICKBEARD_VERSION from sickbeard.webserveInit import initWebServer from lib.configobj import ConfigObj signal.signal(signal.SIGINT, sickbeard.sig_handler) signal.signal(signal.SIGTERM, sickbeard.sig_handler) def loadShowsFromDB(): """ Populates the showList with shows from the database """ myDB = db.DBConnection() sqlResults = myDB.select("SELECT * FROM tv_shows") for sqlShow in sqlResults: try: curShow = TVShow(int(sqlShow["tvdb_id"])) sickbeard.showList.append(curShow) except Exception, e: logger.log(u"There was an error creating the show in " + sqlShow["location"] + ": " + str(e).decode('utf-8'), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) # TODO: update the existing shows if the showlist has something in it def daemonize(): """ Fork off as a daemon """ # pylint: disable=E1101 # Make a non-session-leader child process try: pid = os.fork() # @UndefinedVariable - only available in UNIX if pid != 0: os._exit(0) except OSError, e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) os.setsid() # @UndefinedVariable - only available in UNIX # Make sure I can read my own files and shut out others prev = os.umask(0) os.umask(prev and int('077', 8)) # Make the child a session-leader by detaching from the terminal try: pid = os.fork() # @UndefinedVariable - only available in UNIX if pid != 0: os._exit(0) except OSError, e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # Write pid if sickbeard.CREATEPID: pid = str(os.getpid()) logger.log(u"Writing PID: " + pid + " to " + str(sickbeard.PIDFILE)) try: file(sickbeard.PIDFILE, 'w').write("%s\n" % pid) except IOError, e: logger.log_error_and_exit(u"Unable to write PID file: " + sickbeard.PIDFILE + " Error: " + str(e.strerror) + " [" + str(e.errno) + "]") # Redirect all output sys.stdout.flush() sys.stderr.flush() devnull = getattr(os, 'devnull', '/dev/null') stdin = file(devnull, 'r') stdout = file(devnull, 'a+') stderr = file(devnull, 'a+') os.dup2(stdin.fileno(), sys.stdin.fileno()) os.dup2(stdout.fileno(), sys.stdout.fileno()) os.dup2(stderr.fileno(), sys.stderr.fileno()) def help_message(): """ print help message for commandline options """ help_msg = "\n" help_msg += "Usage: " + sickbeard.MY_FULLNAME + " <option> <another option>\n" help_msg += "\n" help_msg += "Options:\n" help_msg += "\n" help_msg += " -h --help Prints this message\n" help_msg += " -f --forceupdate Force update all shows in the DB (from tvdb) on startup\n" help_msg += " -q --quiet Disables logging to console\n" help_msg += " --nolaunch Suppress launching web browser on startup\n" if sys.platform == 'win32': help_msg += " -d --daemon Running as real daemon is not supported on Windows\n" help_msg += " On Windows, --daemon is substituted with: --quiet --nolaunch\n" else: help_msg += " -d --daemon Run as double forked daemon (includes options --quiet --nolaunch)\n" help_msg += " --pidfile=<path> Combined with --daemon creates a pidfile (full path including filename)\n" help_msg += " -p <port> --port=<port> Override default/configured port to listen on\n" help_msg += " --datadir=<path> Override folder (full path) as location for\n" help_msg += " storing database, configfile, cache, logfiles \n" help_msg += " Default: " + sickbeard.PROG_DIR + "\n" help_msg += " --config=<path> Override config filename (full path including filename)\n" help_msg += " to load configuration from \n" help_msg += " Default: config.ini in " + sickbeard.PROG_DIR + " or --datadir location\n" help_msg += " --noresize Prevent resizing of the banner/posters even if PIL is installed\n" return help_msg def main(): """ TV for me """ # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.DAEMON = False sickbeard.CREATEPID = False sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: sys.exit("Sorry, you MUST add the Sick Beard folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "hfqdp::", ['help', 'forceupdate', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize']) # @UnusedVariable except getopt.GetoptError: sys.exit(help_message()) forceUpdate = False forcedPort = None noLaunch = False for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(help_message()) # Should we update (from tvdb) all shows in the DB right away? if o in ('-f', '--forceupdate'): forceUpdate = True # Disables logging to console if o in ('-q', '--quiet'): consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): noLaunch = True # Run as a double forked daemon if o in ('-d', '--daemon'): sickbeard.DAEMON = True # When running as daemon disable consoleLogging and don't start browser consoleLogging = False noLaunch = True if sys.platform == 'win32': sickbeard.DAEMON = False # Write a pidfile if requested if o in ('--pidfile',): sickbeard.CREATEPID = True sickbeard.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(sickbeard.PIDFILE): sys.exit("PID file: " + sickbeard.PIDFILE + " already exists. Exiting.") # Override default/configured port if o in ('-p', '--port'): try: forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Specify folder to use as data dir (storing database, configfile, cache, logfiles) if o in ('--datadir',): sickbeard.DATA_DIR = os.path.abspath(a) # Specify filename to load the config information from if o in ('--config',): sickbeard.CONFIG_FILE = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if sickbeard.CREATEPID: if sickbeard.DAEMON: pid_dir = os.path.dirname(sickbeard.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not os.access(pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if consoleLogging: sys.stdout.write("Not running in daemon mode. PID file creation disabled.\n") sickbeard.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error: sys.exit("Unable to create data directory: " + sickbeard.DATA_DIR + " Exiting.") # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): sys.exit("Data directory: " + sickbeard.DATA_DIR + " must be writable (write permissions). Exiting.") # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): sys.exit("Config file: " + sickbeard.CONFIG_FILE + " must be writeable (write permissions). Exiting.") elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): sys.exit("Config file directory: " + os.path.dirname(sickbeard.CONFIG_FILE) + " must be writeable (write permissions). Exiting") os.chdir(sickbeard.DATA_DIR) if consoleLogging: sys.stdout.write("Starting up Sick Beard " + SICKBEARD_VERSION + "\n") if not os.path.isfile(sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") # Load the config and publish it to the sickbeard package sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if sickbeard.DAEMON: daemonize() # Use this PID for everything sickbeard.PID = os.getpid() if forcedPort: logger.log(u"Forcing web server to port " + str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = '::' else: webhost = '0.0.0.0' try: initWebServer({ 'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'https_cert': sickbeard.HTTPS_CERT, 'https_key': sickbeard.HTTPS_KEY, }) except IOError: logger.log(u"Unable to start web server, is something else running on port: " + str(startPort), logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit("Unable to start web server, is something else running on port: " + str(startPort)) # Build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # Start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # @UndefinedVariable # Stay alive while my threads do the work while (True): if sickbeard.invoked_command: sickbeard.invoked_command() sickbeard.invoked_command = None time.sleep(1) return if __name__ == "__main__": if sys.hexversion >= 0x020600F0: freeze_support() main()
15,016
Python
.py
323
38.882353
190
0.626223
midgetspy/Sick-Beard
2,890
1,507
113
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,298
db.py
midgetspy_Sick-Beard/sickbeard/db.py
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. from __future__ import with_statement import os.path import re import sqlite3 import time import threading import sickbeard from sickbeard import encodingKludge as ek from sickbeard import logger from sickbeard.exceptions import ex db_lock = threading.Lock() def dbFilename(filename="sickbeard.db", suffix=None): """ @param filename: The sqlite database filename to use. If not specified, will be made to be sickbeard.db @param suffix: The suffix to append to the filename. A '.' will be added automatically, i.e. suffix='v0' will make dbfile.db.v0 @return: the correct location of the database file. """ if suffix: filename = "%s.%s" % (filename, suffix) return ek.ek(os.path.join, sickbeard.DATA_DIR, filename) class DBConnection: def __init__(self, filename="sickbeard.db", suffix=None, row_type=None): self.filename = filename self.connection = sqlite3.connect(dbFilename(filename), 20) if row_type == "dict": self.connection.row_factory = self._dict_factory else: self.connection.row_factory = sqlite3.Row def checkDBVersion(self): try: result = self.select("SELECT db_version FROM db_version") except sqlite3.OperationalError, e: if "no such table: db_version" in e.args[0]: return 0 if result: return int(result[0]["db_version"]) else: return 0 def mass_action(self, querylist, logTransaction=False): with db_lock: if querylist is None: return sqlResult = [] attempt = 0 while attempt < 5: try: for qu in querylist: if len(qu) == 1: if logTransaction: logger.log(qu[0], logger.DEBUG) sqlResult.append(self.connection.execute(qu[0])) elif len(qu) > 1: if logTransaction: logger.log(qu[0] + " with args " + str(qu[1]), logger.DEBUG) sqlResult.append(self.connection.execute(qu[0], qu[1])) self.connection.commit() logger.log(u"Transaction with " + str(len(querylist)) + u" query's executed", logger.DEBUG) return sqlResult except sqlite3.OperationalError, e: sqlResult = [] if self.connection: self.connection.rollback() if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]: logger.log(u"DB error: " + ex(e), logger.WARNING) attempt += 1 time.sleep(1) else: logger.log(u"DB error: " + ex(e), logger.ERROR) raise except sqlite3.DatabaseError, e: sqlResult = [] if self.connection: self.connection.rollback() logger.log(u"Fatal error executing query: " + ex(e), logger.ERROR) raise return sqlResult def action(self, query, args=None): with db_lock: if query is None: return sqlResult = None attempt = 0 while attempt < 5: try: if args is None: logger.log(self.filename + ": " + query, logger.DEBUG) sqlResult = self.connection.execute(query) else: logger.log(self.filename + ": " + query + " with args " + str(args), logger.DEBUG) sqlResult = self.connection.execute(query, args) self.connection.commit() # get out of the connection attempt loop since we were successful break except sqlite3.OperationalError, e: if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]: logger.log(u"DB error: " + ex(e), logger.WARNING) attempt += 1 time.sleep(1) else: logger.log(u"DB error: " + ex(e), logger.ERROR) raise except sqlite3.DatabaseError, e: logger.log(u"Fatal error executing query: " + ex(e), logger.ERROR) raise return sqlResult def select(self, query, args=None): sqlResults = self.action(query, args).fetchall() if sqlResults is None: return [] return sqlResults def upsert(self, tableName, valueDict, keyDict): changesBefore = self.connection.total_changes genParams = lambda myDict: [x + " = ?" for x in myDict.keys()] query = "UPDATE " + tableName + " SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict)) self.action(query, valueDict.values() + keyDict.values()) if self.connection.total_changes == changesBefore: query = "INSERT INTO " + tableName + " (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \ " VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")" self.action(query, valueDict.values() + keyDict.values()) def tableInfo(self, tableName): # FIXME ? binding is not supported here, but I cannot find a way to escape a string manually cursor = self.connection.execute("PRAGMA table_info(%s)" % tableName) columns = {} for column in cursor: columns[column['name']] = { 'type': column['type'] } return columns # http://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query def _dict_factory(self, cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def sanityCheckDatabase(connection, sanity_check): sanity_check(connection).check() class DBSanityCheck(object): def __init__(self, connection): self.connection = connection def check(self): pass # =============== # = Upgrade API = # =============== def upgradeDatabase(connection, schema): logger.log(u"Checking database structure...", logger.MESSAGE) _processUpgrade(connection, schema) def prettyName(class_name): return ' '.join([x.group() for x in re.finditer("([A-Z])([a-z0-9]+)", class_name)]) def _processUpgrade(connection, upgradeClass): instance = upgradeClass(connection) pretty_class_name = prettyName(upgradeClass.__name__) logger.log(u"Checking " + pretty_class_name + " database upgrade", logger.DEBUG) if not instance.test(): logger.log(u"Database upgrade required: " + pretty_class_name, logger.MESSAGE) try: instance.execute() except sqlite3.DatabaseError, e: print "Error in " + str(pretty_class_name) + ": " + ex(e) raise logger.log(pretty_class_name + u" upgrade completed", logger.DEBUG) else: logger.log(pretty_class_name + u" upgrade not required", logger.DEBUG) for upgradeSubClass in upgradeClass.__subclasses__(): _processUpgrade(connection, upgradeSubClass) # Base migration class. All future DB changes should be subclassed from this class class SchemaUpgrade (object): def __init__(self, connection): self.connection = connection def hasTable(self, tableName): return len(self.connection.action("SELECT 1 FROM sqlite_master WHERE name = ?;", (tableName, )).fetchall()) > 0 def hasColumn(self, tableName, column): return column in self.connection.tableInfo(tableName) def addColumn(self, tableName, column, data_type="NUMERIC", default=0): self.connection.action("ALTER TABLE %s ADD %s %s" % (tableName, column, data_type)) self.connection.action("UPDATE %s SET %s = ?" % (tableName, column), (default,)) def checkDBVersion(self): return self.connection.checkDBVersion() def incDBVersion(self): new_version = self.checkDBVersion() + 1 self.connection.action("UPDATE db_version SET db_version = ?", [new_version]) return new_version
9,583
Python
.py
199
35.497487
129
0.57431
midgetspy/Sick-Beard
2,890
1,507
113
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,299
generic_queue.py
midgetspy_Sick-Beard/sickbeard/generic_queue.py
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. import datetime import threading from sickbeard import logger class QueuePriorities: LOW = 10 NORMAL = 20 HIGH = 30 class GenericQueue(object): def __init__(self): self.currentItem = None self.queue = [] self.thread = None self.queue_name = "QUEUE" self.min_priority = 0 self.currentItem = None def pause(self): logger.log(u"Pausing queue") self.min_priority = 999999999999 def unpause(self): logger.log(u"Unpausing queue") self.min_priority = 0 def add_item(self, item): item.added = datetime.datetime.now() self.queue.append(item) return item def run(self): # only start a new task if one isn't already going if self.thread == None or self.thread.isAlive() == False: # if the thread is dead then the current item should be finished if self.currentItem != None: self.currentItem.finish() self.currentItem = None # if there's something in the queue then run it in a thread and take it out of the queue if len(self.queue) > 0: # sort by priority def sorter(x,y): """ Sorts by priority descending then time ascending """ if x.priority == y.priority: if y.added == x.added: return 0 elif y.added < x.added: return 1 elif y.added > x.added: return -1 else: return y.priority-x.priority self.queue.sort(cmp=sorter) queueItem = self.queue[0] if queueItem.priority < self.min_priority: return # launch the queue item in a thread # TODO: improve thread name threadName = self.queue_name + '-' + queueItem.get_thread_name() self.thread = threading.Thread(None, queueItem.execute, threadName) self.thread.start() self.currentItem = queueItem # take it out of the queue del self.queue[0] class QueueItem: def __init__(self, name, action_id = 0): self.name = name self.inProgress = False self.priority = QueuePriorities.NORMAL self.thread_name = None self.action_id = action_id self.added = None def get_thread_name(self): if self.thread_name: return self.thread_name else: return self.name.replace(" ","-").upper() def execute(self): """Implementing classes should call this""" self.inProgress = True def finish(self): """Implementing Classes should call this""" self.inProgress = False
3,916
Python
.py
96
28.416667
101
0.569459
midgetspy/Sick-Beard
2,890
1,507
113
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)