Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
1502 lines (1146 loc) · 46.5 KB
/
Copy pathcore.py
File metadata and controls
1502 lines (1146 loc) · 46.5 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: core.py
# Creation Date: Thu 08 Oct 2015
# Last Modified: Fri 20 Nov 2015 12:05:52 AM MST
# Author: Brett Fedack
import curses
import curses.ascii as ascii
import math
import os
import re
import weakref
from datetime import datetime
from . import signals
from .theme import Theme
os.environ['ESCDELAY'] = '25' # Reduces delay after pressing escape key
def key_from_char(n):
'''
Converts given numeric representation of a keyboard key to a string
Parameters:
n (int): Numeric representation of keyboard key
Returns:
str: String representation of keyboard key
'''
# Get the keyname.
key = curses.keyname(n).decode('utf-8')
# Remove 'KEY_' prefix.
key = re.sub(r'^KEY_', '', key)
# Remove parenthesis in function keys, such as "F(1)".
key = re.sub(r'^F\(([0-9])\)$', r'F\1', key)
return key
class UI():
'''
Curses-based user interface framework class
Attributes:
_error_log (list<Exception>): History of runtime errors
_focus_trace (list<weakref<Widget>>): Trace of input focus
_is_running (bool): Flag controlling run state of this UI
_root (Widget): Root node of widget tree
'''
@property
def root(self):
''' Getter for "root" property '''
return self._root
def __init__(self, signal_router = None):
'''
Parameters:
signal_router (SignalRouter): Communication hub for this component
(Optional)
'''
# Initialize curses library.
curses.initscr()
curses.noecho() # Hidden input
curses.curs_set(0) # Hidden cursor
curses.cbreak() # Non-buffered input
if curses.has_colors(): # Color enabled
curses.start_color()
# Setup signal handling.
signal_router.register('UI_EXIT', self._exit)
# Initialize attributes.
self._error_log = []
self._focus_trace = []
self._is_running = True
self._root = Widget(label = 'root', signal_router = signal_router)
def __del__(self):
# Deinitialize curses library, and display any errors.
if not curses.isendwin():
curses.endwin()
for e in self._error_log:
raise e
def run(self):
''' Executes user interface and logs runtime errors '''
try:
self._run()
except Exception as e:
self._error_log.append(e)
def _backtrace(self):
''' Transfers input focus to the previously focused widget '''
focus_trace = self._focus_trace
# Transfer focus upwards.
focus_trace.pop()
if focus_trace:
Widget.input_focus = focus_trace[-1]()
def _transfer_down(self, new_focus):
''' Transfers input focus to a descendant of the current focus
Parameters:
new_focus (Widget): New subject of input focus
'''
focus_trace = self._focus_trace
# Transfer input focus.
focus_trace.append(weakref.ref(new_focus))
Widget.input_focus = new_focus
# Synchronize the focus trace.
actual_focus = Widget.input_focus
if actual_focus != new_focus:
focus_trace[-1] = weakref.ref(actual_focus)
def _exit(self, **kwargs):
''' Terminates this user interface '''
self._is_running = False
def _run(self):
''' Runs user interface event loop '''
# Determine entry point.
descendants = self.root._descendants
entry_point = descendants[0] if descendants else None
if not entry_point:
return
# Set input focus.
Widget.input_focus = entry_point
# Reset focus trace.
focus_trace = self._focus_trace
focus_trace.clear()
# Run until an exit signal is received.
while self._is_running:
# Redraw user interface.
self.root._draw()
# Synchronize input focus with the focus trace.
if not focus_trace or focus_trace[-1]() is not Widget.input_focus:
focus_trace.append(weakref.ref(Widget.input_focus))
# Get the subject of input focus.
input_focus = Widget.input_focus
# Get user input.
c = input_focus._win.getch()
# Find neighboring, focusable widgets.
ancestor = input_focus._ancestor
siblings = ancestor._descendants if ancestor else None
descendants = input_focus._descendants
# Transfer input focus upward.
if (c == ascii.ESC
and not input_focus._overrides_esc
and len(focus_trace) > 1
):
self._backtrace()
# Transfer input focus laterally.
elif (c in {ascii.TAB, curses.KEY_BTAB}
and not input_focus._overrides_tab
and len(siblings) > 1
):
# Determine if lateral navigation is possible.
if siblings and input_focus in siblings:
# Reference previous and next focusable siblings.
curr_idx = siblings.index(input_focus)
prev = siblings[(curr_idx - 1) % (len(siblings))]
next = siblings[(curr_idx + 1) % (len(siblings))]
# Transfer input focus to a focusable siblings.
new_focus = prev if c == curses.KEY_BTAB else next
Widget.input_focus = new_focus
focus_trace[-1] = weakref.ref(Widget.input_focus)
# Transfer input focus downward.
elif (c in {curses.KEY_ENTER, ascii.LF, ascii.CR}
and not input_focus._overrides_enter
and descendants
):
self._transfer_down(descendants[0])
# Transfer input focus directly to a descendant.
elif (c in input_focus._focus_map
and descendants[input_focus._focus_map[c]].audit()
):
self._transfer_down(descendants[input_focus._focus_map[c]])
# Otherwise, pass user input to the focused widget.
else:
ret = input_focus.operate(c)
# The response should be to continue or end operation.
if ret not in {'CONTINUE', 'END'}:
raise RuntimeError(
'Returned {}; expected value in {"CONTINUE", "END"}'.format(ret)
)
# Backtrace input focus if operation has come to an end.
elif ret == 'END':
self._backtrace()
class MetaWidget(type):
''' Widget metaclass for defining class properties and static methods '''
@staticmethod
def set_input_focus(new_focus, **kwargs):
'''
Setter for "input_focus" property
Parameter:
new_focus (Widget): Widget to set as new input focus
kwargs: Adapter for optional signal data
'''
# Validate input.
if not isinstance(new_focus, Widget):
raise TypeError('Received {}; expected Widget'.format(type(new_focus)))
# Return early if the given widget cannot receive input focus.
if not new_focus._is_focusable:
return
# Retrieve previous input focus.
previous_focus = Widget.input_focus
# Report status of the new input focus.
new_focus._send_status()
# Assign new input focus.
Widget._input_focus = weakref.ref(new_focus)
# Determine if input focus has changed.
if previous_focus and previous_focus is not new_focus:
# Update timestamp of new input focus.
new_focus.update_timestamp()
# Provide visual feedback to indicate a change in input focus.
previous_focus.tag_redraw()
new_focus.tag_redraw()
# Call overridable blur and focus methods.
previous_focus.blur()
new_focus.focus(**kwargs)
# Emit a signal containing data from the previous input focus.
output_is_ready, data = previous_focus.compose()
if output_is_ready:
signal = signals.Signal('DATASIG_OUT', data, False)
previous_focus.bubble(**signal.data)
# Emit a signal requesting data for the new input focus.
new_focus.request()
@property
def input_focus(cls):
''' Getter for "input_focus" property '''
# Return the weakly referenced widget.
return Widget._input_focus() if Widget._input_focus else None
@input_focus.setter
def input_focus(cls, widget):
''' Setter for "input_focus" property '''
Widget.set_input_focus(widget)
@property
def theme(cls):
''' Getter for "theme" property '''
return Widget._theme
class Widget(metaclass = MetaWidget):
'''
Curses-based widget base class
Attributes:
_input_focus (Widget):
_theme (Theme):
_label (str): Identifier for this widget
_win (curses.window): Encapsulated curses window
_signal_router (SignalRouter): Communication hub for this widget
_parent (Widget): Parent node in tree of widgets
_children (list<window>): Child nodes in tree of widgets
_ancestor (Widget): Nearest focusable ancestor widget
_descendants (list<Widget>): Nearest focusable descendant widgets
_focus_key (int): Input character that transfers focus to this widget
_focus_map (dict<int:int>): Mapping of focus keys to descendant indices
_links (list<weakref<Widget>>): Non-descendant nodes that are dependent
on this widget
_is_focusable (bool): Flag indicating if this widget can gain input
focus
_is_drawable (bool): Flag indicating if this widget can be drawn
_is_tagged (bool): Flag indicating a pending draw operation
_is_visible (bool): Flag indicating if the subtree rooted at this
widget is visible
_timestamp (datetime): Reference date & time for animation purposes;
updates automatically when input focus changes
_overrides_enter (bool): Flag indicating if this widget overrides the
default downward navigation key
_overrides_esc (bool): Flag indicating if this widget overrides the
default backtrace navigation key
_overrides_tab (bool): Flag indicating if this widget overrides the
default lateral navigation key
Preconditions:
Curses library shall be intialized.
'''
__metaclass__ = MetaWidget
_input_focus = None
_theme = Theme()
@property
def input_focus(self):
''' Getter for "input_focus" property '''
# Return the weakly referenced widget.
return Widget._input_focus() if Widget._input_focus else None
@input_focus.setter
def input_focus(self, widget):
''' Setter for "input_focus" property '''
self.set_input_focus(widget)
@property
def theme(self):
''' Getter for "theme" property '''
return Widget._theme
@property
def label(self):
''' Getter for "label" property '''
return self._label
def __init__(self, label, parent = None, focus_key = None, signal_router = None):
'''
Parameters:
label (str): Identifier for this widget
parent (Widget): Parent node in tree of widgets (Optional)
focus_key (str): Key that initiates focus (Optional)
signal_router (SignalRouter): Signal router to use for this widget
(Optional)
'''
# Assign given label.
self._label = label
# Insert this node into the tree of widgets.
self._parent = parent
if parent:
self._parent._children.append(self)
self._children = []
self._descendants = []
self._focus_map = dict()
# Indicate that this widget can receive input focus.
self._is_focusable = True
# Find closest ancestor that can receive input focus.
ancestor = parent
while (ancestor
and ancestor._parent
and not ancestor._is_focusable
):
ancestor = ancestor._parent
self._ancestor = ancestor
# Communicate this widget's focus key up the ancestor path.
self._focus_key = focus_key
if ancestor and focus_key:
ancestor._focus_map[focus_key] = len(ancestor._descendants)
ancestor._descendants.append(self)
# Associate a signal router with this widget.
self._signal_router = signal_router if signal_router else signals.SignalRouter()
# Setup signal handlers.
self.add_signal_handler('DATASIG_IN', self.decompose)
self.add_signal_handler('DATASIG_FOCUS', self._focus)
# Encapsulate a curses window in this widget.
pwin = self._parent._win if parent else curses.newwin(0, 0)
ph, pw = pwin.getmaxyx()
py, px = pwin.getbegyx()
win = curses.newwin(ph, pw, py, px)
win.keypad(1)
win.nodelay(1)
self._win = win
# Enable rendering of the subtree rooted at this widget.
self._links = []
self._is_drawable = True
self._is_tagged = True
self._is_visible = True
# Initialize timestamp
self.update_timestamp()
# Disable overrides by default.
self._overrides_enter = False
self._overrides_esc = False
self._overrides_tab = False
def override(enter = False, esc = False, tab = False):
'''
Overrides the default behavior of navigation keys
Parameters:
enter (bool): Flag indicating if default downward navigation key
should be overriden (Optional)
esc (bool): Flag indicating if default backtrace navigation key
should be overriden (Optional)
tab (bool): Flag indicating if default lateral navigation key
should be overriden (Optional)
'''
self._overrides_enter = enter
self._overrides_esc = esc
self._overrides_tab = tab
def update_timestamp(self):
''' Updates timestamp to current date & time '''
self._timestamp = datetime.now()
def get_time(self):
''' Calculates elapsed time (sec) since this widget received focus. '''
return (datetime.now() - self._timestamp).total_seconds()
def get_position(self):
'''
Gets (x, y) coordinates of this widget relative to its parent.
Returns:
2-tuple: x (int), y (int)
'''
sy, sx = self._win.getbegyx()
py, px = self._parent._win.getbegyx() if self._parent else (0, 0)
return sx - px, sy - py
def get_size(self):
'''
Gets the width and height of this widget
Returns:
2-tuple: width (int), height (int)
'''
height, width = self._win.getmaxyx()
return width, height
def offset(self, x = 0, y = 0):
'''
Moves this widget relative to its current position
Parameters:
x (int): Relative x-coordinate (Optional)
y (int): Relative y-coordinate (Optional)
Returns:
Widget: Alias to this widget
'''
# Determine the bounds of both this widget and its parent.
p = self._parent._win if self._parent else curses.newwin(0, 0)
py, px = p.getbegyx()
ph, pw = p.getmaxyx()
s = self._win
sy, sx = s.getbegyx()
sh, sw = s.getmaxyx()
# Constrain given offsets within the parent's bounds.
x = min(max(x + sx, px), px + pw - sw) - sx
y = min(max(y + sy, py), py + ph - sh) - sy
# Offset any linked nodes.
for ref in self._links:
ref().offset(x, y)
# Recursively offset the tree of widgets rooted at this node.
self._offset_tree(x, y)
return self
def move(self, x = None, y = None):
'''
Moves this widget within the bounds of its parent/screen
Parameters:
x (int): x-coordinate (Optional)
y (int): y-coordinate (Optional)
Returns:
Widget: Alias to this widget
'''
# Determine the coordinates of this widget and its parent.
p = self._parent._win if self._parent else curses.newwin(0, 0)
py, px = p.getbegyx()
s = self._win
sy, sx = s.getbegyx()
# Express coordinates as offsets from the current position.
x = 0 if x is None else x - (sx - px)
y = 0 if y is None else y - (sy - py)
# Offset this widget.
self.offset(x, y)
return self
def resize(self, width = None, height = None):
'''
Resizes this widget within the bounds of its parent/screen
Parameters:
width (int): Width in columns (Optional)
height (int): Height in rows (Optional)
Returns:
Widget: Alias to this widget
'''
# Determine the bounds of both this widget and its parent.
p = self._parent._win if self._parent else curses.newwin(0, 0)
py, px = p.getbegyx()
ph, pw = p.getmaxyx()
s = self._win
sy, sx = s.getbegyx()
sh, sw = s.getmaxyx()
# Constrain the given dimensions within the parent's bounds.
width = sw if width is None else min(max(1, width), px + pw - sx)
height = sh if height is None else min(max(1, height), py + ph - sy)
# Resize this widget.
self._win.resize(int(height), int(width))
# Compensate for the effects resizing may have on any children.
for child in self._children:
cy, cx = child._win.getbegyx()
ch, cw = child._win.getmaxyx()
child.resize(cw, ch)
child.move(cx - sx, cy - sy)
return self
def scale(self, width = 0, height = 0):
'''
Resizes this widget relative to its current dimensions
Parameters:
width (int): Change in width (Optional)
height (int): Change in height (Optional)
Returns:
Widget: Alias to this widget
'''
sw, sh = self.get_size()
self.resize(max(2, sw + width), max(2, sh + height))
return self
def inset(self, factor):
'''
Scales this widget inward from its current bounds
Parameters:
factor (int): Inset distance in row-heights
Returns:
Widget: Alias to this widget
'''
self.scale(-4 * factor, -2 * factor)
self.offset(2 * factor, 1 * factor)
return self
def outset(self, factor):
'''
Scales this widget outward from its current bounds
Parameters:
factor (int): Outset distance in row-heights
Returns:
Widget: Alias to this widget
'''
self.offset(-2 * factor, -1 * factor)
self.scale(4 * factor, 2 * factor)
return self
def align(self, mode = 'LEFT', cross = False):
'''
Aligns this widget with respect to the width or height of its parent
Parameters:
mode (str): Alignment mode in {'START', 'CENTER', 'END'}
(Optional)
cross (bool): Cross-alignment flag (Optional)
Returns:
Widget: Alias to this widget
'''
# Get length along this widget's alignment axis.
sw, sh = self.get_size()
span_inner = sh if cross else sw
# Get length along parent's alignment axis.
p = self._parent._win if self._parent else curses.newwin(0, 0)
ph, pw = p.getmaxyx()
span_outer = ph if cross else pw
# Determine offset along alignment axis.
if mode == 'START':
offset = 0
elif mode == 'CENTER':
offset = int((span_outer - span_inner) / 2)
elif mode == 'END':
offset = span_outer - span_inner
# Move this widget.
x, y = self.get_position()
self.move(0, offset) if cross else self.move(offset, 0)
return self
def hide(self):
''' Disables visibility of this widget '''
self._is_visible = False
def show(self):
''' Enables visibility of this widget '''
self._is_visible = True
def toggle_visibility(self):
''' Toggles visibility of this widget '''
self.hide() if self._is_visible else self.show()
def style(self, name):
'''
Retrieves a curses style attribute from this widget's color theme
Parameters:
name (str): Name of item to style
Returns:
curses.attr: Curses style attribute
'''
if not self.audit():
state = 'disabled'
elif self.input_focus == self:
state = 'focused'
else:
state = 'default'
return self.theme.query(state, name)
def add_signal_handler(self, signame, handler):
'''
Registers the given signal handler with this widget's signal router
Parameters:
signame (str): Signal name
handler (function): Signal handler
'''
self._signal_router.register(signame, handler)
def bubble(self, **kwargs):
'''
Builds signal from given data and emits it to all ancestor widgets.
Parameters:
**kwargs: Signal data
'''
# Return early if given data does not identify a signal.
if '_name' not in kwargs:
return
# Build a signal from given data.
signame = kwargs['_name']
propagate = kwargs['_propagate'] if '_propagate' in kwargs else True
signal = signals.Signal(signame, kwargs, propagate)
# Handle the signal with this widget's parent.
if self._parent:
handled = self._parent._signal_router.forward(signal)
# Continue to bubble the signal while it can be handled.
if not handled or propagate:
self._parent.bubble(**kwargs)
def flush(self, **kwargs):
'''
Builds signal from given data and emits it to all descendant widgets.
Parameters:
**kwargs: Signal data
Returns:
bool: True if signal is handled; false otherwise
'''
# Return early if given data does not identify a signal.
if '_name' not in kwargs:
return
# Build a signal from given data.
signame = kwargs['_name']
propagate = kwargs['_propagate'] if '_propagate' in kwargs else True
signal = signals.Signal(signame, kwargs, propagate)
# Handle the given signal with this widget's descendants.
handled = False
for child in self._children:
# Only handle once if the signal cannot propagate.
if handled and not propagate:
break;
# Handle and flush the signal.
handled = child._signal_router.forward(signal) or handled
if not handled or propagate:
handled = child.flush(**kwargs) or handled
return handled
def request(self, **kwargs):
''' Bubbles a request for input data '''
signal = signals.Signal('DATASIG_REQ', propagate = False)
self.bubble(**signal.data)
def tag_redraw(self):
''' Marks this widget to be redrawn during the next draw call '''
self._is_tagged = True
for ref in self._links:
ref().tag_redraw()
def audit(self):
'''
* Abstract method for inserting user-defined code into UI framework *
Determines if this widget is operable/disabled
Returns:
bool: True if operable; false if disabled
'''
return True
def report(self):
'''
* Abstract method for inserting user-defined code into UI framework *
Generates a report based on this widget's state.
Returns:
str: String of status data
'''
return {'usage': '', 'is_valid': True, 'validation_msg': ''}
def focus(self, **kwargs):
'''
* Abstract method for inserting user-defined code into UI framework *
Executes when this widget gains focus; receives optional signal data
'''
return
def blur(self):
'''
* Abstract method for inserting user-defined code into UI framework *
Executes when this widget loses focus
'''
return
def compose(self):
'''
* Abstract method for inserting user-defined code into UI framework *
Defines how to build output signal data
Returns:
2-tuple: control flag (bool), signal data (dict)
'''
return (False, {})
def decompose(self, **kwargs):
'''
* Abstract method for inserting user-defined code into UI framework *
Defines how to integrate input signal data into this widget
'''
return
def draw(self):
'''
* Abstract method for inserting user-defined code into UI framework *
Defines how to render this widget during a draw call.
'''
return
def operate(self, c = None):
'''
* Abstract method for inserting user-defined code into UI framework *
Defines how this widget handles user input
Parameters:
c (int): Character code for user input (Optional)
'''
return 'CONTINUE'
def _focus(self, **kwargs):
''' Transfers input focus to this widget in response to a signal '''
Widget.set_input_focus(self, **kwargs)
def _draw(self):
''' Draws this widget '''
self._draw_tagged()
curses.doupdate()
def _draw_tagged(self):
''' Draws all visible, tagged subtrees in this tree of widgets '''
# Skip hidden trees.
if self._is_visible:
# Draw tree if it is tagged.
if self._is_tagged:
self._draw_tree()
# Otherwise, continue search for tagged trees.
else:
for child in self._children:
child._draw_tagged()
def _draw_tree(self):
''' Draws the tree of widgets rooted at this node '''
# Preemptively remove draw tag.
self._is_tagged = False
# Skip hidden trees.
if self._is_visible:
# Draw this widget.
if self._is_drawable:
self._win.bkgdset(self.style('fill'));
self._win.erase()
self.draw()
self._win.noutrefresh()
# Recursively draw each child subtree.
for child in self._children:
child._draw_tree()
def _offset_tree(self, x, y):
'''
Moves the tree of widgets rooted at this node
Parameters:
x (int): Relative x-coordinate
y (int): Relative y-coordinate
'''
# Move this widget.
y_abs, x_abs = self._win.getbegyx()
self._win.mvwin(int(y_abs + y), int(x_abs + x))
# Recursively move all descendants of this widget.
for child in self._children:
child._offset_tree(x, y)
def _send_status(self):
''' Reports status information, such as usage instructions '''
# Build a usage string from this widget's focus map.
descendants = self._descendants
reverse_focus_map = {v: k for k, v in self._focus_map.items()}
status = ', '.join([
'{}:{}'.format(
key_from_char(reverse_focus_map[i]),
descendants[i]._label
)
for i in range(len(descendants))
if descendants[i]._is_focusable and descendants[i].audit()
])
# Include output from overridable report method in status.
status = (status + ', ' + self.report()['usage']).strip(', ')
# Emit a signal containing this widget's status.
status_signal = signals.Signal('UI_UPDATE_STATUS', {'status': status}, False)
self.bubble(**status_signal.data)
self.flush(**status_signal.data)
class ContentWidget(Widget):
'''
Extends base widget in order to provide safe and convenient methods for
adding content without violating encapsulation of the curses window
'''
@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.inset(1)
return region
def __init__(self, label, parent, focus_key = None):
# Initialize inherited state.
super().__init__(label = label, parent = parent, focus_key = focus_key)
# Initialize attributes.
self._label_ref = None
# Setup handlers.
self.add_signal_handler('UI_CLEAR', self.clear)
def clear(self, **kwargs):
'''
* Abstract method for inserting user-defined code into UI framework *
Defines how to clear content from this widget
'''
return
def draw_border(self,
offset_left = 0,
offset_right = 0,
offset_top = 0,
offset_bottom = 0,
char_left = None,
char_right = None,
char_top = None,
char_bottom = None,
char_top_left = None,
char_top_right = None,
char_bottom_left = None,