Debian Codegraph @

scripts/generate-alt-random-writes.py

raw
1 #!/usr/bin/env python3
2 import argparse
3 import enum
4 import fcntl
5 import random
6 import signal
7 import struct
8 import sys
9 import termios
10
11 from typing import Any
12
13
14 class ColorVariant(enum.IntEnum):
15 NONE = enum.auto()
16 REGULAR = enum.auto()
17 BRIGHT = enum.auto()
18 CUBE = enum.auto()
19 RGB = enum.auto()
20
21
22 def main() -> None:
23 parser = argparse.ArgumentParser()
24 parser.add_argument(
25 'out', type=argparse.FileType(mode='w'), nargs='?', help='name of output file')
26 parser.add_argument('--cols', type=int)
27 parser.add_argument('--rows', type=int)
28 parser.add_argument('--colors-regular', action='store_true')
29 parser.add_argument('--colors-bright', action='store_true')
30 parser.add_argument('--colors-256', action='store_true')
31 parser.add_argument('--colors-rgb', action='store_true')
32 parser.add_argument('--scroll', action='store_true')
33 parser.add_argument('--scroll-region', action='store_true')
34 parser.add_argument('--attr-bold', action='store_true')
35 parser.add_argument('--attr-italic', action='store_true')
36 parser.add_argument('--attr-underline', action='store_true')
37 parser.add_argument('--sixel', action='store_true')
38 parser.add_argument('--seed', type=int)
39
40 opts = parser.parse_args()
41 out = opts.out if opts.out is not None else sys.stdout
42
43 lines: int | None = None
44 cols: int | None = None
45 width: int | None = None
46 height: int | None = None
47
48 if opts.rows is None or opts.cols is None:
49 try:
50 def dummy(*args: Any) -> None:
51 """Need a handler installed for sigwait() to trigger."""
52 _ = args
53 pass
54 signal.signal(signal.SIGWINCH, dummy)
55
56 while True:
57 with open('/dev/tty', 'rb') as pty:
58 lines, cols, height, width = struct.unpack(
59 'HHHH',
60 fcntl.ioctl(pty,
61 termios.TIOCGWINSZ,
62 struct.pack('HHHH', 0, 0, 0, 0)))
63
64 assert width is not None
65 assert height is not None
66
67 if width > 0 and height > 0:
68 break
69
70 # We’re early; the foot window hasn’t been mapped yet. Or,
71 # to be more precise, fonts haven’t yet been loaded,
72 # meaning it doesn’t have any cell geometry yet.
73 signal.sigwait([signal.SIGWINCH])
74
75 signal.signal(signal.SIGWINCH, signal.SIG_DFL)
76
77 except OSError:
78 lines = None
79 cols = None
80 height = None
81 width = None
82
83 if opts.rows is not None:
84 lines = opts.rows
85 assert lines is not None
86 height = 15 * lines # PGO helper binary hardcodes cell height to 15px
87 if opts.cols is not None:
88 cols = opts.cols
89 assert cols is not None
90 width = 8 * cols # PGO help binary hardcodes cell width to 8px
91
92 if lines is None or cols is None or height is None or width is None:
93 raise Exception('could not get terminal width/height; use --rows and --cols')
94
95 assert lines > 0, f'{lines}'
96 assert cols > 0, f'{cols}'
97 assert width > 0, f'{width}'
98 assert height > 0, f'{height}'
99
100 # Number of characters to write to screen
101 count = 256 * 1024**1
102
103 # Characters to choose from
104 alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTSTUVWXYZ0123456789 öäå 👨👩🧒👩🏽‍🔬🇸🇪'
105
106 color_variants = ([ColorVariant.NONE] +
107 ([ColorVariant.REGULAR] if opts.colors_regular else []) +
108 ([ColorVariant.BRIGHT] if opts.colors_bright else []) +
109 ([ColorVariant.CUBE] if opts.colors_256 else []) +
110 ([ColorVariant.RGB] if opts.colors_rgb else []))
111
112 # Enter alt screen
113 out.write('\033[?1049h')
114
115 # uses system time or /dev/urandom if available if opt.seed == None
116 # pin seeding method to make seeding stable across future versions
117 random.seed(a=opts.seed, version=2)
118
119 for _ in range(count):
120 if opts.scroll and random.randrange(256) == 0:
121 out.write('\033[m')
122
123 if opts.scroll_region and random.randrange(256) == 0:
124 top = random.randrange(3)
125 bottom = random.randrange(3)
126 out.write(f'\033[{top};{lines - bottom}r')
127
128 lines_to_scroll = random.randrange(lines - 1)
129 rev = random.randrange(2)
130 if not rev and random.randrange(2):
131 out.write(f'\033[{lines};{cols}H')
132 out.write('\n' * lines_to_scroll)
133 else:
134 out.write(f'\033[{lines_to_scroll + 1}{"T" if rev == 1 else "S"}')
135 continue
136
137 # Generate a random location and a random character
138 row = random.randrange(lines)
139 col = random.randrange(cols)
140 c = random.choice(alphabet)
141
142 repeat = random.randrange((cols - col) + 1)
143 assert col + repeat <= cols
144
145 color_variant = random.choice(color_variants)
146
147 # Position cursor
148 out.write(f'\033[{row + 1};{col + 1}H')
149
150 if color_variant in [ColorVariant.REGULAR, ColorVariant.BRIGHT]:
151 do_bg = random.randrange(2)
152 base = 40 if do_bg else 30
153 base += 60 if color_variant == ColorVariant.BRIGHT else 0
154
155 idx = random.randrange(8)
156 out.write(f'\033[{base + idx}m')
157
158 elif color_variant == ColorVariant.CUBE:
159 do_bg = random.randrange(2)
160 base = 48 if do_bg else 38
161
162 idx = random.randrange(256)
163 if random.randrange(2):
164 # Old-style
165 out.write(f'\033[{base};5;{idx}m')
166 else:
167 # New-style (sub-parameter based)
168 out.write(f'\033[{base}:5:{idx}m')
169
170 elif color_variant == ColorVariant.RGB:
171 do_bg = random.randrange(2)
172 base = 48 if do_bg else 38
173
174 # use list comprehension in favor of randbytes(n)
175 # which is only available for Python >= 3.9
176 rgb = [random.randrange(256) for _ in range(3)]
177
178 if random.randrange(2):
179 # Old-style
180 out.write(f'\033[{base};2;{rgb[0]};{rgb[1]};{rgb[2]}m')
181 else:
182 # New-style (sub-parameter based)
183 out.write(f'\033[{base}:2::{rgb[0]}:{rgb[1]}:{rgb[2]}m')
184
185 if opts.attr_bold and random.randrange(5) == 0:
186 out.write('\033[1m')
187 if opts.attr_italic and random.randrange(5) == 0:
188 out.write('\033[3m')
189 if opts.attr_underline and random.randrange(5) == 0:
190 out.write('\033[4m')
191
192 out.write(c * repeat)
193
194 do_sgr_reset = random.randrange(2)
195 if do_sgr_reset:
196 reset_actions = ['\033[m', '\033[39m', '\033[49m']
197 out.write(random.choice(reset_actions))
198
199 # Reset colors
200 out.write('\033[m\033[r')
201
202 if opts.sixel:
203 # The sixel 'alphabet'
204 sixels = '?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
205
206 last_pos: tuple[int, int] | None = None
207 last_size: tuple[int, int] = 0, 0
208
209 for _ in range(20):
210 if last_pos is not None and random.randrange(2):
211 # Overwrite last sixel. I.e. use same position and
212 # size as last sixel
213 pass
214 else:
215 # Random origin in upper left quadrant
216 last_pos = random.randrange(lines // 2) + 1, random.randrange(cols // 2) + 1
217 last_size = random.randrange((height + 1) // 2), random.randrange((width + 1) // 2)
218
219 out.write(f'\033[{last_pos[0]};{last_pos[1]}H')
220 six_height, six_width = last_size
221 six_rows = (six_height + 5) // 6 # Round up; each sixel is 6 pixels
222
223 # Begin sixel (with P2 set to either 0 or 1 - opaque or transparent)
224 sixel_p2 = random.randrange(2)
225 out.write(f'\033P;{sixel_p2}q')
226
227 # Sixel size. Without this, sixels will be
228 # auto-resized on cell-boundaries.
229 out.write(f'"1;1;{six_width};{six_height}')
230
231 # Set up 256 random colors
232 for idx in range(256):
233 # param 2: 1=HLS, 2=RGB.
234 # param 3/4/5: HLS/RGB values in range 0-100
235 # (except 'hue' which is 0..360)
236 out.write(f'#{idx};2;{random.randrange(101)};{random.randrange(101)};{random.randrange(101)}')
237
238 for row in range(six_rows):
239 band_count = random.randrange(4, 33)
240 for band in range(band_count):
241 # Choose a random color
242 out.write(f'#{random.randrange(256)}')
243
244 if random.randrange(2):
245 for col in range(six_width):
246 out.write(f'{random.choice(sixels)}')
247 else:
248 pix_left = six_width
249 while pix_left > 0:
250 repeat_count = random.randrange(1, pix_left + 1)
251 out.write(f'!{repeat_count}{random.choice(sixels)}')
252 pix_left -= repeat_count
253
254 # Next line
255 if band + 1 < band_count:
256 # Move cursor to beginning of current row
257 out.write('$')
258 elif row + 1 < six_rows:
259 # Newline
260 out.write('-')
261
262 # End sixel
263 out.write('\033\\')
264
265 # Leave alt screen
266 out.write('\033[?1049l')
267
268
269 if __name__ == '__main__':
270 main()