Skip to content

cmd

The command-line module of the library.

See ptg --help for more information.

AppWindow

Bases: ptg.Window

A generic application window.

It contains a header with the app's title, as well as some global settings.

Source code in pytermgui/cmd.py
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
class AppWindow(ptg.Window):
    """A generic application window.

    It contains a header with the app's title, as well as some global
    settings.
    """

    app_title: str
    """The display title of the application."""

    app_id: str
    """The short identifier used by ArgumentParser."""

    standalone: bool
    """Whether this app was launched directly from the CLI."""

    overflow = ptg.Overflow.SCROLL
    vertical_align = ptg.VerticalAlignment.TOP

    def __init__(self, args: Namespace | None = None, **attrs: Any) -> None:
        super().__init__(**attrs)

        self.standalone = bool(getattr(args, self.app_id, None))

        bottom = ptg.Container.chars["border"][-1]
        header_box = ptg.boxes.Box(
            [
                "",
                " x ",
                bottom * 3,
            ]
        )

        self._add_widget(ptg.Container(f"[ptg.title]{self.app_title}", box=header_box))
        self._add_widget("")

    def setup(self) -> None:
        """Centers window, sets its width & height."""

        self.width = int(self.terminal.width * 2 / 3)
        self.height = int(self.terminal.height * 2 / 3)
        self.center(store=False)

    def on_exit(self) -> None:
        """Called on application exit.

        Should be used to print current application state to the user's shell.
        """

        ptg.tim.print(f"{_title()} - [dim]{self.app_title}")
        print()

app_id: str instance-attribute

The short identifier used by ArgumentParser.

app_title: str instance-attribute

The display title of the application.

standalone: bool = bool(getattr(args, self.app_id, None)) instance-attribute

Whether this app was launched directly from the CLI.

on_exit()

Called on application exit.

Should be used to print current application state to the user's shell.

Source code in pytermgui/cmd.py
70
71
72
73
74
75
76
77
def on_exit(self) -> None:
    """Called on application exit.

    Should be used to print current application state to the user's shell.
    """

    ptg.tim.print(f"{_title()} - [dim]{self.app_title}")
    print()

setup()

Centers window, sets its width & height.

Source code in pytermgui/cmd.py
63
64
65
66
67
68
def setup(self) -> None:
    """Centers window, sets its width & height."""

    self.width = int(self.terminal.width * 2 / 3)
    self.height = int(self.terminal.height * 2 / 3)
    self.center(store=False)

ColorPickerWindow

Bases: AppWindow

A window to pick colors from the xterm-256 palette.

Source code in pytermgui/cmd.py
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
class ColorPickerWindow(AppWindow):
    """A window to pick colors from the xterm-256 palette."""

    app_title = "ColorPicker"
    app_id = "color"

    def __init__(self, args: Namespace | None = None, **attrs: Any) -> None:
        super().__init__(args, **attrs)

        self._chosen_rgb = ptg.str_to_color("black")

        self._colorpicker = ptg.ColorPicker()
        self._add_widget(ptg.FancyReprWidget(ptg.palette, starts_at=2))
        self._add_widget(ptg.Collapsible("xterm-256", "", self._colorpicker))
        self._add_widget("")
        self._add_widget(
            ptg.Collapsible("RGB & HEX", "", self._create_rgb_picker(), static_width=81)
        )

        self.setup()

    def _create_rgb_picker(self) -> ptg.Container:
        """Creates the RGB picker 'widget'."""

        root = ptg.Container(static_width=72)

        matrix = ptg.DensePixelMatrix(68, 20)
        hexdisplay = ptg.Label()
        rgbdisplay = ptg.Label()

        sliders = [ptg.Slider() for _ in range(3)]

        def _get_rgb() -> tuple[int, int, int]:
            """Computes the RGB value from the 3 sliders."""

            values = [int(255 * slider.value) for slider in sliders]

            return values[0], values[1], values[2]

        def _update(*_) -> None:
            """Updates the matrix & displays with the current color."""

            color = self._chosen_rgb = ptg.RGBColor.from_rgb(_get_rgb())
            for row in range(matrix.rows):
                for col in range(matrix.columns):
                    matrix[row, col] = color.hex

            hexdisplay.value = f"[ptg.body]{color.hex}"
            rgbdisplay.value = f"[ptg.body]rgb({', '.join(map(str, color.rgb))})"
            matrix.build()

        red, green, blue = sliders

        # red.styles.filled_selected__cursor = "red"
        # green.styles.filled_selected__cursor = "green"
        # blue.styles.filled_selected__cursor = "blue"

        for slider in sliders:
            slider.onchange = _update

        root += hexdisplay
        root += rgbdisplay
        root += ""

        root += matrix
        root += ""

        root += red
        root += green
        root += blue

        _update()
        return root

    def on_exit(self) -> None:
        super().on_exit()

        color = self._chosen_rgb
        eightbit = " ".join(
            button.get_lines()[0] for button in self._colorpicker.chosen
        )

        ptg.tim.print("[ptg.title]Your colors:")
        ptg.tim.print(f"    [{color.hex}]{color.rgb}[/] // [{color.hex}]{color.hex}")
        ptg.tim.print()
        ptg.tim.print(f"    {eightbit}")

GetchWindow

Bases: AppWindow

A window for the Getch utility.

Source code in pytermgui/cmd.py
 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
class GetchWindow(AppWindow):
    """A window for the Getch utility."""

    app_title = "Getch"
    app_id = "getch"

    def __init__(self, args: Namespace | None = None, **attrs: Any) -> None:
        super().__init__(args, **attrs)

        self.bind(ptg.keys.ANY_KEY, self._update)

        self._content = ptg.Container("Press any key...", static_width=50)
        self._add_widget(self._content)

        self.setup()

    def _update(self, _: ptg.Widget, key: str) -> None:
        """Updates window contents on keypress."""

        self._content.set_widgets([])
        name = _get_key_name(key)

        if name != ascii(key):
            name = f"keys.{name}"

        style = ptg.HighlighterStyle(ptg.highlight_python)

        items = [
            "[ptg.title]Your output",
            "",
            {"[ptg.detail]key": ptg.Label(name, style=style)},
            {"[ptg.detail]value:": ptg.Label(ascii(key), style=style)},
            {"[ptg.detail]len()": ptg.Label(str(len(key)), style=style)},
            {
                "[ptg.detail]real_length()": ptg.Label(
                    str(ptg.real_length(key)), style=style
                )
            },
        ]

        for item in items:
            self._content += item

        if self.standalone:
            assert self.manager is not None
            self.manager.stop()

    def on_exit(self) -> None:
        super().on_exit()

        for line in self._content.get_lines():
            print(line)

InspectorWindow

Bases: AppWindow

A window for the inspect utility.

Source code in pytermgui/cmd.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
class InspectorWindow(AppWindow):
    """A window for the `inspect` utility."""

    app_title = "Inspector"
    app_id = "inspect"

    def __init__(self, args: Namespace | None = None, **attrs: Any) -> None:
        super().__init__(args, **attrs)

        self._input = ptg.InputField(value="boxes.Box")

        self._output = ptg.Container(box="EMPTY")
        self._update()

        self._input.bind(ptg.keys.ENTER, self._update)

        self._add_widget(
            ptg.Container(
                self._output,
                "",
                ptg.Container(self._input),
                box="EMPTY",
            )
        )

        self.setup()

        self.select(0)

    @staticmethod
    def obj_from_path(path: str) -> object | None:
        """Retrieves an object from any valid import path.

        An import path could be something like:
            pytermgui.window_manager.compositor.Compositor

        ...or if the library in question imports its parts within `__init__.py`-s:
            pytermgui.Compositor
        """

        parts = path.split(".")

        if parts[0] in dir(builtins):
            obj = getattr(builtins, parts[0])

        elif parts[0] in dir(ptg):
            obj = getattr(ptg, parts[0])

        else:
            try:
                obj = importlib.import_module(".".join(parts[:-1]))
            except (ValueError, ModuleNotFoundError) as error:
                return (
                    f"Could not import object at path {path!r}: {error}."
                    + " Maybe try using the --eval flag?"
                )

        try:
            obj = getattr(obj, parts[-1])
        except AttributeError:
            return obj

        return obj

    def _update(self, *_) -> None:
        """Updates output with new inspection result."""

        obj = self.obj_from_path(self._input.value)

        self._output.vertical_align = ptg.VerticalAlignment.CENTER
        self._output.set_widgets([ptg.inspect(obj)])

    def on_exit(self) -> None:
        super().on_exit()

        self._output.vertical_align = ptg.VerticalAlignment.TOP
        for line in self._output.get_lines():
            print(line)

obj_from_path(path) staticmethod

Retrieves an object from any valid import path.

An import path could be something like

pytermgui.window_manager.compositor.Compositor

...or if the library in question imports its parts within __init__.py-s: pytermgui.Compositor

Source code in pytermgui/cmd.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
@staticmethod
def obj_from_path(path: str) -> object | None:
    """Retrieves an object from any valid import path.

    An import path could be something like:
        pytermgui.window_manager.compositor.Compositor

    ...or if the library in question imports its parts within `__init__.py`-s:
        pytermgui.Compositor
    """

    parts = path.split(".")

    if parts[0] in dir(builtins):
        obj = getattr(builtins, parts[0])

    elif parts[0] in dir(ptg):
        obj = getattr(ptg, parts[0])

    else:
        try:
            obj = importlib.import_module(".".join(parts[:-1]))
        except (ValueError, ModuleNotFoundError) as error:
            return (
                f"Could not import object at path {path!r}: {error}."
                + " Maybe try using the --eval flag?"
            )

    try:
        obj = getattr(obj, parts[-1])
    except AttributeError:
        return obj

    return obj

TIMWindow

Bases: AppWindow

An application to play around with TIM.

Source code in pytermgui/cmd.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
class TIMWindow(AppWindow):
    """An application to play around with TIM."""

    app_title = "TIM Playground"
    app_id = "tim"

    def __init__(self, args: Namespace | None = None, **attrs: Any) -> None:
        super().__init__(args, **attrs)

        if self.standalone:
            self.bind(
                ptg.keys.RETURN,
                lambda *_: self.manager.stop() if self.manager is not None else None,
            )

        self._generate_colors()

        self._output = ptg.Label(parent_align=0)

        self._input = ptg.InputField()
        self._input.styles.value__fill = lambda _, item: item

        self._showcase = self._create_showcase()

        self._input.bind(ptg.keys.ANY_KEY, lambda *_: self._update_output())

        self._add_widget(
            ptg.Container(
                ptg.Container(self._output),
                self._showcase,
                ptg.Container(self._input),
                box="EMPTY",
                static_width=60,
            )
        )

        self.bind(ptg.keys.CTRL_R, self._generate_colors)

        self.setup()

        self.select(0)

    @staticmethod
    def _random_rgb() -> ptg.Color:
        """Returns a random Color."""

        rgb = tuple(random.randint(0, 255) for _ in range(3))

        return ptg.RGBColor.from_rgb(rgb)  # type: ignore

    def _update_output(self) -> None:
        """Updates the output field."""

        self._output.value = self._input.value

    def _generate_colors(self, *_) -> None:
        """Generates self._example_{255,rgb,hex}."""

        ptg.tim.alias("ptg.timwindow.255", str(random.randint(16, 233)))
        ptg.tim.alias("ptg.timwindow.rgb", ";".join(map(str, self._random_rgb().rgb)))
        ptg.tim.alias("ptg.timwindow.hex", self._random_rgb().hex)

    @staticmethod
    def _create_showcase() -> ptg.Container:
        """Creates the showcase container."""

        def _show_style(name: str) -> str:
            return f"[{name}]{name}"  # .replace("'", "")

        def _create_table(source: Iterable[tuple[str, str]]) -> ptg.Container:
            root = ptg.Container()

            for left, right in source:
                row = ptg.Splitter(
                    ptg.Label(left, parent_align=0), ptg.Label(right, parent_align=2)
                )

                row.set_char("separator", f" {ptg.Container.chars['border'][0]}")

                root += row

            return root

        prefix = "ptg.timwindow"
        tags = [_show_style(style) for style in ptg.markup.style_maps.STYLES]
        colors = [
            f"[[{prefix}.255]0-255[/]]",
            f"[[{prefix}.hex]#RRGGBB[/]]",
            f"[[{prefix}.rgb]RRR;GGG;BBB[/]]",
            "",
            f"[[inverse {prefix}.255]@0-255[/]]",
            f"[[inverse {prefix}.hex]@#RRGGBB[/]]",
            f"[[inverse {prefix}.rgb]@RRR;GGG;BBB[/]]",
        ]

        tag_container = _create_table(zip_longest(tags, colors, fillvalue=""))
        user_container = _create_table(
            (_show_style(tag), f"[{tag}]{value}")
            for tag, value in ptg.tim.aliases.items()
            if not tag.startswith("/") and tag not in ptg.palette.data
        )

        return ptg.Container(tag_container, user_container, box="EMPTY")

    def on_exit(self) -> None:
        super().on_exit()
        ptg.tim.print(ptg.highlight_tim(self._input.value))
        ptg.tim.print(self._input.value)

main(argv=None)

Runs the program.

Parameters:

Name Type Description Default
argv list[str] | None

A list of arguments, not included the 0th element pointing to the executable path.

None
Source code in pytermgui/cmd.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def main(argv: list[str] | None = None) -> None:
    """Runs the program.

    Args:
        argv: A list of arguments, not included the 0th element pointing to the
            executable path.
    """

    _create_aliases()

    args = process_args(argv)

    args.app = args.app or (
        "getch"
        if args.getch
        else ("tim" if args.tim else ("color" if args.color else None))
    )

    if args.app or len(sys.argv) == 1:
        run_environment(args)

        return

    with ptg.terminal.record() as recording:
        if args.size:
            ptg.tim.print(f"{ptg.terminal.width}x{ptg.terminal.height}")

        elif args.version:
            _print_version()

        elif args.palette:
            ptg.palette.print()

        elif args.inspect:
            _run_inspect(args)

        elif args.exec:
            args.exec = sys.stdin.read() if args.exec == "-" else args.exec

            for name in dir(ptg):
                obj = getattr(ptg, name, None)
                globals()[name] = obj

            globals()["print"] = ptg.terminal.print

            exec(args.exec, locals(), globals())  # pylint: disable=exec-used

        elif args.highlight:
            text = sys.stdin.read() if args.highlight == "-" else args.highlight

            ptg.tim.print(ptg.highlight_python(text))

        elif args.file:
            _interpret_file(args)

        if args.export_svg:
            recording.save_svg(args.export_svg)

        elif args.export_html:
            recording.save_html(args.export_html)

process_args(argv=None)

Processes command line arguments.

Source code in pytermgui/cmd.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def process_args(argv: list[str] | None = None) -> Namespace:
    """Processes command line arguments."""

    parser = ArgumentParser(
        description=f"{ptg.tim.parse(_title())}'s command line environment."
    )

    apps = [short for (_, short), _ in APPLICATION_MAP.items()]

    app_group = parser.add_argument_group("Applications")
    app_group.add_argument(
        "--app",
        type=str.lower,
        help="Launch an app.",
        metavar=f"{', '.join(app.capitalize() for app in apps)}",
        choices=apps,
    )

    app_group.add_argument(
        "-g", "--getch", help="Launch the Getch app.", action="store_true"
    )

    app_group.add_argument(
        "-t", "--tim", help="Launch the TIM Playground app.", action="store_true"
    )

    app_group.add_argument(
        "-c",
        "--color",
        help="Launch the ColorPicker app.",
        action="store_true",
    )

    inspect_group = parser.add_argument_group("Inspection")
    inspect_group.add_argument(
        "-i", "--inspect", help="Inspect an object.", metavar="PATH_OR_CODE"
    )
    inspect_group.add_argument(
        "-e",
        "--eval",
        help="Evaluate the expression given to `--inspect` instead of treating it as a path.",
        action="store_true",
    )

    inspect_group.add_argument(
        "--methods", help="Always show methods when inspecting.", action="store_true"
    )
    inspect_group.add_argument(
        "--dunder",
        help="Always show __dunder__ methods when inspecting.",
        action="store_true",
    )
    inspect_group.add_argument(
        "--private",
        help="Always show _private methods when inspecting.",
        action="store_true",
    )

    util_group = parser.add_argument_group("Utilities")
    util_group.add_argument(
        "-s",
        "--size",
        help="Output the current terminal size in WxH format.",
        action="store_true",
    )

    util_group.add_argument(
        "-v",
        "--version",
        help="Print version & system information.",
        action="store_true",
    )

    util_group.add_argument(
        "--palette",
        help="Print the default PyTermGUI color palette.",
        action="store_true",
    )

    util_group.add_argument(
        "--highlight",
        help=(
            "Highlight some python-like code syntax."
            + " No argument or '-' will read STDIN."
        ),
        metavar="SYNTAX",
        const="-",
        nargs="?",
    )

    util_group.add_argument(
        "--exec",
        help="Execute some Python code. No argument or '-' will read STDIN.",
        const="-",
        nargs="?",
    )

    util_group.add_argument("-f", "--file", help="Interpret a PTG-YAML file.")
    util_group.add_argument(
        "--print-only",
        help="When interpreting YAML, print the environment without running it interactively.",
        action="store_true",
    )

    export_group = parser.add_argument_group("Exporters")

    export_group.add_argument(
        "--export-svg",
        help="Export the result of any non-interactive argument as an SVG file.",
        metavar="FILE",
    )
    export_group.add_argument(
        "--export-html",
        help="Export the result of any non-interactive argument as an HTML file.",
        metavar="FILE",
    )

    argv = argv or sys.argv[1:]
    args = parser.parse_args(args=argv)

    return args

run_environment(args)

Runs the WindowManager environment.

Parameters:

Name Type Description Default
args Namespace

An argparse namespace containing relevant arguments.

required
Source code in pytermgui/cmd.py
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
def run_environment(args: Namespace) -> None:
    """Runs the WindowManager environment.

    Args:
        args: An argparse namespace containing relevant arguments.
    """

    def _find_focused(manager: ptg.WindowManager) -> ptg.Window | None:
        if manager.focused is None:
            return None

        # Find foremost non-persistent window
        for window in manager:
            if window.is_persistent:
                continue

            return window

        return None

    def _toggle_attachment(manager: ptg.WindowManager) -> None:
        focused = _find_focused(manager)

        if focused is None:
            return

        slot = manager.layout.body
        if slot.content is None:
            slot.content = focused
        else:
            slot.detach_content()

        manager.layout.apply()

    def _close_focused(manager: ptg.WindowManager) -> None:
        focused = _find_focused(manager)

        if focused is None:
            return

        focused.close()

    _configure_widgets()

    window: AppWindow | None = None
    with ptg.WindowManager() as manager:
        app_picker = _create_app_picker(manager)

        manager.bind(
            ptg.keys.CTRL_W,
            lambda *_: _close_focused(manager),
            "Close window",
        )
        manager.bind(
            ptg.keys.F12,
            lambda *_: screenshot(manager),
            "Screenshot",
        )
        manager.bind(
            ptg.keys.CTRL_F,
            lambda *_: _toggle_attachment(manager),
            "Toggle layout",
        )

        manager.bind(
            ptg.keys.CTRL_A,
            lambda *_: {
                manager.focus(app_picker),  # type: ignore
                app_picker.execute_binding(ptg.keys.CTRL_A),
            },
        )
        manager.bind(
            ptg.keys.ALT + ptg.keys.TAB,
            lambda *_: manager.focus_next(),
        )
        manager.bind(
            "!",
            lambda *_: ptg.palette.regenerate(
                primary=";".join(str(random.randint(0, 256)) for _ in range(3))
            ),
            "Re-palette",
        )

        if not args.app:
            manager.layout = _create_layout()

            manager.add(_create_header(), assign="header")
            manager.add(app_picker, assign="applications")
            manager.add(_create_footer(manager), assign="footer")

            manager.toast(
                "[ptg.title]Welcome to the [/ptg.title ptg.brand_title]"
                + "PyTermGUI[/ptg.brand_title ptg.title] CLI!",
                offset=ptg.terminal.height // 2 - 3,
                delay=700,
            )

        else:
            manager.layout.add_slot("Body")

            app = _app_from_short(args.app)
            window = app(args)
            manager.add(window, assign="body")

    window = window or manager.focused  # type: ignore
    if window is None or not isinstance(window, AppWindow):
        return

    window.on_exit()

screenshot(man)

Opens a modal dialogue & saves a screenshot.

Source code in pytermgui/cmd.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def screenshot(man: ptg.WindowManager) -> None:
    """Opens a modal dialogue & saves a screenshot."""

    tempname = ".screenshot_temp.svg"

    modal: ptg.Window

    def _finish(*_: Any) -> None:
        """Closes the modal and renames the window."""

        man.remove(modal)
        filename = field.value or "screenshot"

        if not filename.endswith(".svg"):
            filename += ".svg"

        os.rename(tempname, filename)

        man.toast("[ptg.title]Screenshot saved!", "", f"[ptg.detail]{filename}")

    title = sys.argv[0]
    field = ptg.InputField(prompt="Save as: ")

    man.screenshot(title=title, filename=tempname)

    modal = man.alert(
        "[ptg.title]Screenshot taken!", "", ptg.Container(field), "", ["Save!", _finish]
    )