Repository navigation
Expand file tree
/
Copy pathwidgets.py
More file actions
1618 lines (1233 loc) · 47.7 KB
/
Copy pathwidgets.py
File metadata and controls
1618 lines (1233 loc) · 47.7 KB
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
# Filename: widgets.py
# Creation Date: Thu 08 Oct 2015
# Last Modified: Thu 17 Dec 2015 11:01:48 AM MST
# Author: Brett Fedack
import math
import curses
import curses.ascii as ascii
import weakref
from . import signals
from .core import Widget, ContentWidget, Group
class Button(ContentWidget):
'''
Push button widget
Attributes:
_is_pushed (bool): Button state
'''
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
# Initialize size.
self.fit()
def report(self):
return {'usage': 'Enter:Execute'}
def focus(self, **kwargs):
# This button has yet to be pushed.
self._is_pushed = False
def compose(self):
# Bubble a data signal if this button was pressed.
return (self._is_pushed, {})
def draw(self):
width = self.get_size()[0]
# Draw bounding parenthesis.
self.draw_text('(', attr = self.style('text'))
self.draw_text(')', margin = (width - 1, 0, 0, 0), attr = self.style('text'))
# Draw button label within parenthesis.
self.draw_text(self._label, padding = (1, 1), margin = (1, 1, 0, 0), align = 'CENTER', hint = self._focus_key, attr = self.style('text'))
def operate(self, c):
# Push this button.
if c in {curses.KEY_ENTER, ascii.LF, ascii.CR}:
self._is_pushed = True
return 'END'
return 'CONTINUE'
def fit(self):
''' Fits button to padded label width '''
self.resize(len(self._label) + 4, 1)
class StatusLine(ContentWidget):
'''
Displays usage instructions, feedback messages, and confirmation prompts
Attributes:
_error (bool):
_mode (str): Mode of operation in
{'PROMPT_CONFIRM', 'DISPLAY_FEEDBACK'}
_feedback (str): Message containing feedback
_prompt (str): Confirmation prompt
_sigconfirm (str): Name of confirmation signal to emit
_status (str): Status report
'''
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
# Setup signal handling.
self.add_signal_handler('UI_FEEDBACK', self._display_feedback)
self.add_signal_handler('UI_PROMPT_CONFIRM', self._prompt_confirm)
self.add_signal_handler('UI_UPDATE_STATUS', self._update_status)
# Initialize attributes.
self._mode = ''
self._error = ''
self._feedback = ''
self._prompt = ''
self._sigconfirm = ''
self._status = ''
self._timer = 0
def draw(self):
text = ''
post_text = ''
spacer = 3
margin = [1, 1, 1, 1]
attr = self.style('status')
width, height = self.get_size()
# Format text according to focus state and mode of operation.
if Widget.input_focus is self:
if self._mode == 'PROMPT_CONFIRM':
post_text = 'Enter:OK, Esc:Cancel'
text = self._prompt
elif self._mode == 'DISPLAY_FEEDBACK':
text = ('ERROR' if self._error else 'SUCCESS') + ': ' + self._feedback
post_text = 'Enter/Esc:Continue'
attr = self.style('error') if self._error else self.style('success')
margin[1] += len(post_text) + spacer
else:
text = self._status
# Tag for redraw in order to animate the scroll.
effective_width = width - margin[0] - margin[1]
if len(text) > effective_width:
self.tag_redraw()
# Draw status line text content.
self.draw_text(text, row = 1, margin = margin, fit = 'AUTO_SCROLL', attr = attr)
margin = [width - len(post_text) - 1, 1, 1, 1]
self.draw_text(post_text, row = 1, margin = margin, attr = attr)
# Draw border around status line.
self.draw_border(attr = attr)
def operate(self, c):
# Display prompt until user either confirms or cancels.
if self._mode == 'PROMPT_CONFIRM':
# Confirm.
if c in {curses.KEY_ENTER, ascii.LF, ascii.CR}:
# Emit the requested confirmation signal.
self.bubble(**self._sigconfirm.data)
return 'END'
# Display feedback message until user presses a key.
elif self._mode == 'DISPLAY_FEEDBACK':
if c in {curses.KEY_ENTER, ascii.LF, ascii.CR}:
return 'END'
return 'CONTINUE'
def _display_feedback(self, message, error, **kwargs):
'''
Prompts the user for confirmation (OK, Cancel)
Parameters:
prompt (str): Confirmation request message
sigconfirm (Signal): Signal to emit upon confirmation
'''
self._mode = 'DISPLAY_FEEDBACK'
self._feedback = message
self._error = error
Widget.input_focus = self
def _prompt_confirm(self, prompt, sigconfirm, **kwargs):
'''
Prompts the user for confirmation (OK, Cancel)
Parameters:
prompt (str): Confirmation request message
sigconfirm (Signal): Signal to emit upon confirmation
'''
self._mode = 'PROMPT_CONFIRM'
self._prompt = prompt
self._sigconfirm = sigconfirm
Widget.input_focus = self
def _update_status(self, status, **kwargs):
''' Updates status line usage information '''
self.update_timestamp()
self._status = status
self.tag_redraw()
class Tab(ContentWidget):
'''
Tabbed container for widgets
Attributes:
_tab_list (list<Tab>): List of sibling tabs
'''
@property
def content_region(self):
'''
Creates a group for the valid content region of this widget
Returns:
Group: Valid content region
'''
region = Group(self)
region.scale(height = -2).offset(y = 2).inset(1)
return region
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
# Initialize attributes.
self._tab_list = []
# Update tab list.
tab_list = [node for node in parent._children if isinstance(node, Tab)]
# Synchronize sibling tab lists.
for tab in tab_list:
tab._tab_list = tab_list
# Only show the first tab of the list.
tab_list[0].show()
for tab in tab_list[1:]:
tab.hide()
def focus(self, **kwargs):
# Hide all sibling tabs.
for tab in self._tab_list:
tab.hide()
self.show()
def draw(self):
width, height = self.get_size()
margin = [2, 1, 1, height - 3]
margin_left = margin_right = 0
# Draw sibling tabs.
for tab in self._tab_list:
# Determine dimensions of tab label.
tab_width = len(tab.label) + 4
margin[1] = width - margin[0] - tab_width
# Draw border around sibling tab's label.
if tab is self:
margin_left = margin[0]
margin_right = margin[1]
else:
self.draw_border(
offset_left = margin[0],
offset_right = margin[1],
offset_bottom = margin[3],
attr = self.style('inactive')
)
margin[0] += 2
# Draw sibling tab's label.
if tab is not self:
self.draw_text(
tab.label, row = 1, margin = margin, hint = tab._focus_key,
attr = self.style('inactive')
)
margin[0] += tab_width
# Add border around contained widgets.
self.draw_border(offset_top = 2)
# Draw border around this tab.
margin[0] = margin_left
margin[1] = margin_right
self.draw_border(
offset_left = margin[0],
offset_right = margin[1],
offset_bottom = margin[3],
char_bottom = ord(' '),
char_bottom_left = curses.ACS_LRCORNER,
char_bottom_right = curses.ACS_LLCORNER
)
margin[0] += 2
# Draw this tab's label.
self.draw_text(
self._label, row = 1, margin = margin, hint = self._focus_key,
attr = self.style('label')
)
class VertTab(Tab):
''' Tabbed container for widgets (aligned vertically) '''
@property
def content_region(self):
'''
Creates a widget group for the valid content region of this tab
Returns:
Group: Valid content region
'''
tab_width = max([len(node.label) for node in self._tab_list]) + 4
region = Group(self)
region.scale(width = -1 * (tab_width - 1))
region.offset(tab_width - 1).inset(1)
return region
def draw(self):
width, height = self.get_size()
tab_list = self._tab_list
# Determine width of all tabs.
tab_width = max([len(node.label) for node in self._tab_list]) + 4
# Draw sibling tabs.
tab_offset = 1
margin = (2, width - tab_width + 2, 1, 1)
for i in range(len(tab_list)):
tab = tab_list[i]
# Draw border around sibling tab's label.
if tab is self:
si = i
else:
self.draw_border(
offset_right = width - tab_width,
offset_top = 3 * i + tab_offset,
offset_bottom = height - (3 * i + 2 + tab_offset) - 1,
attr = self.style('inactive')
)
# Draw sibling tab's label.
if tab is not self:
self.draw_text(
tab.label, row = 3 * i + 1 + tab_offset, margin = margin, hint = tab._focus_key,
attr = self.style('inactive')
)
# Add border around contained widgets.
self.draw_border(offset_left = tab_width - 1)
# Draw border around this tab.
self.draw_border(
offset_right = width - tab_width,
offset_top = 3 * si + tab_offset,
offset_bottom = height - (3 * si + 2 + tab_offset) - 1,
char_right = ord(' '),
char_top_right = curses.ACS_LRCORNER,
char_bottom_right = curses.ACS_URCORNER
)
# Draw this tab's label.
self.draw_text(
self._label, row = 3 * si + 1 + tab_offset, margin = margin, hint = self._focus_key,
attr = self.style('label')
)
class Text(ContentWidget):
'''
Text display widget
Attributes
_line_list (list<str>): Lines of text
'''
def __init__(self, label, parent, style = 'text'):
'''
Parameters:
style (str): Theme style attribute for text content
'''
# Initialize inherited state.
super().__init__(label, parent)
# Prevent this widget from receiving input focus.
self._is_focusable = False
# Initialize attributes.
self._style = style
self._line_list = []
def draw(self):
# Draw all lines of text.
line_list = self._line_list
for i in range(len(line_list)):
line = line_list[i]
self.draw_text(line, row = i, attr = self.style(self._style))
def add_line(self, line):
'''
Adds given line of text to this widget
Parameters:
line (str): Line of text
'''
self._line_list.append(line)
def add_raw(self, raw):
'''
Adds given raw string, line-by-line, to this widget
Parameters:
raw (str): Raw string
'''
for line in raw.splitlines():
self.add_line(line)
class Label(ContentWidget):
'''
Widget that is used to display the label of another widget
Attributes:
_used_by (weakref<Widget>): Reference to widget that uses this label
_text (str): Embellished text representation of the label
'''
@property
def used_by(self):
return self._used_by() if self._used_by else None
def __init__(self, parent, used_by):
# Initialize attributes.
self._used_by = weakref.ref(used_by)
self._label = used_by._label
# Initialize inherited state.
super().__init__(self._label, parent)
# Prevent this widget from receiving input focus.
self._is_focusable = False
# Initialize size.
self.fit()
def draw(self):
# Used referenced style.
style = self.used_by.style
# Draw the embellished label.
self.draw_text(self.label, attr = style('label'), hint = self.used_by._focus_key)
def embellish(self, prefix = '', suffix = ''):
'''
Embellishes the label with leading and trailing text
Parameters:
prefix (str): Text to add before label (Optional)
suffix (str): Text to add after label (Optional)
Returns:
Widget: Alias to this widget
'''
self._label = prefix + self.used_by._label + suffix
self.fit()
return self
def fit(self):
'''
Fits this widget's dimensions to its content
Returns:
Widget: Alias to this widget
'''
self.resize(len(self._label), 1)
return self
def shift(self, multiple):
'''
Offsets horizontally by a multiple of this label's width
Parameters:
multiple (float): Scalar multiple of label's width
Returns:
Widget: Alias to this widget
'''
self.offset(x = round(multiple * self.get_size()[0]))
return self
def to_center(self, cross = False):
'''
Moves this label to the center of the widget that uses it
Parameters:
cross (bool): Cross-alignment flag (Optional)
Returns:
Widget: Alias to this widget
'''
ux, uy = self.used_by.get_position()
uw, uh = self.used_by.get_size()
sw, sh = self.get_size()
if cross:
self.move(y = uy + int((uh - sh) / 2))
else:
self.move(x = ux + int((uw - sw) / 2))
return self
def to_left(self):
'''
Moves this label to the left edge of the widget that uses it
Returns:
Widget: Alias to this widget
'''
ux = self.used_by.get_position()[0]
self.move(x = ux)
return self
def to_right(self):
'''
Moves this label to the right edge of the widget that uses it
Returns:
Widget: Alias to this widget
'''
ux = self.used_by.get_position()[0]
uw = self.used_by.get_size()[0]
sw = self.get_size()[0]
self.move(x = ux + uw - sw)
return self
def to_top(self):
'''
Moves this label to the top edge of the widget that uses it
Returns:
Widget: Alias to this widget
'''
uy = self.used_by.get_position()[1]
self.move(y = uy)
return self
def to_bottom(self):
'''
Moves this label to the bottom edge of the widget that uses it
Returns:
Widget: Alias to this widget
'''
uy = self.used_by.get_position()[1]
uh = self.used_by.get_size()[1]
self.move(y = uy + uh - 1)
return self
class Labeled(ContentWidget):
'''
Class of widgets where each displays its label in a separate sibling
widget, allowing label to be displayed outside of this widget's bounds
Attributes:
_linked_label (weakref<Widget>): Widget to use for this widget's label
'''
@property
def linked_label(self):
''' Getter for "linked_label" property '''
return self._linked_label() if self._linked_label else None
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
# Insert label node into the tree of widgets.
label = Label(parent, used_by = self)
# Link this widget to the label.
ref = weakref.ref(label)
self._linked_label = ref
self._links.append(ref)
class FlipSwitch(Labeled):
'''
Boolean state widget
Attributes:
_init_state (bool): Switch state upon receiving focus
_on (bool): Flag indicating if this widget is switched on
'''
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
self._overrides_enter = True
# Initialize attributes.
self._init_state = False
self._on = False
# Initialize size.
self.resize(10, 3)
def report(self):
return {'usage': 'Enter:Toggle'}
def focus(self, **kwargs):
# Store initial switch state.
self._init_state = self._on
def compose(self):
return (self._on != self._init_state, {'enabled': self._on})
def draw(self):
width = self.get_size()[0]
half_width = width // 2
# Draw a border around the switch.
self.draw_border()
# Draw switch to the right-side if on; left-side otherwise.
if self._on:
self.draw_border(offset_left = half_width)
else:
self.draw_border(offset_right = half_width)
# Indicate switch state.
text = 'ON' if self._on else 'OFF'
margin = (2, half_width, 1, 1) if self._on else (half_width, 1, 1, 1)
self.draw_text(text, row = margin[2], margin = margin, attr = self.style('text') | curses.A_BOLD)
def operate(self, c):
# Toggle switch state.
if c in {curses.KEY_ENTER, ascii.LF, ascii.CR}:
self.tag_redraw()
self._on = not self._on
return 'CONTINUE'
class NavPage(ContentWidget):
'''
Container for widgets that is controlled by a navigation list
'''
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
def draw(self):
# Draw a border around the page.
self.draw_border()
# Indicate selection in navlist.
left_arrow = u'\u25C0'
self.draw_text(left_arrow, row = self._parent._selection + 1)
class NavList(Labeled):
'''
Navigable list of containers for widgets (pages)
Attributes:
_page_list (list<NavPage>): List of associated pages
_highlight (int): Index in page list of highlighted option
_selection (int): Index in page list of selected option
_list_width (int): Width of this widget reserved for list
'''
@property
def list_width(self):
''' Getter for "list_width" property '''
return self._list_width
@list_width.setter
def list_width(self, value):
''' Setter for "list_width" property '''
# Set value.
self._list_width = value
# Update position of navlist's label.
linked_label = self.linked_label
linked_label.to_top().to_left().embellish(' ', ' ')
linked_label.offset(x = (value - len(linked_label._label)) // 2)
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
self._overrides_enter = True
# Initialize attributes.
self._page_list = []
self._highlight = 0
self._selection = None
self.list_width = 15
def focus(self, **kwargs):
# Highlight selected page.
self._highlight = self._selection if self._selection else 0
def new_page(self, label):
'''
Creates a page and inserts it into this navlist
Parameters:
label (str): Identifier for page in navlist
Returns:
NavPage: Alias to created page
'''
# Create a widget to serve as a container for page elements.
page = NavPage(label, self)
# Select the first page by default.
if self._page_list:
page.hide()
else:
self._selection = 0
# Associate page with this navlist.
self._page_list.append(page)
# Initialize page layout.
sx, sy = self.get_position()
sw, sh = self.get_size()
list_width = self.list_width
page.resize(sw - list_width, sh)
page.move(sx + list_width - 2, sy)
return page
def draw(self):
page_list = self._page_list
selection = self._selection
selected_page = page_list[selection] if selection >= 0 else None
margin = (1, self.get_size()[0] - self.list_width + 1, 1, 1)
padding = (1, 1)
# Draw a border around the navlist.
self.draw_border(offset_right = margin[1] - 1)
# Draw navlist options.
for i in range(len(page_list)):
page = page_list[i]
attr = self.style('highlight') if i == self._highlight else self.style('text')
self.draw_text(page._label, row = i + margin[2], padding = padding, margin = margin, expand = 'RIGHT', attr = attr)
def operate(self, c):
page_list = self._page_list
selection = self._selection
selected_page = page_list[selection] if selection >= 0 else None
if c in {curses.KEY_DOWN, curses.KEY_UP, curses.KEY_ENTER, ascii.LF, ascii.CR}:
self.tag_redraw()
# Highlight the next option, wrapping if necessary.
if c == curses.KEY_DOWN:
self._highlight += 1
self._highlight %= len(page_list)
# Highlight the previous option, wrapping if necessary.
elif c == curses.KEY_UP:
self._highlight -= 1
self._highlight %= len(page_list)
# Select the highlighted option.
elif c in {curses.KEY_ENTER, ascii.LF, ascii.CR}:
self._select(self._highlight)
return 'CONTINUE'
def _select(self, page_idx):
'''
Selects given page in the navlist and transfers input focus
Parameters:
page_idx: Index of page in navlist
'''
page_list = self._page_list
selection = self._selection
# Select indexed page.
if page_idx >= 0 and page_idx < len(page_list):
# Update visibility states.
page_list[selection].hide()
page_list[page_idx].show()
# Set selection and transfer input focus.
self._selection = page_idx
Widget.input_focus = page_list[page_idx]
class TextBox(Labeled):
'''
Multi-line text input/display widget
Parameters:
_text (str): Text content
_cursor_offset: Position of cursor relative to beginning of the text
_col_scroll (int): Index corresponding to left of viewable region
_row_scroll (int): Index corresponding to top of viewable region
_read_only (bool): Flag controlling ability to edit this widget
'''
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label, parent, focus_key)
self._overrides_enter = True
# Initialize attributes.
self._text = ''
self._cursor_offset = 0
self._col_scroll = 0
self._row_scroll = 0
self._read_only = False
def clear(self, **kwargs):
self._text = ''
self._cursor_offset = 0
self._col_scroll = 0
self._row_scroll = 0
def report(self):
usage = 'Up/Down/Left/Right: Move Cursor'
if not self._read_only:
usage = 'Type text input. Up/Down/Left/Right: Move Cursor'
else:
usage = 'Up/Down/Left/Right: Scroll'
return {'usage': usage}
def compose(self):
return (not self._read_only and self._text != '', {'text': self._text})
def decompose(self, text, **kwargs):
self.clear()
self._text = text
def draw(self):
margin = [2, 3, 1, 1]
width, height = self.get_size()
effective_width = width - margin[0] - margin[1]
effective_height = height - margin[2] - margin[3]
text = self._text
offset = self._cursor_offset
col_scroll = self._col_scroll
row_scroll = self._row_scroll
# Draw border around the text box.
self.draw_border(offset_right = 1)
# Draw lines of text.
line_list = self._build_line_list()
for i in range(min(len(line_list[row_scroll:]), effective_height)):
line = line_list[i + row_scroll]
self.draw_text(line[col_scroll:], row = i + margin[2], margin = margin, fit = 'NO_WRAP')
# Draw the cursor.
if not self._read_only:
col_offset, row_offset = self._split_offset(offset)
self.draw_cursor(col_offset + margin[0] - col_scroll, row_offset + margin[2] - row_scroll, margin = margin)
# Indicate if content exists outside of the visible region.
attr = self.style('border')
padding = (1, 1)
center_row = math.ceil(height / 2) - 1
# Indicate content before.
if col_scroll > 0:
left_arrow = u'\u25C0'
self.draw_text(left_arrow, row = center_row, align = 'LEFT', attr = attr)
# Indicate content after.
num_cols = max([len(i) for i in text.splitlines() or [text]])
if col_scroll < num_cols - effective_width:
right_arrow = u'\u25B6'
self.draw_text(right_arrow, row = center_row, margin = (width - 2, 0, 0, 0), attr = attr)
# Indicate content above.
if row_scroll > 0:
up_arrow = u'\u25B2'
self.draw_text(up_arrow, padding = padding, align = 'CENTER', attr = attr)
# Indicate content below.
num_rows = len(line_list)
if row_scroll < num_rows - effective_height:
down_arrow = u'\u25BC'
self.draw_text(down_arrow, row = height - 1, padding = padding, align = 'CENTER', attr = attr)
def operate(self, c):
margin = [2, 3, 1, 1]
width, height = self.get_size()
effective_width = width - margin[0] - margin[1]
effective_height = height - margin[2] - margin[3]
text = self._text
offset = self._cursor_offset
col_offset, row_offset = self._split_offset(self._cursor_offset)
col_scroll = self._col_scroll
row_scroll = self._row_scroll
# Enforce read-only constraint.
if not self._read_only:
# Add a character.
if (ascii.isprint(c)
or c in {curses.KEY_ENTER, ascii.LF, ascii.CR}
):
self.tag_redraw()
# Insert character before the cursor.
self._text = text[:offset] + chr(c) + text[offset:]
# Update offset of the cursor.
self._cursor_offset += 1
# Delete a character.
elif (c in {ascii.BS, ascii.DEL, curses.KEY_BACKSPACE}
and offset > 0
):
self.tag_redraw()
# Delete character preceding the cursor.
self._text = text[:offset - 1] + text[offset:]
# Update offset of the cursor.
self._cursor_offset -= 1
# Move cursor left unless start of either text or line is
# encountered.
if (c == curses.KEY_LEFT
and offset > 0
and ord(text[offset - 1]) not in {
curses.KEY_ENTER, ascii.LF, ascii.CR
}
):
self.tag_redraw()
self._cursor_offset -= 1
# Move cursor right unless end of either text or line is
# encountered.
elif (c == curses.KEY_RIGHT
and offset < len(text)
and ord(text[offset]) not in {
curses.KEY_ENTER, ascii.LF, ascii.CR
}
):
self.tag_redraw()
self._cursor_offset += 1
# Move cursor up.
elif c == curses.KEY_UP:
self.tag_redraw()
self._cursor_offset = self._join_offsets(col_offset, row_offset - 1)
# Move cursor down.
elif c == curses.KEY_DOWN:
self.tag_redraw()
self._cursor_offset = self._join_offsets(col_offset, row_offset + 1)
# Scroll if necessary.
col_offset, row_offset = self._split_offset(self._cursor_offset)
if col_offset < col_scroll:
self._col_scroll = col_offset
elif col_offset > col_scroll + effective_width - 1:
self._col_scroll += col_offset - (col_scroll + effective_width - 1)
self._col_scroll = col_offset - (effective_width - 1)
if row_offset < row_scroll:
self._row_scroll = row_offset
elif row_offset > row_scroll + effective_height - 1:
self._row_scroll = row_offset - (effective_height - 1)
else: # Read-only mode
line_list = self._build_line_list()
num_cols = max([len(i) for i in line_list])
num_rows = len(line_list)
scroll_sensitivity = 1
# Scroll left.
if c == curses.KEY_LEFT:
self.tag_redraw()