progressbar2 4.3.0__py3-none-any.whl

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.
@@ -0,0 +1,524 @@
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ import collections
5
+ import colorsys
6
+ import threading
7
+ from collections import defaultdict
8
+
9
+ # Ruff is being stupid and doesn't understand `ClassVar` if it comes from the
10
+ # `types` module
11
+ from typing import ClassVar
12
+
13
+ from python_utils import converters, types
14
+
15
+ from .. import (
16
+ base as pbase,
17
+ env,
18
+ )
19
+ from .os_specific import getch
20
+
21
+ ESC = '\x1B'
22
+
23
+
24
+ class CSI:
25
+ _code: str
26
+ _template = ESC + '[{args}{code}'
27
+
28
+ def __init__(self, code, *default_args):
29
+ self._code = code
30
+ self._default_args = default_args
31
+
32
+ def __call__(self, *args):
33
+ return self._template.format(
34
+ args=';'.join(map(str, args or self._default_args)),
35
+ code=self._code,
36
+ )
37
+
38
+ def __str__(self):
39
+ return self()
40
+
41
+
42
+ class CSINoArg(CSI):
43
+ def __call__(self):
44
+ return super().__call__()
45
+
46
+
47
+ #: Cursor Position [row;column] (default = [1,1])
48
+ CUP = CSI('H', 1, 1)
49
+
50
+ #: Cursor Up Ps Times (default = 1) (CUU)
51
+ UP = CSI('A', 1)
52
+
53
+ #: Cursor Down Ps Times (default = 1) (CUD)
54
+ DOWN = CSI('B', 1)
55
+
56
+ #: Cursor Forward Ps Times (default = 1) (CUF)
57
+ RIGHT = CSI('C', 1)
58
+
59
+ #: Cursor Backward Ps Times (default = 1) (CUB)
60
+ LEFT = CSI('D', 1)
61
+
62
+ #: Cursor Next Line Ps Times (default = 1) (CNL)
63
+ #: Same as Cursor Down Ps Times
64
+ NEXT_LINE = CSI('E', 1)
65
+
66
+ #: Cursor Preceding Line Ps Times (default = 1) (CPL)
67
+ #: Same as Cursor Up Ps Times
68
+ PREVIOUS_LINE = CSI('F', 1)
69
+
70
+ #: Cursor Character Absolute [column] (default = [row,1]) (CHA)
71
+ COLUMN = CSI('G', 1)
72
+
73
+ #: Erase in Display (ED)
74
+ CLEAR_SCREEN = CSI('J', 0)
75
+
76
+ #: Erase till end of screen
77
+ CLEAR_SCREEN_TILL_END = CSINoArg('0J')
78
+
79
+ #: Erase till start of screen
80
+ CLEAR_SCREEN_TILL_START = CSINoArg('1J')
81
+
82
+ #: Erase whole screen
83
+ CLEAR_SCREEN_ALL = CSINoArg('2J')
84
+
85
+ #: Erase whole screen and history
86
+ CLEAR_SCREEN_ALL_AND_HISTORY = CSINoArg('3J')
87
+
88
+ #: Erase in Line (EL)
89
+ CLEAR_LINE_ALL = CSI('K')
90
+
91
+ #: Erase in Line from Cursor to End of Line (default)
92
+ CLEAR_LINE_RIGHT = CSINoArg('0K')
93
+
94
+ #: Erase in Line from Cursor to Beginning of Line
95
+ CLEAR_LINE_LEFT = CSINoArg('1K')
96
+
97
+ #: Erase Line containing Cursor
98
+ CLEAR_LINE = CSINoArg('2K')
99
+
100
+ #: Scroll up Ps lines (default = 1) (SU)
101
+ #: Scroll down Ps lines (default = 1) (SD)
102
+ SCROLL_UP = CSI('S')
103
+ SCROLL_DOWN = CSI('T')
104
+
105
+ #: Save Cursor Position (SCP)
106
+ SAVE_CURSOR = CSINoArg('s')
107
+
108
+ #: Restore Cursor Position (RCP)
109
+ RESTORE_CURSOR = CSINoArg('u')
110
+
111
+ #: Cursor Visibility (DECTCEM)
112
+ HIDE_CURSOR = CSINoArg('?25l')
113
+ SHOW_CURSOR = CSINoArg('?25h')
114
+
115
+
116
+ #
117
+ # UP = CSI + '{n}A' # Cursor Up
118
+ # DOWN = CSI + '{n}B' # Cursor Down
119
+ # RIGHT = CSI + '{n}C' # Cursor Forward
120
+ # LEFT = CSI + '{n}D' # Cursor Backward
121
+ # NEXT = CSI + '{n}E' # Cursor Next Line
122
+ # PREV = CSI + '{n}F' # Cursor Previous Line
123
+ # MOVE_COLUMN = CSI + '{n}G' # Cursor Horizontal Absolute
124
+ # MOVE = CSI + '{row};{column}H' # Cursor Position [row;column] (default = [
125
+ # 1,1])
126
+ #
127
+ # CLEAR = CSI + '{n}J' # Clear (part of) the screen
128
+ # CLEAR_BOTTOM = CLEAR.format(n=0) # Clear from cursor to end of screen
129
+ # CLEAR_TOP = CLEAR.format(n=1) # Clear from cursor to beginning of screen
130
+ # CLEAR_SCREEN = CLEAR.format(n=2) # Clear Screen
131
+ # CLEAR_WIPE = CLEAR.format(n=3) # Clear Screen and scrollback buffer
132
+ #
133
+ # CLEAR_LINE = CSI + '{n}K' # Erase in Line
134
+ # CLEAR_LINE_RIGHT = CLEAR_LINE.format(n=0) # Clear from cursor to end of line
135
+ # CLEAR_LINE_LEFT = CLEAR_LINE.format(n=1) # Clear from cursor to beginning
136
+ # of line
137
+ # CLEAR_LINE_ALL = CLEAR_LINE.format(n=2) # Clear Line
138
+
139
+
140
+ def clear_line(n):
141
+ return UP(n) + CLEAR_LINE_ALL() + DOWN(n)
142
+
143
+
144
+ # Report Cursor Position (CPR), response = [row;column] as row;columnR
145
+ class _CPR(str): # pragma: no cover
146
+ _response_lock = threading.Lock()
147
+
148
+ def __call__(self, stream) -> tuple[int, int]:
149
+ res: str = ''
150
+
151
+ with self._response_lock:
152
+ stream.write(str(self))
153
+ stream.flush()
154
+
155
+ while not res.endswith('R'):
156
+ char = getch()
157
+
158
+ if char is not None:
159
+ res += char
160
+
161
+ res_list = res[2:-1].split(';')
162
+
163
+ res_list = tuple(
164
+ int(item) if item.isdigit() else item for item in res_list
165
+ )
166
+
167
+ if len(res_list) == 1:
168
+ return types.cast(types.Tuple[int, int], res_list[0])
169
+
170
+ return types.cast(types.Tuple[int, int], tuple(res_list))
171
+
172
+ def row(self, stream):
173
+ row, _ = self(stream)
174
+ return row
175
+
176
+ def column(self, stream):
177
+ _, column = self(stream)
178
+ return column
179
+
180
+
181
+ class RGB(collections.namedtuple('RGB', ['red', 'green', 'blue'])):
182
+ __slots__ = ()
183
+
184
+ def __str__(self):
185
+ return self.rgb
186
+
187
+ @property
188
+ def rgb(self):
189
+ return f'rgb({self.red}, {self.green}, {self.blue})'
190
+
191
+ @property
192
+ def hex(self):
193
+ return f'#{self.red:02x}{self.green:02x}{self.blue:02x}'
194
+
195
+ @property
196
+ def to_ansi_16(self):
197
+ # Using int instead of round because it maps slightly better
198
+ red = int(self.red / 255)
199
+ green = int(self.green / 255)
200
+ blue = int(self.blue / 255)
201
+ return (blue << 2) | (green << 1) | red
202
+
203
+ @property
204
+ def to_ansi_256(self):
205
+ red = round(self.red / 255 * 5)
206
+ green = round(self.green / 255 * 5)
207
+ blue = round(self.blue / 255 * 5)
208
+ return 16 + 36 * red + 6 * green + blue
209
+
210
+ def interpolate(self, end: RGB, step: float) -> RGB:
211
+ return RGB(
212
+ int(self.red + (end.red - self.red) * step),
213
+ int(self.green + (end.green - self.green) * step),
214
+ int(self.blue + (end.blue - self.blue) * step),
215
+ )
216
+
217
+
218
+ class HSL(collections.namedtuple('HSL', ['hue', 'saturation', 'lightness'])):
219
+ '''
220
+ Hue, Saturation, Lightness color.
221
+
222
+ Hue is a value between 0 and 360, saturation and lightness are between 0(%)
223
+ and 100(%).
224
+
225
+ '''
226
+
227
+ __slots__ = ()
228
+
229
+ @classmethod
230
+ def from_rgb(cls, rgb: RGB) -> HSL:
231
+ '''
232
+ Convert a 0-255 RGB color to a 0-255 HLS color.
233
+ '''
234
+ hls = colorsys.rgb_to_hls(
235
+ rgb.red / 255,
236
+ rgb.green / 255,
237
+ rgb.blue / 255,
238
+ )
239
+ return cls(
240
+ round(hls[0] * 360),
241
+ round(hls[2] * 100),
242
+ round(hls[1] * 100),
243
+ )
244
+
245
+ def interpolate(self, end: HSL, step: float) -> HSL:
246
+ return HSL(
247
+ self.hue + (end.hue - self.hue) * step,
248
+ self.lightness + (end.lightness - self.lightness) * step,
249
+ self.saturation + (end.saturation - self.saturation) * step,
250
+ )
251
+
252
+
253
+ class ColorBase(abc.ABC):
254
+ def get_color(self, value: float) -> Color:
255
+ raise NotImplementedError()
256
+
257
+
258
+ class Color(
259
+ collections.namedtuple(
260
+ 'Color',
261
+ [
262
+ 'rgb',
263
+ 'hls',
264
+ 'name',
265
+ 'xterm',
266
+ ],
267
+ ),
268
+ ColorBase,
269
+ ):
270
+ '''
271
+ Color base class.
272
+
273
+ This class contains the colors in RGB (Red, Green, Blue), HSL (Hue,
274
+ Lightness, Saturation) and Xterm (8-bit) formats. It also contains the
275
+ color name.
276
+
277
+ To make a custom color the only required arguments are the RGB values.
278
+ The other values will be automatically interpolated from that if needed,
279
+ but you can be more explicitly if you wish.
280
+ '''
281
+
282
+ __slots__ = ()
283
+
284
+ def __call__(self, value: str) -> str:
285
+ return self.fg(value)
286
+
287
+ @property
288
+ def fg(self):
289
+ return SGRColor(self, 38, 39)
290
+
291
+ @property
292
+ def bg(self):
293
+ return SGRColor(self, 48, 49)
294
+
295
+ @property
296
+ def underline(self):
297
+ return SGRColor(self, 58, 59)
298
+
299
+ @property
300
+ def ansi(self) -> types.Optional[str]:
301
+ if (
302
+ env.COLOR_SUPPORT is env.ColorSupport.XTERM_TRUECOLOR
303
+ ): # pragma: no branch
304
+ return f'2;{self.rgb.red};{self.rgb.green};{self.rgb.blue}'
305
+
306
+ if self.xterm: # pragma: no branch
307
+ color = self.xterm
308
+ elif (
309
+ env.COLOR_SUPPORT is env.ColorSupport.XTERM_256
310
+ ): # pragma: no branch
311
+ color = self.rgb.to_ansi_256
312
+ elif env.COLOR_SUPPORT is env.ColorSupport.XTERM: # pragma: no branch
313
+ color = self.rgb.to_ansi_16
314
+ else: # pragma: no branch
315
+ return None
316
+
317
+ return f'5;{color}'
318
+
319
+ def interpolate(self, end: Color, step: float) -> Color:
320
+ return Color(
321
+ self.rgb.interpolate(end.rgb, step),
322
+ self.hls.interpolate(end.hls, step),
323
+ self.name if step < 0.5 else end.name,
324
+ self.xterm if step < 0.5 else end.xterm,
325
+ )
326
+
327
+ def __str__(self):
328
+ return self.name
329
+
330
+ def __repr__(self):
331
+ return f'{self.__class__.__name__}({self.name!r})'
332
+
333
+ def __hash__(self):
334
+ return hash(self.rgb)
335
+
336
+
337
+ class Colors:
338
+ by_name: ClassVar[
339
+ defaultdict[str, types.List[Color]]
340
+ ] = collections.defaultdict(list)
341
+ by_lowername: ClassVar[
342
+ defaultdict[str, types.List[Color]]
343
+ ] = collections.defaultdict(list)
344
+ by_hex: ClassVar[
345
+ defaultdict[str, types.List[Color]]
346
+ ] = collections.defaultdict(list)
347
+ by_rgb: ClassVar[
348
+ defaultdict[RGB, types.List[Color]]
349
+ ] = collections.defaultdict(list)
350
+ by_hls: ClassVar[
351
+ defaultdict[HSL, types.List[Color]]
352
+ ] = collections.defaultdict(list)
353
+ by_xterm: ClassVar[dict[int, Color]] = dict()
354
+
355
+ @classmethod
356
+ def register(
357
+ cls,
358
+ rgb: RGB,
359
+ hls: types.Optional[HSL] = None,
360
+ name: types.Optional[str] = None,
361
+ xterm: types.Optional[int] = None,
362
+ ) -> Color:
363
+ color = Color(rgb, hls, name, xterm)
364
+
365
+ if name:
366
+ cls.by_name[name].append(color)
367
+ cls.by_lowername[name.lower()].append(color)
368
+
369
+ if hls is None:
370
+ hls = HSL.from_rgb(rgb)
371
+
372
+ cls.by_hex[rgb.hex].append(color)
373
+ cls.by_rgb[rgb].append(color)
374
+ cls.by_hls[hls].append(color)
375
+
376
+ if xterm is not None:
377
+ cls.by_xterm[xterm] = color
378
+
379
+ return color
380
+
381
+ @classmethod
382
+ def interpolate(cls, color_a: Color, color_b: Color, step: float) -> Color:
383
+ return color_a.interpolate(color_b, step)
384
+
385
+
386
+ class ColorGradient(ColorBase):
387
+ def __init__(self, *colors: Color, interpolate=Colors.interpolate):
388
+ assert colors
389
+ self.colors = colors
390
+ self.interpolate = interpolate
391
+
392
+ def __call__(self, value: float) -> Color:
393
+ return self.get_color(value)
394
+
395
+ def get_color(self, value: float) -> Color:
396
+ 'Map a value from 0 to 1 to a color.'
397
+ if (
398
+ value == pbase.Undefined
399
+ or value == pbase.UnknownLength
400
+ or value <= 0
401
+ ):
402
+ return self.colors[0]
403
+ elif value >= 1:
404
+ return self.colors[-1]
405
+
406
+ max_color_idx = len(self.colors) - 1
407
+ if max_color_idx == 0:
408
+ return self.colors[0]
409
+ elif self.interpolate:
410
+ if max_color_idx > 1:
411
+ index = round(
412
+ converters.remap(value, 0, 1, 0, max_color_idx - 1),
413
+ )
414
+ else:
415
+ index = 0
416
+
417
+ step = converters.remap(
418
+ value,
419
+ index / (max_color_idx),
420
+ (index + 1) / (max_color_idx),
421
+ 0,
422
+ 1,
423
+ )
424
+ color = self.interpolate(
425
+ self.colors[index],
426
+ self.colors[index + 1],
427
+ float(step),
428
+ )
429
+ else:
430
+ index = round(converters.remap(value, 0, 1, 0, max_color_idx))
431
+ color = self.colors[index]
432
+
433
+ return color
434
+
435
+
436
+ OptionalColor = types.Union[Color, ColorGradient, None]
437
+
438
+
439
+ def get_color(value: float, color: OptionalColor) -> Color | None:
440
+ if isinstance(color, ColorGradient):
441
+ color = color(value)
442
+ return color
443
+
444
+
445
+ def apply_colors(
446
+ text: str,
447
+ percentage: float | None = None,
448
+ *,
449
+ fg: OptionalColor = None,
450
+ bg: OptionalColor = None,
451
+ fg_none: Color | None = None,
452
+ bg_none: Color | None = None,
453
+ **kwargs: types.Any,
454
+ ) -> str:
455
+ '''Apply colors/gradients to a string depending on the given percentage.
456
+
457
+ When percentage is `None`, the `fg_none` and `bg_none` colors will be used.
458
+ Otherwise, the `fg` and `bg` colors will be used. If the colors are
459
+ gradients, the color will be interpolated depending on the percentage.
460
+ '''
461
+ if percentage is None:
462
+ if fg_none is not None:
463
+ text = fg_none.fg(text)
464
+ if bg_none is not None:
465
+ text = bg_none.bg(text)
466
+ elif fg is not None or bg is not None:
467
+ fg = get_color(percentage * 0.01, fg)
468
+ bg = get_color(percentage * 0.01, bg)
469
+
470
+ if fg is not None: # pragma: no branch
471
+ text = fg.fg(text)
472
+ if bg is not None: # pragma: no branch
473
+ text = bg.bg(text)
474
+
475
+ return text
476
+
477
+
478
+ class SGR(CSI):
479
+ _start_code: int
480
+ _end_code: int
481
+ _code = 'm'
482
+ __slots__ = '_start_code', '_end_code'
483
+
484
+ def __init__(self, start_code: int, end_code: int):
485
+ self._start_code = start_code
486
+ self._end_code = end_code
487
+
488
+ @property
489
+ def _start_template(self):
490
+ return super().__call__(self._start_code)
491
+
492
+ @property
493
+ def _end_template(self):
494
+ return super().__call__(self._end_code)
495
+
496
+ def __call__(self, text, *args):
497
+ return self._start_template + text + self._end_template
498
+
499
+
500
+ class SGRColor(SGR):
501
+ __slots__ = '_color', '_start_code', '_end_code'
502
+
503
+ def __init__(self, color: Color, start_code: int, end_code: int):
504
+ self._color = color
505
+ super().__init__(start_code, end_code)
506
+
507
+ @property
508
+ def _start_template(self):
509
+ return CSI.__call__(self, self._start_code, self._color.ansi)
510
+
511
+
512
+ encircled = SGR(52, 54)
513
+ framed = SGR(51, 54)
514
+ overline = SGR(53, 55)
515
+ bold = SGR(1, 22)
516
+ gothic = SGR(20, 10)
517
+ italic = SGR(3, 23)
518
+ strike_through = SGR(9, 29)
519
+ fast_blink = SGR(6, 25)
520
+ slow_blink = SGR(5, 25)
521
+ underline = SGR(4, 24)
522
+ double_underline = SGR(21, 24)
523
+ faint = SGR(2, 22)
524
+ inverse = SGR(7, 27)