-
Notifications
You must be signed in to change notification settings - Fork 224
/
debugger.py
2773 lines (2207 loc) · 100 KB
/
debugger.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
__copyright__ = """
Copyright (C) 2009-2017 Andreas Kloeckner
Copyright (C) 2014-2017 Aaron Meurer
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import urwid
import bdb
import gc
import os
import sys
from itertools import count
from functools import partial
from types import TracebackType
from pudb.lowlevel import decode_lines, ui_log
from pudb.settings import load_config, save_config
CONFIG = load_config()
save_config(CONFIG)
HELP_HEADER = r"""
Key Assignments: Use Arrow Down/Up or Page Down/Up to scroll.
"""
HELP_MAIN = r"""
Keys:
Ctrl-p - edit preferences
n - step over ("next")
s - step into
c - continue
r/f - finish current function
t - run to cursor
e - show traceback [post-mortem or in exception state]
b - set/clear breakpoint
Ctrl-e - open file at current line to edit with $EDITOR
H - move to current line (bottom of stack)
u - move up one stack frame
d - move down one stack frame
o - show console/output screen
m - open module
j/k - down/up
l/h - right/left
Ctrl-f/b - page down/up
Ctrl-d/u - page down/up
G/g - end/home
L - show (file/line) location / go to line
/ - search
,/. - search next/previous
V - focus variables
S - focus stack
B - focus breakpoint list
C - focus code
F1/? - show this help screen
q - quit
Ctrl-r - reload breakpoints from saved-breakpoints file
Ctrl-c - when in continue mode, break back to PuDB
Ctrl-l - redraw screen
Shell-related:
! - open the external shell (configured in the settings)
Ctrl-x - toggle the internal shell focus
+/- - grow/shrink inline shell (active in command line history)
_/= - minimize/maximize inline shell (active in command line history)
Ctrl-v - insert newline
Ctrl-n/p - browse command line history
Tab - yes, there is (simple) tab completion
"""
HELP_SIDE = r"""
Sidebar-related (active in sidebar):
+/- - grow/shrink sidebar
_/= - minimize/maximize sidebar
[/] - grow/shrink relative size of active sidebar box
Keys in variables list:
\/enter/space - expand/collapse
h - collapse
l - expand
d/t/r/s/i/c - show default/type/repr/str/id/custom for this variable
H - toggle highlighting
@ - toggle repetition at top
* - cycle attribute visibility: public/_private/__dunder__
m - toggle method visibility
w - toggle line wrapping
n/insert - add new watch expression
e - edit options (also to delete)
Keys in stack list:
enter - jump to frame
Ctrl-e - open file at line to edit with $EDITOR
Keys in breakpoints list:
enter - jump to breakpoint
b - toggle breakpoint
d - delete breakpoint
e - edit breakpoint
Other keys:
j/k - down/up
l/h - right/left
Ctrl-f/b - page down/up
Ctrl-d/u - page down/up
G/g - end/home
V - focus variables
S - focus stack
B - focus breakpoint list
C - focus code
F1/? - show this help screen
q - quit
Ctrl-l - redraw screen
"""
HELP_LICENSE = r"""
License:
--------
PuDB is licensed to you under the MIT/X Consortium license:
Copyright (c) 2009-16 Andreas Kloeckner and contributors
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
# {{{ debugger interface
class Debugger(bdb.Bdb):
def __init__(self, stdin=None, stdout=None, term_size=None, steal_output=False,
**kwargs):
# Pass remaining kwargs to python debugger framework
bdb.Bdb.__init__(self, **kwargs)
self.ui = DebuggerUI(self, stdin=stdin, stdout=stdout, term_size=term_size)
self.steal_output = steal_output
self.setup_state()
if steal_output:
raise NotImplementedError("output stealing")
from io import StringIO
self.stolen_output = sys.stderr = sys.stdout = StringIO()
sys.stdin = StringIO("") # avoid spurious hangs
from pudb.settings import load_breakpoints
for bpoint_descr in load_breakpoints():
self.set_break(*bpoint_descr)
# These (dispatch_line and set_continue) are copied from bdb with the
# patch from https://bugs.python.org/issue16482 applied. See
# https://github.com/inducer/pudb/pull/90.
def dispatch_line(self, frame):
if self.stop_here(frame) or self.break_here(frame):
self.user_line(frame)
if self.quitting:
raise bdb.BdbQuit
# Do not re-install the local trace when we are finished debugging,
# see issues 16482 and 7238.
if not sys.gettrace():
return None
return self.trace_dispatch
def set_continue(self):
# Don't stop except at breakpoints or when finished
self._set_stopinfo(self.botframe, None, -1)
if not self.breaks:
# no breakpoints; run without debugger overhead
sys.settrace(None)
frame = sys._getframe().f_back
while frame:
del frame.f_trace
if frame is self.botframe:
break
frame = frame.f_back
def set_trace(self, frame=None, as_breakpoint=None, paused=True):
"""Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame.
Unlike Bdb.set_trace(), this does not call self.reset(), which causes
the debugger to enter bdb source code. This also implements treating
set_trace() calls as breakpoints in the PuDB UI.
If as_breakpoint=True (the default), this call will be treated like a
breakpoint in the UI (you can press 'b' on it to disable breaking
here).
If paused=False, the debugger will not break here.
"""
if as_breakpoint is None:
if not paused:
as_breakpoint = False
else:
as_breakpoint = True
if frame is None:
frame = thisframe = sys._getframe().f_back
else:
thisframe = frame
# See pudb issue #52. If this works well enough we should upstream to
# stdlib bdb.py.
#self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
thisframe_info = (
self.canonic(thisframe.f_code.co_filename), thisframe.f_lineno)
if thisframe_info not in self.set_traces or self.set_traces[thisframe_info]:
if as_breakpoint:
self.set_traces[thisframe_info] = True
if self.ui.source_code_provider is not None:
self.ui.set_source_code_provider(
self.ui.source_code_provider, force_update=True)
if paused:
self.set_step()
else:
self.set_continue()
sys.settrace(self.trace_dispatch)
else:
return
def save_breakpoints(self):
from pudb.settings import save_breakpoints
save_breakpoints([
bp
for fn, bp_lst in self.get_all_breaks().items()
for lineno in bp_lst
for bp in self.get_breaks(fn, lineno)
if not bp.temporary])
def enter_post_mortem(self, exc_tuple):
self.post_mortem = True
def setup_state(self):
self.bottom_frame = None
self.mainpyfile = ""
self._wait_for_mainpyfile = False
self.current_bp = None
self.post_mortem = False
# Mapping of (filename, lineno) to bool. If True, will stop on the
# set_trace() call at that location.
self.set_traces = {}
def restart(self):
from linecache import checkcache
checkcache()
self.ui.set_source_code_provider(NullSourceCodeProvider())
self.setup_state()
def do_clear(self, arg):
self.clear_bpbynumber(int(arg))
def set_frame_index(self, index):
self.curindex = index
if index < 0 or index >= len(self.stack):
return
self.curframe, lineno = self.stack[index]
filename = self.curframe.f_code.co_filename
import linecache
if not linecache.getlines(filename):
code = self.curframe.f_globals.get("_MODULE_SOURCE_CODE")
if code is not None:
self.ui.set_current_line(lineno,
DirectSourceCodeProvider(
self.curframe.f_code.co_name, code))
else:
self.ui.set_current_line(lineno,
NullSourceCodeProvider())
else:
self.ui.set_current_line(lineno,
FileSourceCodeProvider(self, filename))
self.ui.update_var_view()
self.ui.update_stack()
self.ui.stack_list._w.set_focus(self.ui.translate_ui_stack_index(index))
@staticmethod
def open_file_to_edit(filename, line_number):
if not os.path.isfile(filename):
raise FileNotFoundError(f"'{filename}' not found or is not a file.")
if not line_number:
line_number = 1
editor = os.environ.get("EDITOR", "nano")
import subprocess
subprocess.call([editor, f"+{line_number}", filename], shell=False)
return filename
def move_up_frame(self):
if self.curindex > 0:
self.set_frame_index(self.curindex-1)
def move_down_frame(self):
if self.curindex < len(self.stack)-1:
self.set_frame_index(self.curindex+1)
def get_shortened_stack(self, frame, tb):
stack, index = self.get_stack(frame, tb)
for i, (s_frame, _lineno) in enumerate(stack):
if s_frame is self.bottom_frame and index >= i:
stack = stack[i:]
index -= i
return stack, index
def interaction(self, frame, exc_tuple=None, show_exc_dialog=True):
if exc_tuple is None:
tb = None
elif isinstance(exc_tuple, TracebackType):
# For API compatibility with other debuggers, the second variable
# can be a traceback object. In that case, we need to retrieve the
# corresponding exception tuple.
tb = exc_tuple
exc, = (exc for exc in gc.get_referrers(tb)
if getattr(exc, "__traceback__", None) is tb)
exc_tuple = type(exc), exc, tb
else:
tb = exc_tuple[2]
if frame is None and tb is not None:
frame = tb.tb_frame
found_bottom_frame = False
walk_frame = frame
while True:
if walk_frame is self.bottom_frame:
found_bottom_frame = True
break
if walk_frame is None:
break
walk_frame = walk_frame.f_back
if not found_bottom_frame and not self.post_mortem:
return
self.stack, index = self.get_shortened_stack(frame, tb)
if self.post_mortem:
index = len(self.stack)-1
self.set_frame_index(index)
self.ui.call_with_ui(self.ui.interaction, exc_tuple,
show_exc_dialog=show_exc_dialog)
def get_stack_situation_id(self):
return str(id(self.stack[self.curindex][0].f_code))
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self._wait_for_mainpyfile:
return
if self.stop_here(frame):
self.interaction(frame)
def user_line(self, frame):
"""This function is called when we stop or break at this line."""
if "__exc_tuple__" in frame.f_locals:
del frame.f_locals["__exc_tuple__"]
if self._wait_for_mainpyfile:
if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
or frame.f_lineno <= 0):
return
self._wait_for_mainpyfile = False
self.bottom_frame = frame
if self.get_break(self.canonic(frame.f_code.co_filename), frame.f_lineno):
self.current_bp = (
self.canonic(frame.f_code.co_filename), frame.f_lineno)
else:
self.current_bp = None
try:
self.ui.update_breakpoints()
self.interaction(frame)
except Exception:
self.ui.show_internal_exc_dlg(sys.exc_info())
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
if frame.f_code.co_name != "<module>":
frame.f_locals["__return__"] = return_value
if self._wait_for_mainpyfile:
if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
or frame.f_lineno <= 0):
return
self._wait_for_mainpyfile = False
self.bottom_frame = frame
if "__exc_tuple__" not in frame.f_locals:
self.interaction(frame)
def user_exception(self, frame, exc_tuple):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
frame.f_locals["__exc_tuple__"] = exc_tuple
if not self._wait_for_mainpyfile:
self.interaction(frame, exc_tuple)
def _runscript(self, filename):
# Provide separation from current __main__, which is likely
# pudb.__main__ run. Preserving its namespace is not important, and
# having the script share it ensures that, e.g., pickle can find
# types defined there:
# https://github.com/inducer/pudb/issues/331
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": filename,
"__builtins__": __builtins__,
})
# When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to
# avoid stopping before we reach the main script (see user_line and
# user_call for details).
self._wait_for_mainpyfile = 1
self.mainpyfile = self.canonic(filename)
statement = 'exec(compile(open("{}").read(), "{}", "exec"))'.format(
filename, filename)
# Set up an interrupt handler
from pudb import set_interrupt_handler
set_interrupt_handler()
# Implicitly runs in the namespace of __main__.
self.run(statement)
def _runmodule(self, module_name):
# This is basically stolen from the pdb._runmodule from CPython 3.8
# https://github.com/python/cpython/blob/a1d3be4623c8ec7069bd34ccdce336be9cdeb644/Lib/pdb.py#L1530
import runpy
mod_name, mod_spec, code = runpy._get_module_details(module_name)
self.mainpyfile = self.canonic(code.co_filename)
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": self.mainpyfile,
"__spec__": mod_spec,
"__builtins__": __builtins__,
"__package__": mod_spec.parent,
"__loader__": mod_spec.loader,
})
self._wait_for_mainpyfile = True
self.run(code)
# }}}
# UI stuff --------------------------------------------------------------------
from pudb.ui_tools import make_hotkey_markup, labelled_value, \
SelectableText, SignalWrap, StackFrame, BreakpointFrame
from pudb.var_view import FrameVarInfoKeeper
# {{{ display setup
try:
import curses
except ImportError:
curses = None
from urwid.raw_display import Screen as RawScreen
try:
from urwid.curses_display import Screen as CursesScreen
except ImportError:
CursesScreen = None
class ThreadsafeScreenMixin:
"""A Screen subclass that doesn't crash when running from a non-main thread."""
def signal_init(self):
"""Initialize signal handler, ignoring errors silently."""
try:
super().signal_init()
except ValueError:
pass
def signal_restore(self):
"""Restore default signal handler, ignoring errors silently."""
try:
super().signal_restore()
except ValueError:
pass
class ThreadsafeRawScreen(ThreadsafeScreenMixin, RawScreen):
pass
class ThreadsafeFixedSizeRawScreen(ThreadsafeScreenMixin, RawScreen):
def __init__(self, **kwargs):
self._term_size = kwargs.pop("term_size", None)
super().__init__(**kwargs)
def get_cols_rows(self):
if self._term_size is not None:
return self._term_size
else:
return 80, 24
if curses is not None:
class ThreadsafeCursesScreen(ThreadsafeScreenMixin, RawScreen):
pass
# }}}
# {{{ source code providers
class SourceCodeProvider:
def __ne__(self, other):
return not (self == other)
class NullSourceCodeProvider(SourceCodeProvider):
def __eq__(self, other):
return type(self) == type(other)
def identifier(self):
return "<no source code>"
def get_source_identifier(self):
return None
def clear_cache(self):
pass
def get_lines(self, debugger_ui):
from pudb.source_view import SourceLine
return [
SourceLine(debugger_ui, "<no source code available>"),
SourceLine(debugger_ui, ""),
SourceLine(debugger_ui, "If this is generated code and you would "
"like the source code to show up here,"),
SourceLine(debugger_ui, "add it to linecache.cache, like"),
SourceLine(debugger_ui, ""),
SourceLine(debugger_ui, " import linecache"),
SourceLine(debugger_ui, " linecache.cache[filename] = "
"(size, mtime, lines, fullname)"),
SourceLine(debugger_ui, ""),
SourceLine(debugger_ui, "You can also set the attribute "
"_MODULE_SOURCE_CODE in the module in which this function"),
SourceLine(debugger_ui, "was compiled to a string containing "
"the code."),
]
class FileSourceCodeProvider(SourceCodeProvider):
def __init__(self, debugger, file_name):
self.file_name = debugger.canonic(file_name)
def __eq__(self, other):
return type(self) == type(other) and self.file_name == other.file_name
def identifier(self):
return self.file_name
def get_source_identifier(self):
return self.file_name
def clear_cache(self):
from linecache import clearcache
clearcache()
def get_lines(self, debugger_ui):
from pudb.source_view import SourceLine, format_source
if self.file_name == "<string>":
return [SourceLine(debugger_ui, self.file_name)]
breakpoints = debugger_ui.debugger.get_file_breaks(self.file_name)[:]
breakpoints = [lineno for lineno in breakpoints if
any(bp.enabled
for bp in debugger_ui.debugger.get_breaks(self.file_name, lineno))]
breakpoints += [i for f, i in debugger_ui.debugger.set_traces if f
== self.file_name and debugger_ui.debugger.set_traces[f, i]]
try:
from linecache import getlines
lines = getlines(self.file_name)
return format_source(
debugger_ui, list(decode_lines(lines)), set(breakpoints))
except Exception:
from pudb.lowlevel import format_exception
debugger_ui.message("Could not load source file '{}':\n\n{}".format(
self.file_name, "".join(format_exception(sys.exc_info()))),
title="Source Code Load Error")
return [SourceLine(debugger_ui,
"Error while loading '%s'." % self.file_name)]
class DirectSourceCodeProvider(SourceCodeProvider):
def __init__(self, func_name, code):
self.function_name = func_name
self.code = code
def __eq__(self, other):
return (
type(self) == type(other)
and self.function_name == other.function_name
and self.code is other.code)
def identifier(self):
return "<source code of function %s>" % self.function_name
def get_source_identifier(self):
return None
def clear_cache(self):
pass
def get_lines(self, debugger_ui):
from pudb.source_view import format_source
lines = self.code.splitlines(True)
return format_source(debugger_ui, list(decode_lines(lines)), set())
# }}}
class DebuggerUI(FrameVarInfoKeeper):
# {{{ constructor
def __init__(self, dbg, stdin, stdout, term_size):
FrameVarInfoKeeper.__init__(self)
self.debugger = dbg
from urwid import AttrMap
from pudb.ui_tools import SearchController
self.search_controller = SearchController(self)
self.last_module_filter = ""
# {{{ build ui
# {{{ key bindings
def move_up(w, size, key):
w.keypress(size, "up")
def move_down(w, size, key):
w.keypress(size, "down")
def move_left(w, size, key):
w.keypress(size, "left")
def move_right(w, size, key):
w.keypress(size, "right")
def page_up(w, size, key):
w.keypress(size, "page up")
def page_down(w, size, key):
w.keypress(size, "page down")
def move_home(w, size, key):
w.keypress(size, "home")
def move_end(w, size, key):
w.keypress(size, "end")
def add_vi_nav_keys(widget):
widget.listen("k", move_up)
widget.listen("j", move_down)
widget.listen("h", move_left)
widget.listen("l", move_right)
widget.listen("ctrl b", page_up)
widget.listen("ctrl f", page_down)
widget.listen("ctrl u", page_up)
widget.listen("ctrl d", page_down)
widget.listen("g", move_home)
widget.listen("G", move_end)
def add_help_keys(widget, helpfunc):
widget.listen("f1", helpfunc)
widget.listen("?", helpfunc)
# }}}
# {{{ left/source column
self.source = urwid.SimpleListWalker([])
self.source_list = urwid.ListBox(self.source)
self.source_sigwrap = SignalWrap(self.source_list)
self.source_attr = urwid.AttrMap(self.source_sigwrap, "source")
self.source_hscroll_start = 0
self.cmdline_history = []
self.cmdline_history_position = -1
self.cmdline_contents = urwid.SimpleFocusListWalker([])
self.cmdline_list = urwid.ListBox(self.cmdline_contents)
self.cmdline_edit = urwid.Edit([
("command line prompt", ">>> ")
])
cmdline_edit_attr = urwid.AttrMap(self.cmdline_edit, "command line edit")
self.cmdline_edit_sigwrap = SignalWrap(
cmdline_edit_attr, is_preemptive=True)
def clear_cmdline_history(btn):
del self.cmdline_contents[:]
self.cmdline_edit_bar = urwid.Columns([
self.cmdline_edit_sigwrap,
("fixed", 10, AttrMap(
urwid.Button("Clear", clear_cmdline_history),
"command line clear button", "command line focused button"))
])
self.cmdline_pile = urwid.Pile([
("flow", urwid.Text("Command line: [Ctrl-X]")),
("weight", 1, urwid.AttrMap(self.cmdline_list, "command line output")),
("flow", self.cmdline_edit_bar),
])
self.cmdline_sigwrap = SignalWrap(
urwid.AttrMap(self.cmdline_pile, None, "focused sidebar")
)
self.cmdline_on = not CONFIG["hide_cmdline_win"]
self.cmdline_weight = 1
self.lhs_col = urwid.Pile([
("weight", 5, self.source_attr),
("weight", self.cmdline_weight if self.cmdline_on else 0,
self.cmdline_sigwrap),
])
# }}}
# {{{ right column
self.locals = urwid.SimpleListWalker([])
self.var_list = SignalWrap(
urwid.ListBox(self.locals))
self.stack_walker = urwid.SimpleListWalker([])
self.stack_list = SignalWrap(
urwid.ListBox(self.stack_walker))
self.bp_walker = urwid.SimpleListWalker([])
self.bp_list = SignalWrap(
urwid.ListBox(self.bp_walker))
self.rhs_col = urwid.Pile([
("weight", float(CONFIG["variables_weight"]), AttrMap(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Variables:"))),
AttrMap(self.var_list, "variables"),
]), None, "focused sidebar"),),
("weight", float(CONFIG["stack_weight"]), AttrMap(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Stack:"))),
AttrMap(self.stack_list, "stack"),
]), None, "focused sidebar"),),
("weight", float(CONFIG["breakpoints_weight"]), AttrMap(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Breakpoints:"))),
AttrMap(self.bp_list, "breakpoint"),
]), None, "focused sidebar"),),
])
self.rhs_col_sigwrap = SignalWrap(self.rhs_col)
def helpside(w, size, key):
help(HELP_HEADER + HELP_SIDE + HELP_MAIN + HELP_LICENSE)
add_vi_nav_keys(self.rhs_col_sigwrap)
add_help_keys(self.rhs_col_sigwrap, helpside)
# }}}
self.columns = urwid.Columns(
[
("weight", 1, self.lhs_col),
("weight", float(CONFIG["sidebar_width"]),
self.rhs_col_sigwrap),
],
dividechars=1)
self.caption = urwid.Text("")
header = urwid.AttrMap(self.caption, "header")
self.top = SignalWrap(urwid.Frame(
urwid.AttrMap(self.columns, "background"),
header))
# }}}
def change_rhs_box(name, index, direction, w, size, key):
from pudb.settings import save_config
weight = self.rhs_col.item_types[index][1]
if direction < 0:
if weight > 1/5:
weight /= 1.25
else:
if weight < 5:
weight *= 1.25
CONFIG[name+"_weight"] = weight
save_config(CONFIG)
self.rhs_col.item_types[index] = "weight", weight
self.rhs_col._invalidate()
# {{{ variables listeners
def get_inspect_info(id_path, read_only=False):
return (self.get_frame_var_info(read_only)
.get_inspect_info(id_path, read_only))
def collapse_current(var, pos, iinfo):
if iinfo.show_detail:
# collapse current variable
iinfo.show_detail = False
else:
# collapse parent/container variable
if var.parent is not None:
p_iinfo = get_inspect_info(var.parent.id_path)
p_iinfo.show_detail = False
return self.locals.index(var.parent)
return None
def change_var_state(w, size, key):
var, pos = self.var_list._w.get_focus()
if var is None:
return
iinfo = get_inspect_info(var.id_path)
focus_index = None
if key == "enter" or key == "\\" or key == " ":
iinfo.show_detail = not iinfo.show_detail
elif key == "h":
focus_index = collapse_current(var, pos, iinfo)
elif key == "l":
iinfo.show_detail = True
elif key == "d":
iinfo.display_type = "default"
elif key == "t":
iinfo.display_type = "type"
elif key == "r":
iinfo.display_type = "repr"
elif key == "s":
iinfo.display_type = "str"
elif key == "i":
iinfo.display_type = "id"
elif key == "c":
iinfo.display_type = CONFIG["custom_stringifier"]
elif key == "H":
iinfo.highlighted = not iinfo.highlighted
elif key == "@":
iinfo.repeated_at_top = not iinfo.repeated_at_top
elif key == "*":
levels = ["public", "private", "all", "public"]
iinfo.access_level = levels[levels.index(iinfo.access_level)+1]
elif key == "w":
iinfo.wrap = not iinfo.wrap
elif key == "m":
iinfo.show_methods = not iinfo.show_methods
self.update_var_view(focus_index=focus_index)
def edit_inspector_detail(w, size, key):
var, pos = self.var_list._w.get_focus()
if var is None:
return
fvi = self.get_frame_var_info(read_only=False)
iinfo = fvi.get_inspect_info(var.id_path, read_only=False)
buttons = [
("OK", True),
("Cancel", False),
]
if var.watch_expr is not None:
watch_edit = urwid.Edit([
("label", "Watch expression: ")
], var.watch_expr.expression)
id_segment = [urwid.AttrMap(watch_edit, "value"), urwid.Text("")]
buttons.extend([None, ("Delete", "del")])
title = "Watch Expression Options"
else:
id_segment = [
labelled_value("Identifier Path: ", var.id_path),
urwid.Text(""),
]
title = "Variable Inspection Options"
rb_grp_show = []
rb_show_default = urwid.RadioButton(rb_grp_show, "Default",
iinfo.display_type == "default")
rb_show_type = urwid.RadioButton(rb_grp_show, "Show type()",
iinfo.display_type == "type")
rb_show_repr = urwid.RadioButton(rb_grp_show, "Show repr()",
iinfo.display_type == "repr")
rb_show_str = urwid.RadioButton(rb_grp_show, "Show str()",
iinfo.display_type == "str")
rb_show_id = urwid.RadioButton(rb_grp_show, "Show id()",
iinfo.display_type == "id")
rb_show_custom = urwid.RadioButton(
rb_grp_show, "Show custom (set in prefs)",
iinfo.display_type == CONFIG["custom_stringifier"])
rb_grp_access = []
rb_access_public = urwid.RadioButton(rb_grp_access, "Public members",
iinfo.access_level == "public")
rb_access_private = urwid.RadioButton(
rb_grp_access, "Public and private members",
iinfo.access_level == "private")
rb_access_all = urwid.RadioButton(
rb_grp_access, "All members (including __dunder__)",
iinfo.access_level == "all")
wrap_checkbox = urwid.CheckBox("Line Wrap", iinfo.wrap)
expanded_checkbox = urwid.CheckBox("Expanded", iinfo.show_detail)