File: input_test.py

package info (click to toggle)
urwid 2.6.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,236 kB
  • sloc: python: 29,290; javascript: 382; sh: 34; makefile: 22
file content (160 lines) | stat: -rwxr-xr-x 4,821 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/env python
#
# Urwid keyboard input test app
#    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/

"""
Keyboard test application
"""

from __future__ import annotations

import argparse
import logging

import urwid

if urwid.display.web.is_web_request():
    Screen = urwid.display.web.Screen
    loop_cls = urwid.SelectEventLoop
else:
    event_loops: dict[str, type[urwid.EventLoop] | None] = {
        "none": None,
        "select": urwid.SelectEventLoop,
        "asyncio": urwid.AsyncioEventLoop,
    }
    if hasattr(urwid, "TornadoEventLoop"):
        event_loops["tornado"] = urwid.TornadoEventLoop
    if hasattr(urwid, "GLibEventLoop"):
        event_loops["glib"] = urwid.GLibEventLoop
    if hasattr(urwid, "TwistedEventLoop"):
        event_loops["twisted"] = urwid.TwistedEventLoop
    if hasattr(urwid, "TrioEventLoop"):
        event_loops["trio"] = urwid.TrioEventLoop
    if hasattr(urwid, "ZMQEventLoop"):
        event_loops["zmq"] = urwid.ZMQEventLoop

    parser = argparse.ArgumentParser(description="Input test")
    parser.add_argument(
        "argc",
        help="Positional arguments ('r' for raw display)",
        metavar="<arguments>",
        nargs="*",
        default=(),
    )
    group = parser.add_argument_group("Advanced Options")
    group.add_argument(
        "--event-loop",
        choices=event_loops,
        default="none",
        help="Event loop to use ('none' = use the default)",
    )
    group.add_argument("--debug-log", action="store_true", help="Enable debug logging")

    args = parser.parse_args()

    if not hasattr(urwid.display, "curses") or "r" in args.argc:
        Screen = urwid.display.raw.Screen
    else:
        Screen = urwid.display.curses.Screen

    loop_cls = event_loops[args.event_loop]

    if args.debug_log:
        logging.basicConfig(
            level=logging.DEBUG,
            filename="debug.log",
            format=(
                "%(levelname)1.1s %(asctime)s | %(threadName)s | %(name)s \n"
                "\t%(message)s\n"
                "-------------------------------------------------------------------------------"
            ),
            datefmt="%d-%b-%Y %H:%M:%S",
            force=True,
        )
        logging.captureWarnings(True)


def key_test():
    screen = Screen()
    header = urwid.AttrMap(
        urwid.Text("Values from get_input(). Q exits."),
        "header",
    )
    lw = urwid.SimpleListWalker([])
    listbox = urwid.AttrMap(
        urwid.ListBox(lw),
        "listbox",
    )
    top = urwid.Frame(listbox, header)

    def input_filter(keys, raw):
        if "q" in keys or "Q" in keys:
            raise urwid.ExitMainLoop

        t = []
        for k in keys:
            if isinstance(k, tuple):
                out = []
                for v in k:
                    if out:
                        out += [", "]
                    out += [("key", repr(v))]
                t += ["(", *out, ")"]
            else:
                t += ["'", ("key", k), "' "]

        rawt = urwid.Text(", ".join(f"{r:d}" for r in raw))

        if t:
            lw.append(urwid.Columns([(urwid.WEIGHT, 2, urwid.Text(t)), rawt]))
            listbox.original_widget.set_focus(len(lw) - 1, "above")
        return keys

    loop = urwid.MainLoop(
        top,
        [
            ("header", "black", "dark cyan", "standout"),
            ("key", "yellow", "dark blue", "bold"),
            ("listbox", "light gray", "black"),
        ],
        screen,
        input_filter=input_filter,
        event_loop=loop_cls() if loop_cls is not None else None,
    )

    old = ()

    try:
        old = screen.tty_signal_keys("undefined", "undefined", "undefined", "undefined", "undefined")
        loop.run()
    finally:
        if old:
            screen.tty_signal_keys(*old)


def main():
    urwid.display.web.set_preferences("Input Test")
    if urwid.display.web.handle_short_request():
        return
    key_test()


if __name__ == "__main__" or urwid.display.web.is_web_request():
    main()