notifications.pyΒΆ

 1#!/usr/bin/env python
 2
 3"""Example: messages of each severity in the footer of a window, each shown for five seconds.
 4
 5g, i, w, e and r post a debug, an info, a warning, an error and a critical message,
 6s posts one that stays until it is dismissed,
 7d dismisses the newest message, c clears them all, and q exits. The keys work in either case.
 8"""
 9
10from __future__ import annotations
11
12import itertools
13
14import urwid
15
16
17def main() -> None:
18    """Build the window with the notifications footer and the key handling, and run the main loop."""
19    notifications = urwid.Notifications(
20        max_count=5,
21        severity_attr={
22            urwid.Severity.DEBUG: "debug",
23            urwid.Severity.INFO: "info",
24            urwid.Severity.WARNING: "warning",
25            urwid.Severity.ERROR: "error",
26            urwid.Severity.CRITICAL: "critical",
27        },
28        default="g: debug  i: info  w: warning  e: error  r: critical  s: sticky  d: dismiss  c: clear  q: quit",
29        default_attr="help",
30    )
31    numbers = itertools.count(1)
32    severities = {
33        "g": urwid.Severity.DEBUG,
34        "i": urwid.Severity.INFO,
35        "w": urwid.Severity.WARNING,
36        "e": urwid.Severity.ERROR,
37        "r": urwid.Severity.CRITICAL,
38    }
39
40    def unhandled(key: str | tuple[str, int, int, int]) -> None:
41        if not isinstance(key, str):
42            return
43        # Shift or Caps Lock sends the upper-case key
44        key = key.lower()
45        if key == "q":
46            raise urwid.ExitMainLoop
47        if key in severities:
48            severity = severities[key]
49            notifications.notify(f"{severity.name.lower()} message {next(numbers)}", severity=severity)
50        elif key == "s":
51            notifications.notify(f"sticky message {next(numbers)}, d dismisses it", timeout=None)
52        elif key == "d" and notifications.notifications:
53            notifications.dismiss(notifications.notifications[-1])
54        elif key == "c":
55            notifications.clear()
56
57    body = urwid.Filler(urwid.Text("Messages appear in the footer, oldest at the top.", align="center"))
58    frame: urwid.Frame[urwid.Filler[urwid.Text], None, urwid.Notifications] = urwid.Frame(body, footer=notifications)
59    palette: list[tuple[str, str, str]] = [
60        ("help", "black", "light gray"),
61        ("debug", "dark gray", "black"),
62        ("info", "white", "dark blue"),
63        ("warning", "black", "brown"),
64        ("error", "white", "dark red"),
65        ("critical", "yellow", "dark red"),
66    ]
67    urwid.MainLoop(frame, palette, unhandled_input=unhandled).run()
68
69
70if __name__ == "__main__":
71    main()