exhibit.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import os
  2. import random
  3. import re
  4. import sys
  5. import time
  6. from collections import namedtuple
  7. from enum import Enum
  8. from .internal import BARS, SPINNERS, THEMES
  9. from ..animations.spinners import scrolling_spinner_factory, sequential_spinner_factory
  10. from ..animations.utils import spinner_player
  11. from ..core.configuration import config_handler
  12. from ..utils.cells import print_cells
  13. from ..utils import terminal
  14. Show = Enum('Show', 'SPINNERS BARS THEMES')
  15. def showtime(show=Show.SPINNERS, *, fps=None, length=None, pattern=None):
  16. """Start a show, rendering all styles simultaneously in your screen.
  17. Args:
  18. fps (float): the desired frames per second refresh rate
  19. show (Show): chooses which show will run
  20. length (int): the bar length, as in configuration options
  21. pattern (Pattern): to filter objects displayed
  22. """
  23. show_funcs = {
  24. Show.SPINNERS: show_spinners,
  25. Show.BARS: show_bars,
  26. Show.THEMES: show_themes,
  27. }
  28. assert show in show_funcs, 'Which show do you want? We have Show.SPINNERS, Show.BARS, and ' \
  29. 'Show.THEMES.'
  30. show_funcs[show](fps=fps, length=length, pattern=pattern)
  31. Info = namedtuple('Info', 'title descr tech')
  32. def show_spinners(*, fps=None, length=None, pattern=None):
  33. """Start a spinner show, rendering all styles simultaneously in your screen.
  34. Args:
  35. fps (float): the desired frames per second rendition
  36. length (int): the bar length, as in configuration options
  37. pattern (Pattern): to filter objects displayed
  38. """
  39. selected = _filter(SPINNERS, pattern)
  40. max_name_length = max(len(s) for s in selected) + 2
  41. max_natural = max(s.natural for s in selected.values()) + 2
  42. gens = [_spinner_gen(f'{k:^{max_name_length}}', s, max_natural) for k, s in selected.items()]
  43. info = Info(
  44. title=('Spinners', 'including their unknown bar renditions'),
  45. descr=('Spinners generate and run fluid animations, with a plethora of special effects,'
  46. ' including static frames, scrolling, bouncing, sequential, alongside or delayed!',
  47. 'Each type supports several customization options that allow some very cool tricks,'
  48. ' so be creative 😜'),
  49. tech=('Spinners are advanced generators that dynamically output frames to generate some '
  50. 'effect.',
  51. 'These frames are gathered into full cycles, where the spinner yields. This enables'
  52. ' to mix and match them, without ever breaking animations.',
  53. 'All spinners compile their full animations only once before displaying, so they are'
  54. ' faaaast!',
  55. 'The spinner compiler brings the super cool `.check()` tool, check it out!',
  56. 'A spinner have a specific "natural" length, and know how to spread its contents over'
  57. ' any desired space.',))
  58. _showtime_gen(fps, gens, info, length)
  59. def show_bars(*, fps=None, length=None, pattern=None):
  60. """Start a bar show, rendering all styles simultaneously in your screen.
  61. Args:
  62. fps (float): the desired frames per second rendition
  63. length (int): the bar length, as in configuration options
  64. pattern (Pattern): to filter objects displayed
  65. """
  66. selected = _filter(BARS, pattern)
  67. max_name_length = max(len(s) for s in selected) + 2
  68. gens = [_bar_gen(f'{k:>{max_name_length}}', b) for k, b in selected.items()]
  69. info = Info(
  70. title=('Bars', 'playing all their hidden tricks'),
  71. descr=('A bar can render any percentage with a plethora of effects, including dynamic'
  72. ' chars, tips, backgrounds, transparent fills, underflows and overflows!',
  73. 'Bars also support some advanced use cases, which do not go only forward...'
  74. ' Just use manual mode and be creative 😜'),
  75. tech=('Bars are advanced closures that render percentages with some effect, in a specific'
  76. ' fixed length.',
  77. 'Bars are not compiled, but support the super cool `.check()` tool, check it out!',
  78. 'Furthermore, bars can render any external spinners inside its own borders.'))
  79. _showtime_gen(fps, gens, info, length)
  80. def show_themes(*, fps=None, length=None, pattern=None):
  81. """Start a theme show, rendering all styles simultaneously in your screen.
  82. Args:
  83. fps (float): the desired frames per second rendition
  84. length (int): the bar length, as in configuration options
  85. pattern (Pattern): to filter objects displayed
  86. """
  87. selected = _filter(THEMES, pattern)
  88. max_name_length = max(len(s) for s in selected) + 2
  89. themes = {k: config_handler(**v) for k, v in selected.items()}
  90. max_natural = max(t.spinner.natural for t in themes.values())
  91. gens = [_theme_gen(f'{k:>{max_name_length}}', c, max_natural) for k, c in themes.items()]
  92. info = Info(
  93. title=('Themes', 'featuring their bar, spinner and unknown bar companions'),
  94. descr=('A theme is an aggregator, it wraps styles that go well together.',),
  95. tech=('Themes are syntactic sugar, not actually configuration variables (they are elided'
  96. ' upon usage, only their contents go into the config).',
  97. 'But you can surely customize them, just send any additional config parameters to'
  98. ' override anything.'))
  99. _showtime_gen(fps, gens, info, length)
  100. def _filter(source, pattern):
  101. p = re.compile(pattern or '')
  102. selected = {k: v for k, v in source.items() if p.search(k)}
  103. if not selected:
  104. raise ValueError(f'Nothing was selected with pattern "{pattern}".')
  105. return selected
  106. # unfortunately these cool infos increase considerably the animations' lengths, and I think it
  107. # would be ugly to just truncate the animated gifs on the README to try to keep them within
  108. # reasonable sizes (I can't afford to increase them, since they're very large already).
  109. # so they will be kind of an easter egg, showing only on users' machines ;)
  110. _INFO = os.getenv('ALIVE_BAR_EXHIBIT_FULL_INFO', '1') != '0'
  111. def _showtime_gen(fps, gens, info, length):
  112. if not sys.stdout.isatty():
  113. raise UserWarning('This must be run on a tty connected terminal.')
  114. def title(t, r=False):
  115. return scrolling_spinner_factory(t, right=r, wrap=False).pause(center=12), # 1-tuple.
  116. def message(m, s=None):
  117. return scrolling_spinner_factory(f'{m} 👏, {s}!' if s else m, right=False), # 1-tuple.
  118. info_spinners = sequential_spinner_factory(
  119. *(title('Now on stage...')
  120. + message(*info.title)
  121. + sum((message(d) for d in info.descr), ())
  122. + title('Technical details')
  123. + sum((message(d) for d in info.tech), ())
  124. + title('Enjoy 🤩', True)),
  125. intermix=False
  126. )
  127. # initialize generators, retrieve their line lengths, and create information line.
  128. fps, length = min(60., max(2., float(fps or 15.))), length or 40
  129. cols = max(x for _, x in ((next(gen), gen.send((fps, length))) for gen in gens))
  130. fps_monitor = 'fps: {:.1f}'
  131. info_player = spinner_player(info_spinners(max(3, cols - len(fps_monitor.format(fps)) - 1)))
  132. logo = spinner_player(SPINNERS['waves']())
  133. start, sleep, frame, line_num = time.perf_counter(), 1. / fps, 0, 0
  134. start, current = start - sleep, start # simulates the first frame took exactly "sleep" ms.
  135. term = terminal.get_term()
  136. term.hide_cursor()
  137. try:
  138. while True:
  139. cols, lines = os.get_terminal_size()
  140. title = 'Welcome to alive-progress!', ' ', next(logo)
  141. print_cells(title, cols, term) # line 1.
  142. term.clear_end_line()
  143. print()
  144. info = fps_monitor.format(frame / (current - start)), ' ', next(info_player)
  145. print_cells(info, cols, term) # line 2.
  146. term.clear_end_line()
  147. content = [next(gen) for gen in gens] # always consume gens, to maintain them in sync.
  148. for line_num, fragments in enumerate(content, 3):
  149. if line_num > lines:
  150. break
  151. print()
  152. print_cells(fragments, cols, term)
  153. term.clear_end_line()
  154. frame += 1
  155. current = time.perf_counter()
  156. time.sleep(max(0., start + frame * sleep - current))
  157. print(f'\x1b[{line_num - 1}A', end='\r') # ANSI escape sequence for Cursor Up.
  158. except KeyboardInterrupt:
  159. pass
  160. finally:
  161. term.show_cursor()
  162. def _spinner_gen(name, spinner_factory, max_natural):
  163. fps, length = yield
  164. blanks = (' ',) * (max_natural - spinner_factory.natural)
  165. spinner_gen = exhibit_spinner(spinner_factory())
  166. unknown_gen = exhibit_spinner(spinner_factory(length))
  167. yield len(blanks) + spinner_factory.natural + len(name) + length + 4 + 2 # borders/spaces.
  168. while True:
  169. yield (blanks, '|', next(spinner_gen), '| ', name, ' |', next(unknown_gen), '|')
  170. def exhibit_spinner(spinner):
  171. player = spinner_player(spinner)
  172. while True:
  173. yield next(player)
  174. def _bar_gen(name, bar_factory):
  175. fps, length = yield
  176. bar_gen = exhibit_bar(bar_factory(length), fps)
  177. yield len(name) + length + 2 + 1 # borders/spaces.
  178. while True:
  179. yield name, ' ', next(bar_gen)[0]
  180. def exhibit_bar(bar, fps):
  181. total = int(fps * 5)
  182. while True:
  183. # standard use cases, increment till completion, underflow and overflow.
  184. for s, t in (0, total), (0, int(total * .5)), (int(total * .5), int(total + 1)):
  185. for pos in range(s, t):
  186. percent = pos / total
  187. yield bar(percent), percent
  188. # generates a small pause in movement between cases, based on the fps.
  189. percent = t / total
  190. for _ in range(int(fps * 2)):
  191. yield bar.end(percent), percent
  192. # advanced use cases, which do not go always forward.
  193. factor = random.random() + 1 # a number between 1.0 and 2.0.
  194. for percent in (1. - x * factor / total for x in range(total)):
  195. yield bar(percent), percent
  196. # generates a small giggle, like a real gauge.
  197. measure, giggle = random.random(), lambda: (random.random() - .5) * .2
  198. for _ in range(int(fps * 2)):
  199. percent = measure + giggle()
  200. yield bar(percent), percent
  201. # gradually comes to a full stop.
  202. for t in range(int(fps * 5)): # smoother stabilization.
  203. percent = measure + giggle() / 1.04 ** t
  204. yield bar(percent), percent
  205. # enjoy the full stop for a while.
  206. for t in range(int(fps * 2)):
  207. yield bar(measure), measure
  208. def _theme_gen(name, config, max_natural):
  209. fps, length = yield
  210. bar = config.bar(length, config.unknown)
  211. bar_std = exhibit_bar(bar, fps)
  212. bar_unknown = exhibit_bar(bar.unknown, fps)
  213. blanks = (' ',) * (max_natural - config.spinner.natural)
  214. spinner = exhibit_spinner(config.spinner())
  215. yield len(name) + 2 * length + max_natural + 4 + 3 # borders/spaces.
  216. while True:
  217. yield (name, ' ', next(bar_std)[0], ' ', next(spinner), blanks, ' ', next(bar_unknown)[0])