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/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Dasha Framework - a text-mode desktop and application framework.
2
+
3
+ A text-mode desktop and application framework for local and SSH terminals,
4
+ built entirely on the Python standard library.
5
+ """
6
+
7
+ __all__ = ["__version__"]
8
+
9
+ __version__ = "0.0.1"
dasha/__main__.py ADDED
@@ -0,0 +1,534 @@
1
+ """Command-line entry point, used by ``python -m dasha`` and the ``dasha``
2
+ and ``dasha-desktop`` scripts.
3
+
4
+ ``dasha`` needs to be told what to run: ``dasha desktop`` for the desktop
5
+ (with any applications named after it started on it), or applications by
6
+ id (``dasha notepad``) to run on their own. ``dasha-desktop`` is ``dasha
7
+ desktop``: ``dasha-desktop notepad`` starts the desktop with Notepad on it."""
8
+
9
+ import argparse
10
+ import os
11
+ import sys
12
+ from collections.abc import Sequence
13
+ from pathlib import Path
14
+
15
+ from dasha import __version__, keytest, shell
16
+ from dasha import style, theme
17
+ from dasha import install, registry
18
+ from dasha.config import write_atomically
19
+ from dasha.manager import PresentationManager
20
+ from dasha.printing import say
21
+ from dasha.registry import AppEntry, ManifestError
22
+ from dasha.shortcuts import DEFAULT_PATH, Shortcuts, ShortcutsError
23
+ from dasha.terminal import Terminal
24
+
25
+ DESKTOP = registry.DESKTOP_ID
26
+ """What starts the desktop: ``dasha desktop``, followed by any applications
27
+ to start on it. No application can have it as its id."""
28
+
29
+
30
+ def _desktop( # pylint: disable=too-many-arguments
31
+ shortcuts: Shortcuts | None,
32
+ names: Sequence[str],
33
+ *,
34
+ processes: bool = True,
35
+ entries: dict[str, AppEntry] | None = None,
36
+ theme_name: str | None = "default",
37
+ alone: bool = False,
38
+ animations: bool = True,
39
+ paths: tuple[Path, Path] | None = None,
40
+ colour_depth: str = "auto",
41
+ show_mouse: bool = False,
42
+ escape_timeout: int = registry.ESCAPE_TIMEOUT,
43
+ ) -> PresentationManager:
44
+ """An empty desktop offering the applications Dasha Framework knows (the
45
+ installed ones, unless given ``entries``), with the named
46
+ ones started: each in a process of its own, unless ``processes`` is
47
+ false. ``theme_name`` is the theme it starts with (``None``: the colours
48
+ file's colours), and a theme chosen later is remembered; so is turning
49
+ ``animations`` (on, unless told otherwise) on or off. ``colour_depth``
50
+ is how it draws colours (``style.COLOUR_DEPTHS``), and
51
+ ``show_mouse`` whether it inverts the cell under the mouse, which is
52
+ remembered when it is turned on or off.
53
+
54
+ ``alone`` runs just the named applications, as each would run on its
55
+ own (``PresentationManager.stand_alone``): no system menu, and it ends
56
+ when they do. ``dasha notepad`` is so the same as running Notepad's
57
+ script, and ``dasha desktop notepad`` (or ``dasha-desktop notepad``) the
58
+ desktop with Notepad on it.
59
+
60
+ ``paths`` are the shortcuts file and the colours file, to which
61
+ Settings... saves (by default, ``~/.dasha/shortcuts.json`` and
62
+ ``~/.dasha/colours.json``)."""
63
+ if entries is None:
64
+ entries, _ = install.known_applications()
65
+ manager = PresentationManager(shortcuts=shortcuts)
66
+ manager.use_processes = processes
67
+ manager.theme_name = theme_name
68
+ manager.remember_theme = True
69
+ manager.animations = animations
70
+ manager.remember_animations = True
71
+ manager.set_colour_depth(colour_depth)
72
+ manager.show_mouse = show_mouse
73
+ manager.remember_show_mouse = True
74
+ manager.escape_timeout = escape_timeout / 1000
75
+ if paths is not None:
76
+ manager.shortcuts_path, manager.colours_path = paths
77
+ manager.register(entries.values())
78
+ if alone:
79
+ manager.stand_alone(_listed([entries[name].name for name in names]))
80
+ else:
81
+ manager.use_own_help()
82
+ for name in names:
83
+ manager.start(entries[name])
84
+ return manager
85
+
86
+
87
+ def _listed(names: Sequence[str]) -> str:
88
+ """Names as a sentence lists them: "Notepad", "Notepad and Demo",
89
+ "Notepad, Demo and Clock"."""
90
+ if len(names) < 2:
91
+ return "".join(names)
92
+ return f"{', '.join(names[:-1])} and {names[-1]}"
93
+
94
+
95
+ def _find(name: str, entries: dict[str, AppEntry]) -> list[str]:
96
+ """The ids of the applications that ``name``, given on the command line,
97
+ means: the one with that id; failing that, the one whose id it is in
98
+ another case (``NOTEPAD``); failing that, those that are called it,
99
+ ignoring case (``git``, for an application ``dasha-github`` called
100
+ "Git"). More than one is a name too many applications have; none, a
101
+ name no application has."""
102
+ if name in entries:
103
+ return [name]
104
+ wanted = name.casefold()
105
+ by_id = [app_id for app_id in entries if app_id.casefold() == wanted]
106
+ if by_id:
107
+ return by_id
108
+ return [
109
+ app_id for app_id, entry in entries.items() if entry.name.casefold() == wanted
110
+ ]
111
+
112
+
113
+ def _startup(
114
+ names: Sequence[str], *, desktop: bool = False
115
+ ) -> tuple[dict[str, AppEntry], list[str]] | None:
116
+ """The applications Dasha Framework knows, and the ids of those to start: the
117
+ ones named, by id or by name (``_find``), and, for the ``desktop``,
118
+ first those ``autostart`` in the settings (an application both named
119
+ and autostart's is started once). Problems with manifests are reported
120
+ and those left out; an unknown name, one that more than one application
121
+ has, or a settings file that cannot be read, is reported and gives
122
+ ``None``; as is starting inside the command prompt of a desktop already
123
+ running (see ``dasha.shell``)."""
124
+ if os.environ.get(shell.SUSPENDED_VARIABLE):
125
+ say(
126
+ "dasha: Dasha Framework is already running in this terminal; "
127
+ "type exit to return to it",
128
+ file=sys.stderr,
129
+ )
130
+ return None
131
+ entries, problems = install.known_applications()
132
+ for problem in problems:
133
+ say(f"dasha: {problem} (left out)", file=sys.stderr)
134
+ try:
135
+ autostart = registry.read_autostart(registry.SETTINGS_PATH) if desktop else []
136
+ except ManifestError as error:
137
+ say(f"dasha: {error}", file=sys.stderr)
138
+ return None
139
+ unknown = [name for name in autostart if name not in entries]
140
+ ids: list[str] = []
141
+ for name in names:
142
+ found = _find(name, entries)
143
+ if len(found) > 1:
144
+ say(
145
+ f'dasha: more than one application is called "{name}" '
146
+ f"({', '.join(found)}); name one by its id",
147
+ file=sys.stderr,
148
+ )
149
+ return None
150
+ if found:
151
+ ids.append(found[0])
152
+ else:
153
+ unknown.append(name)
154
+ if unknown:
155
+ known = ", ".join(entries) or "none are installed"
156
+ say(
157
+ f"dasha: no application called {', '.join(unknown)} "
158
+ f"(there are: {known}; see dasha list-apps)",
159
+ file=sys.stderr,
160
+ )
161
+ return None
162
+ return entries, [*autostart, *(app_id for app_id in ids if app_id not in autostart)]
163
+
164
+
165
+ def _parse_arguments(
166
+ argv: Sequence[str] | None, *, desktop: bool = False
167
+ ) -> argparse.Namespace:
168
+ """The command line, as ``dasha`` (or, if ``desktop``, as ``dasha-desktop``)
169
+ takes it. ``apps`` are the applications to start, and ``desktop``
170
+ whether to start them on the desktop. With nothing to run, the usage is
171
+ shown and the program ends (``SystemExit``), as for any mistake in the
172
+ arguments."""
173
+ parser = argparse.ArgumentParser(
174
+ prog="dasha-desktop" if desktop else "dasha",
175
+ description="Dasha Framework - a text-mode desktop and application framework.",
176
+ )
177
+ parser.add_argument(
178
+ "-v", "--version", action="version", version=f"Dasha Framework {__version__}"
179
+ )
180
+ parser.add_argument(
181
+ "-s",
182
+ "--shortcuts",
183
+ type=Path,
184
+ metavar="FILE",
185
+ help=f"keyboard shortcuts file (default: {DEFAULT_PATH})",
186
+ )
187
+ parser.add_argument(
188
+ "--init-shortcuts",
189
+ action="store_true",
190
+ help="write the default shortcuts to the shortcuts file, ready to edit",
191
+ )
192
+ parser.add_argument(
193
+ "-c",
194
+ "--colours",
195
+ type=Path,
196
+ metavar="FILE",
197
+ help=f"colours file (default: {theme.DEFAULT_PATH})",
198
+ )
199
+ parser.add_argument(
200
+ "--init-colours",
201
+ action="store_true",
202
+ help="write the default colours to the colours file, ready to edit",
203
+ )
204
+ parser.add_argument(
205
+ "--init-theme",
206
+ metavar="NAME",
207
+ help=f"write a new theme, NAME, to edit: a file in {theme.THEMES_FOLDER}, "
208
+ "offered by the system menu's Themes",
209
+ )
210
+ parser.add_argument(
211
+ "--monochrome",
212
+ action="store_true",
213
+ help="use no colours, only bold, underline and reverse video "
214
+ "(also chosen by the NO_COLOR environment variable)",
215
+ )
216
+ parser.add_argument(
217
+ "-d",
218
+ "--colour-depth",
219
+ choices=style.COLOUR_DEPTHS,
220
+ help="draw RGB colours as they are (24bit), as the nearest of 256 "
221
+ "colours (256), every colour as the nearest of the 16 standard "
222
+ "colours (16), or as the terminal seems to allow (auto, the default); "
223
+ "remembered for next time",
224
+ )
225
+ parser.add_argument(
226
+ "-m",
227
+ "--show-mouse",
228
+ action="store_true",
229
+ help="show where the mouse is by inverting the cell under it, for "
230
+ "terminals that show no pointer; remembered for next time (Alt+` "
231
+ "turns it on and off)",
232
+ )
233
+ parser.add_argument(
234
+ "-k",
235
+ "--key-test",
236
+ action="store_true",
237
+ help="show the name of each key as you press it (Ctrl+C to finish)",
238
+ )
239
+ if desktop:
240
+ apps_help = (
241
+ "applications, by id or name, to start on the desktop, after those "
242
+ "that start with it (dasha list-apps lists them)"
243
+ )
244
+ else:
245
+ apps_help = (
246
+ f"{DESKTOP} for the desktop, followed by any applications to start "
247
+ "on it; or applications, by id or name, to run on their own with no "
248
+ "desktop around them (dasha list-apps lists them)"
249
+ )
250
+ parser.add_argument("apps", nargs="*", metavar="APP", help=apps_help)
251
+ parser.epilog = (
252
+ "The desktop: dasha desktop [APP ...], or dasha-desktop [APP ...]. "
253
+ "Applications: dasha install-app, uninstall-app and list-apps "
254
+ "(each with --help)."
255
+ )
256
+ # Intermixed, so that options may come between applications, as in
257
+ # "dasha desktop --monochrome notepad".
258
+ args = parser.parse_intermixed_args(argv)
259
+ args.desktop = desktop
260
+ if args.apps[:1] == [DESKTOP]:
261
+ args.desktop, args.apps = True, args.apps[1:]
262
+ runs_nothing = (
263
+ args.key_test
264
+ or args.init_shortcuts
265
+ or args.init_colours
266
+ or args.init_theme is not None
267
+ )
268
+ if not (args.desktop or args.apps or runs_nothing):
269
+ parser.error(
270
+ f"the following arguments are required: APP ({DESKTOP} for the "
271
+ "desktop, or an application's id or name: dasha list-apps lists them)"
272
+ )
273
+ return args
274
+
275
+
276
+ def _write_new_file(path: Path, text: str, what: str) -> int:
277
+ """Write a settings file for the user to edit, never overwriting one."""
278
+ if path.exists():
279
+ say(f"dasha: {path} already exists; not overwriting it", file=sys.stderr)
280
+ return 1
281
+ try:
282
+ path.parent.mkdir(parents=True, exist_ok=True)
283
+ write_atomically(path, text + "\n")
284
+ except OSError as error:
285
+ say(f"dasha: cannot write {path}: {error.strerror}", file=sys.stderr)
286
+ return 1
287
+ say(f"Wrote the default {what} to {path}")
288
+ return 0
289
+
290
+
291
+ def _report_problems(kind: str, path: Path, error: Exception) -> None:
292
+ """Explain why a settings file cannot be used."""
293
+ say(f"dasha: cannot use the {kind} file {path}:", file=sys.stderr)
294
+ for problem in str(error).splitlines():
295
+ say(f" - {problem}", file=sys.stderr)
296
+ say(f"Fix the file, or move it aside to use the default {kind}.", file=sys.stderr)
297
+
298
+
299
+ class _Reported(Exception):
300
+ """A settings problem, already reported to the user."""
301
+
302
+
303
+ def _saved_theme() -> tuple[theme.Theme, str] | None:
304
+ """The theme last chosen from the system menu (``theme`` in the
305
+ settings), if one is remembered. Raises ``_Reported`` once it has said
306
+ why it cannot be used."""
307
+ try:
308
+ name = registry.read_theme_setting(registry.SETTINGS_PATH)
309
+ except ManifestError as error:
310
+ say(f"dasha: {error}", file=sys.stderr)
311
+ raise _Reported from error
312
+ if name is None:
313
+ return None
314
+ try:
315
+ return theme.load_named_theme(name), name
316
+ except theme.ThemeError as error:
317
+ say(
318
+ f'dasha: cannot use the theme "{name}" named in '
319
+ f"{registry.SETTINGS_PATH}:\n - {error}\n"
320
+ "Choose another from the system menu's Themes, or take the "
321
+ "theme line out of the settings.",
322
+ file=sys.stderr,
323
+ )
324
+ raise _Reported from error
325
+
326
+
327
+ def _load_colours( # pylint: disable=too-many-return-statements
328
+ path: Path, explicit: bool, monochrome: bool
329
+ ) -> tuple[theme.Theme, str | None] | None:
330
+ """The colours to start with, and the theme's name (``None`` for the
331
+ colours file's), or ``None`` after reporting why they cannot be used.
332
+
333
+ ``--monochrome``, or a terminal with no colours, comes first, and is the
334
+ Monochrome theme exactly, as the Themes menu gives it: a colours file's
335
+ changes are left out, as they may well add colours. Then ``--colours``,
336
+ then the theme last
337
+ chosen from the system menu (``theme`` in the settings), then the
338
+ colours file, then the default theme (or ``NO_COLOR``'s monochrome)."""
339
+ if explicit and not path.exists():
340
+ say(f"dasha: colours file {path} does not exist", file=sys.stderr)
341
+ return None
342
+ if monochrome or not style.terminal_has_colours():
343
+ return theme.load_named_theme("monochrome"), "monochrome"
344
+ no_colour = bool(os.environ.get("NO_COLOR"))
345
+ try:
346
+ saved = None if explicit else _saved_theme()
347
+ except _Reported:
348
+ return None
349
+ if saved is not None:
350
+ return saved # the colours file is not needed, nor read
351
+ try:
352
+ colours = theme.load_theme(path, no_colour=no_colour)
353
+ except theme.ThemeError as error:
354
+ _report_problems("colours", path, error)
355
+ return None
356
+ if path.exists():
357
+ return colours, None
358
+ return colours, "monochrome" if no_colour else "default"
359
+
360
+
361
+ def _load_shortcuts(path: Path, explicit: bool) -> Shortcuts | None:
362
+ """Load the shortcuts file, or report why it cannot be used."""
363
+ if explicit and not path.exists():
364
+ say(f"dasha: shortcuts file {path} does not exist", file=sys.stderr)
365
+ return None
366
+ try:
367
+ return Shortcuts.load(path)
368
+ except ShortcutsError as error:
369
+ _report_problems("shortcuts", path, error)
370
+ return None
371
+
372
+
373
+ def _load_settings(
374
+ args: argparse.Namespace, shortcuts_path: Path, colours_path: Path
375
+ ) -> tuple[Shortcuts | None, tuple[theme.Theme, str | None]] | None:
376
+ """The shortcuts (not needed for the key test) and the colour theme
377
+ with its name, or ``None`` after reporting why a settings file cannot
378
+ be used."""
379
+ shortcuts = None
380
+ if not args.key_test:
381
+ shortcuts = _load_shortcuts(shortcuts_path, explicit=args.shortcuts is not None)
382
+ if shortcuts is None:
383
+ return None
384
+ colours = _load_colours(
385
+ colours_path, explicit=args.colours is not None, monochrome=args.monochrome
386
+ )
387
+ if colours is None:
388
+ return None
389
+ return shortcuts, colours
390
+
391
+
392
+ def _remember_options(args: argparse.Namespace) -> None:
393
+ """Keep ``--colour-depth`` and ``--show-mouse`` in the settings, as
394
+ Settings... does, so they need not be given every time
395
+ (``--colour-depth auto`` forgets the depth). A settings file that
396
+ cannot be written is reported, and Dasha Framework starts anyway."""
397
+ try:
398
+ if args.colour_depth is not None:
399
+ registry.save_colour_depth_setting(
400
+ args.colour_depth, registry.SETTINGS_PATH
401
+ )
402
+ if args.show_mouse:
403
+ registry.save_show_mouse_setting(True, registry.SETTINGS_PATH)
404
+ except OSError as error:
405
+ say(f"dasha: the settings could not be saved: {error}", file=sys.stderr)
406
+
407
+
408
+ def _take_the_screen(
409
+ args: argparse.Namespace,
410
+ shortcuts: Shortcuts | None,
411
+ theme_name: str | None,
412
+ paths: tuple[Path, Path],
413
+ ) -> int:
414
+ """Run the key test, or the desktop with its applications; an exit code.
415
+ What would stop it is reported before the screen is taken over.
416
+ ``paths`` are the shortcuts and colours files in use."""
417
+ startup = None if args.key_test else _startup(args.apps, desktop=args.desktop)
418
+ if startup is None and not args.key_test:
419
+ return 1
420
+ try:
421
+ animations = args.key_test or registry.read_animations_setting(
422
+ registry.SETTINGS_PATH
423
+ )
424
+ colour_depth = args.colour_depth or registry.read_colour_depth_setting(
425
+ registry.SETTINGS_PATH
426
+ )
427
+ show_mouse = args.show_mouse or registry.read_show_mouse_setting(
428
+ registry.SETTINGS_PATH
429
+ )
430
+ escape_timeout = registry.read_escape_timeout_setting(registry.SETTINGS_PATH)
431
+ except ManifestError as error:
432
+ say(f"dasha: {error}", file=sys.stderr)
433
+ return 1
434
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
435
+ say("dasha: must be run in an interactive terminal", file=sys.stderr)
436
+ return 1
437
+ _remember_options(args)
438
+ desktop: PresentationManager | None = None
439
+ try:
440
+ with Terminal() as terminal:
441
+ if startup is None:
442
+ keytest.run(terminal)
443
+ else:
444
+ entries, names = startup
445
+ desktop = _desktop(
446
+ shortcuts,
447
+ names,
448
+ entries=entries,
449
+ theme_name=theme_name,
450
+ alone=not args.desktop,
451
+ animations=animations,
452
+ paths=paths,
453
+ colour_depth=colour_depth,
454
+ show_mouse=show_mouse,
455
+ escape_timeout=escape_timeout,
456
+ )
457
+ desktop.survive_errors = True # fail softly (dasha.recovery)
458
+ desktop.run(terminal)
459
+ except OSError as error:
460
+ say(f"dasha: {error}", file=sys.stderr)
461
+ return 1
462
+ if desktop is not None:
463
+ _report_unsaid(desktop)
464
+ if _report_errors(desktop):
465
+ return 1
466
+ return 0
467
+
468
+
469
+ def _report_errors(desktop: PresentationManager) -> bool:
470
+ """Say where the log is, if anything went wrong in the desktop's own
471
+ code while it ran; returns whether it went wrong so often that the
472
+ desktop gave up."""
473
+ recovery = desktop.recovery
474
+ if recovery is None:
475
+ return False
476
+ say(f"dasha: {recovery.summary(desktop.stopped_by_errors)}", file=sys.stderr)
477
+ return desktop.stopped_by_errors
478
+
479
+
480
+ def _report_unsaid(desktop: PresentationManager) -> None:
481
+ """What the desktop had to say but ended before it could (an
482
+ application that could not start, when it was the only one): said on
483
+ the terminal instead, once the screen is given back."""
484
+ server = desktop.server
485
+ for title, message in server.notices if server is not None else []:
486
+ say(f"dasha: {title}: {' '.join(message.split())}", file=sys.stderr)
487
+
488
+
489
+ def main(argv: Sequence[str] | None = None, *, desktop: bool = False) -> int:
490
+ """Run the Dasha Framework command line (the ``dasha`` command, or, if
491
+ ``desktop``, ``dasha-desktop``) and return a process exit code."""
492
+ arguments = list(sys.argv[1:] if argv is None else argv)
493
+ if arguments and arguments[0] in install.COMMANDS:
494
+ return install.run(arguments)
495
+ args = _parse_arguments(arguments, desktop=desktop)
496
+ path: Path = args.shortcuts if args.shortcuts is not None else DEFAULT_PATH
497
+
498
+ colours_path: Path = (
499
+ args.colours if args.colours is not None else theme.DEFAULT_PATH
500
+ )
501
+
502
+ if args.init_shortcuts:
503
+ return _write_new_file(path, Shortcuts().to_json(), "shortcuts")
504
+ if args.init_colours:
505
+ return _write_new_file(
506
+ colours_path, theme.theme_to_json(theme.DEFAULT_THEME), "colours"
507
+ )
508
+ if args.init_theme is not None:
509
+ name = registry.slug(args.init_theme)
510
+ return _write_new_file(
511
+ theme.THEMES_FOLDER / f"{name}.json",
512
+ theme.theme_to_json(theme.DEFAULT_THEME),
513
+ f"colours, as the theme {name},",
514
+ )
515
+
516
+ # Load (and check) the settings before taking over the screen, so any
517
+ # problem is reported where the user can read it.
518
+ settings = _load_settings(args, path, colours_path)
519
+ if settings is None:
520
+ return 1
521
+ shortcuts, (colours, theme_name) = settings
522
+ theme.apply_theme(colours)
523
+ return _take_the_screen(args, shortcuts, theme_name, (path, colours_path))
524
+
525
+
526
+ def desktop_main(argv: Sequence[str] | None = None) -> int:
527
+ """Run the ``dasha-desktop`` command, which is ``dasha desktop``: the
528
+ desktop, with any applications named started on it. Returns a process
529
+ exit code."""
530
+ return main(argv, desktop=True)
531
+
532
+
533
+ if __name__ == "__main__":
534
+ raise SystemExit(main())
dasha/animation.py ADDED
@@ -0,0 +1,90 @@
1
+ """Animations: the intermediate frames drawn as a menu drops down from the
2
+ menu bar, or as a window moves from one position to another (see
3
+ ``PresentationManager.animations``).
4
+
5
+ A window is animated as a frame that moves, growing or shrinking, from its
6
+ old position to its new one. Throughout, it holds what was inside the window
7
+ when the animation began, exactly as it was: not laid out again or
8
+ scrolled, but cut off where the frame is smaller, and blank beyond it where
9
+ the frame is bigger.
10
+ """
11
+
12
+ from dataclasses import dataclass
13
+
14
+ from dasha.canvas import Canvas, Rect
15
+ from dasha.window import Window
16
+
17
+
18
+ def frame_parts(frames: int) -> list[float]:
19
+ """How far along each of ``frames`` intermediate frames is, from 0 (the
20
+ start) to 1 (the end), evenly spaced: ``[1/3, 2/3]`` for two frames. The
21
+ end itself is shown by the next ordinary frame."""
22
+ return [step / (frames + 1) for step in range(1, frames + 1)]
23
+
24
+
25
+ def between(start: Rect, end: Rect, part: float) -> Rect:
26
+ """The rectangle that is the fraction ``part`` (from 0 to 1) of the way
27
+ from ``start`` to ``end``, with each edge moving in a straight line. It
28
+ is never smaller than a frame's corners (two by two)."""
29
+
30
+ def along(first: int, last: int) -> int:
31
+ return round(first + (last - first) * part)
32
+
33
+ top, left = along(start.row, end.row), along(start.column, end.column)
34
+ bottom, right = along(start.bottom, end.bottom), along(start.right, end.right)
35
+ return Rect(top, left, max(2, bottom - top), max(2, right - left))
36
+
37
+
38
+ def scroll_bars_shown(window: Window) -> tuple[bool, bool]:
39
+ """Whether a window shows its (vertical, horizontal) scroll bars at its
40
+ current position and size."""
41
+ vertical, horizontal = window.scroll_bars
42
+ return vertical is not None, horizontal is not None
43
+
44
+
45
+ @dataclass
46
+ class WindowAnimation:
47
+ """A window moving from ``start`` to ``end``, as it is maximised,
48
+ minimised or restored."""
49
+
50
+ window: Window
51
+ start: Rect
52
+ end: Rect
53
+ inside: Canvas
54
+ """What was inside the window when the animation began
55
+ (``Window.render_interior``), shown throughout."""
56
+ bars: tuple[bool, bool]
57
+ """The scroll bars (vertical, horizontal) the window may show during the
58
+ animation: those it has at its full size, which is at the end (or at the
59
+ start, when minimising)."""
60
+ showing: bool = True
61
+ """Whether the window is on the screen (rather than minimised) at the
62
+ end. An animation is not drawn if its window is not, or is no longer,
63
+ in the expected state."""
64
+
65
+ @classmethod
66
+ def of(cls, window: Window) -> "WindowAnimation":
67
+ """An animation of a window from its current position, with its
68
+ current contents, ending at the same position until ``end`` is
69
+ set."""
70
+ rect = window.rect
71
+ return cls(
72
+ window, rect, rect, window.render_interior(True), scroll_bars_shown(window)
73
+ )
74
+
75
+ def to_window(self, start: Rect | None = None) -> "WindowAnimation":
76
+ """End the animation where the window is now (and start it from
77
+ ``start``, if given), showing the scroll bars the window has
78
+ there."""
79
+ if start is not None:
80
+ self.start = start
81
+ self.end = self.window.rect
82
+ self.bars = scroll_bars_shown(self.window)
83
+ self.showing = True
84
+ return self
85
+
86
+ def paint(self, canvas: Canvas, part: float) -> None:
87
+ """Draw the window the fraction ``part`` (from 0 to 1) of the way
88
+ along."""
89
+ rect = between(self.start, self.end, part)
90
+ self.window.paint_between(canvas, rect, self.inside, self.bars)