-
Notifications
You must be signed in to change notification settings - Fork 24
/
fish.py
366 lines (279 loc) · 10.1 KB
/
fish.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""
Swimming fishes progress indicator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Well, what can you say really? It's a swimming fish that animates when you
call a certain function. Simple as that.
How to use:
.. code-block:: python
import fish
for datum_to_churn in data:
fish.animate()
churn_churn(datum_to_churn)
With a progress indicator:
.. code-block:: python
import fish
progress = fish.ProgressFish(total=1000)
for i in range(1000):
progress.animate()
churn()
Using other fish or birds:
.. code-block:: python
from fish import Bird
bird = Bird()
while True:
bird.animate()
churn()
"""
import sys
import time
import string
from struct import unpack
from fcntl import ioctl
from termios import TIOCGWINSZ
from itertools import count
def get_term_width():
"""Get terminal width or None."""
for fp in sys.stdin, sys.stdout, sys.stderr:
try:
return unpack("hh", ioctl(fp.fileno(), TIOCGWINSZ, " "))[1]
except IOError:
continue
class ANSIControl(object):
def __init__(self, outfile=sys.stderr, flush=True):
self.outfile = outfile
self.flush = flush
def ansi(self, command):
self.outfile.write("\x1b[%s" % command)
if self.flush:
self.outfile.flush()
def clear_line_right(self): self.ansi("0K\r")
def clear_line_left(self): self.ansi("1K\r")
def clear_line_whole(self): self.ansi("2K\r")
def clear_forward(self): self.ansi("0J")
def clear_backward(self): self.ansi("1J")
def clear_whole(self): self.ansi("2J")
def save_cursor(self): self.ansi("s")
def restore_cursor(self): self.ansi("u")
def move_up(self, n): self.ansi("%dA" % n)
def move_down(self, n): self.ansi("%dB" % n)
class SwimFishBase(object):
def __init__(self, speed=1.0, world_length=None, outfile=sys.stderr):
if not world_length:
world_length = get_term_width() or 79
self.worldstep = self.make_worldstepper()
self.speed = speed
self.world_length = world_length
self.outfile = outfile
self.ansi = ANSIControl(outfile=outfile)
self.last_hash = 0
def test(self):
while True:
self.animate()
time.sleep(0.0125)
@property
def actual_length(self):
# Refit the world so that we can move along an axis and not worry about
# overflowing
return self.world_length - self.own_length
def animate(self, outfile=None, force=False):
step = next(self.worldstep)
# As there are two directions we pretend the world is twice as large as
# it really is, then handle the overflow
pos = (self.speed * step) % (self.actual_length * 2)
reverse = pos < self.actual_length
pos = int(round(abs(pos - self.actual_length), 0))
fish = self.render(step=step, reverse=reverse)
of = outfile or self.outfile
curr_hash = force or hash((of, pos, "".join(fish)))
if force or curr_hash != self.last_hash:
self.print_fish(of, pos, fish)
of.flush()
self.last_hash = curr_hash
def print_fish(self, of, pos, fish):
raise NotImplementedError("you must choose a printer type")
class SingleLineFishPrinter(SwimFishBase):
def print_fish(self, of, pos, fish):
lead = " " * pos
trail = " " * (self.world_length - self.own_length - pos)
self.ansi.clear_line_whole()
assert len(fish) == 1
of.write(lead + fish[0] + trail + "\r")
class MultiLineFishPrinter(SwimFishBase):
_printed = False
def __init__(self, *args, **kwds):
super(MultiLineFishPrinter, self).__init__(*args, **kwds)
self.reset()
def reset(self):
"""Call this when reusing the animation in a new place"""
self._printed = False
def _restore_cursor(self, lines):
if self._printed:
self.ansi.move_up(lines)
self._printed = True
def print_fish(self, of, pos, fish):
lead = " " * pos
trail = " " * (self.world_length - self.own_length - pos)
self._restore_cursor(len(fish))
self.ansi.clear_forward()
for line in fish:
of.write(lead + line + trail + "\n")
class ProgressableFishBase(SwimFishBase):
"""Progressing fish, only compatible with single-line fish"""
def __init__(self, *args, **kwds):
total = kwds.pop("total", None)
self.total = total
super(ProgressableFishBase, self).__init__(*args, **kwds)
if total:
# `pad` is the length required for the progress indicator,
# It, at its longest, is `100% 123/123`
pad = len(str(total)) * 2
pad += 6
self.world_length -= pad
def test(self):
if not self.total:
return super(ProgressableFishBase, self).test()
for i in range(1, self.total * 2 + 1):
self.animate(amount=i)
time.sleep(0.0125)
def animate(self, *args, **kwds):
prev_amount = getattr(self, "amount", None)
self.amount = kwds.pop("amount", None)
if self.amount != prev_amount:
kwds["force"] = True
return super(ProgressableFishBase, self).animate(*args, **kwds)
def print_fish(self, of, pos, fish):
if not self.amount:
return super(ProgressableFishBase, self).print_fish(of, pos, fish)
# Get the progress text
if self.total:
part = self.amount / float(self.total)
done_text = str(self.amount).rjust(len(str(self.total)))
progress = "%3.d%% %s/%d" % (part * 100, done_text, self.total)
lead = " " * pos
trail = " " * (self.world_length - self.own_length - pos)
else:
progress = str(self.amount)
lead = " " * (pos - len(progress))
trail = " " * (self.world_length - self.own_length - pos - len(progress))
self.ansi.clear_line_whole()
assert len(fish) == 1
of.write(lead + fish[0] + trail + progress + "\r")
class BassLook(SingleLineFishPrinter):
def render(self, step, reverse=False):
return ["<'((<" if reverse else ">))'>"]
own_length = len(">))'>")
class SalmonLook(SingleLineFishPrinter):
def render(self, step, reverse=False):
return ["<*}}}><" if reverse else "><{{{*>"]
def docstring2lines(ds):
return list(filter(None, ds.split("\n")))
try:
maketrans = string.maketrans
except AttributeError:
maketrans = str.maketrans
rev_trans = maketrans(r"/\<>76", r"\/></9")
def ascii_rev(ascii):
return [line.translate(rev_trans)[::-1] for line in ascii]
class BirdLook(MultiLineFishPrinter):
# ASCII credit: "jgs"
bird = r"""
___
_,-' ______
.' .-' ____7
/ / ___7
_| / ___7
>(@)\ | ___7
\\/ \_____,.'__
' _/''&;>*
`'----\\`
"""
bird = docstring2lines(bird)
bird_rev = ascii_rev(bird)
def render(self, step, reverse=False):
return self.bird if reverse else self.bird_rev
own_length = max(map(len, bird))
assert sum(map(len, bird)) / float(len(bird)) == own_length
class DuckLook(MultiLineFishPrinter):
# ASCII art crediT: jgs
duck = docstring2lines("""
_
\. _(9>
\==_)
-'=
""")
duck_rev = docstring2lines("""
_
<6)_ ,/
(_==/
='-
""")
def render(self, step, reverse=False):
return self.duck_rev if reverse else self.duck
own_length = max(map(len, duck))
class SwimFishNoSync(SwimFishBase):
@classmethod
def make_worldstepper(cls):
return count()
class SwimFishTimeSync(SwimFishBase):
@classmethod
def make_worldstepper(cls):
return iter(time.time, None)
class SwimFishProgressSync(ProgressableFishBase):
def make_worldstepper(self):
if self.total:
return iter(self.worldstep_progressive, None)
else:
return count()
def worldstep_progressive(self):
part = self.amount / float(self.total)
step = (self.actual_length + part * self.actual_length) / self.speed
return step
class Fish(SwimFishTimeSync, BassLook):
"""The default swimming fish, the one you very likely want to use.
See module-level documentation.
"""
class ProgressFish(SwimFishProgressSync, BassLook):
"""A progress-based swimming fish."""
class Bird(SwimFishTimeSync, BirdLook):
"""What? A bird?"""
default_fish = Fish()
animate = default_fish.animate
fish_types = {"bass": BassLook,
"salmon": SalmonLook,
"bird": BirdLook,
"duck": DuckLook}
if __name__ == "__main__":
import signal
import argparse
signal.signal(signal.SIGINT, lambda *a: sys.exit(0))
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fish", choices=set(fish_types.keys()) | {"?"},
default="bass", help="fish type (specify ? to list)")
parser.add_argument("-s", "--speed", type=int, default=1, metavar="V",
help="fish speed")
parser.add_argument("--sync", choices=("none", "time"), default="time",
help="synchronization mechanism")
args = parser.parse_args()
if args.fish == "?":
for fish_name, fish_type in fish_types.items():
print(fish_name)
print("=" * len(fish_name))
print()
class TempFish(SwimFishTimeSync, fish_type):
pass
normal = TempFish().render(0, reverse=False)
reverse = TempFish().render(0, reverse=True)
for normline, revline in zip(normal, reverse):
print(normline, " ", revline)
print()
sys.exit(0)
else:
fish_look = fish_types[args.fish]
if args.sync == "time":
fish_sync = SwimFishTimeSync
elif args.sync == "none":
fish_sync = SwimFishNoSync
class FishType(fish_sync, fish_look):
pass
fish = FishType(speed=args.speed)
fish.test()