code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def view_text(parent, title, contents, modal=True, wrap='word', _utest=False): """Create text viewer for given text. parent - parent of this dialog title - string which is the title of popup dialog contents - text to display in this dialog wrap - type of text wrapping to use ('word', 'char' or 'none') modal - controls if users can interact with other windows while this dialog is displayed _utest - bool; controls wait_window on unittest """ return ViewWindow(parent, title, contents, modal, wrap=wrap, _utest=_utest)
Create text viewer for given text. parent - parent of this dialog title - string which is the title of popup dialog contents - text to display in this dialog wrap - type of text wrapping to use ('word', 'char' or 'none') modal - controls if users can interact with other windows while this dialog is displayed _utest - bool; controls wait_window on unittest
view_text
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/textview.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/textview.py
MIT
def view_file(parent, title, filename, encoding, modal=True, wrap='word', _utest=False): """Create text viewer for text in filename. Return error message if file cannot be read. Otherwise calls view_text with contents of the file. """ try: with open(filename, 'r', encoding=encoding) as file: contents = file.read() except OSError: showerror(title='File Load Error', message=f'Unable to load file {filename!r} .', parent=parent) except UnicodeDecodeError as err: showerror(title='Unicode Decode Error', message=str(err), parent=parent) else: return view_text(parent, title, contents, modal, wrap=wrap, _utest=_utest) return None
Create text viewer for text in filename. Return error message if file cannot be read. Otherwise calls view_text with contents of the file.
view_file
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/textview.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/textview.py
MIT
def move_at_edge_if_selection(self, edge_index): """Cursor move begins at start or end of selection When a left/right cursor key is pressed create and return to Tkinter a function which causes a cursor move from the associated edge of the selection. """ self_text_index = self.text.index self_text_mark_set = self.text.mark_set edges_table = ("sel.first+1c", "sel.last-1c") def move_at_edge(event): if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed try: self_text_index("sel.first") self_text_mark_set("insert", edges_table[edge_index]) except TclError: pass return move_at_edge
Cursor move begins at start or end of selection When a left/right cursor key is pressed create and return to Tkinter a function which causes a cursor move from the associated edge of the selection.
move_at_edge_if_selection
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
MIT
def open_module(self): """Get module name from user and open it. Return module path or None for calls by open_module_browser when latter is not invoked in named editor window. """ # XXX This, open_module_browser, and open_path_browser # would fit better in iomenu.IOBinding. try: name = self.text.get("sel.first", "sel.last").strip() except TclError: name = '' file_path = query.ModuleName( self.text, "Open Module", "Enter the name of a Python module\n" "to search on sys.path and open:", name).result if file_path is not None: if self.flist: self.flist.open(file_path) else: self.io.loadfile(file_path) return file_path
Get module name from user and open it. Return module path or None for calls by open_module_browser when latter is not invoked in named editor window.
open_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
MIT
def fill_menus(self, menudefs=None, keydefs=None): """Add appropriate entries to the menus and submenus Menus that are absent or None in self.menudict are ignored. """ if menudefs is None: menudefs = self.mainmenu.menudefs if keydefs is None: keydefs = self.mainmenu.default_keydefs menudict = self.menudict text = self.text for mname, entrylist in menudefs: menu = menudict.get(mname) if not menu: continue for entry in entrylist: if not entry: menu.add_separator() else: label, eventname = entry checkbutton = (label[:1] == '!') if checkbutton: label = label[1:] underline, label = prepstr(label) accelerator = get_accelerator(keydefs, eventname) def command(text=text, eventname=eventname): text.event_generate(eventname) if checkbutton: var = self.get_var_obj(eventname, BooleanVar) menu.add_checkbutton(label=label, underline=underline, command=command, accelerator=accelerator, variable=var) else: menu.add_command(label=label, underline=underline, command=command, accelerator=accelerator)
Add appropriate entries to the menus and submenus Menus that are absent or None in self.menudict are ignored.
fill_menus
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
MIT
def newline_and_indent_event(self, event): """Insert a newline and indentation after Enter keypress event. Properly position the cursor on the new line based on information from the current line. This takes into account if the current line is a shell prompt, is empty, has selected text, contains a block opener, contains a block closer, is a continuation line, or is inside a string. """ text = self.text first, last = self.get_selection_indices() text.undo_block_start() try: # Close undo block and expose new line in finally clause. if first and last: text.delete(first, last) text.mark_set("insert", first) line = text.get("insert linestart", "insert") # Count leading whitespace for indent size. i, n = 0, len(line) while i < n and line[i] in " \t": i += 1 if i == n: # The cursor is in or at leading indentation in a continuation # line; just inject an empty line at the start. text.insert("insert linestart", '\n') return "break" indent = line[:i] # Strip whitespace before insert point unless it's in the prompt. i = 0 while line and line[-1] in " \t" and line != self.prompt_last_line: line = line[:-1] i += 1 if i: text.delete("insert - %d chars" % i, "insert") # Strip whitespace after insert point. while text.get("insert") in " \t": text.delete("insert") # Insert new line. text.insert("insert", '\n') # Adjust indentation for continuations and block open/close. # First need to find the last statement. lno = index2line(text.index('insert')) y = pyparse.Parser(self.indentwidth, self.tabwidth) if not self.prompt_last_line: for context in self.num_context_lines: startat = max(lno - context, 1) startatindex = repr(startat) + ".0" rawtext = text.get(startatindex, "insert") y.set_code(rawtext) bod = y.find_good_parse_start( self._build_char_in_string_func(startatindex)) if bod is not None or startat == 1: break y.set_lo(bod or 0) else: r = text.tag_prevrange("console", "insert") if r: startatindex = r[1] else: startatindex = "1.0" rawtext = text.get(startatindex, "insert") y.set_code(rawtext) y.set_lo(0) c = y.get_continuation_type() if c != pyparse.C_NONE: # The current statement hasn't ended yet. if c == pyparse.C_STRING_FIRST_LINE: # After the first line of a string do not indent at all. pass elif c == pyparse.C_STRING_NEXT_LINES: # Inside a string which started before this line; # just mimic the current indent. text.insert("insert", indent) elif c == pyparse.C_BRACKET: # Line up with the first (if any) element of the # last open bracket structure; else indent one # level beyond the indent of the line with the # last open bracket. self.reindent_to(y.compute_bracket_indent()) elif c == pyparse.C_BACKSLASH: # If more than one line in this statement already, just # mimic the current indent; else if initial line # has a start on an assignment stmt, indent to # beyond leftmost =; else to beyond first chunk of # non-whitespace on initial line. if y.get_num_lines_in_stmt() > 1: text.insert("insert", indent) else: self.reindent_to(y.compute_backslash_indent()) else: assert 0, "bogus continuation type %r" % (c,) return "break" # This line starts a brand new statement; indent relative to # indentation of initial line of closest preceding # interesting statement. indent = y.get_base_indent_string() text.insert("insert", indent) if y.is_block_opener(): self.smart_indent_event(event) elif indent and y.is_block_closer(): self.smart_backspace_event(event) return "break" finally: text.see("insert") text.undo_block_stop()
Insert a newline and indentation after Enter keypress event. Properly position the cursor on the new line based on information from the current line. This takes into account if the current line is a shell prompt, is empty, has selected text, contains a block opener, contains a block closer, is a continuation line, or is inside a string.
newline_and_indent_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
MIT
def get_line_indent(line, tabwidth): """Return a line's indentation as (# chars, effective # of spaces). The effective # of spaces is the length after properly "expanding" the tabs into spaces, as done by str.expandtabs(tabwidth). """ m = _line_indent_re.match(line) return m.end(), len(m.group().expandtabs(tabwidth))
Return a line's indentation as (# chars, effective # of spaces). The effective # of spaces is the length after properly "expanding" the tabs into spaces, as done by str.expandtabs(tabwidth).
get_line_indent
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/editor.py
MIT
def _init_tk_type(): """ Initializes OS X Tk variant values for isAquaTk(), isCarbonTk(), isCocoaTk(), and isXQuartz(). """ global _tk_type if platform == 'darwin': root = tkinter.Tk() ws = root.tk.call('tk', 'windowingsystem') if 'x11' in ws: _tk_type = "xquartz" elif 'aqua' not in ws: _tk_type = "other" elif 'AppKit' in root.tk.call('winfo', 'server', '.'): _tk_type = "cocoa" else: _tk_type = "carbon" root.destroy() else: _tk_type = "other"
Initializes OS X Tk variant values for isAquaTk(), isCarbonTk(), isCocoaTk(), and isXQuartz().
_init_tk_type
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def isAquaTk(): """ Returns True if IDLE is using a native OS X Tk (Cocoa or Carbon). """ if not _tk_type: _init_tk_type() return _tk_type == "cocoa" or _tk_type == "carbon"
Returns True if IDLE is using a native OS X Tk (Cocoa or Carbon).
isAquaTk
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def isCarbonTk(): """ Returns True if IDLE is using a Carbon Aqua Tk (instead of the newer Cocoa Aqua Tk). """ if not _tk_type: _init_tk_type() return _tk_type == "carbon"
Returns True if IDLE is using a Carbon Aqua Tk (instead of the newer Cocoa Aqua Tk).
isCarbonTk
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def isCocoaTk(): """ Returns True if IDLE is using a Cocoa Aqua Tk. """ if not _tk_type: _init_tk_type() return _tk_type == "cocoa"
Returns True if IDLE is using a Cocoa Aqua Tk.
isCocoaTk
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def isXQuartz(): """ Returns True if IDLE is using an OS X X11 Tk. """ if not _tk_type: _init_tk_type() return _tk_type == "xquartz"
Returns True if IDLE is using an OS X X11 Tk.
isXQuartz
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def tkVersionWarning(root): """ Returns a string warning message if the Tk version in use appears to be one known to cause problems with IDLE. 1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable. 2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but can still crash unexpectedly. """ if isCocoaTk(): patchlevel = root.tk.call('info', 'patchlevel') if patchlevel not in ('8.5.7', '8.5.9'): return False return ("WARNING: The version of Tcl/Tk ({0}) in use may" " be unstable.\n" "Visit http://www.python.org/download/mac/tcltk/" " for current information.".format(patchlevel)) else: return False
Returns a string warning message if the Tk version in use appears to be one known to cause problems with IDLE. 1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable. 2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but can still crash unexpectedly.
tkVersionWarning
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def readSystemPreferences(): """ Fetch the macOS system preferences. """ if platform != 'darwin': return None plist_path = expanduser('~/Library/Preferences/.GlobalPreferences.plist') try: with open(plist_path, 'rb') as plist_file: return plistlib.load(plist_file) except OSError: return None
Fetch the macOS system preferences.
readSystemPreferences
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def preferTabsPreferenceWarning(): """ Warn if "Prefer tabs when opening documents" is set to "Always". """ if platform != 'darwin': return None prefs = readSystemPreferences() if prefs and prefs.get('AppleWindowTabbingMode') == 'always': return ( 'WARNING: The system preference "Prefer tabs when opening' ' documents" is set to "Always". This will cause various problems' ' with IDLE. For the best experience, change this setting when' ' running IDLE (via System Preferences -> Dock).' ) return None
Warn if "Prefer tabs when opening documents" is set to "Always".
preferTabsPreferenceWarning
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def addOpenEventSupport(root, flist): """ This ensures that the application will respond to open AppleEvents, which makes is feasible to use IDLE as the default application for python files. """ def doOpenFile(*args): for fn in args: flist.open(fn) # The command below is a hook in aquatk that is called whenever the app # receives a file open event. The callback can have multiple arguments, # one for every file that should be opened. root.createcommand("::tk::mac::OpenDocument", doOpenFile)
This ensures that the application will respond to open AppleEvents, which makes is feasible to use IDLE as the default application for python files.
addOpenEventSupport
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def overrideRootMenu(root, flist): """ Replace the Tk root menu by something that is more appropriate for IDLE with an Aqua Tk. """ # The menu that is attached to the Tk root (".") is also used by AquaTk for # all windows that don't specify a menu of their own. The default menubar # contains a number of menus, none of which are appropriate for IDLE. The # Most annoying of those is an 'About Tck/Tk...' menu in the application # menu. # # This function replaces the default menubar by a mostly empty one, it # should only contain the correct application menu and the window menu. # # Due to a (mis-)feature of TkAqua the user will also see an empty Help # menu. from tkinter import Menu from idlelib import mainmenu from idlelib import window closeItem = mainmenu.menudefs[0][1][-2] # Remove the last 3 items of the file menu: a separator, close window and # quit. Close window will be reinserted just above the save item, where # it should be according to the HIG. Quit is in the application menu. del mainmenu.menudefs[0][1][-3:] mainmenu.menudefs[0][1].insert(6, closeItem) # Remove the 'About' entry from the help menu, it is in the application # menu del mainmenu.menudefs[-1][1][0:2] # Remove the 'Configure Idle' entry from the options menu, it is in the # application menu as 'Preferences' del mainmenu.menudefs[-3][1][0:2] menubar = Menu(root) root.configure(menu=menubar) menudict = {} menudict['window'] = menu = Menu(menubar, name='window', tearoff=0) menubar.add_cascade(label='Window', menu=menu, underline=0) def postwindowsmenu(menu=menu): end = menu.index('end') if end is None: end = -1 if end > 0: menu.delete(0, end) window.add_windows_to_menu(menu) window.register_callback(postwindowsmenu) def about_dialog(event=None): "Handle Help 'About IDLE' event." # Synchronize with editor.EditorWindow.about_dialog. from idlelib import help_about help_about.AboutDialog(root) def config_dialog(event=None): "Handle Options 'Configure IDLE' event." # Synchronize with editor.EditorWindow.config_dialog. from idlelib import configdialog # Ensure that the root object has an instance_dict attribute, # mirrors code in EditorWindow (although that sets the attribute # on an EditorWindow instance that is then passed as the first # argument to ConfigDialog) root.instance_dict = flist.inversedict configdialog.ConfigDialog(root, 'Settings') def help_dialog(event=None): "Handle Help 'IDLE Help' event." # Synchronize with editor.EditorWindow.help_dialog. from idlelib import help help.show_idlehelp(root) root.bind('<<about-idle>>', about_dialog) root.bind('<<open-config-dialog>>', config_dialog) root.createcommand('::tk::mac::ShowPreferences', config_dialog) if flist: root.bind('<<close-all-windows>>', flist.close_all_callback) # The binding above doesn't reliably work on all versions of Tk # on macOS. Adding command definition below does seem to do the # right thing for now. root.createcommand('exit', flist.close_all_callback) if isCarbonTk(): # for Carbon AquaTk, replace the default Tk apple menu menudict['application'] = menu = Menu(menubar, name='apple', tearoff=0) menubar.add_cascade(label='IDLE', menu=menu) mainmenu.menudefs.insert(0, ('application', [ ('About IDLE', '<<about-idle>>'), None, ])) if isCocoaTk(): # replace default About dialog with About IDLE one root.createcommand('tkAboutDialog', about_dialog) # replace default "Help" item in Help menu root.createcommand('::tk::mac::ShowHelp', help_dialog) # remove redundant "IDLE Help" from menu del mainmenu.menudefs[-1][1][0]
Replace the Tk root menu by something that is more appropriate for IDLE with an Aqua Tk.
overrideRootMenu
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def fixb2context(root): '''Removed bad AquaTk Button-2 (right) and Paste bindings. They prevent context menu access and seem to be gone in AquaTk8.6. See issue #24801. ''' root.unbind_class('Text', '<B2>') root.unbind_class('Text', '<B2-Motion>') root.unbind_class('Text', '<<PasteSelection>>')
Removed bad AquaTk Button-2 (right) and Paste bindings. They prevent context menu access and seem to be gone in AquaTk8.6. See issue #24801.
fixb2context
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def setupApp(root, flist): """ Perform initial OS X customizations if needed. Called from pyshell.main() after initial calls to Tk() There are currently three major versions of Tk in use on OS X: 1. Aqua Cocoa Tk (native default since OS X 10.6) 2. Aqua Carbon Tk (original native, 32-bit only, deprecated) 3. X11 (supported by some third-party distributors, deprecated) There are various differences among the three that affect IDLE behavior, primarily with menus, mouse key events, and accelerators. Some one-time customizations are performed here. Others are dynamically tested throughout idlelib by calls to the isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which are initialized here as well. """ if isAquaTk(): hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist) fixb2context(root)
Perform initial OS X customizations if needed. Called from pyshell.main() after initial calls to Tk() There are currently three major versions of Tk in use on OS X: 1. Aqua Cocoa Tk (native default since OS X 10.6) 2. Aqua Carbon Tk (original native, 32-bit only, deprecated) 3. X11 (supported by some third-party distributors, deprecated) There are various differences among the three that affect IDLE behavior, primarily with menus, mouse key events, and accelerators. Some one-time customizations are performed here. Others are dynamically tested throughout idlelib by calls to the isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which are initialized here as well.
setupApp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/macosx.py
MIT
def replace(text): """Create or reuse a singleton ReplaceDialog instance. The singleton dialog saves user entries and preferences across instances. Args: text: Text widget containing the text to be searched. """ root = text._root() engine = searchengine.get(root) if not hasattr(engine, "_replacedialog"): engine._replacedialog = ReplaceDialog(root, engine) dialog = engine._replacedialog dialog.open(text)
Create or reuse a singleton ReplaceDialog instance. The singleton dialog saves user entries and preferences across instances. Args: text: Text widget containing the text to be searched.
replace
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def __init__(self, root, engine): """Create search dialog for finding and replacing text. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: replvar: StringVar containing 'Replace with:' value. replent: Entry widget for replvar. Created in create_entries(). ok: Boolean used in searchengine.search_text to indicate whether the search includes the selection. """ super().__init__(root, engine) self.replvar = StringVar(root)
Create search dialog for finding and replacing text. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: replvar: StringVar containing 'Replace with:' value. replent: Entry widget for replvar. Created in create_entries(). ok: Boolean used in searchengine.search_text to indicate whether the search includes the selection.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def open(self, text): """Make dialog visible on top of others and ready to use. Also, highlight the currently selected text and set the search to include the current selection (self.ok). Args: text: Text widget being searched. """ SearchDialogBase.open(self, text) try: first = text.index("sel.first") except TclError: first = None try: last = text.index("sel.last") except TclError: last = None first = first or text.index("insert") last = last or first self.show_hit(first, last) self.ok = True
Make dialog visible on top of others and ready to use. Also, highlight the currently selected text and set the search to include the current selection (self.ok). Args: text: Text widget being searched.
open
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def create_command_buttons(self): """Create base and additional command buttons. The additional buttons are for Find, Replace, Replace+Find, and Replace All. """ SearchDialogBase.create_command_buttons(self) self.make_button("Find", self.find_it) self.make_button("Replace", self.replace_it) self.make_button("Replace+Find", self.default_command, isdef=True) self.make_button("Replace All", self.replace_all)
Create base and additional command buttons. The additional buttons are for Find, Replace, Replace+Find, and Replace All.
create_command_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def replace_it(self, event=None): """Handle the Replace button. If the find is successful, then perform replace. """ if self.do_find(self.ok): self.do_replace()
Handle the Replace button. If the find is successful, then perform replace.
replace_it
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def default_command(self, event=None): """Handle the Replace+Find button as the default command. First performs a replace and then, if the replace was successful, a find next. """ if self.do_find(self.ok): if self.do_replace(): # Only find next match if replace succeeded. # A bad re can cause it to fail. self.do_find(False)
Handle the Replace+Find button as the default command. First performs a replace and then, if the replace was successful, a find next.
default_command
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def replace_all(self, event=None): """Handle the Replace All button. Search text for occurrences of the Find value and replace each of them. The 'wrap around' value controls the start point for searching. If wrap isn't set, then the searching starts at the first occurrence after the current selection; if wrap is set, the replacement starts at the first line. The replacement is always done top-to-bottom in the text. """ prog = self.engine.getprog() if not prog: return repl = self.replvar.get() text = self.text res = self.engine.search_text(text, prog) if not res: self.bell() return text.tag_remove("sel", "1.0", "end") text.tag_remove("hit", "1.0", "end") line = res[0] col = res[1].start() if self.engine.iswrap(): line = 1 col = 0 ok = True first = last = None # XXX ought to replace circular instead of top-to-bottom when wrapping text.undo_block_start() while True: res = self.engine.search_forward(text, prog, line, col, wrap=False, ok=ok) if not res: break line, m = res chars = text.get("%d.0" % line, "%d.0" % (line+1)) orig = m.group() new = self._replace_expand(m, repl) if new is None: break i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) if new == orig: text.mark_set("insert", last) else: text.mark_set("insert", first) if first != last: text.delete(first, last) if new: text.insert(first, new) col = i + len(new) ok = False text.undo_block_stop() if first and last: self.show_hit(first, last) self.close()
Handle the Replace All button. Search text for occurrences of the Find value and replace each of them. The 'wrap around' value controls the start point for searching. If wrap isn't set, then the searching starts at the first occurrence after the current selection; if wrap is set, the replacement starts at the first line. The replacement is always done top-to-bottom in the text.
replace_all
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def do_find(self, ok=False): """Search for and highlight next occurrence of pattern in text. No text replacement is done with this option. """ if not self.engine.getprog(): return False text = self.text res = self.engine.search_text(text, None, ok) if not res: self.bell() return False line, m = res i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) self.show_hit(first, last) self.ok = True return True
Search for and highlight next occurrence of pattern in text. No text replacement is done with this option.
do_find
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def show_hit(self, first, last): """Highlight text between first and last indices. Text is highlighted via the 'hit' tag and the marked section is brought into view. The colors from the 'hit' tag aren't currently shown when the text is displayed. This is due to the 'sel' tag being added first, so the colors in the 'sel' config are seen instead of the colors for 'hit'. """ text = self.text text.mark_set("insert", first) text.tag_remove("sel", "1.0", "end") text.tag_add("sel", first, last) text.tag_remove("hit", "1.0", "end") if first == last: text.tag_add("hit", first) else: text.tag_add("hit", first, last) text.see("insert") text.update_idletasks()
Highlight text between first and last indices. Text is highlighted via the 'hit' tag and the marked section is brought into view. The colors from the 'hit' tag aren't currently shown when the text is displayed. This is due to the 'sel' tag being added first, so the colors in the 'sel' config are seen instead of the colors for 'hit'.
show_hit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def start_debugger(rpchandler, gui_adap_oid): """Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy. """ gui_proxy = GUIProxy(rpchandler, gui_adap_oid) idb = debugger.Idb(gui_proxy) idb_adap = IdbAdapter(idb) rpchandler.register(idb_adap_oid, idb_adap) return idb_adap_oid
Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy.
start_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def start_remote_debugger(rpcclt, pyshell): """Start the subprocess debugger, initialize the debugger GUI and RPC link Request the RPCServer start the Python subprocess debugger and link. Set up the Idle side of the split debugger by instantiating the IdbProxy, debugger GUI, and debugger GUIAdapter objects and linking them together. Register the GUIAdapter with the RPCClient to handle debugger GUI interaction requests coming from the subprocess debugger via the GUIProxy. The IdbAdapter will pass execution and environment requests coming from the Idle debugger GUI to the subprocess debugger via the IdbProxy. """ global idb_adap_oid idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\ (gui_adap_oid,), {}) idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid) gui = debugger.Debugger(pyshell, idb_proxy) gui_adap = GUIAdapter(rpcclt, gui) rpcclt.register(gui_adap_oid, gui_adap) return gui
Start the subprocess debugger, initialize the debugger GUI and RPC link Request the RPCServer start the Python subprocess debugger and link. Set up the Idle side of the split debugger by instantiating the IdbProxy, debugger GUI, and debugger GUIAdapter objects and linking them together. Register the GUIAdapter with the RPCClient to handle debugger GUI interaction requests coming from the subprocess debugger via the GUIProxy. The IdbAdapter will pass execution and environment requests coming from the Idle debugger GUI to the subprocess debugger via the IdbProxy.
start_remote_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def close_remote_debugger(rpcclt): """Shut down subprocess debugger and Idle side of debugger RPC link Request that the RPCServer shut down the subprocess debugger and link. Unregister the GUIAdapter, which will cause a GC on the Idle process debugger and RPC link objects. (The second reference to the debugger GUI is deleted in pyshell.close_remote_debugger().) """ close_subprocess_debugger(rpcclt) rpcclt.unregister(gui_adap_oid)
Shut down subprocess debugger and Idle side of debugger RPC link Request that the RPCServer shut down the subprocess debugger and link. Unregister the GUIAdapter, which will cause a GC on the Idle process debugger and RPC link objects. (The second reference to the debugger GUI is deleted in pyshell.close_remote_debugger().)
close_remote_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ self.parent = parent # Needed for Font call. self.message = message self.text0 = text0 self.used_names = used_names Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.title(title) self.transient(parent) self.grab_set() windowingsystem = self.tk.call('tk', 'windowingsystem') if windowingsystem == 'aqua': try: self.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._w, 'moveableModal', '') except: pass self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.create_widgets() self.update_idletasks() # Need here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) self.resizable(height=False, width=False) if not _utest: self.deiconify() # Unhide now that geometry set. self.wait_window()
Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def create_widgets(self, ok_text='OK'): # Do not replace. """Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2. """ # Bind to self the widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.entry.focus_set() self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E, pady=[10,0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W+E) self.create_extra() self.button_ok = Button( frame, text=ok_text, default='active', command=self.ok) self.button_cancel = Button( frame, text='Cancel', command=self.cancel) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5)
Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2.
create_widgets
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set()
If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel.
ok
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest)
Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def __init__(self, parent, title, *, cli_args=[], _htest=False, _utest=False): """cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display. """ message = 'Command Line Arguments for sys.argv:' super().__init__( parent, title, message, text0=cli_args, _htest=_htest, _utest=_utest)
cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def open_completions(self, args): """Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode. """ evalfuncs, complete, wantwin, mode = args # Cancel another delayed call, if it exists. if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==FILES): # Find the beginning of the string. # fetch_completions will look at the file system to determine # whether the string value constitutes an actual file name # XXX could consider raw strings here and unescape the string # value if it's not raw. self._remove_autocomplete_window() mode = FILES # Find last separator or string start while i and curline[i-1] not in "'\"" + SEPS: i -= 1 comp_start = curline[i:j] j = i # Find string start while i and curline[i-1] not in "'\"": i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==ATTRS): self._remove_autocomplete_window() mode = ATTRS while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127): i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': # Need object with attributes. hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if (not comp_what or (not evalfuncs and comp_what.find('(') != -1)): return None else: comp_what = "" else: return None if complete and not comp_what and not comp_start: return None comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return None self.autocompletewindow = self._make_autocomplete_window() return not self.autocompletewindow.show_window( comp_lists, "insert-%dc" % len(comp_start), complete, mode, wantwin)
Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode.
open_completions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
MIT
def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == ATTRS: if what == "": namespace = {**__main__.__builtins__.__dict__, **__main__.__dict__} bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl
Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run.
fetch_completions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
MIT
def get_line_info(codeline): """Return tuple of (line indent value, codeline, block start keyword). The indentation of empty lines (or comment lines) is INFINITY. If the line does not start a block, the keyword value is False. """ spaces, firstword = get_spaces_firstword(codeline) indent = len(spaces) if len(codeline) == indent or codeline[indent] == '#': indent = INFINITY opener = firstword in BLOCKOPENERS and firstword return indent, codeline, opener
Return tuple of (line indent value, codeline, block start keyword). The indentation of empty lines (or comment lines) is INFINITY. If the line does not start a block, the keyword value is False.
get_line_info
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def __init__(self, editwin): """Initialize settings for context block. editwin is the Editor window for the context block. self.text is the editor window text widget. self.context displays the code context text above the editor text. Initially None, it is toggled via <<toggle-code-context>>. self.topvisible is the number of the top text line displayed. self.info is a list of (line number, indent level, line text, block keyword) tuples for the block structure above topvisible. self.info[0] is initialized with a 'dummy' line which starts the toplevel 'block' of the module. self.t1 and self.t2 are two timer events on the editor text widget to monitor for changes to the context text or editor font. """ self.editwin = editwin self.text = editwin.text self._reset()
Initialize settings for context block. editwin is the Editor window for the context block. self.text is the editor window text widget. self.context displays the code context text above the editor text. Initially None, it is toggled via <<toggle-code-context>>. self.topvisible is the number of the top text line displayed. self.info is a list of (line number, indent level, line text, block keyword) tuples for the block structure above topvisible. self.info[0] is initialized with a 'dummy' line which starts the toplevel 'block' of the module. self.t1 and self.t2 are two timer events on the editor text widget to monitor for changes to the context text or editor font.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def toggle_code_context_event(self, event=None): """Toggle code context display. If self.context doesn't exist, create it to match the size of the editor window text (toggle on). If it does exist, destroy it (toggle off). Return 'break' to complete the processing of the binding. """ if self.context is None: # Calculate the border width and horizontal padding required to # align the context with the text in the main Text widget. # # All values are passed through getint(), since some # values may be pixel objects, which can't simply be added to ints. widgets = self.editwin.text, self.editwin.text_frame # Calculate the required horizontal padding and border width. padx = 0 border = 0 for widget in widgets: info = (widget.grid_info() if widget is self.editwin.text else widget.pack_info()) padx += widget.tk.getint(info['padx']) padx += widget.tk.getint(widget.cget('padx')) border += widget.tk.getint(widget.cget('border')) context = self.context = tkinter.Text( self.editwin.text_frame, height=1, width=1, # Don't request more than we get. highlightthickness=0, padx=padx, border=border, relief=SUNKEN, state='disabled') self.update_font() self.update_highlight_colors() context.bind('<ButtonRelease-1>', self.jumptoline) # Get the current context and initiate the recurring update event. self.timer_event() # Grid the context widget above the text widget. context.grid(row=0, column=1, sticky=NSEW) line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber') self.cell00 = tkinter.Frame(self.editwin.text_frame, bg=line_number_colors['background']) self.cell00.grid(row=0, column=0, sticky=NSEW) menu_status = 'Hide' else: self.context.destroy() self.context = None self.cell00.destroy() self.cell00 = None self.text.after_cancel(self.t1) self._reset() menu_status = 'Show' self.editwin.update_menu_label(menu='options', index='* Code Context', label=f'{menu_status} Code Context') return "break"
Toggle code context display. If self.context doesn't exist, create it to match the size of the editor window text (toggle on). If it does exist, destroy it (toggle off). Return 'break' to complete the processing of the binding.
toggle_code_context_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def get_context(self, new_topvisible, stopline=1, stopindent=0): """Return a list of block line tuples and the 'last' indent. The tuple fields are (linenum, indent, text, opener). The list represents header lines from new_topvisible back to stopline with successively shorter indents > stopindent. The list is returned ordered by line number. Last indent returned is the smallest indent observed. """ assert stopline > 0 lines = [] # The indentation level we are currently in. lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for linenum in range(new_topvisible, stopline-1, -1): codeline = self.text.get(f'{linenum}.0', f'{linenum}.end') indent, text, opener = get_line_info(codeline) if indent < lastindent: lastindent = indent if opener in ("else", "elif"): # Also show the if statement. lastindent += 1 if opener and linenum < new_topvisible and indent >= stopindent: lines.append((linenum, indent, text, opener)) if lastindent <= stopindent: break lines.reverse() return lines, lastindent
Return a list of block line tuples and the 'last' indent. The tuple fields are (linenum, indent, text, opener). The list represents header lines from new_topvisible back to stopline with successively shorter indents > stopindent. The list is returned ordered by line number. Last indent returned is the smallest indent observed.
get_context
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def update_code_context(self): """Update context information and lines visible in the context pane. No update is done if the text hasn't been scrolled. If the text was scrolled, the lines that should be shown in the context will be retrieved and the context area will be updated with the code, up to the number of maxlines. """ new_topvisible = self.editwin.getlineno("@0,0") if self.topvisible == new_topvisible: # Haven't scrolled. return if self.topvisible < new_topvisible: # Scroll down. lines, lastindent = self.get_context(new_topvisible, self.topvisible) # Retain only context info applicable to the region # between topvisible and new_topvisible. while self.info[-1][1] >= lastindent: del self.info[-1] else: # self.topvisible > new_topvisible: # Scroll up. stopindent = self.info[-1][1] + 1 # Retain only context info associated # with lines above new_topvisible. while self.info[-1][0] >= new_topvisible: stopindent = self.info[-1][1] del self.info[-1] lines, lastindent = self.get_context(new_topvisible, self.info[-1][0]+1, stopindent) self.info.extend(lines) self.topvisible = new_topvisible # Last context_depth context lines. context_strings = [x[2] for x in self.info[-self.context_depth:]] showfirst = 0 if context_strings[0] else 1 # Update widget. self.context['height'] = len(context_strings) - showfirst self.context['state'] = 'normal' self.context.delete('1.0', 'end') self.context.insert('end', '\n'.join(context_strings[showfirst:])) self.context['state'] = 'disabled'
Update context information and lines visible in the context pane. No update is done if the text hasn't been scrolled. If the text was scrolled, the lines that should be shown in the context will be retrieved and the context area will be updated with the code, up to the number of maxlines.
update_code_context
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def jumptoline(self, event=None): """ Show clicked context line at top of editor. If a selection was made, don't jump; allow copying. If no visible context, show the top line of the file. """ try: self.context.index("sel.first") except tkinter.TclError: lines = len(self.info) if lines == 1: # No context lines are showing. newtop = 1 else: # Line number clicked. contextline = int(float(self.context.index('insert'))) # Lines not displayed due to maxlines. offset = max(1, lines - self.context_depth) - 1 newtop = self.info[offset + contextline][0] self.text.yview(f'{newtop}.0') self.update_code_context()
Show clicked context line at top of editor. If a selection was made, don't jump; allow copying. If no visible context, show the top line of the file.
jumptoline
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def __init__(self, widget): '''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 already exists, only one WidgetDirector can exist for a given widget. ''' self._operations = {} self.widget = widget # widget instance self.tk = tk = widget.tk # widget's root w = widget._w # widget's (full) Tk pathname self.orig = w + "_orig" # Rename the Tcl command within Tcl: tk.call("rename", w, self.orig) # Create a new Tcl command whose name is the widget's pathname, and # whose action is to dispatch on the operation passed to the widget: tk.createcommand(w, self.dispatch)
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 already exists, only one WidgetDirector can exist for a given widget.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def register(self, operation, function): '''Return OriginalCommand(operation) after registering function. Registration adds an operation: function pair to ._operations. It also adds a 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 same operation, the first function is replaced in both places. ''' self._operations[operation] = function setattr(self.widget, operation, function) return OriginalCommand(self, operation)
Return OriginalCommand(operation) after registering function. Registration adds an operation: function pair to ._operations. It also adds a 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 same operation, the first function is replaced in both places.
register
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def unregister(self, operation): '''Return the function for the operation, or None. Deleting the instance attribute unmasks the class attribute. ''' 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
Return the function for the operation, or None. Deleting the instance attribute unmasks the class attribute.
unregister
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def dispatch(self, operation, *args): '''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 passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see colorizer.py. ''' m = self._operations.get(operation) try: if m: return m(*args) else: return self.tk.call((self.orig, operation) + args) except TclError: return ""
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 passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see colorizer.py.
dispatch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def __init__(self, redir, operation): '''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). ''' self.redir = redir self.operation = operation self.tk = redir.tk # redundant with self.redir self.orig = redir.orig # redundant with self.redir # These two could be deleted after checking recipient code. self.tk_call = redir.tk.call self.orig_and_operation = (redir.orig, operation)
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).
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def expand_substates(states): '''For each item of states return a list containing all combinations of that item with individual bits reset, sorted by the number of set bits. ''' def nbits(n): "number of bits set in n base 2" nb = 0 while n: n, rem = divmod(n, 2) nb += rem return nb statelist = [] for state in states: substates = list(set(state & x for x in states)) substates.sort(key=nbits, reverse=True) statelist.append(substates) return statelist
For each item of states return a list containing all combinations of that item with individual bits reset, sorted by the number of set bits.
expand_substates
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def _parse_sequence(sequence): """Get a string which should describe an event sequence. If it is successfully parsed as one, return a tuple containing the state (as an int), the event type (as an index of _types), and the detail - None if none, or a string if there is one. If the parsing is unsuccessful, return None. """ if not sequence or sequence[0] != '<' or sequence[-1] != '>': return None words = sequence[1:-1].split('-') modifiers = 0 while words and words[0] in _modifier_names: modifiers |= 1 << _modifier_names[words[0]] del words[0] if words and words[0] in _type_names: type = _type_names[words[0]] del words[0] else: return None if _binder_classes[type] is _SimpleBinder: if modifiers or words: return None else: detail = None else: # _ComplexBinder if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]: type_re = _keysym_re else: type_re = _button_re if not words: detail = None elif len(words) == 1 and type_re.match(words[0]): detail = words[0] else: return None return modifiers, type, detail
Get a string which should describe an event sequence. If it is successfully parsed as one, return a tuple containing the state (as an int), the event type (as an index of _types), and the detail - None if none, or a string if there is one. If the parsing is unsuccessful, return None.
_parse_sequence
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def MultiCallCreator(widget): """Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism. """ if widget in _multicall_dict: return _multicall_dict[widget] class MultiCall (widget): assert issubclass(widget, tkinter.Misc) def __init__(self, *args, **kwargs): widget.__init__(self, *args, **kwargs) # a dictionary which maps a virtual event to a tuple with: # 0. the function binded # 1. a list of triplets - the sequences it is binded to self.__eventinfo = {} self.__binders = [_binder_classes[i](i, widget, self) for i in range(len(_types))] def bind(self, sequence=None, func=None, add=None): #print("bind(%s, %s, %s)" % (sequence, func, add), # file=sys.__stderr__) if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>": if sequence in self.__eventinfo: ei = self.__eventinfo[sequence] if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].unbind(triplet, ei[0]) ei[0] = func if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].bind(triplet, func) else: self.__eventinfo[sequence] = [func, []] return widget.bind(self, sequence, func, add) def unbind(self, sequence, funcid=None): if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>" and \ sequence in self.__eventinfo: func, triplets = self.__eventinfo[sequence] if func is not None: for triplet in triplets: self.__binders[triplet[1]].unbind(triplet, func) self.__eventinfo[sequence][0] = None return widget.unbind(self, sequence, funcid) def event_add(self, virtual, *sequences): #print("event_add(%s, %s)" % (repr(virtual), repr(sequences)), # file=sys.__stderr__) if virtual not in self.__eventinfo: self.__eventinfo[virtual] = [None, []] func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_add(%s)" % seq, file=sys.__stderr__) widget.event_add(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].bind(triplet, func) triplets.append(triplet) def event_delete(self, virtual, *sequences): if virtual not in self.__eventinfo: return func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_delete: %s" % seq, file=sys.__stderr__) widget.event_delete(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].unbind(triplet, func) triplets.remove(triplet) def event_info(self, virtual=None): if virtual is None or virtual not in self.__eventinfo: return widget.event_info(self, virtual) else: return tuple(map(_triplet_to_sequence, self.__eventinfo[virtual][1])) + \ widget.event_info(self, virtual) def __del__(self): for virtual in self.__eventinfo: func, triplets = self.__eventinfo[virtual] if func: for triplet in triplets: try: self.__binders[triplet[1]].unbind(triplet, func) except tkinter.TclError as e: if not APPLICATION_GONE in e.args[0]: raise _multicall_dict[widget] = MultiCall return MultiCall
Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism.
MultiCallCreator
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def create_tag_opener(self, indices): """Highlight the single paren that matches""" self.text.tag_add("paren", indices[0]) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the single paren that matches
create_tag_opener
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def create_tag_parens(self, indices): """Highlight the left and right parens""" if self.text.get(indices[1]) in (')', ']', '}'): rightindex = indices[1]+"+1c" else: rightindex = indices[1] self.text.tag_add("paren", indices[0], indices[0]+"+1c", rightindex+"-1c", rightindex) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the left and right parens
create_tag_parens
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def create_tag_expression(self, indices): """Highlight the entire expression""" if self.text.get(indices[1]) in (')', ']', '}'): rightindex = indices[1]+"+1c" else: rightindex = indices[1] self.text.tag_add("paren", indices[0], rightindex) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the entire expression
create_tag_expression
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def set_timeout_none(self): """Highlight will remain until user input turns it off or the insert has moved""" # After CHECK_DELAY, call a function which disables the "paren" tag # if the event is for the most recent timer and the insert has changed, # or schedules another call for itself. self.counter += 1 def callme(callme, self=self, c=self.counter, index=self.text.index("insert")): if index != self.text.index("insert"): self.handle_restore_timer(c) else: self.editwin.text_frame.after(CHECK_DELAY, callme, callme) self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
Highlight will remain until user input turns it off or the insert has moved
set_timeout_none
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def set_timeout_last(self): """The last highlight created will be removed after FLASH_DELAY millisecs""" # associate a counter with an event; only disable the "paren" # tag if the event is for the most recent timer. self.counter += 1 self.editwin.text_frame.after( self.FLASH_DELAY, lambda self=self, c=self.counter: self.handle_restore_timer(c))
The last highlight created will be removed after FLASH_DELAY millisecs
set_timeout_last
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def __init__(self, text): '''Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not). ''' self.text = text self.history = [] self.prefix = None self.pointer = None self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool") text.bind("<<history-previous>>", self.history_prev) text.bind("<<history-next>>", self.history_next)
Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not).
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
MIT
def fetch(self, reverse): '''Fetch statement and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False. ''' nhist = len(self.history) pointer = self.pointer prefix = self.prefix if pointer is not None and prefix is not None: if self.text.compare("insert", "!=", "end-1c") or \ self.text.get("iomark", "end-1c") != self.history[pointer]: pointer = prefix = None self.text.mark_set("insert", "end-1c") # != after cursor move if pointer is None or prefix is None: prefix = self.text.get("iomark", "end-1c") if reverse: pointer = nhist # will be decremented else: if self.cyclic: pointer = -1 # will be incremented else: # abort history_next self.text.bell() return nprefix = len(prefix) while 1: pointer += -1 if reverse else 1 if pointer < 0 or pointer >= nhist: self.text.bell() if not self.cyclic and pointer < 0: # abort history_prev return else: if self.text.get("iomark", "end-1c") != prefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", prefix) pointer = prefix = None break item = self.history[pointer] if item[:nprefix] == prefix and len(item) > nprefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", item) break self.text.see("insert") self.text.tag_remove("sel", "1.0", "end") self.pointer = pointer self.prefix = prefix
Fetch statement and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False.
fetch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
MIT
def get(root): '''Return the singleton SearchEngine instance for the process. The single SearchEngine saves settings between dialog instances. If there is not a SearchEngine already, make one. ''' if not hasattr(root, "_searchengine"): root._searchengine = SearchEngine(root) # This creates a cycle that persists until root is deleted. return root._searchengine
Return the singleton SearchEngine instance for the process. The single SearchEngine saves settings between dialog instances. If there is not a SearchEngine already, make one.
get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards?
Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def search_text(self, text, prog=None, ok=0): '''Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. ''' if not prog: prog = self.getprog() if not prog: return None # Compilation failed -- stop wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res
Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True.
search_text
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def search_reverse(prog, chars, col): '''Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end(). ''' m = prog.search(chars) if not m: return None found = None i, j = m.span() # m.start(), m.end() == match slice indexes while i < col and j <= col: found = m if i == j: j = j+1 m = prog.search(chars, j) if not m: break i, j = m.span() return found
Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end().
search_reverse
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def get_selection(text): '''Return tuple of 'line.col' indexes from selection or insert mark. ''' try: first = text.index("sel.first") last = text.index("sel.last") except TclError: first = last = None if not first: first = text.index("insert") if not last: last = first return first, last
Return tuple of 'line.col' indexes from selection or insert mark.
get_selection
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def get_line_col(index): '''Return (line, col) tuple of ints from 'line.col' string.''' line, col = map(int, index.split(".")) # Fails on invalid index return line, col
Return (line, col) tuple of ints from 'line.col' string.
get_line_col
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def idle_formatwarning(message, category, filename, lineno, line=None): """Format warnings the IDLE way.""" s = "\nWarning (from warnings module):\n" s += ' File \"%s\", line %s\n' % (filename, lineno) if line is None: line = linecache.getline(filename, lineno) line = line.strip() if line: s += " %s\n" % line s += "%s: %s\n" % (category.__name__, message) return s
Format warnings the IDLE way.
idle_formatwarning
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def idle_showwarning_subproc( message, category, filename, lineno, file=None, line=None): """Show Idle-format warning after replacing warnings.showwarning. The only difference is the formatter called. """ if file is None: file = sys.stderr try: file.write(idle_formatwarning( message, category, filename, lineno, line)) except OSError: pass # the file (probably stderr) is invalid - this warning gets lost.
Show Idle-format warning after replacing warnings.showwarning. The only difference is the formatter called.
idle_showwarning_subproc
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle_tk_events(tcl=tcl): """Process any tk events that are ready to be dispatched if tkinter has been imported, a tcl interpreter has been created and tk has been loaded.""" tcl.eval("update")
Process any tk events that are ready to be dispatched if tkinter has been imported, a tcl interpreter has been created and tk has been loaded.
handle_tk_events
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def main(del_exitfunc=False): """Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves. """ global exit_now global quitting global no_exitfunc no_exitfunc = del_exitfunc #time.sleep(15) # test subprocess not responding try: assert(len(sys.argv) > 1) port = int(sys.argv[-1]) except: print("IDLE Subprocess: no IP port passed in sys.argv.", file=sys.__stderr__) return capture_warnings(True) sys.argv[:] = [""] sockthread = threading.Thread(target=manage_socket, name='SockThread', args=((LOCALHOST, port),)) sockthread.daemon = True sockthread.start() while 1: try: if exit_now: try: exit() except KeyboardInterrupt: # exiting but got an extra KBI? Try again! continue try: request = rpc.request_queue.get(block=True, timeout=0.05) except queue.Empty: request = None # Issue 32207: calling handle_tk_events here adds spurious # queue.Empty traceback to event handling exceptions. if request: seq, (method, args, kwargs) = request ret = method(*args, **kwargs) rpc.response_queue.put((seq, ret)) else: handle_tk_events() except KeyboardInterrupt: if quitting: exit_now = True continue except SystemExit: capture_warnings(False) raise except: type, value, tb = sys.exc_info() try: print_exception() rpc.response_queue.put((seq, None)) except: # Link didn't work, print same exception to __stderr__ traceback.print_exception(type, value, tb, file=sys.__stderr__) exit() else: continue
Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves.
main
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def flush_stdout(): """XXX How to do this now?"""
XXX How to do this now?
flush_stdout
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def exit(): """Exit subprocess, possibly after first clearing exit functions. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any functions registered with atexit will be removed before exiting. (VPython support) """ if no_exitfunc: import atexit atexit._clear() capture_warnings(False) sys.exit(0)
Exit subprocess, possibly after first clearing exit functions. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any functions registered with atexit will be removed before exiting. (VPython support)
exit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def fix_scaling(root): """Scale fonts on HiDPI displays.""" import tkinter.font scaling = float(root.tk.call('tk', 'scaling')) if scaling > 1.4: for name in tkinter.font.names(root): font = tkinter.font.Font(root=root, name=name, exists=True) size = int(font['size']) if size < 0: font['size'] = round(-0.75*size)
Scale fonts on HiDPI displays.
fix_scaling
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def install_recursionlimit_wrappers(): """Install wrappers to always add 30 to the recursion limit.""" # see: bpo-26806 @functools.wraps(sys.setrecursionlimit) def setrecursionlimit(*args, **kwargs): # mimic the original sys.setrecursionlimit()'s input handling if kwargs: raise TypeError( "setrecursionlimit() takes no keyword arguments") try: limit, = args except ValueError: raise TypeError(f"setrecursionlimit() takes exactly one " f"argument ({len(args)} given)") if not limit > 0: raise ValueError( "recursion limit must be greater or equal than 1") return setrecursionlimit.__wrapped__(limit + RECURSIONLIMIT_DELTA) fixdoc(setrecursionlimit, f"""\ This IDLE wrapper adds {RECURSIONLIMIT_DELTA} to prevent possible uninterruptible loops.""") @functools.wraps(sys.getrecursionlimit) def getrecursionlimit(): return getrecursionlimit.__wrapped__() - RECURSIONLIMIT_DELTA fixdoc(getrecursionlimit, f"""\ This IDLE wrapper subtracts {RECURSIONLIMIT_DELTA} to compensate for the {RECURSIONLIMIT_DELTA} IDLE adds when setting the limit.""") # add the delta to the default recursion limit, to compensate sys.setrecursionlimit(sys.getrecursionlimit() + RECURSIONLIMIT_DELTA) sys.setrecursionlimit = setrecursionlimit sys.getrecursionlimit = getrecursionlimit
Install wrappers to always add 30 to the recursion limit.
install_recursionlimit_wrappers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def uninstall_recursionlimit_wrappers(): """Uninstall the recursion limit wrappers from the sys module. IDLE only uses this for tests. Users can import run and call this to remove the wrapping. """ if ( getattr(sys.setrecursionlimit, '__wrapped__', None) and getattr(sys.getrecursionlimit, '__wrapped__', None) ): sys.setrecursionlimit = sys.setrecursionlimit.__wrapped__ sys.getrecursionlimit = sys.getrecursionlimit.__wrapped__ sys.setrecursionlimit(sys.getrecursionlimit() - RECURSIONLIMIT_DELTA)
Uninstall the recursion limit wrappers from the sys module. IDLE only uses this for tests. Users can import run and call this to remove the wrapping.
uninstall_recursionlimit_wrappers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle_error(self, request, client_address): """Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped. """ global quitting try: raise except SystemExit: raise except EOFError: global exit_now exit_now = True thread.interrupt_main() except: erf = sys.__stderr__ print('\n' + '-'*40, file=erf) print('Unhandled server exception!', file=erf) print('Thread: %s' % threading.current_thread().name, file=erf) print('Client Address: ', client_address, file=erf) print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) print('\n*** Unrecoverable, server exiting!', file=erf) print('-'*40, file=erf) quitting = True thread.interrupt_main()
Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped.
handle_error
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle(self): """Override base method""" executive = Executive(self) self.register("exec", executive) self.console = self.get_remote_proxy("console") sys.stdin = StdInputFile(self.console, "stdin", iomenu.encoding, iomenu.errors) sys.stdout = StdOutputFile(self.console, "stdout", iomenu.encoding, iomenu.errors) sys.stderr = StdOutputFile(self.console, "stderr", iomenu.encoding, "backslashreplace") sys.displayhook = rpc.displayhook # page help() text to shell. import pydoc # import must be done here to capture i/o binding pydoc.pager = pydoc.plainpager # Keep a reference to stdin so that it won't try to exit IDLE if # sys.stdin gets changed from within IDLE's shell. See issue17838. self._keep_stdin = sys.stdin install_recursionlimit_wrappers() self.interp = self.get_remote_proxy("interp") rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
Override base method
handle
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def __init__(self, master, *, _htest=False, _utest=False): """ _htest - bool, change box location when running htest """ self.master = master self._htest = _htest self._utest = _utest self.init()
_htest - bool, change box location when running htest
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/pathbrowser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/pathbrowser.py
MIT
def _binary_search(self, s): """Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such. """ i = 0; j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m] >= s: j = m else: i = m + 1 return min(i, len(self.completions)-1)
Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such.
_binary_search
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def _complete_string(self, s): """Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s. """ first = self._binary_search(s) if self.completions[first][:len(s)] != s: # There is not even one completion which s is a prefix of. return s # Find the end of the range of completions where s is a prefix of. i = first + 1 j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m][:len(s)] != s: j = m else: i = m + 1 last = i-1 if first == last: # only one possible completion return self.completions[first] # We should return the maximum prefix of first and last first_comp = self.completions[first] last_comp = self.completions[last] min_len = min(len(first_comp), len(last_comp)) i = len(s) while i < min_len and first_comp[i] == last_comp[i]: i += 1 return first_comp[:i]
Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.
_complete_string
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def _selection_changed(self): """Call when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start. """ cursel = int(self.listbox.curselection()[0]) self.listbox.see(cursel) lts = self.lasttypedstart selstart = self.completions[cursel] if self._binary_search(lts) == cursel: newstart = lts else: min_len = min(len(lts), len(selstart)) i = 0 while i < min_len and lts[i] == selstart[i]: i += 1 newstart = selstart[:i] self._change_start(newstart) if self.completions[cursel][:len(self.start)] == self.start: # start is a prefix of the selected completion self.listbox.configure(selectbackground=self.origselbackground, selectforeground=self.origselforeground) else: self.listbox.configure(selectbackground=self.listbox.cget("bg"), selectforeground=self.listbox.cget("fg")) # If there are more completions, show them, and call me again. if self.morecompletions: self.completions = self.morecompletions self.morecompletions = None self.listbox.delete(0, END) for item in self.completions: self.listbox.insert(END, item) self.listbox.select_set(self._binary_search(self.start)) self._selection_changed()
Call when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start.
_selection_changed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def show_window(self, comp_lists, index, complete, mode, userWantsWin): """Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list. """ # Handle the start we already have self.completions, self.morecompletions = comp_lists self.mode = mode self.startindex = self.widget.index(index) self.start = self.widget.get(self.startindex, "insert") if complete: completed = self._complete_string(self.start) start = self.start self._change_start(completed) i = self._binary_search(completed) if self.completions[i] == completed and \ (i == len(self.completions)-1 or self.completions[i+1][:len(completed)] != completed): # There is exactly one matching completion return completed == start self.userwantswindow = userWantsWin self.lasttypedstart = self.start # Put widgets in place self.autocompletewindow = acw = Toplevel(self.widget) # Put it in a position so that it is not seen. acw.wm_geometry("+10000+10000") # Make it float acw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w, "help", "noActivates") except TclError: pass self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL) self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, exportselection=False) for item in self.completions: listbox.insert(END, item) self.origselforeground = listbox.cget("selectforeground") self.origselbackground = listbox.cget("selectbackground") scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=True) acw.lift() # work around bug in Tk 8.5.18+ (issue #24570) # Initialize the listbox selection self.listbox.select_set(self._binary_search(self.start)) self._selection_changed() # bind events self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypress_event) for seq in KEYPRESS_SEQUENCES: self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq) self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, self.listselect_event) self.is_configuring = False self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) return None
Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list.
show_window
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def __init__(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False): """ parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest """ Toplevel.__init__(self, parent) self.withdraw() # Hide while setting geometry. 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.action = action self.current_key_sequences = current_key_sequences self.result = '' self.key_string = StringVar(self) self.key_string.set('') # Set self.modifiers, self.modifier_label. self.set_modifiers_for_platform() self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.create_widgets() self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) # Center dialog over parent (or below htest box). if not _utest: self.deiconify() # Geometry set, unhide. self.wait_window()
parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def set_modifiers_for_platform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # Short name.
Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering.
set_modifiers_for_platform
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def keys_ok(self, keys): """Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. """ final_key = self.list_keys_final.get('anchor') modifiers = self.get_modifiers() title = self.keyerror_title key_sequences = [key for keylist in self.current_key_sequences for key in keylist] if not keys.endswith('>'): self.showerror(title, parent=self, message='Missing the final Key') elif (not modifiers and final_key not in FUNCTION_KEYS + MOVE_KEYS): self.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (final_key not in FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' self.showerror(title=title, parent=self, message=msg) elif keys in key_sequences: msg = 'This key combination is already in use.' self.showerror(title=title, parent=self, message=msg) else: return True return False
Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set.
keys_ok
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def __init__(self, root, engine): '''Initialize root, engine, and top attributes. top (level widget): set in create_widgets() called from open(). text (Text searched): set in open(), only used in subclasses(). ent (ry): created in make_entry() called from create_entry(). row (of grid): 0 in create_widgets(), +1 in make_entry/frame(). default_command: set in subclasses, used in create_widgets(). title (of dialog): class attribute, override in subclasses. icon (of dialog): ditto, use unclear if cannot minimize dialog. ''' self.root = root self.bell = root.bell self.engine = engine self.top = None
Initialize root, engine, and top attributes. top (level widget): set in create_widgets() called from open(). text (Text searched): set in open(), only used in subclasses(). ent (ry): created in make_entry() called from create_entry(). row (of grid): 0 in create_widgets(), +1 in make_entry/frame(). default_command: set in subclasses, used in create_widgets(). title (of dialog): class attribute, override in subclasses. icon (of dialog): ditto, use unclear if cannot minimize dialog.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_widgets(self): '''Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row. ''' top = Toplevel(self.root) top.bind("<Return>", self.default_command) top.bind("<Escape>", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) top.wm_iconname(self.icon) self.top = top self.row = 0 self.top.grid_columnconfigure(0, pad=2, weight=0) self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100) self.create_entries() # row 0 (and maybe 1), cols 0, 1 self.create_option_buttons() # next row, cols 0, 1 self.create_other_buttons() # next row, cols 0, 1 self.create_command_buttons() # col 2, all rows
Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row.
create_widgets
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def make_entry(self, label_text, var): '''Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing. ''' label = Label(self.top, text=label_text) label.grid(row=self.row, column=0, sticky="nw") entry = Entry(self.top, textvariable=var, exportselection=0) entry.grid(row=self.row, column=1, sticky="nwe") self.row = self.row + 1 return entry, label
Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing.
make_entry
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def make_frame(self,labeltext=None): '''Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing. ''' if labeltext: label = Label(self.top, text=labeltext) label.grid(row=self.row, column=0, sticky="nw") else: label = '' frame = Frame(self.top) frame.grid(row=self.row, column=1, columnspan=1, sticky="nwe") self.row = self.row + 1 return frame, label
Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing.
make_frame
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_option_buttons(self): '''Return (filled frame, options) for testing. Options is a list of searchengine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label. ''' frame = self.make_frame("Options")[0] engine = self.engine options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")] if self.needwrapbutton: options.append((engine.wrapvar, "Wrap around")) for var, label in options: btn = Checkbutton(frame, variable=var, text=label) btn.pack(side="left", fill="both") return frame, options
Return (filled frame, options) for testing. Options is a list of searchengine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label.
create_option_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_other_buttons(self): '''Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons. ''' frame = self.make_frame("Direction")[0] var = self.engine.backvar others = [(1, 'Up'), (0, 'Down')] for val, label in others: btn = Radiobutton(frame, variable=var, value=val, text=label) btn.pack(side="left", fill="both") return frame, others
Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons.
create_other_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def get_end_linenumber(text): """Utility to get the last line's number in a Tk text widget.""" return int(float(text.index('end-1c')))
Utility to get the last line's number in a Tk text widget.
get_end_linenumber
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def get_widget_padding(widget): """Get the total padding of a Tk widget, including its border.""" # TODO: use also in codecontext.py manager = widget.winfo_manager() if manager == 'pack': info = widget.pack_info() elif manager == 'grid': info = widget.grid_info() else: raise ValueError(f"Unsupported geometry manager: {manager}") # All values are passed through getint(), since some # values may be pixel objects, which can't simply be added to ints. padx = sum(map(widget.tk.getint, [ info['padx'], widget.cget('padx'), widget.cget('border'), ])) pady = sum(map(widget.tk.getint, [ info['pady'], widget.cget('pady'), widget.cget('border'), ])) return padx, pady
Get the total padding of a Tk widget, including its border.
get_widget_padding
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_font(self): """Update the sidebar text font, usually after config changes.""" font = idleConf.GetFont(self.text, 'main', 'EditorWindow') self._update_font(font)
Update the sidebar text font, usually after config changes.
update_font
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_colors(self): """Update the sidebar text colors, usually after config changes.""" colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'normal') self._update_colors(foreground=colors['foreground'], background=colors['background'])
Update the sidebar text colors, usually after config changes.
update_colors
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_yscroll_event(self, *args, **kwargs): """Redirect vertical scrolling to the main editor text widget. The scroll bar is also updated. """ self.editwin.vbar.set(*args) self.sidebar_text.yview_moveto(args[0]) return 'break'
Redirect vertical scrolling to the main editor text widget. The scroll bar is also updated.
redirect_yscroll_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_focusin_event(self, event): """Redirect focus-in events to the main editor text widget.""" self.text.focus_set() return 'break'
Redirect focus-in events to the main editor text widget.
redirect_focusin_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_mousebutton_event(self, event, event_name): """Redirect mouse button events to the main editor text widget.""" self.text.focus_set() self.text.event_generate(event_name, x=0, y=event.y) return 'break'
Redirect mouse button events to the main editor text widget.
redirect_mousebutton_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_mousewheel_event(self, event): """Redirect mouse wheel events to the editwin text widget.""" self.text.event_generate('<MouseWheel>', x=0, y=event.y, delta=event.delta) return 'break'
Redirect mouse wheel events to the editwin text widget.
redirect_mousewheel_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def __init__(self, changed_callback): """ changed_callback - Callable, will be called after insert or delete operations with the current end line number. """ Delegator.__init__(self) self.changed_callback = changed_callback
changed_callback - Callable, will be called after insert or delete operations with the current end line number.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def drag_update_selection_and_insert_mark(y_coord): """Helper function for drag and selection event handlers.""" lineno = int(float(self.sidebar_text.index(f"@0,{y_coord}"))) a, b = sorted([start_line, lineno]) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", f"{a}.0", f"{b+1}.0") self.text.mark_set("insert", f"{lineno if lineno == a else lineno + 1}.0")
Helper function for drag and selection event handlers.
bind_events.drag_update_selection_and_insert_mark
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT