forked from SoftwareDesignXRays/tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurses_ui.py
More file actions
1656 lines (1342 loc) · 56.4 KB
/
curses_ui.py
File metadata and controls
1656 lines (1342 loc) · 56.4 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
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Curses-Based Command-Line Interface of TensorFlow Debugger (tfdbg)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import curses
from curses import textpad
import os
import signal
import sys
import threading
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.debug.cli import base_ui
from tensorflow.python.debug.cli import cli_shared
from tensorflow.python.debug.cli import command_parser
from tensorflow.python.debug.cli import curses_widgets
from tensorflow.python.debug.cli import debugger_cli_common
from tensorflow.python.debug.cli import tensor_format
_SCROLL_REFRESH = "refresh"
_SCROLL_UP = "up"
_SCROLL_DOWN = "down"
_SCROLL_UP_A_LINE = "up_a_line"
_SCROLL_DOWN_A_LINE = "down_a_line"
_SCROLL_HOME = "home"
_SCROLL_END = "end"
_SCROLL_TO_LINE_INDEX = "scroll_to_line_index"
_COLOR_READY_COLORTERMS = ["gnome-terminal", "xfce4-terminal"]
_COLOR_ENABLED_TERM = "xterm-256color"
def _get_command_from_line_attr_segs(mouse_x, attr_segs):
"""Attempt to extract command from the attribute segments of a line.
Args:
mouse_x: (int) x coordinate of the mouse event.
attr_segs: (list) The list of attribute segments of a line from a
RichTextLines object.
Returns:
(str or None) If a command exists: the command as a str; otherwise, None.
"""
for seg in attr_segs:
if seg[0] <= mouse_x < seg[1]:
attributes = seg[2] if isinstance(seg[2], list) else [seg[2]]
for attr in attributes:
if isinstance(attr, debugger_cli_common.MenuItem):
return attr.content
class ScrollBar(object):
"""Vertical ScrollBar for Curses-based CLI.
An object of this class has knowledge of the location of the scroll bar
in the screen coordinates, the current scrolling position, and the total
number of text lines in the screen text. By using this information, it
can generate text rendering of the scroll bar, which consists of and UP
button on the top and a DOWN button on the bottom, in addition to a scroll
block in between, whose exact location is determined by the scrolling
position. The object can also calculate the scrolling command (e.g.,
_SCROLL_UP_A_LINE, _SCROLL_DOWN) from the coordinate of a mouse click
event in the screen region it occupies.
"""
BASE_ATTR = cli_shared.COLOR_BLACK + "_on_" + cli_shared.COLOR_WHITE
def __init__(self,
min_x,
min_y,
max_x,
max_y,
scroll_position,
output_num_rows):
"""Constructor of ScrollBar.
Args:
min_x: (int) left index of the scroll bar on the screen (inclusive).
min_y: (int) top index of the scroll bar on the screen (inclusive).
max_x: (int) right index of the scroll bar on the screen (inclusive).
max_y: (int) bottom index of the scroll bar on the screen (inclusive).
scroll_position: (int) 0-based location of the screen output. For example,
if the screen output is scrolled to the top, the value of
scroll_position should be 0. If it is scrolled to the bottom, the value
should be output_num_rows - 1.
output_num_rows: (int) Total number of output rows.
Raises:
ValueError: If the width or height of the scroll bar, as determined
by min_x, max_x, min_y and max_y, is too small.
"""
self._min_x = min_x
self._min_y = min_y
self._max_x = max_x
self._max_y = max_y
self._scroll_position = scroll_position
self._output_num_rows = output_num_rows
self._scroll_bar_height = max_y - min_y + 1
if self._max_x < self._min_x:
raise ValueError("Insufficient width for ScrollBar (%d)" %
(self._max_x - self._min_x + 1))
if self._max_y < self._min_y + 3:
raise ValueError("Insufficient height for ScrollBar (%d)" %
(self._max_y - self._min_y + 1))
def _block_y(self, screen_coord_sys=False):
"""Get the 0-based y coordinate of the scroll block.
This y coordinate takes into account the presence of the UP and DN buttons
present at the top and bottom of the ScrollBar. For example, at the home
location, the return value will be 1; at the bottom location, the return
value will be self._scroll_bar_height - 2.
Args:
screen_coord_sys: (`bool`) whether the return value will be in the
screen coordinate system.
Returns:
(int) 0-based y coordinate of the scroll block, in the ScrollBar
coordinate system by default. For example,
when scroll position is at the top, this return value will be 1 (not 0,
because of the presence of the UP button). When scroll position is at
the bottom, this return value will be self._scroll_bar_height - 2
(not self._scroll_bar_height - 1, because of the presence of the DOWN
button).
"""
rel_block_y = int(
float(self._scroll_position) / (self._output_num_rows - 1) *
(self._scroll_bar_height - 3)) + 1
return rel_block_y + self._min_y if screen_coord_sys else rel_block_y
def layout(self):
"""Get the RichTextLines layout of the scroll bar.
Returns:
(debugger_cli_common.RichTextLines) The text layout of the scroll bar.
"""
width = self._max_x - self._min_x + 1
empty_line = " " * width
foreground_font_attr_segs = [(0, width, self.BASE_ATTR)]
if self._output_num_rows > 1:
block_y = self._block_y()
if width == 1:
up_text = "U"
down_text = "D"
elif width == 2:
up_text = "UP"
down_text = "DN"
elif width == 3:
up_text = "UP "
down_text = "DN "
else:
up_text = " UP "
down_text = "DOWN"
layout = debugger_cli_common.RichTextLines(
[up_text], font_attr_segs={0: [(0, width, self.BASE_ATTR)]})
for i in xrange(1, self._scroll_bar_height - 1):
font_attr_segs = foreground_font_attr_segs if i == block_y else None
layout.append(empty_line, font_attr_segs=font_attr_segs)
layout.append(down_text, font_attr_segs=foreground_font_attr_segs)
else:
layout = debugger_cli_common.RichTextLines(
[empty_line] * self._scroll_bar_height)
return layout
def get_click_command(self, mouse_y):
# TODO(cais): Support continuous scrolling when the mouse button is held
# down.
if self._output_num_rows <= 1:
return None
elif mouse_y == self._min_y:
return _SCROLL_UP_A_LINE
elif mouse_y == self._max_y:
return _SCROLL_DOWN_A_LINE
elif (mouse_y > self._block_y(screen_coord_sys=True) and
mouse_y < self._max_y):
return _SCROLL_DOWN
elif (mouse_y < self._block_y(screen_coord_sys=True) and
mouse_y > self._min_y):
return _SCROLL_UP
else:
return None
class CursesUI(base_ui.BaseUI):
"""Curses-based Command-line UI.
In this class, the methods with the prefix "_screen_" are the methods that
interact with the actual terminal using the curses library.
"""
CLI_TERMINATOR_KEY = 7 # Terminator key for input text box.
CLI_TAB_KEY = ord("\t")
BACKSPACE_KEY = ord("\b")
REGEX_SEARCH_PREFIX = "/"
TENSOR_INDICES_NAVIGATION_PREFIX = "@"
_NAVIGATION_FORWARD_COMMAND = "next"
_NAVIGATION_BACK_COMMAND = "prev"
# Limit screen width to work around the limitation of the curses library that
# it may return invalid x coordinates for large values.
_SCREEN_WIDTH_LIMIT = 220
# Possible Enter keys. 343 is curses key code for the num-pad Enter key when
# num lock is off.
CLI_CR_KEYS = [ord("\n"), ord("\r"), 343]
_KEY_MAP = {
127: curses.KEY_BACKSPACE, # Backspace
curses.KEY_DC: 4, # Delete
}
_FOREGROUND_COLORS = {
cli_shared.COLOR_WHITE: curses.COLOR_WHITE,
cli_shared.COLOR_RED: curses.COLOR_RED,
cli_shared.COLOR_GREEN: curses.COLOR_GREEN,
cli_shared.COLOR_YELLOW: curses.COLOR_YELLOW,
cli_shared.COLOR_BLUE: curses.COLOR_BLUE,
cli_shared.COLOR_CYAN: curses.COLOR_CYAN,
cli_shared.COLOR_MAGENTA: curses.COLOR_MAGENTA,
cli_shared.COLOR_BLACK: curses.COLOR_BLACK,
}
_BACKGROUND_COLORS = {
"transparent": -1,
cli_shared.COLOR_WHITE: curses.COLOR_WHITE,
cli_shared.COLOR_BLACK: curses.COLOR_BLACK,
}
# Font attribute for search and highlighting.
_SEARCH_HIGHLIGHT_FONT_ATTR = (
cli_shared.COLOR_BLACK + "_on_" + cli_shared.COLOR_WHITE)
_ARRAY_INDICES_COLOR_PAIR = (
cli_shared.COLOR_BLACK + "_on_" + cli_shared.COLOR_WHITE)
_ERROR_TOAST_COLOR_PAIR = (
cli_shared.COLOR_RED + "_on_" + cli_shared.COLOR_WHITE)
_INFO_TOAST_COLOR_PAIR = (
cli_shared.COLOR_BLUE + "_on_" + cli_shared.COLOR_WHITE)
_STATUS_BAR_COLOR_PAIR = (
cli_shared.COLOR_BLACK + "_on_" + cli_shared.COLOR_WHITE)
_UI_WAIT_COLOR_PAIR = (
cli_shared.COLOR_MAGENTA + "_on_" + cli_shared.COLOR_WHITE)
_NAVIGATION_WARNING_COLOR_PAIR = (
cli_shared.COLOR_RED + "_on_" + cli_shared.COLOR_WHITE)
_UI_WAIT_MESSAGE = "Processing..."
_single_instance_lock = threading.Lock()
def __init__(self, on_ui_exit=None):
"""Constructor of CursesUI.
Args:
on_ui_exit: (Callable) Callback invoked when the UI exits.
"""
base_ui.BaseUI.__init__(self, on_ui_exit=on_ui_exit)
self._screen_init()
self._screen_refresh_size()
# TODO(cais): Error out if the size of the screen is too small.
# Initialize some UI component size and locations.
self._init_layout()
self._command_history_store = debugger_cli_common.CommandHistory()
# Active list of command history, used in history navigation.
# _command_handler_registry holds all the history commands the CLI has
# received, up to a size limit. _active_command_history is the history
# currently being navigated in, e.g., using the Up/Down keys. The latter
# can be different from the former during prefixed or regex-based history
# navigation, e.g., when user enter the beginning of a command and hit Up.
self._active_command_history = []
# Pointer to the current position in the history sequence.
# 0 means it is a new command being keyed in.
self._command_pointer = 0
self._command_history_limit = 100
self._pending_command = ""
self._nav_history = curses_widgets.CursesNavigationHistory(10)
# State related to screen output.
self._output_pad = None
self._output_pad_row = 0
self._output_array_pointer_indices = None
self._curr_unwrapped_output = None
self._curr_wrapped_output = None
try:
# Register signal handler for SIGINT.
signal.signal(signal.SIGINT, self._interrupt_handler)
except ValueError:
# Running in a child thread, can't catch signals.
pass
self.register_command_handler(
"mouse",
self._mouse_mode_command_handler,
"Get or set the mouse mode of this CLI: (on|off)",
prefix_aliases=["m"])
def _init_layout(self):
"""Initialize the layout of UI components.
Initialize the location and size of UI components such as command textbox
and output region according to the terminal size.
"""
# NamedTuple for rectangular locations on screen
self.rectangle = collections.namedtuple("rectangle",
"top left bottom right")
# Height of command text box
self._command_textbox_height = 2
self._title_row = 0
# Row index of the Navigation Bar (i.e., the bar that contains forward and
# backward buttons and displays the current command line).
self._nav_bar_row = 1
# Top row index of the output pad.
# A "pad" is a curses object that holds lines of text and not limited to
# screen size. It can be rendered on the screen partially with scroll
# parameters specified.
self._output_top_row = 2
# Number of rows that the output pad has.
self._output_num_rows = (
self._max_y - self._output_top_row - self._command_textbox_height - 1)
# Row index of scroll information line: Taking into account the zero-based
# row indexing and the command textbox area under the scroll information
# row.
self._output_scroll_row = self._max_y - 1 - self._command_textbox_height
# Tab completion bottom row.
self._candidates_top_row = self._output_scroll_row - 4
self._candidates_bottom_row = self._output_scroll_row - 1
# Maximum number of lines the candidates display can have.
self._candidates_max_lines = int(self._output_num_rows / 2)
self.max_output_lines = 10000
# Regex search state.
self._curr_search_regex = None
self._unwrapped_regex_match_lines = []
# Size of view port on screen, which is always smaller or equal to the
# screen size.
self._output_pad_screen_height = self._output_num_rows - 1
self._output_pad_screen_width = self._max_x - 2
self._output_pad_screen_location = self.rectangle(
top=self._output_top_row,
left=0,
bottom=self._output_top_row + self._output_num_rows,
right=self._output_pad_screen_width)
def _screen_init(self):
"""Screen initialization.
Creates curses stdscr and initialize the color pairs for display.
"""
# If the terminal type is color-ready, enable it.
if os.getenv("COLORTERM") in _COLOR_READY_COLORTERMS:
os.environ["TERM"] = _COLOR_ENABLED_TERM
self._stdscr = curses.initscr()
self._command_window = None
self._screen_color_init()
def _screen_color_init(self):
"""Initialization of screen colors."""
curses.start_color()
curses.use_default_colors()
self._color_pairs = {}
color_index = 0
# Prepare color pairs.
for fg_color in self._FOREGROUND_COLORS:
for bg_color in self._BACKGROUND_COLORS:
color_index += 1
curses.init_pair(color_index, self._FOREGROUND_COLORS[fg_color],
self._BACKGROUND_COLORS[bg_color])
color_name = fg_color
if bg_color != "transparent":
color_name += "_on_" + bg_color
self._color_pairs[color_name] = curses.color_pair(color_index)
# Try getting color(s) available only under 256-color support.
try:
color_index += 1
curses.init_pair(color_index, 245, -1)
self._color_pairs[cli_shared.COLOR_GRAY] = curses.color_pair(color_index)
except curses.error:
# Use fall-back color(s):
self._color_pairs[cli_shared.COLOR_GRAY] = (
self._color_pairs[cli_shared.COLOR_GREEN])
# A_BOLD or A_BLINK is not really a "color". But place it here for
# convenience.
self._color_pairs["bold"] = curses.A_BOLD
self._color_pairs["blink"] = curses.A_BLINK
self._color_pairs["underline"] = curses.A_UNDERLINE
# Default color pair to use when a specified color pair does not exist.
self._default_color_pair = self._color_pairs[cli_shared.COLOR_WHITE]
def _screen_launch(self, enable_mouse_on_start):
"""Launch the curses screen."""
curses.noecho()
curses.cbreak()
self._stdscr.keypad(1)
self._mouse_enabled = enable_mouse_on_start
self._screen_set_mousemask()
self._screen_create_command_window()
def _screen_create_command_window(self):
"""Create command window according to screen size."""
if self._command_window:
del self._command_window
self._command_window = curses.newwin(
self._command_textbox_height, self._max_x - len(self.CLI_PROMPT),
self._max_y - self._command_textbox_height, len(self.CLI_PROMPT))
def _screen_refresh(self):
self._stdscr.refresh()
def _screen_terminate(self):
"""Terminate the curses screen."""
self._stdscr.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
try:
# Remove SIGINT handler.
signal.signal(signal.SIGINT, signal.SIG_DFL)
except ValueError:
# Can't catch signals unless you're the main thread.
pass
def run_ui(self,
init_command=None,
title=None,
title_color=None,
enable_mouse_on_start=True):
"""Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details."""
# Only one instance of the Curses UI can be running at a time, since
# otherwise they would try to both read from the same keystrokes, and write
# to the same screen.
self._single_instance_lock.acquire()
self._screen_launch(enable_mouse_on_start=enable_mouse_on_start)
# Optional initial command.
if init_command is not None:
self._dispatch_command(init_command)
if title is not None:
self._title(title, title_color=title_color)
# CLI main loop.
exit_token = self._ui_loop()
if self._on_ui_exit:
self._on_ui_exit()
self._screen_terminate()
self._single_instance_lock.release()
return exit_token
def get_help(self):
return self._command_handler_registry.get_help()
def _addstr(self, *args):
try:
self._stdscr.addstr(*args)
except curses.error:
pass
def _refresh_pad(self, pad, *args):
try:
pad.refresh(*args)
except curses.error:
pass
def _screen_create_command_textbox(self, existing_command=None):
"""Create command textbox on screen.
Args:
existing_command: (str) A command string to put in the textbox right
after its creation.
"""
# Display the tfdbg prompt.
self._addstr(self._max_y - self._command_textbox_height, 0,
self.CLI_PROMPT, curses.A_BOLD)
self._stdscr.refresh()
self._command_window.clear()
# Command text box.
self._command_textbox = textpad.Textbox(
self._command_window, insert_mode=True)
# Enter existing command.
self._auto_key_in(existing_command)
def _ui_loop(self):
"""Command-line UI loop.
Returns:
An exit token of arbitrary type. The token can be None.
"""
while True:
# Enter history command if pointer is in history (> 0):
if self._command_pointer > 0:
existing_command = self._active_command_history[-self._command_pointer]
else:
existing_command = self._pending_command
self._screen_create_command_textbox(existing_command)
try:
command, terminator, pending_command_changed = self._get_user_command()
except debugger_cli_common.CommandLineExit as e:
return e.exit_token
if not command and terminator != self.CLI_TAB_KEY:
continue
if terminator in self.CLI_CR_KEYS or terminator == curses.KEY_MOUSE:
exit_token = self._dispatch_command(command)
if exit_token is not None:
return exit_token
elif terminator == self.CLI_TAB_KEY:
tab_completed = self._tab_complete(command)
self._pending_command = tab_completed
self._cmd_ptr = 0
elif pending_command_changed:
self._pending_command = command
return
def _get_user_command(self):
"""Get user command from UI.
Returns:
command: (str) The user-entered command.
terminator: (str) Terminator type for the command.
If command is a normal command entered with the Enter key, the value
will be the key itself. If this is a tab completion call (using the
Tab key), the value will reflect that as well.
pending_command_changed: (bool) If the pending command has changed.
Used during command history navigation.
"""
# First, reset textbox state variables.
self._textbox_curr_terminator = None
self._textbox_pending_command_changed = False
command = self._screen_get_user_command()
command = self._strip_terminator(command)
return (command, self._textbox_curr_terminator,
self._textbox_pending_command_changed)
def _screen_get_user_command(self):
return self._command_textbox.edit(validate=self._on_textbox_keypress)
def _strip_terminator(self, command):
if not command:
return command
for v in self.CLI_CR_KEYS:
if v < 256:
command = command.replace(chr(v), "")
return command.strip()
def _screen_refresh_size(self):
self._max_y, self._max_x = self._stdscr.getmaxyx()
if self._max_x > self._SCREEN_WIDTH_LIMIT:
self._max_x = self._SCREEN_WIDTH_LIMIT
def _navigate_screen_output(self, command):
"""Navigate in screen output history.
Args:
command: (`str`) the navigation command, from
{self._NAVIGATION_FORWARD_COMMAND, self._NAVIGATION_BACK_COMMAND}.
"""
if command == self._NAVIGATION_FORWARD_COMMAND:
if self._nav_history.can_go_forward():
item = self._nav_history.go_forward()
scroll_position = item.scroll_position
else:
self._toast("At the LATEST in navigation history!",
color=self._NAVIGATION_WARNING_COLOR_PAIR)
return
else:
if self._nav_history.can_go_back():
item = self._nav_history.go_back()
scroll_position = item.scroll_position
else:
self._toast("At the OLDEST in navigation history!",
color=self._NAVIGATION_WARNING_COLOR_PAIR)
return
self._display_output(item.screen_output)
if scroll_position != 0:
self._scroll_output(_SCROLL_TO_LINE_INDEX, line_index=scroll_position)
def _dispatch_command(self, command):
"""Dispatch user command.
Args:
command: (str) Command to dispatch.
Returns:
An exit token object. None value means that the UI loop should not exit.
A non-None value means the UI loop should exit.
"""
if self._output_pad:
self._toast(self._UI_WAIT_MESSAGE, color=self._UI_WAIT_COLOR_PAIR)
if command in self.CLI_EXIT_COMMANDS:
# Explicit user command-triggered exit: EXPLICIT_USER_EXIT as the exit
# token.
return debugger_cli_common.EXPLICIT_USER_EXIT
elif (command == self._NAVIGATION_FORWARD_COMMAND or
command == self._NAVIGATION_BACK_COMMAND):
self._navigate_screen_output(command)
return
if command:
self._command_history_store.add_command(command)
if (command.startswith(self.REGEX_SEARCH_PREFIX) and
self._curr_unwrapped_output):
if len(command) > len(self.REGEX_SEARCH_PREFIX):
# Command is like "/regex". Perform regex search.
regex = command[len(self.REGEX_SEARCH_PREFIX):]
self._curr_search_regex = regex
self._display_output(self._curr_unwrapped_output, highlight_regex=regex)
elif self._unwrapped_regex_match_lines:
# Command is "/". Continue scrolling down matching lines.
self._display_output(
self._curr_unwrapped_output,
is_refresh=True,
highlight_regex=self._curr_search_regex)
self._command_pointer = 0
self._pending_command = ""
return
elif command.startswith(self.TENSOR_INDICES_NAVIGATION_PREFIX):
indices_str = command[1:].strip()
if indices_str:
try:
indices = command_parser.parse_indices(indices_str)
omitted, line_index, _, _ = tensor_format.locate_tensor_element(
self._curr_wrapped_output, indices)
if not omitted:
self._scroll_output(
_SCROLL_TO_LINE_INDEX, line_index=line_index)
except Exception as e: # pylint: disable=broad-except
self._error_toast(str(e))
else:
self._error_toast("Empty indices.")
return
try:
prefix, args, output_file_path = self._parse_command(command)
except SyntaxError as e:
self._error_toast(str(e))
return
if not prefix:
# Empty command: take no action. Should not exit.
return
# Take into account scroll bar width.
screen_info = {"cols": self._max_x - 2}
exit_token = None
if self._command_handler_registry.is_registered(prefix):
try:
screen_output = self._command_handler_registry.dispatch_command(
prefix, args, screen_info=screen_info)
except debugger_cli_common.CommandLineExit as e:
exit_token = e.exit_token
else:
screen_output = debugger_cli_common.RichTextLines([
self.ERROR_MESSAGE_PREFIX + "Invalid command prefix \"%s\"" % prefix
])
# Clear active command history. Until next up/down history navigation
# occurs, it will stay empty.
self._active_command_history = []
if exit_token is not None:
return exit_token
self._nav_history.add_item(command, screen_output, 0)
self._display_output(screen_output)
if output_file_path:
try:
screen_output.write_to_file(output_file_path)
self._info_toast("Wrote output to %s" % output_file_path)
except Exception: # pylint: disable=broad-except
self._error_toast("Failed to write output to %s" % output_file_path)
self._command_pointer = 0
self._pending_command = ""
def _screen_gather_textbox_str(self):
"""Gather the text string in the command text box.
Returns:
(str) the current text string in the command textbox, excluding any
return keys.
"""
txt = self._command_textbox.gather()
return txt.strip()
def _on_textbox_keypress(self, x):
"""Text box key validator: Callback of key strokes.
Handles a user's keypress in the input text box. Translates certain keys to
terminator keys for the textbox to allow its edit() method to return.
Also handles special key-triggered events such as PgUp/PgDown scrolling of
the screen output.
Args:
x: (int) Key code.
Returns:
(int) A translated key code. In most cases, this is identical to the
input x. However, if x is a Return key, the return value will be
CLI_TERMINATOR_KEY, so that the text box's edit() method can return.
Raises:
TypeError: If the input x is not of type int.
debugger_cli_common.CommandLineExit: If a mouse-triggered command returns
an exit token when dispatched.
"""
if not isinstance(x, int):
raise TypeError("Key validator expected type int, received type %s" %
type(x))
if x in self.CLI_CR_KEYS:
# Make Enter key the terminator
self._textbox_curr_terminator = x
return self.CLI_TERMINATOR_KEY
elif x == self.CLI_TAB_KEY:
self._textbox_curr_terminator = self.CLI_TAB_KEY
return self.CLI_TERMINATOR_KEY
elif x == curses.KEY_PPAGE:
self._scroll_output(_SCROLL_UP_A_LINE)
return x
elif x == curses.KEY_NPAGE:
self._scroll_output(_SCROLL_DOWN_A_LINE)
return x
elif x == curses.KEY_HOME:
self._scroll_output(_SCROLL_HOME)
return x
elif x == curses.KEY_END:
self._scroll_output(_SCROLL_END)
return x
elif x in [curses.KEY_UP, curses.KEY_DOWN]:
# Command history navigation.
if not self._active_command_history:
hist_prefix = self._screen_gather_textbox_str()
self._active_command_history = (
self._command_history_store.lookup_prefix(
hist_prefix, self._command_history_limit))
if self._active_command_history:
if x == curses.KEY_UP:
if self._command_pointer < len(self._active_command_history):
self._command_pointer += 1
elif x == curses.KEY_DOWN:
if self._command_pointer > 0:
self._command_pointer -= 1
else:
self._command_pointer = 0
self._textbox_curr_terminator = x
# Force return from the textbox edit(), so that the textbox can be
# redrawn with a history command entered.
return self.CLI_TERMINATOR_KEY
elif x == curses.KEY_RESIZE:
# Respond to terminal resize.
self._screen_refresh_size()
self._init_layout()
self._screen_create_command_window()
self._redraw_output()
# Force return from the textbox edit(), so that the textbox can be
# redrawn.
return self.CLI_TERMINATOR_KEY
elif x == curses.KEY_MOUSE and self._mouse_enabled:
try:
_, mouse_x, mouse_y, _, mouse_event_type = self._screen_getmouse()
except curses.error:
mouse_event_type = None
if mouse_event_type == curses.BUTTON1_RELEASED:
# Logic for mouse-triggered scrolling.
if mouse_x >= self._max_x - 2:
scroll_command = self._scroll_bar.get_click_command(mouse_y)
if scroll_command is not None:
self._scroll_output(scroll_command)
return x
else:
command = self._fetch_hyperlink_command(mouse_x, mouse_y)
if command:
self._screen_create_command_textbox()
exit_token = self._dispatch_command(command)
if exit_token is not None:
raise debugger_cli_common.CommandLineExit(exit_token=exit_token)
else:
# Mark the pending command as modified.
self._textbox_pending_command_changed = True
# Invalidate active command history.
self._command_pointer = 0
self._active_command_history = []
return self._KEY_MAP.get(x, x)
def _screen_getmouse(self):
return curses.getmouse()
def _redraw_output(self):
if self._curr_unwrapped_output is not None:
self._display_nav_bar()
self._display_main_menu(self._curr_unwrapped_output)
self._display_output(self._curr_unwrapped_output, is_refresh=True)
def _fetch_hyperlink_command(self, mouse_x, mouse_y):
output_top = self._output_top_row
if self._main_menu_pad:
output_top += 1
if mouse_y == self._nav_bar_row and self._nav_bar:
# Click was in the nav bar.
return _get_command_from_line_attr_segs(mouse_x,
self._nav_bar.font_attr_segs[0])
elif mouse_y == self._output_top_row and self._main_menu_pad:
# Click was in the menu bar.
return _get_command_from_line_attr_segs(mouse_x,
self._main_menu.font_attr_segs[0])
else:
absolute_mouse_y = mouse_y + self._output_pad_row - output_top
if absolute_mouse_y in self._curr_wrapped_output.font_attr_segs:
return _get_command_from_line_attr_segs(
mouse_x, self._curr_wrapped_output.font_attr_segs[absolute_mouse_y])
def _title(self, title, title_color=None):
"""Display title.
Args:
title: (str) The title to display.
title_color: (str) Color of the title, e.g., "yellow".
"""
# Pad input title str with "-" and space characters to make it pretty.
self._title_line = "--- %s " % title
if len(self._title_line) < self._max_x:
self._title_line += "-" * (self._max_x - len(self._title_line))
self._screen_draw_text_line(
self._title_row, self._title_line, color=title_color)
def _auto_key_in(self, command, erase_existing=False):
"""Automatically key in a command to the command Textbox.
Args:
command: The command, as a string or None.
erase_existing: (bool) whether existing text (if any) is to be erased
first.
"""
if erase_existing:
self._erase_existing_command()
command = command or ""
for c in command:
self._command_textbox.do_command(ord(c))
def _erase_existing_command(self):
"""Erase existing text in command textpad."""
existing_len = len(self._command_textbox.gather())
for _ in xrange(existing_len):
self._command_textbox.do_command(self.BACKSPACE_KEY)
def _screen_draw_text_line(self, row, line, attr=curses.A_NORMAL, color=None):
"""Render a line of text on the screen.
Args:
row: (int) Row index.
line: (str) The line content.
attr: curses font attribute.
color: (str) font foreground color name.
Raises:
TypeError: If row is not of type int.
"""
if not isinstance(row, int):
raise TypeError("Invalid type in row")
if len(line) > self._max_x:
line = line[:self._max_x]
color_pair = (self._default_color_pair if color is None else
self._color_pairs[color])
self._addstr(row, 0, line, color_pair | attr)
self._screen_refresh()
def _screen_new_output_pad(self, rows, cols):
"""Generate a new pad on the screen.
Args:
rows: (int) Number of rows the pad will have: not limited to screen size.
cols: (int) Number of columns the pad will have: not limited to screen
size.
Returns:
A curses textpad object.
"""
return curses.newpad(rows, cols)
def _screen_display_output(self, output):
"""Actually render text output on the screen.
Wraps the lines according to screen width. Pad lines below according to
screen height so that the user can scroll the output to a state where
the last non-empty line is on the top of the screen. Then renders the
lines on the screen.
Args:
output: (RichTextLines) text lines to display on the screen. These lines
may have widths exceeding the screen width. This method will take care
of the wrapping.
Returns:
(List of int) A list of line indices, in the wrapped output, where there
are regex matches.
"""
# Wrap the output lines according to screen width.
self._curr_wrapped_output, wrapped_line_indices = (
debugger_cli_common.wrap_rich_text_lines(output, self._max_x - 2))