ansinout 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ansinout-1.0.0/.gitignore +10 -0
- ansinout-1.0.0/LICENSE +48 -0
- ansinout-1.0.0/PKG-INFO +280 -0
- ansinout-1.0.0/pyproject.toml +45 -0
- ansinout-1.0.0/readme.md +252 -0
- ansinout-1.0.0/src/ansinout/__init__.py +3 -0
- ansinout-1.0.0/src/ansinout/keyboard.py +63 -0
- ansinout-1.0.0/src/ansinout/screen.py +113 -0
- ansinout-1.0.0/src/ansinout/tui.py +228 -0
ansinout-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
2
|
+
|
|
3
|
+
1. Definitions.
|
|
4
|
+
|
|
5
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
6
|
+
|
|
7
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
8
|
+
|
|
9
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
10
|
+
|
|
11
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
12
|
+
|
|
13
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
14
|
+
|
|
15
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
16
|
+
|
|
17
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
18
|
+
|
|
19
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
20
|
+
|
|
21
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
22
|
+
|
|
23
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
24
|
+
|
|
25
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
26
|
+
|
|
27
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
28
|
+
|
|
29
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
30
|
+
|
|
31
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
32
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
33
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
34
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
35
|
+
|
|
36
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
37
|
+
|
|
38
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
39
|
+
|
|
40
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
41
|
+
|
|
42
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
43
|
+
|
|
44
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
45
|
+
|
|
46
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
47
|
+
|
|
48
|
+
END OF TERMS AND CONDITIONS
|
ansinout-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ansinout
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A dependency-free Python library for building Terminal User Interfaces.
|
|
5
|
+
Author-email: Erin Clemmer <erin.c.clemmer@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: ansi,cli,console,ncurses,terminal,tui
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Operating System :: POSIX
|
|
14
|
+
Classifier: Operating System :: Unix
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Topic :: Terminals
|
|
26
|
+
Requires-Python: >=3.8
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
## ANSINOUT (ANSI + IN + OUT)
|
|
30
|
+
|
|
31
|
+
A small, dependency-free Python library for building Terminal User Interfaces.
|
|
32
|
+
|
|
33
|
+
Ansinout provides a thin layer over raw ANSI escape codes without the weight of a full framework.
|
|
34
|
+
|
|
35
|
+
* **Zero dependencies.** Only uses the standard library.
|
|
36
|
+
* **Keyboard input utils** Easy to use functions for reading user input.
|
|
37
|
+
* **Easy styling** Foreground/background colors and bold are arguments on the text primitive.
|
|
38
|
+
* **Diff-based rendering.** Only cells that have changed since the last frame are written to the terminal.
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
A typical program follows this lifecycle: enter VT mode, build a window, loop on input and repaint, then restore the terminal on exit.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from ansinout import (
|
|
46
|
+
enable_vt_mode, exit_vt_mode,
|
|
47
|
+
TuiWindow, TuiText, TermText,
|
|
48
|
+
read_key, key_available, PressedKey,
|
|
49
|
+
Color, BgColor,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
fd, attrs = enable_vt_mode()
|
|
53
|
+
try:
|
|
54
|
+
win = TuiWindow(size=(40, 10), pos=(0, 0))
|
|
55
|
+
hello = win.add_text(TermText("Hello, world!", fg=Color.Cyan), pos=(0, 0))
|
|
56
|
+
win.paint()
|
|
57
|
+
|
|
58
|
+
while True:
|
|
59
|
+
if key_available(0.05):
|
|
60
|
+
key, raw = read_key()
|
|
61
|
+
if key == PressedKey.Escape:
|
|
62
|
+
break
|
|
63
|
+
win.paint()
|
|
64
|
+
finally:
|
|
65
|
+
exit_vt_mode(fd, attrs)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Screen lifecycle
|
|
69
|
+
|
|
70
|
+
#### `enable_vt_mode() -> (fd, old_attrs)`
|
|
71
|
+
|
|
72
|
+
Prepares the terminal for interactive use. The function captures the current termios attributes of standard input, switches the input file descriptor into cbreak mode so that key presses are delivered without line buffering, enters the alternate screen buffer, clears it, and moves the cursor to the home position. It returns a tuple containing the standard input file descriptor and the original termios attributes, which must be retained and passed to `exit_vt_mode` during shutdown.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
fd, attrs = enable_vt_mode()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
#### `exit_vt_mode(fd, old_attrs)`
|
|
79
|
+
|
|
80
|
+
Restores the terminal to the state it was in before `enable_vt_mode` was called. The function leaves the alternate screen buffer, returning the terminal to the primary screen, and restores the original termios attributes captured by `enable_vt_mode`. The `fd` and `old_attrs` arguments must be the values returned from that call. It should typically be invoked inside a `finally` block to ensure the terminal is restored regardless of how the program exits.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
exit_vt_mode(fd, attrs)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### TUI building blocks
|
|
87
|
+
|
|
88
|
+
#### `TermText(value, fg=None, bg=None, bold=False)`
|
|
89
|
+
|
|
90
|
+
A `TermText` pairs a string with an optional foreground color, an optional background color, and a bold flag. It is accepted by every TUI primitive that renders text. The styling applies uniformly to the entire string.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
title = TermText("Inbox", fg=Color.White, bg=BgColor.Blue, bold=True)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
#### `TuiText`
|
|
97
|
+
|
|
98
|
+
The object returned by `TuiWindow.get_text`. It wraps a `TermText` value together with an `id`, a `position`, a derived `size`, and a `hidden` flag. Instances are created by `TuiWindow.add_text` rather than constructed directly.
|
|
99
|
+
|
|
100
|
+
#### `TuiWindow(size, pos)`
|
|
101
|
+
|
|
102
|
+
The main container. A `TuiWindow` owns a grid of cells with dimensions equal to `size` and a list of `TuiText` objects positioned within it. The window itself is anchored at `pos`, which is interpreted as an absolute `(column, row)` offset in the terminal. All `TuiText` positions are relative to the window's anchor.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
win = TuiWindow(size=(80, 24), pos=(0, 0))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
##### `add_text(value, pos) -> int`
|
|
109
|
+
|
|
110
|
+
Adds a `TermText` to the window at the given relative `(column, row)` position and returns an integer id. The id is used by every other method that operates on a specific text object.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
tid = win.add_text(TermText("Press Esc to quit", fg=Color.Gray), pos=(0, 23))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
##### `update_text(id, value, pos=None)`
|
|
117
|
+
|
|
118
|
+
Replaces the contents and/or position of an existing text object. If `value` is `None`, the existing text is preserved and only the position is changed. If `pos` is `None`, the position is preserved. Cells previously occupied by the old text are cleared so the next `paint()` removes any stale characters.
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
win.update_text(tid, TermText("Bye!", fg=Color.Red))
|
|
122
|
+
win.update_text(tid, None, pos=(10, 5))
|
|
123
|
+
win.update_text(tid, TermText("Hi"), (0, 0))
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
##### `get_text(id) -> TuiText`
|
|
127
|
+
|
|
128
|
+
Returns the underlying `TuiText` instance for the given id or `None` if not found.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
obj = win.get_text(tid)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
##### `hide_txt(id)` and `show_txt(id)`
|
|
135
|
+
|
|
136
|
+
`hide_txt` marks the text object as hidden and clears the cells it currently occupies so the next paint erases it from the terminal. The text object and its id remain in the window and can be redisplayed with `show_txt`, which clears the hidden flag and rewrites the text into the grid.
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
win.hide_txt(tid)
|
|
140
|
+
win.show_txt(tid)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
##### `hide_all()` and `show_all()`
|
|
144
|
+
|
|
145
|
+
Hide or show every text object currently in the window.
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
win.hide_all()
|
|
149
|
+
win.show_all()
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
##### `remove_txt(id)` and `remove_all()`
|
|
153
|
+
|
|
154
|
+
`remove_txt` clears the cells occupied by the text object and removes it from the window's text list. `remove_all` performs the same operation for every text object in the window.
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
win.remove_txt(tid)
|
|
158
|
+
win.remove_all()
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
##### `update_position(pos)`
|
|
162
|
+
|
|
163
|
+
Moves the window to a new absolute `(column, row)` anchor. The function hides all currently visible text objects, paints the cleared state to remove the old rendering, updates the anchor, and restores visibility at the new location.
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
win.update_position((5, 2))
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
##### `clear_screen()`
|
|
170
|
+
|
|
171
|
+
Replaces every cell in the window's grid with a space. This stages a full erase that takes effect on the next `paint()`. It does not remove text objects from the window.
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
win.clear_screen()
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
##### `paint()`
|
|
178
|
+
|
|
179
|
+
Flushes pending changes to the terminal. The method walks the grid and writes only the cells whose contents differ from what was last painted, then returns the cursor to the origin. Because the operation is incremental, `paint()` is safe to call in a tight render loop.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
win.paint()
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Keyboard input
|
|
186
|
+
|
|
187
|
+
#### `key_available(timeout=0.0) -> bool`
|
|
188
|
+
|
|
189
|
+
Reports whether standard input has data ready to be read. The call blocks for at most `timeout` seconds and returns `True` as soon as input becomes available, or `False` if the timeout elapses first. A timeout of `0.0` performs a non-blocking poll. The function is typically used in a render loop to wait briefly for input without preventing periodic repaints.
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
if key_available(0.05):
|
|
193
|
+
key, raw = read_key()
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
#### `read_key() -> (PressedKey, str)`
|
|
197
|
+
|
|
198
|
+
Reads a single key press from standard input and returns a tuple of `(PressedKey, raw)`, where `PressedKey` is the categorized key and `raw` is the underlying byte sequence as a string. The function handles multi-byte escape sequences for the arrow keys and the Delete key, and distinguishes a bare Escape press from the start of an escape sequence by waiting briefly for continuation bytes. Unknown escape sequences are reported as `PressedKey.Nop` with the full received sequence as the raw value.
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
key, raw = read_key()
|
|
202
|
+
if key == PressedKey.Alpha:
|
|
203
|
+
buffer += raw
|
|
204
|
+
elif key == PressedKey.Backspace:
|
|
205
|
+
buffer = buffer[:-1]
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
#### `PressedKey`
|
|
209
|
+
|
|
210
|
+
An enumeration of the key categories produced by `read_key`. The members are `Alpha`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `Backspace`, `Enter`, `Escape`, `Delete`, and `Nop`. The `Alpha` category covers letters, digits, and a set of punctuation characters (`_`, `-`, `.`, `/`, `\`, and `:`). Bytes that do not match any recognized category are reported as `Nop`.
|
|
211
|
+
|
|
212
|
+
### Cursor functions
|
|
213
|
+
|
|
214
|
+
#### `move_cursor(row, col)`
|
|
215
|
+
|
|
216
|
+
Moves the terminal cursor to the given zero-based `(row, col)` position without writing any text. The function is useful for placing the cursor after a series of direct writes, or for positioning a visible cursor over an input field. Errors raised while writing the escape sequence are suppressed.
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
move_cursor(0, 0)
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
#### `change_cursor(cursor_type)`
|
|
223
|
+
|
|
224
|
+
Changes the shape of the terminal cursor. The `cursor_type` argument is a member of the `CursorTypes` enumeration, which defines six shapes: `Default`, `Blinking_Block`, `Steady_Block`, `Blinking_Underline`, `Steady_Underline`, `Blinking_Bar`, and `Steady_Bar`. The effect persists until the next call to `change_cursor` or until the terminal is reset.
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
from ansinout.screen import CursorTypes, change_cursor
|
|
228
|
+
change_cursor(CursorTypes.Steady_Bar)
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Direct drawing
|
|
232
|
+
|
|
233
|
+
#### `print_pos(row, col, s, fg=None, bg=None, bold=False)`
|
|
234
|
+
|
|
235
|
+
Writes the string `s` at the given zero-based `(row, col)` position. The function emits the ANSI cursor-positioning sequence followed by the styled text and flushes standard output. Coordinates are translated to the terminal's one-based addressing internally, so the caller should pass zero-based values. Styling arguments behave as on `TermText`: omitting `fg`, `bg`, and `bold` produces unstyled output.
|
|
236
|
+
|
|
237
|
+
```python
|
|
238
|
+
print_pos(2, 5, "status: ok", fg=Color.Green, bold=True)
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
### Colors
|
|
243
|
+
|
|
244
|
+
#### `Color` and `BgColor`
|
|
245
|
+
|
|
246
|
+
Enumerations of the sixteen standard ANSI color codes for foreground and background respectively. Each enum covers the eight base colors and their eight bright variants, along with a `Default` member that maps to the terminal's configured default. The two enums are kept distinct so that the type system can prevent a background color from being passed where a foreground color is expected. Values are accepted by `TermText`, `print_pos`, and any other function that takes `fg` or `bg` arguments.
|
|
247
|
+
|
|
248
|
+
```python
|
|
249
|
+
TermText("warning", fg=Color.BrightYellow, bg=BgColor.Black, bold=True)
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
#### Standard colors
|
|
253
|
+
|
|
254
|
+
| Name | ANSI (fg) | ANSI (bg) |
|
|
255
|
+
| --- | --- | --- |
|
|
256
|
+
| `Black` | 30 | 40 |
|
|
257
|
+
| `Red` | 31 | 41 |
|
|
258
|
+
| `Green` | 32 | 42 |
|
|
259
|
+
| `Yellow` | 33 | 43 |
|
|
260
|
+
| `Blue` | 34 | 44 |
|
|
261
|
+
| `Magenta` | 35 | 45 |
|
|
262
|
+
| `Cyan` | 36 | 46 |
|
|
263
|
+
| `White` | 37 | 47 |
|
|
264
|
+
| `Default` | 39 | 49 |
|
|
265
|
+
|
|
266
|
+
#### Bright colors
|
|
267
|
+
|
|
268
|
+
| Name | ANSI (fg) | ANSI (bg) |
|
|
269
|
+
| --- | --- | --- |
|
|
270
|
+
| `BrightBlack` | 90 | 100 |
|
|
271
|
+
| `Gray` | 90 | 100 |
|
|
272
|
+
| `BrightRed` | 91 | 101 |
|
|
273
|
+
| `BrightGreen` | 92 | 102 |
|
|
274
|
+
| `BrightYellow` | 93 | 103 |
|
|
275
|
+
| `BrightBlue` | 94 | 104 |
|
|
276
|
+
| `BrightMagenta` | 95 | 105 |
|
|
277
|
+
| `BrightCyan` | 96 | 106 |
|
|
278
|
+
| `BrightWhite` | 97 | 107 |
|
|
279
|
+
|
|
280
|
+
`Gray` is an alias for `BrightBlack`. The exact rendering of each color is determined by the terminal's color scheme.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ansinout"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "A dependency-free Python library for building Terminal User Interfaces."
|
|
9
|
+
readme = "readme.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Erin Clemmer", email = "erin.c.clemmer@gmail.com" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["tui", "terminal", "ansi", "console", "cli", "ncurses"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 5 - Production/Stable",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: POSIX",
|
|
21
|
+
"Operating System :: MacOS",
|
|
22
|
+
"Operating System :: Unix",
|
|
23
|
+
"Programming Language :: Python",
|
|
24
|
+
"Programming Language :: Python :: 3",
|
|
25
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
26
|
+
"Programming Language :: Python :: 3.8",
|
|
27
|
+
"Programming Language :: Python :: 3.9",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Programming Language :: Python :: 3.13",
|
|
32
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
33
|
+
"Topic :: Terminals",
|
|
34
|
+
"Environment :: Console",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/ansinout"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.sdist]
|
|
41
|
+
include = [
|
|
42
|
+
"src/ansinout",
|
|
43
|
+
"readme.md",
|
|
44
|
+
"LICENSE",
|
|
45
|
+
]
|
ansinout-1.0.0/readme.md
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
## ANSINOUT (ANSI + IN + OUT)
|
|
2
|
+
|
|
3
|
+
A small, dependency-free Python library for building Terminal User Interfaces.
|
|
4
|
+
|
|
5
|
+
Ansinout provides a thin layer over raw ANSI escape codes without the weight of a full framework.
|
|
6
|
+
|
|
7
|
+
* **Zero dependencies.** Only uses the standard library.
|
|
8
|
+
* **Keyboard input utils** Easy to use functions for reading user input.
|
|
9
|
+
* **Easy styling** Foreground/background colors and bold are arguments on the text primitive.
|
|
10
|
+
* **Diff-based rendering.** Only cells that have changed since the last frame are written to the terminal.
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
A typical program follows this lifecycle: enter VT mode, build a window, loop on input and repaint, then restore the terminal on exit.
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from ansinout import (
|
|
18
|
+
enable_vt_mode, exit_vt_mode,
|
|
19
|
+
TuiWindow, TuiText, TermText,
|
|
20
|
+
read_key, key_available, PressedKey,
|
|
21
|
+
Color, BgColor,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
fd, attrs = enable_vt_mode()
|
|
25
|
+
try:
|
|
26
|
+
win = TuiWindow(size=(40, 10), pos=(0, 0))
|
|
27
|
+
hello = win.add_text(TermText("Hello, world!", fg=Color.Cyan), pos=(0, 0))
|
|
28
|
+
win.paint()
|
|
29
|
+
|
|
30
|
+
while True:
|
|
31
|
+
if key_available(0.05):
|
|
32
|
+
key, raw = read_key()
|
|
33
|
+
if key == PressedKey.Escape:
|
|
34
|
+
break
|
|
35
|
+
win.paint()
|
|
36
|
+
finally:
|
|
37
|
+
exit_vt_mode(fd, attrs)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Screen lifecycle
|
|
41
|
+
|
|
42
|
+
#### `enable_vt_mode() -> (fd, old_attrs)`
|
|
43
|
+
|
|
44
|
+
Prepares the terminal for interactive use. The function captures the current termios attributes of standard input, switches the input file descriptor into cbreak mode so that key presses are delivered without line buffering, enters the alternate screen buffer, clears it, and moves the cursor to the home position. It returns a tuple containing the standard input file descriptor and the original termios attributes, which must be retained and passed to `exit_vt_mode` during shutdown.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
fd, attrs = enable_vt_mode()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
#### `exit_vt_mode(fd, old_attrs)`
|
|
51
|
+
|
|
52
|
+
Restores the terminal to the state it was in before `enable_vt_mode` was called. The function leaves the alternate screen buffer, returning the terminal to the primary screen, and restores the original termios attributes captured by `enable_vt_mode`. The `fd` and `old_attrs` arguments must be the values returned from that call. It should typically be invoked inside a `finally` block to ensure the terminal is restored regardless of how the program exits.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
exit_vt_mode(fd, attrs)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### TUI building blocks
|
|
59
|
+
|
|
60
|
+
#### `TermText(value, fg=None, bg=None, bold=False)`
|
|
61
|
+
|
|
62
|
+
A `TermText` pairs a string with an optional foreground color, an optional background color, and a bold flag. It is accepted by every TUI primitive that renders text. The styling applies uniformly to the entire string.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
title = TermText("Inbox", fg=Color.White, bg=BgColor.Blue, bold=True)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
#### `TuiText`
|
|
69
|
+
|
|
70
|
+
The object returned by `TuiWindow.get_text`. It wraps a `TermText` value together with an `id`, a `position`, a derived `size`, and a `hidden` flag. Instances are created by `TuiWindow.add_text` rather than constructed directly.
|
|
71
|
+
|
|
72
|
+
#### `TuiWindow(size, pos)`
|
|
73
|
+
|
|
74
|
+
The main container. A `TuiWindow` owns a grid of cells with dimensions equal to `size` and a list of `TuiText` objects positioned within it. The window itself is anchored at `pos`, which is interpreted as an absolute `(column, row)` offset in the terminal. All `TuiText` positions are relative to the window's anchor.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
win = TuiWindow(size=(80, 24), pos=(0, 0))
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
##### `add_text(value, pos) -> int`
|
|
81
|
+
|
|
82
|
+
Adds a `TermText` to the window at the given relative `(column, row)` position and returns an integer id. The id is used by every other method that operates on a specific text object.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
tid = win.add_text(TermText("Press Esc to quit", fg=Color.Gray), pos=(0, 23))
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
##### `update_text(id, value, pos=None)`
|
|
89
|
+
|
|
90
|
+
Replaces the contents and/or position of an existing text object. If `value` is `None`, the existing text is preserved and only the position is changed. If `pos` is `None`, the position is preserved. Cells previously occupied by the old text are cleared so the next `paint()` removes any stale characters.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
win.update_text(tid, TermText("Bye!", fg=Color.Red))
|
|
94
|
+
win.update_text(tid, None, pos=(10, 5))
|
|
95
|
+
win.update_text(tid, TermText("Hi"), (0, 0))
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
##### `get_text(id) -> TuiText`
|
|
99
|
+
|
|
100
|
+
Returns the underlying `TuiText` instance for the given id or `None` if not found.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
obj = win.get_text(tid)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
##### `hide_txt(id)` and `show_txt(id)`
|
|
107
|
+
|
|
108
|
+
`hide_txt` marks the text object as hidden and clears the cells it currently occupies so the next paint erases it from the terminal. The text object and its id remain in the window and can be redisplayed with `show_txt`, which clears the hidden flag and rewrites the text into the grid.
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
win.hide_txt(tid)
|
|
112
|
+
win.show_txt(tid)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
##### `hide_all()` and `show_all()`
|
|
116
|
+
|
|
117
|
+
Hide or show every text object currently in the window.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
win.hide_all()
|
|
121
|
+
win.show_all()
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
##### `remove_txt(id)` and `remove_all()`
|
|
125
|
+
|
|
126
|
+
`remove_txt` clears the cells occupied by the text object and removes it from the window's text list. `remove_all` performs the same operation for every text object in the window.
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
win.remove_txt(tid)
|
|
130
|
+
win.remove_all()
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
##### `update_position(pos)`
|
|
134
|
+
|
|
135
|
+
Moves the window to a new absolute `(column, row)` anchor. The function hides all currently visible text objects, paints the cleared state to remove the old rendering, updates the anchor, and restores visibility at the new location.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
win.update_position((5, 2))
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
##### `clear_screen()`
|
|
142
|
+
|
|
143
|
+
Replaces every cell in the window's grid with a space. This stages a full erase that takes effect on the next `paint()`. It does not remove text objects from the window.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
win.clear_screen()
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
##### `paint()`
|
|
150
|
+
|
|
151
|
+
Flushes pending changes to the terminal. The method walks the grid and writes only the cells whose contents differ from what was last painted, then returns the cursor to the origin. Because the operation is incremental, `paint()` is safe to call in a tight render loop.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
win.paint()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Keyboard input
|
|
158
|
+
|
|
159
|
+
#### `key_available(timeout=0.0) -> bool`
|
|
160
|
+
|
|
161
|
+
Reports whether standard input has data ready to be read. The call blocks for at most `timeout` seconds and returns `True` as soon as input becomes available, or `False` if the timeout elapses first. A timeout of `0.0` performs a non-blocking poll. The function is typically used in a render loop to wait briefly for input without preventing periodic repaints.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
if key_available(0.05):
|
|
165
|
+
key, raw = read_key()
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
#### `read_key() -> (PressedKey, str)`
|
|
169
|
+
|
|
170
|
+
Reads a single key press from standard input and returns a tuple of `(PressedKey, raw)`, where `PressedKey` is the categorized key and `raw` is the underlying byte sequence as a string. The function handles multi-byte escape sequences for the arrow keys and the Delete key, and distinguishes a bare Escape press from the start of an escape sequence by waiting briefly for continuation bytes. Unknown escape sequences are reported as `PressedKey.Nop` with the full received sequence as the raw value.
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
key, raw = read_key()
|
|
174
|
+
if key == PressedKey.Alpha:
|
|
175
|
+
buffer += raw
|
|
176
|
+
elif key == PressedKey.Backspace:
|
|
177
|
+
buffer = buffer[:-1]
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
#### `PressedKey`
|
|
181
|
+
|
|
182
|
+
An enumeration of the key categories produced by `read_key`. The members are `Alpha`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `Backspace`, `Enter`, `Escape`, `Delete`, and `Nop`. The `Alpha` category covers letters, digits, and a set of punctuation characters (`_`, `-`, `.`, `/`, `\`, and `:`). Bytes that do not match any recognized category are reported as `Nop`.
|
|
183
|
+
|
|
184
|
+
### Cursor functions
|
|
185
|
+
|
|
186
|
+
#### `move_cursor(row, col)`
|
|
187
|
+
|
|
188
|
+
Moves the terminal cursor to the given zero-based `(row, col)` position without writing any text. The function is useful for placing the cursor after a series of direct writes, or for positioning a visible cursor over an input field. Errors raised while writing the escape sequence are suppressed.
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
move_cursor(0, 0)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
#### `change_cursor(cursor_type)`
|
|
195
|
+
|
|
196
|
+
Changes the shape of the terminal cursor. The `cursor_type` argument is a member of the `CursorTypes` enumeration, which defines six shapes: `Default`, `Blinking_Block`, `Steady_Block`, `Blinking_Underline`, `Steady_Underline`, `Blinking_Bar`, and `Steady_Bar`. The effect persists until the next call to `change_cursor` or until the terminal is reset.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from ansinout.screen import CursorTypes, change_cursor
|
|
200
|
+
change_cursor(CursorTypes.Steady_Bar)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Direct drawing
|
|
204
|
+
|
|
205
|
+
#### `print_pos(row, col, s, fg=None, bg=None, bold=False)`
|
|
206
|
+
|
|
207
|
+
Writes the string `s` at the given zero-based `(row, col)` position. The function emits the ANSI cursor-positioning sequence followed by the styled text and flushes standard output. Coordinates are translated to the terminal's one-based addressing internally, so the caller should pass zero-based values. Styling arguments behave as on `TermText`: omitting `fg`, `bg`, and `bold` produces unstyled output.
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
print_pos(2, 5, "status: ok", fg=Color.Green, bold=True)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
### Colors
|
|
215
|
+
|
|
216
|
+
#### `Color` and `BgColor`
|
|
217
|
+
|
|
218
|
+
Enumerations of the sixteen standard ANSI color codes for foreground and background respectively. Each enum covers the eight base colors and their eight bright variants, along with a `Default` member that maps to the terminal's configured default. The two enums are kept distinct so that the type system can prevent a background color from being passed where a foreground color is expected. Values are accepted by `TermText`, `print_pos`, and any other function that takes `fg` or `bg` arguments.
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
TermText("warning", fg=Color.BrightYellow, bg=BgColor.Black, bold=True)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
#### Standard colors
|
|
225
|
+
|
|
226
|
+
| Name | ANSI (fg) | ANSI (bg) |
|
|
227
|
+
| --- | --- | --- |
|
|
228
|
+
| `Black` | 30 | 40 |
|
|
229
|
+
| `Red` | 31 | 41 |
|
|
230
|
+
| `Green` | 32 | 42 |
|
|
231
|
+
| `Yellow` | 33 | 43 |
|
|
232
|
+
| `Blue` | 34 | 44 |
|
|
233
|
+
| `Magenta` | 35 | 45 |
|
|
234
|
+
| `Cyan` | 36 | 46 |
|
|
235
|
+
| `White` | 37 | 47 |
|
|
236
|
+
| `Default` | 39 | 49 |
|
|
237
|
+
|
|
238
|
+
#### Bright colors
|
|
239
|
+
|
|
240
|
+
| Name | ANSI (fg) | ANSI (bg) |
|
|
241
|
+
| --- | --- | --- |
|
|
242
|
+
| `BrightBlack` | 90 | 100 |
|
|
243
|
+
| `Gray` | 90 | 100 |
|
|
244
|
+
| `BrightRed` | 91 | 101 |
|
|
245
|
+
| `BrightGreen` | 92 | 102 |
|
|
246
|
+
| `BrightYellow` | 93 | 103 |
|
|
247
|
+
| `BrightBlue` | 94 | 104 |
|
|
248
|
+
| `BrightMagenta` | 95 | 105 |
|
|
249
|
+
| `BrightCyan` | 96 | 106 |
|
|
250
|
+
| `BrightWhite` | 97 | 107 |
|
|
251
|
+
|
|
252
|
+
`Gray` is an alias for `BrightBlack`. The exact rendering of each color is determined by the terminal's color scheme.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import os
|
|
3
|
+
import select
|
|
4
|
+
from typing import Tuple
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
def key_available(timeout: float = 0.0):
|
|
8
|
+
rlist, _, _ = select.select([sys.stdin.fileno()], [], [], timeout)
|
|
9
|
+
return bool(rlist)
|
|
10
|
+
|
|
11
|
+
class PressedKey(Enum):
|
|
12
|
+
Alpha = "Alpha"
|
|
13
|
+
ArrowUp = "ArrowUp"
|
|
14
|
+
ArrowDown = "ArrowDown"
|
|
15
|
+
ArrowLeft = "ArrowLeft"
|
|
16
|
+
ArrowRight = "ArrowRight"
|
|
17
|
+
Backspace = "Backspace"
|
|
18
|
+
Enter = "Enter"
|
|
19
|
+
Escape = "Escape"
|
|
20
|
+
Delete = "Delete"
|
|
21
|
+
Nop = "Nop"
|
|
22
|
+
|
|
23
|
+
def _read_byte() -> str:
|
|
24
|
+
data = os.read(sys.stdin.fileno(), 1)
|
|
25
|
+
return data.decode("utf-8", errors="ignore") if data else ""
|
|
26
|
+
|
|
27
|
+
def read_key() -> Tuple[PressedKey, str]:
|
|
28
|
+
accepted_chars = ["_", "-", ".", "/", "\\", ":"]
|
|
29
|
+
ch = _read_byte()
|
|
30
|
+
if ch.isalpha() or ch.isnumeric() or ch in accepted_chars:
|
|
31
|
+
return PressedKey.Alpha, ch
|
|
32
|
+
if ch == "\n" or ch == "\r":
|
|
33
|
+
return PressedKey.Enter, ch
|
|
34
|
+
if ch == "\x7f":
|
|
35
|
+
return PressedKey.Backspace, ch
|
|
36
|
+
if ch == "\x1b":
|
|
37
|
+
# Distinguish bare Escape from escape sequences (arrows/delete/etc.)
|
|
38
|
+
# by waiting briefly for continuation bytes.
|
|
39
|
+
if not key_available(0.02):
|
|
40
|
+
return PressedKey.Escape, ch
|
|
41
|
+
|
|
42
|
+
seq = ""
|
|
43
|
+
# Read a short sequence like "[A" or "[3~".
|
|
44
|
+
while key_available(0.001) and len(seq) < 8:
|
|
45
|
+
seq += _read_byte()
|
|
46
|
+
# Common final bytes for CSI key sequences.
|
|
47
|
+
if seq and (seq[-1].isalpha() or seq[-1] == "~"):
|
|
48
|
+
break
|
|
49
|
+
|
|
50
|
+
if seq == "[A":
|
|
51
|
+
return PressedKey.ArrowUp, seq
|
|
52
|
+
if seq == "[B":
|
|
53
|
+
return PressedKey.ArrowDown, seq
|
|
54
|
+
if seq == "[D":
|
|
55
|
+
return PressedKey.ArrowLeft, seq
|
|
56
|
+
if seq == "[C":
|
|
57
|
+
return PressedKey.ArrowRight, seq
|
|
58
|
+
if seq == "[3~":
|
|
59
|
+
return PressedKey.Delete, seq
|
|
60
|
+
|
|
61
|
+
# Fallback: unknown escape sequence acts as Escape.
|
|
62
|
+
return PressedKey.Nop, seq
|
|
63
|
+
return PressedKey.Nop, ""
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import termios
|
|
3
|
+
import tty
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
ESC = "\x1b["
|
|
8
|
+
ALT_SCR_ENTER = f"{ESC}?1049h"
|
|
9
|
+
ALT_SCR_EXIT = f"{ESC}?1049l"
|
|
10
|
+
CLS = f"{ESC}2J"
|
|
11
|
+
HOME = f"{ESC}H"
|
|
12
|
+
|
|
13
|
+
def write(s: str):
|
|
14
|
+
sys.stdout.write(s)
|
|
15
|
+
sys.stdout.flush()
|
|
16
|
+
|
|
17
|
+
def enable_vt_mode():
|
|
18
|
+
fd_in = sys.stdin.fileno()
|
|
19
|
+
old_in_attrs = termios.tcgetattr(fd_in)
|
|
20
|
+
tty.setcbreak(fd_in)
|
|
21
|
+
write(ALT_SCR_ENTER + CLS + HOME)
|
|
22
|
+
return (fd_in, old_in_attrs)
|
|
23
|
+
|
|
24
|
+
def exit_vt_mode(fd_in, old_in_attrs):
|
|
25
|
+
write(ALT_SCR_EXIT)
|
|
26
|
+
termios.tcsetattr(fd_in, termios.TCSADRAIN, old_in_attrs)
|
|
27
|
+
|
|
28
|
+
def print_pos(row: int, col: int, s: str, fg: Optional['Color'] = None, bg: Optional['BgColor'] = None, bold: bool = False):
|
|
29
|
+
# ANSI positions are 1-based
|
|
30
|
+
s = color(s, fg, bg, bold)
|
|
31
|
+
write(f"{ESC}{row + 1};{col + 1}H{s}")
|
|
32
|
+
|
|
33
|
+
def move_cursor(row: int, col: int):
|
|
34
|
+
try:
|
|
35
|
+
write(f"{ESC}{row + 1};{col + 1}H")
|
|
36
|
+
except Exception:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
class CursorTypes(Enum):
|
|
40
|
+
Default = 1
|
|
41
|
+
Blinking_Block = 1
|
|
42
|
+
Steady_Block = 2
|
|
43
|
+
Blinking_Underline = 3
|
|
44
|
+
Steady_Underline = 4
|
|
45
|
+
Blinking_Bar = 5
|
|
46
|
+
Steady_Bar = 6
|
|
47
|
+
|
|
48
|
+
def change_cursor(t: CursorTypes):
|
|
49
|
+
write(f"\033[{t.value} q")
|
|
50
|
+
|
|
51
|
+
class Color(Enum):
|
|
52
|
+
# Standard foreground colors (30-37)
|
|
53
|
+
Black = 30
|
|
54
|
+
Red = 31
|
|
55
|
+
Green = 32
|
|
56
|
+
Yellow = 33
|
|
57
|
+
Blue = 34
|
|
58
|
+
Magenta = 35
|
|
59
|
+
Cyan = 36
|
|
60
|
+
White = 37
|
|
61
|
+
Default = 39
|
|
62
|
+
# Bright foreground colors (90-97)
|
|
63
|
+
BrightBlack = 90
|
|
64
|
+
Gray = 90
|
|
65
|
+
BrightRed = 91
|
|
66
|
+
BrightGreen = 92
|
|
67
|
+
BrightYellow = 93
|
|
68
|
+
BrightBlue = 94
|
|
69
|
+
BrightMagenta = 95
|
|
70
|
+
BrightCyan = 96
|
|
71
|
+
BrightWhite = 97
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class BgColor(Enum):
|
|
75
|
+
# Standard background colors (40-47)
|
|
76
|
+
Black = 40
|
|
77
|
+
Red = 41
|
|
78
|
+
Green = 42
|
|
79
|
+
Yellow = 43
|
|
80
|
+
Blue = 44
|
|
81
|
+
Magenta = 45
|
|
82
|
+
Cyan = 46
|
|
83
|
+
White = 47
|
|
84
|
+
Default = 49
|
|
85
|
+
# Bright background colors (100-107)
|
|
86
|
+
BrightBlack = 100
|
|
87
|
+
Gray = 100
|
|
88
|
+
BrightRed = 101
|
|
89
|
+
BrightGreen = 102
|
|
90
|
+
BrightYellow = 103
|
|
91
|
+
BrightBlue = 104
|
|
92
|
+
BrightMagenta = 105
|
|
93
|
+
BrightCyan = 106
|
|
94
|
+
BrightWhite = 107
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def color(text: str, fg: Optional[Color] = None, bg: Optional[BgColor] = None, bold: bool = False) -> str:
|
|
98
|
+
codes = []
|
|
99
|
+
if bold:
|
|
100
|
+
codes.append("1")
|
|
101
|
+
|
|
102
|
+
if isinstance(fg, Color):
|
|
103
|
+
codes.append(str(fg.value))
|
|
104
|
+
|
|
105
|
+
if isinstance(bg, BgColor):
|
|
106
|
+
codes.append(str(bg.value))
|
|
107
|
+
|
|
108
|
+
if len(codes) == 0:
|
|
109
|
+
return text
|
|
110
|
+
|
|
111
|
+
prefix = f"\033[{';'.join(codes)}m"
|
|
112
|
+
reset = "\033[0m"
|
|
113
|
+
return f"{prefix}{text}{reset}"
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
from typing import List, Tuple, Optional
|
|
2
|
+
from ansinout.screen import print_pos, Color, BgColor
|
|
3
|
+
|
|
4
|
+
class TermText:
|
|
5
|
+
value: str
|
|
6
|
+
fg: Optional[Color]
|
|
7
|
+
bg: Optional[BgColor]
|
|
8
|
+
bold: bool
|
|
9
|
+
|
|
10
|
+
def __init__(self, v: str, fg: Optional[Color] = None, bg: Optional[BgColor] = None, bold: bool = False):
|
|
11
|
+
self.value = v
|
|
12
|
+
self.fg = fg
|
|
13
|
+
self.bg = bg
|
|
14
|
+
self.bold = bold
|
|
15
|
+
|
|
16
|
+
class TuiCell:
|
|
17
|
+
text: TermText
|
|
18
|
+
last_paint_ch: str
|
|
19
|
+
|
|
20
|
+
position: Tuple[int, int]
|
|
21
|
+
committed: bool
|
|
22
|
+
|
|
23
|
+
def __init__(self, v: TermText, pos: Tuple[int, int]):
|
|
24
|
+
self.text = v
|
|
25
|
+
self.position = pos
|
|
26
|
+
self.committed = True
|
|
27
|
+
self.last_paint_ch = v.value
|
|
28
|
+
|
|
29
|
+
def set_value(self, tt: TermText):
|
|
30
|
+
if not isinstance(tt, TermText):
|
|
31
|
+
raise Exception(f"Tried to set cell value for non string {tt}")
|
|
32
|
+
if len(tt.value) > 1:
|
|
33
|
+
raise Exception("Tried to set cell with more than one character")
|
|
34
|
+
if tt.value == self.text.value:
|
|
35
|
+
return
|
|
36
|
+
self.text = tt
|
|
37
|
+
self.committed = tt.value == self.last_paint_ch
|
|
38
|
+
|
|
39
|
+
def paint(self, abs_position: Tuple[int, int]):
|
|
40
|
+
if self.committed:
|
|
41
|
+
return
|
|
42
|
+
print_pos(abs_position[1], abs_position[0], self.text.value, self.text.fg, self.text.bg, self.text.bold)
|
|
43
|
+
self.committed = True
|
|
44
|
+
self.last_paint_ch = self.text.value
|
|
45
|
+
|
|
46
|
+
class TuiGrid:
|
|
47
|
+
size: Tuple[int, int]
|
|
48
|
+
position: Tuple[int, int]
|
|
49
|
+
grid: List[List[TuiCell]]
|
|
50
|
+
|
|
51
|
+
def __init__(self, size: Tuple[int, int], pos: Tuple[int, int]):
|
|
52
|
+
self.size = size
|
|
53
|
+
self.position = pos
|
|
54
|
+
self.grid = []
|
|
55
|
+
for x in range(0, self.size[0]):
|
|
56
|
+
rows = []
|
|
57
|
+
for y in range(0, self.size[1]):
|
|
58
|
+
rows.append(TuiCell(TermText(""), (x, y)))
|
|
59
|
+
self.grid.append(rows)
|
|
60
|
+
|
|
61
|
+
def set_cell(self, pos: Tuple[int, int], tt: TermText):
|
|
62
|
+
if pos[0] > self.size[0] or pos[1] > self.size[1]:
|
|
63
|
+
return
|
|
64
|
+
if pos[0] < 0 or pos[1] < 0:
|
|
65
|
+
return
|
|
66
|
+
try:
|
|
67
|
+
self.grid[pos[0]][pos[1]].set_value(tt)
|
|
68
|
+
except IndexError:
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
def paint(self):
|
|
72
|
+
for row in self.grid:
|
|
73
|
+
for cell in row:
|
|
74
|
+
cell.paint((
|
|
75
|
+
self.position[0] + cell.position[0],
|
|
76
|
+
self.position[1] + cell.position[1]
|
|
77
|
+
))
|
|
78
|
+
print_pos(0, 0, '')
|
|
79
|
+
|
|
80
|
+
class TuiText:
|
|
81
|
+
id: int
|
|
82
|
+
hidden: bool
|
|
83
|
+
text: TermText
|
|
84
|
+
size: Tuple[int, int]
|
|
85
|
+
position: Tuple[int, int]
|
|
86
|
+
|
|
87
|
+
def __init__(self, id: int, v: TermText, pos: Tuple[int, int]):
|
|
88
|
+
self.id = id
|
|
89
|
+
if not isinstance(v, TermText):
|
|
90
|
+
raise Exception("TuiText must use TermText")
|
|
91
|
+
self.text = v
|
|
92
|
+
self.position = pos
|
|
93
|
+
self.hidden = False
|
|
94
|
+
self._update_size()
|
|
95
|
+
|
|
96
|
+
def _update_size(self):
|
|
97
|
+
max_len = 0
|
|
98
|
+
lines = self.text.value.split("\n")
|
|
99
|
+
for i in range(0, len(lines)):
|
|
100
|
+
if len(lines[i]) > max_len:
|
|
101
|
+
max_len = len(lines[i])
|
|
102
|
+
|
|
103
|
+
self.size = (max_len, len(lines))
|
|
104
|
+
|
|
105
|
+
def update_value(self, v: TermText):
|
|
106
|
+
if not isinstance(v, TermText):
|
|
107
|
+
raise Exception("TuiText must use TermText")
|
|
108
|
+
self.text = v
|
|
109
|
+
self._update_size()
|
|
110
|
+
|
|
111
|
+
def get_cells(self) -> List[Tuple[TermText, Tuple[int, int]]]:
|
|
112
|
+
cells = []
|
|
113
|
+
lines = self.text.value.split("\n")
|
|
114
|
+
for x in range(0, self.size[0]):
|
|
115
|
+
for y in range(0, self.size[1]):
|
|
116
|
+
if x > len(lines[y]) - 1:
|
|
117
|
+
continue
|
|
118
|
+
tt = TermText(lines[y][x], self.text.fg, self.text.bg, self.text.bold)
|
|
119
|
+
cells.append((tt, (
|
|
120
|
+
self.position[0] + x,
|
|
121
|
+
self.position[1] + y
|
|
122
|
+
)))
|
|
123
|
+
return cells
|
|
124
|
+
|
|
125
|
+
class TuiWindow(TuiGrid):
|
|
126
|
+
_current_id: int
|
|
127
|
+
text_objects: List[TuiText]
|
|
128
|
+
|
|
129
|
+
def __init__(self, size: Tuple[int, int], pos: Tuple[int, int]):
|
|
130
|
+
super().__init__(size, pos)
|
|
131
|
+
self._current_id = 0
|
|
132
|
+
self.text_objects = []
|
|
133
|
+
|
|
134
|
+
def get_text(self, id: int) -> Optional[TuiText]:
|
|
135
|
+
objs = [o for o in self.text_objects if o.id == id]
|
|
136
|
+
if len(objs) == 0:
|
|
137
|
+
return None
|
|
138
|
+
return objs[0]
|
|
139
|
+
|
|
140
|
+
def add_text(self, v: TermText, pos: Tuple[int, int]) -> int:
|
|
141
|
+
self.text_objects.append(TuiText(self._current_id, v, pos))
|
|
142
|
+
self._current_id += 1
|
|
143
|
+
self._update_grid()
|
|
144
|
+
return self._current_id - 1
|
|
145
|
+
|
|
146
|
+
def clear_text(self, id: int):
|
|
147
|
+
txt = self.get_text(id)
|
|
148
|
+
if txt is None:
|
|
149
|
+
return
|
|
150
|
+
whitespace_v = TermText(''.join((c if c.isspace() else ' ') for c in txt.text.value))
|
|
151
|
+
whitespace_obj = TuiText(-1, whitespace_v, txt.position)
|
|
152
|
+
for clear_v, rel_pos in whitespace_obj.get_cells():
|
|
153
|
+
self.set_cell((
|
|
154
|
+
rel_pos[0],
|
|
155
|
+
rel_pos[1]
|
|
156
|
+
), clear_v)
|
|
157
|
+
|
|
158
|
+
def hide_txt(self, id: int):
|
|
159
|
+
txt = self.get_text(id)
|
|
160
|
+
if txt is None:
|
|
161
|
+
return
|
|
162
|
+
txt.hidden = True
|
|
163
|
+
self.clear_text(id)
|
|
164
|
+
|
|
165
|
+
def hide_all(self):
|
|
166
|
+
for txt in self.text_objects:
|
|
167
|
+
self.hide_txt(txt.id)
|
|
168
|
+
|
|
169
|
+
def show_txt(self, id: int):
|
|
170
|
+
txt = self.get_text(id)
|
|
171
|
+
if txt is None:
|
|
172
|
+
return
|
|
173
|
+
txt.hidden = False
|
|
174
|
+
self._update_grid()
|
|
175
|
+
|
|
176
|
+
def show_all(self):
|
|
177
|
+
for txt in self.text_objects:
|
|
178
|
+
self.show_txt(txt.id)
|
|
179
|
+
|
|
180
|
+
def remove_txt(self, id: int):
|
|
181
|
+
self.clear_text(id)
|
|
182
|
+
self.text_objects = [t for t in self.text_objects if t.id != id]
|
|
183
|
+
|
|
184
|
+
def remove_all(self):
|
|
185
|
+
for txt in list(self.text_objects):
|
|
186
|
+
self.remove_txt(txt.id)
|
|
187
|
+
|
|
188
|
+
def update_text(self, id: int, v: Optional[TermText], pos: Optional[Tuple[int, int]] = None):
|
|
189
|
+
txtObj = self.get_text(id)
|
|
190
|
+
|
|
191
|
+
if txtObj is None:
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
self.clear_text(id)
|
|
195
|
+
|
|
196
|
+
if v is not None:
|
|
197
|
+
txtObj.update_value(v)
|
|
198
|
+
|
|
199
|
+
if pos is not None:
|
|
200
|
+
txtObj.position = pos
|
|
201
|
+
|
|
202
|
+
self._update_grid()
|
|
203
|
+
|
|
204
|
+
def update_position(self, pos: Tuple[int, int]):
|
|
205
|
+
shown = [o.id for o in self.text_objects if not o.hidden]
|
|
206
|
+
|
|
207
|
+
self.hide_all()
|
|
208
|
+
self.clear_screen()
|
|
209
|
+
self.paint()
|
|
210
|
+
self.position = pos
|
|
211
|
+
for tid in shown:
|
|
212
|
+
self.show_txt(tid)
|
|
213
|
+
self.paint()
|
|
214
|
+
|
|
215
|
+
def clear_screen(self):
|
|
216
|
+
for x in range(0, self.size[0]):
|
|
217
|
+
for y in range(0, self.size[1]):
|
|
218
|
+
self.set_cell((x, y), TermText(" "))
|
|
219
|
+
|
|
220
|
+
def _update_grid(self):
|
|
221
|
+
for obj in self.text_objects:
|
|
222
|
+
if obj.hidden:
|
|
223
|
+
continue
|
|
224
|
+
for v, rel_pos in obj.get_cells():
|
|
225
|
+
self.set_cell((
|
|
226
|
+
rel_pos[0],
|
|
227
|
+
rel_pos[1]
|
|
228
|
+
), v)
|