Home | History | Annotate | Download | only in idlelib
      1 import bdb
      2 import os
      3 
      4 from tkinter import *
      5 from tkinter.ttk import Scrollbar
      6 
      7 from idlelib import macosx
      8 from idlelib.scrolledlist import ScrolledList
      9 from idlelib.windows import ListedToplevel
     10 
     11 
     12 class Idb(bdb.Bdb):
     13 
     14     def __init__(self, gui):
     15         self.gui = gui
     16         bdb.Bdb.__init__(self)
     17 
     18     def user_line(self, frame):
     19         if self.in_rpc_code(frame):
     20             self.set_step()
     21             return
     22         message = self.__frame2message(frame)
     23         try:
     24             self.gui.interaction(message, frame)
     25         except TclError:  # When closing debugger window with [x] in 3.x
     26             pass
     27 
     28     def user_exception(self, frame, info):
     29         if self.in_rpc_code(frame):
     30             self.set_step()
     31             return
     32         message = self.__frame2message(frame)
     33         self.gui.interaction(message, frame, info)
     34 
     35     def in_rpc_code(self, frame):
     36         if frame.f_code.co_filename.count('rpc.py'):
     37             return True
     38         else:
     39             prev_frame = frame.f_back
     40             prev_name = prev_frame.f_code.co_filename
     41             if 'idlelib' in prev_name and 'debugger' in prev_name:
     42                 # catch both idlelib/debugger.py and idlelib/debugger_r.py
     43                 # on both posix and windows
     44                 return False
     45             return self.in_rpc_code(prev_frame)
     46 
     47     def __frame2message(self, frame):
     48         code = frame.f_code
     49         filename = code.co_filename
     50         lineno = frame.f_lineno
     51         basename = os.path.basename(filename)
     52         message = "%s:%s" % (basename, lineno)
     53         if code.co_name != "?":
     54             message = "%s: %s()" % (message, code.co_name)
     55         return message
     56 
     57 
     58 class Debugger:
     59 
     60     vstack = vsource = vlocals = vglobals = None
     61 
     62     def __init__(self, pyshell, idb=None):
     63         if idb is None:
     64             idb = Idb(self)
     65         self.pyshell = pyshell
     66         self.idb = idb
     67         self.frame = None
     68         self.make_gui()
     69         self.interacting = 0
     70         self.nesting_level = 0
     71 
     72     def run(self, *args):
     73         # Deal with the scenario where we've already got a program running
     74         # in the debugger and we want to start another. If that is the case,
     75         # our second 'run' was invoked from an event dispatched not from
     76         # the main event loop, but from the nested event loop in 'interaction'
     77         # below. So our stack looks something like this:
     78         #       outer main event loop
     79         #         run()
     80         #           <running program with traces>
     81         #             callback to debugger's interaction()
     82         #               nested event loop
     83         #                 run() for second command
     84         #
     85         # This kind of nesting of event loops causes all kinds of problems
     86         # (see e.g. issue #24455) especially when dealing with running as a
     87         # subprocess, where there's all kinds of extra stuff happening in
     88         # there - insert a traceback.print_stack() to check it out.
     89         #
     90         # By this point, we've already called restart_subprocess() in
     91         # ScriptBinding. However, we also need to unwind the stack back to
     92         # that outer event loop.  To accomplish this, we:
     93         #   - return immediately from the nested run()
     94         #   - abort_loop ensures the nested event loop will terminate
     95         #   - the debugger's interaction routine completes normally
     96         #   - the restart_subprocess() will have taken care of stopping
     97         #     the running program, which will also let the outer run complete
     98         #
     99         # That leaves us back at the outer main event loop, at which point our
    100         # after event can fire, and we'll come back to this routine with a
    101         # clean stack.
    102         if self.nesting_level > 0:
    103             self.abort_loop()
    104             self.root.after(100, lambda: self.run(*args))
    105             return
    106         try:
    107             self.interacting = 1
    108             return self.idb.run(*args)
    109         finally:
    110             self.interacting = 0
    111 
    112     def close(self, event=None):
    113         try:
    114             self.quit()
    115         except Exception:
    116             pass
    117         if self.interacting:
    118             self.top.bell()
    119             return
    120         if self.stackviewer:
    121             self.stackviewer.close(); self.stackviewer = None
    122         # Clean up pyshell if user clicked debugger control close widget.
    123         # (Causes a harmless extra cycle through close_debugger() if user
    124         # toggled debugger from pyshell Debug menu)
    125         self.pyshell.close_debugger()
    126         # Now close the debugger control window....
    127         self.top.destroy()
    128 
    129     def make_gui(self):
    130         pyshell = self.pyshell
    131         self.flist = pyshell.flist
    132         self.root = root = pyshell.root
    133         self.top = top = ListedToplevel(root)
    134         self.top.wm_title("Debug Control")
    135         self.top.wm_iconname("Debug")
    136         top.wm_protocol("WM_DELETE_WINDOW", self.close)
    137         self.top.bind("<Escape>", self.close)
    138         #
    139         self.bframe = bframe = Frame(top)
    140         self.bframe.pack(anchor="w")
    141         self.buttons = bl = []
    142         #
    143         self.bcont = b = Button(bframe, text="Go", command=self.cont)
    144         bl.append(b)
    145         self.bstep = b = Button(bframe, text="Step", command=self.step)
    146         bl.append(b)
    147         self.bnext = b = Button(bframe, text="Over", command=self.next)
    148         bl.append(b)
    149         self.bret = b = Button(bframe, text="Out", command=self.ret)
    150         bl.append(b)
    151         self.bret = b = Button(bframe, text="Quit", command=self.quit)
    152         bl.append(b)
    153         #
    154         for b in bl:
    155             b.configure(state="disabled")
    156             b.pack(side="left")
    157         #
    158         self.cframe = cframe = Frame(bframe)
    159         self.cframe.pack(side="left")
    160         #
    161         if not self.vstack:
    162             self.__class__.vstack = BooleanVar(top)
    163             self.vstack.set(1)
    164         self.bstack = Checkbutton(cframe,
    165             text="Stack", command=self.show_stack, variable=self.vstack)
    166         self.bstack.grid(row=0, column=0)
    167         if not self.vsource:
    168             self.__class__.vsource = BooleanVar(top)
    169         self.bsource = Checkbutton(cframe,
    170             text="Source", command=self.show_source, variable=self.vsource)
    171         self.bsource.grid(row=0, column=1)
    172         if not self.vlocals:
    173             self.__class__.vlocals = BooleanVar(top)
    174             self.vlocals.set(1)
    175         self.blocals = Checkbutton(cframe,
    176             text="Locals", command=self.show_locals, variable=self.vlocals)
    177         self.blocals.grid(row=1, column=0)
    178         if not self.vglobals:
    179             self.__class__.vglobals = BooleanVar(top)
    180         self.bglobals = Checkbutton(cframe,
    181             text="Globals", command=self.show_globals, variable=self.vglobals)
    182         self.bglobals.grid(row=1, column=1)
    183         #
    184         self.status = Label(top, anchor="w")
    185         self.status.pack(anchor="w")
    186         self.error = Label(top, anchor="w")
    187         self.error.pack(anchor="w", fill="x")
    188         self.errorbg = self.error.cget("background")
    189         #
    190         self.fstack = Frame(top, height=1)
    191         self.fstack.pack(expand=1, fill="both")
    192         self.flocals = Frame(top)
    193         self.flocals.pack(expand=1, fill="both")
    194         self.fglobals = Frame(top, height=1)
    195         self.fglobals.pack(expand=1, fill="both")
    196         #
    197         if self.vstack.get():
    198             self.show_stack()
    199         if self.vlocals.get():
    200             self.show_locals()
    201         if self.vglobals.get():
    202             self.show_globals()
    203 
    204     def interaction(self, message, frame, info=None):
    205         self.frame = frame
    206         self.status.configure(text=message)
    207         #
    208         if info:
    209             type, value, tb = info
    210             try:
    211                 m1 = type.__name__
    212             except AttributeError:
    213                 m1 = "%s" % str(type)
    214             if value is not None:
    215                 try:
    216                     m1 = "%s: %s" % (m1, str(value))
    217                 except:
    218                     pass
    219             bg = "yellow"
    220         else:
    221             m1 = ""
    222             tb = None
    223             bg = self.errorbg
    224         self.error.configure(text=m1, background=bg)
    225         #
    226         sv = self.stackviewer
    227         if sv:
    228             stack, i = self.idb.get_stack(self.frame, tb)
    229             sv.load_stack(stack, i)
    230         #
    231         self.show_variables(1)
    232         #
    233         if self.vsource.get():
    234             self.sync_source_line()
    235         #
    236         for b in self.buttons:
    237             b.configure(state="normal")
    238         #
    239         self.top.wakeup()
    240         # Nested main loop: Tkinter's main loop is not reentrant, so use
    241         # Tcl's vwait facility, which reenters the event loop until an
    242         # event handler sets the variable we're waiting on
    243         self.nesting_level += 1
    244         self.root.tk.call('vwait', '::idledebugwait')
    245         self.nesting_level -= 1
    246         #
    247         for b in self.buttons:
    248             b.configure(state="disabled")
    249         self.status.configure(text="")
    250         self.error.configure(text="", background=self.errorbg)
    251         self.frame = None
    252 
    253     def sync_source_line(self):
    254         frame = self.frame
    255         if not frame:
    256             return
    257         filename, lineno = self.__frame2fileline(frame)
    258         if filename[:1] + filename[-1:] != "<>" and os.path.exists(filename):
    259             self.flist.gotofileline(filename, lineno)
    260 
    261     def __frame2fileline(self, frame):
    262         code = frame.f_code
    263         filename = code.co_filename
    264         lineno = frame.f_lineno
    265         return filename, lineno
    266 
    267     def cont(self):
    268         self.idb.set_continue()
    269         self.abort_loop()
    270 
    271     def step(self):
    272         self.idb.set_step()
    273         self.abort_loop()
    274 
    275     def next(self):
    276         self.idb.set_next(self.frame)
    277         self.abort_loop()
    278 
    279     def ret(self):
    280         self.idb.set_return(self.frame)
    281         self.abort_loop()
    282 
    283     def quit(self):
    284         self.idb.set_quit()
    285         self.abort_loop()
    286 
    287     def abort_loop(self):
    288         self.root.tk.call('set', '::idledebugwait', '1')
    289 
    290     stackviewer = None
    291 
    292     def show_stack(self):
    293         if not self.stackviewer and self.vstack.get():
    294             self.stackviewer = sv = StackViewer(self.fstack, self.flist, self)
    295             if self.frame:
    296                 stack, i = self.idb.get_stack(self.frame, None)
    297                 sv.load_stack(stack, i)
    298         else:
    299             sv = self.stackviewer
    300             if sv and not self.vstack.get():
    301                 self.stackviewer = None
    302                 sv.close()
    303             self.fstack['height'] = 1
    304 
    305     def show_source(self):
    306         if self.vsource.get():
    307             self.sync_source_line()
    308 
    309     def show_frame(self, stackitem):
    310         self.frame = stackitem[0]  # lineno is stackitem[1]
    311         self.show_variables()
    312 
    313     localsviewer = None
    314     globalsviewer = None
    315 
    316     def show_locals(self):
    317         lv = self.localsviewer
    318         if self.vlocals.get():
    319             if not lv:
    320                 self.localsviewer = NamespaceViewer(self.flocals, "Locals")
    321         else:
    322             if lv:
    323                 self.localsviewer = None
    324                 lv.close()
    325                 self.flocals['height'] = 1
    326         self.show_variables()
    327 
    328     def show_globals(self):
    329         gv = self.globalsviewer
    330         if self.vglobals.get():
    331             if not gv:
    332                 self.globalsviewer = NamespaceViewer(self.fglobals, "Globals")
    333         else:
    334             if gv:
    335                 self.globalsviewer = None
    336                 gv.close()
    337                 self.fglobals['height'] = 1
    338         self.show_variables()
    339 
    340     def show_variables(self, force=0):
    341         lv = self.localsviewer
    342         gv = self.globalsviewer
    343         frame = self.frame
    344         if not frame:
    345             ldict = gdict = None
    346         else:
    347             ldict = frame.f_locals
    348             gdict = frame.f_globals
    349             if lv and gv and ldict is gdict:
    350                 ldict = None
    351         if lv:
    352             lv.load_dict(ldict, force, self.pyshell.interp.rpcclt)
    353         if gv:
    354             gv.load_dict(gdict, force, self.pyshell.interp.rpcclt)
    355 
    356     def set_breakpoint_here(self, filename, lineno):
    357         self.idb.set_break(filename, lineno)
    358 
    359     def clear_breakpoint_here(self, filename, lineno):
    360         self.idb.clear_break(filename, lineno)
    361 
    362     def clear_file_breaks(self, filename):
    363         self.idb.clear_all_file_breaks(filename)
    364 
    365     def load_breakpoints(self):
    366         "Load PyShellEditorWindow breakpoints into subprocess debugger"
    367         for editwin in self.pyshell.flist.inversedict:
    368             filename = editwin.io.filename
    369             try:
    370                 for lineno in editwin.breakpoints:
    371                     self.set_breakpoint_here(filename, lineno)
    372             except AttributeError:
    373                 continue
    374 
    375 class StackViewer(ScrolledList):
    376 
    377     def __init__(self, master, flist, gui):
    378         if macosx.isAquaTk():
    379             # At least on with the stock AquaTk version on OSX 10.4 you'll
    380             # get a shaking GUI that eventually kills IDLE if the width
    381             # argument is specified.
    382             ScrolledList.__init__(self, master)
    383         else:
    384             ScrolledList.__init__(self, master, width=80)
    385         self.flist = flist
    386         self.gui = gui
    387         self.stack = []
    388 
    389     def load_stack(self, stack, index=None):
    390         self.stack = stack
    391         self.clear()
    392         for i in range(len(stack)):
    393             frame, lineno = stack[i]
    394             try:
    395                 modname = frame.f_globals["__name__"]
    396             except:
    397                 modname = "?"
    398             code = frame.f_code
    399             filename = code.co_filename
    400             funcname = code.co_name
    401             import linecache
    402             sourceline = linecache.getline(filename, lineno)
    403             sourceline = sourceline.strip()
    404             if funcname in ("?", "", None):
    405                 item = "%s, line %d: %s" % (modname, lineno, sourceline)
    406             else:
    407                 item = "%s.%s(), line %d: %s" % (modname, funcname,
    408                                                  lineno, sourceline)
    409             if i == index:
    410                 item = "> " + item
    411             self.append(item)
    412         if index is not None:
    413             self.select(index)
    414 
    415     def popup_event(self, event):
    416         "override base method"
    417         if self.stack:
    418             return ScrolledList.popup_event(self, event)
    419 
    420     def fill_menu(self):
    421         "override base method"
    422         menu = self.menu
    423         menu.add_command(label="Go to source line",
    424                          command=self.goto_source_line)
    425         menu.add_command(label="Show stack frame",
    426                          command=self.show_stack_frame)
    427 
    428     def on_select(self, index):
    429         "override base method"
    430         if 0 <= index < len(self.stack):
    431             self.gui.show_frame(self.stack[index])
    432 
    433     def on_double(self, index):
    434         "override base method"
    435         self.show_source(index)
    436 
    437     def goto_source_line(self):
    438         index = self.listbox.index("active")
    439         self.show_source(index)
    440 
    441     def show_stack_frame(self):
    442         index = self.listbox.index("active")
    443         if 0 <= index < len(self.stack):
    444             self.gui.show_frame(self.stack[index])
    445 
    446     def show_source(self, index):
    447         if not (0 <= index < len(self.stack)):
    448             return
    449         frame, lineno = self.stack[index]
    450         code = frame.f_code
    451         filename = code.co_filename
    452         if os.path.isfile(filename):
    453             edit = self.flist.open(filename)
    454             if edit:
    455                 edit.gotoline(lineno)
    456 
    457 
    458 class NamespaceViewer:
    459 
    460     def __init__(self, master, title, dict=None):
    461         width = 0
    462         height = 40
    463         if dict:
    464             height = 20*len(dict) # XXX 20 == observed height of Entry widget
    465         self.master = master
    466         self.title = title
    467         import reprlib
    468         self.repr = reprlib.Repr()
    469         self.repr.maxstring = 60
    470         self.repr.maxother = 60
    471         self.frame = frame = Frame(master)
    472         self.frame.pack(expand=1, fill="both")
    473         self.label = Label(frame, text=title, borderwidth=2, relief="groove")
    474         self.label.pack(fill="x")
    475         self.vbar = vbar = Scrollbar(frame, name="vbar")
    476         vbar.pack(side="right", fill="y")
    477         self.canvas = canvas = Canvas(frame,
    478                                       height=min(300, max(40, height)),
    479                                       scrollregion=(0, 0, width, height))
    480         canvas.pack(side="left", fill="both", expand=1)
    481         vbar["command"] = canvas.yview
    482         canvas["yscrollcommand"] = vbar.set
    483         self.subframe = subframe = Frame(canvas)
    484         self.sfid = canvas.create_window(0, 0, window=subframe, anchor="nw")
    485         self.load_dict(dict)
    486 
    487     dict = -1
    488 
    489     def load_dict(self, dict, force=0, rpc_client=None):
    490         if dict is self.dict and not force:
    491             return
    492         subframe = self.subframe
    493         frame = self.frame
    494         for c in list(subframe.children.values()):
    495             c.destroy()
    496         self.dict = None
    497         if not dict:
    498             l = Label(subframe, text="None")
    499             l.grid(row=0, column=0)
    500         else:
    501             #names = sorted(dict)
    502             ###
    503             # Because of (temporary) limitations on the dict_keys type (not yet
    504             # public or pickleable), have the subprocess to send a list of
    505             # keys, not a dict_keys object.  sorted() will take a dict_keys
    506             # (no subprocess) or a list.
    507             #
    508             # There is also an obscure bug in sorted(dict) where the
    509             # interpreter gets into a loop requesting non-existing dict[0],
    510             # dict[1], dict[2], etc from the debugger_r.DictProxy.
    511             ###
    512             keys_list = dict.keys()
    513             names = sorted(keys_list)
    514             ###
    515             row = 0
    516             for name in names:
    517                 value = dict[name]
    518                 svalue = self.repr.repr(value) # repr(value)
    519                 # Strip extra quotes caused by calling repr on the (already)
    520                 # repr'd value sent across the RPC interface:
    521                 if rpc_client:
    522                     svalue = svalue[1:-1]
    523                 l = Label(subframe, text=name)
    524                 l.grid(row=row, column=0, sticky="nw")
    525                 l = Entry(subframe, width=0, borderwidth=0)
    526                 l.insert(0, svalue)
    527                 l.grid(row=row, column=1, sticky="nw")
    528                 row = row+1
    529         self.dict = dict
    530         # XXX Could we use a <Configure> callback for the following?
    531         subframe.update_idletasks() # Alas!
    532         width = subframe.winfo_reqwidth()
    533         height = subframe.winfo_reqheight()
    534         canvas = self.canvas
    535         self.canvas["scrollregion"] = (0, 0, width, height)
    536         if height > 300:
    537             canvas["height"] = 300
    538             frame.pack(expand=1)
    539         else:
    540             canvas["height"] = height
    541             frame.pack(expand=0)
    542 
    543     def close(self):
    544         self.frame.destroy()
    545