ascii-matrixbox 0.1.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.
- ascii_matrixbox-0.1.0/LICENSE +21 -0
- ascii_matrixbox-0.1.0/PKG-INFO +76 -0
- ascii_matrixbox-0.1.0/README.md +57 -0
- ascii_matrixbox-0.1.0/pyproject.toml +34 -0
- ascii_matrixbox-0.1.0/setup.cfg +4 -0
- ascii_matrixbox-0.1.0/src/ascii_matrixbox.egg-info/PKG-INFO +76 -0
- ascii_matrixbox-0.1.0/src/ascii_matrixbox.egg-info/SOURCES.txt +11 -0
- ascii_matrixbox-0.1.0/src/ascii_matrixbox.egg-info/dependency_links.txt +1 -0
- ascii_matrixbox-0.1.0/src/ascii_matrixbox.egg-info/entry_points.txt +2 -0
- ascii_matrixbox-0.1.0/src/ascii_matrixbox.egg-info/top_level.txt +1 -0
- ascii_matrixbox-0.1.0/src/matrixbox/__init__.py +258 -0
- ascii_matrixbox-0.1.0/src/matrixbox/__main__.py +31 -0
- ascii_matrixbox-0.1.0/tests/test_matrixbox.py +86 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ProjectFS
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ascii-matrixbox
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tiny cmatrix-like ASCII rain window for your terminal. Runs in the background; use it as a decorator or context manager.
|
|
5
|
+
Author: ProjectFS
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://pypi.org/project/ascii-matrixbox/
|
|
8
|
+
Keywords: cmatrix,matrix,ascii,terminal,console,animation,decorator
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Terminals
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# matrixbox
|
|
21
|
+
|
|
22
|
+
A tiny `cmatrix`-style "digital rain" in a small square ASCII window in the
|
|
23
|
+
corner of your terminal. It runs in a background thread, so your program keeps
|
|
24
|
+
working (and printing) independently. Blue by default.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install ascii-matrixbox
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import matrixbox, time
|
|
34
|
+
|
|
35
|
+
# as a decorator: the window lives while the function runs
|
|
36
|
+
@matrixbox.matrix
|
|
37
|
+
def work():
|
|
38
|
+
for i in range(20):
|
|
39
|
+
print("working", i)
|
|
40
|
+
time.sleep(0.3)
|
|
41
|
+
|
|
42
|
+
# with parameters
|
|
43
|
+
@matrixbox.matrix(size=8, color="cyan", corner="top-left")
|
|
44
|
+
def other(): ...
|
|
45
|
+
|
|
46
|
+
# as a context manager
|
|
47
|
+
with matrixbox.MatrixBox(size=8):
|
|
48
|
+
time.sleep(5)
|
|
49
|
+
|
|
50
|
+
# manual control
|
|
51
|
+
matrixbox.start()
|
|
52
|
+
...
|
|
53
|
+
matrixbox.stop()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Works with regular functions, `async def` functions and generators.
|
|
57
|
+
|
|
58
|
+
| option | default | meaning |
|
|
59
|
+
|-----------|---------------|------------------------------------------------------|
|
|
60
|
+
| `size` | `10` | window height in rows (width is `2*size`) |
|
|
61
|
+
| `color` | `"blue"` | `blue`, `green`, `red`, `cyan` |
|
|
62
|
+
| `fps` | `15` | frames per second |
|
|
63
|
+
| `corner` | `"top-right"` | `top-right` or `top-left` |
|
|
64
|
+
| `reserve` | `True` | keep space under the window so `print()` can't overwrite it |
|
|
65
|
+
|
|
66
|
+
If the output is not a terminal (pipe, file), nothing is drawn.
|
|
67
|
+
Needs a terminal with ANSI support (any modern Linux/macOS terminal, Windows Terminal).
|
|
68
|
+
|
|
69
|
+
Demo: `python -m matrixbox --color blue --size 10` (or just `matrixbox`).
|
|
70
|
+
|
|
71
|
+
## По-русски
|
|
72
|
+
|
|
73
|
+
Маленький «матричный дождь» в квадратном ASCII-окошке в углу консоли.
|
|
74
|
+
Работает в фоне, не мешает вашей программе. Используйте как декоратор
|
|
75
|
+
`@matrixbox.matrix`, контекстный менеджер `with matrixbox.MatrixBox():`
|
|
76
|
+
или вручную через `matrixbox.start()` / `matrixbox.stop()`.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# matrixbox
|
|
2
|
+
|
|
3
|
+
A tiny `cmatrix`-style "digital rain" in a small square ASCII window in the
|
|
4
|
+
corner of your terminal. It runs in a background thread, so your program keeps
|
|
5
|
+
working (and printing) independently. Blue by default.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pip install ascii-matrixbox
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import matrixbox, time
|
|
15
|
+
|
|
16
|
+
# as a decorator: the window lives while the function runs
|
|
17
|
+
@matrixbox.matrix
|
|
18
|
+
def work():
|
|
19
|
+
for i in range(20):
|
|
20
|
+
print("working", i)
|
|
21
|
+
time.sleep(0.3)
|
|
22
|
+
|
|
23
|
+
# with parameters
|
|
24
|
+
@matrixbox.matrix(size=8, color="cyan", corner="top-left")
|
|
25
|
+
def other(): ...
|
|
26
|
+
|
|
27
|
+
# as a context manager
|
|
28
|
+
with matrixbox.MatrixBox(size=8):
|
|
29
|
+
time.sleep(5)
|
|
30
|
+
|
|
31
|
+
# manual control
|
|
32
|
+
matrixbox.start()
|
|
33
|
+
...
|
|
34
|
+
matrixbox.stop()
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Works with regular functions, `async def` functions and generators.
|
|
38
|
+
|
|
39
|
+
| option | default | meaning |
|
|
40
|
+
|-----------|---------------|------------------------------------------------------|
|
|
41
|
+
| `size` | `10` | window height in rows (width is `2*size`) |
|
|
42
|
+
| `color` | `"blue"` | `blue`, `green`, `red`, `cyan` |
|
|
43
|
+
| `fps` | `15` | frames per second |
|
|
44
|
+
| `corner` | `"top-right"` | `top-right` or `top-left` |
|
|
45
|
+
| `reserve` | `True` | keep space under the window so `print()` can't overwrite it |
|
|
46
|
+
|
|
47
|
+
If the output is not a terminal (pipe, file), nothing is drawn.
|
|
48
|
+
Needs a terminal with ANSI support (any modern Linux/macOS terminal, Windows Terminal).
|
|
49
|
+
|
|
50
|
+
Demo: `python -m matrixbox --color blue --size 10` (or just `matrixbox`).
|
|
51
|
+
|
|
52
|
+
## По-русски
|
|
53
|
+
|
|
54
|
+
Маленький «матричный дождь» в квадратном ASCII-окошке в углу консоли.
|
|
55
|
+
Работает в фоне, не мешает вашей программе. Используйте как декоратор
|
|
56
|
+
`@matrixbox.matrix`, контекстный менеджер `with matrixbox.MatrixBox():`
|
|
57
|
+
или вручную через `matrixbox.start()` / `matrixbox.stop()`.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ascii-matrixbox"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Tiny cmatrix-like ASCII rain window for your terminal. Runs in the background; use it as a decorator or context manager."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{name = "ProjectFS"}]
|
|
14
|
+
keywords = ["cmatrix", "matrix", "ascii", "terminal", "console", "animation", "decorator"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Topic :: Terminals",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://pypi.org/project/ascii-matrixbox/"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
matrixbox = "matrixbox.__main__:main"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.packages.find]
|
|
31
|
+
where = ["src"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.dynamic]
|
|
34
|
+
version = {attr = "matrixbox.__version__"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ascii-matrixbox
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tiny cmatrix-like ASCII rain window for your terminal. Runs in the background; use it as a decorator or context manager.
|
|
5
|
+
Author: ProjectFS
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://pypi.org/project/ascii-matrixbox/
|
|
8
|
+
Keywords: cmatrix,matrix,ascii,terminal,console,animation,decorator
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Terminals
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# matrixbox
|
|
21
|
+
|
|
22
|
+
A tiny `cmatrix`-style "digital rain" in a small square ASCII window in the
|
|
23
|
+
corner of your terminal. It runs in a background thread, so your program keeps
|
|
24
|
+
working (and printing) independently. Blue by default.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install ascii-matrixbox
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import matrixbox, time
|
|
34
|
+
|
|
35
|
+
# as a decorator: the window lives while the function runs
|
|
36
|
+
@matrixbox.matrix
|
|
37
|
+
def work():
|
|
38
|
+
for i in range(20):
|
|
39
|
+
print("working", i)
|
|
40
|
+
time.sleep(0.3)
|
|
41
|
+
|
|
42
|
+
# with parameters
|
|
43
|
+
@matrixbox.matrix(size=8, color="cyan", corner="top-left")
|
|
44
|
+
def other(): ...
|
|
45
|
+
|
|
46
|
+
# as a context manager
|
|
47
|
+
with matrixbox.MatrixBox(size=8):
|
|
48
|
+
time.sleep(5)
|
|
49
|
+
|
|
50
|
+
# manual control
|
|
51
|
+
matrixbox.start()
|
|
52
|
+
...
|
|
53
|
+
matrixbox.stop()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Works with regular functions, `async def` functions and generators.
|
|
57
|
+
|
|
58
|
+
| option | default | meaning |
|
|
59
|
+
|-----------|---------------|------------------------------------------------------|
|
|
60
|
+
| `size` | `10` | window height in rows (width is `2*size`) |
|
|
61
|
+
| `color` | `"blue"` | `blue`, `green`, `red`, `cyan` |
|
|
62
|
+
| `fps` | `15` | frames per second |
|
|
63
|
+
| `corner` | `"top-right"` | `top-right` or `top-left` |
|
|
64
|
+
| `reserve` | `True` | keep space under the window so `print()` can't overwrite it |
|
|
65
|
+
|
|
66
|
+
If the output is not a terminal (pipe, file), nothing is drawn.
|
|
67
|
+
Needs a terminal with ANSI support (any modern Linux/macOS terminal, Windows Terminal).
|
|
68
|
+
|
|
69
|
+
Demo: `python -m matrixbox --color blue --size 10` (or just `matrixbox`).
|
|
70
|
+
|
|
71
|
+
## По-русски
|
|
72
|
+
|
|
73
|
+
Маленький «матричный дождь» в квадратном ASCII-окошке в углу консоли.
|
|
74
|
+
Работает в фоне, не мешает вашей программе. Используйте как декоратор
|
|
75
|
+
`@matrixbox.matrix`, контекстный менеджер `with matrixbox.MatrixBox():`
|
|
76
|
+
или вручную через `matrixbox.start()` / `matrixbox.stop()`.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/ascii_matrixbox.egg-info/PKG-INFO
|
|
5
|
+
src/ascii_matrixbox.egg-info/SOURCES.txt
|
|
6
|
+
src/ascii_matrixbox.egg-info/dependency_links.txt
|
|
7
|
+
src/ascii_matrixbox.egg-info/entry_points.txt
|
|
8
|
+
src/ascii_matrixbox.egg-info/top_level.txt
|
|
9
|
+
src/matrixbox/__init__.py
|
|
10
|
+
src/matrixbox/__main__.py
|
|
11
|
+
tests/test_matrixbox.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
matrixbox
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""
|
|
2
|
+
matrixbox - маленький "cmatrix" в квадратном ASCII-окошке (по умолчанию синий).
|
|
3
|
+
|
|
4
|
+
Окошко рисуется в фоновом потоке, поэтому основная программа работает
|
|
5
|
+
независимо. Обычный print() прокручивается ПОД окошком и не затирает его.
|
|
6
|
+
|
|
7
|
+
import matrixbox
|
|
8
|
+
|
|
9
|
+
# 1) декоратор - окошко живёт, пока выполняется функция
|
|
10
|
+
@matrixbox.matrix
|
|
11
|
+
def work(): ...
|
|
12
|
+
|
|
13
|
+
@matrixbox.matrix(size=8, color="cyan", corner="top-left")
|
|
14
|
+
def work2(): ...
|
|
15
|
+
|
|
16
|
+
# 2) контекстный менеджер
|
|
17
|
+
with matrixbox.MatrixBox(size=8):
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
# 3) ручной запуск/остановка
|
|
21
|
+
matrixbox.start(); ...; matrixbox.stop()
|
|
22
|
+
"""
|
|
23
|
+
import atexit
|
|
24
|
+
import functools
|
|
25
|
+
import inspect
|
|
26
|
+
import os
|
|
27
|
+
import random
|
|
28
|
+
import shutil
|
|
29
|
+
import sys
|
|
30
|
+
import threading
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
__all__ = ["MatrixBox", "matrix", "start", "stop"]
|
|
34
|
+
|
|
35
|
+
CHARS = "0123456789abcdefghijklmnopqrstuvwxyz@#$%&*+=<>?/\\|"
|
|
36
|
+
|
|
37
|
+
# палитры 256-цветного режима: от яркой головы к тёмному хвосту
|
|
38
|
+
PALETTES = {
|
|
39
|
+
"blue": [195, 117, 39, 33, 27, 21, 19, 17],
|
|
40
|
+
"green": [231, 120, 46, 40, 34, 28, 22, 22],
|
|
41
|
+
"red": [224, 210, 196, 160, 124, 88, 52, 52],
|
|
42
|
+
"cyan": [231, 123, 51, 45, 38, 31, 24, 23],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if os.name == "nt": # включаем ANSI в консоли Windows
|
|
46
|
+
os.system("")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class MatrixBox:
|
|
50
|
+
"""Окошко с «матричным дождём». Можно использовать как менеджер контекста
|
|
51
|
+
или как декоратор: ``@MatrixBox(size=8)``."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, size=10, color="blue", fps=15, corner="top-right",
|
|
54
|
+
reserve=True, stream=None):
|
|
55
|
+
"""
|
|
56
|
+
size - высота окошка в строках (ширина = size*2, чтобы выглядело квадратным)
|
|
57
|
+
color - blue / green / red / cyan
|
|
58
|
+
fps - кадров в секунду
|
|
59
|
+
corner - top-right или top-left
|
|
60
|
+
reserve - зарезервировать место под окошком (print его не затирает)
|
|
61
|
+
"""
|
|
62
|
+
self.h = max(3, int(size))
|
|
63
|
+
self.w = self.h * 2
|
|
64
|
+
self.pal = PALETTES.get(color, PALETTES["blue"])
|
|
65
|
+
self.delay = 1.0 / fps
|
|
66
|
+
self.corner = corner
|
|
67
|
+
self.reserve = reserve
|
|
68
|
+
self._stream = stream
|
|
69
|
+
self._stop = threading.Event()
|
|
70
|
+
self._lock = threading.Lock()
|
|
71
|
+
self._ulock = threading.Lock()
|
|
72
|
+
self._users = 0
|
|
73
|
+
self._atexit = False
|
|
74
|
+
self._thread = None
|
|
75
|
+
self._cols = [self._new_col(initial=True) for _ in range(self.w)]
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def out(self):
|
|
79
|
+
return self._stream or sys.stdout
|
|
80
|
+
|
|
81
|
+
# ---------- логика дождя ----------
|
|
82
|
+
def _new_col(self, initial=False):
|
|
83
|
+
length = random.randint(3, self.h)
|
|
84
|
+
head = random.uniform(-self.h, self.h) if initial else -random.randint(0, self.h)
|
|
85
|
+
return {"head": head, "len": length, "speed": random.uniform(0.3, 1.0),
|
|
86
|
+
"chars": [random.choice(CHARS) for _ in range(self.h)]}
|
|
87
|
+
|
|
88
|
+
def _step(self):
|
|
89
|
+
for i, c in enumerate(self._cols):
|
|
90
|
+
c["head"] += c["speed"]
|
|
91
|
+
if random.random() < 0.3:
|
|
92
|
+
c["chars"][random.randrange(self.h)] = random.choice(CHARS)
|
|
93
|
+
if c["head"] - c["len"] > self.h:
|
|
94
|
+
self._cols[i] = self._new_col()
|
|
95
|
+
|
|
96
|
+
def _frame(self):
|
|
97
|
+
n = len(self.pal)
|
|
98
|
+
lines = []
|
|
99
|
+
for y in range(self.h):
|
|
100
|
+
row, last = [], None
|
|
101
|
+
for c in self._cols:
|
|
102
|
+
d = int(c["head"]) - y
|
|
103
|
+
if 0 <= d < c["len"]:
|
|
104
|
+
color = self.pal[min(n - 1, d * n // c["len"])]
|
|
105
|
+
if color != last:
|
|
106
|
+
row.append(f"\033[38;5;{color}m")
|
|
107
|
+
last = color
|
|
108
|
+
row.append(c["chars"][y])
|
|
109
|
+
else:
|
|
110
|
+
row.append(" ")
|
|
111
|
+
lines.append("".join(row))
|
|
112
|
+
return lines
|
|
113
|
+
|
|
114
|
+
# ---------- вывод в терминал ----------
|
|
115
|
+
def _origin_col(self):
|
|
116
|
+
if self.corner == "top-left":
|
|
117
|
+
return 1
|
|
118
|
+
return max(1, shutil.get_terminal_size().columns - self.w - 1)
|
|
119
|
+
|
|
120
|
+
def _draw(self):
|
|
121
|
+
col = self._origin_col()
|
|
122
|
+
border = "+" + "-" * self.w + "+"
|
|
123
|
+
buf = ["\0337\033[?25l"] # сохранить курсор, скрыть
|
|
124
|
+
buf.append(f"\033[1;{col}H\033[0;34m{border}")
|
|
125
|
+
for i, line in enumerate(self._frame(), start=2):
|
|
126
|
+
buf.append(f"\033[{i};{col}H\033[0;34m|{line}\033[0;34m|")
|
|
127
|
+
buf.append(f"\033[{self.h + 2};{col}H\033[0;34m{border}\033[0m")
|
|
128
|
+
buf.append("\0338\033[?25h") # вернуть курсор
|
|
129
|
+
with self._lock:
|
|
130
|
+
self.out.write("".join(buf))
|
|
131
|
+
self.out.flush()
|
|
132
|
+
|
|
133
|
+
def _loop(self):
|
|
134
|
+
while not self._stop.is_set():
|
|
135
|
+
try:
|
|
136
|
+
self._draw()
|
|
137
|
+
self._step()
|
|
138
|
+
except Exception:
|
|
139
|
+
break
|
|
140
|
+
self._stop.wait(self.delay)
|
|
141
|
+
|
|
142
|
+
# ---------- управление ----------
|
|
143
|
+
def start(self):
|
|
144
|
+
if self._thread and self._thread.is_alive():
|
|
145
|
+
return self
|
|
146
|
+
isatty = getattr(self.out, "isatty", None)
|
|
147
|
+
if not (isatty and isatty()): # не терминал - ничего не делаем
|
|
148
|
+
return self
|
|
149
|
+
self._stop.clear()
|
|
150
|
+
rows = shutil.get_terminal_size().lines
|
|
151
|
+
with self._lock:
|
|
152
|
+
if self.reserve:
|
|
153
|
+
# освободить место сверху и ограничить прокрутку областью под окошком
|
|
154
|
+
self.out.write("\n" * (self.h + 2))
|
|
155
|
+
self.out.write(f"\033[{self.h + 3};{rows}r\033[{rows};1H")
|
|
156
|
+
self.out.flush()
|
|
157
|
+
self._thread = threading.Thread(target=self._loop, daemon=True)
|
|
158
|
+
self._thread.start()
|
|
159
|
+
if not self._atexit:
|
|
160
|
+
atexit.register(self.stop)
|
|
161
|
+
self._atexit = True
|
|
162
|
+
return self
|
|
163
|
+
|
|
164
|
+
def stop(self):
|
|
165
|
+
if not self._thread:
|
|
166
|
+
return
|
|
167
|
+
self._stop.set()
|
|
168
|
+
self._thread.join(timeout=1)
|
|
169
|
+
self._thread = None
|
|
170
|
+
col = self._origin_col()
|
|
171
|
+
buf = ["\0337"]
|
|
172
|
+
for i in range(1, self.h + 3): # стереть окошко
|
|
173
|
+
buf.append(f"\033[{i};{col}H" + " " * (self.w + 2))
|
|
174
|
+
buf.append("\033[r\0338\033[0m\033[?25h") # сбросить область прокрутки
|
|
175
|
+
with self._lock:
|
|
176
|
+
self.out.write("".join(buf))
|
|
177
|
+
self.out.flush()
|
|
178
|
+
|
|
179
|
+
# контекстный менеджер (со счётчиком - безопасно при вложенных/параллельных вызовах)
|
|
180
|
+
def __enter__(self):
|
|
181
|
+
with self._ulock:
|
|
182
|
+
self._users += 1
|
|
183
|
+
if self._users == 1:
|
|
184
|
+
self.start()
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
def __exit__(self, *exc):
|
|
188
|
+
with self._ulock:
|
|
189
|
+
self._users -= 1
|
|
190
|
+
if self._users == 0:
|
|
191
|
+
self.stop()
|
|
192
|
+
|
|
193
|
+
# декоратор: @MatrixBox(size=8)
|
|
194
|
+
def __call__(self, func):
|
|
195
|
+
return _wrap(self, func)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _wrap(box, f):
|
|
199
|
+
"""Обернуть функцию f так, чтобы окошко жило, пока она выполняется.
|
|
200
|
+
Поддерживаются обычные, async-функции и генераторы."""
|
|
201
|
+
if inspect.isasyncgenfunction(f):
|
|
202
|
+
@functools.wraps(f)
|
|
203
|
+
async def agen_wrapper(*a, **k):
|
|
204
|
+
with box:
|
|
205
|
+
async for item in f(*a, **k):
|
|
206
|
+
yield item
|
|
207
|
+
return agen_wrapper
|
|
208
|
+
if inspect.iscoroutinefunction(f):
|
|
209
|
+
@functools.wraps(f)
|
|
210
|
+
async def async_wrapper(*a, **k):
|
|
211
|
+
with box:
|
|
212
|
+
return await f(*a, **k)
|
|
213
|
+
return async_wrapper
|
|
214
|
+
if inspect.isgeneratorfunction(f):
|
|
215
|
+
@functools.wraps(f)
|
|
216
|
+
def gen_wrapper(*a, **k):
|
|
217
|
+
with box:
|
|
218
|
+
return (yield from f(*a, **k))
|
|
219
|
+
return gen_wrapper
|
|
220
|
+
|
|
221
|
+
@functools.wraps(f)
|
|
222
|
+
def wrapper(*a, **k):
|
|
223
|
+
with box:
|
|
224
|
+
return f(*a, **k)
|
|
225
|
+
return wrapper
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def matrix(func=None, **kwargs):
|
|
229
|
+
"""Декоратор. Работает и без скобок, и с параметрами MatrixBox:
|
|
230
|
+
|
|
231
|
+
@matrix
|
|
232
|
+
def f(): ...
|
|
233
|
+
|
|
234
|
+
@matrix(size=8, color="green", corner="top-left")
|
|
235
|
+
def g(): ...
|
|
236
|
+
"""
|
|
237
|
+
def decorate(f):
|
|
238
|
+
return _wrap(MatrixBox(**kwargs), f)
|
|
239
|
+
return decorate(func) if callable(func) else decorate
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ---------- простой функциональный интерфейс ----------
|
|
243
|
+
_default = None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def start(**kwargs):
|
|
247
|
+
"""Запустить окошко с настройками по умолчанию (синее)."""
|
|
248
|
+
global _default
|
|
249
|
+
if _default is None:
|
|
250
|
+
_default = MatrixBox(**kwargs)
|
|
251
|
+
return _default.start()
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def stop():
|
|
255
|
+
global _default
|
|
256
|
+
if _default is not None:
|
|
257
|
+
_default.stop()
|
|
258
|
+
_default = None
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Демо: python -m matrixbox (или команда `matrixbox`)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from . import PALETTES, MatrixBox, __version__
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None):
|
|
9
|
+
p = argparse.ArgumentParser(prog="matrixbox",
|
|
10
|
+
description="Маленькое матричное окошко в консоли.")
|
|
11
|
+
p.add_argument("--size", type=int, default=10, help="высота окошка (строк)")
|
|
12
|
+
p.add_argument("--color", default="blue", choices=sorted(PALETTES))
|
|
13
|
+
p.add_argument("--corner", default="top-right", choices=["top-right", "top-left"])
|
|
14
|
+
p.add_argument("--fps", type=int, default=15)
|
|
15
|
+
p.add_argument("--no-reserve", action="store_true",
|
|
16
|
+
help="не резервировать место под окошком")
|
|
17
|
+
p.add_argument("--version", action="version", version=__version__)
|
|
18
|
+
a = p.parse_args(argv)
|
|
19
|
+
|
|
20
|
+
print("Ctrl+C - выход")
|
|
21
|
+
with MatrixBox(size=a.size, color=a.color, fps=a.fps, corner=a.corner,
|
|
22
|
+
reserve=not a.no_reserve):
|
|
23
|
+
try:
|
|
24
|
+
while True:
|
|
25
|
+
time.sleep(0.2)
|
|
26
|
+
except KeyboardInterrupt:
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
main()
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import io
|
|
3
|
+
import time
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
import matrixbox
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Tty(io.StringIO):
|
|
10
|
+
def isatty(self):
|
|
11
|
+
return True
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DecoratorTests(unittest.TestCase):
|
|
15
|
+
def test_bare_decorator_keeps_result_and_name(self):
|
|
16
|
+
@matrixbox.matrix
|
|
17
|
+
def add(a, b=1):
|
|
18
|
+
"doc"
|
|
19
|
+
return a + b
|
|
20
|
+
self.assertEqual(add(2, b=3), 5)
|
|
21
|
+
self.assertEqual(add.__name__, "add")
|
|
22
|
+
self.assertEqual(add.__doc__, "doc")
|
|
23
|
+
|
|
24
|
+
def test_decorator_with_args(self):
|
|
25
|
+
@matrixbox.matrix(size=5, color="green")
|
|
26
|
+
def f():
|
|
27
|
+
return "ok"
|
|
28
|
+
self.assertEqual(f(), "ok")
|
|
29
|
+
|
|
30
|
+
def test_instance_as_decorator(self):
|
|
31
|
+
@matrixbox.MatrixBox(size=4)
|
|
32
|
+
def f():
|
|
33
|
+
return 42
|
|
34
|
+
self.assertEqual(f(), 42)
|
|
35
|
+
|
|
36
|
+
def test_async(self):
|
|
37
|
+
@matrixbox.matrix
|
|
38
|
+
async def f():
|
|
39
|
+
return 7
|
|
40
|
+
self.assertEqual(asyncio.run(f()), 7)
|
|
41
|
+
|
|
42
|
+
def test_generator(self):
|
|
43
|
+
@matrixbox.matrix
|
|
44
|
+
def g():
|
|
45
|
+
yield 1
|
|
46
|
+
yield 2
|
|
47
|
+
self.assertEqual(list(g()), [1, 2])
|
|
48
|
+
|
|
49
|
+
def test_exception_propagates_and_box_stops(self):
|
|
50
|
+
box = matrixbox.MatrixBox(stream=Tty())
|
|
51
|
+
|
|
52
|
+
def boom():
|
|
53
|
+
raise ValueError("x")
|
|
54
|
+
with self.assertRaises(ValueError):
|
|
55
|
+
box(boom)()
|
|
56
|
+
self.assertIsNone(box._thread)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DrawingTests(unittest.TestCase):
|
|
60
|
+
def test_draws_on_tty_and_cleans_up(self):
|
|
61
|
+
out = Tty()
|
|
62
|
+
box = matrixbox.MatrixBox(size=4, fps=60, stream=out)
|
|
63
|
+
with box:
|
|
64
|
+
time.sleep(0.2)
|
|
65
|
+
text = out.getvalue()
|
|
66
|
+
self.assertIn("\033[38;5;", text) # цвета
|
|
67
|
+
self.assertIn("\033[r", text) # сброс области прокрутки
|
|
68
|
+
self.assertIsNone(box._thread)
|
|
69
|
+
|
|
70
|
+
def test_noop_when_not_tty(self):
|
|
71
|
+
out = io.StringIO()
|
|
72
|
+
with matrixbox.MatrixBox(stream=out):
|
|
73
|
+
pass
|
|
74
|
+
self.assertEqual(out.getvalue(), "")
|
|
75
|
+
|
|
76
|
+
def test_nested_use_stops_only_at_zero(self):
|
|
77
|
+
box = matrixbox.MatrixBox(size=4, stream=Tty())
|
|
78
|
+
with box:
|
|
79
|
+
with box:
|
|
80
|
+
pass
|
|
81
|
+
self.assertIsNotNone(box._thread)
|
|
82
|
+
self.assertIsNone(box._thread)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
unittest.main()
|