Skip to content

frames

Classes to wrap anything that needs a border.

ASCII

Bases: Frame

A frame made up of only ASCII characters.

Preview:

-----
| x |
-----
Source code in pytermgui/widgets/frames.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
class ASCII(Frame):
    """A frame made up of only ASCII characters.

    Preview:

    ```
    -----
    | x |
    -----
    ```
    """

    descriptor = [
        "-----",
        "| x |",
        "-----",
    ]

ASCII_O

Bases: Frame

A frame made up of only ASCII characters, with X-s in the corners.

Preview:

o---o
| x |
o---o
Source code in pytermgui/widgets/frames.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
class ASCII_O(Frame):  # pylint: disable=invalid-name
    """A frame made up of only ASCII characters, with X-s in the corners.

    Preview:

    ```
    o---o
    | x |
    o---o
    ```
    """

    content_char = "x"

    descriptor = [
        "o---o",
        "| x |",
        "o---o",
    ]

ASCII_X

Bases: Frame

A frame made up of only ASCII characters, with X-s in the corners.

Preview:

x---x
| # |
x---x
Source code in pytermgui/widgets/frames.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
class ASCII_X(Frame):  # pylint: disable=invalid-name
    """A frame made up of only ASCII characters, with X-s in the corners.

    Preview:

    ```
    x---x
    | # |
    x---x
    ```
    """

    content_char = "#"

    descriptor = [
        "x---x",
        "| # |",
        "x---x",
    ]

Double

Bases: Frame

A frame with a double outline.

Preview:

╔═══╗
║ x ║
╚═══╝
Source code in pytermgui/widgets/frames.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
class Double(Frame):
    """A frame with a double outline.

    Preview:

    ```
    ╔═══╗
    ║ x ║
    ╚═══╝
    ```
    """

    descriptor = [
        "╔═══╗",
        "║ x ║",
        "╚═══╝",
    ]

Frame

An object that wraps a frame around its parent.

It can be used by any widget in order to draw a 'box' around itself. It implements scrolling as well.

Source code in pytermgui/widgets/frames.py
 26
 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
 78
 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
class Frame:
    """An object that wraps a frame around its parent.

    It can be used by any widget in order to draw a 'box' around itself. It
    implements scrolling as well.
    """

    descriptor: str
    content_char: str = "x"

    # left, top, right, bottom
    borders: tuple[str, str, str, str]

    # left_top, right_top, right_bottom, left_bottom
    corners: tuple[str, str, str, str]

    styles = StyleManager(
        border="surface",
        corner="surface2+2",
    )

    def __init__(self, parent: Widget) -> None:
        """Initializes Frame."""

        self._parent = parent
        self.styles = self.styles.branch(self._parent)

        if self.descriptor is not None:
            self._init_from_descriptor()

    def _init_from_descriptor(self) -> None:
        """Initializes the Frame's border & corner chars from the content property."""

        top, _, bottom = self.descriptor
        top_left, top_right = self._get_corners(top)
        bottom_left, bottom_right = self._get_corners(bottom)

        self.borders = list(self._get_borders(self.descriptor))
        self.corners = [
            top_left,
            top_right,
            bottom_right,
            bottom_left,
        ]

    @staticmethod
    def _find_mode_char(line: str) -> str:
        """Finds the most often consecutively occuring character."""

        instances = 0
        current_char = ""

        results: list[tuple[str, int]] = []
        for char in line:
            if current_char == char:
                instances += 1
            else:
                if len(current_char) > 0:
                    results.append((current_char, instances))

                instances = 1
                current_char = char

        results.append((current_char, instances))

        results.sort(key=lambda item: item[1])
        if len(results) == 0:
            print(line, instances, current_char)

        return results[-1][0]

    def _get_corners(self, line: str) -> tuple[str, str]:
        """Gets corners from a line."""

        mode_char = self._find_mode_char(line)
        left = line[: line.index(mode_char)]
        right = line[real_length(line) - (line[::-1].index(mode_char)) :]

        return left, right

    def _get_borders(self, lines: list[str]) -> tuple[str, str, str, str]:
        """Gets borders from all lines."""

        top, middle, bottom = lines
        middle_reversed = middle[::-1]

        top_border = self._find_mode_char(top)
        left_border = middle[: middle.index(self.content_char)]

        right_border = middle[
            real_length(middle) - middle_reversed.index(self.content_char) :
        ]
        bottom_border = self._find_mode_char(bottom)

        return left_border, top_border, right_border, bottom_border

    @staticmethod
    def from_name(name: str) -> Type[Frame]:
        """Gets a builtin Frame type from its name."""

        if frame := globals().get(name):
            return frame

        raise ValueError(f"No frame defined with name {name!r}.")

    @cached_property
    def left_size(self) -> int:
        """Returns the length of the left border character."""

        return real_length(self.borders[0])

    @cached_property
    def top_size(self) -> int:
        """Returns the height of the top border."""

        return 1

    @cached_property
    def right_size(self) -> int:
        """Returns the length of the right border character."""

        return real_length(self.borders[2])

    @cached_property
    def bottom_size(self) -> int:
        """Returns the height of the bottom border."""

        return 1

    def __call__(self, lines: list[str]) -> list[str]:
        """Frames the given lines, handles scrolling when necessary.

        Args:
            lines: A list of lines to 'frame'. If there are too many
                lines, they are clipped according to the parent's
                `scroll` field.

        Returns:
            Framed lines, clipped to the current scrolling settings.
        """

        if len(self.borders) != 4 or len(self.corners) != 4:
            raise ValueError("Cannot frame with no border or corner values.")

        scroll = self._parent.scroll

        # TODO: Widget.size should substract frame size, once
        #       it is aware of the frame.
        # width, height = self._parent.size
        width, height = self._parent.width, self._parent.height

        lines = lines[scroll.vertical : scroll.vertical + height]

        left_top, right_top, right_bottom, left_bottom = [
            self.styles.corner(corner) for corner in self.corners
        ]

        borders = [self.styles.border(char) for char in self.borders]

        top = (
            left_top
            + (width - real_length(left_top + right_top)) * borders[1]
            + right_top
        )

        bottom = (
            left_bottom
            + (width - real_length(left_bottom + right_bottom)) * borders[3]
            + right_bottom
        )

        framed = []

        if top != "":
            framed.append(top)

        for line in lines:
            # TODO: Implement horizontal scrolling
            framed.append(borders[0] + line + borders[2])

        if bottom != "":
            framed.append(bottom)

        return framed

bottom_size: int cached property

Returns the height of the bottom border.

left_size: int cached property

Returns the length of the left border character.

right_size: int cached property

Returns the length of the right border character.

top_size: int cached property

Returns the height of the top border.

__call__(lines)

Frames the given lines, handles scrolling when necessary.

Parameters:

Name Type Description Default
lines list[str]

A list of lines to 'frame'. If there are too many lines, they are clipped according to the parent's scroll field.

required

Returns:

Type Description
list[str]

Framed lines, clipped to the current scrolling settings.

Source code in pytermgui/widgets/frames.py
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
def __call__(self, lines: list[str]) -> list[str]:
    """Frames the given lines, handles scrolling when necessary.

    Args:
        lines: A list of lines to 'frame'. If there are too many
            lines, they are clipped according to the parent's
            `scroll` field.

    Returns:
        Framed lines, clipped to the current scrolling settings.
    """

    if len(self.borders) != 4 or len(self.corners) != 4:
        raise ValueError("Cannot frame with no border or corner values.")

    scroll = self._parent.scroll

    # TODO: Widget.size should substract frame size, once
    #       it is aware of the frame.
    # width, height = self._parent.size
    width, height = self._parent.width, self._parent.height

    lines = lines[scroll.vertical : scroll.vertical + height]

    left_top, right_top, right_bottom, left_bottom = [
        self.styles.corner(corner) for corner in self.corners
    ]

    borders = [self.styles.border(char) for char in self.borders]

    top = (
        left_top
        + (width - real_length(left_top + right_top)) * borders[1]
        + right_top
    )

    bottom = (
        left_bottom
        + (width - real_length(left_bottom + right_bottom)) * borders[3]
        + right_bottom
    )

    framed = []

    if top != "":
        framed.append(top)

    for line in lines:
        # TODO: Implement horizontal scrolling
        framed.append(borders[0] + line + borders[2])

    if bottom != "":
        framed.append(bottom)

    return framed

__init__(parent)

Initializes Frame.

Source code in pytermgui/widgets/frames.py
47
48
49
50
51
52
53
54
def __init__(self, parent: Widget) -> None:
    """Initializes Frame."""

    self._parent = parent
    self.styles = self.styles.branch(self._parent)

    if self.descriptor is not None:
        self._init_from_descriptor()

from_name(name) staticmethod

Gets a builtin Frame type from its name.

Source code in pytermgui/widgets/frames.py
122
123
124
125
126
127
128
129
@staticmethod
def from_name(name: str) -> Type[Frame]:
    """Gets a builtin Frame type from its name."""

    if frame := globals().get(name):
        return frame

    raise ValueError(f"No frame defined with name {name!r}.")

Frameless

Bases: Frame

A frame that is not. No frame will be drawn around the object.

Preview:

x
Source code in pytermgui/widgets/frames.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class Frameless(Frame):
    """A frame that is not. No frame will be drawn around the object.

    Preview:

    ```

    x

    ```
    """

    descriptor = [
        "",
        "x",
        "",
    ]

Heavy

Bases: Frame

A frame with a heavy outline.

Preview:

┏━━━┓
┃ x ┃
┗━━━┛
Source code in pytermgui/widgets/frames.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
class Heavy(Frame):
    """A frame with a heavy outline.

    Preview:

    ```
    ┏━━━┓
    ┃ x ┃
    ┗━━━┛
    ```
    """

    descriptor = [
        "┏━━━┓",
        "┃ x ┃",
        "┗━━━┛",
    ]

Light

Bases: Frame

A frame with a light outline.

Preview:

┌───┐
│ x │
└───┘
Source code in pytermgui/widgets/frames.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
class Light(Frame):
    """A frame with a light outline.

    Preview:

    ```
    ┌───┐
    │ x │
    └───┘
    ```
    """

    descriptor = [
        "┌───┐",
        "│ x │",
        "└───┘",
    ]

Padded

Bases: Frame

A frame that pads its content by a single space on all sides.

Preview:

x
Source code in pytermgui/widgets/frames.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
class Padded(Frame):
    """A frame that pads its content by a single space on all sides.

    Preview:

    ```
    x
    ```
    """

    descriptor = [
        "   ",
        " x ",
        "   ",
    ]

Rounded

Bases: Frame

A frame with a light outline and rounded corners.

Preview:

╭───╮
│ x │
╰───╯
Source code in pytermgui/widgets/frames.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
class Rounded(Frame):
    """A frame with a light outline and rounded corners.

    Preview:

    ```
    ╭───╮
    │ x │
    ╰───╯
    ```
    """

    descriptor = [
        "╭───╮",
        "│ x │",
        "╰───╯",
    ]