/
debugger.py
1622 lines (1276 loc) · 55.7 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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import urwid
import bdb
import sys
from pudb.settings import load_config, save_config
CONFIG = load_config()
save_config(CONFIG)
from pudb.py3compat import PY3, raw_input
if PY3:
_next = "__next__"
else:
_next = "next"
try:
from functools import partial
except ImportError:
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
HELP_TEXT = """\
Welcome to PuDB, the Python Urwid debugger.
-------------------------------------------
(This help screen is scrollable. Hit Page Down to see more.)
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]
H - move to current line (bottom of stack)
u - move up one stack frame
d - move down one stack frame
! - invoke python shell in current environment
o - show console/output screen
b - toggle breakpoint
m - open module
j/k - up/down
Ctrl-u/d - page up/down
h/l - scroll left/right
g/G - start/end
L - show (file/line) location / go to line
/ - search
,/. - search next/previous
V - focus variables
S - focus stack
B - focus breakpoint list
f1/?/H - show this help screen
q - quit
Ctrl-c - when in continue mode, break back to PuDB
Side-bar related:
+/- - grow/shrink sidebar
_/= - minimize/maximize sidebar
[/] - grow/shrink relative size of active sidebar box
Keys in variables list:
\ - expand/collapse
t/r/s/c - show type/repr/str/custom for this variable
h - toggle highlighting
@ - toggle repetition at top
* - toggle private members
w - toggle line wrapping
n/insert - add new watch expression
enter - edit options (also to delete)
Keys in stack list:
enter - jump to frame
Keys in breakpoints view:
enter - edit breakpoint
d - delete breakpoint
License:
--------
PuDB is licensed to you under the MIT/X Consortium license:
Copyright (c) 2009-13 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, steal_output=False):
bdb.Bdb.__init__(self)
self.ui = DebuggerUI(self)
self.steal_output = steal_output
self.setup_state()
if steal_output:
raise NotImplementedError("output stealing")
import sys
if PY3:
from io import StringIO
else:
from cStringIO 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)
def set_trace(self, frame=None):
"""Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame.
This is exactly the same as Bdb.set_trace(), sans the self.reset() call.
"""
if frame is None:
frame = sys._getframe().f_back
# 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
self.set_step()
sys.settrace(self.trace_dispatch)
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
def restart(self):
from linecache import checkcache
checkcache()
self.ui.set_current_file('<string>')
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]
self.ui.set_current_line(lineno, self.curframe.f_code.co_filename)
self.ui.update_var_view()
self.ui.update_stack()
self.ui.stack_list._w.set_focus(self.ui.translate_ui_stack_index(index))
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
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
self.ui.update_breakpoints()
self.interaction(frame)
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
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):
# Start with fresh empty copy of globals and locals and tell the script
# that it's being run as __main__ to avoid scripts being able to access
# the debugger's namespace.
globals_ = {"__name__" : "__main__", "__file__": filename }
locals_ = globals_
# 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)
if PY3:
statement = 'exec(compile(open("%s").read(), "%s", "exec"))' % (filename, filename)
else:
statement = 'execfile( "%s")' % filename
# Set up an interrupt handler
from pudb import set_interrupt_handler
set_interrupt_handler()
self.run(statement, globals=globals_, locals=locals_)
# }}}
# UI stuff --------------------------------------------------------------------
from pudb.ui_tools import make_hotkey_markup, labelled_value, \
SelectableText, SignalWrap, StackFrame, BreakpointFrame
from pudb.var_view import FrameVarInfoKeeper
try:
import curses
except ImportError:
curses = None
from urwid.raw_display import Screen
class ThreadsafeScreen(Screen):
"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(ThreadsafeScreen, self).signal_init()
except ValueError:
pass
def signal_restore(self):
"Restore default signal handler, ignoring errors silently."
try:
super(ThreadsafeScreen, self).signal_restore()
except ValueError:
pass
class DebuggerUI(FrameVarInfoKeeper):
# {{{ constructor
def __init__(self, dbg):
FrameVarInfoKeeper.__init__(self)
self.debugger = dbg
Attr = urwid.AttrMap
from pudb.ui_tools import SearchController
self.search_controller = SearchController(self)
self.last_module_filter = ""
# {{{ build ui
self.source = urwid.SimpleListWalker([])
self.source_list = urwid.ListBox(self.source)
self.source_sigwrap = SignalWrap(self.source_list)
self.source_hscroll_start = 0
self.lhs_col = urwid.Pile([
("weight", 1, urwid.AttrMap(self.source_sigwrap, "source"))
])
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"]), Attr(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Variables:"))),
Attr(self.var_list, "variables"),
]), None, "focused sidebar"),),
("weight", float(CONFIG["stack_weight"]), Attr(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Stack:"))),
Attr(self.stack_list, "stack"),
]), None, "focused sidebar"),),
("weight", float(CONFIG["breakpoints_weight"]), Attr(urwid.Pile([
("flow", urwid.Text(make_hotkey_markup("_Breakpoints:"))),
Attr(self.bp_list, "breakpoint"),
]), None, "focused sidebar"),),
])
self.columns = urwid.Columns(
[
("weight", 1, self.lhs_col),
("weight", float(CONFIG["sidebar_width"]), self.rhs_col),
],
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]
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 change_var_state(w, size, key):
var, pos = self.var_list._w.get_focus()
iinfo = self.get_frame_var_info(read_only=False) \
.get_inspect_info(var.id_path, read_only=False)
if key == "\\": iinfo.show_detail = not iinfo.show_detail
elif key == "t": iinfo.display_type = "type"
elif key == "r": iinfo.display_type = "repr"
elif key == "s": iinfo.display_type = "str"
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 == "*": iinfo.show_private_members = not iinfo.show_private_members
elif key == "w": iinfo.wrap = not iinfo.wrap
self.update_var_view()
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 = []
rb_show_type = urwid.RadioButton(rb_grp, "Show Type",
iinfo.display_type == "type")
rb_show_repr = urwid.RadioButton(rb_grp, "Show repr()",
iinfo.display_type == "repr")
rb_show_str = urwid.RadioButton(rb_grp, "Show str()",
iinfo.display_type == "str")
rb_show_custom = urwid.RadioButton(rb_grp, "Show custom (set in prefs)",
iinfo.display_type == CONFIG["custom_stringifier"])
wrap_checkbox = urwid.CheckBox("Line Wrap", iinfo.wrap)
expanded_checkbox = urwid.CheckBox("Expanded", iinfo.show_detail)
highlighted_checkbox = urwid.CheckBox("Highlighted", iinfo.highlighted)
repeated_at_top_checkbox = urwid.CheckBox("Repeated at top", iinfo.repeated_at_top)
show_private_checkbox = urwid.CheckBox("Show private members",
iinfo.show_private_members)
lb = urwid.ListBox(
id_segment+rb_grp+[
urwid.Text(""),
wrap_checkbox,
expanded_checkbox,
highlighted_checkbox,
repeated_at_top_checkbox,
show_private_checkbox,
])
result = self.dialog(lb, buttons, title=title)
if result == True:
iinfo.show_detail = expanded_checkbox.get_state()
iinfo.wrap = wrap_checkbox.get_state()
iinfo.highlighted = highlighted_checkbox.get_state()
iinfo.repeated_at_top = repeated_at_top_checkbox.get_state()
iinfo.show_private_members = show_private_checkbox.get_state()
if rb_show_type.get_state():
iinfo.display_type = "type"
elif rb_show_repr.get_state():
iinfo.display_type = "repr"
elif rb_show_str.get_state():
iinfo.display_type = "str"
elif rb_show_custom.get_state():
iinfo.display_type = CONFIG["custom_stringifier"]
if var.watch_expr is not None:
var.watch_expr.expression = watch_edit.get_edit_text()
elif result == "del":
for i, watch_expr in enumerate(fvi.watches):
if watch_expr is var.watch_expr:
del fvi.watches[i]
self.update_var_view()
def insert_watch(w, size, key):
watch_edit = urwid.Edit([
("label", "Watch expression: ")
])
if self.dialog(
urwid.ListBox([
urwid.AttrMap(watch_edit, "value")
]),
[
("OK", True),
("Cancel", False),
], title="Add Watch Expression"):
from pudb.var_view import WatchExpression
we = WatchExpression(watch_edit.get_edit_text())
fvi = self.get_frame_var_info(read_only=False)
fvi.watches.append(we)
self.update_var_view()
self.var_list.listen("\\", change_var_state)
self.var_list.listen("t", change_var_state)
self.var_list.listen("r", change_var_state)
self.var_list.listen("s", change_var_state)
self.var_list.listen("c", change_var_state)
self.var_list.listen("h", change_var_state)
self.var_list.listen("@", change_var_state)
self.var_list.listen("*", change_var_state)
self.var_list.listen("w", change_var_state)
self.var_list.listen("enter", edit_inspector_detail)
self.var_list.listen("n", insert_watch)
self.var_list.listen("insert", insert_watch)
self.var_list.listen("[", partial(change_rhs_box, 'variables', 0, -1))
self.var_list.listen("]", partial(change_rhs_box, 'variables', 0, 1))
# }}}
# {{{ stack listeners
def examine_frame(w, size, key):
_, pos = self.stack_list._w.get_focus()
self.debugger.set_frame_index(self.translate_ui_stack_index(pos))
self.stack_list.listen("enter", examine_frame)
def move_stack_top(w, size, key):
self.debugger.set_frame_index(len(self.debugger.stack)-1)
def move_stack_up(w, size, key):
self.debugger.move_up_frame()
def move_stack_down(w, size, key):
self.debugger.move_down_frame()
self.stack_list.listen("H", move_stack_top)
self.stack_list.listen("u", move_stack_up)
self.stack_list.listen("d", move_stack_down)
self.stack_list.listen("[", partial(change_rhs_box, 'stack', 1, -1))
self.stack_list.listen("]", partial(change_rhs_box, 'stack', 1, 1))
# }}}
# {{{ breakpoint listeners
def save_breakpoints(w, size, key):
self.debugger.save_breakpoints()
def delete_breakpoint(w, size, key):
bp_list = self._get_bp_list()
if bp_list:
_, pos = self.bp_list._w.get_focus()
bp = bp_list[pos]
if self.shown_file == bp.file:
self.source[bp.line-1].set_breakpoint(False)
err = self.debugger.clear_break(bp.file, bp.line)
if err:
self.message("Error clearing breakpoint:\n"+ err)
else:
self.update_breakpoints()
def examine_breakpoint(w, size, key):
bp_entry, pos = self.bp_list._w.get_focus()
if bp_entry is None:
return
bp = self._get_bp_list()[pos]
if bp.cond is None:
cond = ""
else:
cond = str(bp.cond)
enabled_checkbox = urwid.CheckBox(
"Enabled", bp.enabled)
cond_edit = urwid.Edit([
("label", "Condition: ")
], cond)
ign_count_edit = urwid.IntEdit([
("label", "Ignore the next N times: ")
], bp.ignore)
lb = urwid.ListBox([
labelled_value("File: ", bp.file),
labelled_value("Line: ", bp.line),
labelled_value("Hits: ", bp.hits),
urwid.Text(""),
enabled_checkbox,
urwid.AttrMap(cond_edit, "value", "value"),
urwid.AttrMap(ign_count_edit, "value", "value"),
])
result = self.dialog(lb, [
("OK", True),
("Cancel", False),
None,
("Delete", "del"),
("Location", "loc"),
], title="Edit Breakpoint")
if result == True:
bp.enabled = enabled_checkbox.get_state()
bp.ignore = int(ign_count_edit.value())
cond = cond_edit.get_edit_text()
if cond:
bp.cond = cond
else:
bp.cond = None
elif result == "loc":
self.show_line(bp.line, bp.file)
self.columns.set_focus(0)
elif result == "del":
if self.shown_file == bp.file:
self.source[bp.line-1].set_breakpoint(False)
err = self.debugger.clear_break(bp.file, bp.line)
if err:
self.message("Error clearing breakpoint:\n"+ err)
else:
self.update_breakpoints()
self.bp_list.listen("enter", examine_breakpoint)
self.bp_list.listen("d", delete_breakpoint)
self.bp_list.listen("s", save_breakpoints)
self.bp_list.listen("[", partial(change_rhs_box, 'breakpoints', 2, -1))
self.bp_list.listen("]", partial(change_rhs_box, 'breakpoints', 2, 1))
# }}}
# {{{ source listeners
def end():
self.debugger.save_breakpoints()
self.quit_event_loop = True
def next(w, size, key):
if self.debugger.post_mortem:
self.message("Post-mortem mode: Can't modify state.")
else:
self.debugger.set_next(self.debugger.curframe)
end()
def step(w, size, key):
if self.debugger.post_mortem:
self.message("Post-mortem mode: Can't modify state.")
else:
self.debugger.set_step()
end()
def finish(w, size, key):
if self.debugger.post_mortem:
self.message("Post-mortem mode: Can't modify state.")
else:
self.debugger.set_return(self.debugger.curframe)
end()
def cont(w, size, key):
if self.debugger.post_mortem:
self.message("Post-mortem mode: Can't modify state.")
else:
self.debugger.set_continue()
end()
def run_to_cursor(w, size, key):
if self.debugger.post_mortem:
self.message("Post-mortem mode: Can't modify state.")
else:
sline, pos = self.source.get_focus()
lineno = pos+1
from pudb.lowlevel import get_breakpoint_invalid_reason
invalid_reason = get_breakpoint_invalid_reason(
self.shown_file, lineno)
if invalid_reason is not None:
self.message(
"Cannot run to the line you indicated, "
"for the following reason:\n\n"
+ invalid_reason)
else:
err = self.debugger.set_break(self.shown_file, pos+1, temporary=True)
if err:
self.message("Error dealing with breakpoint:\n"+ err)
self.debugger.set_continue()
end()
def move_home(w, size, key):
self.source.set_focus(0)
def move_end(w, size, key):
self.source.set_focus(len(self.source)-1)
def go_to_line(w, size, key):
_, line = self.source.get_focus()
lineno_edit = urwid.IntEdit([
("label", "Line number: ")
], line+1)
if self.dialog(
urwid.ListBox([
labelled_value("File :", self.shown_file),
urwid.AttrMap(lineno_edit, "value")
]),
[
("OK", True),
("Cancel", False),
], title="Go to Line Number"):
lineno = min(max(0, int(lineno_edit.value())-1), len(self.source)-1)
self.source.set_focus(lineno)
def move_down(w, size, key):
w.keypress(size, "down")
def move_up(w, size, key):
w.keypress(size, "up")
def page_down(w, size, key):
w.keypress(size, "page down")
def page_up(w, size, key):
w.keypress(size, "page up")
def scroll_left(w, size, key):
self.source_hscroll_start = max(
0,
self.source_hscroll_start - 4)
for sl in self.source:
sl._invalidate()
def scroll_right(w, size, key):
self.source_hscroll_start += 4
for sl in self.source:
sl._invalidate()
def search(w, size, key):
self.search_controller.open_search_ui()
def search_next(w, size, key):
self.search_controller.perform_search(dir=1, update_search_start=True)
def search_previous(w, size, key):
self.search_controller.perform_search(dir=-1, update_search_start=True)
def toggle_breakpoint(w, size, key):
if self.shown_file:
sline, pos = self.source.get_focus()
lineno = pos+1
existing_breaks = self.debugger.get_breaks(
self.shown_file, lineno)
if existing_breaks:
err = self.debugger.clear_break(self.shown_file, lineno)
sline.set_breakpoint(False)
else:
from pudb.lowlevel import get_breakpoint_invalid_reason
invalid_reason = get_breakpoint_invalid_reason(
self.shown_file, pos+1)
if invalid_reason is not None:
do_set = not self.dialog(urwid.ListBox([
urwid.Text("The breakpoint you just set may be "
"invalid, for the following reason:\n\n"
+ invalid_reason),
]), [
("Cancel", True),
("Set Anyway", False),
], title="Possibly Invalid Breakpoint",
focus_buttons=True)
else:
do_set = True
if do_set:
err = self.debugger.set_break(self.shown_file, pos+1)
sline.set_breakpoint(True)
else:
err = None
if err:
self.message("Error dealing with breakpoint:\n"+ err)
self.update_breakpoints()
else:
raise RuntimeError("no valid current file")
def pick_module(w, size, key):
from os.path import splitext
import sys
def mod_exists(mod):
if not hasattr(mod, "__file__"):
return False
filename = mod.__file__
base, ext = splitext(filename)
ext = ext.lower()
from os.path import exists
if ext == ".pyc":
return exists(base+".py")
else:
return ext == ".py"
new_mod_text = SelectableText("-- update me --")
new_mod_entry = urwid.AttrMap(new_mod_text,
None, "focused selectable")
def build_filtered_mod_list(filt_string=""):
modules = sorted(name
for name, mod in sys.modules.items()
if mod_exists(mod))
result = [urwid.AttrMap(SelectableText(mod),
None, "focused selectable")
for mod in modules if filt_string in mod]
new_mod_text.set_text("<<< IMPORT MODULE '%s' >>>" % filt_string)
result.append(new_mod_entry)
return result
def show_mod(mod):
filename = self.debugger.canonic(mod.__file__)
base, ext = splitext(filename)
if ext == ".pyc":
ext = ".py"
filename = base+".py"
self.set_current_file(filename)
self.source_list.set_focus(0)
class FilterEdit(urwid.Edit):
def keypress(self, size, key):
result = urwid.Edit.keypress(self, size, key)
if result is None:
mod_list[:] = build_filtered_mod_list(
self.get_edit_text())
return result
filt_edit = FilterEdit([("label", "Filter: ")],
self.last_module_filter)
mod_list = urwid.SimpleListWalker(
build_filtered_mod_list(filt_edit.get_edit_text()))
lb = urwid.ListBox(mod_list)
w = urwid.Pile([
("flow", urwid.AttrMap(filt_edit, "value")),
("fixed", 1, urwid.SolidFill()),
urwid.AttrMap(lb, "selectable")])
while True:
result = self.dialog(w, [
("OK", True),
("Cancel", False),
("Reload", "reload"),
], title="Pick Module")
self.last_module_filter = filt_edit.get_edit_text()
if result == True:
widget, pos = lb.get_focus()
if widget is new_mod_entry:
new_mod_name = filt_edit.get_edit_text()
try:
__import__(str(new_mod_name))
except:
from pudb.lowlevel import format_exception
self.message("Could not import module '%s':\n\n%s" % (
new_mod_name, "".join(format_exception(sys.exc_info()))),
title="Import Error")
else:
show_mod(sys.modules[str(new_mod_name)])
break
else:
show_mod(sys.modules[widget.base_widget.get_text()[0]])
break
elif result == False:
break
elif result == "reload":
widget, pos = lb.get_focus()
if widget is not new_mod_entry:
mod_name = widget.base_widget.get_text()[0]
mod = sys.modules[mod_name]
reload(mod)
self.message("'%s' was successfully reloaded." % mod_name)
from linecache import clearcache
clearcache()
self.set_current_file(self.shown_file, force_update=True)
_, pos = self.stack_list._w.get_focus()
self.debugger.set_frame_index(self.translate_ui_stack_index(pos))
self.source_sigwrap.listen("n", next)
self.source_sigwrap.listen("s", step)
self.source_sigwrap.listen("f", finish)
self.source_sigwrap.listen("r", finish)
self.source_sigwrap.listen("c", cont)
self.source_sigwrap.listen("t", run_to_cursor)
self.source_sigwrap.listen("j", move_down)
self.source_sigwrap.listen("k", move_up)
self.source_sigwrap.listen("ctrl d", page_down)
self.source_sigwrap.listen("ctrl u", page_up)