-
Notifications
You must be signed in to change notification settings - Fork 5
/
sailor.py
1481 lines (1180 loc) · 42.3 KB
/
sailor.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import calendar
import curses
import curses.ascii
from curses import textpad
import datetime
import itertools
import logging
import os
import string
logger = logging.getLogger('sailor')
CTRL_A = 1
CTRL_E = ord('e') - ord('a') + 1
CTRL_J = ord('j') - ord('a') + 1
CTRL_K = ord('k') - ord('a') + 1
CTRL_N = ord('n') - ord('a') + 1
CTRL_P = ord('p') - ord('a') + 1
CTRL_U = ord('u') - ord('a') + 1
MAC_BACKSPACE = 127 # Don't feel like finding out why
SHIFT_TAB = 353
CR = 13 # Or Ctrl-M, so don't use that
OTHER_DEL = 330
black = curses.COLOR_BLACK
red = curses.COLOR_RED
green = curses.COLOR_GREEN
white = curses.COLOR_WHITE
blue = curses.COLOR_BLUE
cyan = curses.COLOR_CYAN
magenta = curses.COLOR_MAGENTA
yellow = curses.COLOR_YELLOW
# FIXME: Crash when running off the edges
def reduce_esc_delay():
try:
os.environ['ESCDELAY']
except KeyError:
os.environ['ESCDELAY'] = '25'
def is_enter(ev):
return ev.key in [curses.KEY_ENTER, CR]
def ident(x):
return x
def get_value(x):
return x.value if isinstance(x, Option) else x
def flatten(listOfLists):
return itertools.chain.from_iterable(listOfLists)
class Colorized(object):
def __init__(self, text, color, attr=0):
self.text = text
self.color = color
self.attr = attr
def __str__(self):
return '\0' + str(self.color) + '\1' + str(self.attr) + '\1' + str(self.text) + '\0'
def handle_scroll_key(key, current_row, row_count, scroll_offset, win_height, page_size=10):
"""Handle scrolling one or more lines based on key presses.
Returns:
(change, row_index, scroll_offset) tuple
"""
v_scrolls = {
curses.KEY_UP: -1,
ord('k'): -1,
curses.KEY_PPAGE: -page_size,
ord('K'): -page_size,
curses.KEY_DOWN: 1,
ord('j'): 1,
curses.KEY_NPAGE: page_size,
ord('J'): page_size,
curses.KEY_HOME: -9999999999,
ord('g'): -9999999999,
curses.KEY_END: 9999999999,
ord('G'): 9999999999,
}
if key not in v_scrolls:
return False, current_row, scroll_offset
new_row = max(0, min(current_row + v_scrolls[key], row_count - 1))
if current_row == new_row:
return False, current_row, scroll_offset
scroll_offset = min(scroll_offset, new_row)
scroll_offset = max(scroll_offset, new_row - win_height + 1)
return True, new_row, scroll_offset
#----------------------------------------------------------------------
# VIEW classes
class View(object):
"""Base class for objects that can paint themselves to a curses surface.
Sailor users don't instantiate views. Instead, they instantiate controls,
which render themselves Views to represent their current physical appearance.
"""
def size(self, rect):
"""Return the size that the view takes up."""
return (0, 0)
def display(self, rect):
"""Render the view inside the given rectangle."""
self.rect = rect
if rect.w > 0 and rect.h > 0:
self.disp(rect)
def disp(self, rect):
"""Overridden by subclasses to do the actual rendering."""
raise RuntimeError('Not implemented: disp()')
class Display(View):
"""A view that displays literal characters."""
def __init__(self, text, min_width=0, fg=white, bg=black, attr=0):
if isinstance(text, list):
self.lines = text
else:
self.lines = str(text).split('\n')
self.fg = fg
self.bg = bg
self.min_width = min_width
self.attr = attr
@property
def text(self):
return '\n'.join(self.lines)
def size(self, rect):
return max(self.min_width, max(len(l) for l in self.lines)), len(self.lines)
def disp(self, rect):
col = rect.get_color(self.fg, self.bg)
print_width = max(0, rect.w)
lines = self.lines[:rect.h]
if print_width > 0 and lines:
for i, line in enumerate(lines):
padding = ' ' * min(print_width, self.min_width - len(line))
try:
rect.screen.addstr(rect.y + i, rect.x, line[:print_width] + padding, curses.color_pair(col) | self.attr)
except curses.error, e:
logger.warn(str(e))
class Positioned(View):
"""A view that offsets another view inside the given rectangle."""
def __init__(self, inner, x=-1, y=-1):
self.inner = inner
self.x = x
self.y = y
def size(self, rect):
return self.inner.size(rect)
def disp(self, rect):
size = self.size(rect)
x = max(0, min(self.x, rect.w - size[0]))
irect = Rect(rect.app, rect.screen, x, self.y, size[0], size[1])
irect.clear()
self.inner.display(irect)
class Centered(View):
"""A view that centers another view inside the available rectangle."""
def __init__(self, inner):
self.inner = inner
def size(self, rect):
return rect
def disp(self, rect):
size = self.inner.size(rect)
x = (rect.w - size[0]) / 2
y = (rect.h - size[1]) / 2
irect = rect.sub_rect(x, y, size[0], size[1])
self.inner.display(irect)
class AlignRight(View):
"""A view that right-aligns another view inside the available rectangle."""
def __init__(self, inner, h_margin=2, v_margin=1):
self.inner = inner
self.h_margin = h_margin
self.v_margin = v_margin
def size(self, rect):
return rect.w, rect.h
def disp(self, rect):
w, h = self.inner.size(rect)
irect = rect.adj_rect(rect.w - w - self.h_margin, self.v_margin)
self.inner.display(irect)
class HFill(View):
"""A view that uses a single character to fill out the available width."""
def __init__(self, char, fg=white, bg=black):
self.char = char
self.fg = fg
self.bg = bg
def size(self, rect):
return rect.w, 1
def disp(self, rect):
col = rect.get_color(self.fg, self.bg)
rect.screen.addstr(rect.y, rect.x, self.char * rect.w, curses.color_pair(col))
class Horizontal(View):
"""A view that lays out other views horizontally."""
def __init__(self, views, margin=0):
assert(all(views))
self.views = views
self.margin = margin
def size(self, rect):
sizes = []
for v in self.views:
sizes.append(v.size(rect))
rect = rect.adj_rect(sizes[-1][0], 0)
widths = [s[0] for s in sizes]
heights = [s[1] for s in sizes]
return sum(widths) + max(len(self.views) - 1, 0) * self.margin, max(heights + [0])
def disp(self, rect):
for v in self.views:
v.display(rect)
dx = v.size(rect)[0] + self.margin
rect = rect.adj_rect(dx, 0)
class Grid(View):
"""A view that lays out other views in a grid."""
def __init__(self, grid, h_margin=1, align_right=False):
self.grid = grid
self.h_margin = h_margin
self.align_right = align_right
def size(self, rect):
# FIXME: Not correct for size-adapting controls
self.size_grid = [[col.size(rect) for col in row]
for row in self.grid]
cols = len(self.size_grid[0])
self.col_widths = [max(self.size_grid[i][col_nr][0] for i in range(len(self.size_grid)))
for col_nr in range(cols)]
self.row_heights = [max(col[1] for col in row)
for row in self.size_grid]
w = sum(self.col_widths) + (len(self.col_widths) - 1) * self.h_margin
h = sum(self.row_heights)
return w, h
def disp(self, rect):
for j, row in enumerate(self.grid):
rrect = rect.adj_rect(0, sum(self.row_heights[:j]))
for i, cell in enumerate(row):
col_width = self.col_widths[i]
cell_size = cell.size(rect)
if self.align_right:
rrect = rrect.adj_rect(col_width - cell_size[0], 0)
cell.display(rrect)
rrect = rrect.adj_rect(cell_size[0] + self.h_margin, 0)
class Vertical(View):
"""A view that lays out other views vertically."""
def __init__(self, views, margin=0):
self.views = views
self.margin = margin
def size(self, rect):
sizes = []
for v in self.views:
sizes.append(v.size(rect))
rect = rect.adj_rect(0, sizes[-1][1])
widths = [s[0] for s in sizes]
heights = [s[1] for s in sizes]
return max(widths + [0]), sum(heights) + max(len(self.views) - 1, 0) * self.margin
def disp(self, rect):
for v in self.views:
v.display(rect)
dy = v.size(rect)[1] + self.margin
rect = rect.adj_rect(0, dy)
class Box(View):
"""A box with another view inside it."""
def __init__(self, inner, caption=None, underscript=None, x_margin=1, y_margin=0, x_fill=True, y_fill=False):
self.inner = inner
self.caption = caption
self.underscript = underscript
self.x_margin = x_margin
self.y_margin = y_margin
self.x_fill = x_fill
self.y_fill = y_fill
def size(self, rect):
if not self.x_fill or not self.y_fill:
inner_size = self.inner.size(rect.adj_rect(1 + self.x_margin, 1 + self.y_margin, 1 + self.x_margin, 1 + self.y_margin))
w = rect.w if self.x_fill else inner_size[0] + 2 * (1 + self.x_margin)
h = rect.h if self.y_fill else inner_size[1] + 2 * (1 + self.y_margin)
return w, h
def disp(self, rect):
size = self.size(rect)
rect_w = min(size[0], rect.w)
rect_h = min(size[1], rect.h)
if rect_w > 0 and rect_h > 0:
x1 = rect.x + rect_w - 1
y1 = rect.y + rect_h - 1
# Make sure that we don't draw to the complete end of the screen, because that'll break
screen_h = rect.screen.getmaxyx()[0]
y1 = min(y1, screen_h - 2)
try:
rect.resize(rect_w, rect_h).clear()
textpad.rectangle(rect.screen, rect.y, rect.x, y1, x1)
if self.caption:
self.caption.display(rect.adj_rect(3, 0))
if self.underscript:
s = self.underscript.size(rect)
self.underscript.display(rect.adj_rect(max(3, rect_w - s[0] - 3), rect_h - 1))
except curses.error, e:
# We should not have sent this invalid draw command...
logger.warn(e)
try:
self.inner.display(rect.adj_rect(1 + self.x_margin, 1 + self.y_margin, 1 + self.x_margin, 1 + self.y_margin))
except curses.error, e:
# We should not have sent this invalid draw command...
logger.warn(e)
#----------------------------------------------------------------------
# CONTROL classes
class Control(object):
"""Base class for Controls.
New Control implementations should:
- Pass on constructor **kwargs.
- Put their children in the self.controls member, or override
the children() method.
- Override render() to return an instance of View.
"""
def __init__(self, fg=white, bg=black, id=None):
self.fg = fg
self.bg = bg
self.id = id
self.can_focus = False
self.controls = []
def render(self, app):
raise RuntimeError('Not implemented: render()')
def children(self):
return self.controls
def on_event(self, ev):
pass
def contains(self, ctrl):
if ctrl is self:
return True
for child in self.controls:
if child.contains(ctrl):
return True
return False
def find(self, id):
for parent, child in object_tree(self):
if child.id == id:
return child
raise RuntimeError('No such control: %s' % id)
def _focus_order(self, key):
return (reversed
if key in [curses.KEY_UP, curses.KEY_LEFT, SHIFT_TAB] else
ident)
def enter_focus(self, key, app):
if self.can_focus:
app.layer(self).focus(self)
return True
order = self._focus_order(key)
for child in order(self.children()):
if child.enter_focus(key, app):
return True
return False
class Text(Control):
"""Display some text in the UI."""
def __init__(self, value, **kwargs):
super(Text, self).__init__(**kwargs)
self.value = value
self.can_focus = False
@property
def text(self):
return self.value
def render(self, app):
return Display(self.value, fg=self.fg, bg=self.bg)
def propagate_focus(ev, controls, layer, keys_back, keys_fwd):
"""Propagate focus events forwards and backwards through a list of controls."""
if ev.type == 'key':
if ev.key in keys_back + keys_fwd:
back = ev.key in keys_back
current = ev.app.find_ancestor(ev.last, controls)
if not current:
return False
i = controls.index(current)
while 0 <= i < len(controls) and ev.propagating:
i += -1 if back else 1
if 0 <= i < len(controls) and controls[i].enter_focus(ev.key, ev.app):
ev.stop()
return True
return False
class Panel(Control):
"""Contains other controls vertically, surrounds them with a box."""
def __init__(self, controls, caption=None, underscript=None, **kwargs):
super(Panel, self).__init__(**kwargs)
self.controls = controls
self.caption = caption
self.underscript = None
def render(self, app):
return Box(Vertical([c.render(app) for c in self.controls]),
caption=self.caption.render(app) if self.caption else None,
underscript=self.underscript.render(app) if self.underscript else None)
def on_event(self, ev):
propagate_focus(ev, self.controls, ev.app.layer(self),
[curses.KEY_UP, SHIFT_TAB],
[curses.KEY_DOWN, curses.ascii.TAB])
class Stacked(Control):
"""Just lays out other controls vertically, no decoration."""
def __init__(self, controls, **kwargs):
super(Stacked, self).__init__(**kwargs)
self.controls = controls
def render(self, app):
return Vertical([c.render(app) for c in self.controls])
def on_event(self, ev):
propagate_focus(ev, self.controls, ev.app.layer(self),
[curses.KEY_UP, SHIFT_TAB],
[curses.KEY_DOWN, curses.ascii.TAB])
class Option(object):
"""Helper class to attach data to a string.
This object contains one value, but stringifies to a user-chosen
string, making it ideal for separating symbolic values from human
representation in selection lists/comboboxes.
"""
def __init__(self, value, caption=None):
self.value = value
self.caption = caption or str(value)
def __str__(self):
return self.caption
def __eq__(self, other):
if not isinstance(other, Option):
return self.value == other
return self.value == other.value
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.value)
def __str__(self):
return self.caption
def __repr__(self):
return 'Option(%r, %r)' % (self.value, self.caption)
class Labeled(Control):
"""Applies an offset to a control, fill it with a text label."""
def __init__(self, label, control, **kwargs):
super(Labeled, self).__init__(**kwargs)
assert(control)
self.label = label
self.control = control
def render(self, app):
fg = white if app.contains_focus(self) else green
attr = curses.A_BOLD if app.contains_focus(self) else 0
return Horizontal([Display(self.label, min_width=16, fg=fg, attr=attr),
self.control.render(app)])
def children(self):
return [self.control]
class SelectList(Control):
"""Selection list.
Displays a set of values with an initial selected index, and lets the user
change the selection.
The `selectList.value` property contains the selected value.
"""
def __init__(self, choices, index=0, width=30, height=10, show_captions_at=0, **kwargs):
super(SelectList, self).__init__(**kwargs)
self.choices = choices
self.index = index
self.width = width
self.height = height
self.scroll_offset = max(0, min(self.index, len(self.choices) - height))
self.can_focus = True
self.show_captions_at = show_captions_at
def adjust(self, d):
"""Scroll by the given delta through the options."""
if len(self.choices) > 1:
self.index = (self.index + d + len(self.choices)) % len(self.choices)
self.scroll_offset = min(self.scroll_offset, self.index)
self.scroll_offset = max(self.scroll_offset, self.index - self.height + 1)
def sanitize_index(self):
self.index = min(max(0, self.index), len(self.choices) - 1)
return 0 <= self.index < len(self.choices)
@property
def value(self):
"""Return the currently selected value."""
return get_value(self.choices[self.index])
@value.setter
def value(self, value):
"""Set the currently selected value.
Reset to 0 if not in the list.
"""
self.index = max(0, self.choices.index(value))
def _render_line(self, line, selected):
attr = curses.A_STANDOUT if selected else 0
if self.show_captions_at and isinstance(line, Option):
rem = self.width - self.show_captions_at
return Horizontal([
Display(str(line.value)[:self.show_captions_at], min_width=self.show_captions_at, attr=attr),
Display(str(line.caption)[:rem], min_width=rem, attr=attr, fg=cyan if not selected else white)
])
return Display(line, min_width=self.width, attr=attr)
def render(self, app):
self.sanitize_index()
lines = self.choices[self.scroll_offset:self.scroll_offset + self.height]
lines.extend([''] * (self.height - len(lines)))
self.last_render = Vertical([self._render_line(l, i + self.scroll_offset == self.index) for i, l in enumerate(lines)])
# FIXME: Scroll bar
return self.last_render
def on_event(self, ev):
if ev.type == 'key':
change, self.index, self.scroll_offset = handle_scroll_key(ev.key, self.index, len(self.choices), self.scroll_offset, self.last_render.rect.h)
if change:
ev.stop()
class SelectDate(Control):
"""A Calendar control for selecting a date.
`.value` contains the date as a datetime.datetime.
`.date` contains the date date as a datetime.date.
"""
def __init__(self, value=None, **kwargs):
super(Control, self).__init__(**kwargs)
self.can_focus = True
self.value = value or datetime.datetime.now()
self.controls = []
def _render_monthcell(self, cell):
if not cell:
return Display('')
attr = 0
if cell == self.value.day:
attr = curses.A_STANDOUT if self.has_focus else curses.A_UNDERLINE
return Display(str(cell), attr=attr)
@property
def date(self):
return self.value.date()
def render(self, app):
self.has_focus = app.contains_focus(self)
cal_data = calendar.monthcalendar(self.value.year, self.value.month)
cal_header = [[Display(t, fg=green) for t in calendar.weekheader(3).split(' ')]]
assert(len(cal_data[0]) == len(cal_header[0]))
cells = [[self._render_monthcell(cell) for cell in row]
for row in cal_data]
month_name = Display('%s, %s' % (self.value.strftime('%B'), self.value.year))
grid = Grid(cal_header + cells, align_right=True)
return Vertical([month_name, grid])
def on_event(self, ev):
if ev.type == 'key':
if ev.what == ord('t'):
self.value = datetime.datetime.now()
ev.stop()
if ev.what == curses.KEY_LEFT:
self.value += datetime.timedelta(days=-1)
ev.stop()
if ev.what == curses.KEY_RIGHT:
self.value += datetime.timedelta(days=1)
ev.stop()
if ev.what == curses.KEY_UP:
self.value += datetime.timedelta(weeks=-1)
ev.stop()
if ev.what == curses.KEY_DOWN:
self.value += datetime.timedelta(weeks=1)
ev.stop()
class Composite(Control):
"""Horizontal composition of other controls."""
def __init__(self, controls, margin=0, **kwargs):
super(Composite, self).__init__(**kwargs)
self.controls = controls
self.margin = margin
def render(self, app):
m = Display(' ' * self.margin)
xs = [c.render(app) for c in self.controls]
rendered = list(itertools.chain(*list(zip(xs, itertools.repeat(m)))))
return Horizontal(rendered)
def on_event(self, ev):
propagate_focus(ev, self.controls, ev.app.layer(self),
[curses.KEY_LEFT, SHIFT_TAB],
[curses.KEY_RIGHT, curses.ascii.TAB])
def _focus_order(self, key):
"""If we enter the control from the bottom, still focus the first element."""
return (reversed
if key in [curses.KEY_LEFT, SHIFT_TAB] else
ident)
class Popup(Control):
"""Show a modal popup that contains another control.
After instantiating this object, call `popup.show(app)`.
The popup is automatically removed when an ENTER or ESC
keypress escapes the focused control, but on_close will
only be called if ENTER was used to remove the popup.
"""
def __init__(self, inner, on_close, x=-1, y=-1, caption='', underscript='', **kwargs):
super(Popup, self).__init__(**kwargs)
self.x = x
self.y = y
self.inner = inner
self.on_close = on_close
self.caption = caption
self.underscript = underscript
def render(self, app):
inner = Box(self.inner.render(app),
x_fill=False,
caption=Display(self.caption),
underscript=Display(self.underscript))
if self.x == -1 or self.y == -1:
return Centered(inner)
return Positioned(inner, x=self.x, y=self.y)
def children(self):
return [self.inner]
def show(self, app):
self.layer = app.push_layer(self)
def on_event(self, ev):
if ev.type == 'key':
if ev.key == curses.ascii.ESC:
self.layer.remove()
ev.stop()
if is_enter(ev):
self.on_close(self, ev.app)
self.layer.remove()
ev.stop()
def EditPopup(app, on_close, value='', caption=''):
"""Show a popup with to edit a value."""
Popup(Edit(value=value, min_size=30, fg=cyan), caption=caption, on_close=on_close).show(app)
class Combo(Control):
"""A SelectList in a popup."""
def __init__(self, choices, index=0, **kwargs):
super(Combo, self).__init__(**kwargs)
self._choices = choices
self.index = index
self.can_focus = True
self.last_combo = None
def sanitize_index(self):
self.index = min(max(0, self.index), len(self.choices) - 1)
return 0 <= self.index < len(self.choices)
@property
def choices(self):
if callable(self._choices):
return self._choices()
return self._choices
@property
def value(self):
if not self.sanitize_index():
return None
return get_value(self.choices[self.index])
@value.setter
def value(self, value):
try:
self.index = max(0, self.choices.index(value))
except ValueError:
self.index = 0
@property
def caption(self):
if not self.sanitize_index():
return '-unset-'
return str(self.choices[self.index])
def render(self, app):
attr = curses.A_STANDOUT if app.contains_focus(self) else 0
self.last_combo = Display(self.caption, attr=attr)
return self.last_combo
def on_event(self, ev):
if ev.type == 'key':
if is_enter(ev):
x = max(0, self.last_combo.rect.x - 2)
y = max(0, self.last_combo.rect.y - 1)
Popup(SelectList(self.choices, self.index), self.on_popup_close, x=x, y=y).show(ev.app)
ev.stop()
def on_popup_close(self, popup, app):
self.index = popup.inner.index
class Toasty(Control):
def __init__(self, text, duration=datetime.timedelta(seconds=3), border=True, **kwargs):
super(Toasty, self).__init__(**kwargs)
self.text = text
self.duration = duration
self.border = border
def render(self, app):
inner = Display(self.text, fg=self.fg)
if self.border:
inner = Box(inner, x_fill=False)
return AlignRight(inner)
def show(self, app):
self.layer = app.push_layer(self, modal=False)
app.enqueue(self.duration, self._done)
def _done(self, app):
self.layer.remove()
class DateCombo(Control):
"""A SelectDate in a popup."""
def __init__(self, value=None, **kwargs):
super(DateCombo, self).__init__(**kwargs)
self.value = value or datetime.datetime.now()
self.can_focus = True
@property
def date(self):
return self.value.date()
def render(self, app):
attr = curses.A_STANDOUT if app.contains_focus(self) else 0
visual = self.value.strftime('%B %d, %Y')
self.last_combo = Display(visual, attr=attr)
return self.last_combo
def on_event(self, ev):
if ev.type == 'key':
if is_enter(ev):
x = max(0, self.last_combo.rect.x - 2)
y = max(0, self.last_combo.rect.y - 1)
Popup(SelectDate(self.value), self.on_popup_close, x=x, y=y).show(ev.app)
ev.stop()
def on_popup_close(self, popup, app):
self.value = popup.inner.value
class Time(Composite):
"""A time selection control."""
def __init__(self, value=None, **kwargs):
self.value = value or datetime.datetime.utcnow().time()
now_h = self.value.strftime('%H')
now_m = '%02d' % (int(self.value.minute / 5) * 5)
hours = ['%02d' % h for h in range(0, 24)]
minutes = ['%02d' % m for m in range(0, 60, 5)]
self.hour_combo = Combo(id='hour', choices=hours, index=hours.index(now_h))
self.min_combo = Combo(id='min', choices=minutes, index=minutes.index(now_m))
super(Time, self).__init__([
self.hour_combo,
Text(':'),
self.min_combo,
Text(' UTC')], **kwargs)
@property
def time(self):
return datetime.time(int(self.hour_combo.value), int(self.min_combo.value))
class Edit(Control):
"""Standard text edit control.
Arguments:
highlight, fn: a syntax highlighting function. Will be given a string, and
should return a list of curses (color, attributes), one for every
character.
"""
def __init__(self, value, min_size=0, highlight=None, **kwargs):
super(Edit, self).__init__(**kwargs)
self._value = value
self.min_size = min_size
self.can_focus = True
self.cursor = len(value)
self.highlight = highlight
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self.cursor = len(value)
def render(self, app):
focused = app.contains_focus(self)
# Default highlighting, foreground color
colorized = self.value
if self.highlight:
# Custom highlighting
try:
colorized = self.highlight(self.value)
except Exception, e:
logger.error(str(e))
# Make the field longer for the cursor or display purposes
ext_len = max(0, max(self.cursor + 1 if focused else 0, self.min_size) - len(self.value))
colorized += ' ' * ext_len
# Render that momma
self.rendered = Horizontal(self._render_colorized(colorized, focused))
return self.rendered
def _render_colorized(self, colorized, focused):
"""Split a colorized string into Display() slices."""
base_attr = 0
if focused:
base_attr = curses.A_UNDERLINE
frag_list = []
parts = colorized.split('\0')
chars_so_far = 0
for i in range(0, len(parts), 2):
# i is regular, i+1 is colorized (if it's there)
frag_list.append(Display(parts[i], fg=self.fg, attr=base_attr))
if focused:
chars_so_far = self._inject_cursor(chars_so_far, frag_list)
if i + 1 < len(parts):
color, attr, text = parts[i+1].split('\1')
frag_list.append(Display(text, fg=int(color), attr=base_attr+int(attr)))
if focused:
chars_so_far = self._inject_cursor(chars_so_far, frag_list)
return frag_list
def _inject_cursor(self, chars_so_far, frag_list):
"""If the cursor falls into this fragment, highlight it."""
last = frag_list[-1]
if chars_so_far <= self.cursor < chars_so_far + len(last.text):
offset = self.cursor - chars_so_far
pre, hi, post = last.text[:offset], last.text[offset], last.text[offset+1:]
frag_list[-1:] = [Display(pre, fg=last.fg, attr=last.attr),
Display(hi, fg=last.fg, attr=last.attr + curses.A_STANDOUT),
Display(post, fg=last.fg, attr=last.attr)]
return chars_so_far + len(last.text)
def on_event(self, ev):
if ev.type == 'key':
if ev.key in [CTRL_A, curses.KEY_HOME]:
self.cursor = 0
ev.stop()
if ev.key in [CTRL_E, curses.KEY_END]:
self.cursor = len(self._value)
ev.stop()
if ev.key in [curses.KEY_BACKSPACE, MAC_BACKSPACE]:
if self.cursor > 0:
self._value = self._value[:self.cursor-1] + self._value[self.cursor:]
self.cursor = max(0, self.cursor - 1)
ev.stop()
elif ev.key in [curses.ascii.DEL, OTHER_DEL]:
if self.cursor < len(self._value) - 1:
self._value = self._value[:self.cursor] + self._value[self.cursor+1:]
ev.stop()
if ev.key == curses.KEY_LEFT and self.cursor > 0:
self.cursor -= 1
ev.stop()
if ev.key == curses.KEY_RIGHT and self.cursor < len(self._value):
self.cursor += 1
ev.stop()
if ev.key == CTRL_U:
self.value = ''
self.cursor = 0
ev.stop()
if 32 <= ev.key < 127:
self._value = self._value[:self.cursor] + chr(ev.key) + self._value[self.cursor:]
self.cursor += 1
ev.stop()
class AutoCompleteEdit(Edit):
"""Edit control with autocomplete.
complete_fn is a function that gets the current word under
the cursor, and should return all possible completions.
"""
def __init__(self, value, complete_fn, min_size=0, letters=string.letters, **kwargs):
super(AutoCompleteEdit, self).__init__(value=value, min_size=min_size, **kwargs)
self.complete_fn = complete_fn
self.popup_visible = False
self.select = SelectList([], 0, width=70, show_captions_at=30)
self.popup = Popup(self.select, on_close=self.on_close, underscript='( ^N, ^P to move, Enter to select )')
self.layer = None
self.letters = letters
def on_close(self):
pass
def show_popup(self, app, visible):
if visible and not self.layer:
self.popup.x = self.rendered.rect.x