desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Override to indicate that a test has just errored'
def notifyTestErrored(self, test, err):
pass
'Override to indicate that test was skipped'
def notifyTestSkipped(self, test, reason):
pass
'Override to indicate that test has just failed expectedly'
def notifyTestFailedExpectedly(self, test, err):
pass
'Override to indicate that a test is about to run'
def notifyTestStarted(self, test):
pass
'Override to indicate that a test has finished (it may already have failed or errored)'
def notifyTestFinished(self, test):
pass
'Set up the GUI inside the given root window. The test name entry field will be pre-filled with the given initialTestName.'
def initGUI(self, root, initialTestName):
self.root = root self.statusVar = tk.StringVar() self.statusVar.set('Idle') self.runCountVar = tk.IntVar() self.failCountVar = tk.IntVar() self.errorCountVar = tk.IntVar() self.skipCountVar = tk.IntVar() self.expectFailCountVar = tk.IntVar() self.remainingCountVar = tk.IntVar() s...
'Creates and packs the various widgets. Why is it that GUI code always ends up looking a mess, despite all the best intentions to keep it tidy? Answers on a postcard, please.'
def createWidgets(self):
statusFrame = tk.Frame(self.top, relief=tk.SUNKEN, borderwidth=2) statusFrame.pack(anchor=tk.SW, fill=tk.X, side=tk.BOTTOM) tk.Label(statusFrame, width=1, textvariable=self.statusVar).pack(side=tk.TOP, fill=tk.X) leftFrame = tk.Frame(self.top, borderwidth=3) leftFrame.pack(fill=tk.BOTH, side=tk.LEFT...
'Create a new directory in the Directory table. There is a current component at each point in time for the directory, which is either explicitly created through start_component, or implicitly when files are added for the first time. Files are added into the current component, and into the cab file. To create a director...
def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None):
index = 1 _logical = make_id(_logical) logical = _logical while (logical in _directories): logical = ('%s%d' % (_logical, index)) index += 1 _directories.add(logical) self.db = db self.cab = cab self.basedir = basedir self.physical = physical self.logical = logica...
'Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory\'s default flags are used. If no keyfile is given, the KeyPath is left null i...
def start_component(self, component=None, feature=None, flags=None, keyfile=None, uuid=None):
if (flags is None): flags = self.componentflags if (uuid is None): uuid = gen_uuid() else: uuid = uuid.upper() if (component is None): component = self.logical self.component = component if Win64: flags |= 256 if keyfile: keyid = self.cab.gen_i...
'Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specifi...
def add_file(self, file, src=None, version=None, language=None):
if (not self.component): self.start_component(self.logical, current_feature) if (not src): src = file file = os.path.basename(file) absolute = os.path.join(self.absolute, src) if absolute.startswith(self.absolute): relative = absolute[(len(self.absolute) + 1):] if...
'Add a list of files to the current component as specified in the glob pattern. Individual files can be excluded in the exclude list.'
def glob(self, pattern, exclude=None):
files = glob.glob1(self.absolute, pattern) for f in files: if (exclude and (f in exclude)): continue self.add_file(f) return files
'Remove .pyc/.pyo files from __pycache__ on uninstall'
def remove_pyc(self):
directory = (self.logical + '_pycache') add_data(self.db, 'Directory', [(directory, self.logical, '__PYCA~1|__pycache__')]) flags = (256 if Win64 else 0) add_data(self.db, 'Component', [(directory, gen_uuid(), directory, flags, None, None)]) add_data(self.db, 'FeatureComponents', [(current_feature.i...
'Add a RemoveFile entry'
def removefile(self, key, pattern):
add_data(self.db, 'RemoveFile', [((self.component + key), self.component, pattern, self.logical, 2)])
'Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)'
def __init__(self, *args, **kw):
Dialog.__init__(self, *args) ruler = (self.h - 36) bmwidth = ((152 * ruler) / 328) if kw.get('bitmap', True): self.bitmap('Bitmap', 0, 0, bmwidth, ruler, 'PythonWin') self.line('BottomLine', 0, ruler, self.w, 0)
'Set the title text of the dialog at the top.'
def title(self, title):
self.text('Title', 135, 10, 220, 60, 196611, ('{\\VerdanaBold10}%s' % title))
'Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def back(self, title, next, name='Back', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 180, (self.h - 27), 56, 17, flags, title, next)
'Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def cancel(self, title, next, name='Cancel', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 304, (self.h - 27), 56, 17, flags, title, next)
'Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def next(self, title, next, name='Next', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 236, (self.h - 27), 56, 17, flags, title, next)
'Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated'
def xbutton(self, name, title, next, xpos):
return self.pushbutton(name, int(((self.w * xpos) - 28)), (self.h - 27), 56, 17, 3, title, next)
'Get the gdb.Value for the given field within the PyObject, coping with some python 2 versus python 3 differences. Various libpython types are defined using the "PyObject_HEAD" and "PyObject_VAR_HEAD" macros. In Python 2, this these are defined so that "ob_type" and (for a var object) "ob_size" are fields of the type i...
def field(self, name):
if self.is_null(): raise NullPyObjectPtr(self) if (name == 'ob_type'): pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type()) return pyo_ptr.dereference()[name] if (name == 'ob_size'): pyo_ptr = self._gdbval.cast(PyVarObjectPtr.get_gdb_type()) return pyo_ptr.derefere...
'Get a PyObjectPtr for the given PyObject* field within this PyObject, coping with some python 2 versus python 3 differences.'
def pyop_field(self, name):
return PyObjectPtr.from_pyobject_ptr(self.field(name))
'Extract the PyObject* field named "name", and write its representation to file-like object "out"'
def write_field_repr(self, name, out, visited):
field_obj = self.pyop_field(name) field_obj.write_repr(out, visited)
'Get a repr-like string for the data, but truncate it at "maxlen" bytes (ending the object graph traversal as soon as you do)'
def get_truncated_repr(self, maxlen):
out = TruncatedStringIO(maxlen) try: self.write_repr(out, set()) except StringTruncated: return (out.getvalue() + '...(truncated)') return out.getvalue()
'Is the value of the underlying PyObject* visible to the debugger? This can vary with the precise version of the compiler used to build Python, and the precise version of gdb. See e.g. https://bugzilla.redhat.com/show_bug.cgi?id=556975 with PyEval_EvalFrameEx\'s "f"'
def is_optimized_out(self):
return self._gdbval.is_optimized_out
'Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt. Derived classes will override this. For example, a PyIntObject* with ob_ival 42 in the inferior process should result in an int(42) in this process. visited: a ...
def proxyval(self, visited):
class FakeRepr(object, ): "\n Class representing a non-descript PyObject* value in the inferior\n process for when we don't have a custom scraper, intended to ...
'Write a string representation of the value scraped from the inferior process to "out", a file-like object.'
def write_repr(self, out, visited):
return out.write(repr(self.proxyval(visited)))
'Given a PyTypeObjectPtr instance wrapping a gdb.Value that\'s a (PyTypeObject*), determine the corresponding subclass of PyObjectPtr to use Ideally, we would look up the symbols for the global types, but that isn\'t working yet: (gdb) python print gdb.lookup_symbol(\'PyList_Type\')[0].value Traceback (most recent call...
@classmethod def subclass_from_type(cls, t):
try: tp_name = t.field('tp_name').string() tp_flags = int(t.field('tp_flags')) except RuntimeError: return cls name_map = {'bool': PyBoolObjectPtr, 'classobj': PyClassObjectPtr, 'NoneType': PyNoneStructPtr, 'frame': PyFrameObjectPtr, 'set': PySetObjectPtr, 'frozenset': PySetObjectPtr...
'Try to locate the appropriate derived class dynamically, and cast the pointer accordingly.'
@classmethod def from_pyobject_ptr(cls, gdbval):
try: p = PyObjectPtr(gdbval) cls = cls.subclass_from_type(p.type()) return cls(gdbval, cast_to=cls.get_gdb_type()) except RuntimeError: pass return cls(gdbval)
'Get the PyDictObject ptr representing the attribute dictionary (or None if there\'s a problem)'
def get_attr_dict(self):
try: typeobj = self.type() dictoffset = int_from_int(typeobj.field('tp_dictoffset')) if (dictoffset != 0): if (dictoffset < 0): type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer() tsize = int_from_int(self._gdbval.cast(type_PyVarObject_...
'Support for classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors'
def proxyval(self, visited):
if (self.as_address() in visited): return ProxyAlreadyVisited('<...>') visited.add(self.as_address()) pyop_attr_dict = self.get_attr_dict() if pyop_attr_dict: attr_dict = pyop_attr_dict.proxyval(visited) else: attr_dict = {} tp_name = self.safe_tp_name() return Instan...
'Get the line number for a given bytecode offset Analogous to PyCode_Addr2Line; translated from pseudocode in Objects/lnotab_notes.txt'
def addr2line(self, addrq):
co_lnotab = self.pyop_field('co_lnotab').proxyval(set()) lineno = int_from_int(self.field('co_firstlineno')) addr = 0 for (addr_incr, line_incr) in zip(co_lnotab[::2], co_lnotab[1::2]): addr += ord(addr_incr) if (addr > addrq): return lineno lineno += ord(line_incr) ...
'Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs, analogous to dict.iteritems()'
def iteritems(self):
keys = self.field('ma_keys') values = self.field('ma_values') for i in safe_range(keys['dk_size']): ep = (keys['dk_entries'].address + i) if long(values): pyop_value = PyObjectPtr.from_pyobject_ptr(values[i]) else: pyop_value = PyObjectPtr.from_pyobject_ptr(ep...
'Python\'s Include/longobjrep.h has this declaration: struct _longobject { PyObject_VAR_HEAD digit ob_digit[1]; with this description: The absolute value of a number is equal to SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i) Negative numbers are represented with ob_size < 0; zero is represented by ob_si...
def proxyval(self, visited):
ob_size = long(self.field('ob_size')) if (ob_size == 0): return 0 ob_digit = self.field('ob_digit') if (gdb.lookup_type('digit').sizeof == 2): SHIFT = 15 else: SHIFT = 30 digits = [(long(ob_digit[i]) * (2 ** (SHIFT * i))) for i in safe_range(abs(ob_size))] result = su...
'Yield a sequence of (name,value) pairs of PyObjectPtr instances, for the local variables of this frame'
def iter_locals(self):
if self.is_optimized_out(): return f_localsplus = self.field('f_localsplus') for i in safe_range(self.co_nlocals): pyop_value = PyObjectPtr.from_pyobject_ptr(f_localsplus[i]) if (not pyop_value.is_null()): pyop_name = PyObjectPtr.from_pyobject_ptr(self.co_varnames[i]) ...
'Yield a sequence of (name,value) pairs of PyObjectPtr instances, for the global variables of this frame'
def iter_globals(self):
if self.is_optimized_out(): return () pyop_globals = self.pyop_field('f_globals') return pyop_globals.iteritems()
'Yield a sequence of (name,value) pairs of PyObjectPtr instances, for the builtin variables'
def iter_builtins(self):
if self.is_optimized_out(): return () pyop_builtins = self.pyop_field('f_builtins') return pyop_builtins.iteritems()
'Look for the named local variable, returning a (PyObjectPtr, scope) pair where scope is a string \'local\', \'global\', \'builtin\' If not found, return (None, None)'
def get_var_by_name(self, name):
for (pyop_name, pyop_value) in self.iter_locals(): if (name == pyop_name.proxyval(set())): return (pyop_value, 'local') for (pyop_name, pyop_value) in self.iter_globals(): if (name == pyop_name.proxyval(set())): return (pyop_value, 'global') for (pyop_name, pyop_value...
'Get the path of the current Python source file, as a string'
def filename(self):
if self.is_optimized_out(): return '(frame information optimized out)' return self.co_filename.proxyval(set())
'Get current line number as an integer (1-based) Translated from PyFrame_GetLineNumber and PyCode_Addr2Line See Objects/lnotab_notes.txt'
def current_line_num(self):
if self.is_optimized_out(): return None f_trace = self.field('f_trace') if (long(f_trace) != 0): return self.f_lineno else: return self.co.addr2line(self.f_lasti)
'Get the text of the current source line as a string, with a trailing newline character'
def current_line(self):
if self.is_optimized_out(): return '(frame information optimized out)' filename = self.filename() try: f = open(os_fsencode(filename), 'r') except IOError: return None with f: all_lines = f.readlines() return all_lines[(self.current_line_num() - 1)]
'If supported, select this frame and return True; return False if unsupported Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12 onwards, but absent on Ubuntu buildbot'
def select(self):
if (not hasattr(self._gdbframe, 'select')): print('Unable to select frame: this build of gdb does not expose a gdb.Frame.select method') return False self._gdbframe.select() return True
'Calculate index of frame, starting at 0 for the newest frame within this thread'
def get_index(self):
index = 0 iter_frame = self while iter_frame.newer(): index += 1 iter_frame = iter_frame.newer() return index
'Is this a PyEval_EvalFrameEx frame, or some other important frame? (see is_other_python_frame for what "important" means in this context)'
def is_python_frame(self):
if self.is_evalframeex(): return True if self.is_other_python_frame(): return True return False
'Is this a PyEval_EvalFrameEx frame?'
def is_evalframeex(self):
if (self._gdbframe.name() == 'PyEval_EvalFrameEx'): '\n I believe we also need to filter on the inline\n struct frame_id.inline_depth, only regarding frames with\n ...
'Is this frame worth displaying in python backtraces? Examples: - waiting on the GIL - garbage-collecting - within a CFunction If it is, return a descriptive string For other frames, return False'
def is_other_python_frame(self):
if self.is_waiting_for_gil(): return 'Waiting for the GIL' elif self.is_gc_collect(): return 'Garbage-collecting' else: older = self.older() if (older and (older._gdbframe.name() == 'PyCFunction_Call')): try: func = older._gdbframe.read_va...
'Is this frame waiting on the GIL?'
def is_waiting_for_gil(self):
name = self._gdbframe.name() if name: return ('pthread_cond_timedwait' in name)
'Is this frame "collect" within the garbage-collector?'
def is_gc_collect(self):
return (self._gdbframe.name() == 'collect')
'Try to obtain the Frame for the python-related code in the selected frame, or None'
@classmethod def get_selected_python_frame(cls):
frame = cls.get_selected_frame() while frame: if frame.is_python_frame(): return frame frame = frame.older() return None
'Try to obtain the Frame for the python bytecode interpreter in the selected GDB frame, or None'
@classmethod def get_selected_bytecode_frame(cls):
frame = cls.get_selected_frame() while frame: if frame.is_evalframeex(): return frame frame = frame.older() return None
'Build the bundle.'
def build(self):
builddir = self.builddir if (builddir and (not os.path.exists(builddir))): os.mkdir(builddir) self.message(('Building %s' % repr(self.bundlepath)), 1) if os.path.exists(self.bundlepath): shutil.rmtree(self.bundlepath) if os.path.exists((self.bundlepath + '~')): shutil.rmtr...
'Hook for subclasses.'
def preProcess(self):
pass
'Hook for subclasses.'
def postProcess(self):
pass
'Go to the location of the first blank on the given line, returning the index of the last non-blank character.'
def _end_of_line(self, y):
last = self.maxx while True: if (curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP): last = min(self.maxx, (last + 1)) break elif (last == 0): break last = (last - 1) return last
'Process a single editing command.'
def do_command(self, ch):
(y, x) = self.win.getyx() self.lastcmd = ch if curses.ascii.isprint(ch): if ((y < self.maxy) or (x < self.maxx)): self._insert_printable_char(ch) elif (ch == curses.ascii.SOH): self.win.move(y, 0) elif (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY...
'Collect and return the contents of the window.'
def gather(self):
result = '' for y in range((self.maxy + 1)): self.win.move(y, 0) stop = self._end_of_line(y) if ((stop == 0) and self.stripspaces): continue for x in range((self.maxx + 1)): if (self.stripspaces and (x > stop)): break result = (...
'Edit in the widget window and collect the results.'
def edit(self, validate=None):
while 1: ch = self.win.getch() if validate: ch = validate(ch) if (not ch): continue if (not self.do_command(ch)): break self.win.refresh() return self.gather()
'Run the module after setting up the environment. First check the syntax. If OK, make sure the shell is active and then transfer the arguments, set the run environment\'s working directory to the directory of the module being executed and also add that directory to its sys.path if not already included.'
def _run_module_event(self, event):
filename = self.getfilename() if (not filename): return 'break' code = self.checksyntax(filename) if (not code): return 'break' if (not self.tabnanny(filename)): return 'break' interp = self.shell.interp if PyShell.use_subprocess: interp.restart_subprocess(wit...
'Get source filename. If not saved, offer to save (or create) file The debugger requires a source file. Make sure there is one, and that the current version of the source buffer has been saved. If the user declines to save or cancels the Save As dialog, return None. If the user has configured IDLE for Autosave, the ...
def getfilename(self):
filename = self.editwin.io.filename if (not self.editwin.get_saved()): autosave = idleConf.GetOption('main', 'General', 'autosave', type='bool') if (autosave and filename): self.editwin.io.save(None) else: confirm = self.ask_save_dialog() self.editwin....
'Load PyShellEditorWindow breakpoints into subprocess debugger'
def load_breakpoints(self):
for editwin in self.pyshell.flist.inversedict: filename = editwin.io.filename try: for lineno in editwin.breakpoints: self.set_breakpoint_here(filename, lineno) except AttributeError: continue
'override base method'
def popup_event(self, event):
if self.stack: return ScrolledList.popup_event(self, event)
'override base method'
def fill_menu(self):
menu = self.menu menu.add_command(label='Go to source line', command=self.goto_source_line) menu.add_command(label='Show stack frame', command=self.show_stack_frame)
'override base method'
def on_select(self, index):
if (0 <= index < len(self.stack)): self.gui.show_frame(self.stack[index])
'override base method'
def on_double(self, index):
self.show_source(index)
'Create a Unicode string.'
def _decode(self, two_lines, bytes):
chars = None if bytes.startswith(BOM_UTF8): try: chars = bytes[3:].decode('utf-8') except UnicodeDecodeError: return (None, False) else: self.fileencoding = 'BOM' return (chars, False) try: enc = coding_spec(two_lines) excep...
'Update recent file list on all editor windows'
def updaterecentfileslist(self, filename):
if self.editwin.flist: self.editwin.update_recent_files_list(filename)
'Replace the current word with the next expansion.'
def expand_word_event(self, event):
curinsert = self.text.index('insert') curline = self.text.get('insert linestart', 'insert lineend') if (not self.state): words = self.getwords() index = 0 else: (words, index, insert, line) = self.state if ((insert != curinsert) or (line != curline)): wo...
'Return a list of words that match the prefix before the cursor.'
def getwords(self):
word = self.getprevword() if (not word): return [] before = self.text.get('1.0', 'insert wordstart') wbefore = re.findall((('\\b' + word) + '\\w+\\b'), before) del before after = self.text.get('insert wordend', 'end') wafter = re.findall((('\\b' + word) + '\\w+\\b'), after) ...
'Return the word prefix before the cursor.'
def getprevword(self):
line = self.text.get('insert linestart', 'insert') i = len(line) while ((i > 0) and (line[(i - 1)] in self.wordchars)): i = (i - 1) return line[i:]
'Constructor arguments: select_command -- A callable which will be called when a tab is selected. It is called with the name of the selected tab as an argument. tabs -- A list of strings, the names of the tabs. Should be specified in the desired tab order. The first tab will be the default and first active tab. If tabs...
def __init__(self, page_set, select_command, tabs=None, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
Frame.__init__(self, page_set, **kw) self.select_command = select_command self.n_rows = n_rows self.max_tabs_per_row = max_tabs_per_row self.expand_tabs = expand_tabs self.page_set = page_set self._tabs = {} self._tab2row = {} if tabs: self._tab_names = list(tabs) else: ...
'Add a new tab with the name given in tab_name.'
def add_tab(self, tab_name):
if (not tab_name): raise InvalidNameError(("Invalid Tab name: '%s'" % tab_name)) if (tab_name in self._tab_names): raise AlreadyExistsError(("Tab named '%s' already exists" % tab_name)) self._tab_names.append(tab_name) self._arrange_tabs()
'Remove the tab named <tab_name>'
def remove_tab(self, tab_name):
if (not (tab_name in self._tab_names)): raise KeyError(("No such Tab: '%s" % tab_name)) self._tab_names.remove(tab_name) self._arrange_tabs()
'Show the tab named <tab_name> as the selected one'
def set_selected_tab(self, tab_name):
if (tab_name == self._selected_tab): return if ((tab_name is not None) and (tab_name not in self._tabs)): raise KeyError(("No such Tab: '%s" % tab_name)) if (self._selected_tab is not None): self._tabs[self._selected_tab].set_normal() self._selected_tab = None if (ta...
'Arrange the tabs in rows, in the order in which they were added. If n_rows >= 1, this will be the number of rows used. Otherwise the number of rows will be calculated according to the number of tabs and max_tabs_per_row. In this case, the number of rows may change when adding/removing tabs.'
def _arrange_tabs(self):
while self._tabs: self._tabs.popitem()[1].destroy() self._reset_tab_rows() if (not self._tab_names): return if ((self.n_rows is not None) and (self.n_rows > 0)): n_rows = self.n_rows else: n_rows = (((len(self._tab_names) - 1) // self.max_tabs_per_row) + 1) expand...
'Constructor arguments: name -- The tab\'s name, which will appear in its button. select_command -- The command to be called upon selection of the tab. It is called with the tab\'s name as an argument.'
def __init__(self, name, select_command, tab_row, tab_set):
Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED) self.name = name self.select_command = select_command self.tab_set = tab_set self.is_last_in_row = False self.button = Radiobutton(self, text=name, command=self._select_event, padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE, hi...
'Event handler for tab selection. With TabbedPageSet, this calls TabbedPageSet.change_page, so that selecting a tab changes the page. Note that this does -not- call set_selected -- it will be called by TabSet.set_selected_tab, which should be called when whatever the tabs are related to changes.'
def _select_event(self, *args):
self.select_command(self.name) return
'Assume selected look'
def set_selected(self):
self._place_masks(selected=True)
'Assume normal look'
def set_normal(self):
self._place_masks(selected=False)
'Constructor arguments: page_names -- A list of strings, each will be the dictionary key to a page\'s widget, and the name displayed on the page\'s tab. Should be specified in the desired page order. The first page will be the default and first active page. If page_names is None or empty, the TabbedPageSet will be init...
def __init__(self, parent, page_names=None, page_class=PageLift, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
Frame.__init__(self, parent, **kw) self.page_class = page_class self.pages = {} self._pages_order = [] self._current_page = None self._default_page = None self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.pages_frame = Frame(self) self.pages_frame.grid(row=1, ...
'Add a new page with the name given in page_name.'
def add_page(self, page_name):
if (not page_name): raise InvalidNameError(("Invalid TabPage name: '%s'" % page_name)) if (page_name in self.pages): raise AlreadyExistsError(("TabPage named '%s' already exists" % page_name)) self.pages[page_name] = self.page_class(self.pages_frame) self._pages_orde...
'Destroy the page whose name is given in page_name.'
def remove_page(self, page_name):
if (not (page_name in self.pages)): raise KeyError(("No such TabPage: '%s" % page_name)) self._pages_order.remove(page_name) if (len(self._pages_order) > 0): if (page_name == self._default_page): self._default_page = self._pages_order[0] else: self._default_p...
'Show the page whose name is given in page_name.'
def change_page(self, page_name):
if (self._current_page == page_name): return if ((page_name is not None) and (page_name not in self.pages)): raise KeyError(("No such TabPage: '%s'" % page_name)) if (self._current_page is not None): self.pages[self._current_page]._hide() self._current_page = None if...
'Initialize attributes and setup redirection. _operations: dict mapping operation name to new function. widget: the widget whose tcl command is to be intercepted. tk: widget.tk, a convenience attribute, probably not needed. orig: new name of the original tcl command. Since renaming to orig fails with TclError when orig...
def __init__(self, widget):
self._operations = {} self.widget = widget self.tk = tk = widget.tk w = widget._w self.orig = (w + '_orig') tk.call('rename', w, self.orig) tk.createcommand(w, self.dispatch)
'Unregister operations and revert redirection created by .__init__.'
def close(self):
for operation in list(self._operations): self.unregister(operation) widget = self.widget tk = widget.tk w = widget._w tk.deletecommand(w) tk.call('rename', self.orig, w) del self.widget, self.tk
'Return OriginalCommand(operation) after registering function. Registration adds an operation: function pair to ._operations. It also adds an widget function attribute that masks the tkinter class instance method. Method masking operates independently from command dispatch. If a second function is registered for the s...
def register(self, operation, function):
self._operations[operation] = function setattr(self.widget, operation, function) return OriginalCommand(self, operation)
'Return the function for the operation, or None. Deleting the instance attribute unmasks the class attribute.'
def unregister(self, operation):
if (operation in self._operations): function = self._operations[operation] del self._operations[operation] try: delattr(self.widget, operation) except AttributeError: pass return function else: return None
'Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not p...
def dispatch(self, operation, *args):
m = self._operations.get(operation) try: if m: return m(*args) else: return self.tk.call(((self.orig, operation) + args)) except TclError: return ''
'Create .tk_call and .orig_and_operation for .__call__ method. .redir and .operation store the input args for __repr__. .tk and .orig copy attributes of .redir (probably not needed).'
def __init__(self, redir, operation):
self.redir = redir self.operation = operation self.tk = redir.tk self.orig = redir.orig self.tk_call = redir.tk.call self.orig_and_operation = (redir.orig, operation)
'The user selected the menu entry or hotkey, open the tip.'
def force_open_calltip_event(self, event):
self.open_calltip(True)
'Happens when it would be nice to open a CallTip, but not really necessary, for example after an opening bracket, so function calls won\'t be made.'
def try_open_calltip_event(self, event):
self.open_calltip(False)
'Return the argument list and docstring of a function or class. If there is a Python subprocess, get the calltip there. Otherwise, either this fetch_tip() is running in the subprocess or it was called in an IDLE running without the subprocess. The subprocess environment is that of the most recently run script. If two...
def fetch_tip(self, expression):
try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except AttributeError: rpcclt = None if rpcclt: return rpcclt.remotecall('exec', 'get_the_calltip', (expression,), {}) else: return get_argspec(get_entity(expression))
'_htest - bool, change box location when running htest _utest - bool, don\'t wait_window when running unittest'
def __init__(self, parent, title, _htest=False, _utest=False):
Toplevel.__init__(self, parent) self.parent = parent if _htest: parent.instance_dict = {} self.wm_withdraw() self.configure(borderwidth=5) self.title('IDLE Preferences') self.geometry(('+%d+%d' % ((parent.winfo_rootx() + 20), (parent.winfo_rooty() + (30 if (not _htest) else 150)))...
'Clear and rebuild the HelpFiles section in self.changedItems'
def UpdateUserHelpChangedItems(self):
self.changedItems['main']['HelpFiles'] = {} for num in range(1, (len(self.userHelpList) + 1)): self.AddChangedItem('main', 'HelpFiles', str(num), ';'.join(self.userHelpList[(num - 1)][:2]))
'load configuration from default and user config files and populate the widgets on the config dialog pages.'
def LoadConfigs(self):
self.LoadFontCfg() self.LoadTabCfg() self.LoadThemeCfg() self.LoadKeyCfg() self.LoadGeneralCfg()
'save a newly created core key set. keySetName - string, the name of the new key set keySet - dictionary containing the new key set'
def SaveNewKeySet(self, keySetName, keySet):
if (not idleConf.userCfg['keys'].has_section(keySetName)): idleConf.userCfg['keys'].add_section(keySetName) for event in keySet: value = keySet[event] idleConf.userCfg['keys'].SetOption(keySetName, event, value)
'save a newly created theme. themeName - string, the name of the new theme theme - dictionary containing the new theme'
def SaveNewTheme(self, themeName, theme):
if (not idleConf.userCfg['highlight'].has_section(themeName)): idleConf.userCfg['highlight'].add_section(themeName) for element in theme: value = theme[element] idleConf.userCfg['highlight'].SetOption(themeName, element, value)
'Save configuration changes to the user config file.'
def SaveAllChangedConfigs(self):
idleConf.userCfg['main'].Save() for configType in self.changedItems: cfgTypeHasChanges = False for section in self.changedItems[configType]: if (section == 'HelpFiles'): idleConf.userCfg['main'].remove_section('HelpFiles') cfgTypeHasChanges = True ...
'Dynamically apply configuration changes'
def ActivateConfigChanges(self):
winInstances = self.parent.instance_dict.keys() for instance in winInstances: instance.ResetColorizer() instance.ResetFont() instance.set_notabs_indentwidth() instance.ApplyKeybindings() instance.reset_help_menu_entries()
'Get menu entry and url/ local file location for Additional Help User selects a name for the Help resource and provides a web url or a local file as its source. The user can enter a url or browse for the file. _htest - bool, change box location when running htest'
def __init__(self, parent, title, menuItem='', filePath='', _htest=False):
Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol('WM_DELETE_WINDOW', self.Cancel) self.parent = parent self.result = None self.CreateWidgets() self.me...
'Simple validity check for a sensible menu item name'
def MenuOk(self):
menuOk = True menu = self.menu.get() menu.strip() if (not menu): tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif (len(menu) > 30): tkMessageBox.showerror(title...
'Simple validity check for menu file path'
def PathOk(self):
pathOk = True path = self.path.get() path.strip() if (not path): tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self) self.entryPath.focus_set() pathOk = False elif path.startswith(('www.', 'http')): pa...