dasha-framework 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. dasha/__init__.py +9 -0
  2. dasha/__main__.py +534 -0
  3. dasha/animation.py +90 -0
  4. dasha/application.py +276 -0
  5. dasha/border.py +34 -0
  6. dasha/canvas.py +331 -0
  7. dasha/client.py +642 -0
  8. dasha/clipboard.py +94 -0
  9. dasha/config.py +89 -0
  10. dasha/desktop.py +58 -0
  11. dasha/dialog.py +601 -0
  12. dasha/events.py +471 -0
  13. dasha/filedialog.py +323 -0
  14. dasha/help.py +900 -0
  15. dasha/helppages/applications.md +25 -0
  16. dasha/helppages/index.md +20 -0
  17. dasha/helppages/keyboard.md +45 -0
  18. dasha/helppages/menus.md +32 -0
  19. dasha/helppages/running.md +18 -0
  20. dasha/helppages/settings.md +25 -0
  21. dasha/helppages/windows.md +36 -0
  22. dasha/host.py +120 -0
  23. dasha/hosting.py +1081 -0
  24. dasha/inbox.py +122 -0
  25. dasha/install.py +369 -0
  26. dasha/keytest.py +86 -0
  27. dasha/logs.py +104 -0
  28. dasha/manager.py +2468 -0
  29. dasha/markdown.py +1173 -0
  30. dasha/menu.py +701 -0
  31. dasha/printing.py +42 -0
  32. dasha/processes.py +293 -0
  33. dasha/protocol.py +335 -0
  34. dasha/pseudoterminal/__init__.py +43 -0
  35. dasha/pseudoterminal/_posix.py +133 -0
  36. dasha/pseudoterminal/_windows.py +352 -0
  37. dasha/pseudoterminal/base.py +151 -0
  38. dasha/py.typed +0 -0
  39. dasha/recovery.py +239 -0
  40. dasha/registry.py +475 -0
  41. dasha/remote.py +284 -0
  42. dasha/rundialog.py +342 -0
  43. dasha/scrollbar.py +193 -0
  44. dasha/settings/__init__.py +326 -0
  45. dasha/settings/appearance.py +353 -0
  46. dasha/settings/applications.py +165 -0
  47. dasha/settings/colours.py +94 -0
  48. dasha/settings/keys.py +225 -0
  49. dasha/settings/lists.py +11 -0
  50. dasha/shell.py +118 -0
  51. dasha/shortcuts.py +536 -0
  52. dasha/statusbar.py +111 -0
  53. dasha/style.py +256 -0
  54. dasha/terminal/__init__.py +236 -0
  55. dasha/terminal/_posix.py +130 -0
  56. dasha/terminal/_winbuffer.py +264 -0
  57. dasha/terminal/_windows.py +349 -0
  58. dasha/terminal/ansi.py +46 -0
  59. dasha/theme.py +749 -0
  60. dasha/vt.py +1216 -0
  61. dasha/widgets/__init__.py +90 -0
  62. dasha/widgets/autocomplete.py +153 -0
  63. dasha/widgets/base.py +298 -0
  64. dasha/widgets/button.py +224 -0
  65. dasha/widgets/checkbox.py +52 -0
  66. dasha/widgets/cluster.py +357 -0
  67. dasha/widgets/collapsible.py +224 -0
  68. dasha/widgets/combobox.py +157 -0
  69. dasha/widgets/container.py +182 -0
  70. dasha/widgets/editing.py +195 -0
  71. dasha/widgets/groupbox.py +126 -0
  72. dasha/widgets/label.py +106 -0
  73. dasha/widgets/listbox.py +535 -0
  74. dasha/widgets/paragraph.py +265 -0
  75. dasha/widgets/password.py +60 -0
  76. dasha/widgets/progressbar.py +196 -0
  77. dasha/widgets/radiobutton.py +61 -0
  78. dasha/widgets/scrollbar.py +157 -0
  79. dasha/widgets/slider.py +196 -0
  80. dasha/widgets/spinbox.py +237 -0
  81. dasha/widgets/splitter.py +274 -0
  82. dasha/widgets/switch.py +190 -0
  83. dasha/widgets/table.py +413 -0
  84. dasha/widgets/tabs.py +291 -0
  85. dasha/widgets/terminalview.py +475 -0
  86. dasha/widgets/textarea.py +990 -0
  87. dasha/widgets/textbox.py +591 -0
  88. dasha/widgets/tree.py +443 -0
  89. dasha/window.py +992 -0
  90. dasha/windowmenu.py +165 -0
  91. dasha_framework-0.0.1.dist-info/METADATA +346 -0
  92. dasha_framework-0.0.1.dist-info/RECORD +96 -0
  93. dasha_framework-0.0.1.dist-info/WHEEL +5 -0
  94. dasha_framework-0.0.1.dist-info/entry_points.txt +3 -0
  95. dasha_framework-0.0.1.dist-info/licenses/LICENSE +201 -0
  96. dasha_framework-0.0.1.dist-info/top_level.txt +1 -0
dasha/application.py ADDED
@@ -0,0 +1,276 @@
1
+ """Applications: the programs that run on the Dasha Desktop.
2
+
3
+ An application owns a menu bar, any number of windows, and the dialogs it
4
+ opens from them. To write one, subclass ``Application``, and in ``start``,
5
+ set its ``menus`` and open its first windows::
6
+
7
+ class Hello(Application):
8
+ name = "Hello"
9
+
10
+ def start(self) -> None:
11
+ self.menus = [Menu("&File", [MenuItem("E&xit", self.exit)])]
12
+ self.open(Window("Hello", Rect(2, 2, 6, 30), ["Hello, world"],
13
+ closable=True))
14
+
15
+ if __name__ == "__main__":
16
+ raise SystemExit(Hello().run())
17
+
18
+ While it is the active application, its ``menus`` make up the menu bar,
19
+ together with a Window menu that Dasha Framework adds. It runs until it quits
20
+ (typically through File > Exit), not until its windows are closed. With no
21
+ windows open, its menu bar stays, with the items that need a window
22
+ (``enabled=self.has_window``) greyed out.
23
+
24
+ ``Hello().run()`` runs the application on its own, on a desktop of its own
25
+ that closes when the application ends. On a Dasha Desktop, the same
26
+ class is started with ``manager.launch(Hello)``, or from the Applications
27
+ menu once it has been registered (``manager.register``).
28
+ """
29
+
30
+ import importlib
31
+ import os
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import TYPE_CHECKING
35
+
36
+ from dasha.help import HelpBook, HelpWindow, help_topic_of, open_help
37
+ from dasha.menu import Menu
38
+ from dasha.printing import say
39
+ from dasha.protocol import ADDRESS_VARIABLE
40
+ from dasha.window import Window
41
+
42
+ if TYPE_CHECKING:
43
+ from dasha.manager import PresentationManager
44
+ from dasha.shortcuts import Shortcuts
45
+ from dasha.terminal import Terminal
46
+
47
+
48
+ class Application:
49
+ """An application on the desktop, which owns its menus and windows and
50
+ decides what happens to them."""
51
+
52
+ name: str = "Application"
53
+ """The name of the application, as the Applications menu and messages
54
+ show it."""
55
+ single_instance: bool = False
56
+ """Whether only one copy of the application can run at a time. If so,
57
+ launching it again switches to the running copy instead."""
58
+ help_folder: str | Path | None = None
59
+ """The folder of the application's help pages, ``.md`` files with
60
+ ``index.md`` as the default page (see ``dasha.help``). An application
61
+ has no help by default, and F1 then does nothing."""
62
+ is_remote: bool = False
63
+ """Whether this stands for an application running in another process
64
+ (``dasha.remote``)."""
65
+ log_folder: Path | None = None
66
+ """Where ``run`` keeps the log of anything that goes wrong while the
67
+ application runs on its own. By default, where the system keeps
68
+ programs' logs, in a folder named after the application
69
+ (``dasha.logs.app_log_folder``). On the desktop, the desktop's own log is
70
+ used instead."""
71
+
72
+ def __init__(self) -> None:
73
+ self.manager: "PresentationManager | None" = None
74
+ """The presentation manager it runs on, once launched."""
75
+ self.windows: list[Window] = []
76
+ """Its windows, in the order they were opened (minimised ones too)."""
77
+ self.menus: list[Menu] = []
78
+ """Its menu bar, while it is the active application. Dasha Framework adds
79
+ a Window menu after them."""
80
+ self.is_running = False
81
+ self._help_book: HelpBook | None = None
82
+ self._help_known = False
83
+ self._help_window: HelpWindow | None = None
84
+
85
+ def start(self) -> None:
86
+ """Called once the application has been launched. Set ``menus`` and
87
+ open the first windows here.
88
+
89
+ This runs before the desktop is running, so it cannot show a dialog
90
+ itself. Instead, pass a function that shows the dialog to
91
+ ``manager.call_when_running``, which calls it once the desktop is
92
+ running."""
93
+
94
+ @property
95
+ def active_window(self) -> Window | None:
96
+ """The application's window nearest the front of the desktop (and not
97
+ minimised), if it has one. This is the window its menus act on."""
98
+ manager = self.manager
99
+ if manager is None:
100
+ return None
101
+ for window in reversed(manager.windows):
102
+ if window.application is self:
103
+ return window
104
+ return None
105
+
106
+ def has_window(self) -> bool:
107
+ """Whether the application has a window showing. A method rather
108
+ than a property, unlike the other queries, so that it can be given
109
+ as it is to ``MenuItem(enabled=self.has_window)``."""
110
+ return self.active_window is not None
111
+
112
+ def has_help(self) -> bool:
113
+ """Whether the application has help: a ``help_folder`` with pages in
114
+ it. The folder is looked at once. A method rather than a property, as
115
+ ``has_window`` is, so that it can be given as it is to
116
+ ``MenuItem(enabled=self.has_help)``."""
117
+ if not self._help_known:
118
+ self._help_known = True
119
+ if self.help_folder is not None:
120
+ book = HelpBook(self.help_folder)
121
+ self._help_book = book if book.has_topics() else None
122
+ return self._help_book is not None
123
+
124
+ def show_help(self, topic: str | None = None) -> None:
125
+ """Show the application's help, if it has any, as F1 does. Without a
126
+ topic, that is the topic of whatever has the focus, or else the
127
+ index. A menu item can be given this as it is::
128
+
129
+ MenuItem("&Help", self.show_help, hint("help"), enabled=self.has_help)
130
+
131
+ See ``dasha.help``."""
132
+ manager = self.manager
133
+ if manager is None or not self.has_help():
134
+ return
135
+ assert self._help_book is not None
136
+ if topic is None:
137
+ topic = help_topic_of(manager.answering_dialog or self.active_window)
138
+ self._help_window = open_help(
139
+ manager,
140
+ self._help_book,
141
+ f"{self.name} Help",
142
+ topic,
143
+ window=self._help_window,
144
+ open_window=self.open,
145
+ )
146
+
147
+ def open(self, window: Window) -> Window:
148
+ """Show a window belonging to this application, in front of the
149
+ others."""
150
+ if self.manager is None:
151
+ raise RuntimeError("an application opens windows once it is launched")
152
+ window.application = self
153
+ self.windows.append(window)
154
+ self.manager.add(window)
155
+ return window
156
+
157
+ def close(self, window: Window) -> None:
158
+ """Close one of the application's windows, as the user would (the
159
+ window's ``request_close`` may keep it open)."""
160
+ if self.manager is not None:
161
+ self.manager.close(window)
162
+
163
+ def window_closed(self, window: Window) -> None:
164
+ """Called by the manager when one of the application's windows has
165
+ closed. The application carries on running until it quits."""
166
+ if window in self.windows:
167
+ self.windows.remove(window)
168
+
169
+ def set_theme(self, name: str | Path) -> bool:
170
+ """Change every colour on the screen to a theme's, as the system
171
+ menu's Themes does. The theme can be a built-in one (``"default"``,
172
+ ``"dark"`` or ``"monochrome"``), one in ``~/.dasha/themes`` given
173
+ by name, or the theme file at a path. For an application running on
174
+ its own, its desktop changes at once. On the Dasha Desktop, the
175
+ desktop is asked to change, and does so if this is the application
176
+ the user is working in. Returns whether the theme was changed (or
177
+ the change was requested), and ``False`` before the application has
178
+ been launched. See ``PresentationManager.set_theme``."""
179
+ if self.manager is None:
180
+ return False
181
+ return self.manager.set_theme(name)
182
+
183
+ def shortcuts_changed(self) -> None:
184
+ """Called when the keyboard shortcuts change while the application
185
+ runs (from Settings..., say): ``manager.shortcuts`` holds the new
186
+ ones. Menu items keep the key hints (``shortcut``) they were made
187
+ with, so an application that shows hints can make its menus again
188
+ here. Does nothing by default."""
189
+
190
+ def can_close(self) -> bool:
191
+ """Called before the application ends (``exit``) or the desktop shuts
192
+ down. Return ``False`` to keep running (after offering to save work,
193
+ for example)."""
194
+ return True
195
+
196
+ def exit(self) -> None:
197
+ """End the application if ``can_close`` agrees. This is what
198
+ File > Exit does."""
199
+ if self.can_close():
200
+ self.quit()
201
+
202
+ def quit(self) -> None:
203
+ """End the application immediately, taking its windows off the
204
+ desktop."""
205
+ if not self.is_running:
206
+ return
207
+ self.is_running = False
208
+ manager = self.manager
209
+ for window in list(self.windows):
210
+ self.windows.remove(window)
211
+ if manager is not None and window.manager is manager:
212
+ manager.remove(window)
213
+ if manager is not None:
214
+ manager.application_ended(self)
215
+
216
+ def run(
217
+ self,
218
+ terminal: "Terminal | None" = None,
219
+ *,
220
+ shortcuts: "Shortcuts | None" = None,
221
+ ) -> int:
222
+ """Run the application, and return a process exit code.
223
+
224
+ When a Dasha Desktop started this process (and set
225
+ ``DASHA_ADDRESS``), the application runs on that desktop.
226
+ Otherwise, it runs on its own on a desktop of its own that closes
227
+ when the application ends, in the real terminal unless another
228
+ terminal is given. That desktop has no system menu (``≡``), and Exit
229
+ asks whether to close the application. It has the terminal's size
230
+ before ``start`` is called, so ``start`` can fit windows to the
231
+ screen (``manager.workspace``), and the Monochrome theme if
232
+ ``NO_COLOR`` is set (https://no-color.org). In the real terminal, it
233
+ has the theme the desktop would (``use_starting_theme``), and is
234
+ animated as the desktop is, unless animations were last turned
235
+ off, and it fails softly as the desktop does (an unexpected error
236
+ is logged and reported, and it carries on: see
237
+ ``dasha.recovery``)."""
238
+ if terminal is None and os.environ.get(ADDRESS_VARIABLE):
239
+ # By name: the client imports the manager, which imports this.
240
+ client = importlib.import_module("dasha.client")
241
+ return int(client.run_hosted(self))
242
+ # Imported here: the manager imports this module.
243
+ # pylint: disable-next=import-outside-toplevel
244
+ from dasha.manager import PresentationManager
245
+
246
+ manager = PresentationManager(shortcuts=shortcuts)
247
+ # Just this application: no system menu, and leaving closes it.
248
+ manager.stand_alone(self.name)
249
+ if self.log_folder is not None:
250
+ manager.error_log_folder = Path(self.log_folder)
251
+ given = terminal is not None
252
+ # Before ``start``, which can change it.
253
+ manager.use_starting_theme(saved=not given)
254
+ if terminal is None:
255
+ # pylint: disable-next=import-outside-toplevel
256
+ from dasha.terminal import Terminal
257
+
258
+ terminal = Terminal()
259
+ # The screen's size from the start, so that ``start`` can size its
260
+ # windows to fit (``manager.workspace``), as on the desktop.
261
+ manager.handle_resize(*terminal.size())
262
+ manager.launch(self)
263
+ if not self.is_running:
264
+ return 0 # it ended as it started
265
+ if given:
266
+ manager.run(terminal)
267
+ return 0
268
+ manager.use_saved_animations() # animated as the desktop is
269
+ manager.use_saved_escape_timeout() # and waiting for keys as it does
270
+ manager.survive_errors = True # fail softly, as the desktop does
271
+ with terminal as real:
272
+ manager.run(real)
273
+ if manager.recovery is not None: # said once the screen is back
274
+ summary = manager.recovery.summary(manager.stopped_by_errors)
275
+ say(f"{self.name}: {summary}", file=sys.stderr)
276
+ return 1 if manager.stopped_by_errors else 0
dasha/border.py ADDED
@@ -0,0 +1,34 @@
1
+ """Frame characters for windows, menus and other boxes."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class Border:
8
+ """The six characters that draw a window frame."""
9
+
10
+ top_left: str
11
+ top_right: str
12
+ bottom_left: str
13
+ bottom_right: str
14
+ horizontal: str
15
+ vertical: str
16
+
17
+
18
+ SINGLE = Border(
19
+ "\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}",
20
+ "\N{BOX DRAWINGS LIGHT DOWN AND LEFT}",
21
+ "\N{BOX DRAWINGS LIGHT UP AND RIGHT}",
22
+ "\N{BOX DRAWINGS LIGHT UP AND LEFT}",
23
+ "\N{BOX DRAWINGS LIGHT HORIZONTAL}",
24
+ "\N{BOX DRAWINGS LIGHT VERTICAL}",
25
+ )
26
+
27
+ DOUBLE = Border(
28
+ "\N{BOX DRAWINGS DOUBLE DOWN AND RIGHT}",
29
+ "\N{BOX DRAWINGS DOUBLE DOWN AND LEFT}",
30
+ "\N{BOX DRAWINGS DOUBLE UP AND RIGHT}",
31
+ "\N{BOX DRAWINGS DOUBLE UP AND LEFT}",
32
+ "\N{BOX DRAWINGS DOUBLE HORIZONTAL}",
33
+ "\N{BOX DRAWINGS DOUBLE VERTICAL}",
34
+ )
dasha/canvas.py ADDED
@@ -0,0 +1,331 @@
1
+ """An off-screen grid of styled cells, on which each frame of the screen is
2
+ composed.
3
+
4
+ Everything on the screen (the desktop, windows, menus and the status bar) is
5
+ painted onto a ``Canvas``, from back to front. The finished canvas is then
6
+ compared with the one currently on screen, and only the cells that have
7
+ changed are sent to the terminal. This keeps redrawing fast and free of
8
+ flicker, even over SSH.
9
+
10
+ Control characters never reach the terminal, where they could act as
11
+ commands (for example, from a file whose name contains an escape sequence):
12
+ ``render`` shows them as code page 437 pictures instead (``CONTROL_GLYPHS``).
13
+ Nor do characters that would not take up exactly one cell, or that cannot be
14
+ written at all; see ``shown``.
15
+ """
16
+
17
+ import unicodedata
18
+ from collections.abc import Iterator
19
+ from contextlib import contextmanager
20
+ from dataclasses import dataclass
21
+
22
+ from dasha.style import DEFAULT, Style
23
+ from dasha.terminal import ansi
24
+
25
+ type Cell = tuple[str, Style]
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Rect:
30
+ """A rectangle of cells. ``row`` and ``column`` are 0-based."""
31
+
32
+ row: int
33
+ column: int
34
+ height: int
35
+ width: int
36
+
37
+ @property
38
+ def bottom(self) -> int:
39
+ """The row just below the rectangle."""
40
+ return self.row + self.height
41
+
42
+ @property
43
+ def right(self) -> int:
44
+ """The column just right of the rectangle."""
45
+ return self.column + self.width
46
+
47
+ @property
48
+ def is_empty(self) -> bool:
49
+ """Whether the rectangle covers no cells."""
50
+ return self.height <= 0 or self.width <= 0
51
+
52
+ def contains(self, row: int, column: int) -> bool:
53
+ """Whether the cell at ``row``, ``column`` is inside the rectangle."""
54
+ return self.row <= row < self.bottom and self.column <= column < self.right
55
+
56
+ def intersect(self, other: "Rect") -> "Rect":
57
+ """The overlap of two rectangles (possibly empty)."""
58
+ row = max(self.row, other.row)
59
+ column = max(self.column, other.column)
60
+ return Rect(
61
+ row,
62
+ column,
63
+ max(0, min(self.bottom, other.bottom) - row),
64
+ max(0, min(self.right, other.right) - column),
65
+ )
66
+
67
+ def inset(self, amount: int = 1) -> "Rect":
68
+ """The rectangle shrunk by ``amount`` cells on every side."""
69
+ return Rect(
70
+ self.row + amount,
71
+ self.column + amount,
72
+ max(0, self.height - 2 * amount),
73
+ max(0, self.width - 2 * amount),
74
+ )
75
+
76
+
77
+ SHADOW_BLANKS = frozenset(
78
+ "\N{LOWER HALF BLOCK}\N{UPPER HALF BLOCK}\N{FULL BLOCK}"
79
+ "\N{LEFT HALF BLOCK}\N{RIGHT HALF BLOCK}"
80
+ )
81
+ """Characters a drop shadow replaces with a space: ▄ ▀ █ ▌ ▐."""
82
+
83
+ _C0_GLYPHS = (
84
+ " \N{WHITE SMILING FACE}\N{BLACK SMILING FACE}\N{BLACK HEART SUIT}"
85
+ "\N{BLACK DIAMOND SUIT}\N{BLACK CLUB SUIT}\N{BLACK SPADE SUIT}\N{BULLET}"
86
+ "\N{INVERSE BULLET}\N{WHITE CIRCLE}\N{INVERSE WHITE CIRCLE}\N{MALE SIGN}"
87
+ "\N{FEMALE SIGN}\N{EIGHTH NOTE}\N{BEAMED EIGHTH NOTES}\N{WHITE SUN WITH RAYS}"
88
+ "\N{BLACK RIGHT-POINTING POINTER}\N{BLACK LEFT-POINTING POINTER}"
89
+ "\N{UP DOWN ARROW}\N{DOUBLE EXCLAMATION MARK}\N{PILCROW SIGN}\N{SECTION SIGN}"
90
+ "\N{BLACK RECTANGLE}\N{UP DOWN ARROW WITH BASE}\N{UPWARDS ARROW}"
91
+ "\N{DOWNWARDS ARROW}\N{RIGHTWARDS ARROW}\N{LEFTWARDS ARROW}\N{RIGHT ANGLE}"
92
+ "\N{LEFT RIGHT ARROW}\N{BLACK UP-POINTING TRIANGLE}"
93
+ "\N{BLACK DOWN-POINTING TRIANGLE}"
94
+ )
95
+ """Code page 437's pictures for the C0 control characters, 0x00 to 0x1F."""
96
+
97
+ CONTROL_GLYPHS: dict[str, str] = {
98
+ **{chr(code): glyph for code, glyph in enumerate(_C0_GLYPHS)},
99
+ "\x7f": "\N{HOUSE}",
100
+ **{chr(code): "?" for code in range(0x80, 0xA0)},
101
+ }
102
+ """What ``render`` sends in place of each control character, which the
103
+ terminal could otherwise take as a command or part of one. C0 controls are
104
+ sent as their code page 437 pictures (escape as ←, bell as •), delete as ⌂,
105
+ and C1 controls as ``?``. The canvas itself keeps the original character."""
106
+
107
+ UNSHOWABLE = "?"
108
+ """What ``shown`` draws for a character that cannot take up exactly one
109
+ cell."""
110
+
111
+ _shown_cache: dict[str, str] = {}
112
+
113
+
114
+ def shown(char: str) -> str:
115
+ """What the terminal is sent for a cell holding ``char``: either the
116
+ character itself, or a replacement that is safe to send and takes up
117
+ exactly one column, as every cell must for the rows to line up.
118
+
119
+ - Control characters are replaced by their ``CONTROL_GLYPHS``.
120
+ - Surrogates (such as ``"\\udcff"``, which Python produces for a file
121
+ name that is not valid UTF-8, and which JSON may contain) cannot be
122
+ encoded at all, so they become ``UNSHOWABLE``.
123
+ - Wide characters (such as ``"\\u5bec"``, and most emoji) take up two
124
+ columns, and zero-width characters (combining accents, joiners and
125
+ direction marks) take up none and could make text read in a different
126
+ order, so they also become ``UNSHOWABLE``.
127
+
128
+ Every code page 437 character is shown as it is."""
129
+ if len(char) != 1: # a cell holds one character; anything else is not one
130
+ return UNSHOWABLE
131
+ if char < "̀" and char not in CONTROL_GLYPHS:
132
+ return char # the common case: ASCII and Latin-1, nothing to look up
133
+ known = _shown_cache.get(char)
134
+ if known is None:
135
+ known = CONTROL_GLYPHS.get(char) or _looked_up(char)
136
+ if len(_shown_cache) < 4096:
137
+ _shown_cache[char] = known
138
+ return known
139
+
140
+
141
+ def _looked_up(char: str) -> str:
142
+ if "\ud800" <= char <= "\udfff":
143
+ return UNSHOWABLE
144
+ if unicodedata.east_asian_width(char) in ("W", "F"):
145
+ return UNSHOWABLE
146
+ if unicodedata.category(char) in ("Mn", "Me", "Cf", "Cs", "Co", "Cn"):
147
+ return UNSHOWABLE
148
+ return char
149
+
150
+
151
+ def shadow_rects(rect: Rect, width: int = 2, height: int = 1) -> tuple[Rect, Rect]:
152
+ """Where the drop shadow falls for something occupying ``rect``.
153
+
154
+ The shadow is a strip ``width`` columns wide down the right side,
155
+ starting ``height`` rows below the top, and a strip ``height`` rows high
156
+ along the bottom, starting ``width`` columns in, so that the box seems to
157
+ float above the screen. Two columns by one row looks square in most
158
+ terminal fonts.
159
+ """
160
+ return (
161
+ Rect(rect.row + height, rect.right, rect.height, width),
162
+ Rect(rect.bottom, rect.column + width, height, rect.width - width),
163
+ )
164
+
165
+
166
+ class Canvas:
167
+ """A grid of ``width`` by ``height`` cells, each holding a character and
168
+ a style."""
169
+
170
+ def __init__(self, width: int, height: int) -> None:
171
+ self.width = width
172
+ self.height = height
173
+ self._rows: list[list[Cell]] = [[(" ", DEFAULT)] * width for _ in range(height)]
174
+ self._clip: Rect | None = None
175
+ self.cursor: tuple[int, int] | None = None
176
+ """Where the terminal's cursor is shown (row, column), or ``None`` to
177
+ hide it. A focused text box puts the cursor where typing will go."""
178
+
179
+ @property
180
+ def bounds(self) -> Rect:
181
+ """The rectangle covering the whole canvas."""
182
+ return Rect(0, 0, self.height, self.width)
183
+
184
+ @contextmanager
185
+ def clipped(self, rect: Rect) -> Iterator[None]:
186
+ """Keep all drawing inside ``rect`` (and inside any outer clipping
187
+ area) until the ``with`` block ends.
188
+
189
+ This is used to draw a window's scrolled contents: the widgets draw
190
+ as usual, at positions that may lie outside the window, and only the
191
+ part inside the frame reaches the canvas. Clipping areas can be
192
+ nested.
193
+ """
194
+ outer = self._clip
195
+ self._clip = rect if outer is None else outer.intersect(rect)
196
+ try:
197
+ yield
198
+ finally:
199
+ self._clip = outer
200
+
201
+ def _area(self, rect: Rect | None = None) -> Rect:
202
+ """The part of the canvas drawing may touch: the canvas, within the
203
+ current clip, within ``rect``."""
204
+ area = self.bounds if self._clip is None else self.bounds.intersect(self._clip)
205
+ return area if rect is None else area.intersect(rect)
206
+
207
+ def place_cursor(self, row: int, column: int) -> None:
208
+ """Show the cursor at a position, if that position is inside the
209
+ canvas and the current clipping area; otherwise, leave it hidden."""
210
+ if self._area().contains(row, column):
211
+ self.cursor = (row, column)
212
+
213
+ def cell(self, row: int, column: int) -> Cell:
214
+ """Return the character and style at a position."""
215
+ return self._rows[row][column]
216
+
217
+ def text(self, row: int) -> str:
218
+ """Return the characters of one row, without styles."""
219
+ return "".join(char for char, _ in self._rows[row])
220
+
221
+ def write(
222
+ self,
223
+ row: int,
224
+ column: int,
225
+ text: str,
226
+ style: Style = DEFAULT,
227
+ clip: Rect | None = None,
228
+ ) -> None:
229
+ """Write text at a position, one character to a cell, clipped to
230
+ ``clip`` and to the canvas."""
231
+ area = self._area(clip)
232
+ if not area.row <= row < area.bottom:
233
+ return
234
+ cells = self._rows[row]
235
+ for offset, char in enumerate(text):
236
+ col = column + offset
237
+ if col >= area.right:
238
+ break
239
+ if col >= area.column:
240
+ cells[col] = (char, style)
241
+
242
+ def fill(self, rect: Rect, char: str = " ", style: Style = DEFAULT) -> None:
243
+ """Fill a rectangle (clipped to the canvas) with a single character."""
244
+ area = self._area(rect)
245
+ for row in range(area.row, area.bottom):
246
+ self._rows[row][area.column : area.right] = [(char, style)] * area.width
247
+
248
+ def copy_from(
249
+ self, source: "Canvas", row: int, column: int, clip: Rect | None = None
250
+ ) -> None:
251
+ """Copy every cell of another canvas onto this one, with its top-left
252
+ cell at ``row``, ``column``, clipped to ``clip`` and to this
253
+ canvas."""
254
+ area = self._area(clip).intersect(
255
+ Rect(row, column, source.height, source.width)
256
+ )
257
+ for target in range(area.row, area.bottom):
258
+ cells = source._rows[target - row] # pylint: disable=protected-access
259
+ self._rows[target][area.column : area.right] = cells[
260
+ area.column - column : area.right - column
261
+ ]
262
+
263
+ def restyle(self, rect: Rect, style: Style) -> None:
264
+ """Give every cell in a rectangle (clipped) a new style, keeping its
265
+ character. Shadows use this to darken whatever lies beneath them."""
266
+ area = self._area(rect)
267
+ for row in range(area.row, area.bottom):
268
+ cells = self._rows[row]
269
+ for column in range(area.column, area.right):
270
+ cells[column] = (cells[column][0], style)
271
+
272
+ def cast_shadow(
273
+ self, rect: Rect, style: Style, width: int = 2, height: int = 1
274
+ ) -> None:
275
+ """Darken the area where ``rect`` casts its drop shadow, keeping the
276
+ characters beneath.
277
+
278
+ Block characters (``SHADOW_BLANKS``) become spaces instead, because
279
+ redrawn dark grey on black they would look like bright patches (as
280
+ button shadows did under a window's shadow).
281
+ """
282
+ area = self._area() # the canvas, within any clip
283
+ for shadow in shadow_rects(rect, width, height):
284
+ shadow = area.intersect(shadow)
285
+ for row in range(shadow.row, shadow.bottom):
286
+ cells = self._rows[row]
287
+ for column in range(shadow.column, shadow.right):
288
+ char = cells[column][0]
289
+ cells[column] = (" " if char in SHADOW_BLANKS else char, style)
290
+
291
+ def render(self, previous: "Canvas | None" = None) -> str:
292
+ """Return the terminal output that changes the screen from
293
+ ``previous`` to this canvas.
294
+
295
+ Without ``previous`` (or if it is a different size), every cell is
296
+ drawn. Each cell is sent as ``shown`` translates it: control
297
+ characters as ``CONTROL_GLYPHS``, and characters that cannot take up
298
+ exactly one cell as ``UNSHOWABLE``, never as they are. The cursor
299
+ stays hidden until a canvas has a ``cursor``; the output then ends by
300
+ moving the cursor there and showing it.
301
+ """
302
+ old_rows: list[list[Cell]] | None = None
303
+ if previous is not None and previous.width == self.width:
304
+ if previous.height == self.height:
305
+ old_rows = previous._rows # pylint: disable=protected-access
306
+ parts: list[str] = []
307
+ current_style: Style | None = None
308
+ for row, cells in enumerate(self._rows):
309
+ old_cells: list[Cell] | None = None if old_rows is None else old_rows[row]
310
+ cursor: int | None = None # column the cursor is known to be at
311
+ for column, (char, style) in enumerate(cells):
312
+ if old_cells is not None and old_cells[column] == (char, style):
313
+ continue
314
+ if cursor != column:
315
+ parts.append(ansi.move_to(row, column))
316
+ if style != current_style:
317
+ parts.append(style.sgr())
318
+ current_style = style
319
+ parts.append(shown(char))
320
+ cursor = column + 1
321
+ if current_style is not None:
322
+ parts.append(ansi.RESET_ATTRIBUTES)
323
+ old_cursor = None if previous is None else previous.cursor
324
+ if self.cursor is not None:
325
+ if parts or self.cursor != old_cursor: # drawing moves the cursor
326
+ parts.append(ansi.move_to(*self.cursor))
327
+ if old_cursor is None:
328
+ parts.append(ansi.SHOW_CURSOR)
329
+ elif old_cursor is not None:
330
+ parts.append(ansi.HIDE_CURSOR)
331
+ return "".join(parts)