Debian Codegraph @

progressbar/terminal/base.py

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