Skip to content

base

The basic building blocks making up the Widget system.

Label

Bases: Widget

A Widget to display a string

By default, this widget uses pytermgui.widgets.styles.MARKUP. This allows it to house markup text that is parsed before display, such as:

print("hello world")
import pytermgui as ptg

with ptg.alt_buffer():
    root = ptg.Container(
        ptg.Label("[italic 141 bold]This is some [green]fancy [white inverse]text!")
    )
    root.print()
    ptg.getch()

Source code in pytermgui/widgets/base.py
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
class Label(Widget):
    """A Widget to display a string

    By default, this widget uses `pytermgui.widgets.styles.MARKUP`. This
    allows it to house markup text that is parsed before display, such as:

    ```termage-svg
    print("hello world")
    ```

    ```python3
    import pytermgui as ptg

    with ptg.alt_buffer():
        root = ptg.Container(
            ptg.Label("[italic 141 bold]This is some [green]fancy [white inverse]text!")
        )
        root.print()
        ptg.getch()
    ```

    <p style="text-align: center">
     <img
      src="https://github.com/bczsalba/pytermgui/blob/master/assets/docs/widgets/label.png?raw=true"
      width=100%>
    </p>
    """

    serialized = Widget.serialized + ["*value", "align", "padding"]
    styles = w_styles.StyleManager(value="")

    def __init__(
        self,
        value: str = "",
        style: str | w_styles.StyleValue = "",
        padding: int = 0,
        non_first_padding: int = 0,
        **attrs: Any,
    ) -> None:
        """Initializes a Label.

        Args:
            value: The value of this string. Using the default value style
                (`pytermgui.widgets.styles.MARKUP`),
            style: A pre-set value for self.styles.value.
            padding: The number of space (" ") characters to prepend to every line after
                line breaking.
            non_first_padding: The number of space characters to prepend to every
                non-first line of `get_lines`. This is applied on top of `padding`.
        """

        super().__init__(**attrs)

        self.value = value
        self.padding = padding
        self.non_first_padding = non_first_padding
        self.width = real_length(value) + self.padding

        if style != "":
            self.styles.value = style

    def get_lines(self) -> list[str]:
        """Get lines representing this Label, breaking lines as necessary"""

        lines = []
        limit = self.width - self.padding
        broken = break_line(
            self.styles.value(self.value),
            limit=limit,
            non_first_limit=limit - self.non_first_padding,
        )

        for i, line in enumerate(broken):
            if i == 0:
                lines.append(self.padding * " " + line)
                continue

            lines.append(self.padding * " " + self.non_first_padding * " " + line)

        return lines or [""]

__init__(value='', style='', padding=0, non_first_padding=0, **attrs)

Initializes a Label.

Parameters:

Name Type Description Default
value str

The value of this string. Using the default value style (pytermgui.widgets.styles.MARKUP),

''
style str | w_styles.StyleValue

A pre-set value for self.styles.value.

''
padding int

The number of space (" ") characters to prepend to every line after line breaking.

0
non_first_padding int

The number of space characters to prepend to every non-first line of get_lines. This is applied on top of padding.

0
Source code in pytermgui/widgets/base.py
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
def __init__(
    self,
    value: str = "",
    style: str | w_styles.StyleValue = "",
    padding: int = 0,
    non_first_padding: int = 0,
    **attrs: Any,
) -> None:
    """Initializes a Label.

    Args:
        value: The value of this string. Using the default value style
            (`pytermgui.widgets.styles.MARKUP`),
        style: A pre-set value for self.styles.value.
        padding: The number of space (" ") characters to prepend to every line after
            line breaking.
        non_first_padding: The number of space characters to prepend to every
            non-first line of `get_lines`. This is applied on top of `padding`.
    """

    super().__init__(**attrs)

    self.value = value
    self.padding = padding
    self.non_first_padding = non_first_padding
    self.width = real_length(value) + self.padding

    if style != "":
        self.styles.value = style

get_lines()

Get lines representing this Label, breaking lines as necessary

Source code in pytermgui/widgets/base.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
def get_lines(self) -> list[str]:
    """Get lines representing this Label, breaking lines as necessary"""

    lines = []
    limit = self.width - self.padding
    broken = break_line(
        self.styles.value(self.value),
        limit=limit,
        non_first_limit=limit - self.non_first_padding,
    )

    for i, line in enumerate(broken):
        if i == 0:
            lines.append(self.padding * " " + line)
            continue

        lines.append(self.padding * " " + self.non_first_padding * " " + line)

    return lines or [""]

ScrollableWidget

Bases: Widget

A widget with some scrolling helper methods.

This is not an implementation of the scrolling behaviour itself, just the user-facing API for it.

It provides a _scroll_offset attribute, which is an integer describing the current scroll state offset from the top, as well as some methods to modify the state.

Source code in pytermgui/widgets/base.py
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
class ScrollableWidget(Widget):
    """A widget with some scrolling helper methods.

    This is not an implementation of the scrolling behaviour itself, just the
    user-facing API for it.

    It provides a `_scroll_offset` attribute, which is an integer describing the current
    scroll state offset from the top, as well as some methods to modify the state."""

    def __init__(self, **attrs: Any) -> None:
        """Initializes the scrollable widget."""

        super().__init__(**attrs)

        self._max_scroll = 0
        self._scroll_offset = 0

    def scroll(self, offset: int) -> bool:
        """Scrolls to given offset, returns the new scroll_offset.

        Args:
            offset: The amount to scroll by. Positive offsets scroll down,
                negative up.

        Returns:
            True if the scroll offset changed, False otherwise.
        """

        base = self._scroll_offset

        self._scroll_offset = min(
            max(0, self._scroll_offset + offset), self._max_scroll
        )

        return base != self._scroll_offset

    def scroll_end(self, end: int) -> int:
        """Scrolls to either top or bottom end of this object.

        Args:
            end: The offset to scroll to. 0 goes to the very top, -1 to the
                very bottom.

        Returns:
            True if the scroll offset changed, False otherwise.
        """

        base = self._scroll_offset

        if end == 0:
            self._scroll_offset = 0

        elif end == -1:
            self._scroll_offset = self._max_scroll

        return base != self._scroll_offset

    def get_lines(self) -> list[str]:
        ...

__init__(**attrs)

Initializes the scrollable widget.

Source code in pytermgui/widgets/base.py
816
817
818
819
820
821
822
def __init__(self, **attrs: Any) -> None:
    """Initializes the scrollable widget."""

    super().__init__(**attrs)

    self._max_scroll = 0
    self._scroll_offset = 0

scroll(offset)

Scrolls to given offset, returns the new scroll_offset.

Parameters:

Name Type Description Default
offset int

The amount to scroll by. Positive offsets scroll down, negative up.

required

Returns:

Type Description
bool

True if the scroll offset changed, False otherwise.

Source code in pytermgui/widgets/base.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def scroll(self, offset: int) -> bool:
    """Scrolls to given offset, returns the new scroll_offset.

    Args:
        offset: The amount to scroll by. Positive offsets scroll down,
            negative up.

    Returns:
        True if the scroll offset changed, False otherwise.
    """

    base = self._scroll_offset

    self._scroll_offset = min(
        max(0, self._scroll_offset + offset), self._max_scroll
    )

    return base != self._scroll_offset

scroll_end(end)

Scrolls to either top or bottom end of this object.

Parameters:

Name Type Description Default
end int

The offset to scroll to. 0 goes to the very top, -1 to the very bottom.

required

Returns:

Type Description
int

True if the scroll offset changed, False otherwise.

Source code in pytermgui/widgets/base.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def scroll_end(self, end: int) -> int:
    """Scrolls to either top or bottom end of this object.

    Args:
        end: The offset to scroll to. 0 goes to the very top, -1 to the
            very bottom.

    Returns:
        True if the scroll offset changed, False otherwise.
    """

    base = self._scroll_offset

    if end == 0:
        self._scroll_offset = 0

    elif end == -1:
        self._scroll_offset = self._max_scroll

    return base != self._scroll_offset

Widget

The base of the Widget system

Source code in pytermgui/widgets/base.py
 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
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
220
221
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
330
331
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
551
552
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
class Widget:  # pylint: disable=too-many-public-methods
    """The base of the Widget system"""

    set_style = classmethod(_set_obj_or_cls_style)
    set_char = classmethod(_set_obj_or_cls_char)

    styles = w_styles.StyleManager()
    """Default styles for this class"""

    chars: dict[str, w_styles.CharType] = {}
    """Default characters for this class"""

    keys: dict[str, set[str]] = {}
    """Groups of keys that are used in `handle_key`"""

    serialized: list[str] = [
        "id",
        "pos",
        "depth",
        "width",
        "height",
        "selected_index",
        "selectables_length",
    ]
    """Fields of widget that shall be serialized by `pytermgui.serializer.Serializer`"""

    # This class is loaded after this module,
    # and thus mypy doesn't see its existence.
    _id_manager: Optional["_IDManager"] = None  # type: ignore

    size_policy = SizePolicy.get_default()
    """`pytermgui.enums.SizePolicy` to set widget's width according to"""

    parent_align = HorizontalAlignment.get_default()
    """`pytermgui.enums.HorizontalAlignment` to align widget by"""

    from_data: Callable[..., Widget | list[Widget] | None]

    # We cannot import boxes here due to cyclic imports.
    box: Any

    def __init__(self, **attrs: Any) -> None:
        """Initialize object"""

        self.set_style = lambda key, value: _set_obj_or_cls_style(self, key, value)
        self.set_char = lambda key, value: _set_obj_or_cls_char(self, key, value)

        self.width = 1
        self.height = 1
        self.pos = self.terminal.origin

        self.depth = 0

        self.styles = type(self).styles.branch(self)
        self.chars = type(self).chars.copy()

        self.parent: Widget | None = None
        self.selected_index: int | None = None

        self._selectables_length = 0
        self._id: Optional[str] = None
        self._serialized_fields = type(self).serialized
        self._bindings: dict[str | Type[MouseEvent], tuple[BoundCallback, str]] = {}
        self._relative_width: float | None = None
        self._previous_state: tuple[tuple[int, int], list[str]] | None = None

        self.positioned_line_buffer: list[tuple[tuple[int, int], str]] = []

        for attr, value in attrs.items():
            setattr(self, attr, value)

    def __repr__(self) -> str:
        """Return repr string of this widget.

        Returns:
            Whatever this widget's `debug` method gives.
        """

        return self.debug()

    def __fancy_repr__(self) -> Generator[FancyYield, None, None]:
        """Yields the repr of this object, then a preview of it."""

        yield self.debug()
        yield "\n\n"
        yield {
            "text": "\n".join((line + reset() for line in self.get_lines())),
            "highlight": False,
        }

    def __iter__(self) -> Iterator[Widget]:
        """Return self for iteration"""

        yield self

    @property
    def bindings(self) -> dict[str | Type[MouseEvent], tuple[BoundCallback, str]]:
        """Gets a copy of the bindings internal dictionary.

        Returns:
            A copy of the internal bindings dictionary, such as:

            ```
            {
                "*": (star_callback, "This is a callback activated when '*' is pressed.")
            }
            ```
        """

        return self._bindings.copy()

    @property
    def id(self) -> Optional[str]:  # pylint: disable=invalid-name
        """Gets this widget's id property

        Returns:
            The id string if one is present, None otherwise.
        """

        return self._id

    @id.setter
    def id(self, value: str) -> None:  # pylint: disable=invalid-name
        """Registers a widget to the Widget._id_manager.

        If this widget already had an id, the old value is deregistered
        before the new one is assigned.

        Args:
            value: The new id this widget will be registered as.
        """

        if self._id == value:
            return

        manager = Widget._id_manager
        assert manager is not None

        old = manager.get_id(self)
        if old is not None:
            manager.deregister(old)

        self._id = value
        manager.register(self)

    @property
    def selectables_length(self) -> int:
        """Gets how many selectables this widget contains.

        Returns:
            An integer describing the amount of selectables in this widget.
        """

        return self._selectables_length

    @property
    def selectables(self) -> list[tuple[Widget, int]]:
        """Gets a list of all selectables within this widget

        Returns:
            A list of tuples. In the default implementation this will be
            a list of one tuple, containing a reference to `self`, as well
            as the lowest index, 0.
        """

        return [(self, 0)]

    @property
    def is_selectable(self) -> bool:
        """Determines whether this widget has any selectables.

        Returns:
            A boolean, representing `self.selectables_length != 0`.
        """

        return self.selectables_length != 0

    @property
    def static_width(self) -> int:
        """Allows for a shorter way of setting a width, and SizePolicy.STATIC.

        Args:
            value: The new width integer.

        Returns:
            None, as this is setter only.
        """

        return None  # type: ignore

    @static_width.setter
    def static_width(self, value: int) -> None:
        """See the static_width getter."""

        self.width = value
        self.size_policy = SizePolicy.STATIC

    @property
    def relative_width(self) -> float | None:
        """Sets this widget's relative width, and changes size_policy to RELATIVE.

        The value is clamped to 1.0.

        If a Container holds a width of 30, and it has a subwidget with a relative
        width of 0.5, it will be resized to 15.

        Args:
            value: The multiplier to apply to the parent's width.

        Returns:
            The current relative_width.
        """

        return self._relative_width

    @relative_width.setter
    def relative_width(self, value: float) -> None:
        """See the relative_width getter."""

        self.size_policy = SizePolicy.RELATIVE
        self._relative_width = min(1.0, value)

    @property
    def terminal(self) -> Terminal:
        """Returns the current global terminal instance."""

        return get_terminal()

    def _align(self, lines: list[str]) -> list[str]:
        """Aligns the given lines based on this widget's `parent_align` attribute."""

        width = self.width

        def _align_left(line: str) -> str:
            return line + (width - real_length(line)) * " "

        def _align_center(line: str) -> str:
            right, extra = divmod(width - real_length(line), 2)
            left = right + extra

            return left * " " + line + right * " "

        def _align_right(line: str) -> str:
            return (width - real_length(line)) * " " + line

        if self.parent_align is None:
            raise TypeError("Horizontal alignment cannot be None.")

        assert isinstance(self.parent_align, HorizontalAlignment)

        aligner = {
            HorizontalAlignment.LEFT: _align_left,
            HorizontalAlignment.CENTER: _align_center,
            HorizontalAlignment.RIGHT: _align_right,
        }[self.parent_align]

        aligned = []

        for line in lines:
            aligned.append(aligner(line))

        return aligned

    def get_change(self) -> WidgetChange | None:
        """Determines whether widget lines changed since the last call to this function."""

        lines = self.get_lines()

        if self._previous_state is None:
            self._previous_state = (self.width, self.height), lines
            return WidgetChange.LINES

        lines = self.get_lines()
        (old_width, old_height), old_lines = self._previous_state

        self._previous_state = (self.width, self.height), lines

        if old_width != self.width and old_height != self.height:
            return WidgetChange.SIZE

        if old_width != self.width:
            return WidgetChange.WIDTH

        if old_height != self.height:
            return WidgetChange.HEIGHT

        if old_lines != lines:
            return WidgetChange.LINES

        return None

    def contains(self, pos: tuple[int, int]) -> bool:
        """Determines whether widget contains `pos`.

        Args:
            pos: Position to compare.

        Returns:
            Boolean describing whether the position is inside
                this widget.
        """

        rect = self.pos, (
            self.pos[0] + self.width,
            self.pos[1] + self.height,
        )

        (left, top), (right, bottom) = rect

        return left <= pos[0] < right and top <= pos[1] < bottom

    def handle_mouse(self, event: MouseEvent) -> bool:
        """Tries to call the most specific mouse handler function available.

        This function looks for a set of mouse action handlers. Each handler follows
        the format

            on_{event_name}

        For example, the handler triggered on MouseAction.LEFT_CLICK would be
        `on_left_click`. If no handler is found nothing is done.

        You can also define more general handlers, for example to group left & right
        clicks you can use `on_click`, and to catch both up and down scroll you can use
        `on_scroll`. General handlers are only used if they are the most specific ones,
        i.e. there is no "specific" handler.

        Args:
            event: The event to handle.

        Returns:
            Whether the parent of this widget should treat it as one to "stick" events
            to, e.g. to keep sending mouse events to it. One can "unstick" a widget by
            returning False in the handler.
        """

        def _get_names(action: MouseAction) -> tuple[str, ...]:
            if action.value in ["hover", "release"]:
                return (action.value,)

            parts = action.value.split("_")

            # left click & right click
            if parts[0] in ["left", "right"]:
                return (action.value, parts[1])

            if parts[0] == "shift":
                return (action.value, f"shift_{parts[1]}", parts[1])

            # scroll up & down
            return (action.value, parts[0])

        possible_names = _get_names(event.action)
        for name in possible_names:
            if hasattr(self, f"on_{name}"):
                handle = getattr(self, f"on_{name}")

                return handle(event)

        return False

    def handle_key(self, key: str) -> bool:
        """Handles a mouse event, returning its success.

        Args:
            key: String representation of input string.
                The `pytermgui.input.keys` object can be
                used to retrieve special keys.

        Returns:
            A boolean describing whether the key was handled.
        """

        return False and hasattr(self, key)

    def serialize(self) -> dict[str, Any]:
        """Serializes a widget.

        The fields looked at are defined `Widget.serialized`. Note that
        this method is not very commonly used at the moment, so it might
        not have full functionality in non-nuclear widgets.

        Returns:
            Dictionary of widget attributes. The dictionary will always
            have a `type` field. Any styles are converted into markup
            strings during serialization, so they can be loaded again in
            their original form.

            Example return:
            ```
                {
                    "type": "Label",
                    "value": "[210 bold]I am a title",
                    "parent_align": 0,
                    ...
                }
            ```
        """

        fields = self._serialized_fields

        out: dict[str, Any] = {"type": type(self).__name__}
        for key in fields:
            # Detect styled values
            if key.startswith("*"):
                style = True
                key = key[1:]
            else:
                style = False

            value = getattr(self, key)

            # Convert styled value into markup
            if style:
                style_call = self._get_style(key)
                if isinstance(value, list):
                    out[key] = [get_markup(style_call(char)) for char in value]
                else:
                    out[key] = get_markup(style_call(value))

                continue

            out[key] = value

        # The chars need to be handled separately
        out["chars"] = {}
        for key, value in self.chars.items():
            style_call = self._get_style(key)

            if isinstance(value, list):
                out["chars"][key] = [get_markup(style_call(char)) for char in value]
            else:
                out["chars"][key] = get_markup(style_call(value))

        return out

    def copy(self) -> Widget:
        """Creates a deep copy of this widget"""

        return deepcopy(self)

    def _get_style(self, key: str) -> w_styles.DepthlessStyleType:
        """Gets style call from its key.

        This is analogous to using `self.styles.{key}`

        Args:
            key: A key into the widget's style manager.

        Returns:
            A `pytermgui.styles.StyleCall` object containing the referenced
            style. StyleCall objects should only be used internally inside a
            widget.

        Raises:
            KeyError: Style key is invalid.
        """

        return self.styles[key]

    def _get_char(self, key: str) -> w_styles.CharType:
        """Gets character from its key.

        Args:
            key: A key into the widget's chars dictionary.

        Returns:
            Either a `list[str]` or a simple `str`, depending on the character.

        Raises:
            KeyError: Style key is invalid.
        """

        chars = self.chars[key]

        if isinstance(chars, str):
            if chars.startswith("u:"):
                identifier = " ".join(chars[2:].split("_"))
                chars = u_lookup(identifier)

            return chars

        return chars.copy()

    def get_lines(self) -> list[str]:
        """Gets lines representing this widget.

        These lines have to be equal to the widget in length. All
        widgets must provide this method. Make sure to keep it performant,
        as it will be called very often, often multiple times per WindowManager frame.

        Any longer actions should be done outside of this method, and only their
        result should be looked up here.

        Returns:
            Nothing by default.

        Raises:
            NotImplementedError: As this method is required for **all** widgets, not
                having it defined will raise NotImplementedError.
        """

        raise NotImplementedError(f"get_lines() is not defined for type {type(self)}.")

    def move(self, diff_x: int, diff_y: int) -> None:
        """Moves the widget by the given x and y changes."""

        self.pos = (self.pos[0] + diff_x, self.pos[1] + diff_y)

        adjusted = []
        for pos, line in self.positioned_line_buffer:
            adjusted.append(((pos[0] + diff_x, pos[1] + diff_y), line))

        self.positioned_line_buffer = adjusted

    def bind(
        self, key: str, action: BoundCallback, description: Optional[str] = None
    ) -> None:
        """Binds an action to a keypress.

        This function is only called by implementations above this layer. To use this
        functionality use `pytermgui.window_manager.WindowManager`, or write your own
        custom layer.

        Special keys:
        - keys.ANY_KEY: Any and all keypresses execute this binding.
        - keys.MouseAction: Any and all mouse inputs execute this binding.

        Args:
            key: The key that the action will be bound to.
            action: The action executed when the key is pressed.
            description: An optional description for this binding. It is not really
                used anywhere, but you can provide a helper menu and display them.
        """

        if description is None:
            description = f"Binding of {key} to {action}"

        self._bindings[key] = (action, description)

    def unbind(self, key: str) -> None:
        """Unbinds the given key."""

        del self._bindings[key]

    def execute_binding(self, key: Any, ignore_any: bool = False) -> bool:
        """Executes a binding belonging to key, when present.

        Use this method inside custom widget `handle_keys` methods, or to run a callback
        without its corresponding key having been pressed.

        Args:
            key: Usually a string, indexing into the `_bindings` dictionary. These are the
                same strings as defined in `Widget.bind`.
            ignore_any: If set, `keys.ANY_KEY` bindings will not be executed.

        Returns:
            True if the binding was found, False otherwise. Bindings will always be
                executed if they are found.
        """

        # Execute special binding
        if not ignore_any and keys.ANY_KEY in self._bindings:
            method, _ = self._bindings[keys.ANY_KEY]
            method(self, key)

        if key in self._bindings:
            method, _ = self._bindings[key]
            method(self, key)

            return True

        return False

    def select(self, index: int | None = None) -> None:
        """Selects a part of this Widget.

        Args:
            index: The index to select.

        Raises:
            TypeError: This widget has no selectables, i.e. widget.is_selectable == False.
        """

        if not self.is_selectable:
            raise TypeError(f"Object of type {type(self)} has no selectables.")

        if index is not None:
            index = min(max(0, index), self.selectables_length - 1)
        self.selected_index = index

    def print(self) -> None:
        """Prints this widget"""

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

    def debug(self) -> str:
        """Returns identifiable information about this widget.

        This method is used to easily differentiate between widgets. By default, all widget's
        __repr__ method is an alias to this. The signature of each widget is used to generate
        the return value.

        Returns:
            A string almost exactly matching the line of code that could have defined the widget.

            Example return:

            ```
            Container(Label(value="This is a label", padding=0),
            Button(label="This is a button", padding=0), **attrs)
            ```

        """

        constructor = "("
        for name in signature(getattr(self, "__init__")).parameters:
            current = ""
            if name == "attrs":
                current += "**attrs"
                continue

            if len(constructor) > 1:
                current += ", "

            current += name

            attr = getattr(self, name, None)
            if attr is None:
                continue

            current += "="

            if isinstance(attr, str):
                current += f'"{attr}"'
            else:
                current += str(attr)

            constructor += current

        constructor += ")"

        return type(self).__name__ + constructor

bindings: dict[str | Type[MouseEvent], tuple[BoundCallback, str]] property

Gets a copy of the bindings internal dictionary.

Returns:

Type Description
dict[str | Type[MouseEvent], tuple[BoundCallback, str]]

A copy of the internal bindings dictionary, such as:

dict[str | Type[MouseEvent], tuple[BoundCallback, str]]

```

dict[str | Type[MouseEvent], tuple[BoundCallback, str]]

{ "": (star_callback, "This is a callback activated when '' is pressed.")

dict[str | Type[MouseEvent], tuple[BoundCallback, str]]

}

dict[str | Type[MouseEvent], tuple[BoundCallback, str]]

```

chars: dict[str, w_styles.CharType] = type(self).chars.copy() class-attribute instance-attribute

Default characters for this class

id: Optional[str] property writable

Gets this widget's id property

Returns:

Type Description
Optional[str]

The id string if one is present, None otherwise.

is_selectable: bool property

Determines whether this widget has any selectables.

Returns:

Type Description
bool

A boolean, representing self.selectables_length != 0.

keys: dict[str, set[str]] = {} class-attribute instance-attribute

Groups of keys that are used in handle_key

parent_align = HorizontalAlignment.get_default() class-attribute instance-attribute

pytermgui.enums.HorizontalAlignment to align widget by

relative_width: float | None property writable

Sets this widget's relative width, and changes size_policy to RELATIVE.

The value is clamped to 1.0.

If a Container holds a width of 30, and it has a subwidget with a relative width of 0.5, it will be resized to 15.

Parameters:

Name Type Description Default
value

The multiplier to apply to the parent's width.

required

Returns:

Type Description
float | None

The current relative_width.

selectables: list[tuple[Widget, int]] property

Gets a list of all selectables within this widget

Returns:

Type Description
list[tuple[Widget, int]]

A list of tuples. In the default implementation this will be

list[tuple[Widget, int]]

a list of one tuple, containing a reference to self, as well

list[tuple[Widget, int]]

as the lowest index, 0.

selectables_length: int property

Gets how many selectables this widget contains.

Returns:

Type Description
int

An integer describing the amount of selectables in this widget.

serialized: list[str] = ['id', 'pos', 'depth', 'width', 'height', 'selected_index', 'selectables_length'] class-attribute instance-attribute

Fields of widget that shall be serialized by pytermgui.serializer.Serializer

size_policy = SizePolicy.get_default() class-attribute instance-attribute

pytermgui.enums.SizePolicy to set widget's width according to

static_width: int property writable

Allows for a shorter way of setting a width, and SizePolicy.STATIC.

Parameters:

Name Type Description Default
value

The new width integer.

required

Returns:

Type Description
int

None, as this is setter only.

styles = type(self).styles.branch(self) class-attribute instance-attribute

Default styles for this class

terminal: Terminal property

Returns the current global terminal instance.

__fancy_repr__()

Yields the repr of this object, then a preview of it.

Source code in pytermgui/widgets/base.py
159
160
161
162
163
164
165
166
167
def __fancy_repr__(self) -> Generator[FancyYield, None, None]:
    """Yields the repr of this object, then a preview of it."""

    yield self.debug()
    yield "\n\n"
    yield {
        "text": "\n".join((line + reset() for line in self.get_lines())),
        "highlight": False,
    }

__init__(**attrs)

Initialize object

Source code in pytermgui/widgets/base.py
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
def __init__(self, **attrs: Any) -> None:
    """Initialize object"""

    self.set_style = lambda key, value: _set_obj_or_cls_style(self, key, value)
    self.set_char = lambda key, value: _set_obj_or_cls_char(self, key, value)

    self.width = 1
    self.height = 1
    self.pos = self.terminal.origin

    self.depth = 0

    self.styles = type(self).styles.branch(self)
    self.chars = type(self).chars.copy()

    self.parent: Widget | None = None
    self.selected_index: int | None = None

    self._selectables_length = 0
    self._id: Optional[str] = None
    self._serialized_fields = type(self).serialized
    self._bindings: dict[str | Type[MouseEvent], tuple[BoundCallback, str]] = {}
    self._relative_width: float | None = None
    self._previous_state: tuple[tuple[int, int], list[str]] | None = None

    self.positioned_line_buffer: list[tuple[tuple[int, int], str]] = []

    for attr, value in attrs.items():
        setattr(self, attr, value)

__iter__()

Return self for iteration

Source code in pytermgui/widgets/base.py
169
170
171
172
def __iter__(self) -> Iterator[Widget]:
    """Return self for iteration"""

    yield self

__repr__()

Return repr string of this widget.

Returns:

Type Description
str

Whatever this widget's debug method gives.

Source code in pytermgui/widgets/base.py
150
151
152
153
154
155
156
157
def __repr__(self) -> str:
    """Return repr string of this widget.

    Returns:
        Whatever this widget's `debug` method gives.
    """

    return self.debug()

bind(key, action, description=None)

Binds an action to a keypress.

This function is only called by implementations above this layer. To use this functionality use pytermgui.window_manager.WindowManager, or write your own custom layer.

Special keys: - keys.ANY_KEY: Any and all keypresses execute this binding. - keys.MouseAction: Any and all mouse inputs execute this binding.

Parameters:

Name Type Description Default
key str

The key that the action will be bound to.

required
action BoundCallback

The action executed when the key is pressed.

required
description Optional[str]

An optional description for this binding. It is not really used anywhere, but you can provide a helper menu and display them.

None
Source code in pytermgui/widgets/base.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
def bind(
    self, key: str, action: BoundCallback, description: Optional[str] = None
) -> None:
    """Binds an action to a keypress.

    This function is only called by implementations above this layer. To use this
    functionality use `pytermgui.window_manager.WindowManager`, or write your own
    custom layer.

    Special keys:
    - keys.ANY_KEY: Any and all keypresses execute this binding.
    - keys.MouseAction: Any and all mouse inputs execute this binding.

    Args:
        key: The key that the action will be bound to.
        action: The action executed when the key is pressed.
        description: An optional description for this binding. It is not really
            used anywhere, but you can provide a helper menu and display them.
    """

    if description is None:
        description = f"Binding of {key} to {action}"

    self._bindings[key] = (action, description)

contains(pos)

Determines whether widget contains pos.

Parameters:

Name Type Description Default
pos tuple[int, int]

Position to compare.

required

Returns:

Type Description
bool

Boolean describing whether the position is inside this widget.

Source code in pytermgui/widgets/base.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def contains(self, pos: tuple[int, int]) -> bool:
    """Determines whether widget contains `pos`.

    Args:
        pos: Position to compare.

    Returns:
        Boolean describing whether the position is inside
            this widget.
    """

    rect = self.pos, (
        self.pos[0] + self.width,
        self.pos[1] + self.height,
    )

    (left, top), (right, bottom) = rect

    return left <= pos[0] < right and top <= pos[1] < bottom

copy()

Creates a deep copy of this widget

Source code in pytermgui/widgets/base.py
515
516
517
518
def copy(self) -> Widget:
    """Creates a deep copy of this widget"""

    return deepcopy(self)

debug()

Returns identifiable information about this widget.

This method is used to easily differentiate between widgets. By default, all widget's repr method is an alias to this. The signature of each widget is used to generate the return value.

Returns:

Type Description
str

A string almost exactly matching the line of code that could have defined the widget.

str

Example return:

str

```

str

Container(Label(value="This is a label", padding=0),

str

Button(label="This is a button", padding=0), **attrs)

str

```

Source code in pytermgui/widgets/base.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def debug(self) -> str:
    """Returns identifiable information about this widget.

    This method is used to easily differentiate between widgets. By default, all widget's
    __repr__ method is an alias to this. The signature of each widget is used to generate
    the return value.

    Returns:
        A string almost exactly matching the line of code that could have defined the widget.

        Example return:

        ```
        Container(Label(value="This is a label", padding=0),
        Button(label="This is a button", padding=0), **attrs)
        ```

    """

    constructor = "("
    for name in signature(getattr(self, "__init__")).parameters:
        current = ""
        if name == "attrs":
            current += "**attrs"
            continue

        if len(constructor) > 1:
            current += ", "

        current += name

        attr = getattr(self, name, None)
        if attr is None:
            continue

        current += "="

        if isinstance(attr, str):
            current += f'"{attr}"'
        else:
            current += str(attr)

        constructor += current

    constructor += ")"

    return type(self).__name__ + constructor

execute_binding(key, ignore_any=False)

Executes a binding belonging to key, when present.

Use this method inside custom widget handle_keys methods, or to run a callback without its corresponding key having been pressed.

Parameters:

Name Type Description Default
key Any

Usually a string, indexing into the _bindings dictionary. These are the same strings as defined in Widget.bind.

required
ignore_any bool

If set, keys.ANY_KEY bindings will not be executed.

False

Returns:

Type Description
bool

True if the binding was found, False otherwise. Bindings will always be executed if they are found.

Source code in pytermgui/widgets/base.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def execute_binding(self, key: Any, ignore_any: bool = False) -> bool:
    """Executes a binding belonging to key, when present.

    Use this method inside custom widget `handle_keys` methods, or to run a callback
    without its corresponding key having been pressed.

    Args:
        key: Usually a string, indexing into the `_bindings` dictionary. These are the
            same strings as defined in `Widget.bind`.
        ignore_any: If set, `keys.ANY_KEY` bindings will not be executed.

    Returns:
        True if the binding was found, False otherwise. Bindings will always be
            executed if they are found.
    """

    # Execute special binding
    if not ignore_any and keys.ANY_KEY in self._bindings:
        method, _ = self._bindings[keys.ANY_KEY]
        method(self, key)

    if key in self._bindings:
        method, _ = self._bindings[key]
        method(self, key)

        return True

    return False

get_change()

Determines whether widget lines changed since the last call to this function.

Source code in pytermgui/widgets/base.py
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
def get_change(self) -> WidgetChange | None:
    """Determines whether widget lines changed since the last call to this function."""

    lines = self.get_lines()

    if self._previous_state is None:
        self._previous_state = (self.width, self.height), lines
        return WidgetChange.LINES

    lines = self.get_lines()
    (old_width, old_height), old_lines = self._previous_state

    self._previous_state = (self.width, self.height), lines

    if old_width != self.width and old_height != self.height:
        return WidgetChange.SIZE

    if old_width != self.width:
        return WidgetChange.WIDTH

    if old_height != self.height:
        return WidgetChange.HEIGHT

    if old_lines != lines:
        return WidgetChange.LINES

    return None

get_lines()

Gets lines representing this widget.

These lines have to be equal to the widget in length. All widgets must provide this method. Make sure to keep it performant, as it will be called very often, often multiple times per WindowManager frame.

Any longer actions should be done outside of this method, and only their result should be looked up here.

Returns:

Type Description
list[str]

Nothing by default.

Raises:

Type Description
NotImplementedError

As this method is required for all widgets, not having it defined will raise NotImplementedError.

Source code in pytermgui/widgets/base.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def get_lines(self) -> list[str]:
    """Gets lines representing this widget.

    These lines have to be equal to the widget in length. All
    widgets must provide this method. Make sure to keep it performant,
    as it will be called very often, often multiple times per WindowManager frame.

    Any longer actions should be done outside of this method, and only their
    result should be looked up here.

    Returns:
        Nothing by default.

    Raises:
        NotImplementedError: As this method is required for **all** widgets, not
            having it defined will raise NotImplementedError.
    """

    raise NotImplementedError(f"get_lines() is not defined for type {type(self)}.")

handle_key(key)

Handles a mouse event, returning its success.

Parameters:

Name Type Description Default
key str

String representation of input string. The pytermgui.input.keys object can be used to retrieve special keys.

required

Returns:

Type Description
bool

A boolean describing whether the key was handled.

Source code in pytermgui/widgets/base.py
440
441
442
443
444
445
446
447
448
449
450
451
452
def handle_key(self, key: str) -> bool:
    """Handles a mouse event, returning its success.

    Args:
        key: String representation of input string.
            The `pytermgui.input.keys` object can be
            used to retrieve special keys.

    Returns:
        A boolean describing whether the key was handled.
    """

    return False and hasattr(self, key)

handle_mouse(event)

Tries to call the most specific mouse handler function available.

This function looks for a set of mouse action handlers. Each handler follows the format

on_{event_name}

For example, the handler triggered on MouseAction.LEFT_CLICK would be on_left_click. If no handler is found nothing is done.

You can also define more general handlers, for example to group left & right clicks you can use on_click, and to catch both up and down scroll you can use on_scroll. General handlers are only used if they are the most specific ones, i.e. there is no "specific" handler.

Parameters:

Name Type Description Default
event MouseEvent

The event to handle.

required

Returns:

Type Description
bool

Whether the parent of this widget should treat it as one to "stick" events

bool

to, e.g. to keep sending mouse events to it. One can "unstick" a widget by

bool

returning False in the handler.

Source code in pytermgui/widgets/base.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def handle_mouse(self, event: MouseEvent) -> bool:
    """Tries to call the most specific mouse handler function available.

    This function looks for a set of mouse action handlers. Each handler follows
    the format

        on_{event_name}

    For example, the handler triggered on MouseAction.LEFT_CLICK would be
    `on_left_click`. If no handler is found nothing is done.

    You can also define more general handlers, for example to group left & right
    clicks you can use `on_click`, and to catch both up and down scroll you can use
    `on_scroll`. General handlers are only used if they are the most specific ones,
    i.e. there is no "specific" handler.

    Args:
        event: The event to handle.

    Returns:
        Whether the parent of this widget should treat it as one to "stick" events
        to, e.g. to keep sending mouse events to it. One can "unstick" a widget by
        returning False in the handler.
    """

    def _get_names(action: MouseAction) -> tuple[str, ...]:
        if action.value in ["hover", "release"]:
            return (action.value,)

        parts = action.value.split("_")

        # left click & right click
        if parts[0] in ["left", "right"]:
            return (action.value, parts[1])

        if parts[0] == "shift":
            return (action.value, f"shift_{parts[1]}", parts[1])

        # scroll up & down
        return (action.value, parts[0])

    possible_names = _get_names(event.action)
    for name in possible_names:
        if hasattr(self, f"on_{name}"):
            handle = getattr(self, f"on_{name}")

            return handle(event)

    return False

move(diff_x, diff_y)

Moves the widget by the given x and y changes.

Source code in pytermgui/widgets/base.py
583
584
585
586
587
588
589
590
591
592
def move(self, diff_x: int, diff_y: int) -> None:
    """Moves the widget by the given x and y changes."""

    self.pos = (self.pos[0] + diff_x, self.pos[1] + diff_y)

    adjusted = []
    for pos, line in self.positioned_line_buffer:
        adjusted.append(((pos[0] + diff_x, pos[1] + diff_y), line))

    self.positioned_line_buffer = adjusted

print()

Prints this widget

Source code in pytermgui/widgets/base.py
670
671
672
673
674
def print(self) -> None:
    """Prints this widget"""

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

select(index=None)

Selects a part of this Widget.

Parameters:

Name Type Description Default
index int | None

The index to select.

None

Raises:

Type Description
TypeError

This widget has no selectables, i.e. widget.is_selectable == False.

Source code in pytermgui/widgets/base.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
def select(self, index: int | None = None) -> None:
    """Selects a part of this Widget.

    Args:
        index: The index to select.

    Raises:
        TypeError: This widget has no selectables, i.e. widget.is_selectable == False.
    """

    if not self.is_selectable:
        raise TypeError(f"Object of type {type(self)} has no selectables.")

    if index is not None:
        index = min(max(0, index), self.selectables_length - 1)
    self.selected_index = index

serialize()

Serializes a widget.

The fields looked at are defined Widget.serialized. Note that this method is not very commonly used at the moment, so it might not have full functionality in non-nuclear widgets.

Returns:

Type Description
dict[str, Any]

Dictionary of widget attributes. The dictionary will always

dict[str, Any]

have a type field. Any styles are converted into markup

dict[str, Any]

strings during serialization, so they can be loaded again in

dict[str, Any]

their original form.

dict[str, Any]

Example return:

dict[str, Any]

``` { "type": "Label", "value": "[210 bold]I am a title", "parent_align": 0, ... }

dict[str, Any]

```

Source code in pytermgui/widgets/base.py
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
def serialize(self) -> dict[str, Any]:
    """Serializes a widget.

    The fields looked at are defined `Widget.serialized`. Note that
    this method is not very commonly used at the moment, so it might
    not have full functionality in non-nuclear widgets.

    Returns:
        Dictionary of widget attributes. The dictionary will always
        have a `type` field. Any styles are converted into markup
        strings during serialization, so they can be loaded again in
        their original form.

        Example return:
        ```
            {
                "type": "Label",
                "value": "[210 bold]I am a title",
                "parent_align": 0,
                ...
            }
        ```
    """

    fields = self._serialized_fields

    out: dict[str, Any] = {"type": type(self).__name__}
    for key in fields:
        # Detect styled values
        if key.startswith("*"):
            style = True
            key = key[1:]
        else:
            style = False

        value = getattr(self, key)

        # Convert styled value into markup
        if style:
            style_call = self._get_style(key)
            if isinstance(value, list):
                out[key] = [get_markup(style_call(char)) for char in value]
            else:
                out[key] = get_markup(style_call(value))

            continue

        out[key] = value

    # The chars need to be handled separately
    out["chars"] = {}
    for key, value in self.chars.items():
        style_call = self._get_style(key)

        if isinstance(value, list):
            out["chars"][key] = [get_markup(style_call(char)) for char in value]
        else:
            out["chars"][key] = get_markup(style_call(value))

    return out

unbind(key)

Unbinds the given key.

Source code in pytermgui/widgets/base.py
619
620
621
622
def unbind(self, key: str) -> None:
    """Unbinds the given key."""

    del self._bindings[key]