path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
cosmopolitan/third_party/python/Lib/idlelib/parenmatch.py | """ParenMatch -- for parenthesis matching.
When you hit a right paren, the cursor should move briefly to the left
paren. Paren here is used generically; the matching applies to
parentheses, square brackets, and curly braces.
"""
from idlelib.hyperparser import HyperParser
from idlelib.config import idleConf
_openers = {')':'(',']':'[','}':'{'}
CHECK_DELAY = 100 # milliseconds
class ParenMatch:
"""Highlight matching openers and closers, (), [], and {}.
There are three supported styles of paren matching. When a right
paren (opener) is typed:
opener -- highlight the matching left paren (closer);
parens -- highlight the left and right parens (opener and closer);
expression -- highlight the entire expression from opener to closer.
(For back compatibility, 'default' is a synonym for 'opener').
Flash-delay is the maximum milliseconds the highlighting remains.
Any cursor movement (key press or click) before that removes the
highlight. If flash-delay is 0, there is no maximum.
TODO:
- Augment bell() with mismatch warning in status window.
- Highlight when cursor is moved to the right of a closer.
This might be too expensive to check.
"""
RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>"
# We want the restore event be called before the usual return and
# backspace events.
RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>",
"<Key-Return>", "<Key-BackSpace>")
def __init__(self, editwin):
self.editwin = editwin
self.text = editwin.text
# Bind the check-restore event to the function restore_event,
# so that we can then use activate_restore (which calls event_add)
# and deactivate_restore (which calls event_delete).
editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME,
self.restore_event)
self.counter = 0
self.is_restore_active = 0
@classmethod
def reload(cls):
cls.STYLE = idleConf.GetOption(
'extensions','ParenMatch','style', default='opener')
cls.FLASH_DELAY = idleConf.GetOption(
'extensions','ParenMatch','flash-delay', type='int',default=500)
cls.BELL = idleConf.GetOption(
'extensions','ParenMatch','bell', type='bool', default=1)
cls.HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(),
'hilite')
def activate_restore(self):
"Activate mechanism to restore text from highlighting."
if not self.is_restore_active:
for seq in self.RESTORE_SEQUENCES:
self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
self.is_restore_active = True
def deactivate_restore(self):
"Remove restore event bindings."
if self.is_restore_active:
for seq in self.RESTORE_SEQUENCES:
self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
self.is_restore_active = False
def flash_paren_event(self, event):
"Handle editor 'show surrounding parens' event (menu or shortcut)."
indices = (HyperParser(self.editwin, "insert")
.get_surrounding_brackets())
self.finish_paren_event(indices)
return "break"
def paren_closed_event(self, event):
"Handle user input of closer."
# If user bound non-closer to <<paren-closed>>, quit.
closer = self.text.get("insert-1c")
if closer not in _openers:
return
hp = HyperParser(self.editwin, "insert-1c")
if not hp.is_in_code():
return
indices = hp.get_surrounding_brackets(_openers[closer], True)
self.finish_paren_event(indices)
return # Allow calltips to see ')'
def finish_paren_event(self, indices):
if indices is None and self.BELL:
self.text.bell()
return
self.activate_restore()
# self.create_tag(indices)
self.tagfuncs.get(self.STYLE, self.create_tag_expression)(self, indices)
# self.set_timeout()
(self.set_timeout_last if self.FLASH_DELAY else
self.set_timeout_none)()
def restore_event(self, event=None):
"Remove effect of doing match."
self.text.tag_delete("paren")
self.deactivate_restore()
self.counter += 1 # disable the last timer, if there is one.
def handle_restore_timer(self, timer_count):
if timer_count == self.counter:
self.restore_event()
# any one of the create_tag_XXX methods can be used depending on
# the style
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)
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)
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)
tagfuncs = {
'opener': create_tag_opener,
'default': create_tag_opener,
'parens': create_tag_parens,
'expression': create_tag_expression,
}
# any one of the set_timeout_XXX methods can be used depending on
# the style
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)
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))
ParenMatch.reload()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_parenmatch', verbosity=2)
| 7,204 | 184 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/config_key.py | """
Dialog for building Tkinter accelerator key bindings
"""
from tkinter import *
from tkinter.ttk import Scrollbar
from tkinter import messagebox
import string
import sys
class GetKeysDialog(Toplevel):
# Dialog title for invalid key sequence
keyerror_title = 'Key Sequence Error'
def __init__(self, parent, title, action, currentKeySequences,
*, _htest=False, _utest=False):
"""
action - string, the name of the virtual event these keys will be
mapped to
currentKeys - list, a list of all key sequence lists currently mapped
to virtual events, for overlap checking
_utest - bool, do not wait when running unittest
_htest - bool, change box location when running htest
"""
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.currentKeySequences = currentKeySequences
self.result = ''
self.keyString = StringVar(self)
self.keyString.set('')
self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label
self.modifier_vars = []
for modifier in self.modifiers:
variable = StringVar(self)
variable.set('')
self.modifier_vars.append(variable)
self.advanced = False
self.CreateWidgets()
self.LoadFinalKeyList()
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)
) ) #centre dialog over parent (or below htest box)
if not _utest:
self.deiconify() #geometry set, unhide
self.wait_window()
def showerror(self, *args, **kwargs):
# Make testing easier. Replace in #30751.
messagebox.showerror(*args, **kwargs)
def CreateWidgets(self):
frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
frameButtons=Frame(self)
frameButtons.pack(side=BOTTOM,fill=X)
self.buttonOK = Button(frameButtons,text='OK',
width=8,command=self.OK)
self.buttonOK.grid(row=0,column=0,padx=5,pady=5)
self.buttonCancel = Button(frameButtons,text='Cancel',
width=8,command=self.Cancel)
self.buttonCancel.grid(row=0,column=1,padx=5,pady=5)
self.frameKeySeqBasic = Frame(frameMain)
self.frameKeySeqAdvanced = Frame(frameMain)
self.frameControlsBasic = Frame(frameMain)
self.frameHelpAdvanced = Frame(frameMain)
self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
self.frameKeySeqBasic.lift()
self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5)
self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5)
self.frameControlsBasic.lift()
self.buttonLevel = Button(frameMain,command=self.ToggleLevel,
text='Advanced Key Binding Entry >>')
self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5)
labelTitleBasic = Label(self.frameKeySeqBasic,
text="New keys for '"+self.action+"' :")
labelTitleBasic.pack(anchor=W)
labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT,
textvariable=self.keyString,relief=GROOVE,borderwidth=2)
labelKeysBasic.pack(ipadx=5,ipady=5,fill=X)
self.modifier_checkbuttons = {}
column = 0
for modifier, variable in zip(self.modifiers, self.modifier_vars):
label = self.modifier_label.get(modifier, modifier)
check=Checkbutton(self.frameControlsBasic,
command=self.BuildKeyString,
text=label,variable=variable,onvalue=modifier,offvalue='')
check.grid(row=0,column=column,padx=2,sticky=W)
self.modifier_checkbuttons[modifier] = check
column += 1
labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
text=\
"Select the desired modifier keys\n"+
"above, and the final key from the\n"+
"list on the right.\n\n" +
"Use upper case Symbols when using\n" +
"the Shift modifier. (Letters will be\n" +
"converted automatically.)")
labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
selectmode=SINGLE)
self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
command=self.listKeysFinal.yview)
self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
self.buttonClear=Button(self.frameControlsBasic,
text='Clear Keys',command=self.ClearKeySeq)
self.buttonClear.grid(row=2,column=0,columnspan=4)
labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
text="Enter new binding(s) for '"+self.action+"' :\n"+
"(These bindings will not be checked for validity!)")
labelTitleAdvanced.pack(anchor=W)
self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
textvariable=self.keyString)
self.entryKeysAdvanced.pack(fill=X)
labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
text="Key bindings are specified using Tkinter keysyms as\n"+
"in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
"<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
"Upper case is used when the Shift modifier is present!\n\n" +
"'Emacs style' multi-keystroke bindings are specified as\n" +
"follows: <Control-x><Control-y>, where the first key\n" +
"is the 'do-nothing' keybinding.\n\n" +
"Multiple separate bindings for one action should be\n"+
"separated by a space, eg., <Alt-v> <Meta-v>." )
labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)
def SetModifiersForPlatform(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
def ToggleLevel(self):
if self.buttonLevel.cget('text')[:8]=='Advanced':
self.ClearKeySeq()
self.buttonLevel.config(text='<< Basic Key Binding Entry')
self.frameKeySeqAdvanced.lift()
self.frameHelpAdvanced.lift()
self.entryKeysAdvanced.focus_set()
self.advanced = True
else:
self.ClearKeySeq()
self.buttonLevel.config(text='Advanced Key Binding Entry >>')
self.frameKeySeqBasic.lift()
self.frameControlsBasic.lift()
self.advanced = False
def FinalKeySelected(self,event):
self.BuildKeyString()
def BuildKeyString(self):
keyList = modifiers = self.GetModifiers()
finalKey = self.listKeysFinal.get(ANCHOR)
if finalKey:
finalKey = self.TranslateKey(finalKey, modifiers)
keyList.append(finalKey)
self.keyString.set('<' + '-'.join(keyList) + '>')
def GetModifiers(self):
modList = [variable.get() for variable in self.modifier_vars]
return [mod for mod in modList if mod]
def ClearKeySeq(self):
self.listKeysFinal.select_clear(0,END)
self.listKeysFinal.yview(MOVETO, '0.0')
for variable in self.modifier_vars:
variable.set('')
self.keyString.set('')
def LoadFinalKeyList(self):
#these tuples are also available for use in validity checks
self.functionKeys=('F1','F2','F3','F4','F5','F6','F7','F8','F9',
'F10','F11','F12')
self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
self.whitespaceKeys=('Tab','Space','Return')
self.editKeys=('BackSpace','Delete','Insert')
self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
'Right Arrow','Up Arrow','Down Arrow')
#make a tuple of most of the useful common 'final' keys
keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
self.whitespaceKeys+self.editKeys+self.moveKeys)
self.listKeysFinal.insert(END, *keys)
def TranslateKey(self, key, modifiers):
"Translate from keycap symbol to the Tkinter keysym"
translateDict = {'Space':'space',
'~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
'%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
'(':'parenleft',')':'parenright','_':'underscore','-':'minus',
'+':'plus','=':'equal','{':'braceleft','}':'braceright',
'[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
':':'colon',',':'comma','.':'period','<':'less','>':'greater',
'/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
'Down Arrow': 'Down', 'Tab':'Tab'}
if key in translateDict:
key = translateDict[key]
if 'Shift' in modifiers and key in string.ascii_lowercase:
key = key.upper()
key = 'Key-' + key
return key
def OK(self, event=None):
keys = self.keyString.get().strip()
if not keys:
self.showerror(title=self.keyerror_title, parent=self,
message="No key specified.")
return
if (self.advanced or self.KeysOK(keys)) and self.bind_ok(keys):
self.result = keys
self.grab_release()
self.destroy()
def Cancel(self, event=None):
self.result=''
self.grab_release()
self.destroy()
def KeysOK(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.
'''
finalKey = self.listKeysFinal.get(ANCHOR)
modifiers = self.GetModifiers()
keysOK = False
title = self.keyerror_title
key_sequences = [key for keylist in self.currentKeySequences
for key in keylist]
if not keys.endswith('>'):
self.showerror(title, parent=self,
message='Missing the final Key')
elif (not modifiers
and finalKey not in self.functionKeys + self.moveKeys):
self.showerror(title=title, parent=self,
message='No modifier key(s) specified.')
elif (modifiers == ['Shift']) \
and (finalKey not in
self.functionKeys + self.moveKeys + ('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:
keysOK = True
return keysOK
def bind_ok(self, keys):
"Return True if Tcl accepts the new keys else show message."
try:
binding = self.bind(keys, lambda: None)
except TclError as err:
self.showerror(
title=self.keyerror_title, parent=self,
message=(f'The entered key sequence is not accepted.\n\n'
f'Error: {err}'))
return False
else:
self.unbind(keys, binding)
return True
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_config_key', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(GetKeysDialog)
| 13,408 | 301 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/mainmenu.py | """Define the menu contents, hotkeys, and event bindings.
There is additional configuration information in the EditorWindow class (and
subclasses): the menus are created there based on the menu_specs (class)
variable, and menus not created are silently skipped in the code here. This
makes it possible, for example, to define a Debug menu which is only present in
the PythonShell window, and a Format menu which is only present in the Editor
windows.
"""
from importlib.util import find_spec
from idlelib.config import idleConf
# Warning: menudefs is altered in macosx.overrideRootMenu()
# after it is determined that an OS X Aqua Tk is in use,
# which cannot be done until after Tk() is first called.
# Do not alter the 'file', 'options', or 'help' cascades here
# without altering overrideRootMenu() as well.
# TODO: Make this more robust
menudefs = [
# underscore prefixes character to underscore
('file', [
('_New File', '<<open-new-window>>'),
('_Open...', '<<open-window-from-file>>'),
('Open _Module...', '<<open-module>>'),
('Module _Browser', '<<open-class-browser>>'),
('_Path Browser', '<<open-path-browser>>'),
None,
('_Save', '<<save-window>>'),
('Save _As...', '<<save-window-as-file>>'),
('Save Cop_y As...', '<<save-copy-of-window-as-file>>'),
None,
('Prin_t Window', '<<print-window>>'),
None,
('_Close', '<<close-window>>'),
('E_xit', '<<close-all-windows>>'),
]),
('edit', [
('_Undo', '<<undo>>'),
('_Redo', '<<redo>>'),
None,
('Cu_t', '<<cut>>'),
('_Copy', '<<copy>>'),
('_Paste', '<<paste>>'),
('Select _All', '<<select-all>>'),
None,
('_Find...', '<<find>>'),
('Find A_gain', '<<find-again>>'),
('Find _Selection', '<<find-selection>>'),
('Find in Files...', '<<find-in-files>>'),
('R_eplace...', '<<replace>>'),
('Go to _Line', '<<goto-line>>'),
('S_how Completions', '<<force-open-completions>>'),
('E_xpand Word', '<<expand-word>>'),
('Show C_all Tip', '<<force-open-calltip>>'),
('Show Surrounding P_arens', '<<flash-paren>>'),
]),
('format', [
('_Indent Region', '<<indent-region>>'),
('_Dedent Region', '<<dedent-region>>'),
('Comment _Out Region', '<<comment-region>>'),
('U_ncomment Region', '<<uncomment-region>>'),
('Tabify Region', '<<tabify-region>>'),
('Untabify Region', '<<untabify-region>>'),
('Toggle Tabs', '<<toggle-tabs>>'),
('New Indent Width', '<<change-indentwidth>>'),
('F_ormat Paragraph', '<<format-paragraph>>'),
('S_trip Trailing Whitespace', '<<do-rstrip>>'),
]),
('run', [
('Python Shell', '<<open-python-shell>>'),
('C_heck Module', '<<check-module>>'),
('R_un Module', '<<run-module>>'),
]),
('shell', [
('_View Last Restart', '<<view-restart>>'),
('_Restart Shell', '<<restart-shell>>'),
None,
('_Interrupt Execution', '<<interrupt-execution>>'),
]),
('debug', [
('_Go to File/Line', '<<goto-file-line>>'),
('!_Debugger', '<<toggle-debugger>>'),
('_Stack Viewer', '<<open-stack-viewer>>'),
('!_Auto-open Stack Viewer', '<<toggle-jit-stack-viewer>>'),
]),
('options', [
('Configure _IDLE', '<<open-config-dialog>>'),
('_Code Context', '<<toggle-code-context>>'),
]),
('window', [
('Zoom Height', '<<zoom-height>>'),
]),
('help', [
('_About IDLE', '<<about-idle>>'),
None,
('_IDLE Help', '<<help>>'),
('Python _Docs', '<<python-docs>>'),
]),
]
if find_spec('turtledemo'):
menudefs[-1][1].append(('Turtle Demo', '<<open-turtle-demo>>'))
default_keydefs = idleConf.GetCurrentKeySet()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_mainmenu', verbosity=2)
| 3,703 | 120 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/calltip.py | """Pop up a reminder of how to call a function.
Call Tips are floating windows which display function, class, and method
parameter and docstring information when you type an opening parenthesis, and
which disappear when you type a closing parenthesis.
"""
import inspect
import re
import sys
import textwrap
import types
from idlelib import calltip_w
from idlelib.hyperparser import HyperParser
import __main__
class Calltip:
def __init__(self, editwin=None):
if editwin is None: # subprocess and test
self.editwin = None
else:
self.editwin = editwin
self.text = editwin.text
self.active_calltip = None
self._calltip_window = self._make_tk_calltip_window
def close(self):
self._calltip_window = None
def _make_tk_calltip_window(self):
# See __init__ for usage
return calltip_w.CalltipWindow(self.text)
def _remove_calltip_window(self, event=None):
if self.active_calltip:
self.active_calltip.hidetip()
self.active_calltip = None
def force_open_calltip_event(self, event):
"The user selected the menu entry or hotkey, open the tip."
self.open_calltip(True)
return "break"
def try_open_calltip_event(self, event):
"""Happens when it would be nice to open a calltip, but not really
necessary, for example after an opening bracket, so function calls
won't be made.
"""
self.open_calltip(False)
def refresh_calltip_event(self, event):
if self.active_calltip and self.active_calltip.tipwindow:
self.open_calltip(False)
def open_calltip(self, evalfuncs):
self._remove_calltip_window()
hp = HyperParser(self.editwin, "insert")
sur_paren = hp.get_surrounding_brackets('(')
if not sur_paren:
return
hp.set_index(sur_paren[0])
expression = hp.get_expression()
if not expression:
return
if not evalfuncs and (expression.find('(') != -1):
return
argspec = self.fetch_tip(expression)
if not argspec:
return
self.active_calltip = self._calltip_window()
self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1])
def fetch_tip(self, expression):
"""Return the argument list and docstring of a function or class.
If there is a Python subprocess, get the calltip there. Otherwise,
either this fetch_tip() is running in the subprocess or it was
called in an IDLE running without the subprocess.
The subprocess environment is that of the most recently run script. If
two unrelated modules are being edited some calltips in the current
module may be inoperative if the module was not the last to run.
To find methods, fetch_tip must be fed a fully qualified name.
"""
try:
rpcclt = self.editwin.flist.pyshell.interp.rpcclt
except AttributeError:
rpcclt = None
if rpcclt:
return rpcclt.remotecall("exec", "get_the_calltip",
(expression,), {})
else:
return get_argspec(get_entity(expression))
def get_entity(expression):
"""Return the object corresponding to expression evaluated
in a namespace spanning sys.modules and __main.dict__.
"""
if expression:
namespace = sys.modules.copy()
namespace.update(__main__.__dict__)
try:
return eval(expression, namespace)
except BaseException:
# An uncaught exception closes idle, and eval can raise any
# exception, especially if user classes are involved.
return None
# The following are used in get_argspec and some in tests
_MAX_COLS = 85
_MAX_LINES = 5 # enough for bytes
_INDENT = ' '*4 # for wrapped signatures
_first_param = re.compile(r'(?<=\()\w*\,?\s*')
_default_callable_argspec = "See source or doc"
_invalid_method = "invalid method signature"
_argument_positional = "\n['/' marks preceding arguments as positional-only]\n"
def get_argspec(ob):
'''Return a string describing the signature of a callable object, or ''.
For Python-coded functions and methods, the first line is introspected.
Delete 'self' parameter for classes (.__init__) and bound methods.
The next lines are the first lines of the doc string up to the first
empty line or _MAX_LINES. For builtins, this typically includes
the arguments in addition to the return value.
'''
argspec = default = ""
try:
ob_call = ob.__call__
except BaseException:
return default
fob = ob_call if isinstance(ob_call, types.MethodType) else ob
try:
argspec = str(inspect.signature(fob))
except ValueError as err:
msg = str(err)
if msg.startswith(_invalid_method):
return _invalid_method
if '/' in argspec:
"""Using AC's positional argument should add the explain"""
argspec += _argument_positional
if isinstance(fob, type) and argspec == '()':
"""fob with no argument, use default callable argspec"""
argspec = _default_callable_argspec
lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT)
if len(argspec) > _MAX_COLS else [argspec] if argspec else [])
if isinstance(ob_call, types.MethodType):
doc = ob_call.__doc__
else:
doc = getattr(ob, "__doc__", "")
if doc:
for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]:
line = line.strip()
if not line:
break
if len(line) > _MAX_COLS:
line = line[: _MAX_COLS - 3] + '...'
lines.append(line)
argspec = '\n'.join(lines)
if not argspec:
argspec = _default_callable_argspec
return argspec
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_calltip', verbosity=2)
| 6,067 | 179 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/search.py | from tkinter import TclError
from idlelib import searchengine
from idlelib.searchbase import SearchDialogBase
def _setup(text):
"Create or find the singleton SearchDialog instance."
root = text._root()
engine = searchengine.get(root)
if not hasattr(engine, "_searchdialog"):
engine._searchdialog = SearchDialog(root, engine)
return engine._searchdialog
def find(text):
"Handle the editor edit menu item and corresponding event."
pat = text.get("sel.first", "sel.last")
return _setup(text).open(text, pat) # Open is inherited from SDBase.
def find_again(text):
"Handle the editor edit menu item and corresponding event."
return _setup(text).find_again(text)
def find_selection(text):
"Handle the editor edit menu item and corresponding event."
return _setup(text).find_selection(text)
class SearchDialog(SearchDialogBase):
def create_widgets(self):
SearchDialogBase.create_widgets(self)
self.make_button("Find Next", self.default_command, 1)
def default_command(self, event=None):
if not self.engine.getprog():
return
self.find_again(self.text)
def find_again(self, text):
if not self.engine.getpat():
self.open(text)
return False
if not self.engine.getprog():
return False
res = self.engine.search_text(text)
if res:
line, m = res
i, j = m.span()
first = "%d.%d" % (line, i)
last = "%d.%d" % (line, j)
try:
selfirst = text.index("sel.first")
sellast = text.index("sel.last")
if selfirst == first and sellast == last:
self.bell()
return False
except TclError:
pass
text.tag_remove("sel", "1.0", "end")
text.tag_add("sel", first, last)
text.mark_set("insert", self.engine.isback() and first or last)
text.see("insert")
return True
else:
self.bell()
return False
def find_selection(self, text):
pat = text.get("sel.first", "sel.last")
if pat:
self.engine.setcookedpat(pat)
return self.find_again(text)
def _search_dialog(parent): # htest #
"Display search test box."
from tkinter import Toplevel, Text
from tkinter.ttk import Button
box = Toplevel(parent)
box.title("Test SearchDialog")
x, y = map(int, parent.geometry().split('+')[1:])
box.geometry("+%d+%d" % (x, y + 175))
text = Text(box, inactiveselectbackground='gray')
text.pack()
text.insert("insert","This is a sample string.\n"*5)
def show_find():
text.tag_add('sel', '1.0', 'end')
_setup(text).open(text)
text.tag_remove('sel', '1.0', 'end')
button = Button(box, text="Search (selection ignored)", command=show_find)
button.pack()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_search', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_search_dialog)
| 3,164 | 102 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/help.py | """ help.py: Implement the Idle help menu.
Contents are subject to revision at any time, without notice.
Help => About IDLE: diplay About Idle dialog
<to be moved here from help_about.py>
Help => IDLE Help: Display help.html with proper formatting.
Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html
(help.copy_strip)=> Lib/idlelib/help.html
HelpParser - Parse help.html and render to tk Text.
HelpText - Display formatted help.html.
HelpFrame - Contain text, scrollbar, and table-of-contents.
(This will be needed for display in a future tabbed window.)
HelpWindow - Display HelpFrame in a standalone window.
copy_strip - Copy idle.html to help.html, rstripping each line.
show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog.
"""
from html.parser import HTMLParser
from os.path import abspath, dirname, isfile, join
from platform import python_version
from tkinter import Toplevel, Frame, Text, Menu
from tkinter.ttk import Menubutton, Scrollbar
from tkinter import font as tkfont
from idlelib.config import idleConf
## About IDLE ##
## IDLE Help ##
class HelpParser(HTMLParser):
"""Render help.html into a text widget.
The overridden handle_xyz methods handle a subset of html tags.
The supplied text should have the needed tag configurations.
The behavior for unsupported tags, such as table, is undefined.
If the tags generated by Sphinx change, this class, especially
the handle_starttag and handle_endtags methods, might have to also.
"""
def __init__(self, text):
HTMLParser.__init__(self, convert_charrefs=True)
self.text = text # text widget we're rendering into
self.tags = '' # current block level text tags to apply
self.chartags = '' # current character level text tags
self.show = False # used so we exclude page navigation
self.hdrlink = False # used so we don't show header links
self.level = 0 # indentation level
self.pre = False # displaying preformatted text
self.hprefix = '' # prefix such as '25.5' to strip from headings
self.nested_dl = False # if we're in a nested <dl>
self.simplelist = False # simple list (no double spacing)
self.toc = [] # pair headers with text indexes for toc
self.header = '' # text within header tags for toc
def indent(self, amt=1):
self.level += amt
self.tags = '' if self.level == 0 else 'l'+str(self.level)
def handle_starttag(self, tag, attrs):
"Handle starttags in help.html."
class_ = ''
for a, v in attrs:
if a == 'class':
class_ = v
s = ''
if tag == 'div' and class_ == 'section':
self.show = True # start of main content
elif tag == 'div' and class_ == 'sphinxsidebar':
self.show = False # end of main content
elif tag == 'p' and class_ != 'first':
s = '\n\n'
elif tag == 'span' and class_ == 'pre':
self.chartags = 'pre'
elif tag == 'span' and class_ == 'versionmodified':
self.chartags = 'em'
elif tag == 'em':
self.chartags = 'em'
elif tag in ['ul', 'ol']:
if class_.find('simple') != -1:
s = '\n'
self.simplelist = True
else:
self.simplelist = False
self.indent()
elif tag == 'dl':
if self.level > 0:
self.nested_dl = True
elif tag == 'li':
s = '\n* ' if self.simplelist else '\n\n* '
elif tag == 'dt':
s = '\n\n' if not self.nested_dl else '\n' # avoid extra line
self.nested_dl = False
elif tag == 'dd':
self.indent()
s = '\n'
elif tag == 'pre':
self.pre = True
if self.show:
self.text.insert('end', '\n\n')
self.tags = 'preblock'
elif tag == 'a' and class_ == 'headerlink':
self.hdrlink = True
elif tag == 'h1':
self.tags = tag
elif tag in ['h2', 'h3']:
if self.show:
self.header = ''
self.text.insert('end', '\n\n')
self.tags = tag
if self.show:
self.text.insert('end', s, (self.tags, self.chartags))
def handle_endtag(self, tag):
"Handle endtags in help.html."
if tag in ['h1', 'h2', 'h3']:
self.indent(0) # clear tag, reset indent
if self.show:
indent = (' ' if tag == 'h3' else
' ' if tag == 'h2' else
'')
self.toc.append((indent+self.header, self.text.index('insert')))
elif tag in ['span', 'em']:
self.chartags = ''
elif tag == 'a':
self.hdrlink = False
elif tag == 'pre':
self.pre = False
self.tags = ''
elif tag in ['ul', 'dd', 'ol']:
self.indent(amt=-1)
def handle_data(self, data):
"Handle date segments in help.html."
if self.show and not self.hdrlink:
d = data if self.pre else data.replace('\n', ' ')
if self.tags == 'h1':
try:
self.hprefix = d[0:d.index(' ')]
except ValueError:
self.hprefix = ''
if self.tags in ['h1', 'h2', 'h3']:
if (self.hprefix != '' and
d[0:len(self.hprefix)] == self.hprefix):
d = d[len(self.hprefix):]
self.header += d.strip()
self.text.insert('end', d, (self.tags, self.chartags))
class HelpText(Text):
"Display help.html."
def __init__(self, parent, filename):
"Configure tags and feed file to parser."
uwide = idleConf.GetOption('main', 'EditorWindow', 'width', type='int')
uhigh = idleConf.GetOption('main', 'EditorWindow', 'height', type='int')
uhigh = 3 * uhigh // 4 # lines average 4/3 of editor line height
Text.__init__(self, parent, wrap='word', highlightthickness=0,
padx=5, borderwidth=0, width=uwide, height=uhigh)
normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica'])
fixedfont = self.findfont(['TkFixedFont', 'monaco', 'courier'])
self['font'] = (normalfont, 12)
self.tag_configure('em', font=(normalfont, 12, 'italic'))
self.tag_configure('h1', font=(normalfont, 20, 'bold'))
self.tag_configure('h2', font=(normalfont, 18, 'bold'))
self.tag_configure('h3', font=(normalfont, 15, 'bold'))
self.tag_configure('pre', font=(fixedfont, 12), background='#f6f6ff')
self.tag_configure('preblock', font=(fixedfont, 10), lmargin1=25,
borderwidth=1, relief='solid', background='#eeffcc')
self.tag_configure('l1', lmargin1=25, lmargin2=25)
self.tag_configure('l2', lmargin1=50, lmargin2=50)
self.tag_configure('l3', lmargin1=75, lmargin2=75)
self.tag_configure('l4', lmargin1=100, lmargin2=100)
self.parser = HelpParser(self)
with open(filename, encoding='utf-8') as f:
contents = f.read()
self.parser.feed(contents)
self['state'] = 'disabled'
def findfont(self, names):
"Return name of first font family derived from names."
for name in names:
if name.lower() in (x.lower() for x in tkfont.names(root=self)):
font = tkfont.Font(name=name, exists=True, root=self)
return font.actual()['family']
elif name.lower() in (x.lower()
for x in tkfont.families(root=self)):
return name
class HelpFrame(Frame):
"Display html text, scrollbar, and toc."
def __init__(self, parent, filename):
Frame.__init__(self, parent)
# keep references to widgets for test access.
self.text = text = HelpText(self, filename)
self['background'] = text['background']
self.toc = toc = self.toc_menu(text)
self.scroll = scroll = Scrollbar(self, command=text.yview)
text['yscrollcommand'] = scroll.set
self.rowconfigure(0, weight=1)
self.columnconfigure(1, weight=1) # text
toc.grid(row=0, column=0, sticky='nw')
text.grid(row=0, column=1, sticky='nsew')
scroll.grid(row=0, column=2, sticky='ns')
def toc_menu(self, text):
"Create table of contents as drop-down menu."
toc = Menubutton(self, text='TOC')
drop = Menu(toc, tearoff=False)
for lbl, dex in text.parser.toc:
drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex))
toc['menu'] = drop
return toc
class HelpWindow(Toplevel):
"Display frame with rendered html."
def __init__(self, parent, filename, title):
Toplevel.__init__(self, parent)
self.wm_title(title)
self.protocol("WM_DELETE_WINDOW", self.destroy)
HelpFrame(self, filename).grid(column=0, row=0, sticky='nsew')
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
def copy_strip():
"""Copy idle.html to idlelib/help.html, stripping trailing whitespace.
Files with trailing whitespace cannot be pushed to the git cpython
repository. For 3.x (on Windows), help.html is generated, after
editing idle.rst on the master branch, with
sphinx-build -bhtml . build/html
python_d.exe -c "from idlelib.help import copy_strip; copy_strip()"
Check build/html/library/idle.html, the help.html diff, and the text
displayed by Help => IDLE Help. Add a blurb and create a PR.
It can be worthwhile to occasionally generate help.html without
touching idle.rst. Changes to the master version and to the doc
build system may result in changes that should not changed
the displayed text, but might break HelpParser.
As long as master and maintenance versions of idle.rst remain the
same, help.html can be backported. The internal Python version
number is not displayed. If maintenance idle.rst diverges from
the master version, then instead of backporting help.html from
master, repeat the proceedure above to generate a maintenance
version.
"""
src = join(abspath(dirname(dirname(dirname(__file__)))),
'Doc', 'build', 'html', 'library', 'idle.html')
dst = join(abspath(dirname(__file__)), 'help.html')
with open(src, 'rb') as inn,\
open(dst, 'wb') as out:
for line in inn:
out.write(line.rstrip() + b'\n')
print(f'{src} copied to {dst}')
def show_idlehelp(parent):
"Create HelpWindow; called from Idle Help event handler."
filename = join(abspath(dirname(__file__)), 'help.html')
if not isfile(filename):
# try copy_strip, present message
return
HelpWindow(parent, filename, 'IDLE Help (%s)' % python_version())
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_help', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(show_idlehelp)
| 11,325 | 286 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/config-main.def | # IDLE reads several config files to determine user preferences. This
# file is the default config file for general idle settings.
#
# When IDLE starts, it will look in
# the following two sets of files, in order:
#
# default configuration files in idlelib
# --------------------------------------
# config-main.def default general config file
# config-extensions.def default extension config file
# config-highlight.def default highlighting config file
# config-keys.def default keybinding config file
#
# user configuration files in ~/.idlerc
# -------------------------------------
# config-main.cfg user general config file
# config-extensions.cfg user extension config file
# config-highlight.cfg user highlighting config file
# config-keys.cfg user keybinding config file
#
# On Windows, the default location of the home directory ('~' above)
# depends on the version. For Windows 10, it is C:\Users\<username>.
#
# Any options the user saves through the config dialog will be saved to
# the relevant user config file. Reverting any general or extension
# setting to the default causes that entry to be wiped from the user
# file and re-read from the default file. This rule applies to each
# item, except that the three editor font items are saved as a group.
#
# User highlighting themes and keybinding sets must have (section) names
# distinct from the default names. All items are added and saved as a
# group. They are retained unless specifically deleted within the config
# dialog. Choosing one of the default themes or keysets just applies the
# relevant settings from the default file.
#
# Additional help sources are listed in the [HelpFiles] section below
# and should be viewable by a web browser (or the Windows Help viewer in
# the case of .chm files). These sources will be listed on the Help
# menu. The pattern, and two examples, are
#
# <sequence_number = menu item;/path/to/help/source>
# 1 = IDLE;C:/Programs/Python36/Lib/idlelib/help.html
# 2 = Pillow;https://pillow.readthedocs.io/en/latest/
#
# You can't use a semi-colon in a menu item or path. The path will be
# platform specific because of path separators, drive specs etc.
#
# The default files should not be edited except to add new sections to
# config-extensions.def for added extensions . The user files should be
# modified through the Settings dialog.
[General]
editor-on-startup= 0
autosave= 0
print-command-posix=lpr %%s
print-command-win=start /min notepad /p %%s
delete-exitfunc= 1
[EditorWindow]
width= 80
height= 40
font= TkFixedFont
# For TkFixedFont, the actual size and boldness are obtained from tk
# and override 10 and 0. See idlelib.config.IdleConf.GetFont
font-size= 10
font-bold= 0
encoding= none
[PyShell]
auto-squeeze-min-lines= 50
[Indent]
use-spaces= 1
num-spaces= 4
[Theme]
default= 1
name= IDLE Classic
name2=
# name2 set in user config-main.cfg for themes added after 2015 Oct 1
[Keys]
default= 1
name=
name2=
# name2 set in user config-main.cfg for keys added after 2016 July 1
[History]
cyclic=1
[HelpFiles]
| 3,128 | 92 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/colorizer.py | import builtins
import keyword
import re
import time
from idlelib.config import idleConf
from idlelib.delegator import Delegator
DEBUG = False
def any(name, alternates):
"Return a named group pattern matching list of alternates."
return "(?P<%s>" % name + "|".join(alternates) + ")"
def make_pat():
kw = r"\b" + any("KEYWORD", keyword.kwlist + ['async', 'await']) + r"\b"
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_') and \
name not in keyword.kwlist]
builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b"
comment = any("COMMENT", [r"#[^\n]*"])
stringprefix = r"(?i:r|u|f|fr|rf|b|br|rb)?"
sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?'
sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?"
dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?'
string = any("STRING", [sq3string, dq3string, sqstring, dqstring])
return kw + "|" + builtin + "|" + comment + "|" + string +\
"|" + any("SYNC", [r"\n"])
prog = re.compile(make_pat(), re.S)
idprog = re.compile(r"\s+(\w+)", re.S)
def color_config(text):
"""Set color options of Text widget.
If ColorDelegator is used, this should be called first.
"""
# Called from htest, TextFrame, Editor, and Turtledemo.
# Not automatic because ColorDelegator does not know 'text'.
theme = idleConf.CurrentTheme()
normal_colors = idleConf.GetHighlight(theme, 'normal')
cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
select_colors = idleConf.GetHighlight(theme, 'hilite')
text.config(
foreground=normal_colors['foreground'],
background=normal_colors['background'],
insertbackground=cursor_color,
selectforeground=select_colors['foreground'],
selectbackground=select_colors['background'],
inactiveselectbackground=select_colors['background'], # new in 8.5
)
class ColorDelegator(Delegator):
def __init__(self):
Delegator.__init__(self)
self.prog = prog
self.idprog = idprog
self.LoadTagDefs()
def setdelegate(self, delegate):
if self.delegate is not None:
self.unbind("<<toggle-auto-coloring>>")
Delegator.setdelegate(self, delegate)
if delegate is not None:
self.config_colors()
self.bind("<<toggle-auto-coloring>>", self.toggle_colorize_event)
self.notify_range("1.0", "end")
else:
# No delegate - stop any colorizing
self.stop_colorizing = True
self.allow_colorizing = False
def config_colors(self):
for tag, cnf in self.tagdefs.items():
if cnf:
self.tag_configure(tag, **cnf)
self.tag_raise('sel')
def LoadTagDefs(self):
theme = idleConf.CurrentTheme()
self.tagdefs = {
"COMMENT": idleConf.GetHighlight(theme, "comment"),
"KEYWORD": idleConf.GetHighlight(theme, "keyword"),
"BUILTIN": idleConf.GetHighlight(theme, "builtin"),
"STRING": idleConf.GetHighlight(theme, "string"),
"DEFINITION": idleConf.GetHighlight(theme, "definition"),
"SYNC": {'background':None,'foreground':None},
"TODO": {'background':None,'foreground':None},
"ERROR": idleConf.GetHighlight(theme, "error"),
# The following is used by ReplaceDialog:
"hit": idleConf.GetHighlight(theme, "hit"),
}
if DEBUG: print('tagdefs',self.tagdefs)
def insert(self, index, chars, tags=None):
index = self.index(index)
self.delegate.insert(index, chars, tags)
self.notify_range(index, index + "+%dc" % len(chars))
def delete(self, index1, index2=None):
index1 = self.index(index1)
self.delegate.delete(index1, index2)
self.notify_range(index1)
after_id = None
allow_colorizing = True
colorizing = False
def notify_range(self, index1, index2=None):
self.tag_add("TODO", index1, index2)
if self.after_id:
if DEBUG: print("colorizing already scheduled")
return
if self.colorizing:
self.stop_colorizing = True
if DEBUG: print("stop colorizing")
if self.allow_colorizing:
if DEBUG: print("schedule colorizing")
self.after_id = self.after(1, self.recolorize)
close_when_done = None # Window to be closed when done colorizing
def close(self, close_when_done=None):
if self.after_id:
after_id = self.after_id
self.after_id = None
if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id)
self.allow_colorizing = False
self.stop_colorizing = True
if close_when_done:
if not self.colorizing:
close_when_done.destroy()
else:
self.close_when_done = close_when_done
def toggle_colorize_event(self, event):
if self.after_id:
after_id = self.after_id
self.after_id = None
if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id)
if self.allow_colorizing and self.colorizing:
if DEBUG: print("stop colorizing")
self.stop_colorizing = True
self.allow_colorizing = not self.allow_colorizing
if self.allow_colorizing and not self.colorizing:
self.after_id = self.after(1, self.recolorize)
if DEBUG:
print("auto colorizing turned",\
self.allow_colorizing and "on" or "off")
return "break"
def recolorize(self):
self.after_id = None
if not self.delegate:
if DEBUG: print("no delegate")
return
if not self.allow_colorizing:
if DEBUG: print("auto colorizing is off")
return
if self.colorizing:
if DEBUG: print("already colorizing")
return
try:
self.stop_colorizing = False
self.colorizing = True
if DEBUG: print("colorizing...")
t0 = time.perf_counter()
self.recolorize_main()
t1 = time.perf_counter()
if DEBUG: print("%.3f seconds" % (t1-t0))
finally:
self.colorizing = False
if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"):
if DEBUG: print("reschedule colorizing")
self.after_id = self.after(1, self.recolorize)
if self.close_when_done:
top = self.close_when_done
self.close_when_done = None
top.destroy()
def recolorize_main(self):
next = "1.0"
while True:
item = self.tag_nextrange("TODO", next)
if not item:
break
head, tail = item
self.tag_remove("SYNC", head, tail)
item = self.tag_prevrange("SYNC", head)
if item:
head = item[1]
else:
head = "1.0"
chars = ""
next = head
lines_to_get = 1
ok = False
while not ok:
mark = next
next = self.index(mark + "+%d lines linestart" %
lines_to_get)
lines_to_get = min(lines_to_get * 2, 100)
ok = "SYNC" in self.tag_names(next + "-1c")
line = self.get(mark, next)
##print head, "get", mark, next, "->", repr(line)
if not line:
return
for tag in self.tagdefs:
self.tag_remove(tag, mark, next)
chars = chars + line
m = self.prog.search(chars)
while m:
for key, value in m.groupdict().items():
if value:
a, b = m.span(key)
self.tag_add(key,
head + "+%dc" % a,
head + "+%dc" % b)
if value in ("def", "class"):
m1 = self.idprog.match(chars, b)
if m1:
a, b = m1.span(1)
self.tag_add("DEFINITION",
head + "+%dc" % a,
head + "+%dc" % b)
m = self.prog.search(chars, m.end())
if "SYNC" in self.tag_names(next + "-1c"):
head = next
chars = ""
else:
ok = False
if not ok:
# We're in an inconsistent state, and the call to
# update may tell us to stop. It may also change
# the correct value for "next" (since this is a
# line.col string, not a true mark). So leave a
# crumb telling the next invocation to resume here
# in case update tells us to leave.
self.tag_add("TODO", next)
self.update()
if self.stop_colorizing:
if DEBUG: print("colorizing stopped")
return
def removecolors(self):
for tag in self.tagdefs:
self.tag_remove(tag, "1.0", "end")
def _color_delegator(parent): # htest #
from tkinter import Toplevel, Text
from idlelib.percolator import Percolator
top = Toplevel(parent)
top.title("Test ColorDelegator")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("700x250+%d+%d" % (x + 20, y + 175))
source = (
"if True: int ('1') # keyword, builtin, string, comment\n"
"elif False: print(0)\n"
"else: float(None)\n"
"if iF + If + IF: 'keyword matching must respect case'\n"
"if'': x or'' # valid string-keyword no-space combinations\n"
"async def f(): await g()\n"
"# All valid prefixes for unicode and byte strings should be colored.\n"
"'x', '''x''', \"x\", \"\"\"x\"\"\"\n"
"r'x', u'x', R'x', U'x', f'x', F'x'\n"
"fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x'\n"
"b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x'.rB'x',Rb'x',RB'x'\n"
"# Invalid combinations of legal characters should be half colored.\n"
"ur'x', ru'x', uf'x', fu'x', UR'x', ufr'x', rfu'x', xf'x', fx'x'\n"
)
text = Text(top, background="white")
text.pack(expand=1, fill="both")
text.insert("insert", source)
text.focus_set()
color_config(text)
p = Percolator(text)
d = ColorDelegator()
p.insertfilter(d)
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_colorizer', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_color_delegator)
| 11,275 | 297 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/NEWS.txt | What's New in IDLE 3.6.8
Released on 2018-12-20?
**This is the final 3.6 bugfix maintenance release**
======================================
bpo-34864: When starting IDLE on MacOS, warn if the system setting
"Prefer tabs when opening documents" is "Always". As previous
documented for this issue, running IDLE with this setting causes
problems. If the setting is changed while IDLE is running,
there will be no warning until IDLE is restarted.
bpo-35213: Where appropriate, use 'macOS' in idlelib.
bpo-34864: Document two IDLE on MacOS issues. The System Preferences
Dock "prefer tabs always" setting disables some IDLE features.
Menus are a bit different than as described for Windows and Linux.
bpo-35202: Remove unused imports in idlelib.
bpo-33000: Document that IDLE's shell has no line limit.
A program that runs indefinitely can overfill memory.
bpo-23220: Explain how IDLE's Shell displays output.
Add new subsection "User output in Shell".
bpo-35099: Improve the doc about IDLE running user code.
"IDLE -- console differences" is renamed "Running user code".
It mostly covers the implications of using custom sys.stdxxx objects.
bpo-35097: Add IDLE doc subsection explaining editor windows.
Topics include opening, title and status bars, .py* extension, and running.
Issue 35093: Document the IDLE document viewer in the IDLE doc.
Add a paragraph in "Help and preferences", "Help sources" subsection.
bpo-1529353: Explain Shell text squeezing in the IDLE doc.
bpo-35088: Update idlelib.help.copy_string docstring.
We now use git and backporting instead of hg and forward merging.
bpo-35087: Update idlelib help files for the current doc build.
The main change is the elimination of chapter-section numbers.
What's New in IDLE 3.6.7
Released on 2018-10-20
======================================
bpo-1529353: Output over N lines (50 by default) is squeezed down to a button.
N can be changed in the PyShell section of the General page of the
Settings dialog. Fewer, but possibly extra long, lines can be squeezed by
right clicking on the output. Squeezed output can be expanded in place
by double-clicking the button or into the clipboard or a separate window
by right-clicking the button.
bpo-34548: Use configured color theme for read-only text views.
bpo-33839: Refactor ToolTip and CallTip classes; add documentation
and tests.
bpo-34047: Fix mouse wheel scrolling direction on macOS.
bpo-34275: Make calltips always visible on Mac.
Patch by Kevin Walzer.
bpo-34120: Fix freezing after closing some dialogs on Mac.
This is one of multiple regressions from using newer tcl/tk.
bpo-33975: Avoid small type when running htests.
Since part of the purpose of human-viewed tests is to determine that
widgets look right, it is important that they look the same for
testing as when running IDLE.
bpo-33905: Add test for idlelib.stackview.StackBrowser.
bpo-33924: Change mainmenu.menudefs key 'windows' to 'window'.
Every other menudef key is the lowercase version of the
corresponding main menu entry (in this case, 'Window').
bpo-33906: Rename idlelib.windows as window
Match Window on the main menu and remove last plural module name.
Change imports, test, and attribute references to match new name.
bpo-33917: Fix and document idlelib/idle_test/template.py.
The revised file compiles, runs, and tests OK. idle_test/README.txt
explains how to use it to create new IDLE test files.
bpo-33904: In rstrip module, rename class RstripExtension as Rstrip.
bpo-33907: For consistency and clarity, rename calltip objects.
Module calltips and its class CallTips are now calltip and Calltip.
In module calltip_w, class CallTip is now CalltipWindow.
bpo-33855: Minimally test all IDLE modules.
Standardize the test file format. Add missing test files that import
the tested module and perform at least one test. Check and record the
coverage of each test.
bpo-33856: Add 'help' to Shell's initial welcome message.
What's New in IDLE 3.6.6
Released on 2018-06-27
======================================
bpo-33656: On Windows, add API call saying that tk scales for DPI.
On Windows 8.1+ or 10, with DPI compatibility properties of the Python
binary unchanged, and a monitor resolution greater than 96 DPI, this
should make text and lines sharper and some colors brighter.
On other systems, it should have no effect. If you have a custom theme,
you may want to adjust a color or two. If perchance it make text worse
on your monitor, you can disable the ctypes.OleDLL call near the top of
pyshell.py and report the problem on python-list or [email protected].
bpo-33768: Clicking on a context line moves that line to the top
of the editor window.
bpo-33763: Replace the code context label widget with a text widget.
bpo-33664: Scroll IDLE editor text by lines.
(Previously, the mouse wheel and scrollbar slider moved text by a fixed
number of pixels, resulting in partial lines at the top of the editor
box.) This change also applies to the shell and grep output windows,
but currently not to read-only text views.
bpo-33679: Enable theme-specific color configuration for Code Context.
(Previously, there was one code context foreground and background font
color setting, default or custom, on the extensions tab, that applied
to all themes.) For built-in themes, the foreground is the same as
normal text and the background is a contrasting gray. Context colors for
custom themes are set on the Hightlights tab along with other colors.
When one starts IDLE from a console and loads a custom theme without
definitions for 'context', one will see a warning message on the
console.
bpo-33642: Display up to maxlines non-blank lines for Code Context.
If there is no current context, show a single blank line. (Previously,
the Code Contex had numlines lines, usually with some blank.) The use
of a new option, 'maxlines' (default 15), avoids possible interference
with user settings of the old option, 'numlines' (default 3).
bpo-33628: Cleanup codecontext.py and its test.
bpo-32831: Add docstrings and tests for codecontext.py.
Coverage is 100%. Patch by Cheryl Sabella.
bpo-33564: Code context now recognizes async as a block opener.
bpo-29706: IDLE now colors async and await as keywords in 3.6.
They become full keywords in 3.7.
bpo-21474: Update word/identifier definition from ascii to unicode.
In text and entry boxes, this affects selection by double-click,
movement left/right by control-left/right, and deletion left/right
by control-BACKSPACE/DEL.
bpo-33204: Consistently color invalid string prefixes.
A 'u' string prefix cannot be paired with either 'r' or 'f'.
IDLE now consistently colors as much of the prefix, starting at the
right, as is valid. Revise and extend colorizer test.
What's New in IDLE 3.6.5
Released on 2018-03-28
======================================
bpo-32984: Set __file__ while running a startup file.
Like Python, IDLE optionally runs 1 startup file in the Shell window
before presenting the first interactive input prompt. For IDLE,
option -s runs a file named in environmental variable IDLESTARTUP or
PYTHONSTARTUP; -r file runs file. Python sets __file__ to the startup
file name before running the file and unsets it before the first
prompt. IDLE now does the same when run normally, without the -n
option.
bpo-32940: Replace StringTranslatePseudoMapping with faster code.
bpo-32916: Change 'str' to 'code' in idlelib.pyparse and users.
bpo-32905: Remove unused code in pyparse module.
bpo-32874: IDLE - add pyparse tests with 97% coverage.
bpo-32837: IDLE - require encoding argument for textview.view_file.
Using the system and place-dependent default encoding for open()
is a bad idea for IDLE's system and location-independent files.
bpo-32826: Add "encoding=utf-8" to open() in IDLE's test_help_about.
GUI test test_file_buttons() only looks at initial ascii-only lines,
but failed on systems where open() defaults to 'ascii' because
readline() internally reads and decodes far enough ahead to encounter
a non-ascii character in CREDITS.txt.
bpo-32765: Update configdialog General tab create page docstring.
Add new widgets to the widget list.
What's New in IDLE 3.6.4
Released on 2017-12-19
========================
bpo-32207: Improve tk event exception tracebacks in IDLE.
When tk event handling is driven by IDLE's run loop, a confusing
and distracting queue.EMPTY traceback context is no longer added
to tk event exception tracebacks. The traceback is now the same
as when event handling is driven by user code. Patch based on
a suggestion by Serhiy Storchaka.
bpo-32164: Delete unused file idlelib/tabbedpages.py.
Use of TabbedPageSet in configdialog was replaced by ttk.Notebook.
bpo-32100: Fix old and new bugs in pathbrowser; improve tests.
Patch mostly by Cheryl Sabella.
bpo-31860: The font sample in the settings dialog is now editable.
Edits persist while IDLE remains open.
Patch by Serhiy Storchake and Terry Jan Reedy.
bpo-31858: Restrict shell prompt manipulation to the shell.
Editor and output windows only see an empty last prompt line. This
simplifies the code and fixes a minor bug when newline is inserted.
Sys.ps1, if present, is read on Shell start-up, but is not set or changed.
Patch by Terry Jan Reedy.
bpo-28603: Fix a TypeError that caused a shell restart when printing
a traceback that includes an exception that is unhashable.
Patch by Zane Bitter.
bpo-13802: Use non-Latin characters in the Font settings sample.
Even if one selects a font that defines a limited subset of the unicode
Basic Multilingual Plane, tcl/tk will use other fonts that define a
character. The expanded example give users of non-Latin characters
a better idea of what they might see in the shell and editors.
To make room for the expanded sample, frames on the Font tab are
re-arranged. The Font/Tabs help explains a bit about the additions.
Patch by Terry Jan Reedy
What's New in IDLE 3.6.3
Released on 2017-10-03
========================
bpo-31460: Simplify the API of IDLE's Module Browser.
Passing a widget instead of an flist with a root widget opens the
option of creating a browser frame that is only part of a window.
Passing a full file name instead of pieces assumed to come from a
.py file opens the possibility of browsing python files that do not
end in .py.
bpo-31649: Make _htest and _utest parameters keyword-only.
These are used to adjust code for human and unit tests.
bpo-31459: Rename module browser from Class Browser to Module Browser.
The original module-level class and method browser became a module
browser, with the addition of module-level functions, years ago.
Nested classes and functions were added yesterday. For back-
compatibility, the virtual event <<open-class-browser>>, which
appears on the Keys tab of the Settings dialog, is not changed.
Patch by Cheryl Sabella.
bpo-1612262: Module browser now shows nested classes and functions.
Original patches for code and tests by Guilherme Polo and
Cheryl Sabella, respectively. Revisions by Terry Jan Reedy.
bpo-31500: Tk's default fonts now are scaled on HiDPI displays.
This affects all dialogs. Patch by Serhiy Storchaka.
bpo-31493: Fix code context update and font update timers.
Canceling timers prevents a warning message when test_idle completes.
bpo-31488: Update non-key options in former extension classes.
When applying configdialog changes, call .reload for each feature class.
Change ParenMatch so updated options affect existing instances attached
to existing editor windows.
bpo-31477: Improve rstrip entry in IDLE doc.
Strip Trailing Whitespace strips more than blank spaces.
Multiline string literals are not skipped.
bpo-31480: fix tests to pass with zzdummy extension disabled. (#3590)
To see the example in action, enable it on options extensions tab.
bpo-31421: Document how IDLE runs tkinter programs.
IDLE calls tcl/tk update in the background in order to make live
interaction and experimentation with tkinter applications much easier.
bpo-31414: Fix tk entry box tests by deleting first.
Adding to an int entry is not the same as deleting and inserting
because int('') will fail. Patch by Terry Jan Reedy.
bpo-27099: Convert IDLE's built-in 'extensions' to regular features.
About 10 IDLE features were implemented as supposedly optional
extensions. Their different behavior could be confusing or worse for
users and not good for maintenance. Hence the conversion.
The main difference for users is that user configurable key bindings
for builtin features are now handled uniformly. Now, editing a binding
in a keyset only affects its value in the keyset. All bindings are
defined together in the system-specific default keysets in config-
extensions.def. All custom keysets are saved as a whole in config-
extension.cfg. All take effect as soon as one clicks Apply or Ok.
The affected events are '<<force-open-completions>>',
'<<expand-word>>', '<<force-open-calltip>>', '<<flash-paren>>',
'<<format-paragraph>>', '<<run-module>>', '<<check-module>>', and
'<<zoom-height>>'. Any (global) customizations made before 3.6.3 will
not affect their keyset-specific customization after 3.6.3. and vice
versa.
Initial patch by Charles Wohlganger, revised by Terry Jan Reedy.
bpo-31051: Rearrange condigdialog General tab.
Sort non-Help options into Window (Shell+Editor) and Editor (only).
Leave room for the addition of new options.
Patch by Terry Jan Reedy.
bpo-30617: Add docstrings and tests for outwin subclass of editor.
Move some data and functions from the class to module level.
Patch by Cheryl Sabella.
bpo-31287: Do not modify tkinter.messagebox in test_configdialog.
Instead, mask it with an instance mock that can be deleted.
Patch by Terry Jan Reedy.
bpo-30781: Use ttk widgets in ConfigDialog pages.
These should especially look better on MacOSX.
Patches by Terry Jan Reedy and Cheryl Sabella.
bpo-31206: Factor HighPage(Frame) class from ConfigDialog.
Patch by Cheryl Sabella.
bp0-31001: Add tests for configdialog highlight tab.
Patch by Cheryl Sabella.
bpo-31205: Factor KeysPage(Frame) class from ConfigDialog.
The slightly modified tests continue to pass.
Patch by Cheryl Sabella.
bpo-31002: Add tests for configdialog keys tab.
Patch by Cheryl Sabella.
bpo-19903: Change calltipes to use inspect.signature.
Idlelib.calltips.get_argspec now uses inspect.signature instead of
inspect.getfullargspec, like help() does. This improves the signature
in the call tip in a few different cases, including builtins converted
to provide a signature. A message is added if the object is not
callable, has an invalid signature, or if it has positional-only
parameters. Patch by Louie Lu.
bop-31083: Add an outline of a TabPage class in configdialog.
Add template as comment. Update existing classes to match outline.
Initial patch by Cheryl Sabella.
bpo-31050: Factor GenPage(Frame) class from ConfigDialog.
The slightly modified tests for the General tab continue to pass.
Patch by Cheryl Sabella.
bpo-31004: Factor FontPage(Frame) class from ConfigDialog.
The slightly modified tests continue to pass. The General test
broken by the switch to ttk.Notebook is fixed.
Patch mostly by Cheryl Sabella.
bpo-30781: IDLE - Use ttk Notebook in ConfigDialog.
This improves navigation by tabbing.
Patch by Terry Jan Reedy.
bpo-31060: IDLE - Finish rearranging methods of ConfigDialog.
Grouping methods pertaining to each tab and the buttons will aid
writing tests and improving the tabs and will enable splitting the
groups into classes.
Patch by Terry Jan Reedy.
bpo-30853: IDLE -- Factor a VarTrace class out of ConfigDialog.
Instance tracers manages pairs consisting of a tk variable and a
callback function. When tracing is turned on, setting the variable
calls the function. Test coverage for the new class is 100%.
Patch by Terry Jan Reedy.
bpo-31003: IDLE: Add more tests for General tab.
Patch by Terry Jan Reedy.
bpo-30993: IDLE - Improve configdialog font page and tests.
*In configdialog: Document causal pathways in create_font_tab
docstring. Simplify some attribute names. Move set_samples calls to
var_changed_font (idea from Cheryl Sabella). Move related functions to
positions after the create widgets function.
* In test_configdialog: Fix test_font_set so not order dependent. Fix
renamed test_indent_scale so it tests the widget. Adjust tests for
movement of set_samples call. Add tests for load functions. Put all
font tests in one class and tab indent tests in another. Except for
two lines, these tests completely cover the related functions.
Patch by Terry Jan Reedy.
bpo-30981: IDLE -- Add more configdialog font page tests.
bpo-28523: IDLE: replace 'colour' with 'color' in configdialog.
bpo-30917: Add tests for idlelib.config.IdleConf.
Increase coverage from 46% to 96%.
Patch by Louie Lu.
bpo-30913: Document ConfigDialog tk Vars, methods, and widgets in docstrings
This will facilitate improving the dialog and splitting up the class.
Original patch by Cheryl Sabella.
bpo-30899: Add tests for ConfigParser subclasses in config.
Coverage is 100% for those classes and ConfigChanges.
Patch by Louie Lu.
bpo-30881: Add docstrings to browser.py.
Patch by Cheryl Sabella.
bpo-30851: Remove unused tk variables in configdialog.
One is a duplicate, one is set but cannot be altered by users.
Patch by Cheryl Sabella.
bpo-30870: Select font option with Up and Down keys, as well as with mouse.
Added test increases configdialog coverage to 60%
Patches mostly by Louie Lu.
bpo-8231: Call config.IdleConf.GetUserCfgDir only once per process.
bpo-30779: Factor ConfigChanges class from configdialog, put in config; test.
* In config, put dump test code in a function; run it and unittest in
'if __name__ == '__main__'.
* Add class config.ConfigChanges based on changes_class_v4.py on bpo issue.
* Add class test_config.ChangesTest, partly using configdialog_tests_v1.py.
* Revise configdialog to use ConfigChanges; see tracker msg297804.
* Revise test_configdialog to match configdialog changes.
* Remove configdialog functions unused or moved to ConfigChanges.
Cheryl Sabella contributed parts of the patch.
bpo-30777: Configdialog - add docstrings and improve comments.
Patch by Cheryl Sabella.
bpo-30495: Improve textview with docstrings, PEP8 names, and more tests.
Split TextViewer class into ViewWindow, ViewFrame, and TextFrame classes
so that instances of the latter two can be placed with other widgets
within a multiframe window.
Patches by Cheryl Sabella and Terry Jan Reedy.
bpo-30723: Make several improvements to parenmatch.
* Add 'parens' style to highlight both opener and closer.
* Make 'default' style, which is not default, a synonym for 'opener'.
* Make time-delay work the same with all styles.
* Add help for config dialog extensions tab, including parenmatch.
* Add new tests.
Original patch by Charles Wohlganger. Revisions by Terry Jan Reedy
bpo-30674: Grep -- Add docstrings. Patch by Cheryl Sabella.
bpo-21519: IDLE's basic custom key entry dialog now detects
duplicates properly. Original patch by Saimadhav Heblikar.
bpo-29910: IDLE no longer deletes a character after commenting out a
region by a key shortcut. Add "return 'break'" for this and other
potential conflicts between IDLE and default key bindings.
Patch by Serhiy Storchaka.
bpo-30728: Modernize idlelib.configdialog:
* replace import * with specific imports;
* lowercase method and attribute lines.
Patch by Cheryl Sabella.
bpo-6739: Verify user-entered key sequences by trying to bind them
with to a tk widget. Add tests for all 3 validation functions.
Original patch by G Polo. Tests added by Cheryl Sabella.
Code revised and more tests added by Terry Jan Reedy
bpo-24813: Add icon to help_about and make other changes.
What's New in IDLE 3.6.2
Released on 2017-07-17
========================
bpo-15786: Fix several problems with IDLE's autocompletion box.
The following should now work: clicking on selection box items;
using the scrollbar; selecting an item by hitting Return.
Hangs on MacOSX should no longer happen. Patch by Louie Lu.
bpo-25514: Add doc subsubsection about IDLE failure to start.
Popup no-connection message directs users to this section.
bpo-30642: Fix reference leaks in IDLE tests.
Patches by Louie Lu and Terry Jan Reedy.
bpo-30495: Add docstrings for textview.py and use PEP8 names.
Patches by Cheryl Sabella and Terry Jan Reedy.
bpo-30290: Help-about: use pep8 names and add tests.
Increase coverage to 100%.
Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.
bpo-30303: Add _utest option to textview; add new tests.
Increase coverage to 100%.
Patches by Louie Lu and Terry Jan Reedy.
What's New in IDLE 3.6.1
Released on 2017-03-21
========================
Issue #29071: IDLE colors f-string prefixes but not invalid ur prefixes.
Issue #28572: Add 10% to coverage of IDLE's test_configdialog.
Update and augment description of the configuration system.
What's New in IDLE 3.6.0 (since 3.5.0)
Released on 2016-12-23
======================================
- Issue #15308: Add 'interrupt execution' (^C) to Shell menu.
Patch by Roger Serwy, updated by Bayard Randel.
- Issue #27922: Stop IDLE tests from 'flashing' gui widgets on the screen.
- Issue #27891: Consistently group and sort imports within idlelib modules.
- Issue #17642: add larger font sizes for classroom projection.
- Add version to title of IDLE help window.
- Issue #25564: In section on IDLE -- console differences, mention that
using exec means that __builtins__ is defined for each statement.
- Issue #27821: Fix 3.6.0a3 regression that prevented custom key sets
from being selected when no custom theme was defined.
- Issue #27714: text_textview and test_autocomplete now pass when re-run
in the same process. This occurs when test_idle fails when run with the
-w option but without -jn. Fix warning from test_config.
- Issue #27621: Put query response validation error messages in the query
box itself instead of in a separate messagebox. Redo tests to match.
Add Mac OSX refinements. Original patch by Mark Roseman.
- Issue #27620: Escape key now closes Query box as cancelled.
- Issue #27609: IDLE: tab after initial whitespace should tab, not
autocomplete. This fixes problem with writing docstrings at least
twice indented.
- Issue #27609: Explicitly return None when there are also non-None
returns. In a few cases, reverse a condition and eliminate a return.
- Issue #25507: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.
- Issue #27173: Add 'IDLE Modern Unix' to the built-in key sets.
Make the default key set depend on the platform.
Add tests for the changes to the config module.
- Issue #27452: add line counter and crc to IDLE configHandler test dump.
- Issue #27477: IDLE search dialogs now use ttk widgets.
- Issue #27173: Add 'IDLE Modern Unix' to the built-in key sets.
Make the default key set depend on the platform.
Add tests for the changes to the config module.
- Issue #27452: make command line "idle-test> python test_help.py" work.
__file__ is relative when python is started in the file's directory.
- Issue #27452: add line counter and crc to IDLE configHandler test dump.
- Issue #27380: IDLE: add query.py with base Query dialog and ttk widgets.
Module had subclasses SectionName, ModuleName, and HelpSource, which are
used to get information from users by configdialog and file =>Load Module.
Each subclass has itw own validity checks. Using ModuleName allows users
to edit bad module names instead of starting over.
Add tests and delete the two files combined into the new one.
- Issue #27372: Test_idle no longer changes the locale.
- Issue #27365: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.
- Issue #27245: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.
- Issue #24137: Run IDLE, test_idle, and htest with tkinter default root disabled.
Fix code and tests that fail with this restriction.
Fix htests to not create a second and redundant root and mainloop.
- Issue #27310: Fix IDLE.app failure to launch on OS X due to vestigial import.
- Issue #5124: Paste with text selected now replaces the selection on X11.
This matches how paste works on Windows, Mac, most modern Linux apps,
and ttk widgets. Original patch by Serhiy Storchaka.
- Issue #24750: Switch all scrollbars in IDLE to ttk versions.
Where needed, minimal tests are added to cover changes.
- Issue #24759: IDLE requires tk 8.5 and availability ttk widgets.
Delete now unneeded tk version tests and code for older versions.
Add test for IDLE syntax colorizer.
- Issue #27239: idlelib.macosx.isXyzTk functions initialize as needed.
- Issue #27262: move Aqua unbinding code, which enable context menus, to macosx.
- Issue #24759: Make clear in idlelib.idle_test.__init__ that the directory
is a private implementation of test.test_idle and tool for maintainers.
- Issue #27196: Stop 'ThemeChanged' warnings when running IDLE tests.
These persisted after other warnings were suppressed in #20567.
Apply Serhiy Storchaka's update_idletasks solution to four test files.
Record this additional advice in idle_test/README.txt
- Issue #20567: Revise idle_test/README.txt with advice about avoiding
tk warning messages from tests. Apply advice to several IDLE tests.
- Issue # 24225: Update idlelib/README.txt with new file names
and event handlers.
- Issue #27156: Remove obsolete code not used by IDLE. Replacements:
1. help.txt, replaced by help.html, is out-of-date and should not be used.
Its dedicated viewer has be replaced by the html viewer in help.py.
2. 'import idlever; I = idlever.IDLE_VERSION' is the same as
'import sys; I = version[:version.index(' ')]'
3. After 'ob = stackviewer.VariablesTreeItem(*args)',
'ob.keys()' == 'list(ob.object.keys).
4. In macosc, runningAsOSXAPP == isAquaTk; idCarbonAquaTk == isCarbonTk
- Issue #27117: Make colorizer htest and turtledemo work with dark themes.
Move code for configuring text widget colors to a new function.
- Issue #24225: Rename many idlelib/*.py and idle_test/test_*.py files.
Edit files to replace old names with new names when the old name
referred to the module rather than the class it contained.
See the issue and IDLE section in What's New in 3.6 for more.
- Issue #26673: When tk reports font size as 0, change to size 10.
Such fonts on Linux prevented the configuration dialog from opening.
- Issue #21939: Add test for IDLE's percolator.
Original patch by Saimadhav Heblikar.
- Issue #21676: Add test for IDLE's replace dialog.
Original patch by Saimadhav Heblikar.
- Issue #18410: Add test for IDLE's search dialog.
Original patch by Westley MartÃnez.
- Issue #21703: Add test for undo delegator. Patch mostly by
Saimadhav Heblikar .
- Issue #27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks.
- Issue #23977: Add more asserts to test_delegator.
- Issue #20640: Add tests for idlelib.configHelpSourceEdit.
Patch by Saimadhav Heblikar.
- In the 'IDLE-console differences' section of the IDLE doc, clarify
how running with IDLE affects sys.modules and the standard streams.
- Issue #25507: fix incorrect change in IOBinding that prevented printing.
Augment IOBinding htest to include all major IOBinding functions.
- Issue #25905: Revert unwanted conversion of ' to â RIGHT SINGLE QUOTATION
MARK in README.txt and open this and NEWS.txt with 'ascii'.
Re-encode CREDITS.txt to utf-8 and open it with 'utf-8'.
- Issue 15348: Stop the debugger engine (normally in a user process)
before closing the debugger window (running in the IDLE process).
This prevents the RuntimeErrors that were being caught and ignored.
- Issue #24455: Prevent IDLE from hanging when a) closing the shell while the
debugger is active (15347); b) closing the debugger with the [X] button
(15348); and c) activating the debugger when already active (24455).
The patch by Mark Roseman does this by making two changes.
1. Suspend and resume the gui.interaction method with the tcl vwait
mechanism intended for this purpose (instead of root.mainloop & .quit).
2. In gui.run, allow any existing interaction to terminate first.
- Change 'The program' to 'Your program' in an IDLE 'kill program?' message
to make it clearer that the program referred to is the currently running
user program, not IDLE itself.
- Issue #24750: Improve the appearance of the IDLE editor window status bar.
Patch by Mark Roseman.
- Issue #25313: Change the handling of new built-in text color themes to better
address the compatibility problem introduced by the addition of IDLE Dark.
Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.
- Issue #24782: Extension configuration is now a tab in the IDLE Preferences
dialog rather than a separate dialog. The former tabs are now a sorted
list. Patch by Mark Roseman.
- Issue #22726: Re-activate the config dialog help button with some content
about the other buttons and the new IDLE Dark theme.
- Issue #24820: IDLE now has an 'IDLE Dark' built-in text color theme.
It is more or less IDLE Classic inverted, with a cobalt blue background.
Strings, comments, keywords, ... are still green, red, orange, ... .
To use it with IDLEs released before November 2015, hit the
'Save as New Custom Theme' button and enter a new name,
such as 'Custom Dark'. The custom theme will work with any IDLE
release, and can be modified.
- Issue #25224: README.txt is now an idlelib index for IDLE developers and
curious users. The previous user content is now in the IDLE doc chapter.
'IDLE' now means 'Integrated Development and Learning Environment'.
- Issue #24820: Users can now set breakpoint colors in
Settings -> Custom Highlighting. Original patch by Mark Roseman.
- Issue #24972: Inactive selection background now matches active selection
background, as configured by users, on all systems. Found items are now
always highlighted on Windows. Initial patch by Mark Roseman.
- Issue #24570: Idle: make calltip and completion boxes appear on Macs
affected by a tk regression. Initial patch by Mark Roseman.
- Issue #24988: Idle ScrolledList context menus (used in debugger)
now work on Mac Aqua. Patch by Mark Roseman.
- Issue #24801: Make right-click for context menu work on Mac Aqua.
Patch by Mark Roseman.
- Issue #25173: Associate tkinter messageboxes with a specific widget.
For Mac OSX, make them a 'sheet'. Patch by Mark Roseman.
- Issue #25198: Enhance the initial html viewer now used for Idle Help.
* Properly indent fixed-pitch text (patch by Mark Roseman).
* Give code snippet a very Sphinx-like light blueish-gray background.
* Re-use initial width and height set by users for shell and editor.
* When the Table of Contents (TOC) menu is used, put the section header
at the top of the screen.
- Issue #25225: Condense and rewrite Idle doc section on text colors.
- Issue #21995: Explain some differences between IDLE and console Python.
- Issue #22820: Explain need for *print* when running file from Idle editor.
- Issue #25224: Doc: augment Idle feature list and no-subprocess section.
- Issue #25219: Update doc for Idle command line options.
Some were missing and notes were not correct.
- Issue #24861: Most of idlelib is private and subject to change.
Use idleib.idle.* to start Idle. See idlelib.__init__.__doc__.
- Issue #25199: Idle: add synchronization comments for future maintainers.
- Issue #16893: Replace help.txt with help.html for Idle doc display.
The new idlelib/help.html is rstripped Doc/build/html/library/idle.html.
It looks better than help.txt and will better document Idle as released.
The tkinter html viewer that works for this file was written by Mark Roseman.
The now unused EditorWindow.HelpDialog class and helt.txt file are deprecated.
- Issue #24199: Deprecate unused idlelib.idlever with possible removal in 3.6.
- Issue #24790: Remove extraneous code (which also create 2 & 3 conflicts).
What's New in IDLE 3.5.0?
=========================
*Release date: 2015-09-13*
- Issue #23672: Allow Idle to edit and run files with astral chars in name.
Patch by Mohd Sanad Zaki Rizvi.
- Issue 24745: Idle editor default font. Switch from Courier to
platform-sensitive TkFixedFont. This should not affect current customized
font selections. If there is a problem, edit $HOME/.idlerc/config-main.cfg
and remove 'fontxxx' entries from [Editor Window]. Patch by Mark Roseman.
- Issue #21192: Idle editor. When a file is run, put its name in the restart bar.
Do not print false prompts. Original patch by Adnan Umer.
- Issue #13884: Idle menus. Remove tearoff lines. Patch by Roger Serwy.
- Issue #23184: remove unused names and imports in idlelib.
Initial patch by Al Sweigart.
- Issue #20577: Configuration of the max line length for the FormatParagraph
extension has been moved from the General tab of the Idle preferences dialog
to the FormatParagraph tab of the Config Extensions dialog.
Patch by Tal Einat.
- Issue #16893: Update Idle doc chapter to match current Idle and add new
information.
- Issue #3068: Add Idle extension configuration dialog to Options menu.
Changes are written to HOME/.idlerc/config-extensions.cfg.
Original patch by Tal Einat.
- Issue #16233: A module browser (File : Class Browser, Alt+C) requires an
editor window with a filename. When Class Browser is requested otherwise,
from a shell, output window, or 'Untitled' editor, Idle no longer displays
an error box. It now pops up an Open Module box (Alt+M). If a valid name
is entered and a module is opened, a corresponding browser is also opened.
- Issue #4832: Save As to type Python files automatically adds .py to the
name you enter (even if your system does not display it). Some systems
automatically add .txt when type is Text files.
- Issue #21986: Code objects are not normally pickled by the pickle module.
To match this, they are no longer pickled when running under Idle.
- Issue #23180: Rename IDLE "Windows" menu item to "Window".
Patch by Al Sweigart.
- Issue #17390: Adjust Editor window title; remove 'Python',
move version to end.
- Issue #14105: Idle debugger breakpoints no longer disappear
when inserting or deleting lines.
- Issue #17172: Turtledemo can now be run from Idle.
Currently, the entry is on the Help menu, but it may move to Run.
Patch by Ramchandra Apt and Lita Cho.
- Issue #21765: Add support for non-ascii identifiers to HyperParser.
- Issue #21940: Add unittest for WidgetRedirector. Initial patch by Saimadhav
Heblikar.
- Issue #18592: Add unittest for SearchDialogBase. Patch by Phil Webster.
- Issue #21694: Add unittest for ParenMatch. Patch by Saimadhav Heblikar.
- Issue #21686: add unittest for HyperParser. Original patch by Saimadhav
Heblikar.
- Issue #12387: Add missing upper(lower)case versions of default Windows key
bindings for Idle so Caps Lock does not disable them. Patch by Roger Serwy.
- Issue #21695: Closing a Find-in-files output window while the search is
still in progress no longer closes Idle.
- Issue #18910: Add unittest for textView. Patch by Phil Webster.
- Issue #18292: Add unittest for AutoExpand. Patch by Saihadhav Heblikar.
- Issue #18409: Add unittest for AutoComplete. Patch by Phil Webster.
- Issue #21477: htest.py - Improve framework, complete set of tests.
Patches by Saimadhav Heblikar
- Issue #18104: Add idlelib/idle_test/htest.py with a few sample tests to begin
consolidating and improving human-validated tests of Idle. Change other files
as needed to work with htest. Running the module as __main__ runs all tests.
- Issue #21139: Change default paragraph width to 72, the PEP 8 recommendation.
- Issue #21284: Paragraph reformat test passes after user changes reformat width.
- Issue #17654: Ensure IDLE menus are customized properly on OS X for
non-framework builds and for all variants of Tk.
What's New in IDLE 3.4.0?
=========================
*Release date: 2014-03-16*
- Issue #17390: Display Python version on Idle title bar.
Initial patch by Edmond Burnett.
- Issue #5066: Update IDLE docs. Patch by Todd Rovito.
- Issue #17625: Close the replace dialog after it is used.
- Issue #16226: Fix IDLE Path Browser crash.
(Patch by Roger Serwy)
- Issue #15853: Prevent IDLE crash on OS X when opening Preferences menu
with certain versions of Tk 8.5. Initial patch by Kevin Walzer.
What's New in IDLE 3.3.0?
=========================
*Release date: 2012-09-29*
- Issue #17625: Close the replace dialog after it is used.
- Issue #7163: Propagate return value of sys.stdout.write.
- Issue #15318: Prevent writing to sys.stdin.
- Issue #4832: Modify IDLE to save files with .py extension by
default on Windows and OS X (Tk 8.5) as it already does with X11 Tk.
- Issue #13532, #15319: Check that arguments to sys.stdout.write are strings.
- Issue # 12510: Attempt to get certain tool tips no longer crashes IDLE.
Erroneous tool tips have been corrected. Default added for callables.
- Issue #10365: File open dialog now works instead of crashing even when
parent window is closed while dialog is open.
- Issue 14876: use user-selected font for highlight configuration.
- Issue #14937: Perform auto-completion of filenames in strings even for
non-ASCII filenames. Likewise for identifiers.
- Issue #8515: Set __file__ when run file in IDLE.
Initial patch by Bruce Frederiksen.
- IDLE can be launched as `python -m idlelib`
- Issue #14409: IDLE now properly executes commands in the Shell window
when it cannot read the normal config files on startup and
has to use the built-in default key bindings.
There was previously a bug in one of the defaults.
- Issue #3573: IDLE hangs when passing invalid command line args
(directory(ies) instead of file(s)).
- Issue #14018: Update checks for unstable system Tcl/Tk versions on OS X
to include versions shipped with OS X 10.7 and 10.8 in addition to 10.6.
What's New in IDLE 3.2.1?
=========================
*Release date: 15-May-11*
- Issue #6378: Further adjust idle.bat to start associated Python
- Issue #11896: Save on Close failed despite selecting "Yes" in dialog.
- Issue #1028: Ctrl-space binding to show completions was causing IDLE to exit.
Tk < 8.5 was sending invalid Unicode null; replaced with valid null.
- Issue #4676: <Home> toggle failing on Tk 8.5, causing IDLE exits and strange selection
behavior. Improve selection extension behaviour.
- Issue #3851: <Home> toggle non-functional when NumLock set on Windows.
What's New in IDLE 3.1b1?
=========================
*Release date: 06-May-09*
- Issue #5707: Use of 'filter' in keybindingDialog.py was causing custom key assignment to
fail. Patch by Amaury Forgeot d'Arc.
- Issue #4815: Offer conversion to UTF-8 if source files have
no encoding declaration and are not encoded in UTF-8.
- Issue #4008: Fix problems with non-ASCII source files.
- Issue #4323: Always encode source as UTF-8 without asking
the user (unless a different encoding is declared); remove
user configuration of source encoding; all according to
PEP 3120.
- Issue #2665: On Windows, an IDLE installation upgraded from an old version
would not start if a custom theme was defined.
------------------------------------------------------------------------
Refer to NEWS2x.txt and HISTORY.txt for information on earlier releases.
------------------------------------------------------------------------
| 39,839 | 959 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/_pyclbr.py | # A private copy of 3.7.0a1 pyclbr for use by idlelib.browser
"""Parse a Python module and describe its classes and functions.
Parse enough of a Python file to recognize imports and class and
function definitions, and to find out the superclasses of a class.
The interface consists of a single function:
readmodule_ex(module, path=None)
where module is the name of a Python module, and path is an optional
list of directories where the module is to be searched. If present,
path is prepended to the system search path sys.path. The return value
is a dictionary. The keys of the dictionary are the names of the
classes and functions defined in the module (including classes that are
defined via the from XXX import YYY construct). The values are
instances of classes Class and Function. One special key/value pair is
present for packages: the key '__path__' has a list as its value which
contains the package search path.
Classes and Functions have a common superclass: _Object. Every instance
has the following attributes:
module -- name of the module;
name -- name of the object;
file -- file in which the object is defined;
lineno -- line in the file where the object's definition starts;
parent -- parent of this object, if any;
children -- nested objects contained in this object.
The 'children' attribute is a dictionary mapping names to objects.
Instances of Function describe functions with the attributes from _Object.
Instances of Class describe classes with the attributes from _Object,
plus the following:
super -- list of super classes (Class instances if possible);
methods -- mapping of method names to beginning line numbers.
If the name of a super class is not recognized, the corresponding
entry in the list of super classes is not a class instance but a
string giving the name of the super class. Since import statements
are recognized and imported modules are scanned as well, this
shouldn't happen often.
"""
import io
import sys
import importlib.util
import tokenize
from token import NAME, DEDENT, OP
__all__ = ["readmodule", "readmodule_ex", "Class", "Function"]
_modules = {} # Initialize cache of modules we've seen.
class _Object:
"Informaton about Python class or function."
def __init__(self, module, name, file, lineno, parent):
self.module = module
self.name = name
self.file = file
self.lineno = lineno
self.parent = parent
self.children = {}
def _addchild(self, name, obj):
self.children[name] = obj
class Function(_Object):
"Information about a Python function, including methods."
def __init__(self, module, name, file, lineno, parent=None):
_Object.__init__(self, module, name, file, lineno, parent)
class Class(_Object):
"Information about a Python class."
def __init__(self, module, name, super, file, lineno, parent=None):
_Object.__init__(self, module, name, file, lineno, parent)
self.super = [] if super is None else super
self.methods = {}
def _addmethod(self, name, lineno):
self.methods[name] = lineno
def _nest_function(ob, func_name, lineno):
"Return a Function after nesting within ob."
newfunc = Function(ob.module, func_name, ob.file, lineno, ob)
ob._addchild(func_name, newfunc)
if isinstance(ob, Class):
ob._addmethod(func_name, lineno)
return newfunc
def _nest_class(ob, class_name, lineno, super=None):
"Return a Class after nesting within ob."
newclass = Class(ob.module, class_name, super, ob.file, lineno, ob)
ob._addchild(class_name, newclass)
return newclass
def readmodule(module, path=None):
"""Return Class objects for the top-level classes in module.
This is the original interface, before Functions were added.
"""
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res
def readmodule_ex(module, path=None):
"""Return a dictionary with all functions and classes in module.
Search for module in PATH + sys.path.
If possible, include imported superclasses.
Do this by reading source, without importing (and executing) it.
"""
return _readmodule(module, path or [])
def _readmodule(module, path, inpackage=None):
"""Do the hard work for readmodule[_ex].
If inpackage is given, it must be the dotted name of the package in
which we are searching for a submodule, and then PATH must be the
package search path; otherwise, we are searching for a top-level
module, and path is combined with sys.path.
"""
# Compute the full module name (prepending inpackage if set).
if inpackage is not None:
fullmodule = "%s.%s" % (inpackage, module)
else:
fullmodule = module
# Check in the cache.
if fullmodule in _modules:
return _modules[fullmodule]
# Initialize the dict for this module's contents.
tree = {}
# Check if it is a built-in module; we don't do much for these.
if module in sys.builtin_module_names and inpackage is None:
_modules[module] = tree
return tree
# Check for a dotted module name.
i = module.rfind('.')
if i >= 0:
package = module[:i]
submodule = module[i+1:]
parent = _readmodule(package, path, inpackage)
if inpackage is not None:
package = "%s.%s" % (inpackage, package)
if not '__path__' in parent:
raise ImportError('No package named {}'.format(package))
return _readmodule(submodule, parent['__path__'], package)
# Search the path for the module.
f = None
if inpackage is not None:
search_path = path
else:
search_path = path + sys.path
spec = importlib.util._find_spec_from_path(fullmodule, search_path)
_modules[fullmodule] = tree
# Is module a package?
if spec.submodule_search_locations is not None:
tree['__path__'] = spec.submodule_search_locations
try:
source = spec.loader.get_source(fullmodule)
if source is None:
return tree
except (AttributeError, ImportError):
# If module is not Python source, we cannot do anything.
return tree
fname = spec.loader.get_filename(fullmodule)
return _create_tree(fullmodule, path, fname, source, tree, inpackage)
def _create_tree(fullmodule, path, fname, source, tree, inpackage):
"""Return the tree for a particular module.
fullmodule (full module name), inpackage+module, becomes o.module.
path is passed to recursive calls of _readmodule.
fname becomes o.file.
source is tokenized. Imports cause recursive calls to _readmodule.
tree is {} or {'__path__': <submodule search locations>}.
inpackage, None or string, is passed to recursive calls of _readmodule.
The effect of recursive calls is mutation of global _modules.
"""
f = io.StringIO(source)
stack = [] # Initialize stack of (class, indent) pairs.
g = tokenize.generate_tokens(f.readline)
try:
for tokentype, token, start, _end, _line in g:
if tokentype == DEDENT:
lineno, thisindent = start
# Close previous nested classes and defs.
while stack and stack[-1][1] >= thisindent:
del stack[-1]
elif token == 'def':
lineno, thisindent = start
# Close previous nested classes and defs.
while stack and stack[-1][1] >= thisindent:
del stack[-1]
tokentype, func_name, start = next(g)[0:3]
if tokentype != NAME:
continue # Skip def with syntax error.
cur_func = None
if stack:
cur_obj = stack[-1][0]
cur_func = _nest_function(cur_obj, func_name, lineno)
else:
# It is just a function.
cur_func = Function(fullmodule, func_name, fname, lineno)
tree[func_name] = cur_func
stack.append((cur_func, thisindent))
elif token == 'class':
lineno, thisindent = start
# Close previous nested classes and defs.
while stack and stack[-1][1] >= thisindent:
del stack[-1]
tokentype, class_name, start = next(g)[0:3]
if tokentype != NAME:
continue # Skip class with syntax error.
# Parse what follows the class name.
tokentype, token, start = next(g)[0:3]
inherit = None
if token == '(':
names = [] # Initialize list of superclasses.
level = 1
super = [] # Tokens making up current superclass.
while True:
tokentype, token, start = next(g)[0:3]
if token in (')', ',') and level == 1:
n = "".join(super)
if n in tree:
# We know this super class.
n = tree[n]
else:
c = n.split('.')
if len(c) > 1:
# Super class form is module.class:
# look in module for class.
m = c[-2]
c = c[-1]
if m in _modules:
d = _modules[m]
if c in d:
n = d[c]
names.append(n)
super = []
if token == '(':
level += 1
elif token == ')':
level -= 1
if level == 0:
break
elif token == ',' and level == 1:
pass
# Only use NAME and OP (== dot) tokens for type name.
elif tokentype in (NAME, OP) and level == 1:
super.append(token)
# Expressions in the base list are not supported.
inherit = names
if stack:
cur_obj = stack[-1][0]
cur_class = _nest_class(
cur_obj, class_name, lineno, inherit)
else:
cur_class = Class(fullmodule, class_name, inherit,
fname, lineno)
tree[class_name] = cur_class
stack.append((cur_class, thisindent))
elif token == 'import' and start[1] == 0:
modules = _getnamelist(g)
for mod, _mod2 in modules:
try:
# Recursively read the imported module.
if inpackage is None:
_readmodule(mod, path)
else:
try:
_readmodule(mod, path, inpackage)
except ImportError:
_readmodule(mod, [])
except:
# If we can't find or parse the imported module,
# too bad -- don't die here.
pass
elif token == 'from' and start[1] == 0:
mod, token = _getname(g)
if not mod or token != "import":
continue
names = _getnamelist(g)
try:
# Recursively read the imported module.
d = _readmodule(mod, path, inpackage)
except:
# If we can't find or parse the imported module,
# too bad -- don't die here.
continue
# Add any classes that were defined in the imported module
# to our name space if they were mentioned in the list.
for n, n2 in names:
if n in d:
tree[n2 or n] = d[n]
elif n == '*':
# Don't add names that start with _.
for n in d:
if n[0] != '_':
tree[n] = d[n]
except StopIteration:
pass
f.close()
return tree
def _getnamelist(g):
"""Return list of (dotted-name, as-name or None) tuples for token source g.
An as-name is the name that follows 'as' in an as clause.
"""
names = []
while True:
name, token = _getname(g)
if not name:
break
if token == 'as':
name2, token = _getname(g)
else:
name2 = None
names.append((name, name2))
while token != "," and "\n" not in token:
token = next(g)[1]
if token != ",":
break
return names
def _getname(g):
"Return (dotted-name or None, next-token) tuple for token source g."
parts = []
tokentype, token = next(g)[0:2]
if tokentype != NAME and token != '*':
return (None, token)
parts.append(token)
while True:
tokentype, token = next(g)[0:2]
if token != '.':
break
tokentype, token = next(g)[0:2]
if tokentype != NAME:
break
parts.append(token)
return (".".join(parts), token)
def _main():
"Print module output (default this file) for quick visual check."
import os
try:
mod = sys.argv[1]
except:
mod = __file__
if os.path.exists(mod):
path = [os.path.dirname(mod)]
mod = os.path.basename(mod)
if mod.lower().endswith(".py"):
mod = mod[:-3]
else:
path = []
tree = readmodule_ex(mod, path)
lineno_key = lambda a: getattr(a, 'lineno', 0)
objs = sorted(tree.values(), key=lineno_key, reverse=True)
indent_level = 2
while objs:
obj = objs.pop()
if isinstance(obj, list):
# Value is a __path__ key.
continue
if not hasattr(obj, 'indent'):
obj.indent = 0
if isinstance(obj, _Object):
new_objs = sorted(obj.children.values(),
key=lineno_key, reverse=True)
for ob in new_objs:
ob.indent = obj.indent + indent_level
objs.extend(new_objs)
if isinstance(obj, Class):
print("{}class {} {} {}"
.format(' ' * obj.indent, obj.name, obj.super, obj.lineno))
elif isinstance(obj, Function):
print("{}def {} {}".format(' ' * obj.indent, obj.name, obj.lineno))
if __name__ == "__main__":
_main()
| 15,199 | 403 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/filelist.py | "idlelib.filelist"
import os
from tkinter import messagebox as tkMessageBox
class FileList:
# N.B. this import overridden in PyShellFileList.
from idlelib.editor import EditorWindow
def __init__(self, root):
self.root = root
self.dict = {}
self.inversedict = {}
self.vars = {} # For EditorWindow.getrawvar (shared Tcl variables)
def open(self, filename, action=None):
assert filename
filename = self.canonize(filename)
if os.path.isdir(filename):
# This can happen when bad filename is passed on command line:
tkMessageBox.showerror(
"File Error",
"%r is a directory." % (filename,),
master=self.root)
return None
key = os.path.normcase(filename)
if key in self.dict:
edit = self.dict[key]
edit.top.wakeup()
return edit
if action:
# Don't create window, perform 'action', e.g. open in same window
return action(filename)
else:
edit = self.EditorWindow(self, filename, key)
if edit.good_load:
return edit
else:
edit._close()
return None
def gotofileline(self, filename, lineno=None):
edit = self.open(filename)
if edit is not None and lineno is not None:
edit.gotoline(lineno)
def new(self, filename=None):
return self.EditorWindow(self, filename)
def close_all_callback(self, *args, **kwds):
for edit in list(self.inversedict):
reply = edit.close()
if reply == "cancel":
break
return "break"
def unregister_maybe_terminate(self, edit):
try:
key = self.inversedict[edit]
except KeyError:
print("Don't know this EditorWindow object. (close)")
return
if key:
del self.dict[key]
del self.inversedict[edit]
if not self.inversedict:
self.root.quit()
def filename_changed_edit(self, edit):
edit.saved_change_hook()
try:
key = self.inversedict[edit]
except KeyError:
print("Don't know this EditorWindow object. (rename)")
return
filename = edit.io.filename
if not filename:
if key:
del self.dict[key]
self.inversedict[edit] = None
return
filename = self.canonize(filename)
newkey = os.path.normcase(filename)
if newkey == key:
return
if newkey in self.dict:
conflict = self.dict[newkey]
self.inversedict[conflict] = None
tkMessageBox.showerror(
"Name Conflict",
"You now have multiple edit windows open for %r" % (filename,),
master=self.root)
self.dict[newkey] = edit
self.inversedict[edit] = newkey
if key:
try:
del self.dict[key]
except KeyError:
pass
def canonize(self, filename):
if not os.path.isabs(filename):
try:
pwd = os.getcwd()
except OSError:
pass
else:
filename = os.path.join(pwd, filename)
return os.path.normpath(filename)
def _test(): # TODO check and convert to htest
from tkinter import Tk
from idlelib.editor import fixwordbreaks
from idlelib.run import fix_scaling
root = Tk()
fix_scaling(root)
fixwordbreaks(root)
root.withdraw()
flist = FileList(root)
flist.new()
if flist.inversedict:
root.mainloop()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_filelist', verbosity=2)
# _test()
| 3,896 | 132 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/pyshell.py | #! /usr/bin/env python3
import sys
try:
from tkinter import *
except ImportError:
print("** IDLE can't import Tkinter.\n"
"Your Python may not be configured for Tk. **", file=sys.__stderr__)
raise SystemExit(1)
# Valid arguments for the ...Awareness call below are defined in the following.
# https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
if sys.platform == 'win32':
try:
import ctypes
PROCESS_SYSTEM_DPI_AWARE = 1
ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
except (ImportError, AttributeError, OSError):
pass
import tkinter.messagebox as tkMessageBox
if TkVersion < 8.5:
root = Tk() # otherwise create root in main
root.withdraw()
from idlelib.run import fix_scaling
fix_scaling(root)
tkMessageBox.showerror("Idle Cannot Start",
"Idle requires tcl/tk 8.5+, not %s." % TkVersion,
parent=root)
raise SystemExit(1)
from code import InteractiveInterpreter
import linecache
import os
import os.path
from platform import python_version
import re
import socket
import subprocess
from textwrap import TextWrapper
import threading
import time
import tokenize
import warnings
from idlelib.colorizer import ColorDelegator
from idlelib.config import idleConf
from idlelib import debugger
from idlelib import debugger_r
from idlelib.editor import EditorWindow, fixwordbreaks
from idlelib.filelist import FileList
from idlelib.outwin import OutputWindow
from idlelib import rpc
from idlelib.run import idle_formatwarning, PseudoInputFile, PseudoOutputFile
from idlelib.undo import UndoDelegator
HOST = '127.0.0.1' # python execution server on localhost loopback
PORT = 0 # someday pass in host, port for remote debug capability
# Override warnings module to write to warning_stream. Initialize to send IDLE
# internal warnings to the console. ScriptBinding.check_syntax() will
# temporarily redirect the stream to the shell window to display warnings when
# checking user's code.
warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
def idle_showwarning(
message, category, filename, lineno, file=None, line=None):
"""Show Idle-format warning (after replacing warnings.showwarning).
The differences are the formatter called, the file=None replacement,
which can be None, the capture of the consequence AttributeError,
and the output of a hard-coded prompt.
"""
if file is None:
file = warning_stream
try:
file.write(idle_formatwarning(
message, category, filename, lineno, line=line))
file.write(">>> ")
except (AttributeError, OSError):
pass # if file (probably __stderr__) is invalid, skip warning.
_warnings_showwarning = None
def capture_warnings(capture):
"Replace warning.showwarning with idle_showwarning, or reverse."
global _warnings_showwarning
if capture:
if _warnings_showwarning is None:
_warnings_showwarning = warnings.showwarning
warnings.showwarning = idle_showwarning
else:
if _warnings_showwarning is not None:
warnings.showwarning = _warnings_showwarning
_warnings_showwarning = None
capture_warnings(True)
def extended_linecache_checkcache(filename=None,
orig_checkcache=linecache.checkcache):
"""Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the
<pyshell#...> entries, call the original linecache.checkcache()
(skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original
method, allowing it to be patched.
"""
cache = linecache.cache
save = {}
for key in list(cache):
if key[:1] + key[-1:] == '<>':
save[key] = cache.pop(key)
orig_checkcache(filename)
cache.update(save)
# Patch linecache.checkcache():
linecache.checkcache = extended_linecache_checkcache
class PyShellEditorWindow(EditorWindow):
"Regular text edit window in IDLE, supports breakpoints"
def __init__(self, *args):
self.breakpoints = []
EditorWindow.__init__(self, *args)
self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
self.text.bind("<<open-python-shell>>", self.flist.open_shell)
self.breakpointPath = os.path.join(
idleConf.userdir, 'breakpoints.lst')
# whenever a file is changed, restore breakpoints
def filename_changed_hook(old_hook=self.io.filename_change_hook,
self=self):
self.restore_file_breaks()
old_hook()
self.io.set_filename_change_hook(filename_changed_hook)
if self.io.filename:
self.restore_file_breaks()
self.color_breakpoint_text()
rmenu_specs = [
("Cut", "<<cut>>", "rmenu_check_cut"),
("Copy", "<<copy>>", "rmenu_check_copy"),
("Paste", "<<paste>>", "rmenu_check_paste"),
(None, None, None),
("Set Breakpoint", "<<set-breakpoint-here>>", None),
("Clear Breakpoint", "<<clear-breakpoint-here>>", None)
]
def color_breakpoint_text(self, color=True):
"Turn colorizing of breakpoint text on or off"
if self.io is None:
# possible due to update in restore_file_breaks
return
if color:
theme = idleConf.CurrentTheme()
cfg = idleConf.GetHighlight(theme, "break")
else:
cfg = {'foreground': '', 'background': ''}
self.text.tag_config('BREAK', cfg)
def set_breakpoint(self, lineno):
text = self.text
filename = self.io.filename
text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
try:
self.breakpoints.index(lineno)
except ValueError: # only add if missing, i.e. do once
self.breakpoints.append(lineno)
try: # update the subprocess debugger
debug = self.flist.pyshell.interp.debugger
debug.set_breakpoint_here(filename, lineno)
except: # but debugger may not be active right now....
pass
def set_breakpoint_here(self, event=None):
text = self.text
filename = self.io.filename
if not filename:
text.bell()
return
lineno = int(float(text.index("insert")))
self.set_breakpoint(lineno)
def clear_breakpoint_here(self, event=None):
text = self.text
filename = self.io.filename
if not filename:
text.bell()
return
lineno = int(float(text.index("insert")))
try:
self.breakpoints.remove(lineno)
except:
pass
text.tag_remove("BREAK", "insert linestart",\
"insert lineend +1char")
try:
debug = self.flist.pyshell.interp.debugger
debug.clear_breakpoint_here(filename, lineno)
except:
pass
def clear_file_breaks(self):
if self.breakpoints:
text = self.text
filename = self.io.filename
if not filename:
text.bell()
return
self.breakpoints = []
text.tag_remove("BREAK", "1.0", END)
try:
debug = self.flist.pyshell.interp.debugger
debug.clear_file_breaks(filename)
except:
pass
def store_file_breaks(self):
"Save breakpoints when file is saved"
# XXX 13 Dec 2002 KBK Currently the file must be saved before it can
# be run. The breaks are saved at that time. If we introduce
# a temporary file save feature the save breaks functionality
# needs to be re-verified, since the breaks at the time the
# temp file is created may differ from the breaks at the last
# permanent save of the file. Currently, a break introduced
# after a save will be effective, but not persistent.
# This is necessary to keep the saved breaks synched with the
# saved file.
#
# Breakpoints are set as tagged ranges in the text.
# Since a modified file has to be saved before it is
# run, and since self.breakpoints (from which the subprocess
# debugger is loaded) is updated during the save, the visible
# breaks stay synched with the subprocess even if one of these
# unexpected breakpoint deletions occurs.
breaks = self.breakpoints
filename = self.io.filename
try:
with open(self.breakpointPath, "r") as fp:
lines = fp.readlines()
except OSError:
lines = []
try:
with open(self.breakpointPath, "w") as new_file:
for line in lines:
if not line.startswith(filename + '='):
new_file.write(line)
self.update_breakpoints()
breaks = self.breakpoints
if breaks:
new_file.write(filename + '=' + str(breaks) + '\n')
except OSError as err:
if not getattr(self.root, "breakpoint_error_displayed", False):
self.root.breakpoint_error_displayed = True
tkMessageBox.showerror(title='IDLE Error',
message='Unable to update breakpoint list:\n%s'
% str(err),
parent=self.text)
def restore_file_breaks(self):
self.text.update() # this enables setting "BREAK" tags to be visible
if self.io is None:
# can happen if IDLE closes due to the .update() call
return
filename = self.io.filename
if filename is None:
return
if os.path.isfile(self.breakpointPath):
with open(self.breakpointPath, "r") as fp:
lines = fp.readlines()
for line in lines:
if line.startswith(filename + '='):
breakpoint_linenumbers = eval(line[len(filename)+1:])
for breakpoint_linenumber in breakpoint_linenumbers:
self.set_breakpoint(breakpoint_linenumber)
def update_breakpoints(self):
"Retrieves all the breakpoints in the current window"
text = self.text
ranges = text.tag_ranges("BREAK")
linenumber_list = self.ranges_to_linenumbers(ranges)
self.breakpoints = linenumber_list
def ranges_to_linenumbers(self, ranges):
lines = []
for index in range(0, len(ranges), 2):
lineno = int(float(ranges[index].string))
end = int(float(ranges[index+1].string))
while lineno < end:
lines.append(lineno)
lineno += 1
return lines
# XXX 13 Dec 2002 KBK Not used currently
# def saved_change_hook(self):
# "Extend base method - clear breaks if module is modified"
# if not self.get_saved():
# self.clear_file_breaks()
# EditorWindow.saved_change_hook(self)
def _close(self):
"Extend base method - clear breaks when module is closed"
self.clear_file_breaks()
EditorWindow._close(self)
class PyShellFileList(FileList):
"Extend base class: IDLE supports a shell and breakpoints"
# override FileList's class variable, instances return PyShellEditorWindow
# instead of EditorWindow when new edit windows are created.
EditorWindow = PyShellEditorWindow
pyshell = None
def open_shell(self, event=None):
if self.pyshell:
self.pyshell.top.wakeup()
else:
self.pyshell = PyShell(self)
if self.pyshell:
if not self.pyshell.begin():
return None
return self.pyshell
class ModifiedColorDelegator(ColorDelegator):
"Extend base class: colorizer for the shell window itself"
def __init__(self):
ColorDelegator.__init__(self)
self.LoadTagDefs()
def recolorize_main(self):
self.tag_remove("TODO", "1.0", "iomark")
self.tag_add("SYNC", "1.0", "iomark")
ColorDelegator.recolorize_main(self)
def LoadTagDefs(self):
ColorDelegator.LoadTagDefs(self)
theme = idleConf.CurrentTheme()
self.tagdefs.update({
"stdin": {'background':None,'foreground':None},
"stdout": idleConf.GetHighlight(theme, "stdout"),
"stderr": idleConf.GetHighlight(theme, "stderr"),
"console": idleConf.GetHighlight(theme, "console"),
})
def removecolors(self):
# Don't remove shell color tags before "iomark"
for tag in self.tagdefs:
self.tag_remove(tag, "iomark", "end")
class ModifiedUndoDelegator(UndoDelegator):
"Extend base class: forbid insert/delete before the I/O mark"
def insert(self, index, chars, tags=None):
try:
if self.delegate.compare(index, "<", "iomark"):
self.delegate.bell()
return
except TclError:
pass
UndoDelegator.insert(self, index, chars, tags)
def delete(self, index1, index2=None):
try:
if self.delegate.compare(index1, "<", "iomark"):
self.delegate.bell()
return
except TclError:
pass
UndoDelegator.delete(self, index1, index2)
class MyRPCClient(rpc.RPCClient):
def handle_EOF(self):
"Override the base class - just re-raise EOFError"
raise EOFError
class ModifiedInterpreter(InteractiveInterpreter):
def __init__(self, tkconsole):
self.tkconsole = tkconsole
locals = sys.modules['__main__'].__dict__
InteractiveInterpreter.__init__(self, locals=locals)
self.save_warnings_filters = None
self.restarting = False
self.subprocess_arglist = None
self.port = PORT
self.original_compiler_flags = self.compile.compiler.flags
_afterid = None
rpcclt = None
rpcsubproc = None
def spawn_subprocess(self):
if self.subprocess_arglist is None:
self.subprocess_arglist = self.build_subprocess_arglist()
self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)
def build_subprocess_arglist(self):
assert (self.port!=0), (
"Socket should have been assigned a port number.")
w = ['-W' + s for s in sys.warnoptions]
# Maybe IDLE is installed and is being accessed via sys.path,
# or maybe it's not installed and the idle.py script is being
# run from the IDLE source directory.
del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
default=False, type='bool')
if __name__ == 'idlelib.pyshell':
command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
else:
command = "__import__('run').main(%r)" % (del_exitf,)
return [sys.executable] + w + ["-c", command, str(self.port)]
def start_subprocess(self):
addr = (HOST, self.port)
# GUI makes several attempts to acquire socket, listens for connection
for i in range(3):
time.sleep(i)
try:
self.rpcclt = MyRPCClient(addr)
break
except OSError:
pass
else:
self.display_port_binding_error()
return None
# if PORT was 0, system will assign an 'ephemeral' port. Find it out:
self.port = self.rpcclt.listening_sock.getsockname()[1]
# if PORT was not 0, probably working with a remote execution server
if PORT != 0:
# To allow reconnection within the 2MSL wait (cf. Stevens TCP
# V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
# on Windows since the implementation allows two active sockets on
# the same address!
self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
self.spawn_subprocess()
#time.sleep(20) # test to simulate GUI not accepting connection
# Accept the connection from the Python execution server
self.rpcclt.listening_sock.settimeout(10)
try:
self.rpcclt.accept()
except socket.timeout:
self.display_no_subprocess_error()
return None
self.rpcclt.register("console", self.tkconsole)
self.rpcclt.register("stdin", self.tkconsole.stdin)
self.rpcclt.register("stdout", self.tkconsole.stdout)
self.rpcclt.register("stderr", self.tkconsole.stderr)
self.rpcclt.register("flist", self.tkconsole.flist)
self.rpcclt.register("linecache", linecache)
self.rpcclt.register("interp", self)
self.transfer_path(with_cwd=True)
self.poll_subprocess()
return self.rpcclt
def restart_subprocess(self, with_cwd=False, filename=''):
if self.restarting:
return self.rpcclt
self.restarting = True
# close only the subprocess debugger
debug = self.getdebugger()
if debug:
try:
# Only close subprocess debugger, don't unregister gui_adap!
debugger_r.close_subprocess_debugger(self.rpcclt)
except:
pass
# Kill subprocess, spawn a new one, accept connection.
self.rpcclt.close()
self.terminate_subprocess()
console = self.tkconsole
was_executing = console.executing
console.executing = False
self.spawn_subprocess()
try:
self.rpcclt.accept()
except socket.timeout:
self.display_no_subprocess_error()
return None
self.transfer_path(with_cwd=with_cwd)
console.stop_readline()
# annotate restart in shell window and mark it
console.text.delete("iomark", "end-1c")
tag = 'RESTART: ' + (filename if filename else 'Shell')
halfbar = ((int(console.width) -len(tag) - 4) // 2) * '='
console.write("\n{0} {1} {0}".format(halfbar, tag))
console.text.mark_set("restart", "end-1c")
console.text.mark_gravity("restart", "left")
if not filename:
console.showprompt()
# restart subprocess debugger
if debug:
# Restarted debugger connects to current instance of debug GUI
debugger_r.restart_subprocess_debugger(self.rpcclt)
# reload remote debugger breakpoints for all PyShellEditWindows
debug.load_breakpoints()
self.compile.compiler.flags = self.original_compiler_flags
self.restarting = False
return self.rpcclt
def __request_interrupt(self):
self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
def interrupt_subprocess(self):
threading.Thread(target=self.__request_interrupt).start()
def kill_subprocess(self):
if self._afterid is not None:
self.tkconsole.text.after_cancel(self._afterid)
try:
self.rpcclt.listening_sock.close()
except AttributeError: # no socket
pass
try:
self.rpcclt.close()
except AttributeError: # no socket
pass
self.terminate_subprocess()
self.tkconsole.executing = False
self.rpcclt = None
def terminate_subprocess(self):
"Make sure subprocess is terminated"
try:
self.rpcsubproc.kill()
except OSError:
# process already terminated
return
else:
try:
self.rpcsubproc.wait()
except OSError:
return
def transfer_path(self, with_cwd=False):
if with_cwd: # Issue 13506
path = [''] # include Current Working Directory
path.extend(sys.path)
else:
path = sys.path
self.runcommand("""if 1:
import sys as _sys
_sys.path = %r
del _sys
\n""" % (path,))
active_seq = None
def poll_subprocess(self):
clt = self.rpcclt
if clt is None:
return
try:
response = clt.pollresponse(self.active_seq, wait=0.05)
except (EOFError, OSError, KeyboardInterrupt):
# lost connection or subprocess terminated itself, restart
# [the KBI is from rpc.SocketIO.handle_EOF()]
if self.tkconsole.closing:
return
response = None
self.restart_subprocess()
if response:
self.tkconsole.resetoutput()
self.active_seq = None
how, what = response
console = self.tkconsole.console
if how == "OK":
if what is not None:
print(repr(what), file=console)
elif how == "EXCEPTION":
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
self.remote_stack_viewer()
elif how == "ERROR":
errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n"
print(errmsg, what, file=sys.__stderr__)
print(errmsg, what, file=console)
# we received a response to the currently active seq number:
try:
self.tkconsole.endexecuting()
except AttributeError: # shell may have closed
pass
# Reschedule myself
if not self.tkconsole.closing:
self._afterid = self.tkconsole.text.after(
self.tkconsole.pollinterval, self.poll_subprocess)
debugger = None
def setdebugger(self, debugger):
self.debugger = debugger
def getdebugger(self):
return self.debugger
def open_remote_stack_viewer(self):
"""Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this
method we allow the subprocess to unblock. After a bit the shell
requests the subprocess to open the remote stack viewer which returns a
static object looking at the last exception. It is queried through
the RPC mechanism.
"""
self.tkconsole.text.after(300, self.remote_stack_viewer)
return
def remote_stack_viewer(self):
from idlelib import debugobj_r
oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
if oid is None:
self.tkconsole.root.bell()
return
item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid)
from idlelib.tree import ScrolledCanvas, TreeNode
top = Toplevel(self.tkconsole.root)
theme = idleConf.CurrentTheme()
background = idleConf.GetHighlight(theme, 'normal')['background']
sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
sc.frame.pack(expand=1, fill="both")
node = TreeNode(sc.canvas, None, item)
node.expand()
# XXX Should GC the remote tree when closing the window
gid = 0
def execsource(self, source):
"Like runsource() but assumes complete exec source"
filename = self.stuffsource(source)
self.execfile(filename, source)
def execfile(self, filename, source=None):
"Execute an existing file"
if source is None:
with tokenize.open(filename) as fp:
source = fp.read()
if use_subprocess:
source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n"
+ source + "\ndel __file__")
try:
code = compile(source, filename, "exec")
except (OverflowError, SyntaxError):
self.tkconsole.resetoutput()
print('*** Error in script or command!\n'
'Traceback (most recent call last):',
file=self.tkconsole.stderr)
InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt()
else:
self.runcode(code)
def runsource(self, source):
"Extend base class method: Stuff the source in the line cache first"
filename = self.stuffsource(source)
self.more = 0
self.save_warnings_filters = warnings.filters[:]
warnings.filterwarnings(action="error", category=SyntaxWarning)
# at the moment, InteractiveInterpreter expects str
assert isinstance(source, str)
#if isinstance(source, str):
# from idlelib import iomenu
# try:
# source = source.encode(iomenu.encoding)
# except UnicodeError:
# self.tkconsole.resetoutput()
# self.write("Unsupported characters in input\n")
# return
try:
# InteractiveInterpreter.runsource() calls its runcode() method,
# which is overridden (see below)
return InteractiveInterpreter.runsource(self, source, filename)
finally:
if self.save_warnings_filters is not None:
warnings.filters[:] = self.save_warnings_filters
self.save_warnings_filters = None
def stuffsource(self, source):
"Stuff source in the filename cache"
filename = "<pyshell#%d>" % self.gid
self.gid = self.gid + 1
lines = source.split("\n")
linecache.cache[filename] = len(source)+1, 0, lines, filename
return filename
def prepend_syspath(self, filename):
"Prepend sys.path with file's directory if not already included"
self.runcommand("""if 1:
_filename = %r
import sys as _sys
from os.path import dirname as _dirname
_dir = _dirname(_filename)
if not _dir in _sys.path:
_sys.path.insert(0, _dir)
del _filename, _sys, _dirname, _dir
\n""" % (filename,))
def showsyntaxerror(self, filename=None):
"""Override Interactive Interpreter method: Use Colorizing
Color the offending position instead of printing it and pointing at it
with a caret.
"""
tkconsole = self.tkconsole
text = tkconsole.text
text.tag_remove("ERROR", "1.0", "end")
type, value, tb = sys.exc_info()
msg = getattr(value, 'msg', '') or value or "<no detail available>"
lineno = getattr(value, 'lineno', '') or 1
offset = getattr(value, 'offset', '') or 0
if offset == 0:
lineno += 1 #mark end of offending line
if lineno == 1:
pos = "iomark + %d chars" % (offset-1)
else:
pos = "iomark linestart + %d lines + %d chars" % \
(lineno-1, offset-1)
tkconsole.colorize_syntax_error(text, pos)
tkconsole.resetoutput()
self.write("SyntaxError: %s\n" % msg)
tkconsole.showprompt()
def showtraceback(self):
"Extend base class method to reset output properly"
self.tkconsole.resetoutput()
self.checklinecache()
InteractiveInterpreter.showtraceback(self)
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
self.tkconsole.open_stack_viewer()
def checklinecache(self):
c = linecache.cache
for key in list(c.keys()):
if key[:1] + key[-1:] != "<>":
del c[key]
def runcommand(self, code):
"Run the code without invoking the debugger"
# The code better not raise an exception!
if self.tkconsole.executing:
self.display_executing_dialog()
return 0
if self.rpcclt:
self.rpcclt.remotequeue("exec", "runcode", (code,), {})
else:
exec(code, self.locals)
return 1
def runcode(self, code):
"Override base class method"
if self.tkconsole.executing:
self.interp.restart_subprocess()
self.checklinecache()
if self.save_warnings_filters is not None:
warnings.filters[:] = self.save_warnings_filters
self.save_warnings_filters = None
debugger = self.debugger
try:
self.tkconsole.beginexecuting()
if not debugger and self.rpcclt is not None:
self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
(code,), {})
elif debugger:
debugger.run(code, self.locals)
else:
exec(code, self.locals)
except SystemExit:
if not self.tkconsole.closing:
if tkMessageBox.askyesno(
"Exit?",
"Do you want to exit altogether?",
default="yes",
parent=self.tkconsole.text):
raise
else:
self.showtraceback()
else:
raise
except:
if use_subprocess:
print("IDLE internal error in runcode()",
file=self.tkconsole.stderr)
self.showtraceback()
self.tkconsole.endexecuting()
else:
if self.tkconsole.canceled:
self.tkconsole.canceled = False
print("KeyboardInterrupt", file=self.tkconsole.stderr)
else:
self.showtraceback()
finally:
if not use_subprocess:
try:
self.tkconsole.endexecuting()
except AttributeError: # shell may have closed
pass
def write(self, s):
"Override base class method"
return self.tkconsole.stderr.write(s)
def display_port_binding_error(self):
tkMessageBox.showerror(
"Port Binding Error",
"IDLE can't bind to a TCP/IP port, which is necessary to "
"communicate with its Python execution server. This might be "
"because no networking is installed on this computer. "
"Run IDLE with the -n command line switch to start without a "
"subprocess and refer to Help/IDLE Help 'Running without a "
"subprocess' for further details.",
parent=self.tkconsole.text)
def display_no_subprocess_error(self):
tkMessageBox.showerror(
"Subprocess Startup Error",
"IDLE's subprocess didn't make connection. Either IDLE can't "
"start a subprocess or personal firewall software is blocking "
"the connection.",
parent=self.tkconsole.text)
def display_executing_dialog(self):
tkMessageBox.showerror(
"Already executing",
"The Python Shell window is already executing a command; "
"please wait until it is finished.",
parent=self.tkconsole.text)
class PyShell(OutputWindow):
shell_title = "Python " + python_version() + " Shell"
# Override classes
ColorDelegator = ModifiedColorDelegator
UndoDelegator = ModifiedUndoDelegator
# Override menus
menu_specs = [
("file", "_File"),
("edit", "_Edit"),
("debug", "_Debug"),
("options", "_Options"),
("window", "_Window"),
("help", "_Help"),
]
# Extend right-click context menu
rmenu_specs = OutputWindow.rmenu_specs + [
("Squeeze", "<<squeeze-current-text>>"),
]
# New classes
from idlelib.history import History
def __init__(self, flist=None):
if use_subprocess:
ms = self.menu_specs
if ms[2][0] != "shell":
ms.insert(2, ("shell", "She_ll"))
self.interp = ModifiedInterpreter(self)
if flist is None:
root = Tk()
fixwordbreaks(root)
root.withdraw()
flist = PyShellFileList(root)
OutputWindow.__init__(self, flist, None, None)
self.usetabs = True
# indentwidth must be 8 when using tabs. See note in EditorWindow:
self.indentwidth = 8
self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>> '
self.prompt_last_line = self.sys_ps1.split('\n')[-1]
self.prompt = self.sys_ps1 # Changes when debug active
text = self.text
text.configure(wrap="char")
text.bind("<<newline-and-indent>>", self.enter_callback)
text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
text.bind("<<interrupt-execution>>", self.cancel_callback)
text.bind("<<end-of-file>>", self.eof_callback)
text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
text.bind("<<toggle-debugger>>", self.toggle_debugger)
text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
if use_subprocess:
text.bind("<<view-restart>>", self.view_restart_mark)
text.bind("<<restart-shell>>", self.restart_shell)
self.save_stdout = sys.stdout
self.save_stderr = sys.stderr
self.save_stdin = sys.stdin
from idlelib import iomenu
self.stdin = PseudoInputFile(self, "stdin", iomenu.encoding)
self.stdout = PseudoOutputFile(self, "stdout", iomenu.encoding)
self.stderr = PseudoOutputFile(self, "stderr", iomenu.encoding)
self.console = PseudoOutputFile(self, "console", iomenu.encoding)
if not use_subprocess:
sys.stdout = self.stdout
sys.stderr = self.stderr
sys.stdin = self.stdin
try:
# page help() text to shell.
import pydoc # import must be done here to capture i/o rebinding.
# XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc
pydoc.pager = pydoc.plainpager
except:
sys.stderr = sys.__stderr__
raise
#
self.history = self.History(self.text)
#
self.pollinterval = 50 # millisec
def get_standard_extension_names(self):
return idleConf.GetExtensions(shell_only=True)
reading = False
executing = False
canceled = False
endoffile = False
closing = False
_stop_readline_flag = False
def set_warning_stream(self, stream):
global warning_stream
warning_stream = stream
def get_warning_stream(self):
return warning_stream
def toggle_debugger(self, event=None):
if self.executing:
tkMessageBox.showerror("Don't debug now",
"You can only toggle the debugger when idle",
parent=self.text)
self.set_debugger_indicator()
return "break"
else:
db = self.interp.getdebugger()
if db:
self.close_debugger()
else:
self.open_debugger()
def set_debugger_indicator(self):
db = self.interp.getdebugger()
self.setvar("<<toggle-debugger>>", not not db)
def toggle_jit_stack_viewer(self, event=None):
pass # All we need is the variable
def close_debugger(self):
db = self.interp.getdebugger()
if db:
self.interp.setdebugger(None)
db.close()
if self.interp.rpcclt:
debugger_r.close_remote_debugger(self.interp.rpcclt)
self.resetoutput()
self.console.write("[DEBUG OFF]\n")
self.prompt = self.sys_ps1
self.showprompt()
self.set_debugger_indicator()
def open_debugger(self):
if self.interp.rpcclt:
dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt,
self)
else:
dbg_gui = debugger.Debugger(self)
self.interp.setdebugger(dbg_gui)
dbg_gui.load_breakpoints()
self.prompt = "[DEBUG ON]\n" + self.sys_ps1
self.showprompt()
self.set_debugger_indicator()
def beginexecuting(self):
"Helper for ModifiedInterpreter"
self.resetoutput()
self.executing = 1
def endexecuting(self):
"Helper for ModifiedInterpreter"
self.executing = 0
self.canceled = 0
self.showprompt()
def close(self):
"Extend EditorWindow.close()"
if self.executing:
response = tkMessageBox.askokcancel(
"Kill?",
"Your program is still running!\n Do you want to kill it?",
default="ok",
parent=self.text)
if response is False:
return "cancel"
self.stop_readline()
self.canceled = True
self.closing = True
return EditorWindow.close(self)
def _close(self):
"Extend EditorWindow._close(), shut down debugger and execution server"
self.close_debugger()
if use_subprocess:
self.interp.kill_subprocess()
# Restore std streams
sys.stdout = self.save_stdout
sys.stderr = self.save_stderr
sys.stdin = self.save_stdin
# Break cycles
self.interp = None
self.console = None
self.flist.pyshell = None
self.history = None
EditorWindow._close(self)
def ispythonsource(self, filename):
"Override EditorWindow method: never remove the colorizer"
return True
def short_title(self):
return self.shell_title
COPYRIGHT = \
'Type "help", "copyright", "credits" or "license()" for more information.'
def begin(self):
self.text.mark_set("iomark", "insert")
self.resetoutput()
if use_subprocess:
nosub = ''
client = self.interp.start_subprocess()
if not client:
self.close()
return False
else:
nosub = ("==== No Subprocess ====\n\n" +
"WARNING: Running IDLE without a Subprocess is deprecated\n" +
"and will be removed in a later version. See Help/IDLE Help\n" +
"for details.\n\n")
sys.displayhook = rpc.displayhook
self.write("Python %s on %s\n%s\n%s" %
(sys.version, sys.platform, self.COPYRIGHT, nosub))
self.text.focus_force()
self.showprompt()
import tkinter
tkinter._default_root = None # 03Jan04 KBK What's this?
return True
def stop_readline(self):
if not self.reading: # no nested mainloop to exit.
return
self._stop_readline_flag = True
self.top.quit()
def readline(self):
save = self.reading
try:
self.reading = 1
self.top.mainloop() # nested mainloop()
finally:
self.reading = save
if self._stop_readline_flag:
self._stop_readline_flag = False
return ""
line = self.text.get("iomark", "end-1c")
if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
line = "\n"
self.resetoutput()
if self.canceled:
self.canceled = 0
if not use_subprocess:
raise KeyboardInterrupt
if self.endoffile:
self.endoffile = 0
line = ""
return line
def isatty(self):
return True
def cancel_callback(self, event=None):
try:
if self.text.compare("sel.first", "!=", "sel.last"):
return # Active selection -- always use default binding
except:
pass
if not (self.executing or self.reading):
self.resetoutput()
self.interp.write("KeyboardInterrupt\n")
self.showprompt()
return "break"
self.endoffile = 0
self.canceled = 1
if (self.executing and self.interp.rpcclt):
if self.interp.getdebugger():
self.interp.restart_subprocess()
else:
self.interp.interrupt_subprocess()
if self.reading:
self.top.quit() # exit the nested mainloop() in readline()
return "break"
def eof_callback(self, event):
if self.executing and not self.reading:
return # Let the default binding (delete next char) take over
if not (self.text.compare("iomark", "==", "insert") and
self.text.compare("insert", "==", "end-1c")):
return # Let the default binding (delete next char) take over
if not self.executing:
self.resetoutput()
self.close()
else:
self.canceled = 0
self.endoffile = 1
self.top.quit()
return "break"
def linefeed_callback(self, event):
# Insert a linefeed without entering anything (still autoindented)
if self.reading:
self.text.insert("insert", "\n")
self.text.see("insert")
else:
self.newline_and_indent_event(event)
return "break"
def enter_callback(self, event):
if self.executing and not self.reading:
return # Let the default binding (insert '\n') take over
# If some text is selected, recall the selection
# (but only if this before the I/O mark)
try:
sel = self.text.get("sel.first", "sel.last")
if sel:
if self.text.compare("sel.last", "<=", "iomark"):
self.recall(sel, event)
return "break"
except:
pass
# If we're strictly before the line containing iomark, recall
# the current line, less a leading prompt, less leading or
# trailing whitespace
if self.text.compare("insert", "<", "iomark linestart"):
# Check if there's a relevant stdin range -- if so, use it
prev = self.text.tag_prevrange("stdin", "insert")
if prev and self.text.compare("insert", "<", prev[1]):
self.recall(self.text.get(prev[0], prev[1]), event)
return "break"
next = self.text.tag_nextrange("stdin", "insert")
if next and self.text.compare("insert lineend", ">=", next[0]):
self.recall(self.text.get(next[0], next[1]), event)
return "break"
# No stdin mark -- just get the current line, less any prompt
indices = self.text.tag_nextrange("console", "insert linestart")
if indices and \
self.text.compare(indices[0], "<=", "insert linestart"):
self.recall(self.text.get(indices[1], "insert lineend"), event)
else:
self.recall(self.text.get("insert linestart", "insert lineend"), event)
return "break"
# If we're between the beginning of the line and the iomark, i.e.
# in the prompt area, move to the end of the prompt
if self.text.compare("insert", "<", "iomark"):
self.text.mark_set("insert", "iomark")
# If we're in the current input and there's only whitespace
# beyond the cursor, erase that whitespace first
s = self.text.get("insert", "end-1c")
if s and not s.strip():
self.text.delete("insert", "end-1c")
# If we're in the current input before its last line,
# insert a newline right at the insert point
if self.text.compare("insert", "<", "end-1c linestart"):
self.newline_and_indent_event(event)
return "break"
# We're in the last line; append a newline and submit it
self.text.mark_set("insert", "end-1c")
if self.reading:
self.text.insert("insert", "\n")
self.text.see("insert")
else:
self.newline_and_indent_event(event)
self.text.tag_add("stdin", "iomark", "end-1c")
self.text.update_idletasks()
if self.reading:
self.top.quit() # Break out of recursive mainloop()
else:
self.runit()
return "break"
def recall(self, s, event):
# remove leading and trailing empty or whitespace lines
s = re.sub(r'^\s*\n', '' , s)
s = re.sub(r'\n\s*$', '', s)
lines = s.split('\n')
self.text.undo_block_start()
try:
self.text.tag_remove("sel", "1.0", "end")
self.text.mark_set("insert", "end-1c")
prefix = self.text.get("insert linestart", "insert")
if prefix.rstrip().endswith(':'):
self.newline_and_indent_event(event)
prefix = self.text.get("insert linestart", "insert")
self.text.insert("insert", lines[0].strip())
if len(lines) > 1:
orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
for line in lines[1:]:
if line.startswith(orig_base_indent):
# replace orig base indentation with new indentation
line = new_base_indent + line[len(orig_base_indent):]
self.text.insert('insert', '\n'+line.rstrip())
finally:
self.text.see("insert")
self.text.undo_block_stop()
def runit(self):
line = self.text.get("iomark", "end-1c")
# Strip off last newline and surrounding whitespace.
# (To allow you to hit return twice to end a statement.)
i = len(line)
while i > 0 and line[i-1] in " \t":
i = i-1
if i > 0 and line[i-1] == "\n":
i = i-1
while i > 0 and line[i-1] in " \t":
i = i-1
line = line[:i]
self.interp.runsource(line)
def open_stack_viewer(self, event=None):
if self.interp.rpcclt:
return self.interp.remote_stack_viewer()
try:
sys.last_traceback
except:
tkMessageBox.showerror("No stack trace",
"There is no stack trace yet.\n"
"(sys.last_traceback is not defined)",
parent=self.text)
return
from idlelib.stackviewer import StackBrowser
StackBrowser(self.root, self.flist)
def view_restart_mark(self, event=None):
self.text.see("iomark")
self.text.see("restart")
def restart_shell(self, event=None):
"Callback for Run/Restart Shell Cntl-F6"
self.interp.restart_subprocess(with_cwd=True)
def showprompt(self):
self.resetoutput()
self.console.write(self.prompt)
self.text.mark_set("insert", "end-1c")
self.set_line_and_column()
self.io.reset_undo()
def show_warning(self, msg):
width = self.interp.tkconsole.width
wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True)
wrapped_msg = '\n'.join(wrapper.wrap(msg))
if not wrapped_msg.endswith('\n'):
wrapped_msg += '\n'
self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr")
def resetoutput(self):
source = self.text.get("iomark", "end-1c")
if self.history:
self.history.store(source)
if self.text.get("end-2c") != "\n":
self.text.insert("end-1c", "\n")
self.text.mark_set("iomark", "end-1c")
self.set_line_and_column()
def write(self, s, tags=()):
if isinstance(s, str) and len(s) and max(s) > '\uffff':
# Tk doesn't support outputting non-BMP characters
# Let's assume what printed string is not very long,
# find first non-BMP character and construct informative
# UnicodeEncodeError exception.
for start, char in enumerate(s):
if char > '\uffff':
break
raise UnicodeEncodeError("UCS-2", char, start, start+1,
'Non-BMP character not supported in Tk')
try:
self.text.mark_gravity("iomark", "right")
count = OutputWindow.write(self, s, tags, "iomark")
self.text.mark_gravity("iomark", "left")
except:
raise ###pass # ### 11Aug07 KBK if we are expecting exceptions
# let's find out what they are and be specific.
if self.canceled:
self.canceled = 0
if not use_subprocess:
raise KeyboardInterrupt
return count
def rmenu_check_cut(self):
try:
if self.text.compare('sel.first', '<', 'iomark'):
return 'disabled'
except TclError: # no selection, so the index 'sel.first' doesn't exist
return 'disabled'
return super().rmenu_check_cut()
def rmenu_check_paste(self):
if self.text.compare('insert','<','iomark'):
return 'disabled'
return super().rmenu_check_paste()
def fix_x11_paste(root):
"Make paste replace selection on x11. See issue #5124."
if root._windowingsystem == 'x11':
for cls in 'Text', 'Entry', 'Spinbox':
root.bind_class(
cls,
'<<Paste>>',
'catch {%W delete sel.first sel.last}\n' +
root.bind_class(cls, '<<Paste>>'))
usage_msg = """\
USAGE: idle [-deins] [-t title] [file]*
idle [-dns] [-t title] (-c cmd | -r file) [arg]*
idle [-dns] [-t title] - [arg]*
-h print this help message and exit
-n run IDLE without a subprocess (DEPRECATED,
see Help/IDLE Help for details)
The following options will override the IDLE 'settings' configuration:
-e open an edit window
-i open a shell window
The following options imply -i and will open a shell:
-c cmd run the command in a shell, or
-r file run script from file
-d enable the debugger
-s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
-t title set title of shell window
A default edit window will be bypassed when -c, -r, or - are used.
[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
Examples:
idle
Open an edit window or shell depending on IDLE's configuration.
idle foo.py foobar.py
Edit the files, also open a shell if configured to start with shell.
idle -est "Baz" foo.py
Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
window with the title "Baz".
idle -c "import sys; print(sys.argv)" "foo"
Open a shell window and run the command, passing "-c" in sys.argv[0]
and "foo" in sys.argv[1].
idle -d -s -r foo.py "Hello World"
Open a shell window, run a startup script, enable the debugger, and
run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
sys.argv[1].
echo "import sys; print(sys.argv)" | idle - "foobar"
Open a shell window, run the script piped in, passing '' in sys.argv[0]
and "foobar" in sys.argv[1].
"""
def main():
import getopt
from platform import system
from idlelib import testing # bool value
from idlelib import macosx
global flist, root, use_subprocess
capture_warnings(True)
use_subprocess = True
enable_shell = False
enable_edit = False
debug = False
cmd = None
script = None
startup = False
try:
opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
except getopt.error as msg:
print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr)
sys.exit(2)
for o, a in opts:
if o == '-c':
cmd = a
enable_shell = True
if o == '-d':
debug = True
enable_shell = True
if o == '-e':
enable_edit = True
if o == '-h':
sys.stdout.write(usage_msg)
sys.exit()
if o == '-i':
enable_shell = True
if o == '-n':
print(" Warning: running IDLE without a subprocess is deprecated.",
file=sys.stderr)
use_subprocess = False
if o == '-r':
script = a
if os.path.isfile(script):
pass
else:
print("No script file: ", script)
sys.exit()
enable_shell = True
if o == '-s':
startup = True
enable_shell = True
if o == '-t':
PyShell.shell_title = a
enable_shell = True
if args and args[0] == '-':
cmd = sys.stdin.read()
enable_shell = True
# process sys.argv and sys.path:
for i in range(len(sys.path)):
sys.path[i] = os.path.abspath(sys.path[i])
if args and args[0] == '-':
sys.argv = [''] + args[1:]
elif cmd:
sys.argv = ['-c'] + args
elif script:
sys.argv = [script] + args
elif args:
enable_edit = True
pathx = []
for filename in args:
pathx.append(os.path.dirname(filename))
for dir in pathx:
dir = os.path.abspath(dir)
if not dir in sys.path:
sys.path.insert(0, dir)
else:
dir = os.getcwd()
if dir not in sys.path:
sys.path.insert(0, dir)
# check the IDLE settings configuration (but command line overrides)
edit_start = idleConf.GetOption('main', 'General',
'editor-on-startup', type='bool')
enable_edit = enable_edit or edit_start
enable_shell = enable_shell or not enable_edit
# Setup root. Don't break user code run in IDLE process.
# Don't change environment when testing.
if use_subprocess and not testing:
NoDefaultRoot()
root = Tk(className="Idle")
root.withdraw()
from idlelib.run import fix_scaling
fix_scaling(root)
# set application icon
icondir = os.path.join(os.path.dirname(__file__), 'Icons')
if system() == 'Windows':
iconfile = os.path.join(icondir, 'idle.ico')
root.wm_iconbitmap(default=iconfile)
else:
ext = '.png' if TkVersion >= 8.6 else '.gif'
iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
for size in (16, 32, 48)]
icons = [PhotoImage(master=root, file=iconfile)
for iconfile in iconfiles]
root.wm_iconphoto(True, *icons)
# start editor and/or shell windows:
fixwordbreaks(root)
fix_x11_paste(root)
flist = PyShellFileList(root)
macosx.setupApp(root, flist)
if enable_edit:
if not (cmd or script):
for filename in args[:]:
if flist.open(filename) is None:
# filename is a directory actually, disconsider it
args.remove(filename)
if not args:
flist.new()
if enable_shell:
shell = flist.open_shell()
if not shell:
return # couldn't open shell
if macosx.isAquaTk() and flist.dict:
# On OSX: when the user has double-clicked on a file that causes
# IDLE to be launched the shell window will open just in front of
# the file she wants to see. Lower the interpreter window when
# there are open files.
shell.top.lower()
else:
shell = flist.pyshell
# Handle remaining options. If any of these are set, enable_shell
# was set also, so shell must be true to reach here.
if debug:
shell.open_debugger()
if startup:
filename = os.environ.get("IDLESTARTUP") or \
os.environ.get("PYTHONSTARTUP")
if filename and os.path.isfile(filename):
shell.interp.execfile(filename)
if cmd or script:
shell.interp.runcommand("""if 1:
import sys as _sys
_sys.argv = %r
del _sys
\n""" % (sys.argv,))
if cmd:
shell.interp.execsource(cmd)
elif script:
shell.interp.prepend_syspath(script)
shell.interp.execfile(script)
elif shell:
# If there is a shell window and no cmd or script in progress,
# check for problematic issues and print warning message(s) in
# the IDLE shell window; this is less intrusive than always
# opening a separate window.
# Warn if using a problematic OS X Tk version.
tkversionwarning = macosx.tkVersionWarning(root)
if tkversionwarning:
shell.show_warning(tkversionwarning)
# Warn if the "Prefer tabs when opening documents" system
# preference is set to "Always".
prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning()
if prefer_tabs_preference_warning:
shell.show_warning(prefer_tabs_preference_warning)
while flist.inversedict: # keep IDLE running while files are open.
root.mainloop()
root.destroy()
capture_warnings(False)
if __name__ == "__main__":
sys.modules['pyshell'] = sys.modules['__main__']
main()
capture_warnings(False) # Make sure turned off; see issue 18081
| 57,717 | 1,578 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/tree.py | # XXX TO DO:
# - popup menu
# - support partial or total redisplay
# - key bindings (instead of quick-n-dirty bindings on Canvas):
# - up/down arrow keys to move focus around
# - ditto for page up/down, home/end
# - left/right arrows to expand/collapse & move out/in
# - more doc strings
# - add icons for "file", "module", "class", "method"; better "python" icon
# - callback for selection???
# - multiple-item selection
# - tooltips
# - redo geometry without magic numbers
# - keep track of object ids to allow more careful cleaning
# - optimize tree redraw after expand of subnode
import os
from tkinter import *
from tkinter.ttk import Scrollbar
from idlelib.config import idleConf
from idlelib import zoomheight
ICONDIR = "Icons"
# Look for Icons subdirectory in the same directory as this module
try:
_icondir = os.path.join(os.path.dirname(__file__), ICONDIR)
except NameError:
_icondir = ICONDIR
if os.path.isdir(_icondir):
ICONDIR = _icondir
elif not os.path.isdir(ICONDIR):
raise RuntimeError("can't find icon directory (%r)" % (ICONDIR,))
def listicons(icondir=ICONDIR):
"""Utility to display the available icons."""
root = Tk()
import glob
list = glob.glob(os.path.join(icondir, "*.gif"))
list.sort()
images = []
row = column = 0
for file in list:
name = os.path.splitext(os.path.basename(file))[0]
image = PhotoImage(file=file, master=root)
images.append(image)
label = Label(root, image=image, bd=1, relief="raised")
label.grid(row=row, column=column)
label = Label(root, text=name)
label.grid(row=row+1, column=column)
column = column + 1
if column >= 10:
row = row+2
column = 0
root.images = images
class TreeNode:
def __init__(self, canvas, parent, item):
self.canvas = canvas
self.parent = parent
self.item = item
self.state = 'collapsed'
self.selected = False
self.children = []
self.x = self.y = None
self.iconimages = {} # cache of PhotoImage instances for icons
def destroy(self):
for c in self.children[:]:
self.children.remove(c)
c.destroy()
self.parent = None
def geticonimage(self, name):
try:
return self.iconimages[name]
except KeyError:
pass
file, ext = os.path.splitext(name)
ext = ext or ".gif"
fullname = os.path.join(ICONDIR, file + ext)
image = PhotoImage(master=self.canvas, file=fullname)
self.iconimages[name] = image
return image
def select(self, event=None):
if self.selected:
return
self.deselectall()
self.selected = True
self.canvas.delete(self.image_id)
self.drawicon()
self.drawtext()
def deselect(self, event=None):
if not self.selected:
return
self.selected = False
self.canvas.delete(self.image_id)
self.drawicon()
self.drawtext()
def deselectall(self):
if self.parent:
self.parent.deselectall()
else:
self.deselecttree()
def deselecttree(self):
if self.selected:
self.deselect()
for child in self.children:
child.deselecttree()
def flip(self, event=None):
if self.state == 'expanded':
self.collapse()
else:
self.expand()
self.item.OnDoubleClick()
return "break"
def expand(self, event=None):
if not self.item._IsExpandable():
return
if self.state != 'expanded':
self.state = 'expanded'
self.update()
self.view()
def collapse(self, event=None):
if self.state != 'collapsed':
self.state = 'collapsed'
self.update()
def view(self):
top = self.y - 2
bottom = self.lastvisiblechild().y + 17
height = bottom - top
visible_top = self.canvas.canvasy(0)
visible_height = self.canvas.winfo_height()
visible_bottom = self.canvas.canvasy(visible_height)
if visible_top <= top and bottom <= visible_bottom:
return
x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
if top >= visible_top and height <= visible_height:
fraction = top + height - visible_height
else:
fraction = top
fraction = float(fraction) / y1
self.canvas.yview_moveto(fraction)
def lastvisiblechild(self):
if self.children and self.state == 'expanded':
return self.children[-1].lastvisiblechild()
else:
return self
def update(self):
if self.parent:
self.parent.update()
else:
oldcursor = self.canvas['cursor']
self.canvas['cursor'] = "watch"
self.canvas.update()
self.canvas.delete(ALL) # XXX could be more subtle
self.draw(7, 2)
x0, y0, x1, y1 = self.canvas.bbox(ALL)
self.canvas.configure(scrollregion=(0, 0, x1, y1))
self.canvas['cursor'] = oldcursor
def draw(self, x, y):
# XXX This hard-codes too many geometry constants!
dy = 20
self.x, self.y = x, y
self.drawicon()
self.drawtext()
if self.state != 'expanded':
return y + dy
# draw children
if not self.children:
sublist = self.item._GetSubList()
if not sublist:
# _IsExpandable() was mistaken; that's allowed
return y+17
for item in sublist:
child = self.__class__(self.canvas, self, item)
self.children.append(child)
cx = x+20
cy = y + dy
cylast = 0
for child in self.children:
cylast = cy
self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
cy = child.draw(cx, cy)
if child.item._IsExpandable():
if child.state == 'expanded':
iconname = "minusnode"
callback = child.collapse
else:
iconname = "plusnode"
callback = child.expand
image = self.geticonimage(iconname)
id = self.canvas.create_image(x+9, cylast+7, image=image)
# XXX This leaks bindings until canvas is deleted:
self.canvas.tag_bind(id, "<1>", callback)
self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
##stipple="gray50", # XXX Seems broken in Tk 8.0.x
fill="gray50")
self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
return cy
def drawicon(self):
if self.selected:
imagename = (self.item.GetSelectedIconName() or
self.item.GetIconName() or
"openfolder")
else:
imagename = self.item.GetIconName() or "folder"
image = self.geticonimage(imagename)
id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
self.image_id = id
self.canvas.tag_bind(id, "<1>", self.select)
self.canvas.tag_bind(id, "<Double-1>", self.flip)
def drawtext(self):
textx = self.x+20-1
texty = self.y-4
labeltext = self.item.GetLabelText()
if labeltext:
id = self.canvas.create_text(textx, texty, anchor="nw",
text=labeltext)
self.canvas.tag_bind(id, "<1>", self.select)
self.canvas.tag_bind(id, "<Double-1>", self.flip)
x0, y0, x1, y1 = self.canvas.bbox(id)
textx = max(x1, 200) + 10
text = self.item.GetText() or "<no text>"
try:
self.entry
except AttributeError:
pass
else:
self.edit_finish()
try:
self.label
except AttributeError:
# padding carefully selected (on Windows) to match Entry widget:
self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
theme = idleConf.CurrentTheme()
if self.selected:
self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
else:
self.label.configure(idleConf.GetHighlight(theme, 'normal'))
id = self.canvas.create_window(textx, texty,
anchor="nw", window=self.label)
self.label.bind("<1>", self.select_or_edit)
self.label.bind("<Double-1>", self.flip)
self.text_id = id
def select_or_edit(self, event=None):
if self.selected and self.item.IsEditable():
self.edit(event)
else:
self.select(event)
def edit(self, event=None):
self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
self.entry.insert(0, self.label['text'])
self.entry.selection_range(0, END)
self.entry.pack(ipadx=5)
self.entry.focus_set()
self.entry.bind("<Return>", self.edit_finish)
self.entry.bind("<Escape>", self.edit_cancel)
def edit_finish(self, event=None):
try:
entry = self.entry
del self.entry
except AttributeError:
return
text = entry.get()
entry.destroy()
if text and text != self.item.GetText():
self.item.SetText(text)
text = self.item.GetText()
self.label['text'] = text
self.drawtext()
self.canvas.focus_set()
def edit_cancel(self, event=None):
try:
entry = self.entry
del self.entry
except AttributeError:
return
entry.destroy()
self.drawtext()
self.canvas.focus_set()
class TreeItem:
"""Abstract class representing tree items.
Methods should typically be overridden, otherwise a default action
is used.
"""
def __init__(self):
"""Constructor. Do whatever you need to do."""
def GetText(self):
"""Return text string to display."""
def GetLabelText(self):
"""Return label text string to display in front of text (if any)."""
expandable = None
def _IsExpandable(self):
"""Do not override! Called by TreeNode."""
if self.expandable is None:
self.expandable = self.IsExpandable()
return self.expandable
def IsExpandable(self):
"""Return whether there are subitems."""
return 1
def _GetSubList(self):
"""Do not override! Called by TreeNode."""
if not self.IsExpandable():
return []
sublist = self.GetSubList()
if not sublist:
self.expandable = 0
return sublist
def IsEditable(self):
"""Return whether the item's text may be edited."""
def SetText(self, text):
"""Change the item's text (if it is editable)."""
def GetIconName(self):
"""Return name of icon to be displayed normally."""
def GetSelectedIconName(self):
"""Return name of icon to be displayed when selected."""
def GetSubList(self):
"""Return list of items forming sublist."""
def OnDoubleClick(self):
"""Called on a double-click on the item."""
# Example application
class FileTreeItem(TreeItem):
"""Example TreeItem subclass -- browse the file system."""
def __init__(self, path):
self.path = path
def GetText(self):
return os.path.basename(self.path) or self.path
def IsEditable(self):
return os.path.basename(self.path) != ""
def SetText(self, text):
newpath = os.path.dirname(self.path)
newpath = os.path.join(newpath, text)
if os.path.dirname(newpath) != os.path.dirname(self.path):
return
try:
os.rename(self.path, newpath)
self.path = newpath
except OSError:
pass
def GetIconName(self):
if not self.IsExpandable():
return "python" # XXX wish there was a "file" icon
def IsExpandable(self):
return os.path.isdir(self.path)
def GetSubList(self):
try:
names = os.listdir(self.path)
except OSError:
return []
names.sort(key = os.path.normcase)
sublist = []
for name in names:
item = FileTreeItem(os.path.join(self.path, name))
sublist.append(item)
return sublist
# A canvas widget with scroll bars and some useful bindings
class ScrolledCanvas:
def __init__(self, master, **opts):
if 'yscrollincrement' not in opts:
opts['yscrollincrement'] = 17
self.master = master
self.frame = Frame(master)
self.frame.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
self.canvas = Canvas(self.frame, **opts)
self.canvas.grid(row=0, column=0, sticky="nsew")
self.vbar = Scrollbar(self.frame, name="vbar")
self.vbar.grid(row=0, column=1, sticky="nse")
self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
self.hbar.grid(row=1, column=0, sticky="ews")
self.canvas['yscrollcommand'] = self.vbar.set
self.vbar['command'] = self.canvas.yview
self.canvas['xscrollcommand'] = self.hbar.set
self.hbar['command'] = self.canvas.xview
self.canvas.bind("<Key-Prior>", self.page_up)
self.canvas.bind("<Key-Next>", self.page_down)
self.canvas.bind("<Key-Up>", self.unit_up)
self.canvas.bind("<Key-Down>", self.unit_down)
#if isinstance(master, Toplevel) or isinstance(master, Tk):
self.canvas.bind("<Alt-Key-2>", self.zoom_height)
self.canvas.focus_set()
def page_up(self, event):
self.canvas.yview_scroll(-1, "page")
return "break"
def page_down(self, event):
self.canvas.yview_scroll(1, "page")
return "break"
def unit_up(self, event):
self.canvas.yview_scroll(-1, "unit")
return "break"
def unit_down(self, event):
self.canvas.yview_scroll(1, "unit")
return "break"
def zoom_height(self, event):
zoomheight.zoom_height(self.master)
return "break"
def _tree_widget(parent): # htest #
top = Toplevel(parent)
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" % (x+50, y+175))
sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both", side=LEFT)
item = FileTreeItem(ICONDIR)
node = TreeNode(sc.canvas, None, item)
node.expand()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_tree', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_tree_widget)
| 15,089 | 470 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle.py | import os.path
import sys
# Enable running IDLE with idlelib in a non-standard location.
# This was once used to run development versions of IDLE.
# Because PEP 434 declared idle.py a public interface,
# removal should require deprecation.
idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if idlelib_dir not in sys.path:
sys.path.insert(0, idlelib_dir)
from idlelib.pyshell import main # This is subject to change
main()
| 454 | 15 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/zoomheight.py | "Zoom a window to maximum height."
import re
import sys
from idlelib import macosx
class ZoomHeight:
def __init__(self, editwin):
self.editwin = editwin
def zoom_height_event(self, event=None):
top = self.editwin.top
zoom_height(top)
return "break"
def zoom_height(top):
geom = top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
if not m:
top.bell()
return
width, height, x, y = map(int, m.groups())
newheight = top.winfo_screenheight()
if sys.platform == 'win32':
newy = 0
newheight = newheight - 72
elif macosx.isAquaTk():
# The '88' below is a magic number that avoids placing the bottom
# of the window below the panel on my machine. I don't know how
# to calculate the correct value for this with tkinter.
newy = 22
newheight = newheight - newy - 88
else:
#newy = 24
newy = 0
#newheight = newheight - 96
newheight = newheight - 88
if height >= newheight:
newgeom = ""
else:
newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
top.wm_geometry(newgeom)
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_zoomheight', verbosity=2, exit=False)
# Add htest?
| 1,340 | 56 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/paragraph.py | """Format a paragraph, comment block, or selection to a max width.
Does basic, standard text formatting, and also understands Python
comment blocks. Thus, for editing Python source code, this
extension is really only suitable for reformatting these comment
blocks or triple-quoted strings.
Known problems with comment reformatting:
* If there is a selection marked, and the first line of the
selection is not complete, the block will probably not be detected
as comments, and will have the normal "text formatting" rules
applied.
* If a comment block has leading whitespace that mixes tabs and
spaces, they will not be considered part of the same block.
* Fancy comments, like this bulleted list, aren't handled :-)
"""
import re
from idlelib.config import idleConf
class FormatParagraph:
def __init__(self, editwin):
self.editwin = editwin
@classmethod
def reload(cls):
cls.max_width = idleConf.GetOption('extensions', 'FormatParagraph',
'max-width', type='int', default=72)
def close(self):
self.editwin = None
def format_paragraph_event(self, event, limit=None):
"""Formats paragraph to a max width specified in idleConf.
If text is selected, format_paragraph_event will start breaking lines
at the max width, starting from the beginning selection.
If no text is selected, format_paragraph_event uses the current
cursor location to determine the paragraph (lines of text surrounded
by blank lines) and formats it.
The length limit parameter is for testing with a known value.
"""
limit = self.max_width if limit is None else limit
text = self.editwin.text
first, last = self.editwin.get_selection_indices()
if first and last:
data = text.get(first, last)
comment_header = get_comment_header(data)
else:
first, last, comment_header, data = \
find_paragraph(text, text.index("insert"))
if comment_header:
newdata = reformat_comment(data, limit, comment_header)
else:
newdata = reformat_paragraph(data, limit)
text.tag_remove("sel", "1.0", "end")
if newdata != data:
text.mark_set("insert", first)
text.undo_block_start()
text.delete(first, last)
text.insert(first, newdata)
text.undo_block_stop()
else:
text.mark_set("insert", last)
text.see("insert")
return "break"
FormatParagraph.reload()
def find_paragraph(text, mark):
"""Returns the start/stop indices enclosing the paragraph that mark is in.
Also returns the comment format string, if any, and paragraph of text
between the start/stop indices.
"""
lineno, col = map(int, mark.split("."))
line = text.get("%d.0" % lineno, "%d.end" % lineno)
# Look for start of next paragraph if the index passed in is a blank line
while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
lineno = lineno + 1
line = text.get("%d.0" % lineno, "%d.end" % lineno)
first_lineno = lineno
comment_header = get_comment_header(line)
comment_header_len = len(comment_header)
# Once start line found, search for end of paragraph (a blank line)
while get_comment_header(line)==comment_header and \
not is_all_white(line[comment_header_len:]):
lineno = lineno + 1
line = text.get("%d.0" % lineno, "%d.end" % lineno)
last = "%d.0" % lineno
# Search back to beginning of paragraph (first blank line before)
lineno = first_lineno - 1
line = text.get("%d.0" % lineno, "%d.end" % lineno)
while lineno > 0 and \
get_comment_header(line)==comment_header and \
not is_all_white(line[comment_header_len:]):
lineno = lineno - 1
line = text.get("%d.0" % lineno, "%d.end" % lineno)
first = "%d.0" % (lineno+1)
return first, last, comment_header, text.get(first, last)
# This should perhaps be replaced with textwrap.wrap
def reformat_paragraph(data, limit):
"""Return data reformatted to specified width (limit)."""
lines = data.split("\n")
i = 0
n = len(lines)
while i < n and is_all_white(lines[i]):
i = i+1
if i >= n:
return data
indent1 = get_indent(lines[i])
if i+1 < n and not is_all_white(lines[i+1]):
indent2 = get_indent(lines[i+1])
else:
indent2 = indent1
new = lines[:i]
partial = indent1
while i < n and not is_all_white(lines[i]):
# XXX Should take double space after period (etc.) into account
words = re.split(r"(\s+)", lines[i])
for j in range(0, len(words), 2):
word = words[j]
if not word:
continue # Can happen when line ends in whitespace
if len((partial + word).expandtabs()) > limit and \
partial != indent1:
new.append(partial.rstrip())
partial = indent2
partial = partial + word + " "
if j+1 < len(words) and words[j+1] != " ":
partial = partial + " "
i = i+1
new.append(partial.rstrip())
# XXX Should reformat remaining paragraphs as well
new.extend(lines[i:])
return "\n".join(new)
def reformat_comment(data, limit, comment_header):
"""Return data reformatted to specified width with comment header."""
# Remove header from the comment lines
lc = len(comment_header)
data = "\n".join(line[lc:] for line in data.split("\n"))
# Reformat to maxformatwidth chars or a 20 char width,
# whichever is greater.
format_width = max(limit - len(comment_header), 20)
newdata = reformat_paragraph(data, format_width)
# re-split and re-insert the comment header.
newdata = newdata.split("\n")
# If the block ends in a \n, we don't want the comment prefix
# inserted after it. (Im not sure it makes sense to reformat a
# comment block that is not made of complete lines, but whatever!)
# Can't think of a clean solution, so we hack away
block_suffix = ""
if not newdata[-1]:
block_suffix = "\n"
newdata = newdata[:-1]
return '\n'.join(comment_header+line for line in newdata) + block_suffix
def is_all_white(line):
"""Return True if line is empty or all whitespace."""
return re.match(r"^\s*$", line) is not None
def get_indent(line):
"""Return the initial space or tab indent of line."""
return re.match(r"^([ \t]*)", line).group()
def get_comment_header(line):
"""Return string with leading whitespace and '#' from line or ''.
A null return indicates that the line is not a comment line. A non-
null return, such as ' #', will be used to find the other lines of
a comment block with the same indent.
"""
m = re.match(r"^([ \t]*#*)", line)
if m is None: return ""
return m.group(1)
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_paragraph', verbosity=2, exit=False)
| 7,167 | 195 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/editor.py | import importlib.abc
import importlib.util
import os
import platform
import string
import tokenize
import traceback
import webbrowser
from tkinter import *
from tkinter.ttk import Scrollbar
import tkinter.simpledialog as tkSimpleDialog
import tkinter.messagebox as tkMessageBox
from idlelib.config import idleConf
from idlelib import configdialog
from idlelib import grep
from idlelib import help
from idlelib import help_about
from idlelib import macosx
from idlelib.multicall import MultiCallCreator
from idlelib import pyparse
from idlelib import query
from idlelib import replace
from idlelib import search
from idlelib import window
# The default tab setting for a Text widget, in average-width characters.
TK_TABWIDTH_DEFAULT = 8
_py_version = ' (%s)' % platform.python_version()
darwin = sys.platform == 'darwin'
def _sphinx_version():
"Format sys.version_info to produce the Sphinx version string used to install the chm docs"
major, minor, micro, level, serial = sys.version_info
release = '%s%s' % (major, minor)
release += '%s' % (micro,)
if level == 'candidate':
release += 'rc%s' % (serial,)
elif level != 'final':
release += '%s%s' % (level[0], serial)
return release
class EditorWindow(object):
from idlelib.percolator import Percolator
from idlelib.colorizer import ColorDelegator, color_config
from idlelib.undo import UndoDelegator
from idlelib.iomenu import IOBinding, encoding
from idlelib import mainmenu
from idlelib.statusbar import MultiStatusBar
from idlelib.autocomplete import AutoComplete
from idlelib.autoexpand import AutoExpand
from idlelib.calltip import Calltip
from idlelib.codecontext import CodeContext
from idlelib.paragraph import FormatParagraph
from idlelib.parenmatch import ParenMatch
from idlelib.rstrip import Rstrip
from idlelib.squeezer import Squeezer
from idlelib.zoomheight import ZoomHeight
filesystemencoding = sys.getfilesystemencoding() # for file names
help_url = None
def __init__(self, flist=None, filename=None, key=None, root=None):
# Delay import: runscript imports pyshell imports EditorWindow.
from idlelib.runscript import ScriptBinding
if EditorWindow.help_url is None:
dochome = os.path.join(sys.base_prefix, 'Doc', 'index.html')
if sys.platform.count('linux'):
# look for html docs in a couple of standard places
pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3]
if os.path.isdir('/var/www/html/python/'): # "python2" rpm
dochome = '/var/www/html/python/index.html'
else:
basepath = '/usr/share/doc/' # standard location
dochome = os.path.join(basepath, pyver,
'Doc', 'index.html')
elif sys.platform[:3] == 'win':
chmfile = os.path.join(sys.base_prefix, 'Doc',
'Python%s.chm' % _sphinx_version())
if os.path.isfile(chmfile):
dochome = chmfile
elif sys.platform == 'darwin':
# documentation may be stored inside a python framework
dochome = os.path.join(sys.base_prefix,
'Resources/English.lproj/Documentation/index.html')
dochome = os.path.normpath(dochome)
if os.path.isfile(dochome):
EditorWindow.help_url = dochome
if sys.platform == 'darwin':
# Safari requires real file:-URLs
EditorWindow.help_url = 'file://' + EditorWindow.help_url
else:
EditorWindow.help_url = ("https://docs.python.org/%d.%d/"
% sys.version_info[:2])
self.flist = flist
root = root or flist.root
self.root = root
self.menubar = Menu(root)
self.top = top = window.ListedToplevel(root, menu=self.menubar)
if flist:
self.tkinter_vars = flist.vars
#self.top.instance_dict makes flist.inversedict available to
#configdialog.py so it can access all EditorWindow instances
self.top.instance_dict = flist.inversedict
else:
self.tkinter_vars = {} # keys: Tkinter event names
# values: Tkinter variable instances
self.top.instance_dict = {}
self.recent_files_path = os.path.join(
idleConf.userdir, 'recent-files.lst')
self.prompt_last_line = '' # Override in PyShell
self.text_frame = text_frame = Frame(top)
self.vbar = vbar = Scrollbar(text_frame, name='vbar')
self.width = idleConf.GetOption('main', 'EditorWindow',
'width', type='int')
text_options = {
'name': 'text',
'padx': 5,
'wrap': 'none',
'highlightthickness': 0,
'width': self.width,
'tabstyle': 'wordprocessor', # new in 8.5
'height': idleConf.GetOption(
'main', 'EditorWindow', 'height', type='int'),
}
self.text = text = MultiCallCreator(Text)(text_frame, **text_options)
self.top.focused_widget = self.text
self.createmenubar()
self.apply_bindings()
self.top.protocol("WM_DELETE_WINDOW", self.close)
self.top.bind("<<close-window>>", self.close_event)
if macosx.isAquaTk():
# Command-W on editor windows doesn't work without this.
text.bind('<<close-window>>', self.close_event)
# Some OS X systems have only one mouse button, so use
# control-click for popup context menus there. For two
# buttons, AquaTk defines <2> as the right button, not <3>.
text.bind("<Control-Button-1>",self.right_menu_event)
text.bind("<2>", self.right_menu_event)
else:
# Elsewhere, use right-click for popup menus.
text.bind("<3>",self.right_menu_event)
text.bind('<MouseWheel>', self.mousescroll)
text.bind('<Button-4>', self.mousescroll)
text.bind('<Button-5>', self.mousescroll)
text.bind("<<cut>>", self.cut)
text.bind("<<copy>>", self.copy)
text.bind("<<paste>>", self.paste)
text.bind("<<center-insert>>", self.center_insert_event)
text.bind("<<help>>", self.help_dialog)
text.bind("<<python-docs>>", self.python_docs)
text.bind("<<about-idle>>", self.about_dialog)
text.bind("<<open-config-dialog>>", self.config_dialog)
text.bind("<<open-module>>", self.open_module_event)
text.bind("<<do-nothing>>", lambda event: "break")
text.bind("<<select-all>>", self.select_all)
text.bind("<<remove-selection>>", self.remove_selection)
text.bind("<<find>>", self.find_event)
text.bind("<<find-again>>", self.find_again_event)
text.bind("<<find-in-files>>", self.find_in_files_event)
text.bind("<<find-selection>>", self.find_selection_event)
text.bind("<<replace>>", self.replace_event)
text.bind("<<goto-line>>", self.goto_line_event)
text.bind("<<smart-backspace>>",self.smart_backspace_event)
text.bind("<<newline-and-indent>>",self.newline_and_indent_event)
text.bind("<<smart-indent>>",self.smart_indent_event)
text.bind("<<indent-region>>",self.indent_region_event)
text.bind("<<dedent-region>>",self.dedent_region_event)
text.bind("<<comment-region>>",self.comment_region_event)
text.bind("<<uncomment-region>>",self.uncomment_region_event)
text.bind("<<tabify-region>>",self.tabify_region_event)
text.bind("<<untabify-region>>",self.untabify_region_event)
text.bind("<<toggle-tabs>>",self.toggle_tabs_event)
text.bind("<<change-indentwidth>>",self.change_indentwidth_event)
text.bind("<Left>", self.move_at_edge_if_selection(0))
text.bind("<Right>", self.move_at_edge_if_selection(1))
text.bind("<<del-word-left>>", self.del_word_left)
text.bind("<<del-word-right>>", self.del_word_right)
text.bind("<<beginning-of-line>>", self.home_callback)
if flist:
flist.inversedict[self] = key
if key:
flist.dict[key] = self
text.bind("<<open-new-window>>", self.new_callback)
text.bind("<<close-all-windows>>", self.flist.close_all_callback)
text.bind("<<open-class-browser>>", self.open_module_browser)
text.bind("<<open-path-browser>>", self.open_path_browser)
text.bind("<<open-turtle-demo>>", self.open_turtle_demo)
self.set_status_bar()
vbar['command'] = self.handle_yview
vbar.pack(side=RIGHT, fill=Y)
text['yscrollcommand'] = vbar.set
text['font'] = idleConf.GetFont(self.root, 'main', 'EditorWindow')
text_frame.pack(side=LEFT, fill=BOTH, expand=1)
text.pack(side=TOP, fill=BOTH, expand=1)
text.focus_set()
# usetabs true -> literal tab characters are used by indent and
# dedent cmds, possibly mixed with spaces if
# indentwidth is not a multiple of tabwidth,
# which will cause Tabnanny to nag!
# false -> tab characters are converted to spaces by indent
# and dedent cmds, and ditto TAB keystrokes
# Although use-spaces=0 can be configured manually in config-main.def,
# configuration of tabs v. spaces is not supported in the configuration
# dialog. IDLE promotes the preferred Python indentation: use spaces!
usespaces = idleConf.GetOption('main', 'Indent',
'use-spaces', type='bool')
self.usetabs = not usespaces
# tabwidth is the display width of a literal tab character.
# CAUTION: telling Tk to use anything other than its default
# tab setting causes it to use an entirely different tabbing algorithm,
# treating tab stops as fixed distances from the left margin.
# Nobody expects this, so for now tabwidth should never be changed.
self.tabwidth = 8 # must remain 8 until Tk is fixed.
# indentwidth is the number of screen characters per indent level.
# The recommended Python indentation is four spaces.
self.indentwidth = self.tabwidth
self.set_notabs_indentwidth()
# If context_use_ps1 is true, parsing searches back for a ps1 line;
# else searches for a popular (if, def, ...) Python stmt.
self.context_use_ps1 = False
# When searching backwards for a reliable place to begin parsing,
# first start num_context_lines[0] lines back, then
# num_context_lines[1] lines back if that didn't work, and so on.
# The last value should be huge (larger than the # of lines in a
# conceivable file).
# Making the initial values larger slows things down more often.
self.num_context_lines = 50, 500, 5000000
self.per = per = self.Percolator(text)
self.undo = undo = self.UndoDelegator()
per.insertfilter(undo)
text.undo_block_start = undo.undo_block_start
text.undo_block_stop = undo.undo_block_stop
undo.set_saved_change_hook(self.saved_change_hook)
# IOBinding implements file I/O and printing functionality
self.io = io = self.IOBinding(self)
io.set_filename_change_hook(self.filename_change_hook)
self.good_load = False
self.set_indentation_params(False)
self.color = None # initialized below in self.ResetColorizer
if filename:
if os.path.exists(filename) and not os.path.isdir(filename):
if io.loadfile(filename):
self.good_load = True
is_py_src = self.ispythonsource(filename)
self.set_indentation_params(is_py_src)
else:
io.set_filename(filename)
self.good_load = True
self.ResetColorizer()
self.saved_change_hook()
self.update_recent_files_list()
self.load_extensions()
menu = self.menudict.get('window')
if menu:
end = menu.index("end")
if end is None:
end = -1
if end >= 0:
menu.add_separator()
end = end + 1
self.wmenu_end = end
window.register_callback(self.postwindowsmenu)
# Some abstractions so IDLE extensions are cross-IDE
self.askyesno = tkMessageBox.askyesno
self.askinteger = tkSimpleDialog.askinteger
self.showerror = tkMessageBox.showerror
# Add pseudoevents for former extension fixed keys.
# (This probably needs to be done once in the process.)
text.event_add('<<autocomplete>>', '<Key-Tab>')
text.event_add('<<try-open-completions>>', '<KeyRelease-period>',
'<KeyRelease-slash>', '<KeyRelease-backslash>')
text.event_add('<<try-open-calltip>>', '<KeyRelease-parenleft>')
text.event_add('<<refresh-calltip>>', '<KeyRelease-parenright>')
text.event_add('<<paren-closed>>', '<KeyRelease-parenright>',
'<KeyRelease-bracketright>', '<KeyRelease-braceright>')
# Former extension bindings depends on frame.text being packed
# (called from self.ResetColorizer()).
autocomplete = self.AutoComplete(self)
text.bind("<<autocomplete>>", autocomplete.autocomplete_event)
text.bind("<<try-open-completions>>",
autocomplete.try_open_completions_event)
text.bind("<<force-open-completions>>",
autocomplete.force_open_completions_event)
text.bind("<<expand-word>>", self.AutoExpand(self).expand_word_event)
text.bind("<<format-paragraph>>",
self.FormatParagraph(self).format_paragraph_event)
parenmatch = self.ParenMatch(self)
text.bind("<<flash-paren>>", parenmatch.flash_paren_event)
text.bind("<<paren-closed>>", parenmatch.paren_closed_event)
scriptbinding = ScriptBinding(self)
text.bind("<<check-module>>", scriptbinding.check_module_event)
text.bind("<<run-module>>", scriptbinding.run_module_event)
text.bind("<<do-rstrip>>", self.Rstrip(self).do_rstrip)
ctip = self.Calltip(self)
text.bind("<<try-open-calltip>>", ctip.try_open_calltip_event)
#refresh-calltip must come after paren-closed to work right
text.bind("<<refresh-calltip>>", ctip.refresh_calltip_event)
text.bind("<<force-open-calltip>>", ctip.force_open_calltip_event)
text.bind("<<zoom-height>>", self.ZoomHeight(self).zoom_height_event)
text.bind("<<toggle-code-context>>",
self.CodeContext(self).toggle_code_context_event)
squeezer = self.Squeezer(self)
text.bind("<<squeeze-current-text>>",
squeezer.squeeze_current_text_event)
def _filename_to_unicode(self, filename):
"""Return filename as BMP unicode so diplayable in Tk."""
# Decode bytes to unicode.
if isinstance(filename, bytes):
try:
filename = filename.decode(self.filesystemencoding)
except UnicodeDecodeError:
try:
filename = filename.decode(self.encoding)
except UnicodeDecodeError:
# byte-to-byte conversion
filename = filename.decode('iso8859-1')
# Replace non-BMP char with diamond questionmark.
return re.sub('[\U00010000-\U0010FFFF]', '\ufffd', filename)
def new_callback(self, event):
dirname, basename = self.io.defaultfilename()
self.flist.new(dirname)
return "break"
def home_callback(self, event):
if (event.state & 4) != 0 and event.keysym == "Home":
# state&4==Control. If <Control-Home>, use the Tk binding.
return None
if self.text.index("iomark") and \
self.text.compare("iomark", "<=", "insert lineend") and \
self.text.compare("insert linestart", "<=", "iomark"):
# In Shell on input line, go to just after prompt
insertpt = int(self.text.index("iomark").split(".")[1])
else:
line = self.text.get("insert linestart", "insert lineend")
for insertpt in range(len(line)):
if line[insertpt] not in (' ','\t'):
break
else:
insertpt=len(line)
lineat = int(self.text.index("insert").split('.')[1])
if insertpt == lineat:
insertpt = 0
dest = "insert linestart+"+str(insertpt)+"c"
if (event.state&1) == 0:
# shift was not pressed
self.text.tag_remove("sel", "1.0", "end")
else:
if not self.text.index("sel.first"):
# there was no previous selection
self.text.mark_set("my_anchor", "insert")
else:
if self.text.compare(self.text.index("sel.first"), "<",
self.text.index("insert")):
self.text.mark_set("my_anchor", "sel.first") # extend back
else:
self.text.mark_set("my_anchor", "sel.last") # extend forward
first = self.text.index(dest)
last = self.text.index("my_anchor")
if self.text.compare(first,">",last):
first,last = last,first
self.text.tag_remove("sel", "1.0", "end")
self.text.tag_add("sel", first, last)
self.text.mark_set("insert", dest)
self.text.see("insert")
return "break"
def set_status_bar(self):
self.status_bar = self.MultiStatusBar(self.top)
sep = Frame(self.top, height=1, borderwidth=1, background='grey75')
if sys.platform == "darwin":
# Insert some padding to avoid obscuring some of the statusbar
# by the resize widget.
self.status_bar.set_label('_padding1', ' ', side=RIGHT)
self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
self.status_bar.pack(side=BOTTOM, fill=X)
sep.pack(side=BOTTOM, fill=X)
self.text.bind("<<set-line-and-column>>", self.set_line_and_column)
self.text.event_add("<<set-line-and-column>>",
"<KeyRelease>", "<ButtonRelease>")
self.text.after_idle(self.set_line_and_column)
def set_line_and_column(self, event=None):
line, column = self.text.index(INSERT).split('.')
self.status_bar.set_label('column', 'Col: %s' % column)
self.status_bar.set_label('line', 'Ln: %s' % line)
menu_specs = [
("file", "_File"),
("edit", "_Edit"),
("format", "F_ormat"),
("run", "_Run"),
("options", "_Options"),
("window", "_Window"),
("help", "_Help"),
]
def createmenubar(self):
mbar = self.menubar
self.menudict = menudict = {}
for name, label in self.menu_specs:
underline, label = prepstr(label)
menudict[name] = menu = Menu(mbar, name=name, tearoff=0)
mbar.add_cascade(label=label, menu=menu, underline=underline)
if macosx.isCarbonTk():
# Insert the application menu
menudict['application'] = menu = Menu(mbar, name='apple',
tearoff=0)
mbar.add_cascade(label='IDLE', menu=menu)
self.fill_menus()
self.recent_files_menu = Menu(self.menubar, tearoff=0)
self.menudict['file'].insert_cascade(3, label='Recent Files',
underline=0,
menu=self.recent_files_menu)
self.base_helpmenu_length = self.menudict['help'].index(END)
self.reset_help_menu_entries()
def postwindowsmenu(self):
# Only called when Window menu exists
menu = self.menudict['window']
end = menu.index("end")
if end is None:
end = -1
if end > self.wmenu_end:
menu.delete(self.wmenu_end+1, end)
window.add_windows_to_menu(menu)
def handle_yview(self, event, *args):
"Handle scrollbar."
if event == 'moveto':
fraction = float(args[0])
lines = (round(self.getlineno('end') * fraction) -
self.getlineno('@0,0'))
event = 'scroll'
args = (lines, 'units')
self.text.yview(event, *args)
return 'break'
def mousescroll(self, event):
"""Handle scrollwheel event.
For wheel up, event.delta = 120*n on Windows, -1*n on darwin,
where n can be > 1 if one scrolls fast. Flicking the wheel
generates up to maybe 20 events with n up to 10 or more 1.
Macs use wheel down (delta = 1*n) to scroll up, so positive
delta means to scroll up on both systems.
X-11 sends Control-Button-4 event instead.
"""
up = {EventType.MouseWheel: event.delta > 0,
EventType.Button: event.num == 4}
lines = -5 if up[event.type] else 5
self.text.yview_scroll(lines, 'units')
return 'break'
rmenu = None
def right_menu_event(self, event):
self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
if not self.rmenu:
self.make_rmenu()
rmenu = self.rmenu
self.event = event
iswin = sys.platform[:3] == 'win'
if iswin:
self.text.config(cursor="arrow")
for item in self.rmenu_specs:
try:
label, eventname, verify_state = item
except ValueError: # see issue1207589
continue
if verify_state is None:
continue
state = getattr(self, verify_state)()
rmenu.entryconfigure(label, state=state)
rmenu.tk_popup(event.x_root, event.y_root)
if iswin:
self.text.config(cursor="ibeam")
return "break"
rmenu_specs = [
# ("Label", "<<virtual-event>>", "statefuncname"), ...
("Close", "<<close-window>>", None), # Example
]
def make_rmenu(self):
rmenu = Menu(self.text, tearoff=0)
for item in self.rmenu_specs:
label, eventname = item[0], item[1]
if label is not None:
def command(text=self.text, eventname=eventname):
text.event_generate(eventname)
rmenu.add_command(label=label, command=command)
else:
rmenu.add_separator()
self.rmenu = rmenu
def rmenu_check_cut(self):
return self.rmenu_check_copy()
def rmenu_check_copy(self):
try:
indx = self.text.index('sel.first')
except TclError:
return 'disabled'
else:
return 'normal' if indx else 'disabled'
def rmenu_check_paste(self):
try:
self.text.tk.call('tk::GetSelection', self.text, 'CLIPBOARD')
except TclError:
return 'disabled'
else:
return 'normal'
def about_dialog(self, event=None):
"Handle Help 'About IDLE' event."
# Synchronize with macosx.overrideRootMenu.about_dialog.
help_about.AboutDialog(self.top)
return "break"
def config_dialog(self, event=None):
"Handle Options 'Configure IDLE' event."
# Synchronize with macosx.overrideRootMenu.config_dialog.
configdialog.ConfigDialog(self.top,'Settings')
return "break"
def help_dialog(self, event=None):
"Handle Help 'IDLE Help' event."
# Synchronize with macosx.overrideRootMenu.help_dialog.
if self.root:
parent = self.root
else:
parent = self.top
help.show_idlehelp(parent)
return "break"
def python_docs(self, event=None):
if sys.platform[:3] == 'win':
try:
os.startfile(self.help_url)
except OSError as why:
tkMessageBox.showerror(title='Document Start Failure',
message=str(why), parent=self.text)
else:
webbrowser.open(self.help_url)
return "break"
def cut(self,event):
self.text.event_generate("<<Cut>>")
return "break"
def copy(self,event):
if not self.text.tag_ranges("sel"):
# There is no selection, so do nothing and maybe interrupt.
return None
self.text.event_generate("<<Copy>>")
return "break"
def paste(self,event):
self.text.event_generate("<<Paste>>")
self.text.see("insert")
return "break"
def select_all(self, event=None):
self.text.tag_add("sel", "1.0", "end-1c")
self.text.mark_set("insert", "1.0")
self.text.see("insert")
return "break"
def remove_selection(self, event=None):
self.text.tag_remove("sel", "1.0", "end")
self.text.see("insert")
return "break"
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
def del_word_left(self, event):
self.text.event_generate('<Meta-Delete>')
return "break"
def del_word_right(self, event):
self.text.event_generate('<Meta-d>')
return "break"
def find_event(self, event):
search.find(self.text)
return "break"
def find_again_event(self, event):
search.find_again(self.text)
return "break"
def find_selection_event(self, event):
search.find_selection(self.text)
return "break"
def find_in_files_event(self, event):
grep.grep(self.text, self.io, self.flist)
return "break"
def replace_event(self, event):
replace.replace(self.text)
return "break"
def goto_line_event(self, event):
text = self.text
lineno = tkSimpleDialog.askinteger("Goto",
"Go to line number:",parent=text)
if lineno is None:
return "break"
if lineno <= 0:
text.bell()
return "break"
text.mark_set("insert", "%d.0" % lineno)
text.see("insert")
return "break"
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
def open_module_event(self, event):
self.open_module()
return "break"
def open_module_browser(self, event=None):
filename = self.io.filename
if not (self.__class__.__name__ == 'PyShellEditorWindow'
and filename):
filename = self.open_module()
if filename is None:
return "break"
from idlelib import browser
browser.ModuleBrowser(self.root, filename)
return "break"
def open_path_browser(self, event=None):
from idlelib import pathbrowser
pathbrowser.PathBrowser(self.root)
return "break"
def open_turtle_demo(self, event = None):
import subprocess
cmd = [sys.executable,
'-c',
'from turtledemo.__main__ import main; main()']
subprocess.Popen(cmd, shell=False)
return "break"
def gotoline(self, lineno):
if lineno is not None and lineno > 0:
self.text.mark_set("insert", "%d.0" % lineno)
self.text.tag_remove("sel", "1.0", "end")
self.text.tag_add("sel", "insert", "insert +1l")
self.center()
def ispythonsource(self, filename):
if not filename or os.path.isdir(filename):
return True
base, ext = os.path.splitext(os.path.basename(filename))
if os.path.normcase(ext) in (".py", ".pyw"):
return True
line = self.text.get('1.0', '1.0 lineend')
return line.startswith('#!') and 'python' in line
def close_hook(self):
if self.flist:
self.flist.unregister_maybe_terminate(self)
self.flist = None
def set_close_hook(self, close_hook):
self.close_hook = close_hook
def filename_change_hook(self):
if self.flist:
self.flist.filename_changed_edit(self)
self.saved_change_hook()
self.top.update_windowlist_registry(self)
self.ResetColorizer()
def _addcolorizer(self):
if self.color:
return
if self.ispythonsource(self.io.filename):
self.color = self.ColorDelegator()
# can add more colorizers here...
if self.color:
self.per.removefilter(self.undo)
self.per.insertfilter(self.color)
self.per.insertfilter(self.undo)
def _rmcolorizer(self):
if not self.color:
return
self.color.removecolors()
self.per.removefilter(self.color)
self.color = None
def ResetColorizer(self):
"Update the color theme"
# Called from self.filename_change_hook and from configdialog.py
self._rmcolorizer()
self._addcolorizer()
EditorWindow.color_config(self.text)
IDENTCHARS = string.ascii_letters + string.digits + "_"
def colorize_syntax_error(self, text, pos):
text.tag_add("ERROR", pos)
char = text.get(pos)
if char and char in self.IDENTCHARS:
text.tag_add("ERROR", pos + " wordstart", pos)
if '\n' == text.get(pos): # error at line end
text.mark_set("insert", pos)
else:
text.mark_set("insert", pos + "+1c")
text.see(pos)
def ResetFont(self):
"Update the text widgets' font if it is changed"
# Called from configdialog.py
self.text['font'] = idleConf.GetFont(self.root, 'main','EditorWindow')
def RemoveKeybindings(self):
"Remove the keybindings before they are changed."
# Called from configdialog.py
self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
for event, keylist in keydefs.items():
self.text.event_delete(event, *keylist)
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
if xkeydefs:
for event, keylist in xkeydefs.items():
self.text.event_delete(event, *keylist)
def ApplyKeybindings(self):
"Update the keybindings after they are changed"
# Called from configdialog.py
self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
self.apply_bindings()
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
if xkeydefs:
self.apply_bindings(xkeydefs)
#update menu accelerators
menuEventDict = {}
for menu in self.mainmenu.menudefs:
menuEventDict[menu[0]] = {}
for item in menu[1]:
if item:
menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1]
for menubarItem in self.menudict:
menu = self.menudict[menubarItem]
end = menu.index(END)
if end is None:
# Skip empty menus
continue
end += 1
for index in range(0, end):
if menu.type(index) == 'command':
accel = menu.entrycget(index, 'accelerator')
if accel:
itemName = menu.entrycget(index, 'label')
event = ''
if menubarItem in menuEventDict:
if itemName in menuEventDict[menubarItem]:
event = menuEventDict[menubarItem][itemName]
if event:
accel = get_accelerator(keydefs, event)
menu.entryconfig(index, accelerator=accel)
def set_notabs_indentwidth(self):
"Update the indentwidth if changed and not using tabs in this window"
# Called from configdialog.py
if not self.usetabs:
self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
type='int')
def reset_help_menu_entries(self):
"Update the additional help entries on the Help menu"
help_list = idleConf.GetAllExtraHelpSourcesList()
helpmenu = self.menudict['help']
# first delete the extra help entries, if any
helpmenu_length = helpmenu.index(END)
if helpmenu_length > self.base_helpmenu_length:
helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
# then rebuild them
if help_list:
helpmenu.add_separator()
for entry in help_list:
cmd = self.__extra_help_callback(entry[1])
helpmenu.add_command(label=entry[0], command=cmd)
# and update the menu dictionary
self.menudict['help'] = helpmenu
def __extra_help_callback(self, helpfile):
"Create a callback with the helpfile value frozen at definition time"
def display_extra_help(helpfile=helpfile):
if not helpfile.startswith(('www', 'http')):
helpfile = os.path.normpath(helpfile)
if sys.platform[:3] == 'win':
try:
os.startfile(helpfile)
except OSError as why:
tkMessageBox.showerror(title='Document Start Failure',
message=str(why), parent=self.text)
else:
webbrowser.open(helpfile)
return display_extra_help
def update_recent_files_list(self, new_file=None):
"Load and update the recent files list and menus"
rf_list = []
if os.path.exists(self.recent_files_path):
with open(self.recent_files_path, 'r',
encoding='utf_8', errors='replace') as rf_list_file:
rf_list = rf_list_file.readlines()
if new_file:
new_file = os.path.abspath(new_file) + '\n'
if new_file in rf_list:
rf_list.remove(new_file) # move to top
rf_list.insert(0, new_file)
# clean and save the recent files list
bad_paths = []
for path in rf_list:
if '\0' in path or not os.path.exists(path[0:-1]):
bad_paths.append(path)
rf_list = [path for path in rf_list if path not in bad_paths]
ulchars = "1234567890ABCDEFGHIJK"
rf_list = rf_list[0:len(ulchars)]
try:
with open(self.recent_files_path, 'w',
encoding='utf_8', errors='replace') as rf_file:
rf_file.writelines(rf_list)
except OSError as err:
if not getattr(self.root, "recentfilelist_error_displayed", False):
self.root.recentfilelist_error_displayed = True
tkMessageBox.showwarning(title='IDLE Warning',
message="Cannot update File menu Recent Files list. "
"Your operating system says:\n%s\n"
"Select OK and IDLE will continue without updating."
% self._filename_to_unicode(str(err)),
parent=self.text)
# for each edit window instance, construct the recent files menu
for instance in self.top.instance_dict:
menu = instance.recent_files_menu
menu.delete(0, END) # clear, and rebuild:
for i, file_name in enumerate(rf_list):
file_name = file_name.rstrip() # zap \n
# make unicode string to display non-ASCII chars correctly
ufile_name = self._filename_to_unicode(file_name)
callback = instance.__recent_file_callback(file_name)
menu.add_command(label=ulchars[i] + " " + ufile_name,
command=callback,
underline=0)
def __recent_file_callback(self, file_name):
def open_recent_file(fn_closure=file_name):
self.io.open(editFile=fn_closure)
return open_recent_file
def saved_change_hook(self):
short = self.short_title()
long = self.long_title()
if short and long:
title = short + " - " + long + _py_version
elif short:
title = short
elif long:
title = long
else:
title = "Untitled"
icon = short or long or title
if not self.get_saved():
title = "*%s*" % title
icon = "*%s" % icon
self.top.wm_title(title)
self.top.wm_iconname(icon)
def get_saved(self):
return self.undo.get_saved()
def set_saved(self, flag):
self.undo.set_saved(flag)
def reset_undo(self):
self.undo.reset_undo()
def short_title(self):
filename = self.io.filename
if filename:
filename = os.path.basename(filename)
else:
filename = "Untitled"
# return unicode string to display non-ASCII chars correctly
return self._filename_to_unicode(filename)
def long_title(self):
# return unicode string to display non-ASCII chars correctly
return self._filename_to_unicode(self.io.filename or "")
def center_insert_event(self, event):
self.center()
return "break"
def center(self, mark="insert"):
text = self.text
top, bot = self.getwindowlines()
lineno = self.getlineno(mark)
height = bot - top
newtop = max(1, lineno - height//2)
text.yview(float(newtop))
def getwindowlines(self):
text = self.text
top = self.getlineno("@0,0")
bot = self.getlineno("@0,65535")
if top == bot and text.winfo_height() == 1:
# Geometry manager hasn't run yet
height = int(text['height'])
bot = top + height - 1
return top, bot
def getlineno(self, mark="insert"):
text = self.text
return int(float(text.index(mark)))
def get_geometry(self):
"Return (width, height, x, y)"
geom = self.top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
return list(map(int, m.groups()))
def close_event(self, event):
self.close()
return "break"
def maybesave(self):
if self.io:
if not self.get_saved():
if self.top.state()!='normal':
self.top.deiconify()
self.top.lower()
self.top.lift()
return self.io.maybesave()
def close(self):
reply = self.maybesave()
if str(reply) != "cancel":
self._close()
return reply
def _close(self):
if self.io.filename:
self.update_recent_files_list(new_file=self.io.filename)
window.unregister_callback(self.postwindowsmenu)
self.unload_extensions()
self.io.close()
self.io = None
self.undo = None
if self.color:
self.color.close(False)
self.color = None
self.text = None
self.tkinter_vars = None
self.per.close()
self.per = None
self.top.destroy()
if self.close_hook:
# unless override: unregister from flist, terminate if last window
self.close_hook()
def load_extensions(self):
self.extensions = {}
self.load_standard_extensions()
def unload_extensions(self):
for ins in list(self.extensions.values()):
if hasattr(ins, "close"):
ins.close()
self.extensions = {}
def load_standard_extensions(self):
for name in self.get_standard_extension_names():
try:
self.load_extension(name)
except:
print("Failed to load extension", repr(name))
traceback.print_exc()
def get_standard_extension_names(self):
return idleConf.GetExtensions(editor_only=True)
extfiles = { # Map built-in config-extension section names to file names.
'ZzDummy': 'zzdummy',
}
def load_extension(self, name):
fname = self.extfiles.get(name, name)
try:
try:
mod = importlib.import_module('.' + fname, package=__package__)
except (ImportError, TypeError):
mod = importlib.import_module(fname)
except ImportError:
print("\nFailed to import extension: ", name)
raise
cls = getattr(mod, name)
keydefs = idleConf.GetExtensionBindings(name)
if hasattr(cls, "menudefs"):
self.fill_menus(cls.menudefs, keydefs)
ins = cls(self)
self.extensions[name] = ins
if keydefs:
self.apply_bindings(keydefs)
for vevent in keydefs:
methodname = vevent.replace("-", "_")
while methodname[:1] == '<':
methodname = methodname[1:]
while methodname[-1:] == '>':
methodname = methodname[:-1]
methodname = methodname + "_event"
if hasattr(ins, methodname):
self.text.bind(vevent, getattr(ins, methodname))
def apply_bindings(self, keydefs=None):
if keydefs is None:
keydefs = self.mainmenu.default_keydefs
text = self.text
text.keydefs = keydefs
for event, keylist in keydefs.items():
if keylist:
text.event_add(event, *keylist)
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)
def getvar(self, name):
var = self.get_var_obj(name)
if var:
value = var.get()
return value
else:
raise NameError(name)
def setvar(self, name, value, vartype=None):
var = self.get_var_obj(name, vartype)
if var:
var.set(value)
else:
raise NameError(name)
def get_var_obj(self, name, vartype=None):
var = self.tkinter_vars.get(name)
if not var and vartype:
# create a Tkinter variable object with self.text as master:
self.tkinter_vars[name] = var = vartype(self.text)
return var
# Tk implementations of "virtual text methods" -- each platform
# reusing IDLE's support code needs to define these for its GUI's
# flavor of widget.
# Is character at text_index in a Python string? Return 0 for
# "guaranteed no", true for anything else. This info is expensive
# to compute ab initio, but is probably already known by the
# platform's colorizer.
def is_char_in_string(self, text_index):
if self.color:
# Return true iff colorizer hasn't (re)gotten this far
# yet, or the character is tagged as being in a string
return self.text.tag_prevrange("TODO", text_index) or \
"STRING" in self.text.tag_names(text_index)
else:
# The colorizer is missing: assume the worst
return 1
# If a selection is defined in the text widget, return (start,
# end) as Tkinter text indices, otherwise return (None, None)
def get_selection_indices(self):
try:
first = self.text.index("sel.first")
last = self.text.index("sel.last")
return first, last
except TclError:
return None, None
# Return the text widget's current view of what a tab stop means
# (equivalent width in spaces).
def get_tk_tabwidth(self):
current = self.text['tabs'] or TK_TABWIDTH_DEFAULT
return int(current)
# Set the text widget's current view of what a tab stop means.
def set_tk_tabwidth(self, newtabwidth):
text = self.text
if self.get_tk_tabwidth() != newtabwidth:
# Set text widget tab width
pixels = text.tk.call("font", "measure", text["font"],
"-displayof", text.master,
"n" * newtabwidth)
text.configure(tabs=pixels)
### begin autoindent code ### (configuration was moved to beginning of class)
def set_indentation_params(self, is_py_src, guess=True):
if is_py_src and guess:
i = self.guess_indent()
if 2 <= i <= 8:
self.indentwidth = i
if self.indentwidth != self.tabwidth:
self.usetabs = False
self.set_tk_tabwidth(self.tabwidth)
def smart_backspace_event(self, event):
text = self.text
first, last = self.get_selection_indices()
if first and last:
text.delete(first, last)
text.mark_set("insert", first)
return "break"
# Delete whitespace left, until hitting a real char or closest
# preceding virtual tab stop.
chars = text.get("insert linestart", "insert")
if chars == '':
if text.compare("insert", ">", "1.0"):
# easy: delete preceding newline
text.delete("insert-1c")
else:
text.bell() # at start of buffer
return "break"
if chars[-1] not in " \t":
# easy: delete preceding real char
text.delete("insert-1c")
return "break"
# Ick. It may require *inserting* spaces if we back up over a
# tab character! This is written to be clear, not fast.
tabwidth = self.tabwidth
have = len(chars.expandtabs(tabwidth))
assert have > 0
want = ((have - 1) // self.indentwidth) * self.indentwidth
# Debug prompt is multilined....
ncharsdeleted = 0
while 1:
if chars == self.prompt_last_line: # '' unless PyShell
break
chars = chars[:-1]
ncharsdeleted = ncharsdeleted + 1
have = len(chars.expandtabs(tabwidth))
if have <= want or chars[-1] not in " \t":
break
text.undo_block_start()
text.delete("insert-%dc" % ncharsdeleted, "insert")
if have < want:
text.insert("insert", ' ' * (want - have))
text.undo_block_stop()
return "break"
def smart_indent_event(self, event):
# if intraline selection:
# delete it
# elif multiline selection:
# do indent-region
# else:
# indent one level
text = self.text
first, last = self.get_selection_indices()
text.undo_block_start()
try:
if first and last:
if index2line(first) != index2line(last):
return self.indent_region_event(event)
text.delete(first, last)
text.mark_set("insert", first)
prefix = text.get("insert linestart", "insert")
raw, effective = classifyws(prefix, self.tabwidth)
if raw == len(prefix):
# only whitespace to the left
self.reindent_to(effective + self.indentwidth)
else:
# tab to the next 'stop' within or to right of line's text:
if self.usetabs:
pad = '\t'
else:
effective = len(prefix.expandtabs(self.tabwidth))
n = self.indentwidth
pad = ' ' * (n - effective % n)
text.insert("insert", pad)
text.see("insert")
return "break"
finally:
text.undo_block_stop()
def newline_and_indent_event(self, event):
text = self.text
first, last = self.get_selection_indices()
text.undo_block_start()
try:
if first and last:
text.delete(first, last)
text.mark_set("insert", first)
line = text.get("insert linestart", "insert")
i, n = 0, len(line)
while i < n and line[i] in " \t":
i = 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 = 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")
# start new line
text.insert("insert", '\n')
# adjust indentation for continuations and block
# open/close first need to find the last stmt
lno = index2line(text.index('insert'))
y = pyparse.Parser(self.indentwidth, self.tabwidth)
if not self.context_use_ps1:
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.context_use_ps1,
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 stmt 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 stmt 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 stmt; indent relative to
# indentation of initial line of closest preceding
# interesting stmt.
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()
# Our editwin provides an is_char_in_string function that works
# with a Tk text index, but PyParse only knows about offsets into
# a string. This builds a function for PyParse that accepts an
# offset.
def _build_char_in_string_func(self, startindex):
def inner(offset, _startindex=startindex,
_icis=self.is_char_in_string):
return _icis(_startindex + "+%dc" % offset)
return inner
def indent_region_event(self, event):
head, tail, chars, lines = self.get_region()
for pos in range(len(lines)):
line = lines[pos]
if line:
raw, effective = classifyws(line, self.tabwidth)
effective = effective + self.indentwidth
lines[pos] = self._make_blanks(effective) + line[raw:]
self.set_region(head, tail, chars, lines)
return "break"
def dedent_region_event(self, event):
head, tail, chars, lines = self.get_region()
for pos in range(len(lines)):
line = lines[pos]
if line:
raw, effective = classifyws(line, self.tabwidth)
effective = max(effective - self.indentwidth, 0)
lines[pos] = self._make_blanks(effective) + line[raw:]
self.set_region(head, tail, chars, lines)
return "break"
def comment_region_event(self, event):
head, tail, chars, lines = self.get_region()
for pos in range(len(lines) - 1):
line = lines[pos]
lines[pos] = '##' + line
self.set_region(head, tail, chars, lines)
return "break"
def uncomment_region_event(self, event):
head, tail, chars, lines = self.get_region()
for pos in range(len(lines)):
line = lines[pos]
if not line:
continue
if line[:2] == '##':
line = line[2:]
elif line[:1] == '#':
line = line[1:]
lines[pos] = line
self.set_region(head, tail, chars, lines)
return "break"
def tabify_region_event(self, event):
head, tail, chars, lines = self.get_region()
tabwidth = self._asktabwidth()
if tabwidth is None: return
for pos in range(len(lines)):
line = lines[pos]
if line:
raw, effective = classifyws(line, tabwidth)
ntabs, nspaces = divmod(effective, tabwidth)
lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
self.set_region(head, tail, chars, lines)
return "break"
def untabify_region_event(self, event):
head, tail, chars, lines = self.get_region()
tabwidth = self._asktabwidth()
if tabwidth is None: return
for pos in range(len(lines)):
lines[pos] = lines[pos].expandtabs(tabwidth)
self.set_region(head, tail, chars, lines)
return "break"
def toggle_tabs_event(self, event):
if self.askyesno(
"Toggle tabs",
"Turn tabs " + ("on", "off")[self.usetabs] +
"?\nIndent width " +
("will be", "remains at")[self.usetabs] + " 8." +
"\n Note: a tab is always 8 columns",
parent=self.text):
self.usetabs = not self.usetabs
# Try to prevent inconsistent indentation.
# User must change indent width manually after using tabs.
self.indentwidth = 8
return "break"
# XXX this isn't bound to anything -- see tabwidth comments
## def change_tabwidth_event(self, event):
## new = self._asktabwidth()
## if new != self.tabwidth:
## self.tabwidth = new
## self.set_indentation_params(0, guess=0)
## return "break"
def change_indentwidth_event(self, event):
new = self.askinteger(
"Indent width",
"New indent width (2-16)\n(Always use 8 when using tabs)",
parent=self.text,
initialvalue=self.indentwidth,
minvalue=2,
maxvalue=16)
if new and new != self.indentwidth and not self.usetabs:
self.indentwidth = new
return "break"
def get_region(self):
text = self.text
first, last = self.get_selection_indices()
if first and last:
head = text.index(first + " linestart")
tail = text.index(last + "-1c lineend +1c")
else:
head = text.index("insert linestart")
tail = text.index("insert lineend +1c")
chars = text.get(head, tail)
lines = chars.split("\n")
return head, tail, chars, lines
def set_region(self, head, tail, chars, lines):
text = self.text
newchars = "\n".join(lines)
if newchars == chars:
text.bell()
return
text.tag_remove("sel", "1.0", "end")
text.mark_set("insert", head)
text.undo_block_start()
text.delete(head, tail)
text.insert(head, newchars)
text.undo_block_stop()
text.tag_add("sel", head, "insert")
# Make string that displays as n leading blanks.
def _make_blanks(self, n):
if self.usetabs:
ntabs, nspaces = divmod(n, self.tabwidth)
return '\t' * ntabs + ' ' * nspaces
else:
return ' ' * n
# Delete from beginning of line to insert point, then reinsert
# column logical (meaning use tabs if appropriate) spaces.
def reindent_to(self, column):
text = self.text
text.undo_block_start()
if text.compare("insert linestart", "!=", "insert"):
text.delete("insert linestart", "insert")
if column:
text.insert("insert", self._make_blanks(column))
text.undo_block_stop()
def _asktabwidth(self):
return self.askinteger(
"Tab width",
"Columns per tab? (2-16)",
parent=self.text,
initialvalue=self.indentwidth,
minvalue=2,
maxvalue=16)
# Guess indentwidth from text content.
# Return guessed indentwidth. This should not be believed unless
# it's in a reasonable range (e.g., it will be 0 if no indented
# blocks are found).
def guess_indent(self):
opener, indented = IndentSearcher(self.text, self.tabwidth).run()
if opener and indented:
raw, indentsmall = classifyws(opener, self.tabwidth)
raw, indentlarge = classifyws(indented, self.tabwidth)
else:
indentsmall = indentlarge = 0
return indentlarge - indentsmall
# "line.col" -> line, as an int
def index2line(index):
return int(float(index))
# Look at the leading whitespace in s.
# Return pair (# of leading ws characters,
# effective # of leading blanks after expanding
# tabs to width tabwidth)
def classifyws(s, tabwidth):
raw = effective = 0
for ch in s:
if ch == ' ':
raw = raw + 1
effective = effective + 1
elif ch == '\t':
raw = raw + 1
effective = (effective // tabwidth + 1) * tabwidth
else:
break
return raw, effective
class IndentSearcher(object):
# .run() chews over the Text widget, looking for a block opener
# and the stmt following it. Returns a pair,
# (line containing block opener, line containing stmt)
# Either or both may be None.
def __init__(self, text, tabwidth):
self.text = text
self.tabwidth = tabwidth
self.i = self.finished = 0
self.blkopenline = self.indentedline = None
def readline(self):
if self.finished:
return ""
i = self.i = self.i + 1
mark = repr(i) + ".0"
if self.text.compare(mark, ">=", "end"):
return ""
return self.text.get(mark, mark + " lineend+1c")
def tokeneater(self, type, token, start, end, line,
INDENT=tokenize.INDENT,
NAME=tokenize.NAME,
OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
if self.finished:
pass
elif type == NAME and token in OPENERS:
self.blkopenline = line
elif type == INDENT and self.blkopenline:
self.indentedline = line
self.finished = 1
def run(self):
save_tabsize = tokenize.tabsize
tokenize.tabsize = self.tabwidth
try:
try:
tokens = tokenize.generate_tokens(self.readline)
for token in tokens:
self.tokeneater(*token)
except (tokenize.TokenError, SyntaxError):
# since we cut off the tokenizer early, we can trigger
# spurious errors
pass
finally:
tokenize.tabsize = save_tabsize
return self.blkopenline, self.indentedline
### end autoindent code ###
def prepstr(s):
# Helper to extract the underscore from a string, e.g.
# prepstr("Co_py") returns (2, "Copy").
i = s.find('_')
if i >= 0:
s = s[:i] + s[i+1:]
return i, s
keynames = {
'bracketleft': '[',
'bracketright': ']',
'slash': '/',
}
def get_accelerator(keydefs, eventname):
keylist = keydefs.get(eventname)
# issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5
# if not keylist:
if (not keylist) or (macosx.isCocoaTk() and eventname in {
"<<open-module>>",
"<<goto-line>>",
"<<change-indentwidth>>"}):
return ""
s = keylist[0]
s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s)
s = re.sub("Key-", "", s)
s = re.sub("Cancel","Ctrl-Break",s) # [email protected]
s = re.sub("Control-", "Ctrl-", s)
s = re.sub("-", "+", s)
s = re.sub("><", " ", s)
s = re.sub("<", "", s)
s = re.sub(">", "", s)
return s
def fixwordbreaks(root):
# On Windows, tcl/tk breaks 'words' only on spaces, as in Command Prompt.
# We want Motif style everywhere. See #21474, msg218992 and followup.
tk = root.tk
tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded
tk.call('set', 'tcl_wordchars', r'\w')
tk.call('set', 'tcl_nonwordchars', r'\W')
def _editor_window(parent): # htest #
# error if close master window first - timer event, after script
root = parent
fixwordbreaks(root)
if sys.argv[1:]:
filename = sys.argv[1]
else:
filename = None
macosx.setupApp(root, None)
edit = EditorWindow(root=root, filename=filename)
text = edit.text
text['height'] = 10
for i in range(20):
text.insert('insert', ' '*i + str(i) + '\n')
# text.bind("<<close-all-windows>>", edit.close_event)
# Does not stop error, neither does following
# edit.text.bind("<<close-window>>", edit.close_event)
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_editor', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_editor_window)
| 67,275 | 1,726 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/squeezer.py | """An IDLE extension to avoid having very long texts printed in the shell.
A common problem in IDLE's interactive shell is printing of large amounts of
text into the shell. This makes looking at the previous history difficult.
Worse, this can cause IDLE to become very slow, even to the point of being
completely unusable.
This extension will automatically replace long texts with a small button.
Double-cliking this button will remove it and insert the original text instead.
Middle-clicking will copy the text to the clipboard. Right-clicking will open
the text in a separate viewing window.
Additionally, any output can be manually "squeezed" by the user. This includes
output written to the standard error stream ("stderr"), such as exception
messages and their tracebacks.
"""
import re
import tkinter as tk
from tkinter.font import Font
import tkinter.messagebox as tkMessageBox
from idlelib.config import idleConf
from idlelib.textview import view_text
from idlelib.tooltip import Hovertip
from idlelib import macosx
def count_lines_with_wrapping(s, linewidth=80, tabwidth=8):
"""Count the number of lines in a given string.
Lines are counted as if the string was wrapped so that lines are never over
linewidth characters long.
Tabs are considered tabwidth characters long.
"""
pos = 0
linecount = 1
current_column = 0
for m in re.finditer(r"[\t\n]", s):
# process the normal chars up to tab or newline
numchars = m.start() - pos
pos += numchars
current_column += numchars
# deal with tab or newline
if s[pos] == '\n':
linecount += 1
current_column = 0
else:
assert s[pos] == '\t'
current_column += tabwidth - (current_column % tabwidth)
# if a tab passes the end of the line, consider the entire tab as
# being on the next line
if current_column > linewidth:
linecount += 1
current_column = tabwidth
pos += 1 # after the tab or newline
# avoid divmod(-1, linewidth)
if current_column > 0:
# If the length was exactly linewidth, divmod would give (1,0),
# even though a new line hadn't yet been started. The same is true
# if length is any exact multiple of linewidth. Therefore, subtract
# 1 before doing divmod, and later add 1 to the column to
# compensate.
lines, column = divmod(current_column - 1, linewidth)
linecount += lines
current_column = column + 1
# process remaining chars (no more tabs or newlines)
current_column += len(s) - pos
# avoid divmod(-1, linewidth)
if current_column > 0:
linecount += (current_column - 1) // linewidth
else:
# the text ended with a newline; don't count an extra line after it
linecount -= 1
return linecount
class ExpandingButton(tk.Button):
"""Class for the "squeezed" text buttons used by Squeezer
These buttons are displayed inside a Tk Text widget in place of text. A
user can then use the button to replace it with the original text, copy
the original text to the clipboard or view the original text in a separate
window.
Each button is tied to a Squeezer instance, and it knows to update the
Squeezer instance when it is expanded (and therefore removed).
"""
def __init__(self, s, tags, numoflines, squeezer):
self.s = s
self.tags = tags
self.numoflines = numoflines
self.squeezer = squeezer
self.editwin = editwin = squeezer.editwin
self.text = text = editwin.text
# the base Text widget of the PyShell object, used to change text
# before the iomark
self.base_text = editwin.per.bottom
button_text = "Squeezed text (%d lines)." % self.numoflines
tk.Button.__init__(self, text, text=button_text,
background="#FFFFC0", activebackground="#FFFFE0")
button_tooltip_text = (
"Double-click to expand, right-click for more options."
)
Hovertip(self, button_tooltip_text, hover_delay=80)
self.bind("<Double-Button-1>", self.expand)
if macosx.isAquaTk():
# AquaTk defines <2> as the right button, not <3>.
self.bind("<Button-2>", self.context_menu_event)
else:
self.bind("<Button-3>", self.context_menu_event)
self.selection_handle(
lambda offset, length: s[int(offset):int(offset) + int(length)])
self.is_dangerous = None
self.after_idle(self.set_is_dangerous)
def set_is_dangerous(self):
dangerous_line_len = 50 * self.text.winfo_width()
self.is_dangerous = (
self.numoflines > 1000 or
len(self.s) > 50000 or
any(
len(line_match.group(0)) >= dangerous_line_len
for line_match in re.finditer(r'[^\n]+', self.s)
)
)
def expand(self, event=None):
"""expand event handler
This inserts the original text in place of the button in the Text
widget, removes the button and updates the Squeezer instance.
If the original text is dangerously long, i.e. expanding it could
cause a performance degradation, ask the user for confirmation.
"""
if self.is_dangerous is None:
self.set_is_dangerous()
if self.is_dangerous:
confirm = tkMessageBox.askokcancel(
title="Expand huge output?",
message="\n\n".join([
"The squeezed output is very long: %d lines, %d chars.",
"Expanding it could make IDLE slow or unresponsive.",
"It is recommended to view or copy the output instead.",
"Really expand?"
]) % (self.numoflines, len(self.s)),
default=tkMessageBox.CANCEL,
parent=self.text)
if not confirm:
return "break"
self.base_text.insert(self.text.index(self), self.s, self.tags)
self.base_text.delete(self)
self.squeezer.expandingbuttons.remove(self)
def copy(self, event=None):
"""copy event handler
Copy the original text to the clipboard.
"""
self.clipboard_clear()
self.clipboard_append(self.s)
def view(self, event=None):
"""view event handler
View the original text in a separate text viewer window.
"""
view_text(self.text, "Squeezed Output Viewer", self.s,
modal=False, wrap='none')
rmenu_specs = (
# item structure: (label, method_name)
('copy', 'copy'),
('view', 'view'),
)
def context_menu_event(self, event):
self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
rmenu = tk.Menu(self.text, tearoff=0)
for label, method_name in self.rmenu_specs:
rmenu.add_command(label=label, command=getattr(self, method_name))
rmenu.tk_popup(event.x_root, event.y_root)
return "break"
class Squeezer:
"""Replace long outputs in the shell with a simple button.
This avoids IDLE's shell slowing down considerably, and even becoming
completely unresponsive, when very long outputs are written.
"""
@classmethod
def reload(cls):
"""Load class variables from config."""
cls.auto_squeeze_min_lines = idleConf.GetOption(
"main", "PyShell", "auto-squeeze-min-lines",
type="int", default=50,
)
def __init__(self, editwin):
"""Initialize settings for Squeezer.
editwin is the shell's Editor window.
self.text is the editor window text widget.
self.base_test is the actual editor window Tk text widget, rather than
EditorWindow's wrapper.
self.expandingbuttons is the list of all buttons representing
"squeezed" output.
"""
self.editwin = editwin
self.text = text = editwin.text
# Get the base Text widget of the PyShell object, used to change text
# before the iomark. PyShell deliberately disables changing text before
# the iomark via its 'text' attribute, which is actually a wrapper for
# the actual Text widget. Squeezer, however, needs to make such changes.
self.base_text = editwin.per.bottom
self.expandingbuttons = []
from idlelib.pyshell import PyShell # done here to avoid import cycle
if isinstance(editwin, PyShell):
# If we get a PyShell instance, replace its write method with a
# wrapper, which inserts an ExpandingButton instead of a long text.
def mywrite(s, tags=(), write=editwin.write):
# only auto-squeeze text which has just the "stdout" tag
if tags != "stdout":
return write(s, tags)
# only auto-squeeze text with at least the minimum
# configured number of lines
numoflines = self.count_lines(s)
if numoflines < self.auto_squeeze_min_lines:
return write(s, tags)
# create an ExpandingButton instance
expandingbutton = ExpandingButton(s, tags, numoflines,
self)
# insert the ExpandingButton into the Text widget
text.mark_gravity("iomark", tk.RIGHT)
text.window_create("iomark", window=expandingbutton,
padx=3, pady=5)
text.see("iomark")
text.update()
text.mark_gravity("iomark", tk.LEFT)
# add the ExpandingButton to the Squeezer's list
self.expandingbuttons.append(expandingbutton)
editwin.write = mywrite
def count_lines(self, s):
"""Count the number of lines in a given text.
Before calculation, the tab width and line length of the text are
fetched, so that up-to-date values are used.
Lines are counted as if the string was wrapped so that lines are never
over linewidth characters long.
Tabs are considered tabwidth characters long.
"""
# Tab width is configurable
tabwidth = self.editwin.get_tk_tabwidth()
# Get the Text widget's size
linewidth = self.editwin.text.winfo_width()
# Deduct the border and padding
linewidth -= 2*sum([int(self.editwin.text.cget(opt))
for opt in ('border', 'padx')])
# Get the Text widget's font
font = Font(self.editwin.text, name=self.editwin.text.cget('font'))
# Divide the size of the Text widget by the font's width.
# According to Tk8.5 docs, the Text widget's width is set
# according to the width of its font's '0' (zero) character,
# so we will use this as an approximation.
# see: http://www.tcl.tk/man/tcl8.5/TkCmd/text.htm#M-width
linewidth //= font.measure('0')
return count_lines_with_wrapping(s, linewidth, tabwidth)
def squeeze_current_text_event(self, event):
"""squeeze-current-text event handler
Squeeze the block of text inside which contains the "insert" cursor.
If the insert cursor is not in a squeezable block of text, give the
user a small warning and do nothing.
"""
# set tag_name to the first valid tag found on the "insert" cursor
tag_names = self.text.tag_names(tk.INSERT)
for tag_name in ("stdout", "stderr"):
if tag_name in tag_names:
break
else:
# the insert cursor doesn't have a "stdout" or "stderr" tag
self.text.bell()
return "break"
# find the range to squeeze
start, end = self.text.tag_prevrange(tag_name, tk.INSERT + "+1c")
s = self.text.get(start, end)
# if the last char is a newline, remove it from the range
if len(s) > 0 and s[-1] == '\n':
end = self.text.index("%s-1c" % end)
s = s[:-1]
# delete the text
self.base_text.delete(start, end)
# prepare an ExpandingButton
numoflines = self.count_lines(s)
expandingbutton = ExpandingButton(s, tag_name, numoflines, self)
# insert the ExpandingButton to the Text
self.text.window_create(start, window=expandingbutton,
padx=3, pady=5)
# insert the ExpandingButton to the list of ExpandingButtons, while
# keeping the list ordered according to the position of the buttons in
# the Text widget
i = len(self.expandingbuttons)
while i > 0 and self.text.compare(self.expandingbuttons[i-1],
">", expandingbutton):
i -= 1
self.expandingbuttons.insert(i, expandingbutton)
return "break"
Squeezer.reload()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_squeezer', verbosity=2, exit=False)
# Add htest.
| 13,308 | 356 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/pathbrowser.py | import importlib.machinery
import os
import sys
from idlelib.browser import ModuleBrowser, ModuleBrowserTreeItem
from idlelib.tree import TreeItem
class PathBrowser(ModuleBrowser):
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()
def settitle(self):
"Set window titles."
self.top.wm_title("Path Browser")
self.top.wm_iconname("Path Browser")
def rootnode(self):
return PathBrowserTreeItem()
class PathBrowserTreeItem(TreeItem):
def GetText(self):
return "sys.path"
def GetSubList(self):
sublist = []
for dir in sys.path:
item = DirBrowserTreeItem(dir)
sublist.append(item)
return sublist
class DirBrowserTreeItem(TreeItem):
def __init__(self, dir, packages=[]):
self.dir = dir
self.packages = packages
def GetText(self):
if not self.packages:
return self.dir
else:
return self.packages[-1] + ": package"
def GetSubList(self):
try:
names = os.listdir(self.dir or os.curdir)
except OSError:
return []
packages = []
for name in names:
file = os.path.join(self.dir, name)
if self.ispackagedir(file):
nn = os.path.normcase(name)
packages.append((nn, name, file))
packages.sort()
sublist = []
for nn, name, file in packages:
item = DirBrowserTreeItem(file, self.packages + [name])
sublist.append(item)
for nn, name in self.listmodules(names):
item = ModuleBrowserTreeItem(os.path.join(self.dir, name))
sublist.append(item)
return sublist
def ispackagedir(self, file):
" Return true for directories that are packages."
if not os.path.isdir(file):
return False
init = os.path.join(file, "__init__.py")
return os.path.exists(init)
def listmodules(self, allnames):
modules = {}
suffixes = importlib.machinery.EXTENSION_SUFFIXES[:]
suffixes += importlib.machinery.SOURCE_SUFFIXES
suffixes += importlib.machinery.BYTECODE_SUFFIXES
sorted = []
for suff in suffixes:
i = -len(suff)
for name in allnames[:]:
normed_name = os.path.normcase(name)
if normed_name[i:] == suff:
mod_name = name[:i]
if mod_name not in modules:
modules[mod_name] = None
sorted.append((normed_name, name))
allnames.remove(name)
sorted.sort()
return sorted
def _path_browser(parent): # htest #
PathBrowser(parent, _htest=True)
parent.mainloop()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_pathbrowser', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_path_browser)
| 3,193 | 112 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/debugger_r.py | """Support for remote Python debugging.
Some ASCII art to describe the structure:
IN PYTHON SUBPROCESS # IN IDLE PROCESS
#
# oid='gui_adapter'
+----------+ # +------------+ +-----+
| GUIProxy |--remote#call-->| GUIAdapter |--calls-->| GUI |
+-----+--calls-->+----------+ # +------------+ +-----+
| Idb | # /
+-----+<-calls--+------------+ # +----------+<--calls-/
| IdbAdapter |<--remote#call--| IdbProxy |
+------------+ # +----------+
oid='idb_adapter' #
The purpose of the Proxy and Adapter classes is to translate certain
arguments and return values that cannot be transported through the RPC
barrier, in particular frame and traceback objects.
"""
import types
from idlelib import debugger
debugging = 0
idb_adap_oid = "idb_adapter"
gui_adap_oid = "gui_adapter"
#=======================================
#
# In the PYTHON subprocess:
frametable = {}
dicttable = {}
codetable = {}
tracebacktable = {}
def wrap_frame(frame):
fid = id(frame)
frametable[fid] = frame
return fid
def wrap_info(info):
"replace info[2], a traceback instance, by its ID"
if info is None:
return None
else:
traceback = info[2]
assert isinstance(traceback, types.TracebackType)
traceback_id = id(traceback)
tracebacktable[traceback_id] = traceback
modified_info = (info[0], info[1], traceback_id)
return modified_info
class GUIProxy:
def __init__(self, conn, gui_adap_oid):
self.conn = conn
self.oid = gui_adap_oid
def interaction(self, message, frame, info=None):
# calls rpc.SocketIO.remotecall() via run.MyHandler instance
# pass frame and traceback object IDs instead of the objects themselves
self.conn.remotecall(self.oid, "interaction",
(message, wrap_frame(frame), wrap_info(info)),
{})
class IdbAdapter:
def __init__(self, idb):
self.idb = idb
#----------called by an IdbProxy----------
def set_step(self):
self.idb.set_step()
def set_quit(self):
self.idb.set_quit()
def set_continue(self):
self.idb.set_continue()
def set_next(self, fid):
frame = frametable[fid]
self.idb.set_next(frame)
def set_return(self, fid):
frame = frametable[fid]
self.idb.set_return(frame)
def get_stack(self, fid, tbid):
frame = frametable[fid]
if tbid is None:
tb = None
else:
tb = tracebacktable[tbid]
stack, i = self.idb.get_stack(frame, tb)
stack = [(wrap_frame(frame2), k) for frame2, k in stack]
return stack, i
def run(self, cmd):
import __main__
self.idb.run(cmd, __main__.__dict__)
def set_break(self, filename, lineno):
msg = self.idb.set_break(filename, lineno)
return msg
def clear_break(self, filename, lineno):
msg = self.idb.clear_break(filename, lineno)
return msg
def clear_all_file_breaks(self, filename):
msg = self.idb.clear_all_file_breaks(filename)
return msg
#----------called by a FrameProxy----------
def frame_attr(self, fid, name):
frame = frametable[fid]
return getattr(frame, name)
def frame_globals(self, fid):
frame = frametable[fid]
dict = frame.f_globals
did = id(dict)
dicttable[did] = dict
return did
def frame_locals(self, fid):
frame = frametable[fid]
dict = frame.f_locals
did = id(dict)
dicttable[did] = dict
return did
def frame_code(self, fid):
frame = frametable[fid]
code = frame.f_code
cid = id(code)
codetable[cid] = code
return cid
#----------called by a CodeProxy----------
def code_name(self, cid):
code = codetable[cid]
return code.co_name
def code_filename(self, cid):
code = codetable[cid]
return code.co_filename
#----------called by a DictProxy----------
def dict_keys(self, did):
raise NotImplementedError("dict_keys not public or pickleable")
## dict = dicttable[did]
## return dict.keys()
### Needed until dict_keys is type is finished and pickealable.
### Will probably need to extend rpc.py:SocketIO._proxify at that time.
def dict_keys_list(self, did):
dict = dicttable[did]
return list(dict.keys())
def dict_item(self, did, key):
dict = dicttable[did]
value = dict[key]
value = repr(value) ### can't pickle module 'builtins'
return value
#----------end class IdbAdapter----------
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
#=======================================
#
# In the IDLE process:
class FrameProxy:
def __init__(self, conn, fid):
self._conn = conn
self._fid = fid
self._oid = "idb_adapter"
self._dictcache = {}
def __getattr__(self, name):
if name[:1] == "_":
raise AttributeError(name)
if name == "f_code":
return self._get_f_code()
if name == "f_globals":
return self._get_f_globals()
if name == "f_locals":
return self._get_f_locals()
return self._conn.remotecall(self._oid, "frame_attr",
(self._fid, name), {})
def _get_f_code(self):
cid = self._conn.remotecall(self._oid, "frame_code", (self._fid,), {})
return CodeProxy(self._conn, self._oid, cid)
def _get_f_globals(self):
did = self._conn.remotecall(self._oid, "frame_globals",
(self._fid,), {})
return self._get_dict_proxy(did)
def _get_f_locals(self):
did = self._conn.remotecall(self._oid, "frame_locals",
(self._fid,), {})
return self._get_dict_proxy(did)
def _get_dict_proxy(self, did):
if did in self._dictcache:
return self._dictcache[did]
dp = DictProxy(self._conn, self._oid, did)
self._dictcache[did] = dp
return dp
class CodeProxy:
def __init__(self, conn, oid, cid):
self._conn = conn
self._oid = oid
self._cid = cid
def __getattr__(self, name):
if name == "co_name":
return self._conn.remotecall(self._oid, "code_name",
(self._cid,), {})
if name == "co_filename":
return self._conn.remotecall(self._oid, "code_filename",
(self._cid,), {})
class DictProxy:
def __init__(self, conn, oid, did):
self._conn = conn
self._oid = oid
self._did = did
## def keys(self):
## return self._conn.remotecall(self._oid, "dict_keys", (self._did,), {})
# 'temporary' until dict_keys is a pickleable built-in type
def keys(self):
return self._conn.remotecall(self._oid,
"dict_keys_list", (self._did,), {})
def __getitem__(self, key):
return self._conn.remotecall(self._oid, "dict_item",
(self._did, key), {})
def __getattr__(self, name):
##print("*** Failed DictProxy.__getattr__:", name)
raise AttributeError(name)
class GUIAdapter:
def __init__(self, conn, gui):
self.conn = conn
self.gui = gui
def interaction(self, message, fid, modified_info):
##print("*** Interaction: (%s, %s, %s)" % (message, fid, modified_info))
frame = FrameProxy(self.conn, fid)
self.gui.interaction(message, frame, modified_info)
class IdbProxy:
def __init__(self, conn, shell, oid):
self.oid = oid
self.conn = conn
self.shell = shell
def call(self, methodname, *args, **kwargs):
##print("*** IdbProxy.call %s %s %s" % (methodname, args, kwargs))
value = self.conn.remotecall(self.oid, methodname, args, kwargs)
##print("*** IdbProxy.call %s returns %r" % (methodname, value))
return value
def run(self, cmd, locals):
# Ignores locals on purpose!
seq = self.conn.asyncqueue(self.oid, "run", (cmd,), {})
self.shell.interp.active_seq = seq
def get_stack(self, frame, tbid):
# passing frame and traceback IDs, not the objects themselves
stack, i = self.call("get_stack", frame._fid, tbid)
stack = [(FrameProxy(self.conn, fid), k) for fid, k in stack]
return stack, i
def set_continue(self):
self.call("set_continue")
def set_step(self):
self.call("set_step")
def set_next(self, frame):
self.call("set_next", frame._fid)
def set_return(self, frame):
self.call("set_return", frame._fid)
def set_quit(self):
self.call("set_quit")
def set_break(self, filename, lineno):
msg = self.call("set_break", filename, lineno)
return msg
def clear_break(self, filename, lineno):
msg = self.call("clear_break", filename, lineno)
return msg
def clear_all_file_breaks(self, filename):
msg = self.call("clear_all_file_breaks", filename)
return msg
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
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)
def close_subprocess_debugger(rpcclt):
rpcclt.remotecall("exec", "stop_the_debugger", (idb_adap_oid,), {})
def restart_subprocess_debugger(rpcclt):
idb_adap_oid_ret = rpcclt.remotecall("exec", "start_the_debugger",\
(gui_adap_oid,), {})
assert idb_adap_oid_ret == idb_adap_oid, 'Idb restarted with different oid'
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_debugger', verbosity=2, exit=False)
| 12,140 | 394 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/__main__.py | """
IDLE main entry point
Run IDLE as python -m idlelib
"""
import idlelib.pyshell
idlelib.pyshell.main()
# This file does not work for 2.7; See issue 24212.
| 159 | 9 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/query.py | """
Dialogs that query users and verify the answer before accepting.
Use ttk widgets, limiting use to tcl/tk 8.5+, as in IDLE 3.6+.
Query is the generic base class for a popup dialog.
The user must either enter a valid answer or close the dialog.
Entries are validated when <Return> is entered or [Ok] is clicked.
Entries are ignored when [Cancel] or [X] are clicked.
The 'return value' is .result set to either a valid answer or None.
Subclass SectionName gets a name for a new config file section.
Configdialog uses it for new highlight theme and keybinding set names.
Subclass ModuleName gets a name for File => Open Module.
Subclass HelpSource gets menu item and path for additions to Help menu.
"""
# Query and Section name result from splitting GetCfgSectionNameDialog
# of configSectionNameDialog.py (temporarily config_sec.py) into
# generic and specific parts. 3.6 only, July 2016.
# ModuleName.entry_ok came from editor.EditorWindow.load_module.
# HelpSource was extracted from configHelpSourceEdit.py (temporarily
# config_help.py), with darwin code moved from ok to path_ok.
import importlib
import os
from sys import executable, platform # Platform is set for one test.
from tkinter import Toplevel, StringVar, W, E, S
from tkinter.ttk import Frame, Button, Entry, Label
from tkinter import filedialog
from tkinter.font import Font
class Query(Toplevel):
"""Base class for getting verified answer from a user.
For this base class, accept any non-blank string.
"""
def __init__(self, parent, title, message, *, text0='', used_names={},
_htest=False, _utest=False):
"""Create popup, do not return until tk widget destroyed.
Additional subclass init must be done before calling 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
"""
Toplevel.__init__(self, parent)
self.withdraw() # Hide while configuring, especially geometry.
self.parent = parent
self.title(title)
self.message = message
self.text0 = text0
self.used_names = used_names
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.resizable(height=False, width=False)
self.create_widgets()
self.update_idletasks() # Needed 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)
) )
if not _utest:
self.deiconify() # Unhide now that geometry set.
self.wait_window()
def create_widgets(self): # Call from override, if any.
# Bind to self 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)
self.button_ok = Button(
frame, text='OK', default='active', command=self.ok)
self.button_cancel = Button(
frame, text='Cancel', command=self.cancel)
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.button_ok.grid(column=1, row=99, padx=5)
self.button_cancel.grid(column=2, row=99, padx=5)
def showerror(self, message, widget=None):
#self.bell(displayof=self)
(widget or self.entry_error)['text'] = 'ERROR: ' + message
def entry_ok(self): # Example: usually replace.
"Return non-blank entry or None."
self.entry_error['text'] = ''
entry = self.entry.get().strip()
if not entry:
self.showerror('blank line.')
return None
return entry
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()
def cancel(self, event=None): # Do not replace.
"Set dialog result to None and destroy tk widget."
self.result = None
self.destroy()
def destroy(self):
self.grab_release()
super().destroy()
class SectionName(Query):
"Get a name for a config file section name."
# Used in ConfigDialog.GetNewKeysName, .GetNewThemeName (837)
def __init__(self, parent, title, message, used_names,
*, _htest=False, _utest=False):
super().__init__(parent, title, message, used_names=used_names,
_htest=_htest, _utest=_utest)
def entry_ok(self):
"Return sensible ConfigParser section name or None."
self.entry_error['text'] = ''
name = self.entry.get().strip()
if not name:
self.showerror('no name specified.')
return None
elif len(name)>30:
self.showerror('name is longer than 30 characters.')
return None
elif name in self.used_names:
self.showerror('name is already in use.')
return None
return name
class ModuleName(Query):
"Get a module name for Open Module menu entry."
# Used in open_module (editor.EditorWindow until move to iobinding).
def __init__(self, parent, title, message, text0,
*, _htest=False, _utest=False):
super().__init__(parent, title, message, text0=text0,
_htest=_htest, _utest=_utest)
def entry_ok(self):
"Return entered module name as file path or None."
self.entry_error['text'] = ''
name = self.entry.get().strip()
if not name:
self.showerror('no name specified.')
return None
# XXX Ought to insert current file's directory in front of path.
try:
spec = importlib.util.find_spec(name)
except (ValueError, ImportError) as msg:
self.showerror(str(msg))
return None
if spec is None:
self.showerror("module not found")
return None
if not isinstance(spec.loader, importlib.abc.SourceLoader):
self.showerror("not a source-based module")
return None
try:
file_path = spec.loader.get_filename(name)
except AttributeError:
self.showerror("loader does not support get_filename",
parent=self)
return None
return file_path
class HelpSource(Query):
"Get menu name and help source for Help menu."
# Used in ConfigDialog.HelpListItemAdd/Edit, (941/9)
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)
def create_widgets(self):
super().create_widgets()
frame = self.frame
pathlabel = Label(frame, anchor='w', justify='left',
text='Help File Path: Enter URL or browse for file')
self.pathvar = StringVar(self, self.filepath)
self.path = Entry(frame, textvariable=self.pathvar, width=40)
browse = Button(frame, text='Browse', width=8,
command=self.browse_file)
self.path_error = Label(frame, text=' ', foreground='red',
font=self.error_font)
pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0],
sticky=W)
self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E,
pady=[10,0])
browse.grid(column=2, row=11, padx=5, sticky=W+S)
self.path_error.grid(column=0, row=12, columnspan=3, padx=5,
sticky=W+E)
def askfilename(self, filetypes, initdir, initfile): # htest #
# Extracted from browse_file so can mock for unittests.
# Cannot unittest as cannot simulate button clicks.
# Test by running htest, such as by running this file.
return filedialog.Open(parent=self, filetypes=filetypes)\
.show(initialdir=initdir, initialfile=initfile)
def browse_file(self):
filetypes = [
("HTML Files", "*.htm *.html", "TEXT"),
("PDF Files", "*.pdf", "TEXT"),
("Windows Help Files", "*.chm"),
("Text Files", "*.txt", "TEXT"),
("All Files", "*")]
path = self.pathvar.get()
if path:
dir, base = os.path.split(path)
else:
base = None
if platform[:3] == 'win':
dir = os.path.join(os.path.dirname(executable), 'Doc')
if not os.path.isdir(dir):
dir = os.getcwd()
else:
dir = os.getcwd()
file = self.askfilename(filetypes, dir, base)
if file:
self.pathvar.set(file)
item_ok = SectionName.entry_ok # localize for test override
def path_ok(self):
"Simple validity check for menu file path"
path = self.path.get().strip()
if not path: #no path specified
self.showerror('no help file path specified.', self.path_error)
return None
elif not path.startswith(('www.', 'http')):
if path[:5] == 'file:':
path = path[5:]
if not os.path.exists(path):
self.showerror('help file path does not exist.',
self.path_error)
return None
if platform == 'darwin': # for Mac Safari
path = "file://" + path
return path
def entry_ok(self):
"Return apparently valid (name, path) or None"
self.entry_error['text'] = ''
self.path_error['text'] = ''
name = self.item_ok()
path = self.path_ok()
return None if name is None or path is None else (name, path)
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_query', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(Query, HelpSource)
| 12,434 | 313 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/history.py | "Implement Idle Shell history mechanism with History class"
from idlelib.config import idleConf
class History:
''' Implement Idle Shell history mechanism.
store - Store source statement (called from pyshell.resetoutput).
fetch - Fetch stored statement matching prefix already entered.
history_next - Bound to <<history-next>> event (default Alt-N).
history_prev - Bound to <<history-prev>> event (default Alt-P).
'''
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)
def history_next(self, event):
"Fetch later statement; start with ealiest if cyclic."
self.fetch(reverse=False)
return "break"
def history_prev(self, event):
"Fetch earlier statement; start with most recent."
self.fetch(reverse=True)
return "break"
def fetch(self, reverse):
'''Fetch statememt 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
def store(self, source):
"Store Shell input statement into history list."
source = source.strip()
if len(source) > 2:
# avoid duplicates
try:
self.history.remove(source)
except ValueError:
pass
self.history.append(source)
self.pointer = None
self.prefix = None
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_history', verbosity=2, exit=False)
| 4,043 | 107 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/runscript.py | """Execute code from an editor.
Check module: do a full syntax check of the current module.
Also run the tabnanny to catch any inconsistent tabs.
Run module: also execute the module's code in the __main__ namespace.
The window must have been saved previously. The module is added to
sys.modules, and is also added to the __main__ namespace.
TODO: Specify command line arguments in a dialog box.
"""
import os
import tabnanny
import tokenize
import tkinter.messagebox as tkMessageBox
from idlelib.config import idleConf
from idlelib import macosx
from idlelib import pyshell
indent_message = """Error: Inconsistent indentation detected!
1) Your indentation is outright incorrect (easy to fix), OR
2) Your indentation mixes tabs and spaces.
To fix case 2, change all tabs to spaces by using Edit->Select All followed \
by Format->Untabify Region and specify the number of columns used by each tab.
"""
class ScriptBinding:
def __init__(self, editwin):
self.editwin = editwin
# Provide instance variables referenced by debugger
# XXX This should be done differently
self.flist = self.editwin.flist
self.root = self.editwin.root
if macosx.isCocoaTk():
self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
def check_module_event(self, event):
filename = self.getfilename()
if not filename:
return 'break'
if not self.checksyntax(filename):
return 'break'
if not self.tabnanny(filename):
return 'break'
return "break"
def tabnanny(self, filename):
# XXX: tabnanny should work on binary files as well
with tokenize.open(filename) as f:
try:
tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
except tokenize.TokenError as msg:
msgtxt, (lineno, start) = msg.args
self.editwin.gotoline(lineno)
self.errorbox("Tabnanny Tokenizing Error",
"Token Error: %s" % msgtxt)
return False
except tabnanny.NannyNag as nag:
# The error messages from tabnanny are too confusing...
self.editwin.gotoline(nag.get_lineno())
self.errorbox("Tab/space error", indent_message)
return False
return True
def checksyntax(self, filename):
self.shell = shell = self.flist.open_shell()
saved_stream = shell.get_warning_stream()
shell.set_warning_stream(shell.stderr)
with open(filename, 'rb') as f:
source = f.read()
if b'\r' in source:
source = source.replace(b'\r\n', b'\n')
source = source.replace(b'\r', b'\n')
if source and source[-1] != ord(b'\n'):
source = source + b'\n'
editwin = self.editwin
text = editwin.text
text.tag_remove("ERROR", "1.0", "end")
try:
# If successful, return the compiled code
return compile(source, filename, "exec")
except (SyntaxError, OverflowError, ValueError) as value:
msg = getattr(value, 'msg', '') or value or "<no detail available>"
lineno = getattr(value, 'lineno', '') or 1
offset = getattr(value, 'offset', '') or 0
if offset == 0:
lineno += 1 #mark end of offending line
pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
editwin.colorize_syntax_error(text, pos)
self.errorbox("SyntaxError", "%-20s" % msg)
return False
finally:
shell.set_warning_stream(saved_stream)
def run_module_event(self, event):
if macosx.isCocoaTk():
# Tk-Cocoa in MacOSX is broken until at least
# Tk 8.5.9, and without this rather
# crude workaround IDLE would hang when a user
# tries to run a module using the keyboard shortcut
# (the menu item works fine).
self.editwin.text_frame.after(200,
lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
return 'break'
else:
return self._run_module_event(event)
def _run_module_event(self, event):
"""Run the module after setting up the environment.
First check the syntax. If OK, make sure the shell is active and
then transfer the arguments, set the run environment's working
directory to the directory of the module being executed and also
add that directory to its sys.path if not already included.
"""
filename = self.getfilename()
if not filename:
return 'break'
code = self.checksyntax(filename)
if not code:
return 'break'
if not self.tabnanny(filename):
return 'break'
interp = self.shell.interp
if pyshell.use_subprocess:
interp.restart_subprocess(with_cwd=False, filename=
self.editwin._filename_to_unicode(filename))
dirname = os.path.dirname(filename)
# XXX Too often this discards arguments the user just set...
interp.runcommand("""if 1:
__file__ = {filename!r}
import sys as _sys
from os.path import basename as _basename
if (not _sys.argv or
_basename(_sys.argv[0]) != _basename(__file__)):
_sys.argv = [__file__]
import os as _os
_os.chdir({dirname!r})
del _sys, _basename, _os
\n""".format(filename=filename, dirname=dirname))
interp.prepend_syspath(filename)
# XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
# go to __stderr__. With subprocess, they go to the shell.
# Need to change streams in pyshell.ModifiedInterpreter.
interp.runcode(code)
return 'break'
def getfilename(self):
"""Get source filename. If not saved, offer to save (or create) file
The debugger requires a source file. Make sure there is one, and that
the current version of the source buffer has been saved. If the user
declines to save or cancels the Save As dialog, return None.
If the user has configured IDLE for Autosave, the file will be
silently saved if it already exists and is dirty.
"""
filename = self.editwin.io.filename
if not self.editwin.get_saved():
autosave = idleConf.GetOption('main', 'General',
'autosave', type='bool')
if autosave and filename:
self.editwin.io.save(None)
else:
confirm = self.ask_save_dialog()
self.editwin.text.focus_set()
if confirm:
self.editwin.io.save(None)
filename = self.editwin.io.filename
else:
filename = None
return filename
def ask_save_dialog(self):
msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
message=msg,
default=tkMessageBox.OK,
parent=self.editwin.text)
return confirm
def errorbox(self, title, message):
# XXX This should really be a function of EditorWindow...
tkMessageBox.showerror(title, message, parent=self.editwin.text)
self.editwin.text.focus_set()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_runscript', verbosity=2,)
| 7,841 | 201 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/CREDITS.txt | Guido van Rossum, as well as being the creator of the Python language, is the
original creator of IDLE. Other contributors prior to Version 0.8 include
Mark Hammond, Jeremy Hylton, Tim Peters, and Moshe Zadka.
IDLE's recent development was carried out in the SF IDLEfork project. The
objective was to develop a version of IDLE which had an execution environment
which could be initialized prior to each run of user code.
The IDLEfork project was initiated by David Scherer, with some help from Peter
Schneider-Kamp and Nicholas Riley. David wrote the first version of the RPC
code and designed a fast turn-around environment for VPython. Guido developed
the RPC code and Remote Debugger currently integrated in IDLE. Bruce Sherwood
contributed considerable time testing and suggesting improvements.
Besides David and Guido, the main developers who were active on IDLEfork
are Stephen M. Gava, who implemented the configuration GUI, the new
configuration system, and the About dialog, and Kurt B. Kaiser, who completed
the integration of the RPC and remote debugger, implemented the threaded
subprocess, and made a number of usability enhancements.
Other contributors include Raymond Hettinger, Tony Lownds (Mac integration),
Neal Norwitz (code check and clean-up), Ronald Oussoren (Mac integration),
Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC
integration, debugger integration and persistent breakpoints).
Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou,
Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb,
Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful
patches. Thanks, guys!
For additional details refer to NEWS.txt and Changelog.
Please contact the IDLE maintainer ([email protected]) to have yourself included
here if you are one of those we missed!
| 1,866 | 38 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/multicall.py | """
MultiCall - a class which inherits its methods from a Tkinter widget (Text, for
example), but enables multiple calls of functions per virtual event - all
matching events will be called, not only the most specific one. This is done
by wrapping the event functions - event_add, event_delete and event_info.
MultiCall recognizes only a subset of legal event sequences. Sequences which
are not recognized are treated by the original Tk handling mechanism. A
more-specific event will be called before a less-specific event.
The recognized sequences are complete one-event sequences (no emacs-style
Ctrl-X Ctrl-C, no shortcuts like <3>), for all types of events.
Key/Button Press/Release events can have modifiers.
The recognized modifiers are Shift, Control, Option and Command for Mac, and
Control, Alt, Shift, Meta/M for other platforms.
For all events which were handled by MultiCall, a new member is added to the
event instance passed to the binded functions - mc_type. This is one of the
event type constants defined in this module (such as MC_KEYPRESS).
For Key/Button events (which are handled by MultiCall and may receive
modifiers), another member is added - mc_state. This member gives the state
of the recognized modifiers, as a combination of the modifier constants
also defined in this module (for example, MC_SHIFT).
Using these members is absolutely portable.
The order by which events are called is defined by these rules:
1. A more-specific event will be called before a less-specific event.
2. A recently-binded event will be called before a previously-binded event,
unless this conflicts with the first rule.
Each function will be called at most once for each event.
"""
import re
import sys
import tkinter
# the event type constants, which define the meaning of mc_type
MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3;
MC_ACTIVATE=4; MC_CIRCULATE=5; MC_COLORMAP=6; MC_CONFIGURE=7;
MC_DEACTIVATE=8; MC_DESTROY=9; MC_ENTER=10; MC_EXPOSE=11; MC_FOCUSIN=12;
MC_FOCUSOUT=13; MC_GRAVITY=14; MC_LEAVE=15; MC_MAP=16; MC_MOTION=17;
MC_MOUSEWHEEL=18; MC_PROPERTY=19; MC_REPARENT=20; MC_UNMAP=21; MC_VISIBILITY=22;
# the modifier state constants, which define the meaning of mc_state
MC_SHIFT = 1<<0; MC_CONTROL = 1<<2; MC_ALT = 1<<3; MC_META = 1<<5
MC_OPTION = 1<<6; MC_COMMAND = 1<<7
# define the list of modifiers, to be used in complex event types.
if sys.platform == "darwin":
_modifiers = (("Shift",), ("Control",), ("Option",), ("Command",))
_modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND)
else:
_modifiers = (("Control",), ("Alt",), ("Shift",), ("Meta", "M"))
_modifier_masks = (MC_CONTROL, MC_ALT, MC_SHIFT, MC_META)
# a dictionary to map a modifier name into its number
_modifier_names = dict([(name, number)
for number in range(len(_modifiers))
for name in _modifiers[number]])
# In 3.4, if no shell window is ever open, the underlying Tk widget is
# destroyed before .__del__ methods here are called. The following
# is used to selectively ignore shutdown exceptions to avoid
# 'Exception ignored' messages. See http://bugs.python.org/issue20167
APPLICATION_GONE = "application has been destroyed"
# A binder is a class which binds functions to one type of event. It has two
# methods: bind and unbind, which get a function and a parsed sequence, as
# returned by _parse_sequence(). There are two types of binders:
# _SimpleBinder handles event types with no modifiers and no detail.
# No Python functions are called when no events are binded.
# _ComplexBinder handles event types with modifiers and a detail.
# A Python function is called each time an event is generated.
class _SimpleBinder:
def __init__(self, type, widget, widgetinst):
self.type = type
self.sequence = '<'+_types[type][0]+'>'
self.widget = widget
self.widgetinst = widgetinst
self.bindedfuncs = []
self.handlerid = None
def bind(self, triplet, func):
if not self.handlerid:
def handler(event, l = self.bindedfuncs, mc_type = self.type):
event.mc_type = mc_type
wascalled = {}
for i in range(len(l)-1, -1, -1):
func = l[i]
if func not in wascalled:
wascalled[func] = True
r = func(event)
if r:
return r
self.handlerid = self.widget.bind(self.widgetinst,
self.sequence, handler)
self.bindedfuncs.append(func)
def unbind(self, triplet, func):
self.bindedfuncs.remove(func)
if not self.bindedfuncs:
self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
self.handlerid = None
def __del__(self):
if self.handlerid:
try:
self.widget.unbind(self.widgetinst, self.sequence,
self.handlerid)
except tkinter.TclError as e:
if not APPLICATION_GONE in e.args[0]:
raise
# An int in range(1 << len(_modifiers)) represents a combination of modifiers
# (if the least significant bit is on, _modifiers[0] is on, and so on).
# _state_subsets gives for each combination of modifiers, or *state*,
# a list of the states which are a subset of it. This list is ordered by the
# number of modifiers is the state - the most specific state comes first.
_states = range(1 << len(_modifiers))
_state_names = [''.join(m[0]+'-'
for i, m in enumerate(_modifiers)
if (1 << i) & s)
for s in _states]
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
_state_subsets = expand_substates(_states)
# _state_codes gives for each state, the portable code to be passed as mc_state
_state_codes = []
for s in _states:
r = 0
for i in range(len(_modifiers)):
if (1 << i) & s:
r |= _modifier_masks[i]
_state_codes.append(r)
class _ComplexBinder:
# This class binds many functions, and only unbinds them when it is deleted.
# self.handlerids is the list of seqs and ids of binded handler functions.
# The binded functions sit in a dictionary of lists of lists, which maps
# a detail (or None) and a state into a list of functions.
# When a new detail is discovered, handlers for all the possible states
# are binded.
def __create_handler(self, lists, mc_type, mc_state):
def handler(event, lists = lists,
mc_type = mc_type, mc_state = mc_state,
ishandlerrunning = self.ishandlerrunning,
doafterhandler = self.doafterhandler):
ishandlerrunning[:] = [True]
event.mc_type = mc_type
event.mc_state = mc_state
wascalled = {}
r = None
for l in lists:
for i in range(len(l)-1, -1, -1):
func = l[i]
if func not in wascalled:
wascalled[func] = True
r = l[i](event)
if r:
break
if r:
break
ishandlerrunning[:] = []
# Call all functions in doafterhandler and remove them from list
for f in doafterhandler:
f()
doafterhandler[:] = []
if r:
return r
return handler
def __init__(self, type, widget, widgetinst):
self.type = type
self.typename = _types[type][0]
self.widget = widget
self.widgetinst = widgetinst
self.bindedfuncs = {None: [[] for s in _states]}
self.handlerids = []
# we don't want to change the lists of functions while a handler is
# running - it will mess up the loop and anyway, we usually want the
# change to happen from the next event. So we have a list of functions
# for the handler to run after it finishes calling the binded functions.
# It calls them only once.
# ishandlerrunning is a list. An empty one means no, otherwise - yes.
# this is done so that it would be mutable.
self.ishandlerrunning = []
self.doafterhandler = []
for s in _states:
lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]]
handler = self.__create_handler(lists, type, _state_codes[s])
seq = '<'+_state_names[s]+self.typename+'>'
self.handlerids.append((seq, self.widget.bind(self.widgetinst,
seq, handler)))
def bind(self, triplet, func):
if triplet[2] not in self.bindedfuncs:
self.bindedfuncs[triplet[2]] = [[] for s in _states]
for s in _states:
lists = [ self.bindedfuncs[detail][i]
for detail in (triplet[2], None)
for i in _state_subsets[s] ]
handler = self.__create_handler(lists, self.type,
_state_codes[s])
seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2])
self.handlerids.append((seq, self.widget.bind(self.widgetinst,
seq, handler)))
doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func)
if not self.ishandlerrunning:
doit()
else:
self.doafterhandler.append(doit)
def unbind(self, triplet, func):
doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func)
if not self.ishandlerrunning:
doit()
else:
self.doafterhandler.append(doit)
def __del__(self):
for seq, id in self.handlerids:
try:
self.widget.unbind(self.widgetinst, seq, id)
except tkinter.TclError as e:
if not APPLICATION_GONE in e.args[0]:
raise
# define the list of event types to be handled by MultiEvent. the order is
# compatible with the definition of event type constants.
_types = (
("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"),
("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",),
("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",),
("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",),
("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",),
("Visibility",),
)
# which binder should be used for every event type?
_binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4)
# A dictionary to map a type name into its number
_type_names = dict([(name, number)
for number in range(len(_types))
for name in _types[number]])
_keysym_re = re.compile(r"^\w+$")
_button_re = re.compile(r"^[1-5]$")
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
def _triplet_to_sequence(triplet):
if triplet[2]:
return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \
triplet[2]+'>'
else:
return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>'
_multicall_dict = {}
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
def _multi_call(parent): # htest #
top = tkinter.Toplevel(parent)
top.title("Test MultiCall")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" % (x, y + 175))
text = MultiCallCreator(tkinter.Text)(top)
text.pack()
def bindseq(seq, n=[0]):
def handler(event):
print(seq)
text.bind("<<handler%d>>"%n[0], handler)
text.event_add("<<handler%d>>"%n[0], seq)
n[0] += 1
bindseq("<Key>")
bindseq("<Control-Key>")
bindseq("<Alt-Key-a>")
bindseq("<Control-Key-a>")
bindseq("<Alt-Control-Key-a>")
bindseq("<Key-b>")
bindseq("<Control-Button-1>")
bindseq("<Button-2>")
bindseq("<Alt-Button-1>")
bindseq("<FocusOut>")
bindseq("<Enter>")
bindseq("<Leave>")
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_mainmenu', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_multi_call)
| 18,648 | 449 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/iomenu.py | import codecs
from codecs import BOM_UTF8
import os
import re
import shlex
import sys
import tempfile
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
from tkinter.simpledialog import askstring
import idlelib
from idlelib.config import idleConf
if idlelib.testing: # Set True by test.test_idle to avoid setlocale.
encoding = 'utf-8'
else:
# Try setting the locale, so that we can find out
# what encoding to use
try:
import locale
locale.setlocale(locale.LC_CTYPE, "")
except (ImportError, locale.Error):
pass
locale_decode = 'ascii'
if sys.platform == 'win32':
# On Windows, we could use "mbcs". However, to give the user
# a portable encoding name, we need to find the code page
try:
locale_encoding = locale.getdefaultlocale()[1]
codecs.lookup(locale_encoding)
except LookupError:
pass
else:
try:
# Different things can fail here: the locale module may not be
# loaded, it may not offer nl_langinfo, or CODESET, or the
# resulting codeset may be unknown to Python. We ignore all
# these problems, falling back to ASCII
locale_encoding = locale.nl_langinfo(locale.CODESET)
if locale_encoding is None or locale_encoding == '':
# situation occurs on macOS
locale_encoding = 'ascii'
codecs.lookup(locale_encoding)
except (NameError, AttributeError, LookupError):
# Try getdefaultlocale: it parses environment variables,
# which may give a clue. Unfortunately, getdefaultlocale has
# bugs that can cause ValueError.
try:
locale_encoding = locale.getdefaultlocale()[1]
if locale_encoding is None or locale_encoding == '':
# situation occurs on macOS
locale_encoding = 'ascii'
codecs.lookup(locale_encoding)
except (ValueError, LookupError):
pass
locale_encoding = locale_encoding.lower()
encoding = locale_encoding
# Encoding is used in multiple files; locale_encoding nowhere.
# The only use of 'encoding' below is in _decode as initial value
# of deprecated block asking user for encoding.
# Perhaps use elsewhere should be reviewed.
coding_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
def coding_spec(data):
"""Return the encoding declaration according to PEP 263.
When checking encoded data, only the first two lines should be passed
in to avoid a UnicodeDecodeError if the rest of the data is not unicode.
The first two lines would contain the encoding specification.
Raise a LookupError if the encoding is declared but unknown.
"""
if isinstance(data, bytes):
# This encoding might be wrong. However, the coding
# spec must be ASCII-only, so any non-ASCII characters
# around here will be ignored. Decoding to Latin-1 should
# never fail (except for memory outage)
lines = data.decode('iso-8859-1')
else:
lines = data
# consider only the first two lines
if '\n' in lines:
lst = lines.split('\n', 2)[:2]
elif '\r' in lines:
lst = lines.split('\r', 2)[:2]
else:
lst = [lines]
for line in lst:
match = coding_re.match(line)
if match is not None:
break
if not blank_re.match(line):
return None
else:
return None
name = match.group(1)
try:
codecs.lookup(name)
except LookupError:
# The standard encoding error does not indicate the encoding
raise LookupError("Unknown encoding: "+name)
return name
class IOBinding:
# One instance per editor Window so methods know which to save, close.
# Open returns focus to self.editwin if aborted.
# EditorWindow.open_module, others, belong here.
def __init__(self, editwin):
self.editwin = editwin
self.text = editwin.text
self.__id_open = self.text.bind("<<open-window-from-file>>", self.open)
self.__id_save = self.text.bind("<<save-window>>", self.save)
self.__id_saveas = self.text.bind("<<save-window-as-file>>",
self.save_as)
self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>",
self.save_a_copy)
self.fileencoding = None
self.__id_print = self.text.bind("<<print-window>>", self.print_window)
def close(self):
# Undo command bindings
self.text.unbind("<<open-window-from-file>>", self.__id_open)
self.text.unbind("<<save-window>>", self.__id_save)
self.text.unbind("<<save-window-as-file>>",self.__id_saveas)
self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy)
self.text.unbind("<<print-window>>", self.__id_print)
# Break cycles
self.editwin = None
self.text = None
self.filename_change_hook = None
def get_saved(self):
return self.editwin.get_saved()
def set_saved(self, flag):
self.editwin.set_saved(flag)
def reset_undo(self):
self.editwin.reset_undo()
filename_change_hook = None
def set_filename_change_hook(self, hook):
self.filename_change_hook = hook
filename = None
dirname = None
def set_filename(self, filename):
if filename and os.path.isdir(filename):
self.filename = None
self.dirname = filename
else:
self.filename = filename
self.dirname = None
self.set_saved(1)
if self.filename_change_hook:
self.filename_change_hook()
def open(self, event=None, editFile=None):
flist = self.editwin.flist
# Save in case parent window is closed (ie, during askopenfile()).
if flist:
if not editFile:
filename = self.askopenfile()
else:
filename=editFile
if filename:
# If editFile is valid and already open, flist.open will
# shift focus to its existing window.
# If the current window exists and is a fresh unnamed,
# unmodified editor window (not an interpreter shell),
# pass self.loadfile to flist.open so it will load the file
# in the current window (if the file is not already open)
# instead of a new window.
if (self.editwin and
not getattr(self.editwin, 'interp', None) and
not self.filename and
self.get_saved()):
flist.open(filename, self.loadfile)
else:
flist.open(filename)
else:
if self.text:
self.text.focus_set()
return "break"
# Code for use outside IDLE:
if self.get_saved():
reply = self.maybesave()
if reply == "cancel":
self.text.focus_set()
return "break"
if not editFile:
filename = self.askopenfile()
else:
filename=editFile
if filename:
self.loadfile(filename)
else:
self.text.focus_set()
return "break"
eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac)
eol_re = re.compile(eol)
eol_convention = os.linesep # default
def loadfile(self, filename):
try:
# open the file in binary mode so that we can handle
# end-of-line convention ourselves.
with open(filename, 'rb') as f:
two_lines = f.readline() + f.readline()
f.seek(0)
bytes = f.read()
except OSError as msg:
tkMessageBox.showerror("I/O Error", str(msg), parent=self.text)
return False
chars, converted = self._decode(two_lines, bytes)
if chars is None:
tkMessageBox.showerror("Decoding Error",
"File %s\nFailed to Decode" % filename,
parent=self.text)
return False
# We now convert all end-of-lines to '\n's
firsteol = self.eol_re.search(chars)
if firsteol:
self.eol_convention = firsteol.group(0)
chars = self.eol_re.sub(r"\n", chars)
self.text.delete("1.0", "end")
self.set_filename(None)
self.text.insert("1.0", chars)
self.reset_undo()
self.set_filename(filename)
if converted:
# We need to save the conversion results first
# before being able to execute the code
self.set_saved(False)
self.text.mark_set("insert", "1.0")
self.text.yview("insert")
self.updaterecentfileslist(filename)
return True
def _decode(self, two_lines, bytes):
"Create a Unicode string."
chars = None
# Check presence of a UTF-8 signature first
if bytes.startswith(BOM_UTF8):
try:
chars = bytes[3:].decode("utf-8")
except UnicodeDecodeError:
# has UTF-8 signature, but fails to decode...
return None, False
else:
# Indicates that this file originally had a BOM
self.fileencoding = 'BOM'
return chars, False
# Next look for coding specification
try:
enc = coding_spec(two_lines)
except LookupError as name:
tkMessageBox.showerror(
title="Error loading the file",
message="The encoding '%s' is not known to this Python "\
"installation. The file may not display correctly" % name,
parent = self.text)
enc = None
except UnicodeDecodeError:
return None, False
if enc:
try:
chars = str(bytes, enc)
self.fileencoding = enc
return chars, False
except UnicodeDecodeError:
pass
# Try ascii:
try:
chars = str(bytes, 'ascii')
self.fileencoding = None
return chars, False
except UnicodeDecodeError:
pass
# Try utf-8:
try:
chars = str(bytes, 'utf-8')
self.fileencoding = 'utf-8'
return chars, False
except UnicodeDecodeError:
pass
# Finally, try the locale's encoding. This is deprecated;
# the user should declare a non-ASCII encoding
try:
# Wait for the editor window to appear
self.editwin.text.update()
enc = askstring(
"Specify file encoding",
"The file's encoding is invalid for Python 3.x.\n"
"IDLE will convert it to UTF-8.\n"
"What is the current encoding of the file?",
initialvalue = encoding,
parent = self.editwin.text)
if enc:
chars = str(bytes, enc)
self.fileencoding = None
return chars, True
except (UnicodeDecodeError, LookupError):
pass
return None, False # None on failure
def maybesave(self):
if self.get_saved():
return "yes"
message = "Do you want to save %s before closing?" % (
self.filename or "this untitled document")
confirm = tkMessageBox.askyesnocancel(
title="Save On Close",
message=message,
default=tkMessageBox.YES,
parent=self.text)
if confirm:
reply = "yes"
self.save(None)
if not self.get_saved():
reply = "cancel"
elif confirm is None:
reply = "cancel"
else:
reply = "no"
self.text.focus_set()
return reply
def save(self, event):
if not self.filename:
self.save_as(event)
else:
if self.writefile(self.filename):
self.set_saved(True)
try:
self.editwin.store_file_breaks()
except AttributeError: # may be a PyShell
pass
self.text.focus_set()
return "break"
def save_as(self, event):
filename = self.asksavefile()
if filename:
if self.writefile(filename):
self.set_filename(filename)
self.set_saved(1)
try:
self.editwin.store_file_breaks()
except AttributeError:
pass
self.text.focus_set()
self.updaterecentfileslist(filename)
return "break"
def save_a_copy(self, event):
filename = self.asksavefile()
if filename:
self.writefile(filename)
self.text.focus_set()
self.updaterecentfileslist(filename)
return "break"
def writefile(self, filename):
self.fixlastline()
text = self.text.get("1.0", "end-1c")
if self.eol_convention != "\n":
text = text.replace("\n", self.eol_convention)
chars = self.encode(text)
try:
with open(filename, "wb") as f:
f.write(chars)
return True
except OSError as msg:
tkMessageBox.showerror("I/O Error", str(msg),
parent=self.text)
return False
def encode(self, chars):
if isinstance(chars, bytes):
# This is either plain ASCII, or Tk was returning mixed-encoding
# text to us. Don't try to guess further.
return chars
# Preserve a BOM that might have been present on opening
if self.fileencoding == 'BOM':
return BOM_UTF8 + chars.encode("utf-8")
# See whether there is anything non-ASCII in it.
# If not, no need to figure out the encoding.
try:
return chars.encode('ascii')
except UnicodeError:
pass
# Check if there is an encoding declared
try:
# a string, let coding_spec slice it to the first two lines
enc = coding_spec(chars)
failed = None
except LookupError as msg:
failed = msg
enc = None
else:
if not enc:
# PEP 3120: default source encoding is UTF-8
enc = 'utf-8'
if enc:
try:
return chars.encode(enc)
except UnicodeError:
failed = "Invalid encoding '%s'" % enc
tkMessageBox.showerror(
"I/O Error",
"%s.\nSaving as UTF-8" % failed,
parent = self.text)
# Fallback: save as UTF-8, with BOM - ignoring the incorrect
# declared encoding
return BOM_UTF8 + chars.encode("utf-8")
def fixlastline(self):
c = self.text.get("end-2c")
if c != '\n':
self.text.insert("end-1c", "\n")
def print_window(self, event):
confirm = tkMessageBox.askokcancel(
title="Print",
message="Print to Default Printer",
default=tkMessageBox.OK,
parent=self.text)
if not confirm:
self.text.focus_set()
return "break"
tempfilename = None
saved = self.get_saved()
if saved:
filename = self.filename
# shell undo is reset after every prompt, looks saved, probably isn't
if not saved or filename is None:
(tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_')
filename = tempfilename
os.close(tfd)
if not self.writefile(tempfilename):
os.unlink(tempfilename)
return "break"
platform = os.name
printPlatform = True
if platform == 'posix': #posix platform
command = idleConf.GetOption('main','General',
'print-command-posix')
command = command + " 2>&1"
elif platform == 'nt': #win32 platform
command = idleConf.GetOption('main','General','print-command-win')
else: #no printing for this platform
printPlatform = False
if printPlatform: #we can try to print for this platform
command = command % shlex.quote(filename)
pipe = os.popen(command, "r")
# things can get ugly on NT if there is no printer available.
output = pipe.read().strip()
status = pipe.close()
if status:
output = "Printing failed (exit status 0x%x)\n" % \
status + output
if output:
output = "Printing command: %s\n" % repr(command) + output
tkMessageBox.showerror("Print status", output, parent=self.text)
else: #no printing for this platform
message = "Printing is not enabled for this platform: %s" % platform
tkMessageBox.showinfo("Print status", message, parent=self.text)
if tempfilename:
os.unlink(tempfilename)
return "break"
opendialog = None
savedialog = None
filetypes = (
("Python files", "*.py *.pyw", "TEXT"),
("Text files", "*.txt", "TEXT"),
("All files", "*"),
)
defaultextension = '.py' if sys.platform == 'darwin' else ''
def askopenfile(self):
dir, base = self.defaultfilename("open")
if not self.opendialog:
self.opendialog = tkFileDialog.Open(parent=self.text,
filetypes=self.filetypes)
filename = self.opendialog.show(initialdir=dir, initialfile=base)
return filename
def defaultfilename(self, mode="open"):
if self.filename:
return os.path.split(self.filename)
elif self.dirname:
return self.dirname, ""
else:
try:
pwd = os.getcwd()
except OSError:
pwd = ""
return pwd, ""
def asksavefile(self):
dir, base = self.defaultfilename("save")
if not self.savedialog:
self.savedialog = tkFileDialog.SaveAs(
parent=self.text,
filetypes=self.filetypes,
defaultextension=self.defaultextension)
filename = self.savedialog.show(initialdir=dir, initialfile=base)
return filename
def updaterecentfileslist(self,filename):
"Update recent file list on all editor windows"
if self.editwin.flist:
self.editwin.update_recent_files_list(filename)
def _io_binding(parent): # htest #
from tkinter import Toplevel, Text
root = Toplevel(parent)
root.title("Test IOBinding")
x, y = map(int, parent.geometry().split('+')[1:])
root.geometry("+%d+%d" % (x, y + 175))
class MyEditWin:
def __init__(self, text):
self.text = text
self.flist = None
self.text.bind("<Control-o>", self.open)
self.text.bind('<Control-p>', self.print)
self.text.bind("<Control-s>", self.save)
self.text.bind("<Alt-s>", self.saveas)
self.text.bind('<Control-c>', self.savecopy)
def get_saved(self): return 0
def set_saved(self, flag): pass
def reset_undo(self): pass
def open(self, event):
self.text.event_generate("<<open-window-from-file>>")
def print(self, event):
self.text.event_generate("<<print-window>>")
def save(self, event):
self.text.event_generate("<<save-window>>")
def saveas(self, event):
self.text.event_generate("<<save-window-as-file>>")
def savecopy(self, event):
self.text.event_generate("<<save-copy-of-window-as-file>>")
text = Text(root)
text.pack()
text.focus_set()
editwin = MyEditWin(text)
IOBinding(editwin)
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_iomenu', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_io_binding)
| 20,734 | 575 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/run.py | import io
import linecache
import queue
import sys
import time
import traceback
import _thread as thread
import threading
import warnings
import tkinter # Tcl, deletions, messagebox if startup fails
from idlelib import autocomplete # AutoComplete, fetch_encodings
from idlelib import calltip # Calltip
from idlelib import debugger_r # start_debugger
from idlelib import debugobj_r # remote_object_tree_item
from idlelib import iomenu # encoding
from idlelib import rpc # multiple objects
from idlelib import stackviewer # StackTreeItem
import __main__
for mod in ('simpledialog', 'messagebox', 'font',
'dialog', 'filedialog', 'commondialog',
'ttk'):
delattr(tkinter, mod)
del sys.modules['tkinter.' + mod]
LOCALHOST = '127.0.0.1'
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
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.
_warnings_showwarning = None
def capture_warnings(capture):
"Replace warning.showwarning with idle_showwarning_subproc, or reverse."
global _warnings_showwarning
if capture:
if _warnings_showwarning is None:
_warnings_showwarning = warnings.showwarning
warnings.showwarning = idle_showwarning_subproc
else:
if _warnings_showwarning is not None:
warnings.showwarning = _warnings_showwarning
_warnings_showwarning = None
capture_warnings(True)
tcl = tkinter.Tcl()
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")
# Thread shared globals: Establish a queue between a subthread (which handles
# the socket) and the main thread (which runs user code), plus global
# completion, exit and interruptable (the main thread) flags:
exit_now = False
quitting = False
interruptable = False
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
def manage_socket(address):
for i in range(3):
time.sleep(i)
try:
server = MyRPCServer(address, MyHandler)
break
except OSError as err:
print("IDLE Subprocess: OSError: " + err.args[1] +
", retrying....", file=sys.__stderr__)
socket_error = err
else:
print("IDLE Subprocess: Connection to "
"IDLE GUI failed, exiting.", file=sys.__stderr__)
show_socket_error(socket_error, address)
global exit_now
exit_now = True
return
server.handle_request() # A single request only
def show_socket_error(err, address):
"Display socket error from manage_socket."
import tkinter
from tkinter.messagebox import showerror
root = tkinter.Tk()
fix_scaling(root)
root.withdraw()
msg = f"IDLE's subprocess can't connect to {address[0]}:{address[1]}.\n"\
f"Fatal OSError #{err.errno}: {err.strerror}.\n"\
f"See the 'Startup failure' section of the IDLE doc, online at\n"\
f"https://docs.python.org/3/library/idle.html#startup-failure"
showerror("IDLE Subprocess Error", msg, parent=root)
root.destroy()
def print_exception():
import linecache
linecache.checkcache()
flush_stdout()
efile = sys.stderr
typ, val, tb = excinfo = sys.exc_info()
sys.last_type, sys.last_value, sys.last_traceback = excinfo
seen = set()
def print_exc(typ, exc, tb):
seen.add(id(exc))
context = exc.__context__
cause = exc.__cause__
if cause is not None and id(cause) not in seen:
print_exc(type(cause), cause, cause.__traceback__)
print("\nThe above exception was the direct cause "
"of the following exception:\n", file=efile)
elif (context is not None and
not exc.__suppress_context__ and
id(context) not in seen):
print_exc(type(context), context, context.__traceback__)
print("\nDuring handling of the above exception, "
"another exception occurred:\n", file=efile)
if tb:
tbe = traceback.extract_tb(tb)
print('Traceback (most recent call last):', file=efile)
exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
"debugger_r.py", "bdb.py")
cleanup_traceback(tbe, exclude)
traceback.print_list(tbe, file=efile)
lines = traceback.format_exception_only(typ, exc)
for line in lines:
print(line, end='', file=efile)
print_exc(typ, val, tb)
def cleanup_traceback(tb, exclude):
"Remove excluded traces from beginning/end of tb; get cached lines"
orig_tb = tb[:]
while tb:
for rpcfile in exclude:
if tb[0][0].count(rpcfile):
break # found an exclude, break for: and delete tb[0]
else:
break # no excludes, have left RPC code, break while:
del tb[0]
while tb:
for rpcfile in exclude:
if tb[-1][0].count(rpcfile):
break
else:
break
del tb[-1]
if len(tb) == 0:
# exception was in IDLE internals, don't prune!
tb[:] = orig_tb[:]
print("** IDLE Internal Exception: ", file=sys.stderr)
rpchandler = rpc.objecttable['exec'].rpchandler
for i in range(len(tb)):
fn, ln, nm, line = tb[i]
if nm == '?':
nm = "-toplevel-"
if not line and fn.startswith("<pyshell#"):
line = rpchandler.remotecall('linecache', 'getline',
(fn, ln), {})
tb[i] = fn, ln, nm, line
def flush_stdout():
"""XXX How to do this now?"""
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)
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)
class MyRPCServer(rpc.RPCServer):
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()
# Pseudofiles for shell-remote communication (also used in pyshell)
class PseudoFile(io.TextIOBase):
def __init__(self, shell, tags, encoding=None):
self.shell = shell
self.tags = tags
self._encoding = encoding
@property
def encoding(self):
return self._encoding
@property
def name(self):
return '<%s>' % self.tags
def isatty(self):
return True
class PseudoOutputFile(PseudoFile):
def writable(self):
return True
def write(self, s):
if self.closed:
raise ValueError("write to closed file")
if type(s) is not str:
if not isinstance(s, str):
raise TypeError('must be str, not ' + type(s).__name__)
# See issue #19481
s = str.__str__(s)
return self.shell.write(s, self.tags)
class PseudoInputFile(PseudoFile):
def __init__(self, shell, tags, encoding=None):
PseudoFile.__init__(self, shell, tags, encoding)
self._line_buffer = ''
def readable(self):
return True
def read(self, size=-1):
if self.closed:
raise ValueError("read from closed file")
if size is None:
size = -1
elif not isinstance(size, int):
raise TypeError('must be int, not ' + type(size).__name__)
result = self._line_buffer
self._line_buffer = ''
if size < 0:
while True:
line = self.shell.readline()
if not line: break
result += line
else:
while len(result) < size:
line = self.shell.readline()
if not line: break
result += line
self._line_buffer = result[size:]
result = result[:size]
return result
def readline(self, size=-1):
if self.closed:
raise ValueError("read from closed file")
if size is None:
size = -1
elif not isinstance(size, int):
raise TypeError('must be int, not ' + type(size).__name__)
line = self._line_buffer or self.shell.readline()
if size < 0:
size = len(line)
eol = line.find('\n', 0, size)
if eol >= 0:
size = eol + 1
self._line_buffer = line[size:]
return line[:size]
def close(self):
self.shell.close()
class MyHandler(rpc.RPCHandler):
def handle(self):
"""Override base method"""
executive = Executive(self)
self.register("exec", executive)
self.console = self.get_remote_proxy("console")
sys.stdin = PseudoInputFile(self.console, "stdin",
iomenu.encoding)
sys.stdout = PseudoOutputFile(self.console, "stdout",
iomenu.encoding)
sys.stderr = PseudoOutputFile(self.console, "stderr",
iomenu.encoding)
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
self.interp = self.get_remote_proxy("interp")
rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
def exithook(self):
"override SocketIO method - wait for MainThread to shut us down"
time.sleep(10)
def EOFhook(self):
"Override SocketIO method - terminate wait on callback and exit thread"
global quitting
quitting = True
thread.interrupt_main()
def decode_interrupthook(self):
"interrupt awakened thread"
global quitting
quitting = True
thread.interrupt_main()
class Executive(object):
def __init__(self, rpchandler):
self.rpchandler = rpchandler
self.locals = __main__.__dict__
self.calltip = calltip.Calltip()
self.autocomplete = autocomplete.AutoComplete()
def runcode(self, code):
global interruptable
try:
self.usr_exc_info = None
interruptable = True
try:
exec(code, self.locals)
finally:
interruptable = False
except SystemExit:
# Scripts that raise SystemExit should just
# return to the interactive prompt
pass
except:
self.usr_exc_info = sys.exc_info()
if quitting:
exit()
# even print a user code SystemExit exception, continue
print_exception()
jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
if jit:
self.rpchandler.interp.open_remote_stack_viewer()
else:
flush_stdout()
def interrupt_the_server(self):
if interruptable:
thread.interrupt_main()
def start_the_debugger(self, gui_adap_oid):
return debugger_r.start_debugger(self.rpchandler, gui_adap_oid)
def stop_the_debugger(self, idb_adap_oid):
"Unregister the Idb Adapter. Link objects and Idb then subject to GC"
self.rpchandler.unregister(idb_adap_oid)
def get_the_calltip(self, name):
return self.calltip.fetch_tip(name)
def get_the_completion_list(self, what, mode):
return self.autocomplete.fetch_completions(what, mode)
def stackviewer(self, flist_oid=None):
if self.usr_exc_info:
typ, val, tb = self.usr_exc_info
else:
return None
flist = None
if flist_oid is not None:
flist = self.rpchandler.get_remote_proxy(flist_oid)
while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
tb = tb.tb_next
sys.last_type = typ
sys.last_value = val
item = stackviewer.StackTreeItem(flist, tb)
return debugobj_r.remote_object_tree_item(item)
capture_warnings(False) # Make sure turned off; see issue 18081
| 17,272 | 526 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/help_about.py | """About Dialog for IDLE
"""
import os
import sys
from platform import python_version, architecture
from tkinter import Toplevel, Frame, Label, Button, PhotoImage
from tkinter import SUNKEN, TOP, BOTTOM, LEFT, X, BOTH, W, EW, NSEW, E
from idlelib import textview
def build_bits():
"Return bits for platform."
if sys.platform == 'darwin':
return '64' if sys.maxsize > 2**32 else '32'
else:
return architecture()[0][:2]
class AboutDialog(Toplevel):
"""Modal about dialog for idle
"""
def __init__(self, parent, title=None, *, _htest=False, _utest=False):
"""Create popup, do not return until tk widget destroyed.
parent - parent of this dialog
title - string which is title of popup dialog
_htest - bool, change box location when running htest
_utest - bool, don't wait_window when running unittest
"""
Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
# place dialog below parent if running htest
self.geometry("+%d+%d" % (
parent.winfo_rootx()+30,
parent.winfo_rooty()+(30 if not _htest else 100)))
self.bg = "#bbbbbb"
self.fg = "#000000"
self.create_widgets()
self.resizable(height=False, width=False)
self.title(title or
f'About IDLE {python_version()} ({build_bits()} bit)')
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.ok)
self.parent = parent
self.button_ok.focus_set()
self.bind('<Return>', self.ok) # dismiss dialog
self.bind('<Escape>', self.ok) # dismiss dialog
self._current_textview = None
self._utest = _utest
if not _utest:
self.deiconify()
self.wait_window()
def create_widgets(self):
frame = Frame(self, borderwidth=2, relief=SUNKEN)
frame_buttons = Frame(self)
frame_buttons.pack(side=BOTTOM, fill=X)
frame.pack(side=TOP, expand=True, fill=BOTH)
self.button_ok = Button(frame_buttons, text='Close',
command=self.ok)
self.button_ok.pack(padx=5, pady=5)
frame_background = Frame(frame, bg=self.bg)
frame_background.pack(expand=True, fill=BOTH)
header = Label(frame_background, text='IDLE', fg=self.fg,
bg=self.bg, font=('courier', 24, 'bold'))
header.grid(row=0, column=0, sticky=E, padx=10, pady=10)
tk_patchlevel = self.tk.call('info', 'patchlevel')
ext = '.png' if tk_patchlevel >= '8.6' else '.gif'
icon = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'Icons', f'idle_48{ext}')
self.icon_image = PhotoImage(master=self._root(), file=icon)
logo = Label(frame_background, image=self.icon_image, bg=self.bg)
logo.grid(row=0, column=0, sticky=W, rowspan=2, padx=10, pady=10)
byline_text = "Python's Integrated Development\nand Learning Environment" + 5*'\n'
byline = Label(frame_background, text=byline_text, justify=LEFT,
fg=self.fg, bg=self.bg)
byline.grid(row=2, column=0, sticky=W, columnspan=3, padx=10, pady=5)
email = Label(frame_background, text='email: [email protected]',
justify=LEFT, fg=self.fg, bg=self.bg)
email.grid(row=6, column=0, columnspan=2, sticky=W, padx=10, pady=0)
docs = Label(frame_background, text='https://docs.python.org/' +
python_version()[:3] + '/library/idle.html',
justify=LEFT, fg=self.fg, bg=self.bg)
docs.grid(row=7, column=0, columnspan=2, sticky=W, padx=10, pady=0)
Frame(frame_background, borderwidth=1, relief=SUNKEN,
height=2, bg=self.bg).grid(row=8, column=0, sticky=EW,
columnspan=3, padx=5, pady=5)
pyver = Label(frame_background,
text='Python version: ' + python_version(),
fg=self.fg, bg=self.bg)
pyver.grid(row=9, column=0, sticky=W, padx=10, pady=0)
tkver = Label(frame_background, text='Tk version: ' + tk_patchlevel,
fg=self.fg, bg=self.bg)
tkver.grid(row=9, column=1, sticky=W, padx=2, pady=0)
py_buttons = Frame(frame_background, bg=self.bg)
py_buttons.grid(row=10, column=0, columnspan=2, sticky=NSEW)
self.py_license = Button(py_buttons, text='License', width=8,
highlightbackground=self.bg,
command=self.show_py_license)
self.py_license.pack(side=LEFT, padx=10, pady=10)
self.py_copyright = Button(py_buttons, text='Copyright', width=8,
highlightbackground=self.bg,
command=self.show_py_copyright)
self.py_copyright.pack(side=LEFT, padx=10, pady=10)
self.py_credits = Button(py_buttons, text='Credits', width=8,
highlightbackground=self.bg,
command=self.show_py_credits)
self.py_credits.pack(side=LEFT, padx=10, pady=10)
Frame(frame_background, borderwidth=1, relief=SUNKEN,
height=2, bg=self.bg).grid(row=11, column=0, sticky=EW,
columnspan=3, padx=5, pady=5)
idlever = Label(frame_background,
text='IDLE version: ' + python_version(),
fg=self.fg, bg=self.bg)
idlever.grid(row=12, column=0, sticky=W, padx=10, pady=0)
idle_buttons = Frame(frame_background, bg=self.bg)
idle_buttons.grid(row=13, column=0, columnspan=3, sticky=NSEW)
self.readme = Button(idle_buttons, text='README', width=8,
highlightbackground=self.bg,
command=self.show_readme)
self.readme.pack(side=LEFT, padx=10, pady=10)
self.idle_news = Button(idle_buttons, text='NEWS', width=8,
highlightbackground=self.bg,
command=self.show_idle_news)
self.idle_news.pack(side=LEFT, padx=10, pady=10)
self.idle_credits = Button(idle_buttons, text='Credits', width=8,
highlightbackground=self.bg,
command=self.show_idle_credits)
self.idle_credits.pack(side=LEFT, padx=10, pady=10)
# License, copyright, and credits are of type _sitebuiltins._Printer
def show_py_license(self):
"Handle License button event."
self.display_printer_text('About - License', license)
def show_py_copyright(self):
"Handle Copyright button event."
self.display_printer_text('About - Copyright', copyright)
def show_py_credits(self):
"Handle Python Credits button event."
self.display_printer_text('About - Python Credits', credits)
# Encode CREDITS.txt to utf-8 for proper version of Loewis.
# Specify others as ascii until need utf-8, so catch errors.
def show_idle_credits(self):
"Handle Idle Credits button event."
self.display_file_text('About - Credits', 'CREDITS.txt', 'utf-8')
def show_readme(self):
"Handle Readme button event."
self.display_file_text('About - Readme', 'README.txt', 'ascii')
def show_idle_news(self):
"Handle News button event."
self.display_file_text('About - NEWS', 'NEWS.txt', 'utf-8')
def display_printer_text(self, title, printer):
"""Create textview for built-in constants.
Built-in constants have type _sitebuiltins._Printer. The
text is extracted from the built-in and then sent to a text
viewer with self as the parent and title as the title of
the popup.
"""
printer._Printer__setup()
text = '\n'.join(printer._Printer__lines)
self._current_textview = textview.view_text(
self, title, text, _utest=self._utest)
def display_file_text(self, title, filename, encoding=None):
"""Create textview for filename.
The filename needs to be in the current directory. The path
is sent to a text viewer with self as the parent, title as
the title of the popup, and the file encoding.
"""
fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)
self._current_textview = textview.view_file(
self, title, fn, encoding, _utest=self._utest)
def ok(self, event=None):
"Dismiss help_about dialog."
self.grab_release()
self.destroy()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_help_about', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(AboutDialog)
| 8,981 | 208 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/searchbase.py | '''Define SearchDialogBase used by Search, Replace, and Grep dialogs.'''
from tkinter import Toplevel, Frame
from tkinter.ttk import Entry, Label, Button, Checkbutton, Radiobutton
class SearchDialogBase:
'''Create most of a 3 or 4 row, 3 column search dialog.
The left and wide middle column contain:
1 or 2 labeled text entry lines (make_entry, create_entries);
a row of standard Checkbuttons (make_frame, create_option_buttons),
each of which corresponds to a search engine Variable;
a row of dialog-specific Check/Radiobuttons (create_other_buttons).
The narrow right column contains command buttons
(make_button, create_command_buttons).
These are bound to functions that execute the command.
Except for command buttons, this base class is not limited to items
common to all three subclasses. Rather, it is the Find dialog minus
the "Find Next" command, its execution function, and the
default_command attribute needed in create_widgets. The other
dialogs override attributes and methods, the latter to replace and
add widgets.
'''
title = "Search Dialog" # replace in subclasses
icon = "Search"
needwrapbutton = 1 # not in Find in Files
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_widgers().
title (of dialog): class attribute, override in subclasses.
icon (of dialog): ditto, use unclear if cannot minimize dialog.
'''
self.root = root
self.engine = engine
self.top = None
def open(self, text, searchphrase=None):
"Make dialog visible on top of others and ready to use."
self.text = text
if not self.top:
self.create_widgets()
else:
self.top.deiconify()
self.top.tkraise()
if searchphrase:
self.ent.delete(0,"end")
self.ent.insert("end",searchphrase)
self.ent.focus_set()
self.ent.selection_range(0, "end")
self.ent.icursor(0)
self.top.grab_set()
def close(self, event=None):
"Put dialog away for later use."
if self.top:
self.top.grab_release()
self.top.withdraw()
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.bell = top.bell
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
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
def create_entries(self):
"Create one or more entry lines with make_entry."
self.ent = self.make_entry("Find:", self.engine.patvar)[0]
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
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
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
def make_button(self, label, command, isdef=0):
"Return command button gridded in command frame."
b = Button(self.buttonframe,
text=label, command=command,
default=isdef and "active" or "normal")
cols,rows=self.buttonframe.grid_size()
b.grid(pady=1,row=rows,column=0,sticky="ew")
self.buttonframe.grid(rowspan=rows+1)
return b
def create_command_buttons(self):
"Place buttons in vertical command frame gridded on right."
f = self.buttonframe = Frame(self.top)
f.grid(row=0,column=2,padx=2,pady=2,ipadx=2,ipady=2)
b = self.make_button("close", self.close)
b.lower()
class _searchbase(SearchDialogBase): # htest #
"Create auto-opening dialog with no text connection."
def __init__(self, parent):
import re
from idlelib import searchengine
self.root = parent
self.engine = searchengine.get(parent)
self.create_widgets()
print(parent.geometry())
width,height, x,y = list(map(int, re.split('[x+]', parent.geometry())))
self.top.geometry("+%d+%d" % (x + 40, y + 175))
def default_command(self, dummy): pass
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_searchbase', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_searchbase)
| 7,451 | 202 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/codecontext.py | """codecontext - display the block context above the edit window
Once code has scrolled off the top of a window, it can be difficult to
determine which block you are in. This extension implements a pane at the top
of each IDLE edit window which provides block structure hints. These hints are
the lines which contain the block opening keywords, e.g. 'if', for the
enclosing block. The number of hint lines is determined by the maxlines
variable in the codecontext section of config-extensions.def. Lines which do
not open blocks are not shown in the context hints pane.
"""
import re
from sys import maxsize as INFINITY
import tkinter
from tkinter.constants import TOP, X, SUNKEN
from idlelib.config import idleConf
BLOCKOPENERS = {"class", "def", "elif", "else", "except", "finally", "for",
"if", "try", "while", "with", "async"}
UPDATEINTERVAL = 100 # millisec
CONFIGUPDATEINTERVAL = 1000 # millisec
def get_spaces_firstword(codeline, c=re.compile(r"^(\s*)(\w*)")):
"Extract the beginning whitespace and first word from codeline."
return c.match(codeline).groups()
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
class CodeContext:
"Display block context above the edit window."
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.textfont is the editor window font.
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.textfont = self.text["font"]
self.contextcolors = CodeContext.colors
self.context = None
self.topvisible = 1
self.info = [(0, -1, "", False)]
# Start two update cycles, one for context lines, one for font changes.
self.t1 = self.text.after(UPDATEINTERVAL, self.timer_event)
self.t2 = self.text.after(CONFIGUPDATEINTERVAL, self.config_timer_event)
@classmethod
def reload(cls):
"Load class variables from config."
cls.context_depth = idleConf.GetOption("extensions", "CodeContext",
"maxlines", type="int", default=15)
cls.colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'context')
def __del__(self):
"Cancel scheduled events."
try:
self.text.after_cancel(self.t1)
self.text.after_cancel(self.t2)
except:
pass
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 not self.context:
# 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:
padx += widget.tk.getint(widget.pack_info()['padx'])
padx += widget.tk.getint(widget.cget('padx'))
border += widget.tk.getint(widget.cget('border'))
self.context = tkinter.Text(
self.editwin.top, font=self.textfont,
bg=self.contextcolors['background'],
fg=self.contextcolors['foreground'],
height=1,
width=1, # Don't request more than we get.
padx=padx, border=border, relief=SUNKEN, state='disabled')
self.context.bind('<ButtonRelease-1>', self.jumptoline)
# Pack the context widget before and above the text_frame widget,
# thus ensuring that it will appear directly above text_frame.
self.context.pack(side=TOP, fill=X, expand=False,
before=self.editwin.text_frame)
else:
self.context.destroy()
self.context = None
return "break"
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
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 = int(self.text.index("@0,0").split('.')[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'
def jumptoline(self, event=None):
"Show clicked context line at top of editor."
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()
def timer_event(self):
"Event on editor text widget triggered every UPDATEINTERVAL ms."
if self.context:
self.update_code_context()
self.t1 = self.text.after(UPDATEINTERVAL, self.timer_event)
def config_timer_event(self):
"Event on editor text widget triggered every CONFIGUPDATEINTERVAL ms."
newtextfont = self.text["font"]
if (self.context and (newtextfont != self.textfont or
CodeContext.colors != self.contextcolors)):
self.textfont = newtextfont
self.contextcolors = CodeContext.colors
self.context["font"] = self.textfont
self.context['background'] = self.contextcolors['background']
self.context['foreground'] = self.contextcolors['foreground']
self.t2 = self.text.after(CONFIGUPDATEINTERVAL, self.config_timer_event)
CodeContext.reload()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_codecontext', verbosity=2, exit=False)
# Add htest.
| 10,490 | 241 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/configdialog.py | """IDLE Configuration Dialog: support user customization of IDLE by GUI
Customize font faces, sizes, and colorization attributes. Set indentation
defaults. Customize keybindings. Colorization and keybindings can be
saved as user defined sets. Select startup options including shell/editor
and default window size. Define additional help sources.
Note that tab width in IDLE is currently fixed at eight due to Tk issues.
Refer to comments in EditorWindow autoindent code for details.
"""
from tkinter import (Toplevel, Listbox, Text, Scale, Canvas,
StringVar, BooleanVar, IntVar, TRUE, FALSE,
TOP, BOTTOM, RIGHT, LEFT, SOLID, GROOVE,
NONE, BOTH, X, Y, W, E, EW, NS, NSEW, NW,
HORIZONTAL, VERTICAL, ANCHOR, ACTIVE, END)
from tkinter.ttk import (Button, Checkbutton, Entry, Frame, Label, LabelFrame,
OptionMenu, Notebook, Radiobutton, Scrollbar, Style)
import tkinter.colorchooser as tkColorChooser
import tkinter.font as tkFont
from tkinter import messagebox
from idlelib.config import idleConf, ConfigChanges
from idlelib.config_key import GetKeysDialog
from idlelib.dynoption import DynOptionMenu
from idlelib import macosx
from idlelib.query import SectionName, HelpSource
from idlelib.textview import view_text
from idlelib.autocomplete import AutoComplete
from idlelib.codecontext import CodeContext
from idlelib.parenmatch import ParenMatch
from idlelib.paragraph import FormatParagraph
from idlelib.squeezer import Squeezer
changes = ConfigChanges()
# Reload changed options in the following classes.
reloadables = (AutoComplete, CodeContext, ParenMatch, FormatParagraph,
Squeezer)
class ConfigDialog(Toplevel):
"""Config dialog for IDLE.
"""
def __init__(self, parent, title='', *, _htest=False, _utest=False):
"""Show the tabbed dialog for user configuration.
Args:
parent - parent of this dialog
title - string which is the title of this popup dialog
_htest - bool, change box location when running htest
_utest - bool, don't wait_window when running unittest
Note: Focus set on font page fontlist.
Methods:
create_widgets
cancel: Bound to DELETE_WINDOW protocol.
"""
Toplevel.__init__(self, parent)
self.parent = parent
if _htest:
parent.instance_dict = {}
if not _utest:
self.withdraw()
self.configure(borderwidth=5)
self.title(title or 'IDLE Preferences')
x = parent.winfo_rootx() + 20
y = parent.winfo_rooty() + (30 if not _htest else 150)
self.geometry(f'+{x}+{y}')
# Each theme element key is its display name.
# The first value of the tuple is the sample area tag name.
# The second value is the display name list sort index.
self.create_widgets()
self.resizable(height=FALSE, width=FALSE)
self.transient(parent)
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.fontpage.fontlist.focus_set()
# XXX Decide whether to keep or delete these key bindings.
# Key bindings for this dialog.
# self.bind('<Escape>', self.Cancel) #dismiss dialog, no save
# self.bind('<Alt-a>', self.Apply) #apply changes, save
# self.bind('<F1>', self.Help) #context help
# Attach callbacks after loading config to avoid calling them.
tracers.attach()
if not _utest:
self.grab_set()
self.wm_deiconify()
self.wait_window()
def create_widgets(self):
"""Create and place widgets for tabbed dialog.
Widgets Bound to self:
note: Notebook
highpage: HighPage
fontpage: FontPage
keyspage: KeysPage
genpage: GenPage
extpage: self.create_page_extensions
Methods:
create_action_buttons
load_configs: Load pages except for extensions.
activate_config_changes: Tell editors to reload.
"""
self.note = note = Notebook(self)
self.highpage = HighPage(note)
self.fontpage = FontPage(note, self.highpage)
self.keyspage = KeysPage(note)
self.genpage = GenPage(note)
self.extpage = self.create_page_extensions()
note.add(self.fontpage, text='Fonts/Tabs')
note.add(self.highpage, text='Highlights')
note.add(self.keyspage, text=' Keys ')
note.add(self.genpage, text=' General ')
note.add(self.extpage, text='Extensions')
note.enable_traversal()
note.pack(side=TOP, expand=TRUE, fill=BOTH)
self.create_action_buttons().pack(side=BOTTOM)
def create_action_buttons(self):
"""Return frame of action buttons for dialog.
Methods:
ok
apply
cancel
help
Widget Structure:
outer: Frame
buttons: Frame
(no assignment): Button (ok)
(no assignment): Button (apply)
(no assignment): Button (cancel)
(no assignment): Button (help)
(no assignment): Frame
"""
if macosx.isAquaTk():
# Changing the default padding on OSX results in unreadable
# text in the buttons.
padding_args = {}
else:
padding_args = {'padding': (6, 3)}
outer = Frame(self, padding=2)
buttons = Frame(outer, padding=2)
for txt, cmd in (
('Ok', self.ok),
('Apply', self.apply),
('Cancel', self.cancel),
('Help', self.help)):
Button(buttons, text=txt, command=cmd, takefocus=FALSE,
**padding_args).pack(side=LEFT, padx=5)
# Add space above buttons.
Frame(outer, height=2, borderwidth=0).pack(side=TOP)
buttons.pack(side=BOTTOM)
return outer
def ok(self):
"""Apply config changes, then dismiss dialog.
Methods:
apply
destroy: inherited
"""
self.apply()
self.destroy()
def apply(self):
"""Apply config changes and leave dialog open.
Methods:
deactivate_current_config
save_all_changed_extensions
activate_config_changes
"""
self.deactivate_current_config()
changes.save_all()
self.save_all_changed_extensions()
self.activate_config_changes()
def cancel(self):
"""Dismiss config dialog.
Methods:
destroy: inherited
"""
self.destroy()
def destroy(self):
global font_sample_text
font_sample_text = self.fontpage.font_sample.get('1.0', 'end')
self.grab_release()
super().destroy()
def help(self):
"""Create textview for config dialog help.
Attrbutes accessed:
note
Methods:
view_text: Method from textview module.
"""
page = self.note.tab(self.note.select(), option='text').strip()
view_text(self, title='Help for IDLE preferences',
text=help_common+help_pages.get(page, ''))
def deactivate_current_config(self):
"""Remove current key bindings.
Iterate over window instances defined in parent and remove
the keybindings.
"""
# Before a config is saved, some cleanup of current
# config must be done - remove the previous keybindings.
win_instances = self.parent.instance_dict.keys()
for instance in win_instances:
instance.RemoveKeybindings()
def activate_config_changes(self):
"""Apply configuration changes to current windows.
Dynamically update the current parent window instances
with some of the configuration changes.
"""
win_instances = self.parent.instance_dict.keys()
for instance in win_instances:
instance.ResetColorizer()
instance.ResetFont()
instance.set_notabs_indentwidth()
instance.ApplyKeybindings()
instance.reset_help_menu_entries()
for klass in reloadables:
klass.reload()
def create_page_extensions(self):
"""Part of the config dialog used for configuring IDLE extensions.
This code is generic - it works for any and all IDLE extensions.
IDLE extensions save their configuration options using idleConf.
This code reads the current configuration using idleConf, supplies a
GUI interface to change the configuration values, and saves the
changes using idleConf.
Not all changes take effect immediately - some may require restarting IDLE.
This depends on each extension's implementation.
All values are treated as text, and it is up to the user to supply
reasonable values. The only exception to this are the 'enable*' options,
which are boolean, and can be toggled with a True/False button.
Methods:
load_extensions:
extension_selected: Handle selection from list.
create_extension_frame: Hold widgets for one extension.
set_extension_value: Set in userCfg['extensions'].
save_all_changed_extensions: Call extension page Save().
"""
parent = self.parent
frame = Frame(self.note)
self.ext_defaultCfg = idleConf.defaultCfg['extensions']
self.ext_userCfg = idleConf.userCfg['extensions']
self.is_int = self.register(is_int)
self.load_extensions()
# Create widgets - a listbox shows all available extensions, with the
# controls for the extension selected in the listbox to the right.
self.extension_names = StringVar(self)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(2, weight=1)
self.extension_list = Listbox(frame, listvariable=self.extension_names,
selectmode='browse')
self.extension_list.bind('<<ListboxSelect>>', self.extension_selected)
scroll = Scrollbar(frame, command=self.extension_list.yview)
self.extension_list.yscrollcommand=scroll.set
self.details_frame = LabelFrame(frame, width=250, height=250)
self.extension_list.grid(column=0, row=0, sticky='nws')
scroll.grid(column=1, row=0, sticky='ns')
self.details_frame.grid(column=2, row=0, sticky='nsew', padx=[10, 0])
frame.configure(padding=10)
self.config_frame = {}
self.current_extension = None
self.outerframe = self # TEMPORARY
self.tabbed_page_set = self.extension_list # TEMPORARY
# Create the frame holding controls for each extension.
ext_names = ''
for ext_name in sorted(self.extensions):
self.create_extension_frame(ext_name)
ext_names = ext_names + '{' + ext_name + '} '
self.extension_names.set(ext_names)
self.extension_list.selection_set(0)
self.extension_selected(None)
return frame
def load_extensions(self):
"Fill self.extensions with data from the default and user configs."
self.extensions = {}
for ext_name in idleConf.GetExtensions(active_only=False):
# Former built-in extensions are already filtered out.
self.extensions[ext_name] = []
for ext_name in self.extensions:
opt_list = sorted(self.ext_defaultCfg.GetOptionList(ext_name))
# Bring 'enable' options to the beginning of the list.
enables = [opt_name for opt_name in opt_list
if opt_name.startswith('enable')]
for opt_name in enables:
opt_list.remove(opt_name)
opt_list = enables + opt_list
for opt_name in opt_list:
def_str = self.ext_defaultCfg.Get(
ext_name, opt_name, raw=True)
try:
def_obj = {'True':True, 'False':False}[def_str]
opt_type = 'bool'
except KeyError:
try:
def_obj = int(def_str)
opt_type = 'int'
except ValueError:
def_obj = def_str
opt_type = None
try:
value = self.ext_userCfg.Get(
ext_name, opt_name, type=opt_type, raw=True,
default=def_obj)
except ValueError: # Need this until .Get fixed.
value = def_obj # Bad values overwritten by entry.
var = StringVar(self)
var.set(str(value))
self.extensions[ext_name].append({'name': opt_name,
'type': opt_type,
'default': def_str,
'value': value,
'var': var,
})
def extension_selected(self, event):
"Handle selection of an extension from the list."
newsel = self.extension_list.curselection()
if newsel:
newsel = self.extension_list.get(newsel)
if newsel is None or newsel != self.current_extension:
if self.current_extension:
self.details_frame.config(text='')
self.config_frame[self.current_extension].grid_forget()
self.current_extension = None
if newsel:
self.details_frame.config(text=newsel)
self.config_frame[newsel].grid(column=0, row=0, sticky='nsew')
self.current_extension = newsel
def create_extension_frame(self, ext_name):
"""Create a frame holding the widgets to configure one extension"""
f = VerticalScrolledFrame(self.details_frame, height=250, width=250)
self.config_frame[ext_name] = f
entry_area = f.interior
# Create an entry for each configuration option.
for row, opt in enumerate(self.extensions[ext_name]):
# Create a row with a label and entry/checkbutton.
label = Label(entry_area, text=opt['name'])
label.grid(row=row, column=0, sticky=NW)
var = opt['var']
if opt['type'] == 'bool':
Checkbutton(entry_area, variable=var,
onvalue='True', offvalue='False', width=8
).grid(row=row, column=1, sticky=W, padx=7)
elif opt['type'] == 'int':
Entry(entry_area, textvariable=var, validate='key',
validatecommand=(self.is_int, '%P'), width=10
).grid(row=row, column=1, sticky=NSEW, padx=7)
else: # type == 'str'
# Limit size to fit non-expanding space with larger font.
Entry(entry_area, textvariable=var, width=15
).grid(row=row, column=1, sticky=NSEW, padx=7)
return
def set_extension_value(self, section, opt):
"""Return True if the configuration was added or changed.
If the value is the same as the default, then remove it
from user config file.
"""
name = opt['name']
default = opt['default']
value = opt['var'].get().strip() or default
opt['var'].set(value)
# if self.defaultCfg.has_section(section):
# Currently, always true; if not, indent to return.
if (value == default):
return self.ext_userCfg.RemoveOption(section, name)
# Set the option.
return self.ext_userCfg.SetOption(section, name, value)
def save_all_changed_extensions(self):
"""Save configuration changes to the user config file.
Attributes accessed:
extensions
Methods:
set_extension_value
"""
has_changes = False
for ext_name in self.extensions:
options = self.extensions[ext_name]
for opt in options:
if self.set_extension_value(ext_name, opt):
has_changes = True
if has_changes:
self.ext_userCfg.Save()
# class TabPage(Frame): # A template for Page classes.
# def __init__(self, master):
# super().__init__(master)
# self.create_page_tab()
# self.load_tab_cfg()
# def create_page_tab(self):
# # Define tk vars and register var and callback with tracers.
# # Create subframes and widgets.
# # Pack widgets.
# def load_tab_cfg(self):
# # Initialize widgets with data from idleConf.
# def var_changed_var_name():
# # For each tk var that needs other than default callback.
# def other_methods():
# # Define tab-specific behavior.
font_sample_text = (
'<ASCII/Latin1>\n'
'AaBbCcDdEeFfGgHhIiJj\n1234567890#:+=(){}[]\n'
'\u00a2\u00a3\u00a5\u00a7\u00a9\u00ab\u00ae\u00b6\u00bd\u011e'
'\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c7\u00d0\u00d8\u00df\n'
'\n<IPA,Greek,Cyrillic>\n'
'\u0250\u0255\u0258\u025e\u025f\u0264\u026b\u026e\u0270\u0277'
'\u027b\u0281\u0283\u0286\u028e\u029e\u02a2\u02ab\u02ad\u02af\n'
'\u0391\u03b1\u0392\u03b2\u0393\u03b3\u0394\u03b4\u0395\u03b5'
'\u0396\u03b6\u0397\u03b7\u0398\u03b8\u0399\u03b9\u039a\u03ba\n'
'\u0411\u0431\u0414\u0434\u0416\u0436\u041f\u043f\u0424\u0444'
'\u0427\u0447\u042a\u044a\u042d\u044d\u0460\u0464\u046c\u04dc\n'
'\n<Hebrew, Arabic>\n'
'\u05d0\u05d1\u05d2\u05d3\u05d4\u05d5\u05d6\u05d7\u05d8\u05d9'
'\u05da\u05db\u05dc\u05dd\u05de\u05df\u05e0\u05e1\u05e2\u05e3\n'
'\u0627\u0628\u062c\u062f\u0647\u0648\u0632\u062d\u0637\u064a'
'\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\n'
'\n<Devanagari, Tamil>\n'
'\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f'
'\u0905\u0906\u0907\u0908\u0909\u090a\u090f\u0910\u0913\u0914\n'
'\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef'
'\u0b85\u0b87\u0b89\u0b8e\n'
'\n<East Asian>\n'
'\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\n'
'\u6c49\u5b57\u6f22\u5b57\u4eba\u6728\u706b\u571f\u91d1\u6c34\n'
'\uac00\ub0d0\ub354\ub824\ubaa8\ubd64\uc218\uc720\uc988\uce58\n'
'\u3042\u3044\u3046\u3048\u304a\u30a2\u30a4\u30a6\u30a8\u30aa\n'
)
class FontPage(Frame):
def __init__(self, master, highpage):
super().__init__(master)
self.highlight_sample = highpage.highlight_sample
self.create_page_font_tab()
self.load_font_cfg()
self.load_tab_cfg()
def create_page_font_tab(self):
"""Return frame of widgets for Font/Tabs tab.
Fonts: Enable users to provisionally change font face, size, or
boldness and to see the consequence of proposed choices. Each
action set 3 options in changes structuree and changes the
corresponding aspect of the font sample on this page and
highlight sample on highlight page.
Function load_font_cfg initializes font vars and widgets from
idleConf entries and tk.
Fontlist: mouse button 1 click or up or down key invoke
on_fontlist_select(), which sets var font_name.
Sizelist: clicking the menubutton opens the dropdown menu. A
mouse button 1 click or return key sets var font_size.
Bold_toggle: clicking the box toggles var font_bold.
Changing any of the font vars invokes var_changed_font, which
adds all 3 font options to changes and calls set_samples.
Set_samples applies a new font constructed from the font vars to
font_sample and to highlight_sample on the highlight page.
Tabs: Enable users to change spaces entered for indent tabs.
Changing indent_scale value with the mouse sets Var space_num,
which invokes the default callback to add an entry to
changes. Load_tab_cfg initializes space_num to default.
Widgets for FontPage(Frame): (*) widgets bound to self
frame_font: LabelFrame
frame_font_name: Frame
font_name_title: Label
(*)fontlist: ListBox - font_name
scroll_font: Scrollbar
frame_font_param: Frame
font_size_title: Label
(*)sizelist: DynOptionMenu - font_size
(*)bold_toggle: Checkbutton - font_bold
frame_sample: LabelFrame
(*)font_sample: Label
frame_indent: LabelFrame
indent_title: Label
(*)indent_scale: Scale - space_num
"""
self.font_name = tracers.add(StringVar(self), self.var_changed_font)
self.font_size = tracers.add(StringVar(self), self.var_changed_font)
self.font_bold = tracers.add(BooleanVar(self), self.var_changed_font)
self.space_num = tracers.add(IntVar(self), ('main', 'Indent', 'num-spaces'))
# Define frames and widgets.
frame_font = LabelFrame(
self, borderwidth=2, relief=GROOVE, text=' Shell/Editor Font ')
frame_sample = LabelFrame(
self, borderwidth=2, relief=GROOVE,
text=' Font Sample (Editable) ')
frame_indent = LabelFrame(
self, borderwidth=2, relief=GROOVE, text=' Indentation Width ')
# frame_font.
frame_font_name = Frame(frame_font)
frame_font_param = Frame(frame_font)
font_name_title = Label(
frame_font_name, justify=LEFT, text='Font Face :')
self.fontlist = Listbox(frame_font_name, height=15,
takefocus=True, exportselection=FALSE)
self.fontlist.bind('<ButtonRelease-1>', self.on_fontlist_select)
self.fontlist.bind('<KeyRelease-Up>', self.on_fontlist_select)
self.fontlist.bind('<KeyRelease-Down>', self.on_fontlist_select)
scroll_font = Scrollbar(frame_font_name)
scroll_font.config(command=self.fontlist.yview)
self.fontlist.config(yscrollcommand=scroll_font.set)
font_size_title = Label(frame_font_param, text='Size :')
self.sizelist = DynOptionMenu(frame_font_param, self.font_size, None)
self.bold_toggle = Checkbutton(
frame_font_param, variable=self.font_bold,
onvalue=1, offvalue=0, text='Bold')
# frame_sample.
self.font_sample = Text(frame_sample, width=20, height=20)
self.font_sample.insert(END, font_sample_text)
# frame_indent.
indent_title = Label(
frame_indent, justify=LEFT,
text='Python Standard: 4 Spaces!')
self.indent_scale = Scale(
frame_indent, variable=self.space_num,
orient='horizontal', tickinterval=2, from_=2, to=16)
# Grid and pack widgets:
self.columnconfigure(1, weight=1)
frame_font.grid(row=0, column=0, padx=5, pady=5)
frame_sample.grid(row=0, column=1, rowspan=2, padx=5, pady=5,
sticky='nsew')
frame_indent.grid(row=1, column=0, padx=5, pady=5, sticky='ew')
# frame_font.
frame_font_name.pack(side=TOP, padx=5, pady=5, fill=X)
frame_font_param.pack(side=TOP, padx=5, pady=5, fill=X)
font_name_title.pack(side=TOP, anchor=W)
self.fontlist.pack(side=LEFT, expand=TRUE, fill=X)
scroll_font.pack(side=LEFT, fill=Y)
font_size_title.pack(side=LEFT, anchor=W)
self.sizelist.pack(side=LEFT, anchor=W)
self.bold_toggle.pack(side=LEFT, anchor=W, padx=20)
# frame_sample.
self.font_sample.pack(expand=TRUE, fill=BOTH)
# frame_indent.
indent_title.pack(side=TOP, anchor=W, padx=5)
self.indent_scale.pack(side=TOP, padx=5, fill=X)
def load_font_cfg(self):
"""Load current configuration settings for the font options.
Retrieve current font with idleConf.GetFont and font families
from tk. Setup fontlist and set font_name. Setup sizelist,
which sets font_size. Set font_bold. Call set_samples.
"""
configured_font = idleConf.GetFont(self, 'main', 'EditorWindow')
font_name = configured_font[0].lower()
font_size = configured_font[1]
font_bold = configured_font[2]=='bold'
# Set editor font selection list and font_name.
fonts = list(tkFont.families(self))
fonts.sort()
for font in fonts:
self.fontlist.insert(END, font)
self.font_name.set(font_name)
lc_fonts = [s.lower() for s in fonts]
try:
current_font_index = lc_fonts.index(font_name)
self.fontlist.see(current_font_index)
self.fontlist.select_set(current_font_index)
self.fontlist.select_anchor(current_font_index)
self.fontlist.activate(current_font_index)
except ValueError:
pass
# Set font size dropdown.
self.sizelist.SetMenu(('7', '8', '9', '10', '11', '12', '13', '14',
'16', '18', '20', '22', '25', '29', '34', '40'),
font_size)
# Set font weight.
self.font_bold.set(font_bold)
self.set_samples()
def var_changed_font(self, *params):
"""Store changes to font attributes.
When one font attribute changes, save them all, as they are
not independent from each other. In particular, when we are
overriding the default font, we need to write out everything.
"""
value = self.font_name.get()
changes.add_option('main', 'EditorWindow', 'font', value)
value = self.font_size.get()
changes.add_option('main', 'EditorWindow', 'font-size', value)
value = self.font_bold.get()
changes.add_option('main', 'EditorWindow', 'font-bold', value)
self.set_samples()
def on_fontlist_select(self, event):
"""Handle selecting a font from the list.
Event can result from either mouse click or Up or Down key.
Set font_name and example displays to selection.
"""
font = self.fontlist.get(
ACTIVE if event.type.name == 'KeyRelease' else ANCHOR)
self.font_name.set(font.lower())
def set_samples(self, event=None):
"""Update update both screen samples with the font settings.
Called on font initialization and change events.
Accesses font_name, font_size, and font_bold Variables.
Updates font_sample and highlight page highlight_sample.
"""
font_name = self.font_name.get()
font_weight = tkFont.BOLD if self.font_bold.get() else tkFont.NORMAL
new_font = (font_name, self.font_size.get(), font_weight)
self.font_sample['font'] = new_font
self.highlight_sample['font'] = new_font
def load_tab_cfg(self):
"""Load current configuration settings for the tab options.
Attributes updated:
space_num: Set to value from idleConf.
"""
# Set indent sizes.
space_num = idleConf.GetOption(
'main', 'Indent', 'num-spaces', default=4, type='int')
self.space_num.set(space_num)
def var_changed_space_num(self, *params):
"Store change to indentation size."
value = self.space_num.get()
changes.add_option('main', 'Indent', 'num-spaces', value)
class HighPage(Frame):
def __init__(self, master):
super().__init__(master)
self.cd = master.master
self.style = Style(master)
self.create_page_highlight()
self.load_theme_cfg()
def create_page_highlight(self):
"""Return frame of widgets for Highlighting tab.
Enable users to provisionally change foreground and background
colors applied to textual tags. Color mappings are stored in
complete listings called themes. Built-in themes in
idlelib/config-highlight.def are fixed as far as the dialog is
concerned. Any theme can be used as the base for a new custom
theme, stored in .idlerc/config-highlight.cfg.
Function load_theme_cfg() initializes tk variables and theme
lists and calls paint_theme_sample() and set_highlight_target()
for the current theme. Radiobuttons builtin_theme_on and
custom_theme_on toggle var theme_source, which controls if the
current set of colors are from a builtin or custom theme.
DynOptionMenus builtinlist and customlist contain lists of the
builtin and custom themes, respectively, and the current item
from each list is stored in vars builtin_name and custom_name.
Function paint_theme_sample() applies the colors from the theme
to the tags in text widget highlight_sample and then invokes
set_color_sample(). Function set_highlight_target() sets the state
of the radiobuttons fg_on and bg_on based on the tag and it also
invokes set_color_sample().
Function set_color_sample() sets the background color for the frame
holding the color selector. This provides a larger visual of the
color for the current tag and plane (foreground/background).
Note: set_color_sample() is called from many places and is often
called more than once when a change is made. It is invoked when
foreground or background is selected (radiobuttons), from
paint_theme_sample() (theme is changed or load_cfg is called), and
from set_highlight_target() (target tag is changed or load_cfg called).
Button delete_custom invokes delete_custom() to delete
a custom theme from idleConf.userCfg['highlight'] and changes.
Button save_custom invokes save_as_new_theme() which calls
get_new_theme_name() and create_new() to save a custom theme
and its colors to idleConf.userCfg['highlight'].
Radiobuttons fg_on and bg_on toggle var fg_bg_toggle to control
if the current selected color for a tag is for the foreground or
background.
DynOptionMenu targetlist contains a readable description of the
tags applied to Python source within IDLE. Selecting one of the
tags from this list populates highlight_target, which has a callback
function set_highlight_target().
Text widget highlight_sample displays a block of text (which is
mock Python code) in which is embedded the defined tags and reflects
the color attributes of the current theme and changes for those tags.
Mouse button 1 allows for selection of a tag and updates
highlight_target with that tag value.
Note: The font in highlight_sample is set through the config in
the fonts tab.
In other words, a tag can be selected either from targetlist or
by clicking on the sample text within highlight_sample. The
plane (foreground/background) is selected via the radiobutton.
Together, these two (tag and plane) control what color is
shown in set_color_sample() for the current theme. Button set_color
invokes get_color() which displays a ColorChooser to change the
color for the selected tag/plane. If a new color is picked,
it will be saved to changes and the highlight_sample and
frame background will be updated.
Tk Variables:
color: Color of selected target.
builtin_name: Menu variable for built-in theme.
custom_name: Menu variable for custom theme.
fg_bg_toggle: Toggle for foreground/background color.
Note: this has no callback.
theme_source: Selector for built-in or custom theme.
highlight_target: Menu variable for the highlight tag target.
Instance Data Attributes:
theme_elements: Dictionary of tags for text highlighting.
The key is the display name and the value is a tuple of
(tag name, display sort order).
Methods [attachment]:
load_theme_cfg: Load current highlight colors.
get_color: Invoke colorchooser [button_set_color].
set_color_sample_binding: Call set_color_sample [fg_bg_toggle].
set_highlight_target: set fg_bg_toggle, set_color_sample().
set_color_sample: Set frame background to target.
on_new_color_set: Set new color and add option.
paint_theme_sample: Recolor sample.
get_new_theme_name: Get from popup.
create_new: Combine theme with changes and save.
save_as_new_theme: Save [button_save_custom].
set_theme_type: Command for [theme_source].
delete_custom: Activate default [button_delete_custom].
save_new: Save to userCfg['theme'] (is function).
Widgets of highlights page frame: (*) widgets bound to self
frame_custom: LabelFrame
(*)highlight_sample: Text
(*)frame_color_set: Frame
(*)button_set_color: Button
(*)targetlist: DynOptionMenu - highlight_target
frame_fg_bg_toggle: Frame
(*)fg_on: Radiobutton - fg_bg_toggle
(*)bg_on: Radiobutton - fg_bg_toggle
(*)button_save_custom: Button
frame_theme: LabelFrame
theme_type_title: Label
(*)builtin_theme_on: Radiobutton - theme_source
(*)custom_theme_on: Radiobutton - theme_source
(*)builtinlist: DynOptionMenu - builtin_name
(*)customlist: DynOptionMenu - custom_name
(*)button_delete_custom: Button
(*)theme_message: Label
"""
self.theme_elements = {
'Normal Text': ('normal', '00'),
'Code Context': ('context', '01'),
'Python Keywords': ('keyword', '02'),
'Python Definitions': ('definition', '03'),
'Python Builtins': ('builtin', '04'),
'Python Comments': ('comment', '05'),
'Python Strings': ('string', '06'),
'Selected Text': ('hilite', '07'),
'Found Text': ('hit', '08'),
'Cursor': ('cursor', '09'),
'Editor Breakpoint': ('break', '10'),
'Shell Normal Text': ('console', '11'),
'Shell Error Text': ('error', '12'),
'Shell Stdout Text': ('stdout', '13'),
'Shell Stderr Text': ('stderr', '14'),
}
self.builtin_name = tracers.add(
StringVar(self), self.var_changed_builtin_name)
self.custom_name = tracers.add(
StringVar(self), self.var_changed_custom_name)
self.fg_bg_toggle = BooleanVar(self)
self.color = tracers.add(
StringVar(self), self.var_changed_color)
self.theme_source = tracers.add(
BooleanVar(self), self.var_changed_theme_source)
self.highlight_target = tracers.add(
StringVar(self), self.var_changed_highlight_target)
# Create widgets:
# body frame and section frames.
frame_custom = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Custom Highlighting ')
frame_theme = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Highlighting Theme ')
# frame_custom.
text = self.highlight_sample = Text(
frame_custom, relief=SOLID, borderwidth=1,
font=('courier', 12, ''), cursor='hand2', width=21, height=13,
takefocus=FALSE, highlightthickness=0, wrap=NONE)
text.bind('<Double-Button-1>', lambda e: 'break')
text.bind('<B1-Motion>', lambda e: 'break')
text_and_tags=(
('\n', 'normal'),
('#you can click here', 'comment'), ('\n', 'normal'),
('#to choose items', 'comment'), ('\n', 'normal'),
('code context section', 'context'), ('\n\n', 'normal'),
('def', 'keyword'), (' ', 'normal'),
('func', 'definition'), ('(param):\n ', 'normal'),
('"""string"""', 'string'), ('\n var0 = ', 'normal'),
("'string'", 'string'), ('\n var1 = ', 'normal'),
("'selected'", 'hilite'), ('\n var2 = ', 'normal'),
("'found'", 'hit'), ('\n var3 = ', 'normal'),
('list', 'builtin'), ('(', 'normal'),
('None', 'keyword'), (')\n', 'normal'),
(' breakpoint("line")', 'break'), ('\n\n', 'normal'),
(' error ', 'error'), (' ', 'normal'),
('cursor |', 'cursor'), ('\n ', 'normal'),
('shell', 'console'), (' ', 'normal'),
('stdout', 'stdout'), (' ', 'normal'),
('stderr', 'stderr'), ('\n\n', 'normal'))
for texttag in text_and_tags:
text.insert(END, texttag[0], texttag[1])
for element in self.theme_elements:
def tem(event, elem=element):
# event.widget.winfo_top_level().highlight_target.set(elem)
self.highlight_target.set(elem)
text.tag_bind(
self.theme_elements[element][0], '<ButtonPress-1>', tem)
text['state'] = 'disabled'
self.style.configure('frame_color_set.TFrame', borderwidth=1,
relief='solid')
self.frame_color_set = Frame(frame_custom, style='frame_color_set.TFrame')
frame_fg_bg_toggle = Frame(frame_custom)
self.button_set_color = Button(
self.frame_color_set, text='Choose Color for :',
command=self.get_color)
self.targetlist = DynOptionMenu(
self.frame_color_set, self.highlight_target, None,
highlightthickness=0) #, command=self.set_highlight_targetBinding
self.fg_on = Radiobutton(
frame_fg_bg_toggle, variable=self.fg_bg_toggle, value=1,
text='Foreground', command=self.set_color_sample_binding)
self.bg_on = Radiobutton(
frame_fg_bg_toggle, variable=self.fg_bg_toggle, value=0,
text='Background', command=self.set_color_sample_binding)
self.fg_bg_toggle.set(1)
self.button_save_custom = Button(
frame_custom, text='Save as New Custom Theme',
command=self.save_as_new_theme)
# frame_theme.
theme_type_title = Label(frame_theme, text='Select : ')
self.builtin_theme_on = Radiobutton(
frame_theme, variable=self.theme_source, value=1,
command=self.set_theme_type, text='a Built-in Theme')
self.custom_theme_on = Radiobutton(
frame_theme, variable=self.theme_source, value=0,
command=self.set_theme_type, text='a Custom Theme')
self.builtinlist = DynOptionMenu(
frame_theme, self.builtin_name, None, command=None)
self.customlist = DynOptionMenu(
frame_theme, self.custom_name, None, command=None)
self.button_delete_custom = Button(
frame_theme, text='Delete Custom Theme',
command=self.delete_custom)
self.theme_message = Label(frame_theme, borderwidth=2)
# Pack widgets:
# body.
frame_custom.pack(side=LEFT, padx=5, pady=5, expand=TRUE, fill=BOTH)
frame_theme.pack(side=TOP, padx=5, pady=5, fill=X)
# frame_custom.
self.frame_color_set.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=X)
frame_fg_bg_toggle.pack(side=TOP, padx=5, pady=0)
self.highlight_sample.pack(
side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
self.button_set_color.pack(side=TOP, expand=TRUE, fill=X, padx=8, pady=4)
self.targetlist.pack(side=TOP, expand=TRUE, fill=X, padx=8, pady=3)
self.fg_on.pack(side=LEFT, anchor=E)
self.bg_on.pack(side=RIGHT, anchor=W)
self.button_save_custom.pack(side=BOTTOM, fill=X, padx=5, pady=5)
# frame_theme.
theme_type_title.pack(side=TOP, anchor=W, padx=5, pady=5)
self.builtin_theme_on.pack(side=TOP, anchor=W, padx=5)
self.custom_theme_on.pack(side=TOP, anchor=W, padx=5, pady=2)
self.builtinlist.pack(side=TOP, fill=X, padx=5, pady=5)
self.customlist.pack(side=TOP, fill=X, anchor=W, padx=5, pady=5)
self.button_delete_custom.pack(side=TOP, fill=X, padx=5, pady=5)
self.theme_message.pack(side=TOP, fill=X, pady=5)
def load_theme_cfg(self):
"""Load current configuration settings for the theme options.
Based on the theme_source toggle, the theme is set as
either builtin or custom and the initial widget values
reflect the current settings from idleConf.
Attributes updated:
theme_source: Set from idleConf.
builtinlist: List of default themes from idleConf.
customlist: List of custom themes from idleConf.
custom_theme_on: Disabled if there are no custom themes.
custom_theme: Message with additional information.
targetlist: Create menu from self.theme_elements.
Methods:
set_theme_type
paint_theme_sample
set_highlight_target
"""
# Set current theme type radiobutton.
self.theme_source.set(idleConf.GetOption(
'main', 'Theme', 'default', type='bool', default=1))
# Set current theme.
current_option = idleConf.CurrentTheme()
# Load available theme option menus.
if self.theme_source.get(): # Default theme selected.
item_list = idleConf.GetSectionList('default', 'highlight')
item_list.sort()
self.builtinlist.SetMenu(item_list, current_option)
item_list = idleConf.GetSectionList('user', 'highlight')
item_list.sort()
if not item_list:
self.custom_theme_on.state(('disabled',))
self.custom_name.set('- no custom themes -')
else:
self.customlist.SetMenu(item_list, item_list[0])
else: # User theme selected.
item_list = idleConf.GetSectionList('user', 'highlight')
item_list.sort()
self.customlist.SetMenu(item_list, current_option)
item_list = idleConf.GetSectionList('default', 'highlight')
item_list.sort()
self.builtinlist.SetMenu(item_list, item_list[0])
self.set_theme_type()
# Load theme element option menu.
theme_names = list(self.theme_elements.keys())
theme_names.sort(key=lambda x: self.theme_elements[x][1])
self.targetlist.SetMenu(theme_names, theme_names[0])
self.paint_theme_sample()
self.set_highlight_target()
def var_changed_builtin_name(self, *params):
"""Process new builtin theme selection.
Add the changed theme's name to the changed_items and recreate
the sample with the values from the selected theme.
"""
old_themes = ('IDLE Classic', 'IDLE New')
value = self.builtin_name.get()
if value not in old_themes:
if idleConf.GetOption('main', 'Theme', 'name') not in old_themes:
changes.add_option('main', 'Theme', 'name', old_themes[0])
changes.add_option('main', 'Theme', 'name2', value)
self.theme_message['text'] = 'New theme, see Help'
else:
changes.add_option('main', 'Theme', 'name', value)
changes.add_option('main', 'Theme', 'name2', '')
self.theme_message['text'] = ''
self.paint_theme_sample()
def var_changed_custom_name(self, *params):
"""Process new custom theme selection.
If a new custom theme is selected, add the name to the
changed_items and apply the theme to the sample.
"""
value = self.custom_name.get()
if value != '- no custom themes -':
changes.add_option('main', 'Theme', 'name', value)
self.paint_theme_sample()
def var_changed_theme_source(self, *params):
"""Process toggle between builtin and custom theme.
Update the default toggle value and apply the newly
selected theme type.
"""
value = self.theme_source.get()
changes.add_option('main', 'Theme', 'default', value)
if value:
self.var_changed_builtin_name()
else:
self.var_changed_custom_name()
def var_changed_color(self, *params):
"Process change to color choice."
self.on_new_color_set()
def var_changed_highlight_target(self, *params):
"Process selection of new target tag for highlighting."
self.set_highlight_target()
def set_theme_type(self):
"""Set available screen options based on builtin or custom theme.
Attributes accessed:
theme_source
Attributes updated:
builtinlist
customlist
button_delete_custom
custom_theme_on
Called from:
handler for builtin_theme_on and custom_theme_on
delete_custom
create_new
load_theme_cfg
"""
if self.theme_source.get():
self.builtinlist['state'] = 'normal'
self.customlist['state'] = 'disabled'
self.button_delete_custom.state(('disabled',))
else:
self.builtinlist['state'] = 'disabled'
self.custom_theme_on.state(('!disabled',))
self.customlist['state'] = 'normal'
self.button_delete_custom.state(('!disabled',))
def get_color(self):
"""Handle button to select a new color for the target tag.
If a new color is selected while using a builtin theme, a
name must be supplied to create a custom theme.
Attributes accessed:
highlight_target
frame_color_set
theme_source
Attributes updated:
color
Methods:
get_new_theme_name
create_new
"""
target = self.highlight_target.get()
prev_color = self.style.lookup(self.frame_color_set['style'],
'background')
rgbTuplet, color_string = tkColorChooser.askcolor(
parent=self, title='Pick new color for : '+target,
initialcolor=prev_color)
if color_string and (color_string != prev_color):
# User didn't cancel and they chose a new color.
if self.theme_source.get(): # Current theme is a built-in.
message = ('Your changes will be saved as a new Custom Theme. '
'Enter a name for your new Custom Theme below.')
new_theme = self.get_new_theme_name(message)
if not new_theme: # User cancelled custom theme creation.
return
else: # Create new custom theme based on previously active theme.
self.create_new(new_theme)
self.color.set(color_string)
else: # Current theme is user defined.
self.color.set(color_string)
def on_new_color_set(self):
"Display sample of new color selection on the dialog."
new_color = self.color.get()
self.style.configure('frame_color_set.TFrame', background=new_color)
plane = 'foreground' if self.fg_bg_toggle.get() else 'background'
sample_element = self.theme_elements[self.highlight_target.get()][0]
self.highlight_sample.tag_config(sample_element, **{plane: new_color})
theme = self.custom_name.get()
theme_element = sample_element + '-' + plane
changes.add_option('highlight', theme, theme_element, new_color)
def get_new_theme_name(self, message):
"Return name of new theme from query popup."
used_names = (idleConf.GetSectionList('user', 'highlight') +
idleConf.GetSectionList('default', 'highlight'))
new_theme = SectionName(
self, 'New Custom Theme', message, used_names).result
return new_theme
def save_as_new_theme(self):
"""Prompt for new theme name and create the theme.
Methods:
get_new_theme_name
create_new
"""
new_theme_name = self.get_new_theme_name('New Theme Name:')
if new_theme_name:
self.create_new(new_theme_name)
def create_new(self, new_theme_name):
"""Create a new custom theme with the given name.
Create the new theme based on the previously active theme
with the current changes applied. Once it is saved, then
activate the new theme.
Attributes accessed:
builtin_name
custom_name
Attributes updated:
customlist
theme_source
Method:
save_new
set_theme_type
"""
if self.theme_source.get():
theme_type = 'default'
theme_name = self.builtin_name.get()
else:
theme_type = 'user'
theme_name = self.custom_name.get()
new_theme = idleConf.GetThemeDict(theme_type, theme_name)
# Apply any of the old theme's unsaved changes to the new theme.
if theme_name in changes['highlight']:
theme_changes = changes['highlight'][theme_name]
for element in theme_changes:
new_theme[element] = theme_changes[element]
# Save the new theme.
self.save_new(new_theme_name, new_theme)
# Change GUI over to the new theme.
custom_theme_list = idleConf.GetSectionList('user', 'highlight')
custom_theme_list.sort()
self.customlist.SetMenu(custom_theme_list, new_theme_name)
self.theme_source.set(0)
self.set_theme_type()
def set_highlight_target(self):
"""Set fg/bg toggle and color based on highlight tag target.
Instance variables accessed:
highlight_target
Attributes updated:
fg_on
bg_on
fg_bg_toggle
Methods:
set_color_sample
Called from:
var_changed_highlight_target
load_theme_cfg
"""
if self.highlight_target.get() == 'Cursor': # bg not possible
self.fg_on.state(('disabled',))
self.bg_on.state(('disabled',))
self.fg_bg_toggle.set(1)
else: # Both fg and bg can be set.
self.fg_on.state(('!disabled',))
self.bg_on.state(('!disabled',))
self.fg_bg_toggle.set(1)
self.set_color_sample()
def set_color_sample_binding(self, *args):
"""Change color sample based on foreground/background toggle.
Methods:
set_color_sample
"""
self.set_color_sample()
def set_color_sample(self):
"""Set the color of the frame background to reflect the selected target.
Instance variables accessed:
theme_elements
highlight_target
fg_bg_toggle
highlight_sample
Attributes updated:
frame_color_set
"""
# Set the color sample area.
tag = self.theme_elements[self.highlight_target.get()][0]
plane = 'foreground' if self.fg_bg_toggle.get() else 'background'
color = self.highlight_sample.tag_cget(tag, plane)
self.style.configure('frame_color_set.TFrame', background=color)
def paint_theme_sample(self):
"""Apply the theme colors to each element tag in the sample text.
Instance attributes accessed:
theme_elements
theme_source
builtin_name
custom_name
Attributes updated:
highlight_sample: Set the tag elements to the theme.
Methods:
set_color_sample
Called from:
var_changed_builtin_name
var_changed_custom_name
load_theme_cfg
"""
if self.theme_source.get(): # Default theme
theme = self.builtin_name.get()
else: # User theme
theme = self.custom_name.get()
for element_title in self.theme_elements:
element = self.theme_elements[element_title][0]
colors = idleConf.GetHighlight(theme, element)
if element == 'cursor': # Cursor sample needs special painting.
colors['background'] = idleConf.GetHighlight(
theme, 'normal', fgBg='bg')
# Handle any unsaved changes to this theme.
if theme in changes['highlight']:
theme_dict = changes['highlight'][theme]
if element + '-foreground' in theme_dict:
colors['foreground'] = theme_dict[element + '-foreground']
if element + '-background' in theme_dict:
colors['background'] = theme_dict[element + '-background']
self.highlight_sample.tag_config(element, **colors)
self.set_color_sample()
def save_new(self, theme_name, theme):
"""Save a newly created theme to idleConf.
theme_name - string, the name of the new theme
theme - dictionary containing the new theme
"""
if not idleConf.userCfg['highlight'].has_section(theme_name):
idleConf.userCfg['highlight'].add_section(theme_name)
for element in theme:
value = theme[element]
idleConf.userCfg['highlight'].SetOption(theme_name, element, value)
def askyesno(self, *args, **kwargs):
# Make testing easier. Could change implementation.
return messagebox.askyesno(*args, **kwargs)
def delete_custom(self):
"""Handle event to delete custom theme.
The current theme is deactivated and the default theme is
activated. The custom theme is permanently removed from
the config file.
Attributes accessed:
custom_name
Attributes updated:
custom_theme_on
customlist
theme_source
builtin_name
Methods:
deactivate_current_config
save_all_changed_extensions
activate_config_changes
set_theme_type
"""
theme_name = self.custom_name.get()
delmsg = 'Are you sure you wish to delete the theme %r ?'
if not self.askyesno(
'Delete Theme', delmsg % theme_name, parent=self):
return
self.cd.deactivate_current_config()
# Remove theme from changes, config, and file.
changes.delete_section('highlight', theme_name)
# Reload user theme list.
item_list = idleConf.GetSectionList('user', 'highlight')
item_list.sort()
if not item_list:
self.custom_theme_on.state(('disabled',))
self.customlist.SetMenu(item_list, '- no custom themes -')
else:
self.customlist.SetMenu(item_list, item_list[0])
# Revert to default theme.
self.theme_source.set(idleConf.defaultCfg['main'].Get('Theme', 'default'))
self.builtin_name.set(idleConf.defaultCfg['main'].Get('Theme', 'name'))
# User can't back out of these changes, they must be applied now.
changes.save_all()
self.cd.save_all_changed_extensions()
self.cd.activate_config_changes()
self.set_theme_type()
class KeysPage(Frame):
def __init__(self, master):
super().__init__(master)
self.cd = master.master
self.create_page_keys()
self.load_key_cfg()
def create_page_keys(self):
"""Return frame of widgets for Keys tab.
Enable users to provisionally change both individual and sets of
keybindings (shortcut keys). Except for features implemented as
extensions, keybindings are stored in complete sets called
keysets. Built-in keysets in idlelib/config-keys.def are fixed
as far as the dialog is concerned. Any keyset can be used as the
base for a new custom keyset, stored in .idlerc/config-keys.cfg.
Function load_key_cfg() initializes tk variables and keyset
lists and calls load_keys_list for the current keyset.
Radiobuttons builtin_keyset_on and custom_keyset_on toggle var
keyset_source, which controls if the current set of keybindings
are from a builtin or custom keyset. DynOptionMenus builtinlist
and customlist contain lists of the builtin and custom keysets,
respectively, and the current item from each list is stored in
vars builtin_name and custom_name.
Button delete_custom_keys invokes delete_custom_keys() to delete
a custom keyset from idleConf.userCfg['keys'] and changes. Button
save_custom_keys invokes save_as_new_key_set() which calls
get_new_keys_name() and create_new_key_set() to save a custom keyset
and its keybindings to idleConf.userCfg['keys'].
Listbox bindingslist contains all of the keybindings for the
selected keyset. The keybindings are loaded in load_keys_list()
and are pairs of (event, [keys]) where keys can be a list
of one or more key combinations to bind to the same event.
Mouse button 1 click invokes on_bindingslist_select(), which
allows button_new_keys to be clicked.
So, an item is selected in listbindings, which activates
button_new_keys, and clicking button_new_keys calls function
get_new_keys(). Function get_new_keys() gets the key mappings from the
current keyset for the binding event item that was selected. The
function then displays another dialog, GetKeysDialog, with the
selected binding event and current keys and allows new key sequences
to be entered for that binding event. If the keys aren't
changed, nothing happens. If the keys are changed and the keyset
is a builtin, function get_new_keys_name() will be called
for input of a custom keyset name. If no name is given, then the
change to the keybinding will abort and no updates will be made. If
a custom name is entered in the prompt or if the current keyset was
already custom (and thus didn't require a prompt), then
idleConf.userCfg['keys'] is updated in function create_new_key_set()
with the change to the event binding. The item listing in bindingslist
is updated with the new keys. Var keybinding is also set which invokes
the callback function, var_changed_keybinding, to add the change to
the 'keys' or 'extensions' changes tracker based on the binding type.
Tk Variables:
keybinding: Action/key bindings.
Methods:
load_keys_list: Reload active set.
create_new_key_set: Combine active keyset and changes.
set_keys_type: Command for keyset_source.
save_new_key_set: Save to idleConf.userCfg['keys'] (is function).
deactivate_current_config: Remove keys bindings in editors.
Widgets for KeysPage(frame): (*) widgets bound to self
frame_key_sets: LabelFrame
frames[0]: Frame
(*)builtin_keyset_on: Radiobutton - var keyset_source
(*)custom_keyset_on: Radiobutton - var keyset_source
(*)builtinlist: DynOptionMenu - var builtin_name,
func keybinding_selected
(*)customlist: DynOptionMenu - var custom_name,
func keybinding_selected
(*)keys_message: Label
frames[1]: Frame
(*)button_delete_custom_keys: Button - delete_custom_keys
(*)button_save_custom_keys: Button - save_as_new_key_set
frame_custom: LabelFrame
frame_target: Frame
target_title: Label
scroll_target_y: Scrollbar
scroll_target_x: Scrollbar
(*)bindingslist: ListBox - on_bindingslist_select
(*)button_new_keys: Button - get_new_keys & ..._name
"""
self.builtin_name = tracers.add(
StringVar(self), self.var_changed_builtin_name)
self.custom_name = tracers.add(
StringVar(self), self.var_changed_custom_name)
self.keyset_source = tracers.add(
BooleanVar(self), self.var_changed_keyset_source)
self.keybinding = tracers.add(
StringVar(self), self.var_changed_keybinding)
# Create widgets:
# body and section frames.
frame_custom = LabelFrame(
self, borderwidth=2, relief=GROOVE,
text=' Custom Key Bindings ')
frame_key_sets = LabelFrame(
self, borderwidth=2, relief=GROOVE, text=' Key Set ')
# frame_custom.
frame_target = Frame(frame_custom)
target_title = Label(frame_target, text='Action - Key(s)')
scroll_target_y = Scrollbar(frame_target)
scroll_target_x = Scrollbar(frame_target, orient=HORIZONTAL)
self.bindingslist = Listbox(
frame_target, takefocus=FALSE, exportselection=FALSE)
self.bindingslist.bind('<ButtonRelease-1>',
self.on_bindingslist_select)
scroll_target_y['command'] = self.bindingslist.yview
scroll_target_x['command'] = self.bindingslist.xview
self.bindingslist['yscrollcommand'] = scroll_target_y.set
self.bindingslist['xscrollcommand'] = scroll_target_x.set
self.button_new_keys = Button(
frame_custom, text='Get New Keys for Selection',
command=self.get_new_keys, state='disabled')
# frame_key_sets.
frames = [Frame(frame_key_sets, padding=2, borderwidth=0)
for i in range(2)]
self.builtin_keyset_on = Radiobutton(
frames[0], variable=self.keyset_source, value=1,
command=self.set_keys_type, text='Use a Built-in Key Set')
self.custom_keyset_on = Radiobutton(
frames[0], variable=self.keyset_source, value=0,
command=self.set_keys_type, text='Use a Custom Key Set')
self.builtinlist = DynOptionMenu(
frames[0], self.builtin_name, None, command=None)
self.customlist = DynOptionMenu(
frames[0], self.custom_name, None, command=None)
self.button_delete_custom_keys = Button(
frames[1], text='Delete Custom Key Set',
command=self.delete_custom_keys)
self.button_save_custom_keys = Button(
frames[1], text='Save as New Custom Key Set',
command=self.save_as_new_key_set)
self.keys_message = Label(frames[0], borderwidth=2)
# Pack widgets:
# body.
frame_custom.pack(side=BOTTOM, padx=5, pady=5, expand=TRUE, fill=BOTH)
frame_key_sets.pack(side=BOTTOM, padx=5, pady=5, fill=BOTH)
# frame_custom.
self.button_new_keys.pack(side=BOTTOM, fill=X, padx=5, pady=5)
frame_target.pack(side=LEFT, padx=5, pady=5, expand=TRUE, fill=BOTH)
# frame_target.
frame_target.columnconfigure(0, weight=1)
frame_target.rowconfigure(1, weight=1)
target_title.grid(row=0, column=0, columnspan=2, sticky=W)
self.bindingslist.grid(row=1, column=0, sticky=NSEW)
scroll_target_y.grid(row=1, column=1, sticky=NS)
scroll_target_x.grid(row=2, column=0, sticky=EW)
# frame_key_sets.
self.builtin_keyset_on.grid(row=0, column=0, sticky=W+NS)
self.custom_keyset_on.grid(row=1, column=0, sticky=W+NS)
self.builtinlist.grid(row=0, column=1, sticky=NSEW)
self.customlist.grid(row=1, column=1, sticky=NSEW)
self.keys_message.grid(row=0, column=2, sticky=NSEW, padx=5, pady=5)
self.button_delete_custom_keys.pack(side=LEFT, fill=X, expand=True, padx=2)
self.button_save_custom_keys.pack(side=LEFT, fill=X, expand=True, padx=2)
frames[0].pack(side=TOP, fill=BOTH, expand=True)
frames[1].pack(side=TOP, fill=X, expand=True, pady=2)
def load_key_cfg(self):
"Load current configuration settings for the keybinding options."
# Set current keys type radiobutton.
self.keyset_source.set(idleConf.GetOption(
'main', 'Keys', 'default', type='bool', default=1))
# Set current keys.
current_option = idleConf.CurrentKeys()
# Load available keyset option menus.
if self.keyset_source.get(): # Default theme selected.
item_list = idleConf.GetSectionList('default', 'keys')
item_list.sort()
self.builtinlist.SetMenu(item_list, current_option)
item_list = idleConf.GetSectionList('user', 'keys')
item_list.sort()
if not item_list:
self.custom_keyset_on.state(('disabled',))
self.custom_name.set('- no custom keys -')
else:
self.customlist.SetMenu(item_list, item_list[0])
else: # User key set selected.
item_list = idleConf.GetSectionList('user', 'keys')
item_list.sort()
self.customlist.SetMenu(item_list, current_option)
item_list = idleConf.GetSectionList('default', 'keys')
item_list.sort()
self.builtinlist.SetMenu(item_list, idleConf.default_keys())
self.set_keys_type()
# Load keyset element list.
keyset_name = idleConf.CurrentKeys()
self.load_keys_list(keyset_name)
def var_changed_builtin_name(self, *params):
"Process selection of builtin key set."
old_keys = (
'IDLE Classic Windows',
'IDLE Classic Unix',
'IDLE Classic Mac',
'IDLE Classic OSX',
)
value = self.builtin_name.get()
if value not in old_keys:
if idleConf.GetOption('main', 'Keys', 'name') not in old_keys:
changes.add_option('main', 'Keys', 'name', old_keys[0])
changes.add_option('main', 'Keys', 'name2', value)
self.keys_message['text'] = 'New key set, see Help'
else:
changes.add_option('main', 'Keys', 'name', value)
changes.add_option('main', 'Keys', 'name2', '')
self.keys_message['text'] = ''
self.load_keys_list(value)
def var_changed_custom_name(self, *params):
"Process selection of custom key set."
value = self.custom_name.get()
if value != '- no custom keys -':
changes.add_option('main', 'Keys', 'name', value)
self.load_keys_list(value)
def var_changed_keyset_source(self, *params):
"Process toggle between builtin key set and custom key set."
value = self.keyset_source.get()
changes.add_option('main', 'Keys', 'default', value)
if value:
self.var_changed_builtin_name()
else:
self.var_changed_custom_name()
def var_changed_keybinding(self, *params):
"Store change to a keybinding."
value = self.keybinding.get()
key_set = self.custom_name.get()
event = self.bindingslist.get(ANCHOR).split()[0]
if idleConf.IsCoreBinding(event):
changes.add_option('keys', key_set, event, value)
else: # Event is an extension binding.
ext_name = idleConf.GetExtnNameForEvent(event)
ext_keybind_section = ext_name + '_cfgBindings'
changes.add_option('extensions', ext_keybind_section, event, value)
def set_keys_type(self):
"Set available screen options based on builtin or custom key set."
if self.keyset_source.get():
self.builtinlist['state'] = 'normal'
self.customlist['state'] = 'disabled'
self.button_delete_custom_keys.state(('disabled',))
else:
self.builtinlist['state'] = 'disabled'
self.custom_keyset_on.state(('!disabled',))
self.customlist['state'] = 'normal'
self.button_delete_custom_keys.state(('!disabled',))
def get_new_keys(self):
"""Handle event to change key binding for selected line.
A selection of a key/binding in the list of current
bindings pops up a dialog to enter a new binding. If
the current key set is builtin and a binding has
changed, then a name for a custom key set needs to be
entered for the change to be applied.
"""
list_index = self.bindingslist.index(ANCHOR)
binding = self.bindingslist.get(list_index)
bind_name = binding.split()[0]
if self.keyset_source.get():
current_key_set_name = self.builtin_name.get()
else:
current_key_set_name = self.custom_name.get()
current_bindings = idleConf.GetCurrentKeySet()
if current_key_set_name in changes['keys']: # unsaved changes
key_set_changes = changes['keys'][current_key_set_name]
for event in key_set_changes:
current_bindings[event] = key_set_changes[event].split()
current_key_sequences = list(current_bindings.values())
new_keys = GetKeysDialog(self, 'Get New Keys', bind_name,
current_key_sequences).result
if new_keys:
if self.keyset_source.get(): # Current key set is a built-in.
message = ('Your changes will be saved as a new Custom Key Set.'
' Enter a name for your new Custom Key Set below.')
new_keyset = self.get_new_keys_name(message)
if not new_keyset: # User cancelled custom key set creation.
self.bindingslist.select_set(list_index)
self.bindingslist.select_anchor(list_index)
return
else: # Create new custom key set based on previously active key set.
self.create_new_key_set(new_keyset)
self.bindingslist.delete(list_index)
self.bindingslist.insert(list_index, bind_name+' - '+new_keys)
self.bindingslist.select_set(list_index)
self.bindingslist.select_anchor(list_index)
self.keybinding.set(new_keys)
else:
self.bindingslist.select_set(list_index)
self.bindingslist.select_anchor(list_index)
def get_new_keys_name(self, message):
"Return new key set name from query popup."
used_names = (idleConf.GetSectionList('user', 'keys') +
idleConf.GetSectionList('default', 'keys'))
new_keyset = SectionName(
self, 'New Custom Key Set', message, used_names).result
return new_keyset
def save_as_new_key_set(self):
"Prompt for name of new key set and save changes using that name."
new_keys_name = self.get_new_keys_name('New Key Set Name:')
if new_keys_name:
self.create_new_key_set(new_keys_name)
def on_bindingslist_select(self, event):
"Activate button to assign new keys to selected action."
self.button_new_keys.state(('!disabled',))
def create_new_key_set(self, new_key_set_name):
"""Create a new custom key set with the given name.
Copy the bindings/keys from the previously active keyset
to the new keyset and activate the new custom keyset.
"""
if self.keyset_source.get():
prev_key_set_name = self.builtin_name.get()
else:
prev_key_set_name = self.custom_name.get()
prev_keys = idleConf.GetCoreKeys(prev_key_set_name)
new_keys = {}
for event in prev_keys: # Add key set to changed items.
event_name = event[2:-2] # Trim off the angle brackets.
binding = ' '.join(prev_keys[event])
new_keys[event_name] = binding
# Handle any unsaved changes to prev key set.
if prev_key_set_name in changes['keys']:
key_set_changes = changes['keys'][prev_key_set_name]
for event in key_set_changes:
new_keys[event] = key_set_changes[event]
# Save the new key set.
self.save_new_key_set(new_key_set_name, new_keys)
# Change GUI over to the new key set.
custom_key_list = idleConf.GetSectionList('user', 'keys')
custom_key_list.sort()
self.customlist.SetMenu(custom_key_list, new_key_set_name)
self.keyset_source.set(0)
self.set_keys_type()
def load_keys_list(self, keyset_name):
"""Reload the list of action/key binding pairs for the active key set.
An action/key binding can be selected to change the key binding.
"""
reselect = False
if self.bindingslist.curselection():
reselect = True
list_index = self.bindingslist.index(ANCHOR)
keyset = idleConf.GetKeySet(keyset_name)
bind_names = list(keyset.keys())
bind_names.sort()
self.bindingslist.delete(0, END)
for bind_name in bind_names:
key = ' '.join(keyset[bind_name])
bind_name = bind_name[2:-2] # Trim off the angle brackets.
if keyset_name in changes['keys']:
# Handle any unsaved changes to this key set.
if bind_name in changes['keys'][keyset_name]:
key = changes['keys'][keyset_name][bind_name]
self.bindingslist.insert(END, bind_name+' - '+key)
if reselect:
self.bindingslist.see(list_index)
self.bindingslist.select_set(list_index)
self.bindingslist.select_anchor(list_index)
@staticmethod
def save_new_key_set(keyset_name, keyset):
"""Save a newly created core key set.
Add keyset to idleConf.userCfg['keys'], not to disk.
If the keyset doesn't exist, it is created. The
binding/keys are taken from the keyset argument.
keyset_name - string, the name of the new key set
keyset - dictionary containing the new keybindings
"""
if not idleConf.userCfg['keys'].has_section(keyset_name):
idleConf.userCfg['keys'].add_section(keyset_name)
for event in keyset:
value = keyset[event]
idleConf.userCfg['keys'].SetOption(keyset_name, event, value)
def askyesno(self, *args, **kwargs):
# Make testing easier. Could change implementation.
return messagebox.askyesno(*args, **kwargs)
def delete_custom_keys(self):
"""Handle event to delete a custom key set.
Applying the delete deactivates the current configuration and
reverts to the default. The custom key set is permanently
deleted from the config file.
"""
keyset_name = self.custom_name.get()
delmsg = 'Are you sure you wish to delete the key set %r ?'
if not self.askyesno(
'Delete Key Set', delmsg % keyset_name, parent=self):
return
self.cd.deactivate_current_config()
# Remove key set from changes, config, and file.
changes.delete_section('keys', keyset_name)
# Reload user key set list.
item_list = idleConf.GetSectionList('user', 'keys')
item_list.sort()
if not item_list:
self.custom_keyset_on.state(('disabled',))
self.customlist.SetMenu(item_list, '- no custom keys -')
else:
self.customlist.SetMenu(item_list, item_list[0])
# Revert to default key set.
self.keyset_source.set(idleConf.defaultCfg['main']
.Get('Keys', 'default'))
self.builtin_name.set(idleConf.defaultCfg['main'].Get('Keys', 'name')
or idleConf.default_keys())
# User can't back out of these changes, they must be applied now.
changes.save_all()
self.cd.save_all_changed_extensions()
self.cd.activate_config_changes()
self.set_keys_type()
class GenPage(Frame):
def __init__(self, master):
super().__init__(master)
self.create_page_general()
self.load_general_cfg()
def create_page_general(self):
"""Return frame of widgets for General tab.
Enable users to provisionally change general options. Function
load_general_cfg intializes tk variables and helplist using
idleConf. Radiobuttons startup_shell_on and startup_editor_on
set var startup_edit. Radiobuttons save_ask_on and save_auto_on
set var autosave. Entry boxes win_width_int and win_height_int
set var win_width and win_height. Setting var_name invokes the
default callback that adds option to changes.
Helplist: load_general_cfg loads list user_helplist with
name, position pairs and copies names to listbox helplist.
Clicking a name invokes help_source selected. Clicking
button_helplist_name invokes helplist_item_name, which also
changes user_helplist. These functions all call
set_add_delete_state. All but load call update_help_changes to
rewrite changes['main']['HelpFiles'].
Widgets for GenPage(Frame): (*) widgets bound to self
frame_window: LabelFrame
frame_run: Frame
startup_title: Label
(*)startup_editor_on: Radiobutton - startup_edit
(*)startup_shell_on: Radiobutton - startup_edit
frame_win_size: Frame
win_size_title: Label
win_width_title: Label
(*)win_width_int: Entry - win_width
win_height_title: Label
(*)win_height_int: Entry - win_height
frame_autocomplete: Frame
auto_wait_title: Label
(*)auto_wait_int: Entry - autocomplete_wait
frame_paren1: Frame
paren_style_title: Label
(*)paren_style_type: OptionMenu - paren_style
frame_paren2: Frame
paren_time_title: Label
(*)paren_flash_time: Entry - flash_delay
(*)bell_on: Checkbutton - paren_bell
frame_editor: LabelFrame
frame_save: Frame
run_save_title: Label
(*)save_ask_on: Radiobutton - autosave
(*)save_auto_on: Radiobutton - autosave
frame_format: Frame
format_width_title: Label
(*)format_width_int: Entry - format_width
frame_context: Frame
context_title: Label
(*)context_int: Entry - context_lines
frame_shell: LabelFrame
frame_auto_squeeze_min_lines: Frame
auto_squeeze_min_lines_title: Label
(*)auto_squeeze_min_lines_int: Entry - auto_squeeze_min_lines
frame_help: LabelFrame
frame_helplist: Frame
frame_helplist_buttons: Frame
(*)button_helplist_edit
(*)button_helplist_add
(*)button_helplist_remove
(*)helplist: ListBox
scroll_helplist: Scrollbar
"""
# Integer values need StringVar because int('') raises.
self.startup_edit = tracers.add(
IntVar(self), ('main', 'General', 'editor-on-startup'))
self.win_width = tracers.add(
StringVar(self), ('main', 'EditorWindow', 'width'))
self.win_height = tracers.add(
StringVar(self), ('main', 'EditorWindow', 'height'))
self.autocomplete_wait = tracers.add(
StringVar(self), ('extensions', 'AutoComplete', 'popupwait'))
self.paren_style = tracers.add(
StringVar(self), ('extensions', 'ParenMatch', 'style'))
self.flash_delay = tracers.add(
StringVar(self), ('extensions', 'ParenMatch', 'flash-delay'))
self.paren_bell = tracers.add(
BooleanVar(self), ('extensions', 'ParenMatch', 'bell'))
self.auto_squeeze_min_lines = tracers.add(
StringVar(self), ('main', 'PyShell', 'auto-squeeze-min-lines'))
self.autosave = tracers.add(
IntVar(self), ('main', 'General', 'autosave'))
self.format_width = tracers.add(
StringVar(self), ('extensions', 'FormatParagraph', 'max-width'))
self.context_lines = tracers.add(
StringVar(self), ('extensions', 'CodeContext', 'maxlines'))
# Create widgets:
# Section frames.
frame_window = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Window Preferences')
frame_editor = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Editor Preferences')
frame_shell = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Shell Preferences')
frame_help = LabelFrame(self, borderwidth=2, relief=GROOVE,
text=' Additional Help Sources ')
# Frame_window.
frame_run = Frame(frame_window, borderwidth=0)
startup_title = Label(frame_run, text='At Startup')
self.startup_editor_on = Radiobutton(
frame_run, variable=self.startup_edit, value=1,
text="Open Edit Window")
self.startup_shell_on = Radiobutton(
frame_run, variable=self.startup_edit, value=0,
text='Open Shell Window')
frame_win_size = Frame(frame_window, borderwidth=0)
win_size_title = Label(
frame_win_size, text='Initial Window Size (in characters)')
win_width_title = Label(frame_win_size, text='Width')
self.win_width_int = Entry(
frame_win_size, textvariable=self.win_width, width=3)
win_height_title = Label(frame_win_size, text='Height')
self.win_height_int = Entry(
frame_win_size, textvariable=self.win_height, width=3)
frame_autocomplete = Frame(frame_window, borderwidth=0,)
auto_wait_title = Label(frame_autocomplete,
text='Completions Popup Wait (milliseconds)')
self.auto_wait_int = Entry(frame_autocomplete, width=6,
textvariable=self.autocomplete_wait)
frame_paren1 = Frame(frame_window, borderwidth=0)
paren_style_title = Label(frame_paren1, text='Paren Match Style')
self.paren_style_type = OptionMenu(
frame_paren1, self.paren_style, 'expression',
"opener","parens","expression")
frame_paren2 = Frame(frame_window, borderwidth=0)
paren_time_title = Label(
frame_paren2, text='Time Match Displayed (milliseconds)\n'
'(0 is until next input)')
self.paren_flash_time = Entry(
frame_paren2, textvariable=self.flash_delay, width=6)
self.bell_on = Checkbutton(
frame_paren2, text="Bell on Mismatch", variable=self.paren_bell)
# Frame_editor.
frame_save = Frame(frame_editor, borderwidth=0)
run_save_title = Label(frame_save, text='At Start of Run (F5) ')
self.save_ask_on = Radiobutton(
frame_save, variable=self.autosave, value=0,
text="Prompt to Save")
self.save_auto_on = Radiobutton(
frame_save, variable=self.autosave, value=1,
text='No Prompt')
frame_format = Frame(frame_editor, borderwidth=0)
format_width_title = Label(frame_format,
text='Format Paragraph Max Width')
self.format_width_int = Entry(
frame_format, textvariable=self.format_width, width=4)
frame_context = Frame(frame_editor, borderwidth=0)
context_title = Label(frame_context, text='Max Context Lines :')
self.context_int = Entry(
frame_context, textvariable=self.context_lines, width=3)
# Frame_shell.
frame_auto_squeeze_min_lines = Frame(frame_shell, borderwidth=0)
auto_squeeze_min_lines_title = Label(frame_auto_squeeze_min_lines,
text='Auto-Squeeze Min. Lines:')
self.auto_squeeze_min_lines_int = Entry(
frame_auto_squeeze_min_lines, width=4,
textvariable=self.auto_squeeze_min_lines)
# frame_help.
frame_helplist = Frame(frame_help)
frame_helplist_buttons = Frame(frame_helplist)
self.helplist = Listbox(
frame_helplist, height=5, takefocus=True,
exportselection=FALSE)
scroll_helplist = Scrollbar(frame_helplist)
scroll_helplist['command'] = self.helplist.yview
self.helplist['yscrollcommand'] = scroll_helplist.set
self.helplist.bind('<ButtonRelease-1>', self.help_source_selected)
self.button_helplist_edit = Button(
frame_helplist_buttons, text='Edit', state='disabled',
width=8, command=self.helplist_item_edit)
self.button_helplist_add = Button(
frame_helplist_buttons, text='Add',
width=8, command=self.helplist_item_add)
self.button_helplist_remove = Button(
frame_helplist_buttons, text='Remove', state='disabled',
width=8, command=self.helplist_item_remove)
# Pack widgets:
# Body.
frame_window.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
frame_editor.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
frame_shell.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
frame_help.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
# frame_run.
frame_run.pack(side=TOP, padx=5, pady=0, fill=X)
startup_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.startup_shell_on.pack(side=RIGHT, anchor=W, padx=5, pady=5)
self.startup_editor_on.pack(side=RIGHT, anchor=W, padx=5, pady=5)
# frame_win_size.
frame_win_size.pack(side=TOP, padx=5, pady=0, fill=X)
win_size_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.win_height_int.pack(side=RIGHT, anchor=E, padx=10, pady=5)
win_height_title.pack(side=RIGHT, anchor=E, pady=5)
self.win_width_int.pack(side=RIGHT, anchor=E, padx=10, pady=5)
win_width_title.pack(side=RIGHT, anchor=E, pady=5)
# frame_autocomplete.
frame_autocomplete.pack(side=TOP, padx=5, pady=0, fill=X)
auto_wait_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.auto_wait_int.pack(side=TOP, padx=10, pady=5)
# frame_paren.
frame_paren1.pack(side=TOP, padx=5, pady=0, fill=X)
paren_style_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.paren_style_type.pack(side=TOP, padx=10, pady=5)
frame_paren2.pack(side=TOP, padx=5, pady=0, fill=X)
paren_time_title.pack(side=LEFT, anchor=W, padx=5)
self.bell_on.pack(side=RIGHT, anchor=E, padx=15, pady=5)
self.paren_flash_time.pack(side=TOP, anchor=W, padx=15, pady=5)
# frame_save.
frame_save.pack(side=TOP, padx=5, pady=0, fill=X)
run_save_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.save_auto_on.pack(side=RIGHT, anchor=W, padx=5, pady=5)
self.save_ask_on.pack(side=RIGHT, anchor=W, padx=5, pady=5)
# frame_format.
frame_format.pack(side=TOP, padx=5, pady=0, fill=X)
format_width_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.format_width_int.pack(side=TOP, padx=10, pady=5)
# frame_context.
frame_context.pack(side=TOP, padx=5, pady=0, fill=X)
context_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.context_int.pack(side=TOP, padx=5, pady=5)
# frame_auto_squeeze_min_lines
frame_auto_squeeze_min_lines.pack(side=TOP, padx=5, pady=0, fill=X)
auto_squeeze_min_lines_title.pack(side=LEFT, anchor=W, padx=5, pady=5)
self.auto_squeeze_min_lines_int.pack(side=TOP, padx=5, pady=5)
# frame_help.
frame_helplist_buttons.pack(side=RIGHT, padx=5, pady=5, fill=Y)
frame_helplist.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
scroll_helplist.pack(side=RIGHT, anchor=W, fill=Y)
self.helplist.pack(side=LEFT, anchor=E, expand=TRUE, fill=BOTH)
self.button_helplist_edit.pack(side=TOP, anchor=W, pady=5)
self.button_helplist_add.pack(side=TOP, anchor=W)
self.button_helplist_remove.pack(side=TOP, anchor=W, pady=5)
def load_general_cfg(self):
"Load current configuration settings for the general options."
# Set variables for all windows.
self.startup_edit.set(idleConf.GetOption(
'main', 'General', 'editor-on-startup', type='bool'))
self.win_width.set(idleConf.GetOption(
'main', 'EditorWindow', 'width', type='int'))
self.win_height.set(idleConf.GetOption(
'main', 'EditorWindow', 'height', type='int'))
self.autocomplete_wait.set(idleConf.GetOption(
'extensions', 'AutoComplete', 'popupwait', type='int'))
self.paren_style.set(idleConf.GetOption(
'extensions', 'ParenMatch', 'style'))
self.flash_delay.set(idleConf.GetOption(
'extensions', 'ParenMatch', 'flash-delay', type='int'))
self.paren_bell.set(idleConf.GetOption(
'extensions', 'ParenMatch', 'bell'))
# Set variables for editor windows.
self.autosave.set(idleConf.GetOption(
'main', 'General', 'autosave', default=0, type='bool'))
self.format_width.set(idleConf.GetOption(
'extensions', 'FormatParagraph', 'max-width', type='int'))
self.context_lines.set(idleConf.GetOption(
'extensions', 'CodeContext', 'maxlines', type='int'))
# Set variables for shell windows.
self.auto_squeeze_min_lines.set(idleConf.GetOption(
'main', 'PyShell', 'auto-squeeze-min-lines', type='int'))
# Set additional help sources.
self.user_helplist = idleConf.GetAllExtraHelpSourcesList()
self.helplist.delete(0, 'end')
for help_item in self.user_helplist:
self.helplist.insert(END, help_item[0])
self.set_add_delete_state()
def help_source_selected(self, event):
"Handle event for selecting additional help."
self.set_add_delete_state()
def set_add_delete_state(self):
"Toggle the state for the help list buttons based on list entries."
if self.helplist.size() < 1: # No entries in list.
self.button_helplist_edit.state(('disabled',))
self.button_helplist_remove.state(('disabled',))
else: # Some entries.
if self.helplist.curselection(): # There currently is a selection.
self.button_helplist_edit.state(('!disabled',))
self.button_helplist_remove.state(('!disabled',))
else: # There currently is not a selection.
self.button_helplist_edit.state(('disabled',))
self.button_helplist_remove.state(('disabled',))
def helplist_item_add(self):
"""Handle add button for the help list.
Query for name and location of new help sources and add
them to the list.
"""
help_source = HelpSource(self, 'New Help Source').result
if help_source:
self.user_helplist.append(help_source)
self.helplist.insert(END, help_source[0])
self.update_help_changes()
def helplist_item_edit(self):
"""Handle edit button for the help list.
Query with existing help source information and update
config if the values are changed.
"""
item_index = self.helplist.index(ANCHOR)
help_source = self.user_helplist[item_index]
new_help_source = HelpSource(
self, 'Edit Help Source',
menuitem=help_source[0],
filepath=help_source[1],
).result
if new_help_source and new_help_source != help_source:
self.user_helplist[item_index] = new_help_source
self.helplist.delete(item_index)
self.helplist.insert(item_index, new_help_source[0])
self.update_help_changes()
self.set_add_delete_state() # Selected will be un-selected
def helplist_item_remove(self):
"""Handle remove button for the help list.
Delete the help list item from config.
"""
item_index = self.helplist.index(ANCHOR)
del(self.user_helplist[item_index])
self.helplist.delete(item_index)
self.update_help_changes()
self.set_add_delete_state()
def update_help_changes(self):
"Clear and rebuild the HelpFiles section in changes"
changes['main']['HelpFiles'] = {}
for num in range(1, len(self.user_helplist) + 1):
changes.add_option(
'main', 'HelpFiles', str(num),
';'.join(self.user_helplist[num-1][:2]))
class VarTrace:
"""Maintain Tk variables trace state."""
def __init__(self):
"""Store Tk variables and callbacks.
untraced: List of tuples (var, callback)
that do not have the callback attached
to the Tk var.
traced: List of tuples (var, callback) where
that callback has been attached to the var.
"""
self.untraced = []
self.traced = []
def clear(self):
"Clear lists (for tests)."
# Call after all tests in a module to avoid memory leaks.
self.untraced.clear()
self.traced.clear()
def add(self, var, callback):
"""Add (var, callback) tuple to untraced list.
Args:
var: Tk variable instance.
callback: Either function name to be used as a callback
or a tuple with IdleConf config-type, section, and
option names used in the default callback.
Return:
Tk variable instance.
"""
if isinstance(callback, tuple):
callback = self.make_callback(var, callback)
self.untraced.append((var, callback))
return var
@staticmethod
def make_callback(var, config):
"Return default callback function to add values to changes instance."
def default_callback(*params):
"Add config values to changes instance."
changes.add_option(*config, var.get())
return default_callback
def attach(self):
"Attach callback to all vars that are not traced."
while self.untraced:
var, callback = self.untraced.pop()
var.trace_add('write', callback)
self.traced.append((var, callback))
def detach(self):
"Remove callback from traced vars."
while self.traced:
var, callback = self.traced.pop()
var.trace_remove('write', var.trace_info()[0][1])
self.untraced.append((var, callback))
tracers = VarTrace()
help_common = '''\
When you click either the Apply or Ok buttons, settings in this
dialog that are different from IDLE's default are saved in
a .idlerc directory in your home directory. Except as noted,
these changes apply to all versions of IDLE installed on this
machine. [Cancel] only cancels changes made since the last save.
'''
help_pages = {
'Fonts/Tabs':'''
Font sample: This shows what a selection of Basic Multilingual Plane
unicode characters look like for the current font selection. If the
selected font does not define a character, Tk attempts to find another
font that does. Substitute glyphs depend on what is available on a
particular system and will not necessarily have the same size as the
font selected. Line contains 20 characters up to Devanagari, 14 for
Tamil, and 10 for East Asia.
Hebrew and Arabic letters should display right to left, starting with
alef, \u05d0 and \u0627. Arabic digits display left to right. The
Devanagari and Tamil lines start with digits. The East Asian lines
are Chinese digits, Chinese Hanzi, Korean Hangul, and Japanese
Hiragana and Katakana.
You can edit the font sample. Changes remain until IDLE is closed.
''',
'Highlights': '''
Highlighting:
The IDLE Dark color theme is new in October 2015. It can only
be used with older IDLE releases if it is saved as a custom
theme, with a different name.
''',
'Keys': '''
Keys:
The IDLE Modern Unix key set is new in June 2016. It can only
be used with older IDLE releases if it is saved as a custom
key set, with a different name.
''',
'General': '''
General:
AutoComplete: Popupwait is milleseconds to wait after key char, without
cursor movement, before popping up completion box. Key char is '.' after
identifier or a '/' (or '\\' on Windows) within a string.
FormatParagraph: Max-width is max chars in lines after re-formatting.
Use with paragraphs in both strings and comment blocks.
ParenMatch: Style indicates what is highlighted when closer is entered:
'opener' - opener '({[' corresponding to closer; 'parens' - both chars;
'expression' (default) - also everything in between. Flash-delay is how
long to highlight if cursor is not moved (0 means forever).
CodeContext: Maxlines is the maximum number of code context lines to
display when Code Context is turned on for an editor window.
Shell Preferences: Auto-Squeeze Min. Lines is the minimum number of lines
of output to automatically "squeeze".
'''
}
def is_int(s):
"Return 's is blank or represents an int'"
if not s:
return True
try:
int(s)
return True
except ValueError:
return False
class VerticalScrolledFrame(Frame):
"""A pure Tkinter vertically scrollable frame.
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling
"""
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# Create a canvas object and a vertical scrollbar for scrolling it.
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, borderwidth=0, highlightthickness=0,
yscrollcommand=vscrollbar.set, width=240)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# Reset the view.
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# Create a frame inside the canvas which will be scrolled with it.
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)
# Track changes to the canvas and frame width and sync them,
# also updating the scrollbar.
def _configure_interior(event):
# Update the scrollbars to match the size of the inner frame.
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# Update the inner frame's width to fill the canvas.
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
return
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_configdialog', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(ConfigDialog)
| 101,057 | 2,309 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/window.py | from tkinter import *
class WindowList:
def __init__(self):
self.dict = {}
self.callbacks = []
def add(self, window):
window.after_idle(self.call_callbacks)
self.dict[str(window)] = window
def delete(self, window):
try:
del self.dict[str(window)]
except KeyError:
# Sometimes, destroy() is called twice
pass
self.call_callbacks()
def add_windows_to_menu(self, menu):
list = []
for key in self.dict:
window = self.dict[key]
try:
title = window.get_title()
except TclError:
continue
list.append((title, key, window))
list.sort()
for title, key, window in list:
menu.add_command(label=title, command=window.wakeup)
def register_callback(self, callback):
self.callbacks.append(callback)
def unregister_callback(self, callback):
try:
self.callbacks.remove(callback)
except ValueError:
pass
def call_callbacks(self):
for callback in self.callbacks:
try:
callback()
except:
t, v, tb = sys.exc_info()
print("warning: callback failed in WindowList", t, ":", v)
registry = WindowList()
add_windows_to_menu = registry.add_windows_to_menu
register_callback = registry.register_callback
unregister_callback = registry.unregister_callback
class ListedToplevel(Toplevel):
def __init__(self, master, **kw):
Toplevel.__init__(self, master, kw)
registry.add(self)
self.focused_widget = self
def destroy(self):
registry.delete(self)
Toplevel.destroy(self)
# If this is Idle's last window then quit the mainloop
# (Needed for clean exit on Windows 98)
if not registry.dict:
self.quit()
def update_windowlist_registry(self, window):
registry.call_callbacks()
def get_title(self):
# Subclass can override
return self.wm_title()
def wakeup(self):
try:
if self.wm_state() == "iconic":
self.wm_withdraw()
self.wm_deiconify()
self.tkraise()
self.focused_widget.focus_set()
except TclError:
# This can happen when the Window menu was torn off.
# Simply ignore it.
pass
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_window', verbosity=2)
| 2,588 | 98 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/macosx.py | """
A number of functions that enhance IDLE on macOS.
"""
from os.path import expanduser
import plistlib
from sys import platform # Used in _init_tk_type, changed by test.
import tkinter
## Define functions that query the Mac graphics type.
## _tk_type and its initializer are private to this section.
_tk_type = None
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"
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"
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"
def isCocoaTk():
"""
Returns True if IDLE is using a Cocoa Aqua Tk.
"""
if not _tk_type:
_init_tk_type()
return _tk_type == "cocoa"
def isXQuartz():
"""
Returns True if IDLE is using an OS X X11 Tk.
"""
if not _tk_type:
_init_tk_type()
return _tk_type == "xquartz"
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
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
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
## Fix the menu and related functions.
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)
def hideTkConsole(root):
try:
root.tk.call('console', 'hide')
except tkinter.TclError:
# Some versions of the Tk framework don't have a console object
pass
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[-2][1][0]
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]
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>>')
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)
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_macosx', verbosity=2)
| 9,660 | 288 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/dynoption.py | """
OptionMenu widget modified to allow dynamic menu reconfiguration
and setting of highlightthickness
"""
import copy
from tkinter import OptionMenu, _setit, StringVar, Button
class DynOptionMenu(OptionMenu):
"""
unlike OptionMenu, our kwargs can include highlightthickness
"""
def __init__(self, master, variable, value, *values, **kwargs):
# TODO copy value instead of whole dict
kwargsCopy=copy.copy(kwargs)
if 'highlightthickness' in list(kwargs.keys()):
del(kwargs['highlightthickness'])
OptionMenu.__init__(self, master, variable, value, *values, **kwargs)
self.config(highlightthickness=kwargsCopy.get('highlightthickness'))
#self.menu=self['menu']
self.variable=variable
self.command=kwargs.get('command')
def SetMenu(self,valueList,value=None):
"""
clear and reload the menu with a new set of options.
valueList - list of new options
value - initial value to set the optionmenu's menubutton to
"""
self['menu'].delete(0,'end')
for item in valueList:
self['menu'].add_command(label=item,
command=_setit(self.variable,item,self.command))
if value:
self.variable.set(value)
def _dyn_option_menu(parent): # htest #
from tkinter import Toplevel # + StringVar, Button
top = Toplevel(parent)
top.title("Tets dynamic option menu")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("200x100+%d+%d" % (x + 250, y + 175))
top.focus_set()
var = StringVar(top)
var.set("Old option set") #Set the default value
dyn = DynOptionMenu(top,var, "old1","old2","old3","old4")
dyn.pack()
def update():
dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
button = Button(top, text="Change option set", command=update)
button.pack()
if __name__ == '__main__':
from idlelib.idle_test.htest import run
run(_dyn_option_menu)
| 2,017 | 59 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/debugobj_r.py | from idlelib import rpc
def remote_object_tree_item(item):
wrapper = WrappedObjectTreeItem(item)
oid = id(wrapper)
rpc.objecttable[oid] = wrapper
return oid
class WrappedObjectTreeItem:
# Lives in PYTHON subprocess
def __init__(self, item):
self.__item = item
def __getattr__(self, name):
value = getattr(self.__item, name)
return value
def _GetSubList(self):
sub_list = self.__item._GetSubList()
return list(map(remote_object_tree_item, sub_list))
class StubObjectTreeItem:
# Lives in IDLE process
def __init__(self, sockio, oid):
self.sockio = sockio
self.oid = oid
def __getattr__(self, name):
value = rpc.MethodProxy(self.sockio, self.oid, name)
return value
def _GetSubList(self):
sub_list = self.sockio.remotecall(self.oid, "_GetSubList", (), {})
return [StubObjectTreeItem(self.sockio, oid) for oid in sub_list]
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_debugobj_r', verbosity=2)
| 1,082 | 42 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/stackviewer.py | import linecache
import os
import sys
import tkinter as tk
from idlelib.debugobj import ObjectTreeItem, make_objecttreeitem
from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
def StackBrowser(root, flist=None, tb=None, top=None):
global sc, item, node # For testing.
if top is None:
top = tk.Toplevel(root)
sc = ScrolledCanvas(top, bg="white", highlightthickness=0)
sc.frame.pack(expand=1, fill="both")
item = StackTreeItem(flist, tb)
node = TreeNode(sc.canvas, None, item)
node.expand()
class StackTreeItem(TreeItem):
def __init__(self, flist=None, tb=None):
self.flist = flist
self.stack = self.get_stack(tb)
self.text = self.get_exception()
def get_stack(self, tb):
if tb is None:
tb = sys.last_traceback
stack = []
if tb and tb.tb_frame is None:
tb = tb.tb_next
while tb is not None:
stack.append((tb.tb_frame, tb.tb_lineno))
tb = tb.tb_next
return stack
def get_exception(self):
type = sys.last_type
value = sys.last_value
if hasattr(type, "__name__"):
type = type.__name__
s = str(type)
if value is not None:
s = s + ": " + str(value)
return s
def GetText(self):
return self.text
def GetSubList(self):
sublist = []
for info in self.stack:
item = FrameTreeItem(info, self.flist)
sublist.append(item)
return sublist
class FrameTreeItem(TreeItem):
def __init__(self, info, flist):
self.info = info
self.flist = flist
def GetText(self):
frame, lineno = self.info
try:
modname = frame.f_globals["__name__"]
except:
modname = "?"
code = frame.f_code
filename = code.co_filename
funcname = code.co_name
sourceline = linecache.getline(filename, lineno)
sourceline = sourceline.strip()
if funcname in ("?", "", None):
item = "%s, line %d: %s" % (modname, lineno, sourceline)
else:
item = "%s.%s(...), line %d: %s" % (modname, funcname,
lineno, sourceline)
return item
def GetSubList(self):
frame, lineno = self.info
sublist = []
if frame.f_globals is not frame.f_locals:
item = VariablesTreeItem("<locals>", frame.f_locals, self.flist)
sublist.append(item)
item = VariablesTreeItem("<globals>", frame.f_globals, self.flist)
sublist.append(item)
return sublist
def OnDoubleClick(self):
if self.flist:
frame, lineno = self.info
filename = frame.f_code.co_filename
if os.path.isfile(filename):
self.flist.gotofileline(filename, lineno)
class VariablesTreeItem(ObjectTreeItem):
def GetText(self):
return self.labeltext
def GetLabelText(self):
return None
def IsExpandable(self):
return len(self.object) > 0
def GetSubList(self):
sublist = []
for key in self.object.keys():
try:
value = self.object[key]
except KeyError:
continue
def setfunction(value, key=key, object=self.object):
object[key] = value
item = make_objecttreeitem(key + " =", value, setfunction)
sublist.append(item)
return sublist
def _stack_viewer(parent): # htest #
from idlelib.pyshell import PyShellFileList
top = tk.Toplevel(parent)
top.title("Test StackViewer")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" % (x + 50, y + 175))
flist = PyShellFileList(top)
try: # to obtain a traceback object
intentional_name_error
except NameError:
exc_type, exc_value, exc_tb = sys.exc_info()
# inject stack trace to sys
sys.last_type = exc_type
sys.last_value = exc_value
sys.last_traceback = exc_tb
StackBrowser(top, flist=flist, top=top, tb=exc_tb)
# restore sys to original state
del sys.last_type
del sys.last_value
del sys.last_traceback
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_stackviewer', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_stack_viewer)
| 4,454 | 156 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/config.py | """idlelib.config -- Manage IDLE configuration information.
The comments at the beginning of config-main.def describe the
configuration files and the design implemented to update user
configuration information. In particular, user configuration choices
which duplicate the defaults will be removed from the user's
configuration files, and if a user file becomes empty, it will be
deleted.
The configuration database maps options to values. Conceptually, the
database keys are tuples (config-type, section, item). As implemented,
there are separate dicts for default and user values. Each has
config-type keys 'main', 'extensions', 'highlight', and 'keys'. The
value for each key is a ConfigParser instance that maps section and item
to values. For 'main' and 'extenstons', user values override
default values. For 'highlight' and 'keys', user sections augment the
default sections (and must, therefore, have distinct names).
Throughout this module there is an emphasis on returning useable defaults
when a problem occurs in returning a requested configuration value back to
idle. This is to allow IDLE to continue to function in spite of errors in
the retrieval of config information. When a default is returned instead of
a requested config value, a message is printed to stderr to aid in
configuration problem notification and resolution.
"""
# TODOs added Oct 2014, tjr
from configparser import ConfigParser
import os
import sys
from tkinter.font import Font
import idlelib
class InvalidConfigType(Exception): pass
class InvalidConfigSet(Exception): pass
class InvalidFgBg(Exception): pass
class InvalidTheme(Exception): pass
class IdleConfParser(ConfigParser):
"""
A ConfigParser specialised for idle configuration file handling
"""
def __init__(self, cfgFile, cfgDefaults=None):
"""
cfgFile - string, fully specified configuration file name
"""
self.file = cfgFile # This is currently '' when testing.
ConfigParser.__init__(self, defaults=cfgDefaults, strict=False)
def Get(self, section, option, type=None, default=None, raw=False):
"""
Get an option value for given section/option or return default.
If type is specified, return as type.
"""
# TODO Use default as fallback, at least if not None
# Should also print Warning(file, section, option).
# Currently may raise ValueError
if not self.has_option(section, option):
return default
if type == 'bool':
return self.getboolean(section, option)
elif type == 'int':
return self.getint(section, option)
else:
return self.get(section, option, raw=raw)
def GetOptionList(self, section):
"Return a list of options for given section, else []."
if self.has_section(section):
return self.options(section)
else: #return a default value
return []
def Load(self):
"Load the configuration file from disk."
if self.file:
self.read(self.file)
class IdleUserConfParser(IdleConfParser):
"""
IdleConfigParser specialised for user configuration handling.
"""
def SetOption(self, section, option, value):
"""Return True if option is added or changed to value, else False.
Add section if required. False means option already had value.
"""
if self.has_option(section, option):
if self.get(section, option) == value:
return False
else:
self.set(section, option, value)
return True
else:
if not self.has_section(section):
self.add_section(section)
self.set(section, option, value)
return True
def RemoveOption(self, section, option):
"""Return True if option is removed from section, else False.
False if either section does not exist or did not have option.
"""
if self.has_section(section):
return self.remove_option(section, option)
return False
def AddSection(self, section):
"If section doesn't exist, add it."
if not self.has_section(section):
self.add_section(section)
def RemoveEmptySections(self):
"Remove any sections that have no options."
for section in self.sections():
if not self.GetOptionList(section):
self.remove_section(section)
def IsEmpty(self):
"Return True if no sections after removing empty sections."
self.RemoveEmptySections()
return not self.sections()
def RemoveFile(self):
"Remove user config file self.file from disk if it exists."
if os.path.exists(self.file):
os.remove(self.file)
def Save(self):
"""Update user configuration file.
If self not empty after removing empty sections, write the file
to disk. Otherwise, remove the file from disk if it exists.
"""
fname = self.file
if fname:
if not self.IsEmpty():
try:
cfgFile = open(fname, 'w')
except OSError:
os.unlink(fname)
cfgFile = open(fname, 'w')
with cfgFile:
self.write(cfgFile)
else:
self.RemoveFile()
class IdleConf:
"""Hold config parsers for all idle config files in singleton instance.
Default config files, self.defaultCfg --
for config_type in self.config_types:
(idle install dir)/config-{config-type}.def
User config files, self.userCfg --
for config_type in self.config_types:
(user home dir)/.idlerc/config-{config-type}.cfg
"""
def __init__(self, _utest=False):
self.config_types = ('main', 'highlight', 'keys', 'extensions')
self.defaultCfg = {}
self.userCfg = {}
self.cfg = {} # TODO use to select userCfg vs defaultCfg
if not _utest:
self.CreateConfigHandlers()
self.LoadCfgFiles()
def CreateConfigHandlers(self):
"Populate default and user config parser dictionaries."
#build idle install path
if __name__ != '__main__': # we were imported
idleDir = os.path.dirname(__file__)
else: # we were exec'ed (for testing only)
idleDir = os.path.abspath(sys.path[0])
self.userdir = userDir = self.GetUserCfgDir()
defCfgFiles = {}
usrCfgFiles = {}
# TODO eliminate these temporaries by combining loops
for cfgType in self.config_types: #build config file names
defCfgFiles[cfgType] = os.path.join(
idleDir, 'config-' + cfgType + '.def')
usrCfgFiles[cfgType] = os.path.join(
userDir, 'config-' + cfgType + '.cfg')
for cfgType in self.config_types: #create config parsers
self.defaultCfg[cfgType] = IdleConfParser(defCfgFiles[cfgType])
self.userCfg[cfgType] = IdleUserConfParser(usrCfgFiles[cfgType])
def GetUserCfgDir(self):
"""Return a filesystem directory for storing user config files.
Creates it if required.
"""
cfgDir = '.idlerc'
userDir = os.path.expanduser('~')
if userDir != '~': # expanduser() found user home dir
if not os.path.exists(userDir):
warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
userDir + ',\n but the path does not exist.')
try:
print(warn, file=sys.stderr)
except OSError:
pass
userDir = '~'
if userDir == "~": # still no path to home!
# traditionally IDLE has defaulted to os.getcwd(), is this adequate?
userDir = os.getcwd()
userDir = os.path.join(userDir, cfgDir)
if not os.path.exists(userDir):
try:
os.mkdir(userDir)
except OSError:
warn = ('\n Warning: unable to create user config directory\n' +
userDir + '\n Check path and permissions.\n Exiting!\n')
if not idlelib.testing:
print(warn, file=sys.stderr)
raise SystemExit
# TODO continue without userDIr instead of exit
return userDir
def GetOption(self, configType, section, option, default=None, type=None,
warn_on_default=True, raw=False):
"""Return a value for configType section option, or default.
If type is not None, return a value of that type. Also pass raw
to the config parser. First try to return a valid value
(including type) from a user configuration. If that fails, try
the default configuration. If that fails, return default, with a
default of None.
Warn if either user or default configurations have an invalid value.
Warn if default is returned and warn_on_default is True.
"""
try:
if self.userCfg[configType].has_option(section, option):
return self.userCfg[configType].Get(section, option,
type=type, raw=raw)
except ValueError:
warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
' invalid %r value for configuration option %r\n'
' from section %r: %r' %
(type, option, section,
self.userCfg[configType].Get(section, option, raw=raw)))
_warn(warning, configType, section, option)
try:
if self.defaultCfg[configType].has_option(section,option):
return self.defaultCfg[configType].Get(
section, option, type=type, raw=raw)
except ValueError:
pass
#returning default, print warning
if warn_on_default:
warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
' problem retrieving configuration option %r\n'
' from section %r.\n'
' returning default value: %r' %
(option, section, default))
_warn(warning, configType, section, option)
return default
def SetOption(self, configType, section, option, value):
"""Set section option to value in user config file."""
self.userCfg[configType].SetOption(section, option, value)
def GetSectionList(self, configSet, configType):
"""Return sections for configSet configType configuration.
configSet must be either 'user' or 'default'
configType must be in self.config_types.
"""
if not (configType in self.config_types):
raise InvalidConfigType('Invalid configType specified')
if configSet == 'user':
cfgParser = self.userCfg[configType]
elif configSet == 'default':
cfgParser=self.defaultCfg[configType]
else:
raise InvalidConfigSet('Invalid configSet specified')
return cfgParser.sections()
def GetHighlight(self, theme, element, fgBg=None):
"""Return individual theme element highlight color(s).
fgBg - string ('fg' or 'bg') or None.
If None, return a dictionary containing fg and bg colors with
keys 'foreground' and 'background'. Otherwise, only return
fg or bg color, as specified. Colors are intended to be
appropriate for passing to Tkinter in, e.g., a tag_config call).
"""
if self.defaultCfg['highlight'].has_section(theme):
themeDict = self.GetThemeDict('default', theme)
else:
themeDict = self.GetThemeDict('user', theme)
fore = themeDict[element + '-foreground']
if element == 'cursor': # There is no config value for cursor bg
back = themeDict['normal-background']
else:
back = themeDict[element + '-background']
highlight = {"foreground": fore, "background": back}
if not fgBg: # Return dict of both colors
return highlight
else: # Return specified color only
if fgBg == 'fg':
return highlight["foreground"]
if fgBg == 'bg':
return highlight["background"]
else:
raise InvalidFgBg('Invalid fgBg specified')
def GetThemeDict(self, type, themeName):
"""Return {option:value} dict for elements in themeName.
type - string, 'default' or 'user' theme type
themeName - string, theme name
Values are loaded over ultimate fallback defaults to guarantee
that all theme elements are present in a newly created theme.
"""
if type == 'user':
cfgParser = self.userCfg['highlight']
elif type == 'default':
cfgParser = self.defaultCfg['highlight']
else:
raise InvalidTheme('Invalid theme type specified')
# Provide foreground and background colors for each theme
# element (other than cursor) even though some values are not
# yet used by idle, to allow for their use in the future.
# Default values are generally black and white.
# TODO copy theme from a class attribute.
theme ={'normal-foreground':'#000000',
'normal-background':'#ffffff',
'keyword-foreground':'#000000',
'keyword-background':'#ffffff',
'builtin-foreground':'#000000',
'builtin-background':'#ffffff',
'comment-foreground':'#000000',
'comment-background':'#ffffff',
'string-foreground':'#000000',
'string-background':'#ffffff',
'definition-foreground':'#000000',
'definition-background':'#ffffff',
'hilite-foreground':'#000000',
'hilite-background':'gray',
'break-foreground':'#ffffff',
'break-background':'#000000',
'hit-foreground':'#ffffff',
'hit-background':'#000000',
'error-foreground':'#ffffff',
'error-background':'#000000',
#cursor (only foreground can be set)
'cursor-foreground':'#000000',
#shell window
'stdout-foreground':'#000000',
'stdout-background':'#ffffff',
'stderr-foreground':'#000000',
'stderr-background':'#ffffff',
'console-foreground':'#000000',
'console-background':'#ffffff',
'context-foreground':'#000000',
'context-background':'#ffffff',
}
for element in theme:
if not cfgParser.has_option(themeName, element):
# Print warning that will return a default color
warning = ('\n Warning: config.IdleConf.GetThemeDict'
' -\n problem retrieving theme element %r'
'\n from theme %r.\n'
' returning default color: %r' %
(element, themeName, theme[element]))
_warn(warning, 'highlight', themeName, element)
theme[element] = cfgParser.Get(
themeName, element, default=theme[element])
return theme
def CurrentTheme(self):
"Return the name of the currently active text color theme."
return self.current_colors_and_keys('Theme')
def CurrentKeys(self):
"""Return the name of the currently active key set."""
return self.current_colors_and_keys('Keys')
def current_colors_and_keys(self, section):
"""Return the currently active name for Theme or Keys section.
idlelib.config-main.def ('default') includes these sections
[Theme]
default= 1
name= IDLE Classic
name2=
[Keys]
default= 1
name=
name2=
Item 'name2', is used for built-in ('default') themes and keys
added after 2015 Oct 1 and 2016 July 1. This kludge is needed
because setting 'name' to a builtin not defined in older IDLEs
to display multiple error messages or quit.
See https://bugs.python.org/issue25313.
When default = True, 'name2' takes precedence over 'name',
while older IDLEs will just use name. When default = False,
'name2' may still be set, but it is ignored.
"""
cfgname = 'highlight' if section == 'Theme' else 'keys'
default = self.GetOption('main', section, 'default',
type='bool', default=True)
name = ''
if default:
name = self.GetOption('main', section, 'name2', default='')
if not name:
name = self.GetOption('main', section, 'name', default='')
if name:
source = self.defaultCfg if default else self.userCfg
if source[cfgname].has_section(name):
return name
return "IDLE Classic" if section == 'Theme' else self.default_keys()
@staticmethod
def default_keys():
if sys.platform[:3] == 'win':
return 'IDLE Classic Windows'
elif sys.platform == 'darwin':
return 'IDLE Classic OSX'
else:
return 'IDLE Modern Unix'
def GetExtensions(self, active_only=True,
editor_only=False, shell_only=False):
"""Return extensions in default and user config-extensions files.
If active_only True, only return active (enabled) extensions
and optionally only editor or shell extensions.
If active_only False, return all extensions.
"""
extns = self.RemoveKeyBindNames(
self.GetSectionList('default', 'extensions'))
userExtns = self.RemoveKeyBindNames(
self.GetSectionList('user', 'extensions'))
for extn in userExtns:
if extn not in extns: #user has added own extension
extns.append(extn)
for extn in ('AutoComplete','CodeContext',
'FormatParagraph','ParenMatch'):
extns.remove(extn)
# specific exclusions because we are storing config for mainlined old
# extensions in config-extensions.def for backward compatibility
if active_only:
activeExtns = []
for extn in extns:
if self.GetOption('extensions', extn, 'enable', default=True,
type='bool'):
#the extension is enabled
if editor_only or shell_only: # TODO both True contradict
if editor_only:
option = "enable_editor"
else:
option = "enable_shell"
if self.GetOption('extensions', extn,option,
default=True, type='bool',
warn_on_default=False):
activeExtns.append(extn)
else:
activeExtns.append(extn)
return activeExtns
else:
return extns
def RemoveKeyBindNames(self, extnNameList):
"Return extnNameList with keybinding section names removed."
return [n for n in extnNameList if not n.endswith(('_bindings', '_cfgBindings'))]
def GetExtnNameForEvent(self, virtualEvent):
"""Return the name of the extension binding virtualEvent, or None.
virtualEvent - string, name of the virtual event to test for,
without the enclosing '<< >>'
"""
extName = None
vEvent = '<<' + virtualEvent + '>>'
for extn in self.GetExtensions(active_only=0):
for event in self.GetExtensionKeys(extn):
if event == vEvent:
extName = extn # TODO return here?
return extName
def GetExtensionKeys(self, extensionName):
"""Return dict: {configurable extensionName event : active keybinding}.
Events come from default config extension_cfgBindings section.
Keybindings come from GetCurrentKeySet() active key dict,
where previously used bindings are disabled.
"""
keysName = extensionName + '_cfgBindings'
activeKeys = self.GetCurrentKeySet()
extKeys = {}
if self.defaultCfg['extensions'].has_section(keysName):
eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
for eventName in eventNames:
event = '<<' + eventName + '>>'
binding = activeKeys[event]
extKeys[event] = binding
return extKeys
def __GetRawExtensionKeys(self,extensionName):
"""Return dict {configurable extensionName event : keybinding list}.
Events come from default config extension_cfgBindings section.
Keybindings list come from the splitting of GetOption, which
tries user config before default config.
"""
keysName = extensionName+'_cfgBindings'
extKeys = {}
if self.defaultCfg['extensions'].has_section(keysName):
eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
for eventName in eventNames:
binding = self.GetOption(
'extensions', keysName, eventName, default='').split()
event = '<<' + eventName + '>>'
extKeys[event] = binding
return extKeys
def GetExtensionBindings(self, extensionName):
"""Return dict {extensionName event : active or defined keybinding}.
Augment self.GetExtensionKeys(extensionName) with mapping of non-
configurable events (from default config) to GetOption splits,
as in self.__GetRawExtensionKeys.
"""
bindsName = extensionName + '_bindings'
extBinds = self.GetExtensionKeys(extensionName)
#add the non-configurable bindings
if self.defaultCfg['extensions'].has_section(bindsName):
eventNames = self.defaultCfg['extensions'].GetOptionList(bindsName)
for eventName in eventNames:
binding = self.GetOption(
'extensions', bindsName, eventName, default='').split()
event = '<<' + eventName + '>>'
extBinds[event] = binding
return extBinds
def GetKeyBinding(self, keySetName, eventStr):
"""Return the keybinding list for keySetName eventStr.
keySetName - name of key binding set (config-keys section).
eventStr - virtual event, including brackets, as in '<<event>>'.
"""
eventName = eventStr[2:-2] #trim off the angle brackets
binding = self.GetOption('keys', keySetName, eventName, default='',
warn_on_default=False).split()
return binding
def GetCurrentKeySet(self):
"Return CurrentKeys with 'darwin' modifications."
result = self.GetKeySet(self.CurrentKeys())
if sys.platform == "darwin":
# macOS (OS X) Tk variants do not support the "Alt"
# keyboard modifier. Replace it with "Option".
# TODO (Ned?): the "Option" modifier does not work properly
# for Cocoa Tk and XQuartz Tk so we should not use it
# in the default 'OSX' keyset.
for k, v in result.items():
v2 = [ x.replace('<Alt-', '<Option-') for x in v ]
if v != v2:
result[k] = v2
return result
def GetKeySet(self, keySetName):
"""Return event-key dict for keySetName core plus active extensions.
If a binding defined in an extension is already in use, the
extension binding is disabled by being set to ''
"""
keySet = self.GetCoreKeys(keySetName)
activeExtns = self.GetExtensions(active_only=1)
for extn in activeExtns:
extKeys = self.__GetRawExtensionKeys(extn)
if extKeys: #the extension defines keybindings
for event in extKeys:
if extKeys[event] in keySet.values():
#the binding is already in use
extKeys[event] = '' #disable this binding
keySet[event] = extKeys[event] #add binding
return keySet
def IsCoreBinding(self, virtualEvent):
"""Return True if the virtual event is one of the core idle key events.
virtualEvent - string, name of the virtual event to test for,
without the enclosing '<< >>'
"""
return ('<<'+virtualEvent+'>>') in self.GetCoreKeys()
# TODO make keyBindins a file or class attribute used for test above
# and copied in function below.
former_extension_events = { # Those with user-configurable keys.
'<<force-open-completions>>', '<<expand-word>>',
'<<force-open-calltip>>', '<<flash-paren>>', '<<format-paragraph>>',
'<<run-module>>', '<<check-module>>', '<<zoom-height>>'}
def GetCoreKeys(self, keySetName=None):
"""Return dict of core virtual-key keybindings for keySetName.
The default keySetName None corresponds to the keyBindings base
dict. If keySetName is not None, bindings from the config
file(s) are loaded _over_ these defaults, so if there is a
problem getting any core binding there will be an 'ultimate last
resort fallback' to the CUA-ish bindings defined here.
"""
keyBindings={
'<<copy>>': ['<Control-c>', '<Control-C>'],
'<<cut>>': ['<Control-x>', '<Control-X>'],
'<<paste>>': ['<Control-v>', '<Control-V>'],
'<<beginning-of-line>>': ['<Control-a>', '<Home>'],
'<<center-insert>>': ['<Control-l>'],
'<<close-all-windows>>': ['<Control-q>'],
'<<close-window>>': ['<Alt-F4>'],
'<<do-nothing>>': ['<Control-x>'],
'<<end-of-file>>': ['<Control-d>'],
'<<python-docs>>': ['<F1>'],
'<<python-context-help>>': ['<Shift-F1>'],
'<<history-next>>': ['<Alt-n>'],
'<<history-previous>>': ['<Alt-p>'],
'<<interrupt-execution>>': ['<Control-c>'],
'<<view-restart>>': ['<F6>'],
'<<restart-shell>>': ['<Control-F6>'],
'<<open-class-browser>>': ['<Alt-c>'],
'<<open-module>>': ['<Alt-m>'],
'<<open-new-window>>': ['<Control-n>'],
'<<open-window-from-file>>': ['<Control-o>'],
'<<plain-newline-and-indent>>': ['<Control-j>'],
'<<print-window>>': ['<Control-p>'],
'<<redo>>': ['<Control-y>'],
'<<remove-selection>>': ['<Escape>'],
'<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
'<<save-window-as-file>>': ['<Alt-s>'],
'<<save-window>>': ['<Control-s>'],
'<<select-all>>': ['<Alt-a>'],
'<<toggle-auto-coloring>>': ['<Control-slash>'],
'<<undo>>': ['<Control-z>'],
'<<find-again>>': ['<Control-g>', '<F3>'],
'<<find-in-files>>': ['<Alt-F3>'],
'<<find-selection>>': ['<Control-F3>'],
'<<find>>': ['<Control-f>'],
'<<replace>>': ['<Control-h>'],
'<<goto-line>>': ['<Alt-g>'],
'<<smart-backspace>>': ['<Key-BackSpace>'],
'<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'],
'<<smart-indent>>': ['<Key-Tab>'],
'<<indent-region>>': ['<Control-Key-bracketright>'],
'<<dedent-region>>': ['<Control-Key-bracketleft>'],
'<<comment-region>>': ['<Alt-Key-3>'],
'<<uncomment-region>>': ['<Alt-Key-4>'],
'<<tabify-region>>': ['<Alt-Key-5>'],
'<<untabify-region>>': ['<Alt-Key-6>'],
'<<toggle-tabs>>': ['<Alt-Key-t>'],
'<<change-indentwidth>>': ['<Alt-Key-u>'],
'<<del-word-left>>': ['<Control-Key-BackSpace>'],
'<<del-word-right>>': ['<Control-Key-Delete>'],
'<<force-open-completions>>': ['<Control-Key-space>'],
'<<expand-word>>': ['<Alt-Key-slash>'],
'<<force-open-calltip>>': ['<Control-Key-backslash>'],
'<<flash-paren>>': ['<Control-Key-0>'],
'<<format-paragraph>>': ['<Alt-Key-q>'],
'<<run-module>>': ['<Key-F5>'],
'<<check-module>>': ['<Alt-Key-x>'],
'<<zoom-height>>': ['<Alt-Key-2>'],
}
if keySetName:
if not (self.userCfg['keys'].has_section(keySetName) or
self.defaultCfg['keys'].has_section(keySetName)):
warning = (
'\n Warning: config.py - IdleConf.GetCoreKeys -\n'
' key set %r is not defined, using default bindings.' %
(keySetName,)
)
_warn(warning, 'keys', keySetName)
else:
for event in keyBindings:
binding = self.GetKeyBinding(keySetName, event)
if binding:
keyBindings[event] = binding
# Otherwise return default in keyBindings.
elif event not in self.former_extension_events:
warning = (
'\n Warning: config.py - IdleConf.GetCoreKeys -\n'
' problem retrieving key binding for event %r\n'
' from key set %r.\n'
' returning default value: %r' %
(event, keySetName, keyBindings[event])
)
_warn(warning, 'keys', keySetName, event)
return keyBindings
def GetExtraHelpSourceList(self, configSet):
"""Return list of extra help sources from a given configSet.
Valid configSets are 'user' or 'default'. Return a list of tuples of
the form (menu_item , path_to_help_file , option), or return the empty
list. 'option' is the sequence number of the help resource. 'option'
values determine the position of the menu items on the Help menu,
therefore the returned list must be sorted by 'option'.
"""
helpSources = []
if configSet == 'user':
cfgParser = self.userCfg['main']
elif configSet == 'default':
cfgParser = self.defaultCfg['main']
else:
raise InvalidConfigSet('Invalid configSet specified')
options=cfgParser.GetOptionList('HelpFiles')
for option in options:
value=cfgParser.Get('HelpFiles', option, default=';')
if value.find(';') == -1: #malformed config entry with no ';'
menuItem = '' #make these empty
helpPath = '' #so value won't be added to list
else: #config entry contains ';' as expected
value=value.split(';')
menuItem=value[0].strip()
helpPath=value[1].strip()
if menuItem and helpPath: #neither are empty strings
helpSources.append( (menuItem,helpPath,option) )
helpSources.sort(key=lambda x: x[2])
return helpSources
def GetAllExtraHelpSourcesList(self):
"""Return a list of the details of all additional help sources.
Tuples in the list are those of GetExtraHelpSourceList.
"""
allHelpSources = (self.GetExtraHelpSourceList('default') +
self.GetExtraHelpSourceList('user') )
return allHelpSources
def GetFont(self, root, configType, section):
"""Retrieve a font from configuration (font, font-size, font-bold)
Intercept the special value 'TkFixedFont' and substitute
the actual font, factoring in some tweaks if needed for
appearance sakes.
The 'root' parameter can normally be any valid Tkinter widget.
Return a tuple (family, size, weight) suitable for passing
to tkinter.Font
"""
family = self.GetOption(configType, section, 'font', default='courier')
size = self.GetOption(configType, section, 'font-size', type='int',
default='10')
bold = self.GetOption(configType, section, 'font-bold', default=0,
type='bool')
if (family == 'TkFixedFont'):
f = Font(name='TkFixedFont', exists=True, root=root)
actualFont = Font.actual(f)
family = actualFont['family']
size = actualFont['size']
if size <= 0:
size = 10 # if font in pixels, ignore actual size
bold = actualFont['weight'] == 'bold'
return (family, size, 'bold' if bold else 'normal')
def LoadCfgFiles(self):
"Load all configuration files."
for key in self.defaultCfg:
self.defaultCfg[key].Load()
self.userCfg[key].Load() #same keys
def SaveUserCfgFiles(self):
"Write all loaded user configuration files to disk."
for key in self.userCfg:
self.userCfg[key].Save()
idleConf = IdleConf()
_warned = set()
def _warn(msg, *key):
key = (msg,) + key
if key not in _warned:
try:
print(msg, file=sys.stderr)
except OSError:
pass
_warned.add(key)
class ConfigChanges(dict):
"""Manage a user's proposed configuration option changes.
Names used across multiple methods:
page -- one of the 4 top-level dicts representing a
.idlerc/config-x.cfg file.
config_type -- name of a page.
section -- a section within a page/file.
option -- name of an option within a section.
value -- value for the option.
Methods
add_option: Add option and value to changes.
save_option: Save option and value to config parser.
save_all: Save all the changes to the config parser and file.
delete_section: If section exists,
delete from changes, userCfg, and file.
clear: Clear all changes by clearing each page.
"""
def __init__(self):
"Create a page for each configuration file"
self.pages = [] # List of unhashable dicts.
for config_type in idleConf.config_types:
self[config_type] = {}
self.pages.append(self[config_type])
def add_option(self, config_type, section, item, value):
"Add item/value pair for config_type and section."
page = self[config_type]
value = str(value) # Make sure we use a string.
if section not in page:
page[section] = {}
page[section][item] = value
@staticmethod
def save_option(config_type, section, item, value):
"""Return True if the configuration value was added or changed.
Helper for save_all.
"""
if idleConf.defaultCfg[config_type].has_option(section, item):
if idleConf.defaultCfg[config_type].Get(section, item) == value:
# The setting equals a default setting, remove it from user cfg.
return idleConf.userCfg[config_type].RemoveOption(section, item)
# If we goth here, set the option.
return idleConf.userCfg[config_type].SetOption(section, item, value)
def save_all(self):
"""Save configuration changes to the user config file.
Clear self in preparation for additional changes.
Return changed for testing.
"""
idleConf.userCfg['main'].Save()
changed = False
for config_type in self:
cfg_type_changed = False
page = self[config_type]
for section in page:
if section == 'HelpFiles': # Remove it for replacement.
idleConf.userCfg['main'].remove_section('HelpFiles')
cfg_type_changed = True
for item, value in page[section].items():
if self.save_option(config_type, section, item, value):
cfg_type_changed = True
if cfg_type_changed:
idleConf.userCfg[config_type].Save()
changed = True
for config_type in ['keys', 'highlight']:
# Save these even if unchanged!
idleConf.userCfg[config_type].Save()
self.clear()
# ConfigDialog caller must add the following call
# self.save_all_changed_extensions() # Uses a different mechanism.
return changed
def delete_section(self, config_type, section):
"""Delete a section from self, userCfg, and file.
Used to delete custom themes and keysets.
"""
if section in self[config_type]:
del self[config_type][section]
configpage = idleConf.userCfg[config_type]
configpage.remove_section(section)
configpage.Save()
def clear(self):
"""Clear all 4 pages.
Called in save_all after saving to idleConf.
XXX Mark window *title* when there are changes; unmark here.
"""
for page in self.pages:
page.clear()
# TODO Revise test output, write expanded unittest
def _dump(): # htest # (not really, but ignore in coverage)
from zlib import crc32
line, crc = 0, 0
def sprint(obj):
global line, crc
txt = str(obj)
line += 1
crc = crc32(txt.encode(encoding='utf-8'), crc)
print(txt)
#print('***', line, crc, '***') # Uncomment for diagnosis.
def dumpCfg(cfg):
print('\n', cfg, '\n') # Cfg has variable '0xnnnnnnnn' address.
for key in sorted(cfg.keys()):
sections = cfg[key].sections()
sprint(key)
sprint(sections)
for section in sections:
options = cfg[key].options(section)
sprint(section)
sprint(options)
for option in options:
sprint(option + ' = ' + cfg[key].Get(section, option))
dumpCfg(idleConf.defaultCfg)
dumpCfg(idleConf.userCfg)
print('\nlines = ', line, ', crc = ', crc, sep='')
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_config', verbosity=2, exit=False)
# Run revised _dump() as htest?
| 38,879 | 931 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/ChangeLog | Please refer to the IDLEfork and IDLE CVS repositories for
change details subsequent to the 0.8.1 release.
IDLEfork ChangeLog
==================
2001-07-20 11:35 elguavas
* README.txt, NEWS.txt: bring up to date for 0.8.1 release
2001-07-19 16:40 elguavas
* IDLEFORK.html: replaced by IDLEFORK-index.html
2001-07-19 16:39 elguavas
* IDLEFORK-index.html: updated placeholder idlefork homepage
2001-07-19 14:49 elguavas
* ChangeLog, EditorWindow.py, INSTALLATION, NEWS.txt, README.txt,
TODO.txt, idlever.py:
minor tidy-ups ready for 0.8.1 alpha tarball release
2001-07-17 15:12 kbk
* INSTALLATION, setup.py: INSTALLATION: Remove the coexist.patch
instructions
**************** setup.py:
Remove the idles script, add some words on IDLE Fork to the
long_description, and clean up some line spacing.
2001-07-17 15:01 kbk
* coexist.patch: Put this in the attic, at least for now...
2001-07-17 14:59 kbk
* PyShell.py, idle, idles: Implement idle command interface as
suggested by GvR [idle-dev] 16 July **************** PyShell: Added
functionality:
usage: idle.py [-c command] [-d] [-i] [-r script] [-s] [-t title]
[arg] ...
idle file(s) (without options) edit the file(s)
-c cmd run the command in a shell -d enable the
debugger -i open an interactive shell -i file(s) open a
shell and also an editor window for each file -r script run a file
as a script in a shell -s run $IDLESTARTUP or
$PYTHONSTARTUP before anything else -t title set title of shell
window
Remaining arguments are applied to the command (-c) or script (-r).
****************** idles: Removed the idles script, not needed
****************** idle: Removed the IdleConf references, not
required anymore
2001-07-16 17:08 kbk
* INSTALLATION, coexist.patch: Added installation instructions.
Added a patch which modifies idlefork so that it can co-exist with
"official" IDLE in the site-packages directory. This patch is not
necessary if only idlefork IDLE is installed. See INSTALLATION for
further details.
2001-07-16 15:50 kbk
* idles: Add a script "idles" which opens a Python Shell window.
The default behaviour of idlefork idle is to open an editor window
instead of a shell. Complex expressions may be run in a fresh
environment by selecting "run". There are times, however, when a
shell is desired. Though one can be started by "idle -t 'foo'",
this script is more convenient. In addition, a shell and an editor
window can be started in parallel by "idles -e foo.py".
2001-07-16 15:25 kbk
* PyShell.py: Call out IDLE Fork in startup message.
2001-07-16 14:00 kbk
* PyShell.py, setup.py: Add a script "idles" which opens a Python
Shell window.
The default behaviour of idlefork idle is to open an editor window
instead of a shell. Complex expressions may be run in a fresh
environment by selecting "run". There are times, however, when a
shell is desired. Though one can be started by "idle -t 'foo'",
this script is more convenient. In addition, a shell and an editor
window can be started in parallel by "idles -e foo.py".
2001-07-15 03:06 kbk
* pyclbr.py, tabnanny.py: tabnanny and pyclbr are now found in /Lib
2001-07-15 02:29 kbk
* BrowserControl.py: Remove, was retained for 1.5.2 support
2001-07-14 15:48 kbk
* setup.py: Installing Idle to site-packages via Distutils does not
copy the Idle help.txt file.
Ref SF Python Patch 422471
2001-07-14 15:26 kbk
* keydefs.py: py-cvs-2001_07_13 (Rev 1.3) merge
"Make copy, cut and paste events case insensitive. Reported by
Patrick K. O'Brien on idle-dev. (Should other bindings follow
suit?)" --GvR
2001-07-14 15:21 kbk
* idle.py: py-cvs-2001_07_13 (Rev 1.4) merge
"Move the action of loading the configuration to the IdleConf
module rather than the idle.py script. This has advantages and
disadvantages; the biggest advantage being that we can more easily
have an alternative main program." --GvR
2001-07-14 15:18 kbk
* extend.txt: py-cvs-2001_07_13 (Rev 1.4) merge
"Quick update to the extension mechanism (extend.py is gone, long
live config.txt)" --GvR
2001-07-14 15:15 kbk
* StackViewer.py: py-cvs-2001_07_13 (Rev 1.16) merge
"Refactored, with some future plans in mind. This now uses the new
gotofileline() method defined in FileList.py" --GvR
2001-07-14 15:10 kbk
* PyShell.py: py-cvs-2001_07_13 (Rev 1.34) merge
"Amazing. A very subtle change in policy in descr-branch actually
found a bug here. Here's the deal: Class PyShell derives from
class OutputWindow. Method PyShell.close() wants to invoke its
parent method, but because PyShell long ago was inherited from
class PyShellEditorWindow, it invokes
PyShelEditorWindow.close(self). Now, class PyShellEditorWindow
itself derives from class OutputWindow, and inherits the close()
method from there without overriding it. Under the old rules,
PyShellEditorWindow.close would return an unbound method restricted
to the class that defined the implementation of close(), which was
OutputWindow.close. Under the new rules, the unbound method is
restricted to the class whose method was requested, that is
PyShellEditorWindow, and this was correctly trapped as an error."
--GvR
2001-07-14 14:59 kbk
* PyParse.py: py-cvs-2001_07_13 (Rel 1.9) merge
"Taught IDLE's autoident parser that "yield" is a keyword that
begins a stmt. Along w/ the preceding change to keyword.py, making
all this work w/ a future-stmt just looks harder and harder."
--tim_one
(From Rel 1.8: "Hack to make this still work with Python 1.5.2.
;-( " --fdrake)
2001-07-14 14:51 kbk
* IdleConf.py: py-cvs-2001_07_13 (Rel 1.7) merge
"Move the action of loading the configuration to the IdleConf
module rather than the idle.py script. This has advantages and
disadvantages; the biggest advantage being that we can more easily
have an alternative main program." --GvR
2001-07-14 14:45 kbk
* FileList.py: py-cvs-2000_07_13 (Rev 1.9) merge
"Delete goodname() method, which is unused. Add gotofileline(), a
convenience method which I intend to use in a variant. Rename
test() to _test()." --GvR
This was an interesting merge. The join completely missed removing
goodname(), which was adjacent, but outside of, a small conflict.
I only caught it by comparing the 1.1.3.2/1.1.3.3 diff. CVS ain't
infallible.
2001-07-14 13:58 kbk
* EditorWindow.py: py-cvs-2000_07_13 (Rev 1.38) merge "Remove
legacy support for the BrowserControl module; the webbrowser module
has been included since Python 2.0, and that is the preferred
interface." --fdrake
2001-07-14 13:32 kbk
* EditorWindow.py, FileList.py, IdleConf.py, PyParse.py,
PyShell.py, StackViewer.py, extend.txt, idle.py, keydefs.py: Import
the 2001 July 13 23:59 GMT version of Python CVS IDLE on the
existing 1.1.3 vendor branch named py-cvs-vendor-branch. Release
tag is py-cvs-2001_07_13.
2001-07-14 12:02 kbk
* Icons/python.gif: py-cvs-rel2_1 (Rev 1.2) merge Copied py-cvs rev
1.2 changed file to idlefork MAIN
2001-07-14 11:58 kbk
* Icons/minusnode.gif: py-cvs-rel2_1 (Rev 1.2) merge Copied py-cvs
1.2 changed file to idlefork MAIN
2001-07-14 11:23 kbk
* ScrolledList.py: py-cvs-rel2_1 (rev 1.5) merge - whitespace
normalization
2001-07-14 11:20 kbk
* Separator.py: py-cvs-rel2_1 (Rev 1.3) merge - whitespace
normalization
2001-07-14 11:16 kbk
* StackViewer.py: py-cvs-rel2_1 (Rev 1.15) merge - whitespace
normalization
2001-07-14 11:14 kbk
* ToolTip.py: py-cvs-rel2_1 (Rev 1.2) merge - whitespace
normalization
2001-07-14 10:13 kbk
* PyShell.py: cvs-py-rel2_1 (Rev 1.29 - 1.33) merge
Merged the following py-cvs revs without conflict: 1.29 Reduce
copyright text output at startup 1.30 Delay setting sys.args until
Tkinter is fully initialized 1.31 Whitespace normalization 1.32
Turn syntax warning into error when interactive 1.33 Fix warning
initialization bug
Note that module is extensively modified wrt py-cvs
2001-07-14 06:33 kbk
* PyParse.py: py-cvs-rel2_1 (Rev 1.6 - 1.8) merge Fix autoindent
bug and deflect Unicode from text.get()
2001-07-14 06:00 kbk
* Percolator.py: py-cvs-rel2_1 (Rev 1.3) "move "from Tkinter import
*" to module level" --jhylton
2001-07-14 05:57 kbk
* PathBrowser.py: py-cvs-rel2_1 (Rev 1.6) merge - whitespace
normalization
2001-07-14 05:49 kbk
* ParenMatch.py: cvs-py-rel2_1 (Rev 1.5) merge - whitespace
normalization
2001-07-14 03:57 kbk
* ObjectBrowser.py: py-cvs-rel2_1 (Rev 1.3) merge "Make the test
program work outside IDLE." -- GvR
2001-07-14 03:52 kbk
* MultiStatusBar.py: py-cvs-rel2_1 (Rev 1.2) merge - whitespace
normalization
2001-07-14 03:44 kbk
* MultiScrolledLists.py: py-cvs-rel2_1 (Rev 1.2) merge - whitespace
normalization
2001-07-14 03:40 kbk
* IdleHistory.py: py-cvs-rel2_1 (Rev 1.4) merge - whitespace
normalization
2001-07-14 03:38 kbk
* IdleConf.py: py-cvs-rel2_1 (Rev 1.6) merge - whitespace
normalization
2001-07-13 14:18 kbk
* IOBinding.py: py-cvs-rel2_1 (Rev 1.4) merge - move "import *" to
module level
2001-07-13 14:12 kbk
* FormatParagraph.py: py-cvs-rel2_1 (Rev 1.9) merge - whitespace
normalization
2001-07-13 14:07 kbk
* FileList.py: py-cvs-rel2_1 (Rev 1.8) merge - whitespace
normalization
2001-07-13 13:35 kbk
* EditorWindow.py: py-cvs-rel2_1 (Rev 1.33 - 1.37) merge
VP IDLE version depended on VP's ExecBinding.py and spawn.py to get
the path to the Windows Doc directory (relative to python.exe).
Removed this conflicting code in favor of py-cvs updates which on
Windows use a hard coded path relative to the location of this
module. py-cvs updates include support for webbrowser.py. Module
still has BrowserControl.py for 1.5.2 support.
At this point, the differences wrt py-cvs relate to menu
functionality.
2001-07-13 11:30 kbk
* ConfigParser.py: py-cvs-rel2_1 merge - Remove, lives in /Lib
2001-07-13 10:10 kbk
* Delegator.py: py-cvs-rel2_1 (Rev 1.3) merge - whitespace
normalization
2001-07-13 10:07 kbk
* Debugger.py: py-cvs-rel2_1 (Rev 1.15) merge - whitespace
normalization
2001-07-13 10:04 kbk
* ColorDelegator.py: py-cvs-rel2_1 (Rev 1.11 and 1.12) merge
Colorize "as" after "import" / use DEBUG instead of __debug__
2001-07-13 09:54 kbk
* ClassBrowser.py: py-cvs-rel2_1 (Rev 1.12) merge - whitespace
normalization
2001-07-13 09:41 kbk
* BrowserControl.py: py-cvs-rel2_1 (Rev 1.1) merge - New File -
Force HEAD to trunk with -f Note: browser.py was renamed
BrowserControl.py 10 May 2000. It provides a collection of classes
and convenience functions to control external browsers "for 1.5.2
support". It was removed from py-cvs 18 April 2001.
2001-07-13 09:10 kbk
* CallTips.py: py-cvs-rel2_1 (Rev 1.8) merge - whitespace
normalization
2001-07-13 08:26 kbk
* CallTipWindow.py: py-cvs-rel2_1 (Rev 1.3) merge - whitespace
normalization
2001-07-13 08:13 kbk
* AutoExpand.py: py-cvs-rel1_2 (Rev 1.4) merge, "Add Alt-slash to
Unix keydefs (I somehow need it on RH 6.2). Get rid of assignment
to unused self.text.wordlist." --GvR
2001-07-12 16:54 elguavas
* ReplaceDialog.py: py-cvs merge, python 1.5.2 compatibility
2001-07-12 16:46 elguavas
* ScriptBinding.py: py-cvs merge, better error dialog
2001-07-12 16:38 elguavas
* TODO.txt: py-cvs merge, additions
2001-07-12 15:35 elguavas
* WindowList.py: py-cvs merge, correct indentation
2001-07-12 15:24 elguavas
* config.txt: py-cvs merge, correct typo
2001-07-12 15:21 elguavas
* help.txt: py-cvs merge, update colour changing info
2001-07-12 14:51 elguavas
* idle.py: py-cvs merge, idle_dir loading changed
2001-07-12 14:44 elguavas
* idlever.py: py-cvs merge, version update
2001-07-11 12:53 kbk
* BrowserControl.py: Initial revision
2001-07-11 12:53 kbk
* AutoExpand.py, BrowserControl.py, CallTipWindow.py, CallTips.py,
ClassBrowser.py, ColorDelegator.py, Debugger.py, Delegator.py,
EditorWindow.py, FileList.py, FormatParagraph.py, IOBinding.py,
IdleConf.py, IdleHistory.py, MultiScrolledLists.py,
MultiStatusBar.py, ObjectBrowser.py, OutputWindow.py,
ParenMatch.py, PathBrowser.py, Percolator.py, PyParse.py,
PyShell.py, RemoteInterp.py, ReplaceDialog.py, ScriptBinding.py,
ScrolledList.py, Separator.py, StackViewer.py, TODO.txt,
ToolTip.py, WindowList.py, config.txt, help.txt, idle, idle.bat,
idle.py, idlever.py, setup.py, Icons/minusnode.gif,
Icons/python.gif: Import the release 2.1 version of Python CVS IDLE
on the existing 1.1.3 vendor branch named py-cvs-vendor-branch,
with release tag py-cvs-rel2_1.
2001-07-11 12:34 kbk
* AutoExpand.py, AutoIndent.py, Bindings.py, CallTipWindow.py,
CallTips.py, ChangeLog, ClassBrowser.py, ColorDelegator.py,
Debugger.py, Delegator.py, EditorWindow.py, FileList.py,
FormatParagraph.py, FrameViewer.py, GrepDialog.py, IOBinding.py,
IdleConf.py, IdleHistory.py, MultiScrolledLists.py,
MultiStatusBar.py, NEWS.txt, ObjectBrowser.py, OldStackViewer.py,
OutputWindow.py, ParenMatch.py, PathBrowser.py, Percolator.py,
PyParse.py, PyShell.py, README.txt, RemoteInterp.py,
ReplaceDialog.py, ScriptBinding.py, ScrolledList.py,
SearchBinding.py, SearchDialog.py, SearchDialogBase.py,
SearchEngine.py, Separator.py, StackViewer.py, TODO.txt,
ToolTip.py, TreeWidget.py, UndoDelegator.py, WidgetRedirector.py,
WindowList.py, ZoomHeight.py, __init__.py, config-unix.txt,
config-win.txt, config.txt, eventparse.py, extend.txt, help.txt,
idle.bat, idle.py, idle.pyw, idlever.py, keydefs.py, pyclbr.py,
tabnanny.py, testcode.py, Icons/folder.gif, Icons/minusnode.gif,
Icons/openfolder.gif, Icons/plusnode.gif, Icons/python.gif,
Icons/tk.gif: Import the 9 March 2000 version of Python CVS IDLE as
1.1.3 vendor branch named py-cvs-vendor-branch.
2001-07-04 13:43 kbk
* Icons/: folder.gif, minusnode.gif, openfolder.gif, plusnode.gif,
python.gif, tk.gif: Null commit with -f option to force an uprev
and put HEADs firmly on the trunk.
2001-07-04 13:15 kbk
* AutoExpand.py, AutoIndent.py, Bindings.py, CallTipWindow.py,
CallTips.py, ChangeLog, ClassBrowser.py, ColorDelegator.py,
ConfigParser.py, Debugger.py, Delegator.py, EditorWindow.py,
ExecBinding.py, FileList.py, FormatParagraph.py, FrameViewer.py,
GrepDialog.py, IDLEFORK.html, IOBinding.py, IdleConf.py,
IdleHistory.py, MultiScrolledLists.py, MultiStatusBar.py, NEWS.txt,
ObjectBrowser.py, OldStackViewer.py, OutputWindow.py,
ParenMatch.py, PathBrowser.py, Percolator.py, PyParse.py,
PyShell.py, README.txt, Remote.py, RemoteInterp.py,
ReplaceDialog.py, ScriptBinding.py, ScrolledList.py,
SearchBinding.py, SearchDialog.py, SearchDialogBase.py,
SearchEngine.py, Separator.py, StackViewer.py, TODO.txt,
ToolTip.py, TreeWidget.py, UndoDelegator.py, WidgetRedirector.py,
WindowList.py, ZoomHeight.py, __init__.py, config-unix.txt,
config-win.txt, config.txt, eventparse.py, extend.txt, help.txt,
idle, idle.bat, idle.py, idle.pyw, idlever.py, keydefs.py,
loader.py, protocol.py, pyclbr.py, setup.py, spawn.py, tabnanny.py,
testcode.py: Null commit with -f option to force an uprev and put
HEADs firmly on the trunk.
2001-06-27 10:24 elguavas
* IDLEFORK.html: updated contact details
2001-06-25 17:23 elguavas
* idle, RemoteInterp.py, setup.py: Initial revision
2001-06-25 17:23 elguavas
* idle, RemoteInterp.py, setup.py: import current python cvs idle
as a vendor branch
2001-06-24 15:10 elguavas
* IDLEFORK.html: tiny change to test new syncmail setup
2001-06-24 14:41 elguavas
* IDLEFORK.html: change to new developer contact, also a test
commit for new syncmail setup
2001-06-23 18:15 elguavas
* IDLEFORK.html: tiny test update for revitalised idle-fork
2000-09-24 17:29 nriley
* protocol.py: Fixes for Python 1.6 compatibility - socket bind and
connect get a tuple instead two arguments.
2000-09-24 17:28 nriley
* spawn.py: Change for Python 1.6 compatibility - UNIX's 'os'
module defines 'spawnv' now, so we check for 'fork' first.
2000-08-15 22:51 nowonder
* IDLEFORK.html:
corrected email address
2000-08-15 22:47 nowonder
* IDLEFORK.html:
added .html file for http://idlefork.sourceforge.net
2000-08-15 11:13 dscherer
* AutoExpand.py, AutoIndent.py, Bindings.py, CallTipWindow.py,
CallTips.py, __init__.py, ChangeLog, ClassBrowser.py,
ColorDelegator.py, ConfigParser.py, Debugger.py, Delegator.py,
FileList.py, FormatParagraph.py, FrameViewer.py, GrepDialog.py,
IOBinding.py, IdleConf.py, IdleHistory.py, MultiScrolledLists.py,
MultiStatusBar.py, NEWS.txt, ObjectBrowser.py, OldStackViewer.py,
OutputWindow.py, ParenMatch.py, PathBrowser.py, Percolator.py,
PyParse.py, PyShell.py, README.txt, ReplaceDialog.py,
ScriptBinding.py, ScrolledList.py, SearchBinding.py,
SearchDialog.py, SearchDialogBase.py, SearchEngine.py,
Separator.py, StackViewer.py, TODO.txt, ToolTip.py, TreeWidget.py,
UndoDelegator.py, WidgetRedirector.py, WindowList.py, help.txt,
ZoomHeight.py, config-unix.txt, config-win.txt, config.txt,
eventparse.py, extend.txt, idle.bat, idle.py, idle.pyw, idlever.py,
keydefs.py, loader.py, pyclbr.py, tabnanny.py, testcode.py,
EditorWindow.py, ExecBinding.py, Remote.py, protocol.py, spawn.py,
Icons/folder.gif, Icons/minusnode.gif, Icons/openfolder.gif,
Icons/plusnode.gif, Icons/python.gif, Icons/tk.gif: Initial
revision
2000-08-15 11:13 dscherer
* AutoExpand.py, AutoIndent.py, Bindings.py, CallTipWindow.py,
CallTips.py, __init__.py, ChangeLog, ClassBrowser.py,
ColorDelegator.py, ConfigParser.py, Debugger.py, Delegator.py,
FileList.py, FormatParagraph.py, FrameViewer.py, GrepDialog.py,
IOBinding.py, IdleConf.py, IdleHistory.py, MultiScrolledLists.py,
MultiStatusBar.py, NEWS.txt, ObjectBrowser.py, OldStackViewer.py,
OutputWindow.py, ParenMatch.py, PathBrowser.py, Percolator.py,
PyParse.py, PyShell.py, README.txt, ReplaceDialog.py,
ScriptBinding.py, ScrolledList.py, SearchBinding.py,
SearchDialog.py, SearchDialogBase.py, SearchEngine.py,
Separator.py, StackViewer.py, TODO.txt, ToolTip.py, TreeWidget.py,
UndoDelegator.py, WidgetRedirector.py, WindowList.py, help.txt,
ZoomHeight.py, config-unix.txt, config-win.txt, config.txt,
eventparse.py, extend.txt, idle.bat, idle.py, idle.pyw, idlever.py,
keydefs.py, loader.py, pyclbr.py, tabnanny.py, testcode.py,
EditorWindow.py, ExecBinding.py, Remote.py, protocol.py, spawn.py,
Icons/folder.gif, Icons/minusnode.gif, Icons/openfolder.gif,
Icons/plusnode.gif, Icons/python.gif, Icons/tk.gif: Modified IDLE
from VPython 0.2
original IDLE ChangeLog:
========================
Tue Feb 15 18:08:19 2000 Guido van Rossum <[email protected]>
* NEWS.txt: Notice status bar and stack viewer.
* EditorWindow.py: Support for Moshe's status bar.
* MultiStatusBar.py: Status bar code -- by Moshe Zadka.
* OldStackViewer.py:
Adding the old stack viewer implementation back, for the debugger.
* StackViewer.py: New stack viewer, uses a tree widget.
(XXX: the debugger doesn't yet use this.)
* WindowList.py:
Correct a typo and remove an unqualified except that was hiding the error.
* ClassBrowser.py: Add an XXX comment about the ClassBrowser AIP.
* ChangeLog: Updated change log.
* NEWS.txt: News update. Probably incomplete; what else is new?
* README.txt:
Updated for pending IDLE 0.5 release (still very rough -- just getting
it out in a more convenient format than CVS).
* TODO.txt: Tiny addition.
Thu Sep 9 14:16:02 1999 Guido van Rossum <[email protected]>
* TODO.txt: A few new TODO entries.
Thu Aug 26 23:06:22 1999 Guido van Rossum <[email protected]>
* Bindings.py: Add Python Documentation entry to Help menu.
* EditorWindow.py:
Find the help.txt file relative to __file__ or ".", not in sys.path.
(Suggested by Moshe Zadka, but implemented differently.)
Add <<python-docs>> event which, on Unix, brings up Netscape pointing
to http://www.python.doc/current/ (a local copy would be nice but its
location can't be predicted). Windows solution TBD.
Wed Aug 11 14:55:43 1999 Guido van Rossum <[email protected]>
* TreeWidget.py:
Moshe noticed an inconsistency in his comment, so I'm rephrasing it to
be clearer.
* TreeWidget.py:
Patch inspired by Moshe Zadka to search for the Icons directory in the
same directory as __file__, rather than searching for it along sys.path.
This works better when idle is a package.
Thu Jul 15 13:11:02 1999 Guido van Rossum <[email protected]>
* TODO.txt: New wishes.
Sat Jul 10 13:17:35 1999 Guido van Rossum <[email protected]>
* IdlePrefs.py:
Make the color for stderr red (i.e. the standard warning/danger/stop
color) rather than green. Suggested by Sam Schulenburg.
Fri Jun 25 17:26:34 1999 Guido van Rossum <[email protected]>
* PyShell.py: Close debugger when closing. This may break a cycle.
* Debugger.py: Break cycle on close.
* ClassBrowser.py: Destroy the tree when closing.
* TreeWidget.py: Add destroy() method to recursively destroy a tree.
* PyShell.py: Extend _close() to break cycles.
Break some other cycles too (and destroy the root when done).
* EditorWindow.py:
Add _close() method that does the actual cleanup (close() asks the
user what they want first if there's unsaved stuff, and may cancel).
It closes more than before.
Add unload_extensions() method to unload all extensions; called from
_close(). It calls an extension's close() method if it has one.
* Percolator.py: Add close() method that breaks cycles.
* WidgetRedirector.py: Add unregister() method.
Unregister everything at closing.
Don't call close() in __del__, rely on explicit call to close().
* IOBinding.py, FormatParagraph.py, CallTips.py:
Add close() method that breaks a cycle.
Fri Jun 11 15:03:00 1999 Guido van Rossum <[email protected]>
* AutoIndent.py, EditorWindow.py, FormatParagraph.py:
Tim Peters smart.patch:
EditorWindow.py:
+ Added get_tabwidth & set_tabwidth "virtual text" methods, that get/set the
widget's view of what a tab means.
+ Moved TK_TABWIDTH_DEFAULT here from AutoIndent.
+ Renamed Mark's get_selection_index to get_selection_indices (sorry, Mark,
but the name was plain wrong <wink>).
FormatParagraph.py: renamed use of get_selection_index.
AutoIndent.py:
+ Moved TK_TABWIDTH_DEFAULT to EditorWindow.
+ Rewrote set_indentation_params to use new VTW get/set_tabwidth methods.
+ Changed smart_backspace_event to delete whitespace back to closest
preceding virtual tab stop or real character (note that this may require
inserting characters if backspacing over a tab!).
+ Nuked almost references to the selection tag, in favor of using
get_selection_indices. The sole exception is in set_region, for which no
"set_selection" abstraction has yet been agreed upon.
+ Had too much fun using the spiffy new features of the format-paragraph
cmd.
Thu Jun 10 17:48:02 1999 Guido van Rossum <[email protected]>
* FormatParagraph.py:
Code by Mark Hammond to format paragraphs embedded in comments.
Read the comments (which I reformatted using the new feature :-)
for some limitations.
* EditorWindow.py:
Added abstraction get_selection_index() (Mark Hammond). Also
reformatted some comment blocks to show off a cool feature I'm about
to check in next.
* ClassBrowser.py:
Adapt to the new pyclbr's support of listing top-level functions. If
this functionality is not present (e.g. when used with a vintage
Python 1.5.2 installation) top-level functions are not listed.
(Hmm... Any distribution of IDLE 0.5 should probably include a copy
of the new pyclbr.py!)
* AutoIndent.py:
Fix off-by-one error in Tim's recent change to comment_region(): the
list of lines returned by get_region() contains an empty line at the
end representing the start of the next line, and this shouldn't be
commented out!
* CallTips.py:
Mark Hammond writes: Here is another change that allows it to work for
class creation - tries to locate an __init__ function. Also updated
the test code to reflect your new "***" change.
* CallTipWindow.py:
Mark Hammond writes: Tim's suggestion of copying the font for the
CallTipWindow from the text control makes sense, and actually makes
the control look better IMO.
Wed Jun 9 20:34:57 1999 Guido van Rossum <[email protected]>
* CallTips.py:
Append "..." if the appropriate flag (for varargs) in co_flags is set.
Ditto "***" for kwargs.
Tue Jun 8 13:06:07 1999 Guido van Rossum <[email protected]>
* ReplaceDialog.py:
Hmm... Tim didn't turn "replace all" into a single undo block.
I think I like it better if it os, so here.
* ReplaceDialog.py: Tim Peters: made replacement atomic for undo/redo.
* AutoIndent.py: Tim Peters:
+ Set usetabs=1. Editing pyclbr.py was driving me nuts <0.6 wink>.
usetabs=1 is the Emacs pymode default too, and thanks to indentwidth !=
tabwidth magical usetabs disabling, new files are still created with tabs
turned off. The only implication is that if you open a file whose first
indent is a single tab, IDLE will now magically use tabs for that file (and
set indentwidth to 8). Note that the whole scheme doesn't work right for
PythonWin, though, since Windows users typically set tabwidth to 4; Mark
probably has to hide the IDLE algorithm from them (which he already knows).
+ Changed comment_region_event to stick "##" in front of every line. The
"holes" previously left on blank lines were visually confusing (made it
needlessly hard to figure out what to uncomment later).
Mon Jun 7 15:38:40 1999 Guido van Rossum <[email protected]>
* TreeWidget.py, ObjectBrowser.py:
Remove unnecessary reference to pyclbr from test() code.
* PyParse.py: Tim Peters:
Smarter logic for finding a parse synch point.
Does a half to a fifth the work in normal cases; don't notice the speedup,
but makes more breathing room for other extensions.
Speeds terrible cases by at least a factor of 10. "Terrible" == e.g. you put
""" at the start of Tkinter.py, undo it, zoom to the bottom, and start
typing in code. Used to take about 8 seconds for ENTER to respond, now some
large fraction of a second. The new code gets indented correctly, despite
that it all remains "string colored" until the colorizer catches up (after
which, ENTER appears instantaneous again).
Fri Jun 4 19:21:19 1999 Guido van Rossum <[email protected]>
* extend.py: Might as well enable CallTips by default.
If there are too many complaints I'll remove it again or fix it.
Thu Jun 3 14:32:16 1999 Guido van Rossum <[email protected]>
* AutoIndent.py, EditorWindow.py, PyParse.py:
New offerings by Tim Peters; he writes:
IDLE is now the first Python editor in the Universe not confused by my
doctest.py <wink>.
As threatened, this defines IDLE's is_char_in_string function as a
method of EditorWindow. You just need to define one similarly in
whatever it is you pass as editwin to AutoIndent; looking at the
EditorWindow.py part of the patch should make this clear.
* GrepDialog.py: Enclose pattern in quotes in status message.
* CallTips.py:
Mark Hammond fixed some comments and improved the way the tip text is
constructed.
Wed Jun 2 18:18:57 1999 Guido van Rossum <[email protected]>
* CallTips.py:
My fix to Mark's code: restore the universal check on <KeyRelease>.
Always cancel on <Key-Escape> or <ButtonPress>.
* CallTips.py:
A version that Mark Hammond posted to the newsgroup. Has some newer
stuff for getting the tip. Had to fix the Key-( and Key-) events
for Unix. Will have to re-apply my patch for catching KeyRelease and
ButtonRelease events.
* CallTipWindow.py, CallTips.py:
Call tips by Mark Hammond (plus tiny fix by me.)
* IdleHistory.py:
Changes by Mark Hammond: (1) support optional output_sep argument to
the constructor so he can eliminate the sys.ps2 that PythonWin leaves
in the source; (2) remove duplicate history items.
* AutoIndent.py:
Changes by Mark Hammond to allow using IDLE extensions in PythonWin as
well: make three dialog routines instance variables.
* EditorWindow.py:
Change by Mark Hammond to allow using IDLE extensions in PythonWin as
well: make three dialog routines instance variables.
Tue Jun 1 20:06:44 1999 Guido van Rossum <[email protected]>
* AutoIndent.py: Hah! A fix of my own to Tim's code!
Unix bindings for <<toggle-tabs>> and <<change-indentwidth>> were
missing, and somehow that meant the events were never generated,
even though they were in the menu. The new Unix bindings are now
the same as the Windows bindings (M-t and M-u).
* AutoIndent.py, PyParse.py, PyShell.py: Tim Peters again:
The new version (attached) is fast enough all the time in every real module
I have <whew!>. You can make it slow by, e.g., creating an open list with
5,000 90-character identifiers (+ trailing comma) each on its own line, then
adding an item to the end -- but that still consumes less than a second on
my P5-166. Response time in real code appears instantaneous.
Fixed some bugs.
New feature: when hitting ENTER and the cursor is beyond the line's leading
indentation, whitespace is removed on both sides of the cursor; before
whitespace was removed only on the left; e.g., assuming the cursor is
between the comma and the space:
def something(arg1, arg2):
^ cursor to the left of here, and hit ENTER
arg2): # new line used to end up here
arg2): # but now lines up the way you expect
New hack: AutoIndent has grown a context_use_ps1 Boolean config option,
defaulting to 0 (false) and set to 1 (only) by PyShell. Reason: handling
the fancy stuff requires looking backward for a parsing synch point; ps1
lines are the only sensible thing to look for in a shell window, but are a
bad thing to look for in a file window (ps1 lines show up in my module
docstrings often). PythonWin's shell should set this true too.
Persistent problem: strings containing def/class can still screw things up
completely. No improvement. Simplest workaround is on the user's head, and
consists of inserting e.g.
def _(): pass
(or any other def/class) after the end of the multiline string that's
screwing them up. This is especially irksome because IDLE's syntax coloring
is *not* confused, so when this happens the colors don't match the
indentation behavior they see.
* AutoIndent.py: Tim Peters again:
[Tim, after adding some bracket smarts to AutoIndent.py]
> ...
> What it can't possibly do without reparsing large gobs of text is
> suggest a reasonable indent level after you've *closed* a bracket
> left open on some previous line.
> ...
The attached can, and actually fast enough to use -- most of the time. The
code is tricky beyond belief to achieve that, but it works so far; e.g.,
return len(string.expandtabs(str[self.stmt_start :
^ indents to caret
i],
^ indents to caret
self.tabwidth)) + 1
^ indents to caret
It's about as smart as pymode now, wrt both bracket and backslash
continuation rules. It does require reparsing large gobs of text, and if it
happens to find something that looks like a "def" or "class" or sys.ps1
buried in a multiline string, but didn't suck up enough preceding text to
see the start of the string, it's completely hosed. I can't repair that --
it's just too slow to reparse from the start of the file all the time.
AutoIndent has grown a new num_context_lines tuple attribute that controls
how far to look back, and-- like other params --this could/should be made
user-overridable at startup and per-file on the fly.
* PyParse.py: New file by Tim Peters:
One new file in the attached, PyParse.py. The LineStudier (whatever it was
called <wink>) class was removed from AutoIndent; PyParse subsumes its
functionality.
* AutoIndent.py: Tim Peters keeps revising this module (more to come):
Removed "New tabwidth" menu binding.
Added "a tab means how many spaces?" dialog to block tabify and untabify. I
think prompting for this is good now: they're usually at-most-once-per-file
commands, and IDLE can't let them change tabwidth from the Tk default
anymore, so IDLE can no longer presume to have any idea what a tab means.
Irony: for the purpose of keeping comments aligned via tabs, Tk's
non-default approach is much nicer than the Emacs/Notepad/Codewright/vi/etc
approach.
* EditorWindow.py:
1. Catch NameError on import (could be raised by case mismatch on Windows).
2. No longer need to reset pyclbr cache and show watch cursor when calling
ClassBrowser -- the ClassBrowser takes care of pyclbr and the TreeWidget
takes care of the watch cursor.
3. Reset the focus to the current window after error message about class
browser on buffer without filename.
* Icons/minusnode.gif, Icons/plusnode.gif: Missed a few.
* ClassBrowser.py, PathBrowser.py: Rewritten based on TreeWidget.py
* ObjectBrowser.py: Object browser, based on TreeWidget.py.
* TreeWidget.py: Tree widget done right.
* ToolTip.py: As yet unused code for tool tips.
* ScriptBinding.py:
Ensure sys.argv[0] is the script name on Run Script.
* ZoomHeight.py: Move zoom height functionality to separate function.
* Icons/folder.gif, Icons/openfolder.gif, Icons/python.gif, Icons/tk.gif:
A few icons used by ../TreeWidget.py and its callers.
* AutoIndent.py: New version by Tim Peters improves block opening test.
Fri May 21 04:46:17 1999 Guido van Rossum <[email protected]>
* Attic/History.py, PyShell.py: Rename History to IdleHistory.
Add isatty() to pseudo files.
* StackViewer.py: Make initial stack viewer wider
* TODO.txt: New wishes
* AutoIndent.py, EditorWindow.py, PyShell.py:
Much improved autoindent and handling of tabs,
by Tim Peters.
Mon May 3 15:49:52 1999 Guido van Rossum <[email protected]>
* AutoIndent.py, EditorWindow.py, FormatParagraph.py, UndoDelegator.py:
Tim Peters writes:
I'm still unsure, but couldn't stand the virtual event trickery so tried a
different sin (adding undo_block_start/stop methods to the Text instance in
EditorWindow.py). Like it or not, it's efficient and works <wink>. Better
idea?
Give the attached a whirl. Even if you hate the implementation, I think
you'll like the results. Think I caught all the "block edit" cmds,
including Format Paragraph, plus subtler ones involving smart indents and
backspacing.
* WidgetRedirector.py: Tim Peters writes:
[W]hile trying to dope out how redirection works, stumbled into two
possible glitches. In the first, it doesn't appear to make sense to try to
rename a command that's already been destroyed; in the second, the name
"previous" doesn't really bring to mind "ignore the previous value" <wink>.
Fri Apr 30 19:39:25 1999 Guido van Rossum <[email protected]>
* __init__.py: Support for using idle as a package.
* PathBrowser.py:
Avoid listing files more than once (e.g. foomodule.so has two hits:
once for foo + module.so, once for foomodule + .so).
Mon Apr 26 22:20:38 1999 Guido van Rossum <[email protected]>
* ChangeLog, ColorDelegator.py, PyShell.py: Tim Peters strikes again:
Ho ho ho -- that's trickier than it sounded! The colorizer is working with
"line.col" strings instead of Text marks, and the absolute coordinates of
the point of interest can change across the self.update call (voice of
baffled experience, when two quick backspaces no longer fooled it, but a
backspace followed by a quick ENTER did <wink>).
Anyway, the attached appears to do the trick. CPU usage goes way up when
typing quickly into a long triple-quoted string, but the latency is fine for
me (a relatively fast typist on a relatively slow machine). Most of the
changes here are left over from reducing the # of vrbl names to help me
reason about the logic better; I hope the code is a *little* easier to
Fri Apr 23 14:01:25 1999 Guido van Rossum <[email protected]>
* EditorWindow.py:
Provide full arguments to __import__ so it works in packagized IDLE.
Thu Apr 22 23:20:17 1999 Guido van Rossum <[email protected]>
* help.txt:
Bunch of updates necessary due to recent changes; added docs for File
menu, command line and color preferences.
* Bindings.py: Remove obsolete 'script' menu.
* TODO.txt: Several wishes fulfilled.
* OutputWindow.py:
Moved classes OnDemandOutputWindow and PseudoFile here,
from ScriptBinding.py where they are no longer needed.
* ScriptBinding.py:
Mostly rewritten. Instead of the old Run module and Debug module,
there are two new commands:
Import module (F5) imports or reloads the module and also adds its
name to the __main__ namespace. This gets executed in the PyShell
window under control of its debug settings.
Run script (Control-F5) is similar but executes the contents of the
file directly in the __main__ namespace.
* PyShell.py: Nits: document use of $IDLESTARTUP; display idle version
* idlever.py: New version to celebrate new command line
* OutputWindow.py: Added flush(), for completeness.
* PyShell.py:
A lot of changes to make the command line more useful. You can now do:
idle.py -e file ... -- to edit files
idle.py script arg ... -- to run a script
idle.py -c cmd arg ... -- to run a command
Other options, see also the usage message (also new!) for more details:
-d -- enable debugger
-s -- run $IDLESTARTUP or $PYTHONSTARTUP
-t title -- set Python Shell window's title
sys.argv is set accordingly, unless -e is used.
sys.path is absolutized, and all relevant paths are inserted into it.
Other changes:
- the environment in which commands are executed is now the
__main__ module
- explicitly save sys.stdout etc., don't restore from sys.__stdout__
- new interpreter methods execsource(), execfile(), stuffsource()
- a few small nits
* TODO.txt:
Some more TODO items. Made up my mind about command line args,
Run/Import, __main__.
* ColorDelegator.py:
Super-elegant patch by Tim Peters that speeds up colorization
dramatically (up to 15 times he claims). Works by reading more than
one line at a time, up to 100-line chunks (starting with one line and
then doubling up to the limit). On a typical machine (e.g. Tim's
P5-166) this doesn't reduce interactive responsiveness in a noticeable
way.
Wed Apr 21 15:49:34 1999 Guido van Rossum <[email protected]>
* ColorDelegator.py:
Patch by Tim Peters to speed up colorizing of big multiline strings.
Tue Apr 20 17:32:52 1999 Guido van Rossum <[email protected]>
* extend.txt:
For an event 'foo-bar', the corresponding method must be called
foo_bar_event(). Therefore, fix the references to zoom_height() in
the example.
* IdlePrefs.py: Restored the original IDLE color scheme.
* PyShell.py, IdlePrefs.py, ColorDelegator.py, EditorWindow.py:
Color preferences code by Loren Luke (massaged by me somewhat)
* SearchEngine.py:
Patch by Mark Favas: it fixes the search engine behaviour where an
unsuccessful search wraps around and re-searches that part of the file
between the start of the search and the end of the file - only really
an issue for very large files, but... (also removes a redundant
m.span() call).
Mon Apr 19 16:26:02 1999 Guido van Rossum <[email protected]>
* TODO.txt: A few wishes are now fulfilled.
* AutoIndent.py: Tim Peters implements some of my wishes:
o Makes the tab key intelligently insert spaces when appropriate
(see Help list banter twixt David Ascher and me; idea stolen from
every other editor on earth <wink>).
o newline_and_indent_event trims trailing whitespace on the old
line (pymode and Codewright).
o newline_and_indent_event no longer fooled by trailing whitespace or
comment after ":" (pymode, PTUI).
o newline_and_indent_event now reduces the new line's indentation after
return, break, continue, raise and pass stmts (pymode).
The last two are easy to fool in the presence of strings &
continuations, but pymode requires Emacs's high-powered C parsing
functions to avoid that in finite time.
======================================================================
Python release 1.5.2c1, IDLE version 0.4
======================================================================
Wed Apr 7 18:41:59 1999 Guido van Rossum <[email protected]>
* README.txt, NEWS.txt: New version.
* idlever.py: Version bump awaiting impending new release.
(Not much has changed :-( )
Mon Mar 29 14:52:28 1999 Guido van Rossum <[email protected]>
* ScriptBinding.py, PyShell.py:
At Tim Peters' recommendation, add a dummy flush() method to
PseudoFile.
Thu Mar 11 23:21:23 1999 Guido van Rossum <[email protected]>
* PathBrowser.py: Don't crash when sys.path contains an empty string.
* Attic/Outline.py: This file was never supposed to be part of IDLE.
* PathBrowser.py:
- Don't crash in the case where a superclass is a string instead of a
pyclbr.Class object; this can happen when the superclass is
unrecognizable (to pyclbr), e.g. when module renaming is used.
- Show a watch cursor when calling pyclbr (since it may take a while
recursively parsing imported modules!).
Wed Mar 10 05:18:02 1999 Guido van Rossum <[email protected]>
* EditorWindow.py, Bindings.py: Add PathBrowser to File module
* PathBrowser.py: "Path browser" - 4 scrolled lists displaying:
directories on sys.path
modules in selected directory
classes in selected module
methods of selected class
Sinlge clicking in a directory, module or class item updates the next
column with info about the selected item. Double clicking in a
module, class or method item opens the file (and selects the clicked
item if it is a class or method).
I guess eventually I should be using a tree widget for this, but the
ones I've seen don't work well enough, so for now I use the old
Smalltalk or NeXT style multi-column hierarchical browser.
* MultiScrolledLists.py:
New utility: multiple scrolled lists in parallel
* ScrolledList.py: - White background.
- Display "(None)" (or text of your choosing) when empty.
- Don't set the focus.
======================================================================
Python release 1.5.2b2, IDLE version 0.3
======================================================================
Wed Feb 17 22:47:41 1999 Guido van Rossum <[email protected]>
* NEWS.txt: News in 0.3.
* README.txt, idlever.py: Bump version to 0.3.
* EditorWindow.py:
After all, we don't need to call the callbacks ourselves!
* WindowList.py:
When deleting, call the callbacks *after* deleting the window from our list!
* EditorWindow.py:
Fix up the Windows menu via the new callback mechanism instead of
depending on menu post commands (which don't work when the menu is
torn off).
* WindowList.py:
Support callbacks to patch up Windows menus everywhere.
* ChangeLog: Oh, why not. Checking in the Emacs-generated change log.
Tue Feb 16 22:34:17 1999 Guido van Rossum <[email protected]>
* ScriptBinding.py:
Only pop up the stack viewer when requested in the Debug menu.
Mon Feb 8 22:27:49 1999 Guido van Rossum <[email protected]>
* WindowList.py: Don't crash if a window no longer exists.
* TODO.txt: Restructured a bit.
Mon Feb 1 23:06:17 1999 Guido van Rossum <[email protected]>
* PyShell.py: Add current dir or paths of file args to sys.path.
* Debugger.py: Add canonic() function -- for brand new bdb.py feature.
* StackViewer.py: Protect against accessing an empty stack.
Fri Jan 29 20:44:45 1999 Guido van Rossum <[email protected]>
* ZoomHeight.py:
Use only the height to decide whether to zoom in or out.
Thu Jan 28 22:24:30 1999 Guido van Rossum <[email protected]>
* EditorWindow.py, FileList.py:
Make sure the Tcl variables are shared between windows.
* PyShell.py, EditorWindow.py, Bindings.py:
Move menu/key binding code from Bindings.py to EditorWindow.py,
with changed APIs -- it makes much more sense there.
Also add a new feature: if the first character of a menu label is
a '!', it gets a checkbox. Checkboxes are bound to Boolean Tcl variables
that can be accessed through the new getvar/setvar/getrawvar API;
the variable is named after the event to which the menu is bound.
* Debugger.py: Add Quit button to the debugger window.
* SearchDialog.py:
When find_again() finds exactly the current selection, it's a failure.
* idle.py, Attic/idle: Rename idle -> idle.py
Mon Jan 18 15:18:57 1999 Guido van Rossum <[email protected]>
* EditorWindow.py, WindowList.py: Only deiconify when iconic.
* TODO.txt: Misc
Tue Jan 12 22:14:34 1999 Guido van Rossum <[email protected]>
* testcode.py, Attic/test.py:
Renamed test.py to testcode.py so one can import Python's
test package from inside IDLE. (Suggested by Jack Jansen.)
* EditorWindow.py, ColorDelegator.py:
Hack to close a window that is colorizing.
* Separator.py: Vladimir Marangozov's patch:
The separator dances too much and seems to jump by arbitrary amounts
in arbitrary directions when I try to move it for resizing the frames.
This patch makes it more quiet.
Mon Jan 11 14:52:40 1999 Guido van Rossum <[email protected]>
* TODO.txt: Some requests have been fulfilled.
* EditorWindow.py:
Set the cursor to a watch when opening the class browser (which may
take quite a while, browsing multiple files).
Newer, better center() -- but assumes no wrapping.
* SearchBinding.py:
Got rid of debug print statement in goto_line_event().
* ScriptBinding.py:
I think I like it better if it prints the traceback even when it displays
the stack viewer.
* Debugger.py: Bind ESC to close-window.
* ClassBrowser.py: Use a HSeparator between the classes and the items.
Make the list of classes wider by default (40 chars).
Bind ESC to close-window.
* Separator.py:
Separator classes (draggable divider between two panes).
Sat Jan 9 22:01:33 1999 Guido van Rossum <[email protected]>
* WindowList.py:
Don't traceback when wakeup() is called when the window has been destroyed.
This can happen when a torn-of Windows menu references closed windows.
And Tim Peters claims that the Windows menu is his favorite to tear off...
* EditorWindow.py: Allow tearing off of the Windows menu.
* StackViewer.py: Close on ESC.
* help.txt: Updated a bunch of things (it was mostly still 0.1!)
* extend.py: Added ScriptBinding to standard bindings.
* ScriptBinding.py:
This now actually works. See doc string. It can run a module (i.e.
import or reload) or debug it (same with debugger control). Output
goes to a fresh output window, only created when needed.
======================================================================
Python release 1.5.2b1, IDLE version 0.2
======================================================================
Fri Jan 8 17:26:02 1999 Guido van Rossum <[email protected]>
* README.txt, NEWS.txt: What's new in this release.
* Bindings.py, PyShell.py:
Paul Prescod's patches to allow the stack viewer to pop up when a
traceback is printed.
Thu Jan 7 00:12:15 1999 Guido van Rossum <[email protected]>
* FormatParagraph.py:
Change paragraph width limit to 70 (like Emacs M-Q).
* README.txt:
Separating TODO from README. Slight reformulation of features. No
exact release date.
* TODO.txt: Separating TODO from README.
Mon Jan 4 21:19:09 1999 Guido van Rossum <[email protected]>
* FormatParagraph.py:
Hm. There was a boundary condition error at the end of the file too.
* SearchBinding.py: Hm. Add Unix binding for replace, too.
* keydefs.py: Ran eventparse.py again.
* FormatParagraph.py: Added Unix Meta-q key binding;
fix find_paragraph when at start of file.
* AutoExpand.py: Added Meta-/ binding for Unix as alt for Alt-/.
* SearchBinding.py:
Add unix binding for grep (otherwise the menu entry doesn't work!)
* ZoomHeight.py: Adjusted Unix height to work with fvwm96. :=(
* GrepDialog.py: Need to import sys!
* help.txt, extend.txt, README.txt: Formatted some paragraphs
* extend.py, FormatParagraph.py:
Add new extension to reformat a (text) paragraph.
* ZoomHeight.py: Typo in Win specific height setting.
Sun Jan 3 00:47:35 1999 Guido van Rossum <[email protected]>
* AutoIndent.py: Added something like Tim Peters' backspace patch.
* ZoomHeight.py: Adapted to Unix (i.e., more hardcoded constants).
Sat Jan 2 21:28:54 1999 Guido van Rossum <[email protected]>
* keydefs.py, idlever.py, idle.pyw, idle.bat, help.txt, extend.txt, extend.py, eventparse.py, ZoomHeight.py, WindowList.py, UndoDelegator.py, StackViewer.py, SearchEngine.py, SearchDialogBase.py, SearchDialog.py, ScrolledList.py, SearchBinding.py, ScriptBinding.py, ReplaceDialog.py, Attic/README, README.txt, PyShell.py, Attic/PopupMenu.py, OutputWindow.py, IOBinding.py, Attic/HelpWindow.py, History.py, GrepDialog.py, FileList.py, FrameViewer.py, EditorWindow.py, Debugger.py, Delegator.py, ColorDelegator.py, Bindings.py, ClassBrowser.py, AutoExpand.py, AutoIndent.py:
Checking in IDLE 0.2.
Much has changed -- too much, in fact, to write down.
The big news is that there's a standard way to write IDLE extensions;
see extend.txt. Some sample extensions have been provided, and
some existing code has been converted to extensions. Probably the
biggest new user feature is a new search dialog with more options,
search and replace, and even search in files (grep).
This is exactly as downloaded from my laptop after returning
from the holidays -- it hasn't even been tested on Unix yet.
Fri Dec 18 15:52:54 1998 Guido van Rossum <[email protected]>
* FileList.py, ClassBrowser.py:
Fix the class browser to work even when the file is not on sys.path.
Tue Dec 8 20:39:36 1998 Guido van Rossum <[email protected]>
* Attic/turtle.py: Moved to Python 1.5.2/Lib
Fri Nov 27 03:19:20 1998 Guido van Rossum <[email protected]>
* help.txt: Typo
* EditorWindow.py, FileList.py: Support underlining of menu labels
* Bindings.py:
New approach, separate tables for menus (platform-independent) and key
definitions (platform-specific), and generating accelerator strings
automatically from the key definitions.
Mon Nov 16 18:37:42 1998 Guido van Rossum <[email protected]>
* Attic/README: Clarify portability and main program.
* Attic/README: Added intro for 0.1 release and append Grail notes.
Mon Oct 26 18:49:00 1998 Guido van Rossum <[email protected]>
* Attic/turtle.py: root is now a global called _root
Sat Oct 24 16:38:38 1998 Guido van Rossum <[email protected]>
* Attic/turtle.py: Raise the root window on reset().
Different action on WM_DELETE_WINDOW is more likely to do the right thing,
allowing us to destroy old windows.
* Attic/turtle.py:
Split the goto() function in two: _goto() is the internal one,
using Canvas coordinates, and goto() uses turtle coordinates
and accepts variable argument lists.
* Attic/turtle.py: Cope with destruction of the window
* Attic/turtle.py: Turtle graphics
* Debugger.py: Use of Breakpoint class should be bdb.Breakpoint.
Mon Oct 19 03:33:40 1998 Guido van Rossum <[email protected]>
* SearchBinding.py:
Speed up the search a bit -- don't drag a mark around...
* PyShell.py:
Change our special entries from <console#N> to <pyshell#N>.
Patch linecache.checkcache() to keep our special entries alive.
Add popup menu to all editor windows to set a breakpoint.
* Debugger.py:
Use and pass through the 'force' flag to set_dict() where appropriate.
Default source and globals checkboxes to false.
Don't interact in user_return().
Add primitive set_breakpoint() method.
* ColorDelegator.py:
Raise priority of 'sel' tag so its foreground (on Windows) will take
priority over text colorization (which on Windows is almost the
same color as the selection background).
Define a tag and color for breakpoints ("BREAK").
* Attic/PopupMenu.py: Disable "Open stack viewer" and "help" commands.
* StackViewer.py:
Add optional 'force' argument (default 0) to load_dict().
If set, redo the display even if it's the same dict.
Fri Oct 16 21:10:12 1998 Guido van Rossum <[email protected]>
* StackViewer.py: Do nothing when loading the same dict as before.
* PyShell.py: Details for debugger interface.
* Debugger.py:
Restructured and more consistent. Save checkboxes across instantiations.
* EditorWindow.py, Attic/README, Bindings.py:
Get rid of conflicting ^X binding. Use ^W.
* Debugger.py, StackViewer.py:
Debugger can now show local and global variables.
* Debugger.py: Oops
* Debugger.py, PyShell.py: Better debugger support (show stack etc).
* Attic/PopupMenu.py: Follow renames in StackViewer module
* StackViewer.py:
Rename classes to StackViewer (the widget) and StackBrowser (the toplevel).
* ScrolledList.py: Add close() method
* EditorWindow.py: Clarify 'Open Module' dialog text
* StackViewer.py: Restructured into a browser and a widget.
Thu Oct 15 23:27:08 1998 Guido van Rossum <[email protected]>
* ClassBrowser.py, ScrolledList.py:
Generalized the scrolled list which is the base for the class and
method browser into a separate class in its own module.
* Attic/test.py: Cosmetic change
* Debugger.py: Don't show function name if there is none
Wed Oct 14 03:43:05 1998 Guido van Rossum <[email protected]>
* Debugger.py, PyShell.py: Polish the Debugger GUI a bit.
Closing it now also does the right thing.
Tue Oct 13 23:51:13 1998 Guido van Rossum <[email protected]>
* Debugger.py, PyShell.py, Bindings.py:
Ad primitive debugger interface (so far it will step and show you the
source, but it doesn't yet show the stack).
* Attic/README: Misc
* StackViewer.py: Whoops -- referenced self.top before it was set.
* help.txt: Added history and completion commands.
* help.txt: Updated
* FileList.py: Add class browser functionality.
* StackViewer.py:
Add a close() method and bind to WM_DELETE_WINDOW protocol
* PyShell.py: Clear the linecache before printing a traceback
* Bindings.py: Added class browser binding.
* ClassBrowser.py: Much improved, much left to do.
* PyShell.py: Make the return key do what I mean more often.
* ClassBrowser.py:
Adding the beginnings of a Class browser. Incomplete, yet.
* EditorWindow.py, Bindings.py:
Add new command, "Open module". You select or type a module name,
and it opens the source.
Mon Oct 12 23:59:27 1998 Guido van Rossum <[email protected]>
* PyShell.py: Subsume functionality from Popup menu in Debug menu.
Other stuff so the PyShell window can be resurrected from the Windows menu.
* FileList.py: Get rid of PopUp menu.
Create a simple Windows menu. (Imperfect when Untitled windows exist.)
Add wakeup() method: deiconify, raise, focus.
* EditorWindow.py: Generalize menu creation.
* Bindings.py: Add Debug and Help menu items.
* EditorWindow.py: Added a menu bar to every window.
* Bindings.py: Add menu configuration to the event configuration.
* Attic/PopupMenu.py: Pass a root to the help window.
* SearchBinding.py:
Add parent argument to 'go to line number' dialog box.
Sat Oct 10 19:15:32 1998 Guido van Rossum <[email protected]>
* StackViewer.py:
Add a label at the top showing (very basic) help for the stack viewer.
Add a label at the bottom showing the exception info.
* Attic/test.py, Attic/idle: Add Unix main script and test program.
* idle.pyw, help.txt, WidgetRedirector.py, UndoDelegator.py, StackViewer.py, SearchBinding.py, Attic/README, PyShell.py, Attic/PopupMenu.py, Percolator.py, Outline.py, IOBinding.py, History.py, Attic/HelpWindow.py, FrameViewer.py, FileList.py, EditorWindow.py, Delegator.py, ColorDelegator.py, Bindings.py, AutoIndent.py, AutoExpand.py:
Initial checking of Tk-based Python IDE.
Features: text editor with syntax coloring and undo;
subclassed into interactive Python shell which adds history.
| 56,360 | 1,592 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/config-extensions.def | # config-extensions.def
#
# The following sections are for features that are no longer extensions.
# Their options values are left here for back-compatibility.
[AutoComplete]
popupwait= 2000
[CodeContext]
maxlines= 15
[FormatParagraph]
max-width= 72
[ParenMatch]
style= expression
flash-delay= 500
bell= True
# IDLE reads several config files to determine user preferences. This
# file is the default configuration file for IDLE extensions settings.
#
# Each extension must have at least one section, named after the
# extension module. This section must contain an 'enable' item (=True to
# enable the extension, =False to disable it), it may contain
# 'enable_editor' or 'enable_shell' items, to apply it only to editor ir
# shell windows, and may also contain any other general configuration
# items for the extension. Other True/False values will also be
# recognized as boolean by the Extension Configuration dialog.
#
# Each extension must define at least one section named
# ExtensionName_bindings or ExtensionName_cfgBindings. If present,
# ExtensionName_bindings defines virtual event bindings for the
# extension that are not user re-configurable. If present,
# ExtensionName_cfgBindings defines virtual event bindings for the
# extension that may be sensibly re-configured.
#
# If there are no keybindings for a menus' virtual events, include lines
# like <<toggle-code-context>>=.
#
# Currently it is necessary to manually modify this file to change
# extension key bindings and default values. To customize, create
# ~/.idlerc/config-extensions.cfg and append the appropriate customized
# section(s). Those sections will override the defaults in this file.
#
# Note: If a keybinding is already in use when the extension is loaded,
# the extension's virtual event's keybinding will be set to ''.
#
# See config-keys.def for notes on specifying keys and extend.txt for
# information on creating IDLE extensions.
# A fake extension for testing and example purposes. When enabled and
# invoked, inserts or deletes z-text at beginning of every line.
[ZzDummy]
enable= False
enable_shell = False
enable_editor = True
z-text= Z
[ZzDummy_cfgBindings]
z-in= <Control-Shift-KeyRelease-Insert>
[ZzDummy_bindings]
z-out= <Control-Shift-KeyRelease-Delete>
| 2,266 | 63 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/grep.py | """Grep dialog for Find in Files functionality.
Inherits from SearchDialogBase for GUI and uses searchengine
to prepare search pattern.
"""
import fnmatch
import os
import sys
from tkinter import StringVar, BooleanVar
from tkinter.ttk import Checkbutton
from idlelib.searchbase import SearchDialogBase
from idlelib import searchengine
# Importing OutputWindow here fails due to import loop
# EditorWindow -> GrepDialop -> OutputWindow -> EditorWindow
def grep(text, io=None, flist=None):
"""Create or find singleton GrepDialog instance.
Args:
text: Text widget that contains the selected text for
default search phrase.
io: iomenu.IOBinding instance with default path to search.
flist: filelist.FileList instance for OutputWindow parent.
"""
root = text._root()
engine = searchengine.get(root)
if not hasattr(engine, "_grepdialog"):
engine._grepdialog = GrepDialog(root, engine, flist)
dialog = engine._grepdialog
searchphrase = text.get("sel.first", "sel.last")
dialog.open(text, searchphrase, io)
class GrepDialog(SearchDialogBase):
"Dialog for searching multiple files."
title = "Find in Files Dialog"
icon = "Grep"
needwrapbutton = 0
def __init__(self, root, engine, flist):
"""Create search dialog for searching for a phrase in the file system.
Uses SearchDialogBase as the basis for the GUI and a
searchengine instance to prepare the search.
Attributes:
globvar: Value of Text Entry widget for path to search.
recvar: Boolean value of Checkbutton widget
for traversing through subdirectories.
"""
SearchDialogBase.__init__(self, root, engine)
self.flist = flist
self.globvar = StringVar(root)
self.recvar = BooleanVar(root)
def open(self, text, searchphrase, io=None):
"Make dialog visible on top of others and ready to use."
SearchDialogBase.open(self, text, searchphrase)
if io:
path = io.filename or ""
else:
path = ""
dir, base = os.path.split(path)
head, tail = os.path.splitext(base)
if not tail:
tail = ".py"
self.globvar.set(os.path.join(dir, "*" + tail))
def create_entries(self):
"Create base entry widgets and add widget for search path."
SearchDialogBase.create_entries(self)
self.globent = self.make_entry("In files:", self.globvar)[0]
def create_other_buttons(self):
"Add check button to recurse down subdirectories."
btn = Checkbutton(
self.make_frame()[0], variable=self.recvar,
text="Recurse down subdirectories")
btn.pack(side="top", fill="both")
def create_command_buttons(self):
"Create base command buttons and add button for search."
SearchDialogBase.create_command_buttons(self)
self.make_button("Search Files", self.default_command, 1)
def default_command(self, event=None):
"""Grep for search pattern in file path. The default command is bound
to <Return>.
If entry values are populated, set OutputWindow as stdout
and perform search. The search dialog is closed automatically
when the search begins.
"""
prog = self.engine.getprog()
if not prog:
return
path = self.globvar.get()
if not path:
self.top.bell()
return
from idlelib.outwin import OutputWindow # leave here!
save = sys.stdout
try:
sys.stdout = OutputWindow(self.flist)
self.grep_it(prog, path)
finally:
sys.stdout = save
def grep_it(self, prog, path):
"""Search for prog within the lines of the files in path.
For the each file in the path directory, open the file and
search each line for the matching pattern. If the pattern is
found, write the file and line information to stdout (which
is an OutputWindow).
"""
dir, base = os.path.split(path)
list = self.findfiles(dir, base, self.recvar.get())
list.sort()
self.close()
pat = self.engine.getpat()
print(f"Searching {pat!r} in {path} ...")
hits = 0
try:
for fn in list:
try:
with open(fn, errors='replace') as f:
for lineno, line in enumerate(f, 1):
if line[-1:] == '\n':
line = line[:-1]
if prog.search(line):
sys.stdout.write(f"{fn}: {lineno}: {line}\n")
hits += 1
except OSError as msg:
print(msg)
print(f"Hits found: {hits}\n(Hint: right-click to open locations.)"
if hits else "No hits.")
except AttributeError:
# Tk window has been closed, OutputWindow.text = None,
# so in OW.write, OW.text.insert fails.
pass
def findfiles(self, dir, base, rec):
"""Return list of files in the dir that match the base pattern.
If rec is True, recursively iterate through subdirectories.
"""
try:
names = os.listdir(dir or os.curdir)
except OSError as msg:
print(msg)
return []
list = []
subdirs = []
for name in names:
fn = os.path.join(dir, name)
if os.path.isdir(fn):
subdirs.append(fn)
else:
if fnmatch.fnmatch(name, base):
list.append(fn)
if rec:
for subdir in subdirs:
list.extend(self.findfiles(subdir, base, rec))
return list
def _grep_dialog(parent): # htest #
from tkinter import Toplevel, Text, SEL, END
from tkinter.ttk import Button
from idlelib.pyshell import PyShellFileList
top = Toplevel(parent)
top.title("Test GrepDialog")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry(f"+{x}+{y + 175}")
flist = PyShellFileList(top)
text = Text(top, height=5)
text.pack()
def show_grep_dialog():
text.tag_add(SEL, "1.0", END)
grep(text, flist=flist)
text.tag_remove(SEL, "1.0", END)
button = Button(top, text="Show GrepDialog", command=show_grep_dialog)
button.pack()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_grep', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_grep_dialog)
| 6,742 | 201 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/percolator.py | from idlelib.delegator import Delegator
from idlelib.redirector import WidgetRedirector
class Percolator:
def __init__(self, text):
# XXX would be nice to inherit from Delegator
self.text = text
self.redir = WidgetRedirector(text)
self.top = self.bottom = Delegator(text)
self.bottom.insert = self.redir.register("insert", self.insert)
self.bottom.delete = self.redir.register("delete", self.delete)
self.filters = []
def close(self):
while self.top is not self.bottom:
self.removefilter(self.top)
self.top = None
self.bottom.setdelegate(None)
self.bottom = None
self.redir.close()
self.redir = None
self.text = None
def insert(self, index, chars, tags=None):
# Could go away if inheriting from Delegator
self.top.insert(index, chars, tags)
def delete(self, index1, index2=None):
# Could go away if inheriting from Delegator
self.top.delete(index1, index2)
def insertfilter(self, filter):
# Perhaps rename to pushfilter()?
assert isinstance(filter, Delegator)
assert filter.delegate is None
filter.setdelegate(self.top)
self.top = filter
def removefilter(self, filter):
# XXX Perhaps should only support popfilter()?
assert isinstance(filter, Delegator)
assert filter.delegate is not None
f = self.top
if f is filter:
self.top = filter.delegate
filter.setdelegate(None)
else:
while f.delegate is not filter:
assert f is not self.bottom
f.resetcache()
f = f.delegate
f.setdelegate(filter.delegate)
filter.setdelegate(None)
def _percolator(parent): # htest #
import tkinter as tk
class Tracer(Delegator):
def __init__(self, name):
self.name = name
Delegator.__init__(self, None)
def insert(self, *args):
print(self.name, ": insert", args)
self.delegate.insert(*args)
def delete(self, *args):
print(self.name, ": delete", args)
self.delegate.delete(*args)
box = tk.Toplevel(parent)
box.title("Test Percolator")
x, y = map(int, parent.geometry().split('+')[1:])
box.geometry("+%d+%d" % (x, y + 175))
text = tk.Text(box)
p = Percolator(text)
pin = p.insertfilter
pout = p.removefilter
t1 = Tracer("t1")
t2 = Tracer("t2")
def toggle1():
(pin if var1.get() else pout)(t1)
def toggle2():
(pin if var2.get() else pout)(t2)
text.pack()
var1 = tk.IntVar(parent)
cb1 = tk.Checkbutton(box, text="Tracer1", command=toggle1, variable=var1)
cb1.pack()
var2 = tk.IntVar(parent)
cb2 = tk.Checkbutton(box, text="Tracer2", command=toggle2, variable=var2)
cb2.pack()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_percolator', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_percolator)
| 3,130 | 104 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/replace.py | """Replace dialog for IDLE. Inherits SearchDialogBase for GUI.
Uses idlelib.SearchEngine for search capability.
Defines various replace related functions like replace, replace all,
replace+find.
"""
import re
from tkinter import StringVar, TclError
from idlelib.searchbase import SearchDialogBase
from idlelib import searchengine
def replace(text):
"""Returns a singleton ReplaceDialog instance.The single dialog
saves user entries and preferences across instances."""
root = text._root()
engine = searchengine.get(root)
if not hasattr(engine, "_replacedialog"):
engine._replacedialog = ReplaceDialog(root, engine)
dialog = engine._replacedialog
dialog.open(text)
class ReplaceDialog(SearchDialogBase):
title = "Replace Dialog"
icon = "Replace"
def __init__(self, root, engine):
SearchDialogBase.__init__(self, root, engine)
self.replvar = StringVar(root)
def open(self, text):
"""Display the replace dialog"""
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 = 1
def create_entries(self):
"""Create label and text entry widgets"""
SearchDialogBase.create_entries(self)
self.replent = self.make_entry("Replace with:", self.replvar)[0]
def create_command_buttons(self):
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, 1)
self.make_button("Replace All", self.replace_all)
def find_it(self, event=None):
self.do_find(0)
def replace_it(self, event=None):
if self.do_find(self.ok):
self.do_replace()
def default_command(self, event=None):
"Replace and 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(0)
def _replace_expand(self, m, repl):
""" Helper function for expanding a regular expression
in the replace field, if needed. """
if self.engine.isre():
try:
new = m.expand(repl)
except re.error:
self.engine.report_error(repl, 'Invalid Replace Expression')
new = None
else:
new = repl
return new
def replace_all(self, event=None):
"""Replace all instances of patvar with replvar in 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 = 1
first = last = None
# XXX ought to replace circular instead of top-to-bottom when wrapping
text.undo_block_start()
while 1:
res = self.engine.search_forward(text, prog, line, col, 0, 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 = 0
text.undo_block_stop()
if first and last:
self.show_hit(first, last)
self.close()
def do_find(self, ok=0):
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 = 1
return True
def do_replace(self):
prog = self.engine.getprog()
if not prog:
return False
text = self.text
try:
first = pos = text.index("sel.first")
last = text.index("sel.last")
except TclError:
pos = None
if not pos:
first = last = pos = text.index("insert")
line, col = searchengine.get_line_col(pos)
chars = text.get("%d.0" % line, "%d.0" % (line+1))
m = prog.match(chars, col)
if not prog:
return False
new = self._replace_expand(m, self.replvar.get())
if new is None:
return False
text.mark_set("insert", first)
text.undo_block_start()
if m.group():
text.delete(first, last)
if new:
text.insert(first, new)
text.undo_block_stop()
self.show_hit(first, text.index("insert"))
self.ok = 0
return True
def show_hit(self, first, last):
"""Highlight text from 'first' to 'last'.
'first', 'last' - Text indices"""
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()
def close(self, event=None):
SearchDialogBase.close(self, event)
self.text.tag_remove("hit", "1.0", "end")
def _replace_dialog(parent): # htest #
from tkinter import Toplevel, Text, END, SEL
from tkinter.ttk import Button
box = Toplevel(parent)
box.title("Test ReplaceDialog")
x, y = map(int, parent.geometry().split('+')[1:])
box.geometry("+%d+%d" % (x, y + 175))
# mock undo delegator methods
def undo_block_start():
pass
def undo_block_stop():
pass
text = Text(box, inactiveselectbackground='gray')
text.undo_block_start = undo_block_start
text.undo_block_stop = undo_block_stop
text.pack()
text.insert("insert","This is a sample sTring\nPlus MORE.")
text.focus_set()
def show_replace():
text.tag_add(SEL, "1.0", END)
replace(text)
text.tag_remove(SEL, "1.0", END)
button = Button(box, text="Replace", command=show_replace)
button.pack()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_replace', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_replace_dialog)
| 7,502 | 243 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/redirector.py | from tkinter import TclError
class WidgetRedirector:
"""Support for redirecting arbitrary widget subcommands.
Some Tk operations don't normally pass through tkinter. For example, if a
character is inserted into a Text widget by pressing a key, a default Tk
binding to the widget's 'insert' operation is activated, and the Tk library
processes the insert without calling back into tkinter.
Although a binding to <Key> could be made via tkinter, what we really want
to do is to hook the Tk 'insert' operation itself. For one thing, we want
a text.insert call in idle code to have the same effect as a key press.
When a widget is instantiated, a Tcl command is created whose name is the
same as the pathname widget._w. This command is used to invoke the various
widget operations, e.g. insert (for a Text widget). We are going to hook
this command and provide a facility ('register') to intercept the widget
operation. We will also intercept method calls on the tkinter class
instance that represents the tk widget.
In IDLE, WidgetRedirector is used in Percolator to intercept Text
commands. The function being registered provides access to the top
of a Percolator chain. At the bottom of the chain is a call to the
original Tk widget operation.
"""
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)
def __repr__(self):
return "%s(%s<%s>)" % (self.__class__.__name__,
self.widget.__class__.__name__,
self.widget._w)
def close(self):
"Unregister operations and revert redirection created by .__init__."
for operation in list(self._operations):
self.unregister(operation)
widget = self.widget
tk = widget.tk
w = widget._w
# Restore the original widget Tcl command.
tk.deletecommand(w)
tk.call("rename", self.orig, w)
del self.widget, self.tk # Should not be needed
# if instance is deleted after close, as in Percolator.
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)
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
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 ""
class OriginalCommand:
'''Callable for original tk command that has been redirected.
Returned by .register; can be used in the function registered.
redir = WidgetRedirector(text)
def my_insert(*args):
print("insert", args)
original_insert(*args)
original_insert = redir.register("insert", my_insert)
'''
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)
def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__,
self.redir, self.operation)
def __call__(self, *args):
return self.tk_call(self.orig_and_operation + args)
def _widget_redirector(parent): # htest #
from tkinter import Toplevel, Text
top = Toplevel(parent)
top.title("Test WidgetRedirector")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" % (x, y + 175))
text = Text(top)
text.pack()
text.focus_set()
redir = WidgetRedirector(text)
def my_insert(*args):
print("insert", args)
original_insert(*args)
original_insert = redir.register("insert", my_insert)
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_redirector', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_widget_redirector)
| 6,875 | 175 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/outwin.py | """Editor window that can serve as an output file.
"""
import re
from tkinter import messagebox
from idlelib.editor import EditorWindow
from idlelib import iomenu
file_line_pats = [
# order of patterns matters
r'file "([^"]*)", line (\d+)',
r'([^\s]+)\((\d+)\)',
r'^(\s*\S.*?):\s*(\d+):', # Win filename, maybe starting with spaces
r'([^\s]+):\s*(\d+):', # filename or path, ltrim
r'^\s*(\S.*?):\s*(\d+):', # Win abs path with embedded spaces, ltrim
]
file_line_progs = None
def compile_progs():
"Compile the patterns for matching to file name and line number."
global file_line_progs
file_line_progs = [re.compile(pat, re.IGNORECASE)
for pat in file_line_pats]
def file_line_helper(line):
"""Extract file name and line number from line of text.
Check if line of text contains one of the file/line patterns.
If it does and if the file and line are valid, return
a tuple of the file name and line number. If it doesn't match
or if the file or line is invalid, return None.
"""
if not file_line_progs:
compile_progs()
for prog in file_line_progs:
match = prog.search(line)
if match:
filename, lineno = match.group(1, 2)
try:
f = open(filename, "r")
f.close()
break
except OSError:
continue
else:
return None
try:
return filename, int(lineno)
except TypeError:
return None
class OutputWindow(EditorWindow):
"""An editor window that can serve as an output file.
Also the future base class for the Python shell window.
This class has no input facilities.
Adds binding to open a file at a line to the text widget.
"""
# Our own right-button menu
rmenu_specs = [
("Cut", "<<cut>>", "rmenu_check_cut"),
("Copy", "<<copy>>", "rmenu_check_copy"),
("Paste", "<<paste>>", "rmenu_check_paste"),
(None, None, None),
("Go to file/line", "<<goto-file-line>>", None),
]
def __init__(self, *args):
EditorWindow.__init__(self, *args)
self.text.bind("<<goto-file-line>>", self.goto_file_line)
self.text.unbind("<<toggle-code-context>>")
# Customize EditorWindow
def ispythonsource(self, filename):
"Python source is only part of output: do not colorize."
return False
def short_title(self):
"Customize EditorWindow title."
return "Output"
def maybesave(self):
"Customize EditorWindow to not display save file messagebox."
return 'yes' if self.get_saved() else 'no'
# Act as output file
def write(self, s, tags=(), mark="insert"):
"""Write text to text widget.
The text is inserted at the given index with the provided
tags. The text widget is then scrolled to make it visible
and updated to display it, giving the effect of seeing each
line as it is added.
Args:
s: Text to insert into text widget.
tags: Tuple of tag strings to apply on the insert.
mark: Index for the insert.
Return:
Length of text inserted.
"""
if isinstance(s, bytes):
s = s.decode(iomenu.encoding, "replace")
self.text.insert(mark, s, tags)
self.text.see(mark)
self.text.update()
return len(s)
def writelines(self, lines):
"Write each item in lines iterable."
for line in lines:
self.write(line)
def flush(self):
"No flushing needed as write() directly writes to widget."
pass
def showerror(self, *args, **kwargs):
messagebox.showerror(*args, **kwargs)
def goto_file_line(self, event=None):
"""Handle request to open file/line.
If the selected or previous line in the output window
contains a file name and line number, then open that file
name in a new window and position on the line number.
Otherwise, display an error messagebox.
"""
line = self.text.get("insert linestart", "insert lineend")
result = file_line_helper(line)
if not result:
# Try the previous line. This is handy e.g. in tracebacks,
# where you tend to right-click on the displayed source line
line = self.text.get("insert -1line linestart",
"insert -1line lineend")
result = file_line_helper(line)
if not result:
self.showerror(
"No special line",
"The line you point at doesn't look like "
"a valid file name followed by a line number.",
parent=self.text)
return
filename, lineno = result
self.flist.gotofileline(filename, lineno)
# These classes are currently not used but might come in handy
class OnDemandOutputWindow:
tagdefs = {
# XXX Should use IdlePrefs.ColorPrefs
"stdout": {"foreground": "blue"},
"stderr": {"foreground": "#007700"},
}
def __init__(self, flist):
self.flist = flist
self.owin = None
def write(self, s, tags, mark):
if not self.owin:
self.setup()
self.owin.write(s, tags, mark)
def setup(self):
self.owin = owin = OutputWindow(self.flist)
text = owin.text
for tag, cnf in self.tagdefs.items():
if cnf:
text.tag_configure(tag, **cnf)
text.tag_raise('sel')
self.write = self.owin.write
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_outwin', verbosity=2, exit=False)
| 5,808 | 189 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/__init__.py | """The idlelib package implements the Idle application.
Idle includes an interactive shell and editor.
Starting with Python 3.6, IDLE requires tcl/tk 8.5 or later.
Use the files named idle.* to start Idle.
The other files are private implementations. Their details are subject to
change. See PEP 434 for more. Import them at your own risk.
"""
testing = False # Set True by test.test_idle.
| 396 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/rstrip.py | 'Provides "Strip trailing whitespace" under the "Format" menu.'
class Rstrip:
def __init__(self, editwin):
self.editwin = editwin
def do_rstrip(self, event=None):
text = self.editwin.text
undo = self.editwin.undo
undo.undo_block_start()
end_line = int(float(text.index('end')))
for cur in range(1, end_line):
txt = text.get('%i.0' % cur, '%i.end' % cur)
raw = len(txt)
cut = len(txt.rstrip())
# Since text.delete() marks file as changed, even if not,
# only call it when needed to actually delete something.
if cut < raw:
text.delete('%i.%i' % (cur, cut), '%i.end' % cur)
undo.undo_block_stop()
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_rstrip', verbosity=2,)
| 868 | 30 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/autoexpand.py | '''Complete the current word before the cursor with words in the editor.
Each menu selection or shortcut key selection replaces the word with a
different word with the same prefix. The search for matches begins
before the target and moves toward the top of the editor. It then starts
after the cursor and moves down. It then returns to the original word and
the cycle starts again.
Changing the current text line or leaving the cursor in a different
place before requesting the next selection causes AutoExpand to reset
its state.
There is only one instance of Autoexpand.
'''
import re
import string
class AutoExpand:
wordchars = string.ascii_letters + string.digits + "_"
def __init__(self, editwin):
self.text = editwin.text
self.bell = self.text.bell
self.state = None
def expand_word_event(self, event):
"Replace the current word with the next expansion."
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
if not self.state:
words = self.getwords()
index = 0
else:
words, index, insert, line = self.state
if insert != curinsert or line != curline:
words = self.getwords()
index = 0
if not words:
self.bell()
return "break"
word = self.getprevword()
self.text.delete("insert - %d chars" % len(word), "insert")
newword = words[index]
index = (index + 1) % len(words)
if index == 0:
self.bell() # Warn we cycled around
self.text.insert("insert", newword)
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
self.state = words, index, curinsert, curline
return "break"
def getwords(self):
"Return a list of words that match the prefix before the cursor."
word = self.getprevword()
if not word:
return []
before = self.text.get("1.0", "insert wordstart")
wbefore = re.findall(r"\b" + word + r"\w+\b", before)
del before
after = self.text.get("insert wordend", "end")
wafter = re.findall(r"\b" + word + r"\w+\b", after)
del after
if not wbefore and not wafter:
return []
words = []
dict = {}
# search backwards through words before
wbefore.reverse()
for w in wbefore:
if dict.get(w):
continue
words.append(w)
dict[w] = w
# search onwards through words after
for w in wafter:
if dict.get(w):
continue
words.append(w)
dict[w] = w
words.append(word)
return words
def getprevword(self):
"Return the word prefix before the cursor."
line = self.text.get("insert linestart", "insert")
i = len(line)
while i > 0 and line[i-1] in self.wordchars:
i = i-1
return line[i:]
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_autoexpand', verbosity=2)
| 3,216 | 97 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/statusbar.py | from tkinter import Frame, Label
class MultiStatusBar(Frame):
def __init__(self, master, **kw):
Frame.__init__(self, master, **kw)
self.labels = {}
def set_label(self, name, text='', side='left', width=0):
if name not in self.labels:
label = Label(self, borderwidth=0, anchor='w')
label.pack(side=side, pady=0, padx=4)
self.labels[name] = label
else:
label = self.labels[name]
if width != 0:
label.config(width=width)
label.config(text=text)
def _multistatus_bar(parent): # htest #
from tkinter import Toplevel, Frame, Text, Button
top = Toplevel(parent)
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" %(x, y + 175))
top.title("Test multistatus bar")
frame = Frame(top)
text = Text(frame, height=5, width=40)
text.pack()
msb = MultiStatusBar(frame)
msb.set_label("one", "hello")
msb.set_label("two", "world")
msb.pack(side='bottom', fill='x')
def change():
msb.set_label("one", "foo")
msb.set_label("two", "bar")
button = Button(top, text="Update status", command=change)
button.pack(side='bottom')
frame.pack()
if __name__ == '__main__':
from unittest import main
main('idlelib.idle_test.test_statusbar', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(_multistatus_bar)
| 1,441 | 50 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/openfolder.gif | GIF89a
¢ÿ ÿÿÿÏðððÏÏ` ÀÀÀ !ù ,
@BhJÌú@i !²¬ 8OaèéM Ð4kaã0.Â¥gÁ°+аBCÁèÅl ËãlV»}f»Øl ; | 125 | 3 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/idle_16.gif | GIF89a ÷ Ec}Ed}Fd}Ge}Ed~ÿÃ0ÿÇ4ÿÈ3ÿÊ5ÿÌ7ÿÅ8ÿË?ÿÐ=ÿÑ>ÿÒ@ÿÔBÿ×FÿØGÿÒHÿÛKÿÝMÿÛSÿßSÿàQÿãVÿåXÿçZÿé_ÿë`ÿìaÿíaÿícÿâv?q>s>t =u¢=u£<x©<y«;z>~±Cg
ChGi
BiAkAmEo@nKxI~©=¶G²E»q³¬ ¢¢¢¤¤¤¥¥¥¨¨¨ªªª¬¬¬®®®¯¯¯³³³¶¶¶···¹¹¹»»»½½½¾¾¾¿¿¿ÿàÿâÿôÿì¨ÿñ®ÿò·§ºÊ¤¼Ð¢ÂÞ°ÁСÄàÀÀÀÁÁÁÃÃÃÅÅÅÇÇÇÈÈÈÉÉÉÌÌÌÍÍÍÎÎÎÏÏÏÐÐÐÑÑÑÜÜÜÝÝÝÞÞÞßßßÿôÒÓàêáááâââãããäääåååæææçççèèèéééìììíííîîîÿûëêïóðððñññòòòóóóõõõööö÷÷÷øøøùùùúúúûûûüüüýýýþþþÿÿÿ !ù , ç xåJ,]Z¸ 6}þüP@`Br¦O 3mê¨DrPYĴĦÎBVj!eÐB-j
ê3Ð iB¸`aóP1qéésPJjé¨(dÄ``À O´¨Ôi#k*ä°AÂ}¡qãNS; HòP¡!î8ùÀ
!ÓO )0}ø á0LQ3Ç%IÊQJ$Bf6qn¸
¢A²ñá@P*4XжÆC<¬$¹ç·q<zôÐ ; | 1,034 | 3 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/python.gif | GIF89a öd ë»ë¾!óÁúÇýËÿÌëÂ*ÿÏ#ÿÏ$ÿÐ%ÿÐ&ÿÓ-ýÒ/ÿÓ.ÿÓ/ëÅ4èÇ=ÿÓ0ÿÔ0ýÕ6ÿÖ7úÓ9ÿ×8ÿ×9ÿ×:ùÕ>ÿØ:ìÎEýÙAÿÚAÿÚBÿÛBÿÛCÿÛDýÝJÿÞKÿßMýÞNÿßNÿâUÿãWÿãXÿæaÿçaÿçbòánõãoýéjÿël2`6f6g5h6i6i7h7j9l8l9m:o:p;p;p<q=s =s¢=t¡>t¢>u£?v¥@x¦@x§Ay¨B{ªC|«C}C}®D}D~E¯F°F±F²G²H´HµH
¶I
·J¹JºK»L¼L¼M¾L¿NÀOÁPÃRÆÿÿÿ !ù e , ¦eeaZRLF@7]dRJD=8WD>85e_WLD9298ca\UPG@<5§e'#eb_TPJ°5¿1e#WT@§4ÁÄeÇKGeRÓ4e-/,'&!ØeLJCe.0,)äæC>eïñ,Á3á xW.BÊȺe*8,0 £ÇA ; | 585 | 1 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/idle_48.gif | GIF89a0 0 ö Ed~ÿ¸ÿ¼$ÿ½)ÿ¾0ÿÂ,ÿÆ1ÿÊ5ÿÎ:ÿÑ>ÿÈOÿÕCÿØGÿÖLÿÜKÿÊRÿßRÿÓ^ÿâTÿæZÿé]ÿÑfÿÚeÿÕlÿÛmÿØpÿì`ÿïs?r=v¤<y«:}³9¸DfChBjZu@n@pMxJ|¥C}«8¼Aµ@
¼g·o¼7Á>ÃDÅdÀbÍaÐv£Çv¥Íu§Ò¤¤¤´´´½½½ÿÜÿçÿì¢ÿåªÿí³·Ì¹Ñ®Ä×µËÝÁá³ÑèÄÄÄÌÌÌÓÓÓÐ×ÞÜÜÜÿú×äääìììÿúééïôêðõôôôÿüö÷úüüüü !ù X , 0 0 þX
WWTTTPOMXWIXJTJWKOJOKTOPªPKJ<MW¹WMK£³MTMJI;=µJXÁ¢®¬¥OI=´ÉÏÐáÏ×WÚÜݾ¢¤¤MâPIå«ÛÉ·ðð¡£<IOv»²Ì³}áD%IÂãÜJl$êÔP9xÜ[æË;jå=yô¤ªãØK£&*.%ìÌ^±vèTBLPeFaé+LUßF^¹¤
VòbÁá)èDú(aµ ô ,Uɳ@é
Ç®þÝYõÒ/(J`õZRôÙ Þ¬%XÉ]ªV©|òô°$(]÷U õÝ$4T¨ðàaE#TrU®Y]ïY²tå>xHÑ¡"-ŵo$ûÅWTVlp¶ÍÁÄÜ6©âÑUáKÏÁÄtEò´m(1z!HVÒ_©¾r.hº4Ë®ÍÃøò¼E
=+ßè8E4G^yDKj ø.GÄ ly`ä
p8ðtÒÚï]Ã* µ`Â}!hÈ@4
Û#$æ¨
(Æ6_/# W,ÀTþp£'ûQq)]r/¯QÈb.)B pE iÀ¸PÌEMñ¤Ww°hÛrIQiÀ7
R%©²Ý+ÝP¡RÀHP 7>ÈIï¹Rɱ-'
P@ÁHàÀ``¢ÒÉ'{RÂiBáËf,¦pÅPÐ)ä À ¹
O%R ,®ø"Ã\Qëi'©(,G{˪¤®>D
õà,§¸2 @DuÜÂ+(4w
àº:ÐQáIò¨j&±&Í´
$ù~Êð(¼§ÌR±%Âõ Æ¢4j£`©éLMS«À+Ü^Kð°a´¡fPE¥&â®u)Ë;ÍÎmhn¨È\Áù±E0Á§Ü$Ív0µc,3Éë¢ ¬°XH³ñ,Â}Ý_% aÁ¢*ª@X#"ðW׸Ú5ðÜË0tµÎñ,åà~É&T÷0¨l·XáZ5B
@l=µÉT³uÛåµÊIÉ`ÌäBÊbNÃÉ9§lfUªÇ.ûì´×~H ; | 1,388 | 8 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/tk.gif | GIF89a ÿ ÿ ÀÀÀ!ù , @»Ên¯&ØÎrF×ñ¡cè¢J ; ;;º
D ;; | 85 | 2 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/plusnode.gif | GIF89a ÿ ÿÿÿ ÀÀÀ!ù , @ À
¡hp,Çê3§¯â(FL÷Dº¦D
ä8 ; | 79 | 2 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/minusnode.gif | GIF89a ÿÿÿ ÀÀÀ!ù , 2 HP`À°! 28 ÄhÔø0¢D/¼Ø±bÂS | 96 | 1 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/idle_32.gif | GIF89a ÷ò Ec|Ec}Ed}Fd}Ed~Debbbÿ¼$ÿ¼%ÿ¾'ÿ¿(ÿ½+ÿÀ)ÿÁ+ÿÂ,ÿÃ-ÿÄ.ÿÅ/ÿÃ2ÿÅ0ÿÇ1ÿÈ2ÿÈ3ÿÉ4ÿÊ5ÿË6ÿÌ7ÿÁ<ÿÄ?ÿÍ8ÿÍ9ÿÎ:ÿÎ;ÿÏ;ÿÌ=ÿÏ<ÿÐ<ÿÑ=ÿÑ>ÿÑ?ÿÒ?ÿÒ@ÿÓ@ÿÓAÿÔBÿÖDÿ×Eÿ×FÿØFÿØGÿÖHÿÚJÿÛJÿÛKÿÜLÿÝMÿÞOÿËYÿÎ\ÿßPÿÛ\ÿàQÿáRÿâSÿâTÿãUÿãVÿäVÿäWÿåXÿæYÿçZÿè[ÿé]ÿê^ÿê_ÿÛmÿßrÿägÿë`ÿìaÿíbÿâv?p?q?q?r>s>s>s>t>t >u¡=u¢=v£=v¤=v¥=w¦<w§=w§<x¨<x©<yª<y«;z¬;z;z®;{®;{°;|°:|±:}²:}³:}´:~µ9~¶9·9¸DeDfDfCgCg
ChCiBiBjBjBkAkAlAlAmAm@n@n@oY~Fy¢C~®9¹8¼8½iV§A¹m»p²p¶?ÁPÅPÊk¡Îi£Ò¡¡¡²²²´´´···¹¹¹»»»¿¿¿ÿñÿð´¯ÂÓÀÀÀÂÂÂÃÃÃÅÅÅÇÇÇÈÈÈÉÉÉÊÊÊËËËÌÌÌÍÍÍÎÎÎÏÏÏÐÐÐÑÑÑÒÒÒÓÓÓÔÔÔÕÕÕÖÖÖ×××ØØØÚÚÚÛÛÛÜÜÜÝÝÝÞÞÞßßßÿñÏÿòÐÿóÔÿòÕÿòÖÿôÕÿ÷ÜÿøÝÖâíÔâîÖãïÜäëÚåíÔäðÚèóÙèôàààáááâââãããäääåååæææçççèèèéééêêêëëëìììíííîîîïïïÿúêéïôêïôðððñññòòòóóóôôôõõõööö÷÷÷øøøùùùúúúûûûüüüýýýþþþÿÿÿ !ù ó , þ ç H° ÁÙ)TøaÃqÛZáR
!;êzmÛÖ+ºmÑzµò4WŲÛh-DOѶÅ:I°¡Jv
ßé|§.µ3iÎ{']/oÞ¬íÜk\)OÖ4 %:t©Õw¸°²¦jÍ«`{ò˨TßmCºmÜ8k{ÆÕ¢Vhª+V´q½S§Î@¯²SgS¥:
縵Ì;45oÛ>±ÕqT
¦«W/vÞN{ÃͦHnÊ|QDiYè9ÞMø¥fÊdg¡(ÑíTZ¶vY[Æ!£¨
"@|ë-«©*\¹ÆþigM/Ö ñÁ£}ÞbÞçÔSçì»Qêõ°:ðâ<u¹ðeN/ã<s#tÀQÕwì×Ã
<F ÖË9 øÆÃ2w À;7ÀÀBTæÖn½S #o¬T °ß+ Â
óÀxÔ;Àa#U`§_dù¢7ª|óNycxAI8`ÓD T Aã ¥&RïÀÑ¥áÅHÑ
.ð
´([ÛàâÍ;EïÌÅEôP+|
,àç<m3M)I"FñD£)F:iä@Uµº
6zß0 "$:j)º °A1FK/¸`ó×RQ«(ö
6@Û¢J+ô*§ÔõÎAì0CeyÐVÛ0ÇÜ4ÖtÔR,ïçÅÓ@{Kl/¹pR¥JJL0Ð+ÔPÇH!X 1ܬA ; | 1,435 | 9 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/Icons/folder.gif | GIF89a
¢ÿ ÿÿÏÿÿÿÏïïïÏÏ` ÀÀÀ!ù ,
@=xW̦Pªb¦ýwdi¡®DÓ,Xiܤe¸ Å Ä
Gö+)µè\æÍÙs×aYY ; | 120 | 3 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_paragraph.py | "Test paragraph, coverage 76%."
from idlelib import paragraph as pg
import unittest
from test.support import requires
from tkinter import Tk, Text
from idlelib.editor import EditorWindow
class Is_Get_Test(unittest.TestCase):
"""Test the is_ and get_ functions"""
test_comment = '# This is a comment'
test_nocomment = 'This is not a comment'
trailingws_comment = '# This is a comment '
leadingws_comment = ' # This is a comment'
leadingws_nocomment = ' This is not a comment'
def test_is_all_white(self):
self.assertTrue(pg.is_all_white(''))
self.assertTrue(pg.is_all_white('\t\n\r\f\v'))
self.assertFalse(pg.is_all_white(self.test_comment))
def test_get_indent(self):
Equal = self.assertEqual
Equal(pg.get_indent(self.test_comment), '')
Equal(pg.get_indent(self.trailingws_comment), '')
Equal(pg.get_indent(self.leadingws_comment), ' ')
Equal(pg.get_indent(self.leadingws_nocomment), ' ')
def test_get_comment_header(self):
Equal = self.assertEqual
# Test comment strings
Equal(pg.get_comment_header(self.test_comment), '#')
Equal(pg.get_comment_header(self.trailingws_comment), '#')
Equal(pg.get_comment_header(self.leadingws_comment), ' #')
# Test non-comment strings
Equal(pg.get_comment_header(self.leadingws_nocomment), ' ')
Equal(pg.get_comment_header(self.test_nocomment), '')
class FindTest(unittest.TestCase):
"""Test the find_paragraph function in paragraph module.
Using the runcase() function, find_paragraph() is called with 'mark' set at
multiple indexes before and inside the test paragraph.
It appears that code with the same indentation as a quoted string is grouped
as part of the same paragraph, which is probably incorrect behavior.
"""
@classmethod
def setUpClass(cls):
from idlelib.idle_test.mock_tk import Text
cls.text = Text()
def runcase(self, inserttext, stopline, expected):
# Check that find_paragraph returns the expected paragraph when
# the mark index is set to beginning, middle, end of each line
# up to but not including the stop line
text = self.text
text.insert('1.0', inserttext)
for line in range(1, stopline):
linelength = int(text.index("%d.end" % line).split('.')[1])
for col in (0, linelength//2, linelength):
tempindex = "%d.%d" % (line, col)
self.assertEqual(pg.find_paragraph(text, tempindex), expected)
text.delete('1.0', 'end')
def test_find_comment(self):
comment = (
"# Comment block with no blank lines before\n"
"# Comment line\n"
"\n")
self.runcase(comment, 3, ('1.0', '3.0', '#', comment[0:58]))
comment = (
"\n"
"# Comment block with whitespace line before and after\n"
"# Comment line\n"
"\n")
self.runcase(comment, 4, ('2.0', '4.0', '#', comment[1:70]))
comment = (
"\n"
" # Indented comment block with whitespace before and after\n"
" # Comment line\n"
"\n")
self.runcase(comment, 4, ('2.0', '4.0', ' #', comment[1:82]))
comment = (
"\n"
"# Single line comment\n"
"\n")
self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:23]))
comment = (
"\n"
" # Single line comment with leading whitespace\n"
"\n")
self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:51]))
comment = (
"\n"
"# Comment immediately followed by code\n"
"x = 42\n"
"\n")
self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:40]))
comment = (
"\n"
" # Indented comment immediately followed by code\n"
"x = 42\n"
"\n")
self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:53]))
comment = (
"\n"
"# Comment immediately followed by indented code\n"
" x = 42\n"
"\n")
self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:49]))
def test_find_paragraph(self):
teststring = (
'"""String with no blank lines before\n'
'String line\n'
'"""\n'
'\n')
self.runcase(teststring, 4, ('1.0', '4.0', '', teststring[0:53]))
teststring = (
"\n"
'"""String with whitespace line before and after\n'
'String line.\n'
'"""\n'
'\n')
self.runcase(teststring, 5, ('2.0', '5.0', '', teststring[1:66]))
teststring = (
'\n'
' """Indented string with whitespace before and after\n'
' Comment string.\n'
' """\n'
'\n')
self.runcase(teststring, 5, ('2.0', '5.0', ' ', teststring[1:85]))
teststring = (
'\n'
'"""Single line string."""\n'
'\n')
self.runcase(teststring, 3, ('2.0', '3.0', '', teststring[1:27]))
teststring = (
'\n'
' """Single line string with leading whitespace."""\n'
'\n')
self.runcase(teststring, 3, ('2.0', '3.0', ' ', teststring[1:55]))
class ReformatFunctionTest(unittest.TestCase):
"""Test the reformat_paragraph function without the editor window."""
def test_reformat_paragraph(self):
Equal = self.assertEqual
reform = pg.reformat_paragraph
hw = "O hello world"
Equal(reform(' ', 1), ' ')
Equal(reform("Hello world", 20), "Hello world")
# Test without leading newline
Equal(reform(hw, 1), "O\nhello\nworld")
Equal(reform(hw, 6), "O\nhello\nworld")
Equal(reform(hw, 7), "O hello\nworld")
Equal(reform(hw, 12), "O hello\nworld")
Equal(reform(hw, 13), "O hello world")
# Test with leading newline
hw = "\nO hello world"
Equal(reform(hw, 1), "\nO\nhello\nworld")
Equal(reform(hw, 6), "\nO\nhello\nworld")
Equal(reform(hw, 7), "\nO hello\nworld")
Equal(reform(hw, 12), "\nO hello\nworld")
Equal(reform(hw, 13), "\nO hello world")
class ReformatCommentTest(unittest.TestCase):
"""Test the reformat_comment function without the editor window."""
def test_reformat_comment(self):
Equal = self.assertEqual
# reformat_comment formats to a minimum of 20 characters
test_string = (
" \"\"\"this is a test of a reformat for a triple quoted string"
" will it reformat to less than 70 characters for me?\"\"\"")
result = pg.reformat_comment(test_string, 70, " ")
expected = (
" \"\"\"this is a test of a reformat for a triple quoted string will it\n"
" reformat to less than 70 characters for me?\"\"\"")
Equal(result, expected)
test_comment = (
"# this is a test of a reformat for a triple quoted string will "
"it reformat to less than 70 characters for me?")
result = pg.reformat_comment(test_comment, 70, "#")
expected = (
"# this is a test of a reformat for a triple quoted string will it\n"
"# reformat to less than 70 characters for me?")
Equal(result, expected)
class FormatClassTest(unittest.TestCase):
def test_init_close(self):
instance = pg.FormatParagraph('editor')
self.assertEqual(instance.editwin, 'editor')
instance.close()
self.assertEqual(instance.editwin, None)
# For testing format_paragraph_event, Initialize FormatParagraph with
# a mock Editor with .text and .get_selection_indices. The text must
# be a Text wrapper that adds two methods
# A real EditorWindow creates unneeded, time-consuming baggage and
# sometimes emits shutdown warnings like this:
# "warning: callback failed in WindowList <class '_tkinter.TclError'>
# : invalid command name ".55131368.windows".
# Calling EditorWindow._close in tearDownClass prevents this but causes
# other problems (windows left open).
class TextWrapper:
def __init__(self, master):
self.text = Text(master=master)
def __getattr__(self, name):
return getattr(self.text, name)
def undo_block_start(self): pass
def undo_block_stop(self): pass
class Editor:
def __init__(self, root):
self.text = TextWrapper(root)
get_selection_indices = EditorWindow. get_selection_indices
class FormatEventTest(unittest.TestCase):
"""Test the formatting of text inside a Text widget.
This is done with FormatParagraph.format.paragraph_event,
which calls functions in the module as appropriate.
"""
test_string = (
" '''this is a test of a reformat for a triple "
"quoted string will it reformat to less than 70 "
"characters for me?'''\n")
multiline_test_string = (
" '''The first line is under the max width.\n"
" The second line's length is way over the max width. It goes "
"on and on until it is over 100 characters long.\n"
" Same thing with the third line. It is also way over the max "
"width, but FormatParagraph will fix it.\n"
" '''\n")
multiline_test_comment = (
"# The first line is under the max width.\n"
"# The second line's length is way over the max width. It goes on "
"and on until it is over 100 characters long.\n"
"# Same thing with the third line. It is also way over the max "
"width, but FormatParagraph will fix it.\n"
"# The fourth line is short like the first line.")
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
editor = Editor(root=cls.root)
cls.text = editor.text.text # Test code does not need the wrapper.
cls.formatter = pg.FormatParagraph(editor).format_paragraph_event
# Sets the insert mark just after the re-wrapped and inserted text.
@classmethod
def tearDownClass(cls):
del cls.text, cls.formatter
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def test_short_line(self):
self.text.insert('1.0', "Short line\n")
self.formatter("Dummy")
self.assertEqual(self.text.get('1.0', 'insert'), "Short line\n" )
self.text.delete('1.0', 'end')
def test_long_line(self):
text = self.text
# Set cursor ('insert' mark) to '1.0', within text.
text.insert('1.0', self.test_string)
text.mark_set('insert', '1.0')
self.formatter('ParameterDoesNothing', limit=70)
result = text.get('1.0', 'insert')
# find function includes \n
expected = (
" '''this is a test of a reformat for a triple quoted string will it\n"
" reformat to less than 70 characters for me?'''\n") # yes
self.assertEqual(result, expected)
text.delete('1.0', 'end')
# Select from 1.11 to line end.
text.insert('1.0', self.test_string)
text.tag_add('sel', '1.11', '1.end')
self.formatter('ParameterDoesNothing', limit=70)
result = text.get('1.0', 'insert')
# selection excludes \n
expected = (
" '''this is a test of a reformat for a triple quoted string will it reformat\n"
" to less than 70 characters for me?'''") # no
self.assertEqual(result, expected)
text.delete('1.0', 'end')
def test_multiple_lines(self):
text = self.text
# Select 2 long lines.
text.insert('1.0', self.multiline_test_string)
text.tag_add('sel', '2.0', '4.0')
self.formatter('ParameterDoesNothing', limit=70)
result = text.get('2.0', 'insert')
expected = (
" The second line's length is way over the max width. It goes on and\n"
" on until it is over 100 characters long. Same thing with the third\n"
" line. It is also way over the max width, but FormatParagraph will\n"
" fix it.\n")
self.assertEqual(result, expected)
text.delete('1.0', 'end')
def test_comment_block(self):
text = self.text
# Set cursor ('insert') to '1.0', within block.
text.insert('1.0', self.multiline_test_comment)
self.formatter('ParameterDoesNothing', limit=70)
result = text.get('1.0', 'insert')
expected = (
"# The first line is under the max width. The second line's length is\n"
"# way over the max width. It goes on and on until it is over 100\n"
"# characters long. Same thing with the third line. It is also way over\n"
"# the max width, but FormatParagraph will fix it. The fourth line is\n"
"# short like the first line.\n")
self.assertEqual(result, expected)
text.delete('1.0', 'end')
# Select line 2, verify line 1 unaffected.
text.insert('1.0', self.multiline_test_comment)
text.tag_add('sel', '2.0', '3.0')
self.formatter('ParameterDoesNothing', limit=70)
result = text.get('1.0', 'insert')
expected = (
"# The first line is under the max width.\n"
"# The second line's length is way over the max width. It goes on and\n"
"# on until it is over 100 characters long.\n")
self.assertEqual(result, expected)
text.delete('1.0', 'end')
# The following block worked with EditorWindow but fails with the mock.
# Lines 2 and 3 get pasted together even though the previous block left
# the previous line alone. More investigation is needed.
## # Select lines 3 and 4
## text.insert('1.0', self.multiline_test_comment)
## text.tag_add('sel', '3.0', '5.0')
## self.formatter('ParameterDoesNothing')
## result = text.get('3.0', 'insert')
## expected = (
##"# Same thing with the third line. It is also way over the max width,\n"
##"# but FormatParagraph will fix it. The fourth line is short like the\n"
##"# first line.\n")
## self.assertEqual(result, expected)
## text.delete('1.0', 'end')
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
| 14,352 | 380 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/README.txt | README FOR IDLE TESTS IN IDLELIB.IDLE_TEST
0. Quick Start
Automated unit tests were added in 3.3 for Python 3.x.
To run the tests from a command line:
python -m test.test_idle
Human-mediated tests were added later in 3.4.
python -m idlelib.idle_test.htest
1. Test Files
The idle directory, idlelib, has over 60 xyz.py files. The idle_test
subdirectory contains test_xyz.py for each implementation file xyz.py.
To add a test for abc.py, open idle_test/template.py and immediately
Save As test_abc.py. Insert 'abc' on the first line, and replace
'zzdummy' with 'abc.
Remove the imports of requires and tkinter if not needed. Otherwise,
add to the tkinter imports as needed.
Add a prefix to 'Test' for the initial test class. The template class
contains code needed or possibly needed for gui tests. See the next
section if doing gui tests. If not, and not needed for further classes,
this code can be removed.
Add the following at the end of abc.py. If an htest was added first,
insert the import and main lines before the htest lines.
if __name__ == "__main__":
from unittest import main
main('idlelib.idle_test.test_abc', verbosity=2, exit=False)
The ', exit=False' is only needed if an htest follows.
2. GUI Tests
When run as part of the Python test suite, Idle GUI tests need to run
test.support.requires('gui'). A test is a GUI test if it creates a
tkinter.Tk root or master object either directly or indirectly by
instantiating a tkinter or idle class. GUI tests cannot run in test
processes that either have no graphical environment available or are not
allowed to use it.
To guard a module consisting entirely of GUI tests, start with
from test.support import requires
requires('gui')
To guard a test class, put "requires('gui')" in its setUpClass function.
The template.py file does this.
To avoid interfering with other GUI tests, all GUI objects must be
destroyed and deleted by the end of the test. The Tk root created in a
setUpX function should be destroyed in the corresponding tearDownX and
the module or class attribute deleted. Others widgets should descend
from the single root and the attributes deleted BEFORE root is
destroyed. See https://bugs.python.org/issue20567.
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = tk.Tk()
cls.text = tk.Text(root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
The update_idletasks call is sometimes needed to prevent the following
warning either when running a test alone or as part of the test suite
(#27196). It should not hurt if not needed.
can't invoke "event" command: application has been destroyed
...
"ttk::ThemeChanged"
If a test creates instance 'e' of EditorWindow, call 'e._close()' before
or as the first part of teardown. The effect of omitting this depends
on the later shutdown. Then enable the after_cancel loop in the
template. This prevents messages like the following.
bgerror failed to handle background error.
Original error: invalid command name "106096696timer_event"
Error in bgerror: can't invoke "tk" command: application has been destroyed
Requires('gui') causes the test(s) it guards to be skipped if any of
these conditions are met:
- The tests are being run by regrtest.py, and it was started without
enabling the "gui" resource with the "-u" command line option.
- The tests are being run on Windows by a service that is not allowed
to interact with the graphical environment.
- The tests are being run on Linux and X Windows is not available.
- The tests are being run on Mac OSX in a process that cannot make a
window manager connection.
- tkinter.Tk cannot be successfully instantiated for some reason.
- test.support.use_resources has been set by something other than
regrtest.py and does not contain "gui".
Tests of non-GUI operations should avoid creating tk widgets. Incidental
uses of tk variables and messageboxes can be replaced by the mock
classes in idle_test/mock_tk.py. The mock text handles some uses of the
tk Text widget.
3. Running Unit Tests
Assume that xyz.py and test_xyz.py both end with a unittest.main() call.
Running either from an Idle editor runs all tests in the test_xyz file
with the version of Python running Idle. Test output appears in the
Shell window. The 'verbosity=2' option lists all test methods in the
file, which is appropriate when developing tests. The 'exit=False'
option is needed in xyx.py files when an htest follows.
The following command lines also run all test methods, including
GUI tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle'
start Idle and so cannot run tests.)
python -m idlelib.xyz
python -m idlelib.idle_test.test_xyz
The following runs all idle_test/test_*.py tests interactively.
>>> import unittest
>>> unittest.main('idlelib.idle_test', verbosity=2)
The following run all Idle tests at a command line. Option '-v' is the
same as 'verbosity=2'.
python -m unittest -v idlelib.idle_test
python -m test -v -ugui test_idle
python -m test.test_idle
The idle tests are 'discovered' by
idlelib.idle_test.__init__.load_tests, which is also imported into
test.test_idle. Normally, neither file should be changed when working on
individual test modules. The third command runs unittest indirectly
through regrtest. The same happens when the entire test suite is run
with 'python -m test'. So that command must work for buildbots to stay
green. Idle tests must not disturb the environment in a way that makes
other tests fail (issue 18081).
To run an individual Testcase or test method, extend the dotted name
given to unittest on the command line or use the test -m option. The
latter allows use of other regrtest options. When using the latter,
all components of the pattern must be present, but any can be replaced
by '*'.
python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth
python -m test -m idlelib.idle_test.text_xyz.Test_case.test_meth test_idle
The test suite can be run in an IDLE user process from Shell.
>>> import test.autotest # Issue 25588, 2017/10/13, 3.6.4, 3.7.0a2.
There are currently failures not usually present, and this does not
work when run from the editor.
4. Human-mediated Tests
Human-mediated tests are widget tests that cannot be automated but need
human verification. They are contained in idlelib/idle_test/htest.py,
which has instructions. (Some modules need an auxiliary function,
identified with "# htest # on the header line.) The set is about
complete, though some tests need improvement. To run all htests, run the
htest file from an editor or from the command line with:
python -m idlelib.idle_test.htest
5. Test Coverage
Install the coverage package into your Python 3.6 site-packages
directory. (Its exact location depends on the OS).
> python3 -m pip install coverage
(On Windows, replace 'python3 with 'py -3.6' or perhaps just 'python'.)
The problem with running coverage with repository python is that
coverage uses absolute imports for its submodules, hence it needs to be
in a directory in sys.path. One solution: copy the package to the
directory containing the cpython repository. Call it 'dev'. Then run
coverage either directly or from a script in that directory so that
'dev' is prepended to sys.path.
Either edit or add dev/.coveragerc so it looks something like this.
---
# .coveragerc sets coverage options.
[run]
branch = True
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
.*# htest #
if not _utest:
if _htest:
---
The additions for IDLE are 'branch = True', to test coverage both ways,
and the last three exclude lines, to exclude things peculiar to IDLE
that are not executed during tests.
A script like the following cover.bat (for Windows) is very handy.
---
@echo off
rem Usage: cover filename [test_ suffix] # proper case required by coverage
rem filename without .py, 2nd parameter if test is not test_filename
setlocal
set py=f:\dev\3x\pcbuild\win32\python_d.exe
set src=idlelib.%1
if "%2" EQU "" set tst=f:/dev/3x/Lib/idlelib/idle_test/test_%1.py
if "%2" NEQ "" set tst=f:/dev/ex/Lib/idlelib/idle_test/test_%2.py
%py% -m coverage run --pylib --source=%src% %tst%
%py% -m coverage report --show-missing
%py% -m coverage html
start htmlcov\3x_Lib_idlelib_%1_py.html
rem Above opens new report; htmlcov\index.html displays report index
---
The second parameter was added for tests of module x not named test_x.
(There were several before modules were renamed, now only one is left.)
| 8,729 | 239 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_rstrip.py | "Test rstrip, coverage 100%."
from idlelib import rstrip
import unittest
from idlelib.idle_test.mock_idle import Editor
class rstripTest(unittest.TestCase):
def test_rstrip_line(self):
editor = Editor()
text = editor.text
do_rstrip = rstrip.Rstrip(editor).do_rstrip
do_rstrip()
self.assertEqual(text.get('1.0', 'insert'), '')
text.insert('1.0', ' ')
do_rstrip()
self.assertEqual(text.get('1.0', 'insert'), '')
text.insert('1.0', ' \n')
do_rstrip()
self.assertEqual(text.get('1.0', 'insert'), '\n')
def test_rstrip_multiple(self):
editor = Editor()
# Comment above, uncomment 3 below to test with real Editor & Text.
#from idlelib.editor import EditorWindow as Editor
#from tkinter import Tk
#editor = Editor(root=Tk())
text = editor.text
do_rstrip = rstrip.Rstrip(editor).do_rstrip
original = (
"Line with an ending tab \n"
"Line ending in 5 spaces \n"
"Linewithnospaces\n"
" indented line\n"
" indented line with trailing space \n"
" ")
stripped = (
"Line with an ending tab\n"
"Line ending in 5 spaces\n"
"Linewithnospaces\n"
" indented line\n"
" indented line with trailing space\n")
text.insert('1.0', original)
do_rstrip()
self.assertEqual(text.get('1.0', 'insert'), stripped)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 1,605 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_editor.py | "Test editor, coverage 35%."
from idlelib import editor
import unittest
from test.support import requires
from tkinter import Tk
Editor = editor.EditorWindow
class EditorWindowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
for id in cls.root.tk.call('after', 'info'):
cls.root.after_cancel(id)
cls.root.destroy()
del cls.root
def test_init(self):
e = Editor(root=self.root)
self.assertEqual(e.root, self.root)
e._close()
class EditorFunctionTest(unittest.TestCase):
def test_filename_to_unicode(self):
func = Editor._filename_to_unicode
class dummy():
filesystemencoding = 'utf-8'
pairs = (('abc', 'abc'), ('a\U00011111c', 'a\ufffdc'),
(b'abc', 'abc'), (b'a\xf0\x91\x84\x91c', 'a\ufffdc'))
for inp, out in pairs:
self.assertEqual(func(dummy, inp), out)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 1,141 | 47 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_outwin.py | "Test outwin, coverage 76%."
from idlelib import outwin
import unittest
from test.support import requires
from tkinter import Tk, Text
from idlelib.idle_test.mock_tk import Mbox_func
from idlelib.idle_test.mock_idle import Func
from unittest import mock
class OutputWindowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
root = cls.root = Tk()
root.withdraw()
w = cls.window = outwin.OutputWindow(None, None, None, root)
cls.text = w.text = Text(root)
@classmethod
def tearDownClass(cls):
cls.window.close()
del cls.text, cls.window
cls.root.destroy()
del cls.root
def setUp(self):
self.text.delete('1.0', 'end')
def test_ispythonsource(self):
# OutputWindow overrides ispythonsource to always return False.
w = self.window
self.assertFalse(w.ispythonsource('test.txt'))
self.assertFalse(w.ispythonsource(__file__))
def test_window_title(self):
self.assertEqual(self.window.top.title(), 'Output')
def test_maybesave(self):
w = self.window
eq = self.assertEqual
w.get_saved = Func()
w.get_saved.result = False
eq(w.maybesave(), 'no')
eq(w.get_saved.called, 1)
w.get_saved.result = True
eq(w.maybesave(), 'yes')
eq(w.get_saved.called, 2)
del w.get_saved
def test_write(self):
eq = self.assertEqual
delete = self.text.delete
get = self.text.get
write = self.window.write
# Test bytes.
b = b'Test bytes.'
eq(write(b), len(b))
eq(get('1.0', '1.end'), b.decode())
# No new line - insert stays on same line.
delete('1.0', 'end')
test_text = 'test text'
eq(write(test_text), len(test_text))
eq(get('1.0', '1.end'), 'test text')
eq(get('insert linestart', 'insert lineend'), 'test text')
# New line - insert moves to next line.
delete('1.0', 'end')
test_text = 'test text\n'
eq(write(test_text), len(test_text))
eq(get('1.0', '1.end'), 'test text')
eq(get('insert linestart', 'insert lineend'), '')
# Text after new line is tagged for second line of Text widget.
delete('1.0', 'end')
test_text = 'test text\nLine 2'
eq(write(test_text), len(test_text))
eq(get('1.0', '1.end'), 'test text')
eq(get('2.0', '2.end'), 'Line 2')
eq(get('insert linestart', 'insert lineend'), 'Line 2')
# Test tags.
delete('1.0', 'end')
test_text = 'test text\n'
test_text2 = 'Line 2\n'
eq(write(test_text, tags='mytag'), len(test_text))
eq(write(test_text2, tags='secondtag'), len(test_text2))
eq(get('mytag.first', 'mytag.last'), test_text)
eq(get('secondtag.first', 'secondtag.last'), test_text2)
eq(get('1.0', '1.end'), test_text.rstrip('\n'))
eq(get('2.0', '2.end'), test_text2.rstrip('\n'))
def test_writelines(self):
eq = self.assertEqual
get = self.text.get
writelines = self.window.writelines
writelines(('Line 1\n', 'Line 2\n', 'Line 3\n'))
eq(get('1.0', '1.end'), 'Line 1')
eq(get('2.0', '2.end'), 'Line 2')
eq(get('3.0', '3.end'), 'Line 3')
eq(get('insert linestart', 'insert lineend'), '')
def test_goto_file_line(self):
eq = self.assertEqual
w = self.window
text = self.text
w.flist = mock.Mock()
gfl = w.flist.gotofileline = Func()
showerror = w.showerror = Mbox_func()
# No file/line number.
w.write('Not a file line')
self.assertIsNone(w.goto_file_line())
eq(gfl.called, 0)
eq(showerror.title, 'No special line')
# Current file/line number.
w.write(f'{str(__file__)}: 42: spam\n')
w.write(f'{str(__file__)}: 21: spam')
self.assertIsNone(w.goto_file_line())
eq(gfl.args, (str(__file__), 21))
# Previous line has file/line number.
text.delete('1.0', 'end')
w.write(f'{str(__file__)}: 42: spam\n')
w.write('Not a file line')
self.assertIsNone(w.goto_file_line())
eq(gfl.args, (str(__file__), 42))
del w.flist.gotofileline, w.showerror
class ModuleFunctionTest(unittest.TestCase):
@classmethod
def setUp(cls):
outwin.file_line_progs = None
def test_compile_progs(self):
outwin.compile_progs()
for pat, regex in zip(outwin.file_line_pats, outwin.file_line_progs):
self.assertEqual(regex.pattern, pat)
@mock.patch('builtins.open')
def test_file_line_helper(self, mock_open):
flh = outwin.file_line_helper
test_lines = (
(r'foo file "testfile1", line 42, bar', ('testfile1', 42)),
(r'foo testfile2(21) bar', ('testfile2', 21)),
(r' testfile3 : 42: foo bar\n', (' testfile3 ', 42)),
(r'foo testfile4.py :1: ', ('foo testfile4.py ', 1)),
('testfile5: \u19D4\u19D2: ', ('testfile5', 42)),
(r'testfile6: 42', None), # only one `:`
(r'testfile7 42 text', None) # no separators
)
for line, expected_output in test_lines:
self.assertEqual(flh(line), expected_output)
if expected_output:
mock_open.assert_called_with(expected_output[0], 'r')
if __name__ == '__main__':
unittest.main(verbosity=2)
| 5,545 | 172 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_delegator.py | "Test delegator, coverage 100%."
from idlelib.delegator import Delegator
import unittest
class DelegatorTest(unittest.TestCase):
def test_mydel(self):
# Test a simple use scenario.
# Initialize an int delegator.
mydel = Delegator(int)
self.assertIs(mydel.delegate, int)
self.assertEqual(mydel._Delegator__cache, set())
# Trying to access a non-attribute of int fails.
self.assertRaises(AttributeError, mydel.__getattr__, 'xyz')
# Add real int attribute 'bit_length' by accessing it.
bl = mydel.bit_length
self.assertIs(bl, int.bit_length)
self.assertIs(mydel.__dict__['bit_length'], int.bit_length)
self.assertEqual(mydel._Delegator__cache, {'bit_length'})
# Add attribute 'numerator'.
mydel.numerator
self.assertEqual(mydel._Delegator__cache, {'bit_length', 'numerator'})
# Delete 'numerator'.
del mydel.numerator
self.assertNotIn('numerator', mydel.__dict__)
# The current implementation leaves it in the name cache.
# self.assertIn('numerator', mydel._Delegator__cache)
# However, this is not required and not part of the specification
# Change delegate to float, first resetting the attributes.
mydel.setdelegate(float) # calls resetcache
self.assertNotIn('bit_length', mydel.__dict__)
self.assertEqual(mydel._Delegator__cache, set())
self.assertIs(mydel.delegate, float)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
| 1,567 | 45 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_scrolledlist.py | "Test scrolledlist, coverage 38%."
from idlelib.scrolledlist import ScrolledList
import unittest
from test.support import requires
requires('gui')
from tkinter import Tk
class ScrolledListTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def test_init(self):
ScrolledList(self.root)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 496 | 28 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_searchengine.py | "Test searchengine, coverage 99%."
from idlelib import searchengine as se
import unittest
# from test.support import requires
from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text
import tkinter.messagebox as tkMessageBox
from idlelib.idle_test.mock_tk import Var, Mbox
from idlelib.idle_test.mock_tk import Text as mockText
import re
# With mock replacements, the module does not use any gui widgets.
# The use of tk.Text is avoided (for now, until mock Text is improved)
# by patching instances with an index function returning what is needed.
# This works because mock Text.get does not use .index.
# The tkinter imports are used to restore searchengine.
def setUpModule():
# Replace s-e module tkinter imports other than non-gui TclError.
se.BooleanVar = Var
se.StringVar = Var
se.tkMessageBox = Mbox
def tearDownModule():
# Restore 'just in case', though other tests should also replace.
se.BooleanVar = BooleanVar
se.StringVar = StringVar
se.tkMessageBox = tkMessageBox
class Mock:
def __init__(self, *args, **kwargs): pass
class GetTest(unittest.TestCase):
# SearchEngine.get returns singleton created & saved on first call.
def test_get(self):
saved_Engine = se.SearchEngine
se.SearchEngine = Mock # monkey-patch class
try:
root = Mock()
engine = se.get(root)
self.assertIsInstance(engine, se.SearchEngine)
self.assertIs(root._searchengine, engine)
self.assertIs(se.get(root), engine)
finally:
se.SearchEngine = saved_Engine # restore class to module
class GetLineColTest(unittest.TestCase):
# Test simple text-independent helper function
def test_get_line_col(self):
self.assertEqual(se.get_line_col('1.0'), (1, 0))
self.assertEqual(se.get_line_col('1.11'), (1, 11))
self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend'))
self.assertRaises(ValueError, se.get_line_col, ('end'))
class GetSelectionTest(unittest.TestCase):
# Test text-dependent helper function.
## # Need gui for text.index('sel.first/sel.last/insert').
## @classmethod
## def setUpClass(cls):
## requires('gui')
## cls.root = Tk()
##
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
def test_get_selection(self):
# text = Text(master=self.root)
text = mockText()
text.insert('1.0', 'Hello World!')
# fix text.index result when called in get_selection
def sel(s):
# select entire text, cursor irrelevant
if s == 'sel.first': return '1.0'
if s == 'sel.last': return '1.12'
raise TclError
text.index = sel # replaces .tag_add('sel', '1.0, '1.12')
self.assertEqual(se.get_selection(text), ('1.0', '1.12'))
def mark(s):
# no selection, cursor after 'Hello'
if s == 'insert': return '1.5'
raise TclError
text.index = mark # replaces .mark_set('insert', '1.5')
self.assertEqual(se.get_selection(text), ('1.5', '1.5'))
class ReverseSearchTest(unittest.TestCase):
# Test helper function that searches backwards within a line.
def test_search_reverse(self):
Equal = self.assertEqual
line = "Here is an 'is' test text."
prog = re.compile('is')
Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14))
Equal(se.search_reverse(prog, line, 14).span(), (12, 14))
Equal(se.search_reverse(prog, line, 13).span(), (5, 7))
Equal(se.search_reverse(prog, line, 7).span(), (5, 7))
Equal(se.search_reverse(prog, line, 6), None)
class SearchEngineTest(unittest.TestCase):
# Test class methods that do not use Text widget.
def setUp(self):
self.engine = se.SearchEngine(root=None)
# Engine.root is only used to create error message boxes.
# The mock replacement ignores the root argument.
def test_is_get(self):
engine = self.engine
Equal = self.assertEqual
Equal(engine.getpat(), '')
engine.setpat('hello')
Equal(engine.getpat(), 'hello')
Equal(engine.isre(), False)
engine.revar.set(1)
Equal(engine.isre(), True)
Equal(engine.iscase(), False)
engine.casevar.set(1)
Equal(engine.iscase(), True)
Equal(engine.isword(), False)
engine.wordvar.set(1)
Equal(engine.isword(), True)
Equal(engine.iswrap(), True)
engine.wrapvar.set(0)
Equal(engine.iswrap(), False)
Equal(engine.isback(), False)
engine.backvar.set(1)
Equal(engine.isback(), True)
def test_setcookedpat(self):
engine = self.engine
engine.setcookedpat(r'\s')
self.assertEqual(engine.getpat(), r'\s')
engine.revar.set(1)
engine.setcookedpat(r'\s')
self.assertEqual(engine.getpat(), r'\\s')
def test_getcookedpat(self):
engine = self.engine
Equal = self.assertEqual
Equal(engine.getcookedpat(), '')
engine.setpat('hello')
Equal(engine.getcookedpat(), 'hello')
engine.wordvar.set(True)
Equal(engine.getcookedpat(), r'\bhello\b')
engine.wordvar.set(False)
engine.setpat(r'\s')
Equal(engine.getcookedpat(), r'\\s')
engine.revar.set(True)
Equal(engine.getcookedpat(), r'\s')
def test_getprog(self):
engine = self.engine
Equal = self.assertEqual
engine.setpat('Hello')
temppat = engine.getprog()
Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern)
engine.casevar.set(1)
temppat = engine.getprog()
Equal(temppat.pattern, re.compile('Hello').pattern, 0)
engine.setpat('')
Equal(engine.getprog(), None)
engine.setpat('+')
engine.revar.set(1)
Equal(engine.getprog(), None)
self.assertEqual(Mbox.showerror.message,
'Error: nothing to repeat at position 0\nPattern: +')
def test_report_error(self):
showerror = Mbox.showerror
Equal = self.assertEqual
pat = '[a-z'
msg = 'unexpected end of regular expression'
Equal(self.engine.report_error(pat, msg), None)
Equal(showerror.title, 'Regular expression error')
expected_message = ("Error: " + msg + "\nPattern: [a-z")
Equal(showerror.message, expected_message)
Equal(self.engine.report_error(pat, msg, 5), None)
Equal(showerror.title, 'Regular expression error')
expected_message += "\nOffset: 5"
Equal(showerror.message, expected_message)
class SearchTest(unittest.TestCase):
# Test that search_text makes right call to right method.
@classmethod
def setUpClass(cls):
## requires('gui')
## cls.root = Tk()
## cls.text = Text(master=cls.root)
cls.text = mockText()
test_text = (
'First line\n'
'Line with target\n'
'Last line\n')
cls.text.insert('1.0', test_text)
cls.pat = re.compile('target')
cls.engine = se.SearchEngine(None)
cls.engine.search_forward = lambda *args: ('f', args)
cls.engine.search_backward = lambda *args: ('b', args)
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
def test_search(self):
Equal = self.assertEqual
engine = self.engine
search = engine.search_text
text = self.text
pat = self.pat
engine.patvar.set(None)
#engine.revar.set(pat)
Equal(search(text), None)
def mark(s):
# no selection, cursor after 'Hello'
if s == 'insert': return '1.5'
raise TclError
text.index = mark
Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False)))
engine.wrapvar.set(False)
Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False)))
engine.wrapvar.set(True)
engine.backvar.set(True)
Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False)))
engine.backvar.set(False)
def sel(s):
if s == 'sel.first': return '2.10'
if s == 'sel.last': return '2.16'
raise TclError
text.index = sel
Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False)))
Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True)))
engine.backvar.set(True)
Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False)))
Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True)))
class ForwardBackwardTest(unittest.TestCase):
# Test that search_forward method finds the target.
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
@classmethod
def setUpClass(cls):
cls.engine = se.SearchEngine(None)
## requires('gui')
## cls.root = Tk()
## cls.text = Text(master=cls.root)
cls.text = mockText()
# search_backward calls index('end-1c')
cls.text.index = lambda index: '4.0'
test_text = (
'First line\n'
'Line with target\n'
'Last line\n')
cls.text.insert('1.0', test_text)
cls.pat = re.compile('target')
cls.res = (2, (10, 16)) # line, slice indexes of 'target'
cls.failpat = re.compile('xyz') # not in text
cls.emptypat = re.compile(r'\w*') # empty match possible
def make_search(self, func):
def search(pat, line, col, wrap, ok=0):
res = func(self.text, pat, line, col, wrap, ok)
# res is (line, matchobject) or None
return (res[0], res[1].span()) if res else res
return search
def test_search_forward(self):
# search for non-empty match
Equal = self.assertEqual
forward = self.make_search(self.engine.search_forward)
pat = self.pat
Equal(forward(pat, 1, 0, True), self.res)
Equal(forward(pat, 3, 0, True), self.res) # wrap
Equal(forward(pat, 3, 0, False), None) # no wrap
Equal(forward(pat, 2, 10, False), self.res)
Equal(forward(self.failpat, 1, 0, True), None)
Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9)))
#Equal(forward(self.emptypat, 2, 9, True), self.res)
# While the initial empty match is correctly ignored, skipping
# the rest of the line and returning (3, (0,4)) seems buggy - tjr.
Equal(forward(self.emptypat, 2, 10, True), self.res)
def test_search_backward(self):
# search for non-empty match
Equal = self.assertEqual
backward = self.make_search(self.engine.search_backward)
pat = self.pat
Equal(backward(pat, 3, 5, True), self.res)
Equal(backward(pat, 2, 0, True), self.res) # wrap
Equal(backward(pat, 2, 0, False), None) # no wrap
Equal(backward(pat, 2, 16, False), self.res)
Equal(backward(self.failpat, 3, 9, True), None)
Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9)))
# Accepted because 9 < 10, not because ok=True.
# It is not clear that ok=True is useful going back - tjr
Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9)))
if __name__ == '__main__':
unittest.main(verbosity=2)
| 11,543 | 331 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_hyperparser.py | "Test hyperparser, coverage 98%."
from idlelib.hyperparser import HyperParser
import unittest
from test.support import requires
from tkinter import Tk, Text
from idlelib.editor import EditorWindow
class DummyEditwin:
def __init__(self, text):
self.text = text
self.indentwidth = 8
self.tabwidth = 8
self.context_use_ps1 = True
self.num_context_lines = 50, 500, 1000
_build_char_in_string_func = EditorWindow._build_char_in_string_func
is_char_in_string = EditorWindow.is_char_in_string
class HyperParserTest(unittest.TestCase):
code = (
'"""This is a module docstring"""\n'
'# this line is a comment\n'
'x = "this is a string"\n'
"y = 'this is also a string'\n"
'l = [i for i in range(10)]\n'
'm = [py*py for # comment\n'
' py in l]\n'
'x.__len__\n'
"z = ((r'asdf')+('a')))\n"
'[x for x in\n'
'for = False\n'
'cliché = "this is a string with unicode, what a cliché"'
)
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
cls.editwin = DummyEditwin(cls.text)
@classmethod
def tearDownClass(cls):
del cls.text, cls.editwin
cls.root.destroy()
del cls.root
def setUp(self):
self.text.insert('insert', self.code)
def tearDown(self):
self.text.delete('1.0', 'end')
self.editwin.context_use_ps1 = True
def get_parser(self, index):
"""
Return a parser object with index at 'index'
"""
return HyperParser(self.editwin, index)
def test_init(self):
"""
test corner cases in the init method
"""
with self.assertRaises(ValueError) as ve:
self.text.tag_add('console', '1.0', '1.end')
p = self.get_parser('1.5')
self.assertIn('precedes', str(ve.exception))
# test without ps1
self.editwin.context_use_ps1 = False
# number of lines lesser than 50
p = self.get_parser('end')
self.assertEqual(p.rawtext, self.text.get('1.0', 'end'))
# number of lines greater than 50
self.text.insert('end', self.text.get('1.0', 'end')*4)
p = self.get_parser('54.5')
def test_is_in_string(self):
get = self.get_parser
p = get('1.0')
self.assertFalse(p.is_in_string())
p = get('1.4')
self.assertTrue(p.is_in_string())
p = get('2.3')
self.assertFalse(p.is_in_string())
p = get('3.3')
self.assertFalse(p.is_in_string())
p = get('3.7')
self.assertTrue(p.is_in_string())
p = get('4.6')
self.assertTrue(p.is_in_string())
p = get('12.54')
self.assertTrue(p.is_in_string())
def test_is_in_code(self):
get = self.get_parser
p = get('1.0')
self.assertTrue(p.is_in_code())
p = get('1.1')
self.assertFalse(p.is_in_code())
p = get('2.5')
self.assertFalse(p.is_in_code())
p = get('3.4')
self.assertTrue(p.is_in_code())
p = get('3.6')
self.assertFalse(p.is_in_code())
p = get('4.14')
self.assertFalse(p.is_in_code())
def test_get_surrounding_bracket(self):
get = self.get_parser
def without_mustclose(parser):
# a utility function to get surrounding bracket
# with mustclose=False
return parser.get_surrounding_brackets(mustclose=False)
def with_mustclose(parser):
# a utility function to get surrounding bracket
# with mustclose=True
return parser.get_surrounding_brackets(mustclose=True)
p = get('3.2')
self.assertIsNone(with_mustclose(p))
self.assertIsNone(without_mustclose(p))
p = get('5.6')
self.assertTupleEqual(without_mustclose(p), ('5.4', '5.25'))
self.assertTupleEqual(without_mustclose(p), with_mustclose(p))
p = get('5.23')
self.assertTupleEqual(without_mustclose(p), ('5.21', '5.24'))
self.assertTupleEqual(without_mustclose(p), with_mustclose(p))
p = get('6.15')
self.assertTupleEqual(without_mustclose(p), ('6.4', '6.end'))
self.assertIsNone(with_mustclose(p))
p = get('9.end')
self.assertIsNone(with_mustclose(p))
self.assertIsNone(without_mustclose(p))
def test_get_expression(self):
get = self.get_parser
p = get('4.2')
self.assertEqual(p.get_expression(), 'y ')
p = get('4.7')
with self.assertRaises(ValueError) as ve:
p.get_expression()
self.assertIn('is inside a code', str(ve.exception))
p = get('5.25')
self.assertEqual(p.get_expression(), 'range(10)')
p = get('6.7')
self.assertEqual(p.get_expression(), 'py')
p = get('6.8')
self.assertEqual(p.get_expression(), '')
p = get('7.9')
self.assertEqual(p.get_expression(), 'py')
p = get('8.end')
self.assertEqual(p.get_expression(), 'x.__len__')
p = get('9.13')
self.assertEqual(p.get_expression(), "r'asdf'")
p = get('9.17')
with self.assertRaises(ValueError) as ve:
p.get_expression()
self.assertIn('is inside a code', str(ve.exception))
p = get('10.0')
self.assertEqual(p.get_expression(), '')
p = get('10.6')
self.assertEqual(p.get_expression(), '')
p = get('10.11')
self.assertEqual(p.get_expression(), '')
p = get('11.3')
self.assertEqual(p.get_expression(), '')
p = get('11.11')
self.assertEqual(p.get_expression(), 'False')
p = get('12.6')
self.assertEqual(p.get_expression(), 'cliché')
def test_eat_identifier(self):
def is_valid_id(candidate):
result = HyperParser._eat_identifier(candidate, 0, len(candidate))
if result == len(candidate):
return True
elif result == 0:
return False
else:
err_msg = "Unexpected result: {} (expected 0 or {}".format(
result, len(candidate)
)
raise Exception(err_msg)
# invalid first character which is valid elsewhere in an identifier
self.assertFalse(is_valid_id('2notid'))
# ASCII-only valid identifiers
self.assertTrue(is_valid_id('valid_id'))
self.assertTrue(is_valid_id('_valid_id'))
self.assertTrue(is_valid_id('valid_id_'))
self.assertTrue(is_valid_id('_2valid_id'))
# keywords which should be "eaten"
self.assertTrue(is_valid_id('True'))
self.assertTrue(is_valid_id('False'))
self.assertTrue(is_valid_id('None'))
# keywords which should not be "eaten"
self.assertFalse(is_valid_id('for'))
self.assertFalse(is_valid_id('import'))
self.assertFalse(is_valid_id('return'))
# valid unicode identifiers
self.assertTrue(is_valid_id('cliche'))
self.assertTrue(is_valid_id('cliché'))
self.assertTrue(is_valid_id('aÙ¢'))
# invalid unicode identifiers
self.assertFalse(is_valid_id('2a'))
self.assertFalse(is_valid_id('Ù¢a'))
self.assertFalse(is_valid_id('a²'))
# valid identifier after "punctuation"
self.assertEqual(HyperParser._eat_identifier('+ var', 0, 5), len('var'))
self.assertEqual(HyperParser._eat_identifier('+var', 0, 4), len('var'))
self.assertEqual(HyperParser._eat_identifier('.var', 0, 4), len('var'))
# invalid identifiers
self.assertFalse(is_valid_id('+'))
self.assertFalse(is_valid_id(' '))
self.assertFalse(is_valid_id(':'))
self.assertFalse(is_valid_id('?'))
self.assertFalse(is_valid_id('^'))
self.assertFalse(is_valid_id('\\'))
self.assertFalse(is_valid_id('"'))
self.assertFalse(is_valid_id('"a string"'))
def test_eat_identifier_various_lengths(self):
eat_id = HyperParser._eat_identifier
for length in range(1, 21):
self.assertEqual(eat_id('a' * length, 0, length), length)
self.assertEqual(eat_id('é' * length, 0, length), length)
self.assertEqual(eat_id('a' + '2' * (length - 1), 0, length), length)
self.assertEqual(eat_id('é' + '2' * (length - 1), 0, length), length)
self.assertEqual(eat_id('é' + 'a' * (length - 1), 0, length), length)
self.assertEqual(eat_id('é' * (length - 1) + 'a', 0, length), length)
self.assertEqual(eat_id('+' * length, 0, length), 0)
self.assertEqual(eat_id('2' + 'a' * (length - 1), 0, length), 0)
self.assertEqual(eat_id('2' + 'é' * (length - 1), 0, length), 0)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 9,080 | 277 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/template.py | "Test , coverage %."
from idlelib import zzdummy
import unittest
from test.support import requires
from tkinter import Tk
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
## for id in cls.root.tk.call('after', 'info'):
## cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 642 | 31 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_run.py | "Test run, coverage 42%."
from idlelib import run
import unittest
from unittest import mock
from test.support import captured_stderr
import io
class RunTest(unittest.TestCase):
def test_print_exception_unhashable(self):
class UnhashableException(Exception):
def __eq__(self, other):
return True
ex1 = UnhashableException('ex1')
ex2 = UnhashableException('ex2')
try:
raise ex2 from ex1
except UnhashableException:
try:
raise ex1
except UnhashableException:
with captured_stderr() as output:
with mock.patch.object(run,
'cleanup_traceback') as ct:
ct.side_effect = lambda t, e: t
run.print_exception()
tb = output.getvalue().strip().splitlines()
self.assertEqual(11, len(tb))
self.assertIn('UnhashableException: ex2', tb[3])
self.assertIn('UnhashableException: ex1', tb[10])
# PseudoFile tests.
class S(str):
def __str__(self):
return '%s:str' % type(self).__name__
def __unicode__(self):
return '%s:unicode' % type(self).__name__
def __len__(self):
return 3
def __iter__(self):
return iter('abc')
def __getitem__(self, *args):
return '%s:item' % type(self).__name__
def __getslice__(self, *args):
return '%s:slice' % type(self).__name__
class MockShell:
def __init__(self):
self.reset()
def write(self, *args):
self.written.append(args)
def readline(self):
return self.lines.pop()
def close(self):
pass
def reset(self):
self.written = []
def push(self, lines):
self.lines = list(lines)[::-1]
class PseudeInputFilesTest(unittest.TestCase):
def test_misc(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
self.assertIsInstance(f, io.TextIOBase)
self.assertEqual(f.encoding, 'utf-8')
self.assertIsNone(f.errors)
self.assertIsNone(f.newlines)
self.assertEqual(f.name, '<stdin>')
self.assertFalse(f.closed)
self.assertTrue(f.isatty())
self.assertTrue(f.readable())
self.assertFalse(f.writable())
self.assertFalse(f.seekable())
def test_unsupported(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
self.assertRaises(OSError, f.fileno)
self.assertRaises(OSError, f.tell)
self.assertRaises(OSError, f.seek, 0)
self.assertRaises(OSError, f.write, 'x')
self.assertRaises(OSError, f.writelines, ['x'])
def test_read(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.read(), 'one\ntwo\n')
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.read(-1), 'one\ntwo\n')
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.read(None), 'one\ntwo\n')
shell.push(['one\n', 'two\n', 'three\n', ''])
self.assertEqual(f.read(2), 'on')
self.assertEqual(f.read(3), 'e\nt')
self.assertEqual(f.read(10), 'wo\nthree\n')
shell.push(['one\n', 'two\n'])
self.assertEqual(f.read(0), '')
self.assertRaises(TypeError, f.read, 1.5)
self.assertRaises(TypeError, f.read, '1')
self.assertRaises(TypeError, f.read, 1, 1)
def test_readline(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
shell.push(['one\n', 'two\n', 'three\n', 'four\n'])
self.assertEqual(f.readline(), 'one\n')
self.assertEqual(f.readline(-1), 'two\n')
self.assertEqual(f.readline(None), 'three\n')
shell.push(['one\ntwo\n'])
self.assertEqual(f.readline(), 'one\n')
self.assertEqual(f.readline(), 'two\n')
shell.push(['one', 'two', 'three'])
self.assertEqual(f.readline(), 'one')
self.assertEqual(f.readline(), 'two')
shell.push(['one\n', 'two\n', 'three\n'])
self.assertEqual(f.readline(2), 'on')
self.assertEqual(f.readline(1), 'e')
self.assertEqual(f.readline(1), '\n')
self.assertEqual(f.readline(10), 'two\n')
shell.push(['one\n', 'two\n'])
self.assertEqual(f.readline(0), '')
self.assertRaises(TypeError, f.readlines, 1.5)
self.assertRaises(TypeError, f.readlines, '1')
self.assertRaises(TypeError, f.readlines, 1, 1)
def test_readlines(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(), ['one\n', 'two\n'])
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(-1), ['one\n', 'two\n'])
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(None), ['one\n', 'two\n'])
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(0), ['one\n', 'two\n'])
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(3), ['one\n'])
shell.push(['one\n', 'two\n', ''])
self.assertEqual(f.readlines(4), ['one\n', 'two\n'])
shell.push(['one\n', 'two\n', ''])
self.assertRaises(TypeError, f.readlines, 1.5)
self.assertRaises(TypeError, f.readlines, '1')
self.assertRaises(TypeError, f.readlines, 1, 1)
def test_close(self):
shell = MockShell()
f = run.PseudoInputFile(shell, 'stdin', 'utf-8')
shell.push(['one\n', 'two\n', ''])
self.assertFalse(f.closed)
self.assertEqual(f.readline(), 'one\n')
f.close()
self.assertFalse(f.closed)
self.assertEqual(f.readline(), 'two\n')
self.assertRaises(TypeError, f.close, 1)
class PseudeOutputFilesTest(unittest.TestCase):
def test_misc(self):
shell = MockShell()
f = run.PseudoOutputFile(shell, 'stdout', 'utf-8')
self.assertIsInstance(f, io.TextIOBase)
self.assertEqual(f.encoding, 'utf-8')
self.assertIsNone(f.errors)
self.assertIsNone(f.newlines)
self.assertEqual(f.name, '<stdout>')
self.assertFalse(f.closed)
self.assertTrue(f.isatty())
self.assertFalse(f.readable())
self.assertTrue(f.writable())
self.assertFalse(f.seekable())
def test_unsupported(self):
shell = MockShell()
f = run.PseudoOutputFile(shell, 'stdout', 'utf-8')
self.assertRaises(OSError, f.fileno)
self.assertRaises(OSError, f.tell)
self.assertRaises(OSError, f.seek, 0)
self.assertRaises(OSError, f.read, 0)
self.assertRaises(OSError, f.readline, 0)
def test_write(self):
shell = MockShell()
f = run.PseudoOutputFile(shell, 'stdout', 'utf-8')
f.write('test')
self.assertEqual(shell.written, [('test', 'stdout')])
shell.reset()
f.write('t\xe8st')
self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
shell.reset()
f.write(S('t\xe8st'))
self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
self.assertEqual(type(shell.written[0][0]), str)
shell.reset()
self.assertRaises(TypeError, f.write)
self.assertEqual(shell.written, [])
self.assertRaises(TypeError, f.write, b'test')
self.assertRaises(TypeError, f.write, 123)
self.assertEqual(shell.written, [])
self.assertRaises(TypeError, f.write, 'test', 'spam')
self.assertEqual(shell.written, [])
def test_writelines(self):
shell = MockShell()
f = run.PseudoOutputFile(shell, 'stdout', 'utf-8')
f.writelines([])
self.assertEqual(shell.written, [])
shell.reset()
f.writelines(['one\n', 'two'])
self.assertEqual(shell.written,
[('one\n', 'stdout'), ('two', 'stdout')])
shell.reset()
f.writelines(['on\xe8\n', 'tw\xf2'])
self.assertEqual(shell.written,
[('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')])
shell.reset()
f.writelines([S('t\xe8st')])
self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
self.assertEqual(type(shell.written[0][0]), str)
shell.reset()
self.assertRaises(TypeError, f.writelines)
self.assertEqual(shell.written, [])
self.assertRaises(TypeError, f.writelines, 123)
self.assertEqual(shell.written, [])
self.assertRaises(TypeError, f.writelines, [b'test'])
self.assertRaises(TypeError, f.writelines, [123])
self.assertEqual(shell.written, [])
self.assertRaises(TypeError, f.writelines, [], [])
self.assertEqual(shell.written, [])
def test_close(self):
shell = MockShell()
f = run.PseudoOutputFile(shell, 'stdout', 'utf-8')
self.assertFalse(f.closed)
f.write('test')
f.close()
self.assertTrue(f.closed)
self.assertRaises(ValueError, f.write, 'x')
self.assertEqual(shell.written, [('test', 'stdout')])
f.close()
self.assertRaises(TypeError, f.close, 1)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 9,414 | 265 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_browser.py | "Test browser, coverage 90%."
from idlelib import browser
from test.support import requires
import unittest
from unittest import mock
from idlelib.idle_test.mock_idle import Func
from collections import deque
import os.path
from idlelib import _pyclbr as pyclbr
from tkinter import Tk
from idlelib.tree import TreeNode
class ModuleBrowserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.mb = browser.ModuleBrowser(cls.root, __file__, _utest=True)
@classmethod
def tearDownClass(cls):
cls.mb.close()
cls.root.update_idletasks()
cls.root.destroy()
del cls.root, cls.mb
def test_init(self):
mb = self.mb
eq = self.assertEqual
eq(mb.path, __file__)
eq(pyclbr._modules, {})
self.assertIsInstance(mb.node, TreeNode)
self.assertIsNotNone(browser.file_open)
def test_settitle(self):
mb = self.mb
self.assertIn(os.path.basename(__file__), mb.top.title())
self.assertEqual(mb.top.iconname(), 'Module Browser')
def test_rootnode(self):
mb = self.mb
rn = mb.rootnode()
self.assertIsInstance(rn, browser.ModuleBrowserTreeItem)
def test_close(self):
mb = self.mb
mb.top.destroy = Func()
mb.node.destroy = Func()
mb.close()
self.assertTrue(mb.top.destroy.called)
self.assertTrue(mb.node.destroy.called)
del mb.top.destroy, mb.node.destroy
# Nested tree same as in test_pyclbr.py except for supers on C0. C1.
mb = pyclbr
module, fname = 'test', 'test.py'
f0 = mb.Function(module, 'f0', fname, 1)
f1 = mb._nest_function(f0, 'f1', 2)
f2 = mb._nest_function(f1, 'f2', 3)
c1 = mb._nest_class(f0, 'c1', 5)
C0 = mb.Class(module, 'C0', ['base'], fname, 6)
F1 = mb._nest_function(C0, 'F1', 8)
C1 = mb._nest_class(C0, 'C1', 11, [''])
C2 = mb._nest_class(C1, 'C2', 12)
F3 = mb._nest_function(C2, 'F3', 14)
mock_pyclbr_tree = {'f0': f0, 'C0': C0}
# Adjust C0.name, C1.name so tests do not depend on order.
browser.transform_children(mock_pyclbr_tree, 'test') # C0(base)
browser.transform_children(C0.children) # C1()
# The class below checks that the calls above are correct
# and that duplicate calls have no effect.
class TransformChildrenTest(unittest.TestCase):
def test_transform_module_children(self):
eq = self.assertEqual
transform = browser.transform_children
# Parameter matches tree module.
tcl = list(transform(mock_pyclbr_tree, 'test'))
eq(tcl, [f0, C0])
eq(tcl[0].name, 'f0')
eq(tcl[1].name, 'C0(base)')
# Check that second call does not change suffix.
tcl = list(transform(mock_pyclbr_tree, 'test'))
eq(tcl[1].name, 'C0(base)')
# Nothing to traverse if parameter name isn't same as tree module.
tcl = list(transform(mock_pyclbr_tree, 'different name'))
eq(tcl, [])
def test_transform_node_children(self):
eq = self.assertEqual
transform = browser.transform_children
# Class with two children, one name altered.
tcl = list(transform(C0.children))
eq(tcl, [F1, C1])
eq(tcl[0].name, 'F1')
eq(tcl[1].name, 'C1()')
tcl = list(transform(C0.children))
eq(tcl[1].name, 'C1()')
# Function with two children.
eq(list(transform(f0.children)), [f1, c1])
class ModuleBrowserTreeItemTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.mbt = browser.ModuleBrowserTreeItem(fname)
def test_init(self):
self.assertEqual(self.mbt.file, fname)
def test_gettext(self):
self.assertEqual(self.mbt.GetText(), fname)
def test_geticonname(self):
self.assertEqual(self.mbt.GetIconName(), 'python')
def test_isexpandable(self):
self.assertTrue(self.mbt.IsExpandable())
def test_listchildren(self):
save_rex = browser.pyclbr.readmodule_ex
save_tc = browser.transform_children
browser.pyclbr.readmodule_ex = Func(result=mock_pyclbr_tree)
browser.transform_children = Func(result=[f0, C0])
try:
self.assertEqual(self.mbt.listchildren(), [f0, C0])
finally:
browser.pyclbr.readmodule_ex = save_rex
browser.transform_children = save_tc
def test_getsublist(self):
mbt = self.mbt
mbt.listchildren = Func(result=[f0, C0])
sub0, sub1 = mbt.GetSubList()
del mbt.listchildren
self.assertIsInstance(sub0, browser.ChildBrowserTreeItem)
self.assertIsInstance(sub1, browser.ChildBrowserTreeItem)
self.assertEqual(sub0.name, 'f0')
self.assertEqual(sub1.name, 'C0(base)')
@mock.patch('idlelib.browser.file_open')
def test_ondoubleclick(self, fopen):
mbt = self.mbt
with mock.patch('os.path.exists', return_value=False):
mbt.OnDoubleClick()
fopen.assert_not_called()
with mock.patch('os.path.exists', return_value=True):
mbt.OnDoubleClick()
fopen.assert_called()
fopen.called_with(fname)
class ChildBrowserTreeItemTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
CBT = browser.ChildBrowserTreeItem
cls.cbt_f1 = CBT(f1)
cls.cbt_C1 = CBT(C1)
cls.cbt_F1 = CBT(F1)
@classmethod
def tearDownClass(cls):
del cls.cbt_C1, cls.cbt_f1, cls.cbt_F1
def test_init(self):
eq = self.assertEqual
eq(self.cbt_C1.name, 'C1()')
self.assertFalse(self.cbt_C1.isfunction)
eq(self.cbt_f1.name, 'f1')
self.assertTrue(self.cbt_f1.isfunction)
def test_gettext(self):
self.assertEqual(self.cbt_C1.GetText(), 'class C1()')
self.assertEqual(self.cbt_f1.GetText(), 'def f1(...)')
def test_geticonname(self):
self.assertEqual(self.cbt_C1.GetIconName(), 'folder')
self.assertEqual(self.cbt_f1.GetIconName(), 'python')
def test_isexpandable(self):
self.assertTrue(self.cbt_C1.IsExpandable())
self.assertTrue(self.cbt_f1.IsExpandable())
self.assertFalse(self.cbt_F1.IsExpandable())
def test_getsublist(self):
eq = self.assertEqual
CBT = browser.ChildBrowserTreeItem
f1sublist = self.cbt_f1.GetSubList()
self.assertIsInstance(f1sublist[0], CBT)
eq(len(f1sublist), 1)
eq(f1sublist[0].name, 'f2')
eq(self.cbt_F1.GetSubList(), [])
@mock.patch('idlelib.browser.file_open')
def test_ondoubleclick(self, fopen):
goto = fopen.return_value.gotoline = mock.Mock()
self.cbt_F1.OnDoubleClick()
fopen.assert_called()
goto.assert_called()
goto.assert_called_with(self.cbt_F1.obj.lineno)
# Failure test would have to raise OSError or AttributeError.
class NestedChildrenTest(unittest.TestCase):
"Test that all the nodes in a nested tree are added to the BrowserTree."
def test_nested(self):
queue = deque()
actual_names = []
# The tree items are processed in breadth first order.
# Verify that processing each sublist hits every node and
# in the right order.
expected_names = ['f0', 'C0(base)',
'f1', 'c1', 'F1', 'C1()',
'f2', 'C2',
'F3']
CBT = browser.ChildBrowserTreeItem
queue.extend((CBT(f0), CBT(C0)))
while queue:
cb = queue.popleft()
sublist = cb.GetSubList()
queue.extend(sublist)
self.assertIn(cb.name, cb.GetText())
self.assertIn(cb.GetIconName(), ('python', 'folder'))
self.assertIs(cb.IsExpandable(), sublist != [])
actual_names.append(cb.name)
self.assertEqual(actual_names, expected_names)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 7,986 | 249 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_tree.py | "Test tree. coverage 56%."
from idlelib import tree
import unittest
from test.support import requires
requires('gui')
from tkinter import Tk
class TreeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def test_init(self):
# Start with code slightly adapted from htest.
sc = tree.ScrolledCanvas(
self.root, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both", side='left')
item = tree.FileTreeItem(tree.ICONDIR)
node = tree.TreeNode(sc.canvas, None, item)
node.expand()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 792 | 34 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/mock_idle.py | '''Mock classes that imitate idlelib modules or classes.
Attributes and methods will be added as needed for tests.
'''
from idlelib.idle_test.mock_tk import Text
class Func:
'''Record call, capture args, return/raise result set by test.
When mock function is called, set or use attributes:
self.called - increment call number even if no args, kwds passed.
self.args - capture positional arguments.
self.kwds - capture keyword arguments.
self.result - return or raise value set in __init__.
self.return_self - return self instead, to mock query class return.
Most common use will probably be to mock instance methods.
Given class instance, can set and delete as instance attribute.
Mock_tk.Var and Mbox_func are special variants of this.
'''
def __init__(self, result=None, return_self=False):
self.called = 0
self.result = result
self.return_self = return_self
self.args = None
self.kwds = None
def __call__(self, *args, **kwds):
self.called += 1
self.args = args
self.kwds = kwds
if isinstance(self.result, BaseException):
raise self.result
elif self.return_self:
return self
else:
return self.result
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None):
self.text = Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
first = self.text.index('1.0')
last = self.text.index('end')
return first, last
class UndoDelegator:
'''Minimally imitate undo.UndoDelegator class.
'''
# A real undo block is only needed for user interaction.
def undo_block_start(*args):
pass
def undo_block_stop(*args):
pass
| 1,870 | 61 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_debugger.py | "Test debugger, coverage 19%"
from idlelib import debugger
import unittest
from test.support import requires
requires('gui')
from tkinter import Tk
class NameSpaceTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def test_init(self):
debugger.NamespaceViewer(self.root, 'Test')
# Other classes are Idb, Debugger, and StackViewer.
if __name__ == '__main__':
unittest.main(verbosity=2)
| 571 | 30 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_grep.py | """ !Changing this line will break Test_findfile.test_found!
Non-gui unit tests for grep.GrepDialog methods.
dummy_command calls grep_it calls findfiles.
An exception raised in one method will fail callers.
Otherwise, tests are mostly independent.
Currently only test grep_it, coverage 51%.
"""
from idlelib.grep import GrepDialog
import unittest
from test.support import captured_stdout
from idlelib.idle_test.mock_tk import Var
import re
class Dummy_searchengine:
'''GrepDialog.__init__ calls parent SearchDiabolBase which attaches the
passed in SearchEngine instance as attribute 'engine'. Only a few of the
many possible self.engine.x attributes are needed here.
'''
def getpat(self):
return self._pat
searchengine = Dummy_searchengine()
class Dummy_grep:
# Methods tested
#default_command = GrepDialog.default_command
grep_it = GrepDialog.grep_it
findfiles = GrepDialog.findfiles
# Other stuff needed
recvar = Var(False)
engine = searchengine
def close(self): # gui method
pass
grep = Dummy_grep()
class FindfilesTest(unittest.TestCase):
# findfiles is really a function, not a method, could be iterator
# test that filename return filename
# test that idlelib has many .py files
# test that recursive flag adds idle_test .py files
pass
class Grep_itTest(unittest.TestCase):
# Test captured reports with 0 and some hits.
# Should test file names, but Windows reports have mixed / and \ separators
# from incomplete replacement, so 'later'.
def report(self, pat):
grep.engine._pat = pat
with captured_stdout() as s:
grep.grep_it(re.compile(pat), __file__)
lines = s.getvalue().split('\n')
lines.pop() # remove bogus '' after last \n
return lines
def test_unfound(self):
pat = 'xyz*'*7
lines = self.report(pat)
self.assertEqual(len(lines), 2)
self.assertIn(pat, lines[0])
self.assertEqual(lines[1], 'No hits.')
def test_found(self):
pat = '""" !Changing this line will break Test_findfile.test_found!'
lines = self.report(pat)
self.assertEqual(len(lines), 5)
self.assertIn(pat, lines[0])
self.assertIn('py: 1:', lines[1]) # line number 1
self.assertIn('2', lines[3]) # hits found 2
self.assertTrue(lines[4].startswith('(Hint:'))
class Default_commandTest(unittest.TestCase):
# To write this, move outwin import to top of GrepDialog
# so it can be replaced by captured_stdout in class setup/teardown.
pass
if __name__ == '__main__':
unittest.main(verbosity=2)
| 2,660 | 87 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_rpc.py | "Test rpc, coverage 20%."
from idlelib import rpc
import unittest
class CodePicklerTest(unittest.TestCase):
def test_pickle_unpickle(self):
def f(): return a + b + c
func, (cbytes,) = rpc.pickle_code(f.__code__)
self.assertIs(func, rpc.unpickle_code)
self.assertIn(b'test_rpc.py', cbytes)
code = rpc.unpickle_code(cbytes)
self.assertEqual(code.co_names, ('a', 'b', 'c'))
def test_code_pickler(self):
self.assertIn(type((lambda:None).__code__),
rpc.CodePickler.dispatch_table)
def test_dumps(self):
def f(): pass
# The main test here is that pickling code does not raise.
self.assertIn(b'test_rpc.py', rpc.dumps(f.__code__))
if __name__ == '__main__':
unittest.main(verbosity=2)
| 805 | 30 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_warning.py | '''Test warnings replacement in pyshell.py and run.py.
This file could be expanded to include traceback overrides
(in same two modules). If so, change name.
Revise if output destination changes (http://bugs.python.org/issue18318).
Make sure warnings module is left unaltered (http://bugs.python.org/issue18081).
'''
from idlelib import run
from idlelib import pyshell as shell
import unittest
from test.support import captured_stderr
import warnings
# Try to capture default showwarning before Idle modules are imported.
showwarning = warnings.showwarning
# But if we run this file within idle, we are in the middle of the run.main loop
# and default showwarnings has already been replaced.
running_in_idle = 'idle' in showwarning.__name__
# The following was generated from pyshell.idle_formatwarning
# and checked as matching expectation.
idlemsg = '''
Warning (from warnings module):
File "test_warning.py", line 99
Line of code
UserWarning: Test
'''
shellmsg = idlemsg + ">>> "
class RunWarnTest(unittest.TestCase):
@unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
def test_showwarnings(self):
self.assertIs(warnings.showwarning, showwarning)
run.capture_warnings(True)
self.assertIs(warnings.showwarning, run.idle_showwarning_subproc)
run.capture_warnings(False)
self.assertIs(warnings.showwarning, showwarning)
def test_run_show(self):
with captured_stderr() as f:
run.idle_showwarning_subproc(
'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
# The following uses .splitlines to erase line-ending differences
self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines())
class ShellWarnTest(unittest.TestCase):
@unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
def test_showwarnings(self):
self.assertIs(warnings.showwarning, showwarning)
shell.capture_warnings(True)
self.assertIs(warnings.showwarning, shell.idle_showwarning)
shell.capture_warnings(False)
self.assertIs(warnings.showwarning, showwarning)
def test_idle_formatter(self):
# Will fail if format changed without regenerating idlemsg
s = shell.idle_formatwarning(
'Test', UserWarning, 'test_warning.py', 99, 'Line of code')
self.assertEqual(idlemsg, s)
def test_shell_show(self):
with captured_stderr() as f:
shell.idle_showwarning(
'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines())
if __name__ == '__main__':
unittest.main(verbosity=2)
| 2,740 | 74 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_runscript.py | "Test runscript, coverage 16%."
from idlelib import runscript
import unittest
from test.support import requires
from tkinter import Tk
from idlelib.editor import EditorWindow
class ScriptBindingTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
for id in cls.root.tk.call('after', 'info'):
cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
ew = EditorWindow(root=self.root)
sb = runscript.ScriptBinding(ew)
ew._close()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 777 | 34 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_autocomplete_w.py | "Test autocomplete_w, coverage 11%."
import unittest
from test.support import requires
from tkinter import Tk, Text
import idlelib.autocomplete_w as acw
class AutoCompleteWindowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
cls.acw = acw.AutoCompleteWindow(cls.text)
@classmethod
def tearDownClass(cls):
del cls.text, cls.acw
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def test_init(self):
self.assertEqual(self.acw.widget, self.text)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 709 | 33 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_filelist.py | "Test filelist, coverage 19%."
from idlelib import filelist
import unittest
from test.support import requires
from tkinter import Tk
class FileListTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
for id in cls.root.tk.call('after', 'info'):
cls.root.after_cancel(id)
cls.root.destroy()
del cls.root
def test_new_empty(self):
flist = filelist.FileList(self.root)
self.assertEqual(flist.root, self.root)
e = flist.new()
self.assertEqual(type(e), flist.EditorWindow)
e._close()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 795 | 34 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_history.py | " Test history, coverage 100%."
from idlelib.history import History
import unittest
from test.support import requires
import tkinter as tk
from tkinter import Text as tkText
from idlelib.idle_test.mock_tk import Text as mkText
from idlelib.config import idleConf
line1 = 'a = 7'
line2 = 'b = a'
class StoreTest(unittest.TestCase):
'''Tests History.__init__ and History.store with mock Text'''
@classmethod
def setUpClass(cls):
cls.text = mkText()
cls.history = History(cls.text)
def tearDown(self):
self.text.delete('1.0', 'end')
self.history.history = []
def test_init(self):
self.assertIs(self.history.text, self.text)
self.assertEqual(self.history.history, [])
self.assertIsNone(self.history.prefix)
self.assertIsNone(self.history.pointer)
self.assertEqual(self.history.cyclic,
idleConf.GetOption("main", "History", "cyclic", 1, "bool"))
def test_store_short(self):
self.history.store('a')
self.assertEqual(self.history.history, [])
self.history.store(' a ')
self.assertEqual(self.history.history, [])
def test_store_dup(self):
self.history.store(line1)
self.assertEqual(self.history.history, [line1])
self.history.store(line2)
self.assertEqual(self.history.history, [line1, line2])
self.history.store(line1)
self.assertEqual(self.history.history, [line2, line1])
def test_store_reset(self):
self.history.prefix = line1
self.history.pointer = 0
self.history.store(line2)
self.assertIsNone(self.history.prefix)
self.assertIsNone(self.history.pointer)
class TextWrapper:
def __init__(self, master):
self.text = tkText(master=master)
self._bell = False
def __getattr__(self, name):
return getattr(self.text, name)
def bell(self):
self._bell = True
class FetchTest(unittest.TestCase):
'''Test History.fetch with wrapped tk.Text.
'''
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = tk.Tk()
cls.root.withdraw()
def setUp(self):
self.text = text = TextWrapper(self.root)
text.insert('1.0', ">>> ")
text.mark_set('iomark', '1.4')
text.mark_gravity('iomark', 'left')
self.history = History(text)
self.history.history = [line1, line2]
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def fetch_test(self, reverse, line, prefix, index, *, bell=False):
# Perform one fetch as invoked by Alt-N or Alt-P
# Test the result. The line test is the most important.
# The last two are diagnostic of fetch internals.
History = self.history
History.fetch(reverse)
Equal = self.assertEqual
Equal(self.text.get('iomark', 'end-1c'), line)
Equal(self.text._bell, bell)
if bell:
self.text._bell = False
Equal(History.prefix, prefix)
Equal(History.pointer, index)
Equal(self.text.compare("insert", '==', "end-1c"), 1)
def test_fetch_prev_cyclic(self):
prefix = ''
test = self.fetch_test
test(True, line2, prefix, 1)
test(True, line1, prefix, 0)
test(True, prefix, None, None, bell=True)
def test_fetch_next_cyclic(self):
prefix = ''
test = self.fetch_test
test(False, line1, prefix, 0)
test(False, line2, prefix, 1)
test(False, prefix, None, None, bell=True)
# Prefix 'a' tests skip line2, which starts with 'b'
def test_fetch_prev_prefix(self):
prefix = 'a'
self.text.insert('iomark', prefix)
self.fetch_test(True, line1, prefix, 0)
self.fetch_test(True, prefix, None, None, bell=True)
def test_fetch_next_prefix(self):
prefix = 'a'
self.text.insert('iomark', prefix)
self.fetch_test(False, line1, prefix, 0)
self.fetch_test(False, prefix, None, None, bell=True)
def test_fetch_prev_noncyclic(self):
prefix = ''
self.history.cyclic = False
test = self.fetch_test
test(True, line2, prefix, 1)
test(True, line1, prefix, 0)
test(True, line1, prefix, 0, bell=True)
def test_fetch_next_noncyclic(self):
prefix = ''
self.history.cyclic = False
test = self.fetch_test
test(False, prefix, None, None, bell=True)
test(True, line2, prefix, 1)
test(False, prefix, None, None, bell=True)
test(False, prefix, None, None, bell=True)
def test_fetch_cursor_move(self):
# Move cursor after fetch
self.history.fetch(reverse=True) # initialization
self.text.mark_set('insert', 'iomark')
self.fetch_test(True, line2, None, None, bell=True)
def test_fetch_edit(self):
# Edit after fetch
self.history.fetch(reverse=True) # initialization
self.text.delete('iomark', 'insert', )
self.text.insert('iomark', 'a =')
self.fetch_test(True, line1, 'a =', 0) # prefix is reset
def test_history_prev_next(self):
# Minimally test functions bound to events
self.history.history_prev('dummy event')
self.assertEqual(self.history.pointer, 1)
self.history.history_next('dummy event')
self.assertEqual(self.history.pointer, None)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
| 5,517 | 173 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_help.py | "Test help, coverage 87%."
from idlelib import help
import unittest
from test.support import requires
requires('gui')
from os.path import abspath, dirname, join
from tkinter import Tk
class HelpFrameTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
"By itself, this tests that file parsed without exception."
cls.root = root = Tk()
root.withdraw()
helpfile = join(dirname(dirname(abspath(__file__))), 'help.html')
cls.frame = help.HelpFrame(root, helpfile)
@classmethod
def tearDownClass(cls):
del cls.frame
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def test_line1(self):
text = self.frame.text
self.assertEqual(text.get('1.0', '1.end'), ' IDLE ')
if __name__ == '__main__':
unittest.main(verbosity=2)
| 849 | 35 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_redirector.py | "Test redirector, coverage 100%."
from idlelib.redirector import WidgetRedirector
import unittest
from test.support import requires
from tkinter import Tk, Text, TclError
from idlelib.idle_test.mock_idle import Func
class InitCloseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.destroy()
del cls.root
def test_init(self):
redir = WidgetRedirector(self.text)
self.assertEqual(redir.widget, self.text)
self.assertEqual(redir.tk, self.text.tk)
self.assertRaises(TclError, WidgetRedirector, self.text)
redir.close() # restore self.tk, self.text
def test_close(self):
redir = WidgetRedirector(self.text)
redir.register('insert', Func)
redir.close()
self.assertEqual(redir._operations, {})
self.assertFalse(hasattr(self.text, 'widget'))
class WidgetRedirectorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def setUp(self):
self.redir = WidgetRedirector(self.text)
self.func = Func()
self.orig_insert = self.redir.register('insert', self.func)
self.text.insert('insert', 'asdf') # leaves self.text empty
def tearDown(self):
self.text.delete('1.0', 'end')
self.redir.close()
def test_repr(self): # partly for 100% coverage
self.assertIn('Redirector', repr(self.redir))
self.assertIn('Original', repr(self.orig_insert))
def test_register(self):
self.assertEqual(self.text.get('1.0', 'end'), '\n')
self.assertEqual(self.func.args, ('insert', 'asdf'))
self.assertIn('insert', self.redir._operations)
self.assertIn('insert', self.text.__dict__)
self.assertEqual(self.text.insert, self.func)
def test_original_command(self):
self.assertEqual(self.orig_insert.operation, 'insert')
self.assertEqual(self.orig_insert.tk_call, self.text.tk.call)
self.orig_insert('insert', 'asdf')
self.assertEqual(self.text.get('1.0', 'end'), 'asdf\n')
def test_unregister(self):
self.assertIsNone(self.redir.unregister('invalid operation name'))
self.assertEqual(self.redir.unregister('insert'), self.func)
self.assertNotIn('insert', self.redir._operations)
self.assertNotIn('insert', self.text.__dict__)
def test_unregister_no_attribute(self):
del self.text.insert
self.assertEqual(self.redir.unregister('insert'), self.func)
def test_dispatch_intercept(self):
self.func.__init__(True)
self.assertTrue(self.redir.dispatch('insert', False))
self.assertFalse(self.func.args[0])
def test_dispatch_bypass(self):
self.orig_insert('insert', 'asdf')
# tk.call returns '' where Python would return None
self.assertEqual(self.redir.dispatch('delete', '1.0', 'end'), '')
self.assertEqual(self.text.get('1.0', 'end'), '\n')
def test_dispatch_error(self):
self.func.__init__(TclError())
self.assertEqual(self.redir.dispatch('insert', False), '')
self.assertEqual(self.redir.dispatch('invalid'), '')
def test_command_dispatch(self):
# Test that .__init__ causes redirection of tk calls
# through redir.dispatch
self.root.call(self.text._w, 'insert', 'hello')
self.assertEqual(self.func.args, ('hello',))
self.assertEqual(self.text.get('1.0', 'end'), '\n')
# Ensure that called through redir .dispatch and not through
# self.text.insert by having mock raise TclError.
self.func.__init__(TclError())
self.assertEqual(self.root.call(self.text._w, 'insert', 'boo'), '')
if __name__ == '__main__':
unittest.main(verbosity=2)
| 4,176 | 123 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/htest.py | '''Run human tests of Idle's window, dialog, and popup widgets.
run(*tests)
Create a master Tk window. Within that, run each callable in tests
after finding the matching test spec in this file. If tests is empty,
run an htest for each spec dict in this file after finding the matching
callable in the module named in the spec. Close the window to skip or
end the test.
In a tested module, let X be a global name bound to a callable (class
or function) whose .__name__ attribute is also X (the usual situation).
The first parameter of X must be 'parent'. When called, the parent
argument will be the root window. X must create a child Toplevel
window (or subclass thereof). The Toplevel may be a test widget or
dialog, in which case the callable is the corresonding class. Or the
Toplevel may contain the widget to be tested or set up a context in
which a test widget is invoked. In this latter case, the callable is a
wrapper function that sets up the Toplevel and other objects. Wrapper
function names, such as _editor_window', should start with '_'.
End the module with
if __name__ == '__main__':
<unittest, if there is one>
from idlelib.idle_test.htest import run
run(X)
To have wrapper functions and test invocation code ignored by coveragepy
reports, put '# htest #' on the def statement header line.
def _wrapper(parent): # htest #
Also make sure that the 'if __name__' line matches the above. Then have
make sure that .coveragerc includes the following.
[report]
exclude_lines =
.*# htest #
if __name__ == .__main__.:
(The "." instead of "'" is intentional and necessary.)
To run any X, this file must contain a matching instance of the
following template, with X.__name__ prepended to '_spec'.
When all tests are run, the prefix is use to get X.
_spec = {
'file': '',
'kwds': {'title': ''},
'msg': ""
}
file (no .py): run() imports file.py.
kwds: augmented with {'parent':root} and passed to X as **kwds.
title: an example kwd; some widgets need this, delete if not.
msg: master window hints about testing the widget.
Modules and classes not being tested at the moment:
pyshell.PyShellEditorWindow
debugger.Debugger
autocomplete_w.AutoCompleteWindow
outwin.OutputWindow (indirectly being tested with grep test)
'''
import idlelib.pyshell # Set Windows DPI awareness before Tk().
from importlib import import_module
import tkinter as tk
from tkinter.ttk import Scrollbar
tk.NoDefaultRoot()
AboutDialog_spec = {
'file': 'help_about',
'kwds': {'title': 'help_about test',
'_htest': True,
},
'msg': "Test every button. Ensure Python, TK and IDLE versions "
"are correctly displayed.\n [Close] to exit.",
}
# TODO implement ^\; adding '<Control-Key-\\>' to function does not work.
_calltip_window_spec = {
'file': 'calltip_w',
'kwds': {},
'msg': "Typing '(' should display a calltip.\n"
"Typing ') should hide the calltip.\n"
"So should moving cursor out of argument area.\n"
"Force-open-calltip does not work here.\n"
}
_module_browser_spec = {
'file': 'browser',
'kwds': {},
'msg': "Inspect names of module, class(with superclass if "
"applicable), methods and functions.\nToggle nested items.\n"
"Double clicking on items prints a traceback for an exception "
"that is ignored."
}
_color_delegator_spec = {
'file': 'colorizer',
'kwds': {},
'msg': "The text is sample Python code.\n"
"Ensure components like comments, keywords, builtins,\n"
"string, definitions, and break are correctly colored.\n"
"The default color scheme is in idlelib/config-highlight.def"
}
ConfigDialog_spec = {
'file': 'configdialog',
'kwds': {'title': 'ConfigDialogTest',
'_htest': True,},
'msg': "IDLE preferences dialog.\n"
"In the 'Fonts/Tabs' tab, changing font face, should update the "
"font face of the text in the area below it.\nIn the "
"'Highlighting' tab, try different color schemes. Clicking "
"items in the sample program should update the choices above it."
"\nIn the 'Keys', 'General' and 'Extensions' tabs, test settings "
"of interest."
"\n[Ok] to close the dialog.[Apply] to apply the settings and "
"and [Cancel] to revert all changes.\nRe-run the test to ensure "
"changes made have persisted."
}
# TODO Improve message
_dyn_option_menu_spec = {
'file': 'dynoption',
'kwds': {},
'msg': "Select one of the many options in the 'old option set'.\n"
"Click the button to change the option set.\n"
"Select one of the many options in the 'new option set'."
}
# TODO edit wrapper
_editor_window_spec = {
'file': 'editor',
'kwds': {},
'msg': "Test editor functions of interest.\n"
"Best to close editor first."
}
# Update once issue21519 is resolved.
GetKeysDialog_spec = {
'file': 'config_key',
'kwds': {'title': 'Test keybindings',
'action': 'find-again',
'currentKeySequences': [''] ,
'_htest': True,
},
'msg': "Test for different key modifier sequences.\n"
"<nothing> is invalid.\n"
"No modifier key is invalid.\n"
"Shift key with [a-z],[0-9], function key, move key, tab, space "
"is invalid.\nNo validity checking if advanced key binding "
"entry is used."
}
_grep_dialog_spec = {
'file': 'grep',
'kwds': {},
'msg': "Click the 'Show GrepDialog' button.\n"
"Test the various 'Find-in-files' functions.\n"
"The results should be displayed in a new '*Output*' window.\n"
"'Right-click'->'Go to file/line' anywhere in the search results "
"should open that file \nin a new EditorWindow."
}
HelpSource_spec = {
'file': 'query',
'kwds': {'title': 'Help name and source',
'menuitem': 'test',
'filepath': __file__,
'used_names': {'abc'},
'_htest': True},
'msg': "Enter menu item name and help file path\n"
"'', > than 30 chars, and 'abc' are invalid menu item names.\n"
"'' and file does not exist are invalid path items.\n"
"Any url ('www...', 'http...') is accepted.\n"
"Test Browse with and without path, as cannot unittest.\n"
"[Ok] or <Return> prints valid entry to shell\n"
"[Cancel] or <Escape> prints None to shell"
}
_io_binding_spec = {
'file': 'iomenu',
'kwds': {},
'msg': "Test the following bindings.\n"
"<Control-o> to open file from dialog.\n"
"Edit the file.\n"
"<Control-p> to print the file.\n"
"<Control-s> to save the file.\n"
"<Alt-s> to save-as another file.\n"
"<Control-c> to save-copy-as another file.\n"
"Check that changes were saved by opening the file elsewhere."
}
_multi_call_spec = {
'file': 'multicall',
'kwds': {},
'msg': "The following actions should trigger a print to console or IDLE"
" Shell.\nEntering and leaving the text area, key entry, "
"<Control-Key>,\n<Alt-Key-a>, <Control-Key-a>, "
"<Alt-Control-Key-a>, \n<Control-Button-1>, <Alt-Button-1> and "
"focusing out of the window\nare sequences to be tested."
}
_multistatus_bar_spec = {
'file': 'statusbar',
'kwds': {},
'msg': "Ensure presence of multi-status bar below text area.\n"
"Click 'Update Status' to change the multi-status text"
}
_object_browser_spec = {
'file': 'debugobj',
'kwds': {},
'msg': "Double click on items upto the lowest level.\n"
"Attributes of the objects and related information "
"will be displayed side-by-side at each level."
}
_path_browser_spec = {
'file': 'pathbrowser',
'kwds': {},
'msg': "Test for correct display of all paths in sys.path.\n"
"Toggle nested items upto the lowest level.\n"
"Double clicking on an item prints a traceback\n"
"for an exception that is ignored."
}
_percolator_spec = {
'file': 'percolator',
'kwds': {},
'msg': "There are two tracers which can be toggled using a checkbox.\n"
"Toggling a tracer 'on' by checking it should print tracer "
"output to the console or to the IDLE shell.\n"
"If both the tracers are 'on', the output from the tracer which "
"was switched 'on' later, should be printed first\n"
"Test for actions like text entry, and removal."
}
Query_spec = {
'file': 'query',
'kwds': {'title': 'Query',
'message': 'Enter something',
'text0': 'Go',
'_htest': True},
'msg': "Enter with <Return> or [Ok]. Print valid entry to Shell\n"
"Blank line, after stripping, is ignored\n"
"Close dialog with valid entry, <Escape>, [Cancel], [X]"
}
_replace_dialog_spec = {
'file': 'replace',
'kwds': {},
'msg': "Click the 'Replace' button.\n"
"Test various replace options in the 'Replace dialog'.\n"
"Click [Close] or [X] to close the 'Replace Dialog'."
}
_search_dialog_spec = {
'file': 'search',
'kwds': {},
'msg': "Click the 'Search' button.\n"
"Test various search options in the 'Search dialog'.\n"
"Click [Close] or [X] to close the 'Search Dialog'."
}
_searchbase_spec = {
'file': 'searchbase',
'kwds': {},
'msg': "Check the appearance of the base search dialog\n"
"Its only action is to close."
}
_scrolled_list_spec = {
'file': 'scrolledlist',
'kwds': {},
'msg': "You should see a scrollable list of items\n"
"Selecting (clicking) or double clicking an item "
"prints the name to the console or Idle shell.\n"
"Right clicking an item will display a popup."
}
show_idlehelp_spec = {
'file': 'help',
'kwds': {},
'msg': "If the help text displays, this works.\n"
"Text is selectable. Window is scrollable."
}
_stack_viewer_spec = {
'file': 'stackviewer',
'kwds': {},
'msg': "A stacktrace for a NameError exception.\n"
"Expand 'idlelib ...' and '<locals>'.\n"
"Check that exc_value, exc_tb, and exc_type are correct.\n"
}
_tooltip_spec = {
'file': 'tooltip',
'kwds': {},
'msg': "Place mouse cursor over both the buttons\n"
"A tooltip should appear with some text."
}
_tree_widget_spec = {
'file': 'tree',
'kwds': {},
'msg': "The canvas is scrollable.\n"
"Click on folders upto to the lowest level."
}
_undo_delegator_spec = {
'file': 'undo',
'kwds': {},
'msg': "Click [Undo] to undo any action.\n"
"Click [Redo] to redo any action.\n"
"Click [Dump] to dump the current state "
"by printing to the console or the IDLE shell.\n"
}
ViewWindow_spec = {
'file': 'textview',
'kwds': {'title': 'Test textview',
'text': 'The quick brown fox jumps over the lazy dog.\n'*35,
'_htest': True},
'msg': "Test for read-only property of text.\n"
"Select text, scroll window, close"
}
_widget_redirector_spec = {
'file': 'redirector',
'kwds': {},
'msg': "Every text insert should be printed to the console "
"or the IDLE shell."
}
def run(*tests):
root = tk.Tk()
root.title('IDLE htest')
root.resizable(0, 0)
# a scrollable Label like constant width text widget.
frameLabel = tk.Frame(root, padx=10)
frameLabel.pack()
text = tk.Text(frameLabel, wrap='word')
text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70)
scrollbar = Scrollbar(frameLabel, command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(side='right', fill='y', expand=False)
text.pack(side='left', fill='both', expand=True)
test_list = [] # List of tuples of the form (spec, callable widget)
if tests:
for test in tests:
test_spec = globals()[test.__name__ + '_spec']
test_spec['name'] = test.__name__
test_list.append((test_spec, test))
else:
for k, d in globals().items():
if k.endswith('_spec'):
test_name = k[:-5]
test_spec = d
test_spec['name'] = test_name
mod = import_module('idlelib.' + test_spec['file'])
test = getattr(mod, test_name)
test_list.append((test_spec, test))
test_name = tk.StringVar(root)
callable_object = None
test_kwds = None
def next_test():
nonlocal test_name, callable_object, test_kwds
if len(test_list) == 1:
next_button.pack_forget()
test_spec, callable_object = test_list.pop()
test_kwds = test_spec['kwds']
test_kwds['parent'] = root
test_name.set('Test ' + test_spec['name'])
text.configure(state='normal') # enable text editing
text.delete('1.0','end')
text.insert("1.0",test_spec['msg'])
text.configure(state='disabled') # preserve read-only property
def run_test(_=None):
widget = callable_object(**test_kwds)
try:
print(widget.result)
except AttributeError:
pass
def close(_=None):
root.destroy()
button = tk.Button(root, textvariable=test_name,
default='active', command=run_test)
next_button = tk.Button(root, text="Next", command=next_test)
button.pack()
next_button.pack()
next_button.focus_set()
root.bind('<Key-Return>', run_test)
root.bind('<Key-Escape>', close)
next_test()
root.mainloop()
if __name__ == '__main__':
run()
| 13,997 | 416 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_debugobj.py | "Test debugobj, coverage 40%."
from idlelib import debugobj
import unittest
class ObjectTreeItemTest(unittest.TestCase):
def test_init(self):
ti = debugobj.ObjectTreeItem('label', 22)
self.assertEqual(ti.labeltext, 'label')
self.assertEqual(ti.object, 22)
self.assertEqual(ti.setfunction, None)
class ClassTreeItemTest(unittest.TestCase):
def test_isexpandable(self):
ti = debugobj.ClassTreeItem('label', 0)
self.assertTrue(ti.IsExpandable())
class AtomicObjectTreeItemTest(unittest.TestCase):
def test_isexpandable(self):
ti = debugobj.AtomicObjectTreeItem('label', 0)
self.assertFalse(ti.IsExpandable())
class SequenceTreeItemTest(unittest.TestCase):
def test_isexpandable(self):
ti = debugobj.SequenceTreeItem('label', ())
self.assertFalse(ti.IsExpandable())
ti = debugobj.SequenceTreeItem('label', (1,))
self.assertTrue(ti.IsExpandable())
def test_keys(self):
ti = debugobj.SequenceTreeItem('label', 'abc')
self.assertEqual(list(ti.keys()), [0, 1, 2])
class DictTreeItemTest(unittest.TestCase):
def test_isexpandable(self):
ti = debugobj.DictTreeItem('label', {})
self.assertFalse(ti.IsExpandable())
ti = debugobj.DictTreeItem('label', {1:1})
self.assertTrue(ti.IsExpandable())
def test_keys(self):
ti = debugobj.DictTreeItem('label', {1:1, 0:0, 2:2})
self.assertEqual(ti.keys(), [0, 1, 2])
if __name__ == '__main__':
unittest.main(verbosity=2)
| 1,561 | 58 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_colorizer.py | "Test colorizer, coverage 25%."
from idlelib import colorizer
from test.support import requires
from tkinter import Tk, Text
import unittest
class FunctionTest(unittest.TestCase):
def test_any(self):
self.assertTrue(colorizer.any('test', ('a', 'b')))
def test_make_pat(self):
self.assertTrue(colorizer.make_pat())
class ColorConfigTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.text = Text(cls.root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.destroy()
del cls.root
def test_colorizer(self):
colorizer.color_config(self.text)
class ColorDelegatorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def test_colorizer(self):
colorizer.ColorDelegator()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 1,058 | 54 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_zoomheight.py | "Test zoomheight, coverage 66%."
# Some code is system dependent.
from idlelib import zoomheight
import unittest
from test.support import requires
from tkinter import Tk
from idlelib.editor import EditorWindow
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.editwin = EditorWindow(root=cls.root)
@classmethod
def tearDownClass(cls):
cls.editwin._close()
cls.root.update_idletasks()
for id in cls.root.tk.call('after', 'info'):
cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
zoom = zoomheight.ZoomHeight(self.editwin)
self.assertIs(zoom.editwin, self.editwin)
def test_zoom_height_event(self):
zoom = zoomheight.ZoomHeight(self.editwin)
zoom.zoom_height_event()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 999 | 40 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_percolator.py | "Test percolator, coverage 100%."
from idlelib.percolator import Percolator, Delegator
import unittest
from test.support import requires
requires('gui')
from tkinter import Text, Tk, END
class MyFilter(Delegator):
def __init__(self):
Delegator.__init__(self, None)
def insert(self, *args):
self.insert_called_with = args
self.delegate.insert(*args)
def delete(self, *args):
self.delete_called_with = args
self.delegate.delete(*args)
def uppercase_insert(self, index, chars, tags=None):
chars = chars.upper()
self.delegate.insert(index, chars)
def lowercase_insert(self, index, chars, tags=None):
chars = chars.lower()
self.delegate.insert(index, chars)
def dont_insert(self, index, chars, tags=None):
pass
class PercolatorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.text = Text(cls.root)
@classmethod
def tearDownClass(cls):
del cls.text
cls.root.destroy()
del cls.root
def setUp(self):
self.percolator = Percolator(self.text)
self.filter_one = MyFilter()
self.filter_two = MyFilter()
self.percolator.insertfilter(self.filter_one)
self.percolator.insertfilter(self.filter_two)
def tearDown(self):
self.percolator.close()
self.text.delete('1.0', END)
def test_insertfilter(self):
self.assertIsNotNone(self.filter_one.delegate)
self.assertEqual(self.percolator.top, self.filter_two)
self.assertEqual(self.filter_two.delegate, self.filter_one)
self.assertEqual(self.filter_one.delegate, self.percolator.bottom)
def test_removefilter(self):
filter_three = MyFilter()
self.percolator.removefilter(self.filter_two)
self.assertEqual(self.percolator.top, self.filter_one)
self.assertIsNone(self.filter_two.delegate)
filter_three = MyFilter()
self.percolator.insertfilter(self.filter_two)
self.percolator.insertfilter(filter_three)
self.percolator.removefilter(self.filter_one)
self.assertEqual(self.percolator.top, filter_three)
self.assertEqual(filter_three.delegate, self.filter_two)
self.assertEqual(self.filter_two.delegate, self.percolator.bottom)
self.assertIsNone(self.filter_one.delegate)
def test_insert(self):
self.text.insert('insert', 'foo')
self.assertEqual(self.text.get('1.0', END), 'foo\n')
self.assertTupleEqual(self.filter_one.insert_called_with,
('insert', 'foo', None))
def test_modify_insert(self):
self.filter_one.insert = self.filter_one.uppercase_insert
self.text.insert('insert', 'bAr')
self.assertEqual(self.text.get('1.0', END), 'BAR\n')
def test_modify_chain_insert(self):
filter_three = MyFilter()
self.percolator.insertfilter(filter_three)
self.filter_two.insert = self.filter_two.uppercase_insert
self.filter_one.insert = self.filter_one.lowercase_insert
self.text.insert('insert', 'BaR')
self.assertEqual(self.text.get('1.0', END), 'bar\n')
def test_dont_insert(self):
self.filter_one.insert = self.filter_one.dont_insert
self.text.insert('insert', 'foo bar')
self.assertEqual(self.text.get('1.0', END), '\n')
self.filter_one.insert = self.filter_one.dont_insert
self.text.insert('insert', 'foo bar')
self.assertEqual(self.text.get('1.0', END), '\n')
def test_without_filter(self):
self.text.insert('insert', 'hello')
self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')
def test_delete(self):
self.text.insert('insert', 'foo')
self.text.delete('1.0', '1.2')
self.assertEqual(self.text.get('1.0', END), 'o\n')
self.assertTupleEqual(self.filter_one.delete_called_with,
('1.0', '1.2'))
if __name__ == '__main__':
unittest.main(verbosity=2)
| 4,065 | 119 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_pyparse.py | "Test pyparse, coverage 96%."
from idlelib import pyparse
import unittest
from collections import namedtuple
class ParseMapTest(unittest.TestCase):
def test_parsemap(self):
keepwhite = {ord(c): ord(c) for c in ' \t\n\r'}
mapping = pyparse.ParseMap(keepwhite)
self.assertEqual(mapping[ord('\t')], ord('\t'))
self.assertEqual(mapping[ord('a')], ord('x'))
self.assertEqual(mapping[1000], ord('x'))
def test_trans(self):
# trans is the production instance of ParseMap, used in _study1
parser = pyparse.Parser(4, 4)
self.assertEqual('\t a([{b}])b"c\'d\n'.translate(pyparse.trans),
'xxx(((x)))x"x\'x\n')
class PyParseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.parser = pyparse.Parser(indentwidth=4, tabwidth=4)
@classmethod
def tearDownClass(cls):
del cls.parser
def test_init(self):
self.assertEqual(self.parser.indentwidth, 4)
self.assertEqual(self.parser.tabwidth, 4)
def test_set_code(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
# Not empty and doesn't end with newline.
with self.assertRaises(AssertionError):
setcode('a')
tests = ('',
'a\n')
for string in tests:
with self.subTest(string=string):
setcode(string)
eq(p.code, string)
eq(p.study_level, 0)
def test_find_good_parse_start(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
start = p.find_good_parse_start
# Split def across lines.
setcode('"""This is a module docstring"""\n'
'class C():\n'
' def __init__(self, a,\n'
' b=True):\n'
' pass\n'
)
# No value sent for is_char_in_string().
self.assertIsNone(start())
# Make text look like a string. This returns pos as the start
# position, but it's set to None.
self.assertIsNone(start(is_char_in_string=lambda index: True))
# Make all text look like it's not in a string. This means that it
# found a good start position.
eq(start(is_char_in_string=lambda index: False), 44)
# If the beginning of the def line is not in a string, then it
# returns that as the index.
eq(start(is_char_in_string=lambda index: index > 44), 44)
# If the beginning of the def line is in a string, then it
# looks for a previous index.
eq(start(is_char_in_string=lambda index: index >= 44), 33)
# If everything before the 'def' is in a string, then returns None.
# The non-continuation def line returns 44 (see below).
eq(start(is_char_in_string=lambda index: index < 44), None)
# Code without extra line break in def line - mostly returns the same
# values.
setcode('"""This is a module docstring"""\n'
'class C():\n'
' def __init__(self, a, b=True):\n'
' pass\n'
)
eq(start(is_char_in_string=lambda index: False), 44)
eq(start(is_char_in_string=lambda index: index > 44), 44)
eq(start(is_char_in_string=lambda index: index >= 44), 33)
# When the def line isn't split, this returns which doesn't match the
# split line test.
eq(start(is_char_in_string=lambda index: index < 44), 44)
def test_set_lo(self):
code = (
'"""This is a module docstring"""\n'
'class C():\n'
' def __init__(self, a,\n'
' b=True):\n'
' pass\n'
)
p = self.parser
p.set_code(code)
# Previous character is not a newline.
with self.assertRaises(AssertionError):
p.set_lo(5)
# A value of 0 doesn't change self.code.
p.set_lo(0)
self.assertEqual(p.code, code)
# An index that is preceded by a newline.
p.set_lo(44)
self.assertEqual(p.code, code[44:])
def test_study1(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
study = p._study1
(NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
TestInfo = namedtuple('TestInfo', ['string', 'goodlines',
'continuation'])
tests = (
TestInfo('', [0], NONE),
# Docstrings.
TestInfo('"""This is a complete docstring."""\n', [0, 1], NONE),
TestInfo("'''This is a complete docstring.'''\n", [0, 1], NONE),
TestInfo('"""This is a continued docstring.\n', [0, 1], FIRST),
TestInfo("'''This is a continued docstring.\n", [0, 1], FIRST),
TestInfo('"""Closing quote does not match."\n', [0, 1], FIRST),
TestInfo('"""Bracket in docstring [\n', [0, 1], FIRST),
TestInfo("'''Incomplete two line docstring.\n\n", [0, 2], NEXT),
# Single-quoted strings.
TestInfo('"This is a complete string."\n', [0, 1], NONE),
TestInfo('"This is an incomplete string.\n', [0, 1], NONE),
TestInfo("'This is more incomplete.\n\n", [0, 1, 2], NONE),
# Comment (backslash does not continue comments).
TestInfo('# Comment\\\n', [0, 1], NONE),
# Brackets.
TestInfo('("""Complete string in bracket"""\n', [0, 1], BRACKET),
TestInfo('("""Open string in bracket\n', [0, 1], FIRST),
TestInfo('a = (1 + 2) - 5 *\\\n', [0, 1], BACKSLASH), # No bracket.
TestInfo('\n def function1(self, a,\n b):\n',
[0, 1, 3], NONE),
TestInfo('\n def function1(self, a,\\\n', [0, 1, 2], BRACKET),
TestInfo('\n def function1(self, a,\n', [0, 1, 2], BRACKET),
TestInfo('())\n', [0, 1], NONE), # Extra closer.
TestInfo(')(\n', [0, 1], BRACKET), # Extra closer.
# For the mismatched example, it doesn't look like contination.
TestInfo('{)(]\n', [0, 1], NONE), # Mismatched.
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string) # resets study_level
study()
eq(p.study_level, 1)
eq(p.goodlines, test.goodlines)
eq(p.continuation, test.continuation)
# Called again, just returns without reprocessing.
self.assertIsNone(study())
def test_get_continuation_type(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
gettype = p.get_continuation_type
(NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
TestInfo = namedtuple('TestInfo', ['string', 'continuation'])
tests = (
TestInfo('', NONE),
TestInfo('"""This is a continuation docstring.\n', FIRST),
TestInfo("'''This is a multiline-continued docstring.\n\n", NEXT),
TestInfo('a = (1 + 2) - 5 *\\\n', BACKSLASH),
TestInfo('\n def function1(self, a,\\\n', BRACKET)
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
eq(gettype(), test.continuation)
def test_study2(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
study = p._study2
TestInfo = namedtuple('TestInfo', ['string', 'start', 'end', 'lastch',
'openbracket', 'bracketing'])
tests = (
TestInfo('', 0, 0, '', None, ((0, 0),)),
TestInfo("'''This is a multiline continutation docstring.\n\n",
0, 49, "'", None, ((0, 0), (0, 1), (49, 0))),
TestInfo(' # Comment\\\n',
0, 12, '', None, ((0, 0), (1, 1), (12, 0))),
# A comment without a space is a special case
TestInfo(' #Comment\\\n',
0, 0, '', None, ((0, 0),)),
# Backslash continuation.
TestInfo('a = (1 + 2) - 5 *\\\n',
0, 19, '*', None, ((0, 0), (4, 1), (11, 0))),
# Bracket continuation with close.
TestInfo('\n def function1(self, a,\n b):\n',
1, 48, ':', None, ((1, 0), (17, 1), (46, 0))),
# Bracket continuation with unneeded backslash.
TestInfo('\n def function1(self, a,\\\n',
1, 28, ',', 17, ((1, 0), (17, 1))),
# Bracket continuation.
TestInfo('\n def function1(self, a,\n',
1, 27, ',', 17, ((1, 0), (17, 1))),
# Bracket continuation with comment at end of line with text.
TestInfo('\n def function1(self, a, # End of line comment.\n',
1, 51, ',', 17, ((1, 0), (17, 1), (28, 2), (51, 1))),
# Multi-line statement with comment line in between code lines.
TestInfo(' a = ["first item",\n # Comment line\n "next item",\n',
0, 55, ',', 6, ((0, 0), (6, 1), (7, 2), (19, 1),
(23, 2), (38, 1), (42, 2), (53, 1))),
TestInfo('())\n',
0, 4, ')', None, ((0, 0), (0, 1), (2, 0), (3, 0))),
TestInfo(')(\n', 0, 3, '(', 1, ((0, 0), (1, 0), (1, 1))),
# Wrong closers still decrement stack level.
TestInfo('{)(]\n',
0, 5, ']', None, ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
# Character after backslash.
TestInfo(':\\a\n', 0, 4, '\\a', None, ((0, 0),)),
TestInfo('\n', 0, 0, '', None, ((0, 0),)),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
study()
eq(p.study_level, 2)
eq(p.stmt_start, test.start)
eq(p.stmt_end, test.end)
eq(p.lastch, test.lastch)
eq(p.lastopenbracketpos, test.openbracket)
eq(p.stmt_bracketing, test.bracketing)
# Called again, just returns without reprocessing.
self.assertIsNone(study())
def test_get_num_lines_in_stmt(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
getlines = p.get_num_lines_in_stmt
TestInfo = namedtuple('TestInfo', ['string', 'lines'])
tests = (
TestInfo('[x for x in a]\n', 1), # Closed on one line.
TestInfo('[x\nfor x in a\n', 2), # Not closed.
TestInfo('[x\\\nfor x in a\\\n', 2), # "", uneeded backslashes.
TestInfo('[x\nfor x in a\n]\n', 3), # Closed on multi-line.
TestInfo('\n"""Docstring comment L1"""\nL2\nL3\nL4\n', 1),
TestInfo('\n"""Docstring comment L1\nL2"""\nL3\nL4\n', 1),
TestInfo('\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n', 4),
TestInfo('\n\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n"""\n', 5)
)
# Blank string doesn't have enough elements in goodlines.
setcode('')
with self.assertRaises(IndexError):
getlines()
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
eq(getlines(), test.lines)
def test_compute_bracket_indent(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
indent = p.compute_bracket_indent
TestInfo = namedtuple('TestInfo', ['string', 'spaces'])
tests = (
TestInfo('def function1(self, a,\n', 14),
# Characters after bracket.
TestInfo('\n def function1(self, a,\n', 18),
TestInfo('\n\tdef function1(self, a,\n', 18),
# No characters after bracket.
TestInfo('\n def function1(\n', 8),
TestInfo('\n\tdef function1(\n', 8),
TestInfo('\n def function1( \n', 8), # Ignore extra spaces.
TestInfo('[\n"first item",\n # Comment line\n "next item",\n', 0),
TestInfo('[\n "first item",\n # Comment line\n "next item",\n', 2),
TestInfo('["first item",\n # Comment line\n "next item",\n', 1),
TestInfo('(\n', 4),
TestInfo('(a\n', 1),
)
# Must be C_BRACKET continuation type.
setcode('def function1(self, a, b):\n')
with self.assertRaises(AssertionError):
indent()
for test in tests:
setcode(test.string)
eq(indent(), test.spaces)
def test_compute_backslash_indent(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
indent = p.compute_backslash_indent
# Must be C_BACKSLASH continuation type.
errors = (('def function1(self, a, b\\\n'), # Bracket.
(' """ (\\\n'), # Docstring.
('a = #\\\n'), # Inline comment.
)
for string in errors:
with self.subTest(string=string):
setcode(string)
with self.assertRaises(AssertionError):
indent()
TestInfo = namedtuple('TestInfo', ('string', 'spaces'))
tests = (TestInfo('a = (1 + 2) - 5 *\\\n', 4),
TestInfo('a = 1 + 2 - 5 *\\\n', 4),
TestInfo(' a = 1 + 2 - 5 *\\\n', 8),
TestInfo(' a = "spam"\\\n', 6),
TestInfo(' a = \\\n"a"\\\n', 4),
TestInfo(' a = #\\\n"a"\\\n', 5),
TestInfo('a == \\\n', 2),
TestInfo('a != \\\n', 2),
# Difference between containing = and those not.
TestInfo('\\\n', 2),
TestInfo(' \\\n', 6),
TestInfo('\t\\\n', 6),
TestInfo('a\\\n', 3),
TestInfo('{}\\\n', 4),
TestInfo('(1 + 2) - 5 *\\\n', 3),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
eq(indent(), test.spaces)
def test_get_base_indent_string(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
baseindent = p.get_base_indent_string
TestInfo = namedtuple('TestInfo', ['string', 'indent'])
tests = (TestInfo('', ''),
TestInfo('def a():\n', ''),
TestInfo('\tdef a():\n', '\t'),
TestInfo(' def a():\n', ' '),
TestInfo(' def a(\n', ' '),
TestInfo('\t\n def a(\n', ' '),
TestInfo('\t\n # Comment.\n', ' '),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
eq(baseindent(), test.indent)
def test_is_block_opener(self):
yes = self.assertTrue
no = self.assertFalse
p = self.parser
setcode = p.set_code
opener = p.is_block_opener
TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
tests = (
TestInfo('def a():\n', yes),
TestInfo('\n def function1(self, a,\n b):\n', yes),
TestInfo(':\n', yes),
TestInfo('a:\n', yes),
TestInfo('):\n', yes),
TestInfo('(:\n', yes),
TestInfo('":\n', no),
TestInfo('\n def function1(self, a,\n', no),
TestInfo('def function1(self, a):\n pass\n', no),
TestInfo('# A comment:\n', no),
TestInfo('"""A docstring:\n', no),
TestInfo('"""A docstring:\n', no),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
test.assert_(opener())
def test_is_block_closer(self):
yes = self.assertTrue
no = self.assertFalse
p = self.parser
setcode = p.set_code
closer = p.is_block_closer
TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
tests = (
TestInfo('return\n', yes),
TestInfo('\tbreak\n', yes),
TestInfo(' continue\n', yes),
TestInfo(' raise\n', yes),
TestInfo('pass \n', yes),
TestInfo('pass\t\n', yes),
TestInfo('return #\n', yes),
TestInfo('raised\n', no),
TestInfo('returning\n', no),
TestInfo('# return\n', no),
TestInfo('"""break\n', no),
TestInfo('"continue\n', no),
TestInfo('def function1(self, a):\n pass\n', yes),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
test.assert_(closer())
def test_get_last_stmt_bracketing(self):
eq = self.assertEqual
p = self.parser
setcode = p.set_code
bracketing = p.get_last_stmt_bracketing
TestInfo = namedtuple('TestInfo', ['string', 'bracket'])
tests = (
TestInfo('', ((0, 0),)),
TestInfo('a\n', ((0, 0),)),
TestInfo('()()\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
TestInfo('(\n)()\n', ((0, 0), (0, 1), (3, 0), (3, 1), (5, 0))),
TestInfo('()\n()\n', ((3, 0), (3, 1), (5, 0))),
TestInfo('()(\n)\n', ((0, 0), (0, 1), (2, 0), (2, 1), (5, 0))),
TestInfo('(())\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))),
TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))),
# Same as matched test.
TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
TestInfo('(((())\n',
((0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (5, 3), (6, 2))),
)
for test in tests:
with self.subTest(string=test.string):
setcode(test.string)
eq(bracketing(), test.bracket)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 18,588 | 467 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_pathbrowser.py | "Test pathbrowser, coverage 95%."
from idlelib import pathbrowser
import unittest
from test.support import requires
from tkinter import Tk
import os.path
import pyclbr # for _modules
import sys # for sys.path
from idlelib.idle_test.mock_idle import Func
import idlelib # for __file__
from idlelib import browser
from idlelib.tree import TreeNode
class PathBrowserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True)
@classmethod
def tearDownClass(cls):
cls.pb.close()
cls.root.update_idletasks()
cls.root.destroy()
del cls.root, cls.pb
def test_init(self):
pb = self.pb
eq = self.assertEqual
eq(pb.master, self.root)
eq(pyclbr._modules, {})
self.assertIsInstance(pb.node, TreeNode)
self.assertIsNotNone(browser.file_open)
def test_settitle(self):
pb = self.pb
self.assertEqual(pb.top.title(), 'Path Browser')
self.assertEqual(pb.top.iconname(), 'Path Browser')
def test_rootnode(self):
pb = self.pb
rn = pb.rootnode()
self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem)
def test_close(self):
pb = self.pb
pb.top.destroy = Func()
pb.node.destroy = Func()
pb.close()
self.assertTrue(pb.top.destroy.called)
self.assertTrue(pb.node.destroy.called)
del pb.top.destroy, pb.node.destroy
class DirBrowserTreeItemTest(unittest.TestCase):
def test_DirBrowserTreeItem(self):
# Issue16226 - make sure that getting a sublist works
d = pathbrowser.DirBrowserTreeItem('')
d.GetSubList()
self.assertEqual('', d.GetText())
dir = os.path.split(os.path.abspath(idlelib.__file__))[0]
self.assertEqual(d.ispackagedir(dir), True)
self.assertEqual(d.ispackagedir(dir + '/Icons'), False)
class PathBrowserTreeItemTest(unittest.TestCase):
def test_PathBrowserTreeItem(self):
p = pathbrowser.PathBrowserTreeItem()
self.assertEqual(p.GetText(), 'sys.path')
sub = p.GetSubList()
self.assertEqual(len(sub), len(sys.path))
self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=False)
| 2,422 | 87 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_calltip_w.py | "Test calltip_w, coverage 18%."
from idlelib import calltip_w
import unittest
from test.support import requires
from tkinter import Tk, Text
class CallTipWindowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
cls.calltip = calltip_w.CalltipWindow(cls.text)
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
cls.root.destroy()
del cls.text, cls.root
def test_init(self):
self.assertEqual(self.calltip.anchor_widget, self.text)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 686 | 30 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_parenmatch.py | """Test parenmatch, coverage 91%.
This must currently be a gui test because ParenMatch methods use
several text methods not defined on idlelib.idle_test.mock_tk.Text.
"""
from idlelib.parenmatch import ParenMatch
from test.support import requires
requires('gui')
import unittest
from unittest.mock import Mock
from tkinter import Tk, Text
class DummyEditwin:
def __init__(self, text):
self.text = text
self.indentwidth = 8
self.tabwidth = 8
self.context_use_ps1 = True
class ParenMatchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.root.withdraw()
cls.text = Text(cls.root)
cls.editwin = DummyEditwin(cls.text)
cls.editwin.text_frame = Mock()
@classmethod
def tearDownClass(cls):
del cls.text, cls.editwin
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def tearDown(self):
self.text.delete('1.0', 'end')
def get_parenmatch(self):
pm = ParenMatch(self.editwin)
pm.bell = lambda: None
return pm
def test_paren_styles(self):
"""
Test ParenMatch with each style.
"""
text = self.text
pm = self.get_parenmatch()
for style, range1, range2 in (
('opener', ('1.10', '1.11'), ('1.10', '1.11')),
('default',('1.10', '1.11'),('1.10', '1.11')),
('parens', ('1.14', '1.15'), ('1.15', '1.16')),
('expression', ('1.10', '1.15'), ('1.10', '1.16'))):
with self.subTest(style=style):
text.delete('1.0', 'end')
pm.STYLE = style
text.insert('insert', 'def foobar(a, b')
pm.flash_paren_event('event')
self.assertIn('<<parenmatch-check-restore>>', text.event_info())
if style == 'parens':
self.assertTupleEqual(text.tag_nextrange('paren', '1.0'),
('1.10', '1.11'))
self.assertTupleEqual(
text.tag_prevrange('paren', 'end'), range1)
text.insert('insert', ')')
pm.restore_event()
self.assertNotIn('<<parenmatch-check-restore>>',
text.event_info())
self.assertEqual(text.tag_prevrange('paren', 'end'), ())
pm.paren_closed_event('event')
self.assertTupleEqual(
text.tag_prevrange('paren', 'end'), range2)
def test_paren_corner(self):
"""
Test corner cases in flash_paren_event and paren_closed_event.
These cases force conditional expression and alternate paths.
"""
text = self.text
pm = self.get_parenmatch()
text.insert('insert', '# this is a commen)')
pm.paren_closed_event('event')
text.insert('insert', '\ndef')
pm.flash_paren_event('event')
pm.paren_closed_event('event')
text.insert('insert', ' a, *arg)')
pm.paren_closed_event('event')
def test_handle_restore_timer(self):
pm = self.get_parenmatch()
pm.restore_event = Mock()
pm.handle_restore_timer(0)
self.assertTrue(pm.restore_event.called)
pm.restore_event.reset_mock()
pm.handle_restore_timer(1)
self.assertFalse(pm.restore_event.called)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 3,512 | 113 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_stackviewer.py | "Test stackviewer, coverage 63%."
from idlelib import stackviewer
import unittest
from test.support import requires
from tkinter import Tk
from idlelib.tree import TreeNode, ScrolledCanvas
import sys
class StackBrowserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
svs = stackviewer.sys
try:
abc
except NameError:
svs.last_type, svs.last_value, svs.last_traceback = (
sys.exc_info())
requires('gui')
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
svs = stackviewer.sys
del svs.last_traceback, svs.last_type, svs.last_value
cls.root.update_idletasks()
## for id in cls.root.tk.call('after', 'info'):
## cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
sb = stackviewer.StackBrowser(self.root)
isi = self.assertIsInstance
isi(stackviewer.sc, ScrolledCanvas)
isi(stackviewer.item, stackviewer.StackTreeItem)
isi(stackviewer.node, TreeNode)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 1,206 | 48 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/mock_tk.py | """Classes that replace tkinter gui objects used by an object being tested.
A gui object is anything with a master or parent parameter, which is
typically required in spite of what the doc strings say.
"""
class Event:
'''Minimal mock with attributes for testing event handlers.
This is not a gui object, but is used as an argument for callbacks
that access attributes of the event passed. If a callback ignores
the event, other than the fact that is happened, pass 'event'.
Keyboard, mouse, window, and other sources generate Event instances.
Event instances have the following attributes: serial (number of
event), time (of event), type (of event as number), widget (in which
event occurred), and x,y (position of mouse). There are other
attributes for specific events, such as keycode for key events.
tkinter.Event.__doc__ has more but is still not complete.
'''
def __init__(self, **kwds):
"Create event with attributes needed for test"
self.__dict__.update(kwds)
class Var:
"Use for String/Int/BooleanVar: incomplete"
def __init__(self, master=None, value=None, name=None):
self.master = master
self.value = value
self.name = name
def set(self, value):
self.value = value
def get(self):
return self.value
class Mbox_func:
"""Generic mock for messagebox functions, which all have the same signature.
Instead of displaying a message box, the mock's call method saves the
arguments as instance attributes, which test functions can then examime.
The test can set the result returned to ask function
"""
def __init__(self, result=None):
self.result = result # Return None for all show funcs
def __call__(self, title, message, *args, **kwds):
# Save all args for possible examination by tester
self.title = title
self.message = message
self.args = args
self.kwds = kwds
return self.result # Set by tester for ask functions
class Mbox:
"""Mock for tkinter.messagebox with an Mbox_func for each function.
This module was 'tkMessageBox' in 2.x; hence the 'import as' in 3.x.
Example usage in test_module.py for testing functions in module.py:
---
from idlelib.idle_test.mock_tk import Mbox
import module
orig_mbox = module.tkMessageBox
showerror = Mbox.showerror # example, for attribute access in test methods
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
module.tkMessageBox = Mbox
@classmethod
def tearDownClass(cls):
module.tkMessageBox = orig_mbox
---
For 'ask' functions, set func.result return value before calling the method
that uses the message function. When tkMessageBox functions are the
only gui alls in a method, this replacement makes the method gui-free,
"""
askokcancel = Mbox_func() # True or False
askquestion = Mbox_func() # 'yes' or 'no'
askretrycancel = Mbox_func() # True or False
askyesno = Mbox_func() # True or False
askyesnocancel = Mbox_func() # True, False, or None
showerror = Mbox_func() # None
showinfo = Mbox_func() # None
showwarning = Mbox_func() # None
from _tkinter import TclError
class Text:
"""A semi-functional non-gui replacement for tkinter.Text text editors.
The mock's data model is that a text is a list of \n-terminated lines.
The mock adds an empty string at the beginning of the list so that the
index of actual lines start at 1, as with Tk. The methods never see this.
Tk initializes files with a terminal \n that cannot be deleted. It is
invisible in the sense that one cannot move the cursor beyond it.
This class is only tested (and valid) with strings of ascii chars.
For testing, we are not concerned with Tk Text's treatment of,
for instance, 0-width characters or character + accent.
"""
def __init__(self, master=None, cnf={}, **kw):
'''Initialize mock, non-gui, text-only Text widget.
At present, all args are ignored. Almost all affect visual behavior.
There are just a few Text-only options that affect text behavior.
'''
self.data = ['', '\n']
def index(self, index):
"Return string version of index decoded according to current text."
return "%s.%s" % self._decode(index, endflag=1)
def _decode(self, index, endflag=0):
"""Return a (line, char) tuple of int indexes into self.data.
This implements .index without converting the result back to a string.
The result is constrained by the number of lines and linelengths of
self.data. For many indexes, the result is initially (1, 0).
The input index may have any of several possible forms:
* line.char float: converted to 'line.char' string;
* 'line.char' string, where line and char are decimal integers;
* 'line.char lineend', where lineend='lineend' (and char is ignored);
* 'line.end', where end='end' (same as above);
* 'insert', the positions before terminal \n;
* 'end', whose meaning depends on the endflag passed to ._endex.
* 'sel.first' or 'sel.last', where sel is a tag -- not implemented.
"""
if isinstance(index, (float, bytes)):
index = str(index)
try:
index=index.lower()
except AttributeError:
raise TclError('bad text index "%s"' % index) from None
lastline = len(self.data) - 1 # same as number of text lines
if index == 'insert':
return lastline, len(self.data[lastline]) - 1
elif index == 'end':
return self._endex(endflag)
line, char = index.split('.')
line = int(line)
# Out of bounds line becomes first or last ('end') index
if line < 1:
return 1, 0
elif line > lastline:
return self._endex(endflag)
linelength = len(self.data[line]) -1 # position before/at \n
if char.endswith(' lineend') or char == 'end':
return line, linelength
# Tk requires that ignored chars before ' lineend' be valid int
# Out of bounds char becomes first or last index of line
char = int(char)
if char < 0:
char = 0
elif char > linelength:
char = linelength
return line, char
def _endex(self, endflag):
'''Return position for 'end' or line overflow corresponding to endflag.
-1: position before terminal \n; for .insert(), .delete
0: position after terminal \n; for .get, .delete index 1
1: same viewed as beginning of non-existent next line (for .index)
'''
n = len(self.data)
if endflag == 1:
return n, 0
else:
n -= 1
return n, len(self.data[n]) + endflag
def insert(self, index, chars):
"Insert chars before the character at index."
if not chars: # ''.splitlines() is [], not ['']
return
chars = chars.splitlines(True)
if chars[-1][-1] == '\n':
chars.append('')
line, char = self._decode(index, -1)
before = self.data[line][:char]
after = self.data[line][char:]
self.data[line] = before + chars[0]
self.data[line+1:line+1] = chars[1:]
self.data[line+len(chars)-1] += after
def get(self, index1, index2=None):
"Return slice from index1 to index2 (default is 'index1+1')."
startline, startchar = self._decode(index1)
if index2 is None:
endline, endchar = startline, startchar+1
else:
endline, endchar = self._decode(index2)
if startline == endline:
return self.data[startline][startchar:endchar]
else:
lines = [self.data[startline][startchar:]]
for i in range(startline+1, endline):
lines.append(self.data[i])
lines.append(self.data[endline][:endchar])
return ''.join(lines)
def delete(self, index1, index2=None):
'''Delete slice from index1 to index2 (default is 'index1+1').
Adjust default index2 ('index+1) for line ends.
Do not delete the terminal \n at the very end of self.data ([-1][-1]).
'''
startline, startchar = self._decode(index1, -1)
if index2 is None:
if startchar < len(self.data[startline])-1:
# not deleting \n
endline, endchar = startline, startchar+1
elif startline < len(self.data) - 1:
# deleting non-terminal \n, convert 'index1+1 to start of next line
endline, endchar = startline+1, 0
else:
# do not delete terminal \n if index1 == 'insert'
return
else:
endline, endchar = self._decode(index2, -1)
# restricting end position to insert position excludes terminal \n
if startline == endline and startchar < endchar:
self.data[startline] = self.data[startline][:startchar] + \
self.data[startline][endchar:]
elif startline < endline:
self.data[startline] = self.data[startline][:startchar] + \
self.data[endline][endchar:]
startline += 1
for i in range(startline, endline+1):
del self.data[startline]
def compare(self, index1, op, index2):
line1, char1 = self._decode(index1)
line2, char2 = self._decode(index2)
if op == '<':
return line1 < line2 or line1 == line2 and char1 < char2
elif op == '<=':
return line1 < line2 or line1 == line2 and char1 <= char2
elif op == '>':
return line1 > line2 or line1 == line2 and char1 > char2
elif op == '>=':
return line1 > line2 or line1 == line2 and char1 >= char2
elif op == '==':
return line1 == line2 and char1 == char2
elif op == '!=':
return line1 != line2 or char1 != char2
else:
raise TclError('''bad comparison operator "%s": '''
'''must be <, <=, ==, >=, >, or !=''' % op)
# The following Text methods normally do something and return None.
# Whether doing nothing is sufficient for a test will depend on the test.
def mark_set(self, name, index):
"Set mark *name* before the character at index."
pass
def mark_unset(self, *markNames):
"Delete all marks in markNames."
def tag_remove(self, tagName, index1, index2=None):
"Remove tag tagName from all characters between index1 and index2."
pass
# The following Text methods affect the graphics screen and return None.
# Doing nothing should always be sufficient for tests.
def scan_dragto(self, x, y):
"Adjust the view of the text according to scan_mark"
def scan_mark(self, x, y):
"Remember the current X, Y coordinates."
def see(self, index):
"Scroll screen to make the character at INDEX is visible."
pass
# The following is a Misc method inherited by Text.
# It should properly go in a Misc mock, but is included here for now.
def bind(sequence=None, func=None, add=None):
"Bind to this widget at event sequence a call to function func."
pass
class Entry:
"Mock for tkinter.Entry."
def focus_set(self):
pass
| 11,627 | 304 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_replace.py | "Test replace, coverage 78%."
from idlelib.replace import ReplaceDialog
import unittest
from test.support import requires
requires('gui')
from tkinter import Tk, Text
from unittest.mock import Mock
from idlelib.idle_test.mock_tk import Mbox
import idlelib.searchengine as se
orig_mbox = se.tkMessageBox
showerror = Mbox.showerror
class ReplaceDialogTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.root.withdraw()
se.tkMessageBox = Mbox
cls.engine = se.SearchEngine(cls.root)
cls.dialog = ReplaceDialog(cls.root, cls.engine)
cls.dialog.bell = lambda: None
cls.dialog.ok = Mock()
cls.text = Text(cls.root)
cls.text.undo_block_start = Mock()
cls.text.undo_block_stop = Mock()
cls.dialog.text = cls.text
@classmethod
def tearDownClass(cls):
se.tkMessageBox = orig_mbox
del cls.text, cls.dialog, cls.engine
cls.root.destroy()
del cls.root
def setUp(self):
self.text.insert('insert', 'This is a sample sTring')
def tearDown(self):
self.engine.patvar.set('')
self.dialog.replvar.set('')
self.engine.wordvar.set(False)
self.engine.casevar.set(False)
self.engine.revar.set(False)
self.engine.wrapvar.set(True)
self.engine.backvar.set(False)
showerror.title = ''
showerror.message = ''
self.text.delete('1.0', 'end')
def test_replace_simple(self):
# Test replace function with all options at default setting.
# Wrap around - True
# Regular Expression - False
# Match case - False
# Match word - False
# Direction - Forwards
text = self.text
equal = self.assertEqual
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
# test accessor method
self.engine.setpat('asdf')
equal(self.engine.getpat(), pv.get())
# text found and replaced
pv.set('a')
rv.set('asdf')
replace()
equal(text.get('1.8', '1.12'), 'asdf')
# don't "match word" case
text.mark_set('insert', '1.0')
pv.set('is')
rv.set('hello')
replace()
equal(text.get('1.2', '1.7'), 'hello')
# don't "match case" case
pv.set('string')
rv.set('world')
replace()
equal(text.get('1.23', '1.28'), 'world')
# without "regular expression" case
text.mark_set('insert', 'end')
text.insert('insert', '\nline42:')
before_text = text.get('1.0', 'end')
pv.set(r'[a-z][\d]+')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
# test with wrap around selected and complete a cycle
text.mark_set('insert', '1.9')
pv.set('i')
rv.set('j')
replace()
equal(text.get('1.8'), 'i')
equal(text.get('2.1'), 'j')
replace()
equal(text.get('2.1'), 'j')
equal(text.get('1.8'), 'j')
before_text = text.get('1.0', 'end')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
# text not found
before_text = text.get('1.0', 'end')
pv.set('foobar')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
# test access method
self.dialog.find_it(0)
def test_replace_wrap_around(self):
text = self.text
equal = self.assertEqual
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
self.engine.wrapvar.set(False)
# replace candidate found both after and before 'insert'
text.mark_set('insert', '1.4')
pv.set('i')
rv.set('j')
replace()
equal(text.get('1.2'), 'i')
equal(text.get('1.5'), 'j')
replace()
equal(text.get('1.2'), 'i')
equal(text.get('1.20'), 'j')
replace()
equal(text.get('1.2'), 'i')
# replace candidate found only before 'insert'
text.mark_set('insert', '1.8')
pv.set('is')
before_text = text.get('1.0', 'end')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
def test_replace_whole_word(self):
text = self.text
equal = self.assertEqual
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
self.engine.wordvar.set(True)
pv.set('is')
rv.set('hello')
replace()
equal(text.get('1.0', '1.4'), 'This')
equal(text.get('1.5', '1.10'), 'hello')
def test_replace_match_case(self):
equal = self.assertEqual
text = self.text
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
self.engine.casevar.set(True)
before_text = self.text.get('1.0', 'end')
pv.set('this')
rv.set('that')
replace()
after_text = self.text.get('1.0', 'end')
equal(before_text, after_text)
pv.set('This')
replace()
equal(text.get('1.0', '1.4'), 'that')
def test_replace_regex(self):
equal = self.assertEqual
text = self.text
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
self.engine.revar.set(True)
before_text = text.get('1.0', 'end')
pv.set(r'[a-z][\d]+')
rv.set('hello')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
text.insert('insert', '\nline42')
replace()
equal(text.get('2.0', '2.8'), 'linhello')
pv.set('')
replace()
self.assertIn('error', showerror.title)
self.assertIn('Empty', showerror.message)
pv.set(r'[\d')
replace()
self.assertIn('error', showerror.title)
self.assertIn('Pattern', showerror.message)
showerror.title = ''
showerror.message = ''
pv.set('[a]')
rv.set('test\\')
replace()
self.assertIn('error', showerror.title)
self.assertIn('Invalid Replace Expression', showerror.message)
# test access method
self.engine.setcookedpat("?")
equal(pv.get(), "\\?")
def test_replace_backwards(self):
equal = self.assertEqual
text = self.text
pv = self.engine.patvar
rv = self.dialog.replvar
replace = self.dialog.replace_it
self.engine.backvar.set(True)
text.insert('insert', '\nis as ')
pv.set('is')
rv.set('was')
replace()
equal(text.get('1.2', '1.4'), 'is')
equal(text.get('2.0', '2.3'), 'was')
replace()
equal(text.get('1.5', '1.8'), 'was')
replace()
equal(text.get('1.2', '1.5'), 'was')
def test_replace_all(self):
text = self.text
pv = self.engine.patvar
rv = self.dialog.replvar
replace_all = self.dialog.replace_all
text.insert('insert', '\n')
text.insert('insert', text.get('1.0', 'end')*100)
pv.set('is')
rv.set('was')
replace_all()
self.assertNotIn('is', text.get('1.0', 'end'))
self.engine.revar.set(True)
pv.set('')
replace_all()
self.assertIn('error', showerror.title)
self.assertIn('Empty', showerror.message)
pv.set('[s][T]')
rv.set('\\')
replace_all()
self.engine.revar.set(False)
pv.set('text which is not present')
rv.set('foobar')
replace_all()
def test_default_command(self):
text = self.text
pv = self.engine.patvar
rv = self.dialog.replvar
replace_find = self.dialog.default_command
equal = self.assertEqual
pv.set('This')
rv.set('was')
replace_find()
equal(text.get('sel.first', 'sel.last'), 'was')
self.engine.revar.set(True)
pv.set('')
replace_find()
if __name__ == '__main__':
unittest.main(verbosity=2)
| 8,305 | 295 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_autocomplete.py | "Test autocomplete, coverage 57%."
import unittest
from test.support import requires
from tkinter import Tk, Text
import idlelib.autocomplete as ac
import idlelib.autocomplete_w as acw
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Event
class DummyEditwin:
def __init__(self, root, text):
self.root = root
self.text = text
self.indentwidth = 8
self.tabwidth = 8
self.context_use_ps1 = True
class AutoCompleteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.text = Text(cls.root)
cls.editor = DummyEditwin(cls.root, cls.text)
@classmethod
def tearDownClass(cls):
del cls.editor, cls.text
cls.root.destroy()
del cls.root
def setUp(self):
self.editor.text.delete('1.0', 'end')
self.autocomplete = ac.AutoComplete(self.editor)
def test_init(self):
self.assertEqual(self.autocomplete.editwin, self.editor)
def test_make_autocomplete_window(self):
testwin = self.autocomplete._make_autocomplete_window()
self.assertIsInstance(testwin, acw.AutoCompleteWindow)
def test_remove_autocomplete_window(self):
self.autocomplete.autocompletewindow = (
self.autocomplete._make_autocomplete_window())
self.autocomplete._remove_autocomplete_window()
self.assertIsNone(self.autocomplete.autocompletewindow)
def test_force_open_completions_event(self):
# Test that force_open_completions_event calls _open_completions
o_cs = Func()
self.autocomplete.open_completions = o_cs
self.autocomplete.force_open_completions_event('event')
self.assertEqual(o_cs.args, (True, False, True))
def test_try_open_completions_event(self):
Equal = self.assertEqual
autocomplete = self.autocomplete
trycompletions = self.autocomplete.try_open_completions_event
o_c_l = Func()
autocomplete._open_completions_later = o_c_l
# _open_completions_later should not be called with no text in editor
trycompletions('event')
Equal(o_c_l.args, None)
# _open_completions_later should be called with COMPLETE_ATTRIBUTES (1)
self.text.insert('1.0', 're.')
trycompletions('event')
Equal(o_c_l.args, (False, False, False, 1))
# _open_completions_later should be called with COMPLETE_FILES (2)
self.text.delete('1.0', 'end')
self.text.insert('1.0', '"./Lib/')
trycompletions('event')
Equal(o_c_l.args, (False, False, False, 2))
def test_autocomplete_event(self):
Equal = self.assertEqual
autocomplete = self.autocomplete
# Test that the autocomplete event is ignored if user is pressing a
# modifier key in addition to the tab key
ev = Event(mc_state=True)
self.assertIsNone(autocomplete.autocomplete_event(ev))
del ev.mc_state
# Test that tab after whitespace is ignored.
self.text.insert('1.0', ' """Docstring.\n ')
self.assertIsNone(autocomplete.autocomplete_event(ev))
self.text.delete('1.0', 'end')
# If autocomplete window is open, complete() method is called
self.text.insert('1.0', 're.')
# This must call autocomplete._make_autocomplete_window()
Equal(self.autocomplete.autocomplete_event(ev), 'break')
# If autocomplete window is not active or does not exist,
# open_completions is called. Return depends on its return.
autocomplete._remove_autocomplete_window()
o_cs = Func() # .result = None
autocomplete.open_completions = o_cs
Equal(self.autocomplete.autocomplete_event(ev), None)
Equal(o_cs.args, (False, True, True))
o_cs.result = True
Equal(self.autocomplete.autocomplete_event(ev), 'break')
Equal(o_cs.args, (False, True, True))
def test_open_completions_later(self):
# Test that autocomplete._delayed_completion_id is set
pass
def test_delayed_open_completions(self):
# Test that autocomplete._delayed_completion_id set to None and that
# open_completions only called if insertion index is the same as
# _delayed_completion_index
pass
def test_open_completions(self):
# Test completions of files and attributes as well as non-completion
# of errors
pass
def test_fetch_completions(self):
# Test that fetch_completions returns 2 lists:
# For attribute completion, a large list containing all variables, and
# a small list containing non-private variables.
# For file completion, a large list containing all files in the path,
# and a small list containing files that do not start with '.'
pass
def test_get_entity(self):
# Test that a name is in the namespace of sys.modules and
# __main__.__dict__
pass
if __name__ == '__main__':
unittest.main(verbosity=2)
| 5,107 | 145 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_config.py | """Test config, coverage 93%.
(100% for IdleConfParser, IdleUserConfParser*, ConfigChanges).
* Exception is OSError clause in Save method.
Much of IdleConf is also exercised by ConfigDialog and test_configdialog.
"""
from idlelib import config
import sys
import os
import tempfile
from test.support import captured_stderr, findfile
import unittest
from unittest import mock
import idlelib
from idlelib.idle_test.mock_idle import Func
# Tests should not depend on fortuitous user configurations.
# They must not affect actual user .cfg files.
# Replace user parsers with empty parsers that cannot be saved
# due to getting '' as the filename when created.
idleConf = config.idleConf
usercfg = idleConf.userCfg
testcfg = {}
usermain = testcfg['main'] = config.IdleUserConfParser('')
userhigh = testcfg['highlight'] = config.IdleUserConfParser('')
userkeys = testcfg['keys'] = config.IdleUserConfParser('')
userextn = testcfg['extensions'] = config.IdleUserConfParser('')
def setUpModule():
idleConf.userCfg = testcfg
idlelib.testing = True
def tearDownModule():
idleConf.userCfg = usercfg
idlelib.testing = False
class IdleConfParserTest(unittest.TestCase):
"""Test that IdleConfParser works"""
config = """
[one]
one = false
two = true
three = 10
[two]
one = a string
two = true
three = false
"""
def test_get(self):
parser = config.IdleConfParser('')
parser.read_string(self.config)
eq = self.assertEqual
# Test with type argument.
self.assertIs(parser.Get('one', 'one', type='bool'), False)
self.assertIs(parser.Get('one', 'two', type='bool'), True)
eq(parser.Get('one', 'three', type='int'), 10)
eq(parser.Get('two', 'one'), 'a string')
self.assertIs(parser.Get('two', 'two', type='bool'), True)
self.assertIs(parser.Get('two', 'three', type='bool'), False)
# Test without type should fallback to string.
eq(parser.Get('two', 'two'), 'true')
eq(parser.Get('two', 'three'), 'false')
# If option not exist, should return None, or default.
self.assertIsNone(parser.Get('not', 'exist'))
eq(parser.Get('not', 'exist', default='DEFAULT'), 'DEFAULT')
def test_get_option_list(self):
parser = config.IdleConfParser('')
parser.read_string(self.config)
get_list = parser.GetOptionList
self.assertCountEqual(get_list('one'), ['one', 'two', 'three'])
self.assertCountEqual(get_list('two'), ['one', 'two', 'three'])
self.assertEqual(get_list('not exist'), [])
def test_load_nothing(self):
parser = config.IdleConfParser('')
parser.Load()
self.assertEqual(parser.sections(), [])
def test_load_file(self):
# Borrow test/cfgparser.1 from test_configparser.
config_path = findfile('cfgparser.1')
parser = config.IdleConfParser(config_path)
parser.Load()
self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar')
self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo'])
class IdleUserConfParserTest(unittest.TestCase):
"""Test that IdleUserConfParser works"""
def new_parser(self, path=''):
return config.IdleUserConfParser(path)
def test_set_option(self):
parser = self.new_parser()
parser.add_section('Foo')
# Setting new option in existing section should return True.
self.assertTrue(parser.SetOption('Foo', 'bar', 'true'))
# Setting existing option with same value should return False.
self.assertFalse(parser.SetOption('Foo', 'bar', 'true'))
# Setting exiting option with new value should return True.
self.assertTrue(parser.SetOption('Foo', 'bar', 'false'))
self.assertEqual(parser.Get('Foo', 'bar'), 'false')
# Setting option in new section should create section and return True.
self.assertTrue(parser.SetOption('Bar', 'bar', 'true'))
self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
self.assertEqual(parser.Get('Bar', 'bar'), 'true')
def test_remove_option(self):
parser = self.new_parser()
parser.AddSection('Foo')
parser.SetOption('Foo', 'bar', 'true')
self.assertTrue(parser.RemoveOption('Foo', 'bar'))
self.assertFalse(parser.RemoveOption('Foo', 'bar'))
self.assertFalse(parser.RemoveOption('Not', 'Exist'))
def test_add_section(self):
parser = self.new_parser()
self.assertEqual(parser.sections(), [])
# Should not add duplicate section.
# Configparser raises DuplicateError, IdleParser not.
parser.AddSection('Foo')
parser.AddSection('Foo')
parser.AddSection('Bar')
self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
def test_remove_empty_sections(self):
parser = self.new_parser()
parser.AddSection('Foo')
parser.AddSection('Bar')
parser.SetOption('Idle', 'name', 'val')
self.assertCountEqual(parser.sections(), ['Bar', 'Foo', 'Idle'])
parser.RemoveEmptySections()
self.assertEqual(parser.sections(), ['Idle'])
def test_is_empty(self):
parser = self.new_parser()
parser.AddSection('Foo')
parser.AddSection('Bar')
self.assertTrue(parser.IsEmpty())
self.assertEqual(parser.sections(), [])
parser.SetOption('Foo', 'bar', 'false')
parser.AddSection('Bar')
self.assertFalse(parser.IsEmpty())
self.assertCountEqual(parser.sections(), ['Foo'])
def test_remove_file(self):
with tempfile.TemporaryDirectory() as tdir:
path = os.path.join(tdir, 'test.cfg')
parser = self.new_parser(path)
parser.RemoveFile() # Should not raise exception.
parser.AddSection('Foo')
parser.SetOption('Foo', 'bar', 'true')
parser.Save()
self.assertTrue(os.path.exists(path))
parser.RemoveFile()
self.assertFalse(os.path.exists(path))
def test_save(self):
with tempfile.TemporaryDirectory() as tdir:
path = os.path.join(tdir, 'test.cfg')
parser = self.new_parser(path)
parser.AddSection('Foo')
parser.SetOption('Foo', 'bar', 'true')
# Should save to path when config is not empty.
self.assertFalse(os.path.exists(path))
parser.Save()
self.assertTrue(os.path.exists(path))
# Should remove the file from disk when config is empty.
parser.remove_section('Foo')
parser.Save()
self.assertFalse(os.path.exists(path))
class IdleConfTest(unittest.TestCase):
"""Test for idleConf"""
@classmethod
def setUpClass(cls):
cls.config_string = {}
conf = config.IdleConf(_utest=True)
if __name__ != '__main__':
idle_dir = os.path.dirname(__file__)
else:
idle_dir = os.path.abspath(sys.path[0])
for ctype in conf.config_types:
config_path = os.path.join(idle_dir, '../config-%s.def' % ctype)
with open(config_path, 'r') as f:
cls.config_string[ctype] = f.read()
cls.orig_warn = config._warn
config._warn = Func()
@classmethod
def tearDownClass(cls):
config._warn = cls.orig_warn
def new_config(self, _utest=False):
return config.IdleConf(_utest=_utest)
def mock_config(self):
"""Return a mocked idleConf
Both default and user config used the same config-*.def
"""
conf = config.IdleConf(_utest=True)
for ctype in conf.config_types:
conf.defaultCfg[ctype] = config.IdleConfParser('')
conf.defaultCfg[ctype].read_string(self.config_string[ctype])
conf.userCfg[ctype] = config.IdleUserConfParser('')
conf.userCfg[ctype].read_string(self.config_string[ctype])
return conf
@unittest.skipIf(sys.platform.startswith('win'), 'this is test for unix system')
def test_get_user_cfg_dir_unix(self):
"Test to get user config directory under unix"
conf = self.new_config(_utest=True)
# Check normal way should success
with mock.patch('os.path.expanduser', return_value='/home/foo'):
with mock.patch('os.path.exists', return_value=True):
self.assertEqual(conf.GetUserCfgDir(), '/home/foo/.idlerc')
# Check os.getcwd should success
with mock.patch('os.path.expanduser', return_value='~'):
with mock.patch('os.getcwd', return_value='/home/foo/cpython'):
with mock.patch('os.mkdir'):
self.assertEqual(conf.GetUserCfgDir(),
'/home/foo/cpython/.idlerc')
# Check user dir not exists and created failed should raise SystemExit
with mock.patch('os.path.join', return_value='/path/not/exists'):
with self.assertRaises(SystemExit):
with self.assertRaises(FileNotFoundError):
conf.GetUserCfgDir()
@unittest.skipIf(not sys.platform.startswith('win'), 'this is test for Windows system')
def test_get_user_cfg_dir_windows(self):
"Test to get user config directory under Windows"
conf = self.new_config(_utest=True)
# Check normal way should success
with mock.patch('os.path.expanduser', return_value='C:\\foo'):
with mock.patch('os.path.exists', return_value=True):
self.assertEqual(conf.GetUserCfgDir(), 'C:\\foo\\.idlerc')
# Check os.getcwd should success
with mock.patch('os.path.expanduser', return_value='~'):
with mock.patch('os.getcwd', return_value='C:\\foo\\cpython'):
with mock.patch('os.mkdir'):
self.assertEqual(conf.GetUserCfgDir(),
'C:\\foo\\cpython\\.idlerc')
# Check user dir not exists and created failed should raise SystemExit
with mock.patch('os.path.join', return_value='/path/not/exists'):
with self.assertRaises(SystemExit):
with self.assertRaises(FileNotFoundError):
conf.GetUserCfgDir()
def test_create_config_handlers(self):
conf = self.new_config(_utest=True)
# Mock out idle_dir
idle_dir = '/home/foo'
with mock.patch.dict({'__name__': '__foo__'}):
with mock.patch('os.path.dirname', return_value=idle_dir):
conf.CreateConfigHandlers()
# Check keys are equal
self.assertCountEqual(conf.defaultCfg.keys(), conf.config_types)
self.assertCountEqual(conf.userCfg.keys(), conf.config_types)
# Check conf parser are correct type
for default_parser in conf.defaultCfg.values():
self.assertIsInstance(default_parser, config.IdleConfParser)
for user_parser in conf.userCfg.values():
self.assertIsInstance(user_parser, config.IdleUserConfParser)
# Check config path are correct
for config_type, parser in conf.defaultCfg.items():
self.assertEqual(parser.file,
os.path.join(idle_dir, 'config-%s.def' % config_type))
for config_type, parser in conf.userCfg.items():
self.assertEqual(parser.file,
os.path.join(conf.userdir, 'config-%s.cfg' % config_type))
def test_load_cfg_files(self):
conf = self.new_config(_utest=True)
# Borrow test/cfgparser.1 from test_configparser.
config_path = findfile('cfgparser.1')
conf.defaultCfg['foo'] = config.IdleConfParser(config_path)
conf.userCfg['foo'] = config.IdleUserConfParser(config_path)
# Load all config from path
conf.LoadCfgFiles()
eq = self.assertEqual
# Check defaultCfg is loaded
eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
# Check userCfg is loaded
eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
def test_save_user_cfg_files(self):
conf = self.mock_config()
with mock.patch('idlelib.config.IdleUserConfParser.Save') as m:
conf.SaveUserCfgFiles()
self.assertEqual(m.call_count, len(conf.userCfg))
def test_get_option(self):
conf = self.mock_config()
eq = self.assertEqual
eq(conf.GetOption('main', 'EditorWindow', 'width'), '80')
eq(conf.GetOption('main', 'EditorWindow', 'width', type='int'), 80)
with mock.patch('idlelib.config._warn') as _warn:
eq(conf.GetOption('main', 'EditorWindow', 'font', type='int'), None)
eq(conf.GetOption('main', 'EditorWindow', 'NotExists'), None)
eq(conf.GetOption('main', 'EditorWindow', 'NotExists', default='NE'), 'NE')
eq(_warn.call_count, 4)
def test_set_option(self):
conf = self.mock_config()
conf.SetOption('main', 'Foo', 'bar', 'newbar')
self.assertEqual(conf.GetOption('main', 'Foo', 'bar'), 'newbar')
def test_get_section_list(self):
conf = self.mock_config()
self.assertCountEqual(
conf.GetSectionList('default', 'main'),
['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
'Keys', 'History', 'HelpFiles'])
self.assertCountEqual(
conf.GetSectionList('user', 'main'),
['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
'Keys', 'History', 'HelpFiles'])
with self.assertRaises(config.InvalidConfigSet):
conf.GetSectionList('foobar', 'main')
with self.assertRaises(config.InvalidConfigType):
conf.GetSectionList('default', 'notexists')
def test_get_highlight(self):
conf = self.mock_config()
eq = self.assertEqual
eq(conf.GetHighlight('IDLE Classic', 'normal'), {'foreground': '#000000',
'background': '#ffffff'})
eq(conf.GetHighlight('IDLE Classic', 'normal', 'fg'), '#000000')
eq(conf.GetHighlight('IDLE Classic', 'normal', 'bg'), '#ffffff')
with self.assertRaises(config.InvalidFgBg):
conf.GetHighlight('IDLE Classic', 'normal', 'fb')
# Test cursor (this background should be normal-background)
eq(conf.GetHighlight('IDLE Classic', 'cursor'), {'foreground': 'black',
'background': '#ffffff'})
# Test get user themes
conf.SetOption('highlight', 'Foobar', 'normal-foreground', '#747474')
conf.SetOption('highlight', 'Foobar', 'normal-background', '#171717')
with mock.patch('idlelib.config._warn'):
eq(conf.GetHighlight('Foobar', 'normal'), {'foreground': '#747474',
'background': '#171717'})
def test_get_theme_dict(self):
"XXX: NOT YET DONE"
conf = self.mock_config()
# These two should be the same
self.assertEqual(
conf.GetThemeDict('default', 'IDLE Classic'),
conf.GetThemeDict('user', 'IDLE Classic'))
with self.assertRaises(config.InvalidTheme):
conf.GetThemeDict('bad', 'IDLE Classic')
def test_get_current_theme_and_keys(self):
conf = self.mock_config()
self.assertEqual(conf.CurrentTheme(), conf.current_colors_and_keys('Theme'))
self.assertEqual(conf.CurrentKeys(), conf.current_colors_and_keys('Keys'))
def test_current_colors_and_keys(self):
conf = self.mock_config()
self.assertEqual(conf.current_colors_and_keys('Theme'), 'IDLE Classic')
def test_default_keys(self):
current_platform = sys.platform
conf = self.new_config(_utest=True)
sys.platform = 'win32'
self.assertEqual(conf.default_keys(), 'IDLE Classic Windows')
sys.platform = 'darwin'
self.assertEqual(conf.default_keys(), 'IDLE Classic OSX')
sys.platform = 'some-linux'
self.assertEqual(conf.default_keys(), 'IDLE Modern Unix')
# Restore platform
sys.platform = current_platform
def test_get_extensions(self):
userextn.read_string('''
[ZzDummy]
enable = True
[DISABLE]
enable = False
''')
eq = self.assertEqual
iGE = idleConf.GetExtensions
eq(iGE(shell_only=True), [])
eq(iGE(), ['ZzDummy'])
eq(iGE(editor_only=True), ['ZzDummy'])
eq(iGE(active_only=False), ['ZzDummy', 'DISABLE'])
eq(iGE(active_only=False, editor_only=True), ['ZzDummy', 'DISABLE'])
userextn.remove_section('ZzDummy')
userextn.remove_section('DISABLE')
def test_remove_key_bind_names(self):
conf = self.mock_config()
self.assertCountEqual(
conf.RemoveKeyBindNames(conf.GetSectionList('default', 'extensions')),
['AutoComplete', 'CodeContext', 'FormatParagraph', 'ParenMatch', 'ZzDummy'])
def test_get_extn_name_for_event(self):
userextn.read_string('''
[ZzDummy]
enable = True
''')
eq = self.assertEqual
eq(idleConf.GetExtnNameForEvent('z-in'), 'ZzDummy')
eq(idleConf.GetExtnNameForEvent('z-out'), None)
userextn.remove_section('ZzDummy')
def test_get_extension_keys(self):
userextn.read_string('''
[ZzDummy]
enable = True
''')
self.assertEqual(idleConf.GetExtensionKeys('ZzDummy'),
{'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>']})
userextn.remove_section('ZzDummy')
# need option key test
## key = ['<Option-Key-2>'] if sys.platform == 'darwin' else ['<Alt-Key-2>']
## eq(conf.GetExtensionKeys('ZoomHeight'), {'<<zoom-height>>': key})
def test_get_extension_bindings(self):
userextn.read_string('''
[ZzDummy]
enable = True
''')
eq = self.assertEqual
iGEB = idleConf.GetExtensionBindings
eq(iGEB('NotExists'), {})
expect = {'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>'],
'<<z-out>>': ['<Control-Shift-KeyRelease-Delete>']}
eq(iGEB('ZzDummy'), expect)
userextn.remove_section('ZzDummy')
def test_get_keybinding(self):
conf = self.mock_config()
eq = self.assertEqual
eq(conf.GetKeyBinding('IDLE Modern Unix', '<<copy>>'),
['<Control-Shift-Key-C>', '<Control-Key-Insert>'])
eq(conf.GetKeyBinding('IDLE Classic Unix', '<<copy>>'),
['<Alt-Key-w>', '<Meta-Key-w>'])
eq(conf.GetKeyBinding('IDLE Classic Windows', '<<copy>>'),
['<Control-Key-c>', '<Control-Key-C>'])
eq(conf.GetKeyBinding('IDLE Classic Mac', '<<copy>>'), ['<Command-Key-c>'])
eq(conf.GetKeyBinding('IDLE Classic OSX', '<<copy>>'), ['<Command-Key-c>'])
# Test keybinding not exists
eq(conf.GetKeyBinding('NOT EXISTS', '<<copy>>'), [])
eq(conf.GetKeyBinding('IDLE Modern Unix', 'NOT EXISTS'), [])
def test_get_current_keyset(self):
current_platform = sys.platform
conf = self.mock_config()
# Ensure that platform isn't darwin
sys.platform = 'some-linux'
self.assertEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
# This should not be the same, since replace <Alt- to <Option-.
# Above depended on config-extensions.def having Alt keys,
# which is no longer true.
# sys.platform = 'darwin'
# self.assertNotEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
# Restore platform
sys.platform = current_platform
def test_get_keyset(self):
conf = self.mock_config()
# Conflic with key set, should be disable to ''
conf.defaultCfg['extensions'].add_section('Foobar')
conf.defaultCfg['extensions'].add_section('Foobar_cfgBindings')
conf.defaultCfg['extensions'].set('Foobar', 'enable', 'True')
conf.defaultCfg['extensions'].set('Foobar_cfgBindings', 'newfoo', '<Key-F3>')
self.assertEqual(conf.GetKeySet('IDLE Modern Unix')['<<newfoo>>'], '')
def test_is_core_binding(self):
# XXX: Should move out the core keys to config file or other place
conf = self.mock_config()
self.assertTrue(conf.IsCoreBinding('copy'))
self.assertTrue(conf.IsCoreBinding('cut'))
self.assertTrue(conf.IsCoreBinding('del-word-right'))
self.assertFalse(conf.IsCoreBinding('not-exists'))
def test_extra_help_source_list(self):
# Test GetExtraHelpSourceList and GetAllExtraHelpSourcesList in same
# place to prevent prepare input data twice.
conf = self.mock_config()
# Test default with no extra help source
self.assertEqual(conf.GetExtraHelpSourceList('default'), [])
self.assertEqual(conf.GetExtraHelpSourceList('user'), [])
with self.assertRaises(config.InvalidConfigSet):
self.assertEqual(conf.GetExtraHelpSourceList('bad'), [])
self.assertCountEqual(
conf.GetAllExtraHelpSourcesList(),
conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
# Add help source to user config
conf.userCfg['main'].SetOption('HelpFiles', '4', 'Python;https://python.org') # This is bad input
conf.userCfg['main'].SetOption('HelpFiles', '3', 'Python:https://python.org') # This is bad input
conf.userCfg['main'].SetOption('HelpFiles', '2', 'Pillow;https://pillow.readthedocs.io/en/latest/')
conf.userCfg['main'].SetOption('HelpFiles', '1', 'IDLE;C:/Programs/Python36/Lib/idlelib/help.html')
self.assertEqual(conf.GetExtraHelpSourceList('user'),
[('IDLE', 'C:/Programs/Python36/Lib/idlelib/help.html', '1'),
('Pillow', 'https://pillow.readthedocs.io/en/latest/', '2'),
('Python', 'https://python.org', '4')])
self.assertCountEqual(
conf.GetAllExtraHelpSourcesList(),
conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
def test_get_font(self):
from test.support import requires
from tkinter import Tk
from tkinter.font import Font
conf = self.mock_config()
requires('gui')
root = Tk()
root.withdraw()
f = Font.actual(Font(name='TkFixedFont', exists=True, root=root))
self.assertEqual(
conf.GetFont(root, 'main', 'EditorWindow'),
(f['family'], 10 if f['size'] <= 0 else f['size'], f['weight']))
# Cleanup root
root.destroy()
del root
def test_get_core_keys(self):
conf = self.mock_config()
eq = self.assertEqual
eq(conf.GetCoreKeys()['<<center-insert>>'], ['<Control-l>'])
eq(conf.GetCoreKeys()['<<copy>>'], ['<Control-c>', '<Control-C>'])
eq(conf.GetCoreKeys()['<<history-next>>'], ['<Alt-n>'])
eq(conf.GetCoreKeys('IDLE Classic Windows')['<<center-insert>>'],
['<Control-Key-l>', '<Control-Key-L>'])
eq(conf.GetCoreKeys('IDLE Classic OSX')['<<copy>>'], ['<Command-Key-c>'])
eq(conf.GetCoreKeys('IDLE Classic Unix')['<<history-next>>'],
['<Alt-Key-n>', '<Meta-Key-n>'])
eq(conf.GetCoreKeys('IDLE Modern Unix')['<<history-next>>'],
['<Alt-Key-n>', '<Meta-Key-n>'])
class CurrentColorKeysTest(unittest.TestCase):
""" Test colorkeys function with user config [Theme] and [Keys] patterns.
colorkeys = config.IdleConf.current_colors_and_keys
Test all patterns written by IDLE and some errors
Item 'default' should really be 'builtin' (versus 'custom).
"""
colorkeys = idleConf.current_colors_and_keys
default_theme = 'IDLE Classic'
default_keys = idleConf.default_keys()
def test_old_builtin_theme(self):
# On initial installation, user main is blank.
self.assertEqual(self.colorkeys('Theme'), self.default_theme)
# For old default, name2 must be blank.
usermain.read_string('''
[Theme]
default = True
''')
# IDLE omits 'name' for default old builtin theme.
self.assertEqual(self.colorkeys('Theme'), self.default_theme)
# IDLE adds 'name' for non-default old builtin theme.
usermain['Theme']['name'] = 'IDLE New'
self.assertEqual(self.colorkeys('Theme'), 'IDLE New')
# Erroneous non-default old builtin reverts to default.
usermain['Theme']['name'] = 'non-existent'
self.assertEqual(self.colorkeys('Theme'), self.default_theme)
usermain.remove_section('Theme')
def test_new_builtin_theme(self):
# IDLE writes name2 for new builtins.
usermain.read_string('''
[Theme]
default = True
name2 = IDLE Dark
''')
self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
# Leftover 'name', not removed, is ignored.
usermain['Theme']['name'] = 'IDLE New'
self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
# Erroneous non-default new builtin reverts to default.
usermain['Theme']['name2'] = 'non-existent'
self.assertEqual(self.colorkeys('Theme'), self.default_theme)
usermain.remove_section('Theme')
def test_user_override_theme(self):
# Erroneous custom name (no definition) reverts to default.
usermain.read_string('''
[Theme]
default = False
name = Custom Dark
''')
self.assertEqual(self.colorkeys('Theme'), self.default_theme)
# Custom name is valid with matching Section name.
userhigh.read_string('[Custom Dark]\na=b')
self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
# Name2 is ignored.
usermain['Theme']['name2'] = 'non-existent'
self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
usermain.remove_section('Theme')
userhigh.remove_section('Custom Dark')
def test_old_builtin_keys(self):
# On initial installation, user main is blank.
self.assertEqual(self.colorkeys('Keys'), self.default_keys)
# For old default, name2 must be blank, name is always used.
usermain.read_string('''
[Keys]
default = True
name = IDLE Classic Unix
''')
self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix')
# Erroneous non-default old builtin reverts to default.
usermain['Keys']['name'] = 'non-existent'
self.assertEqual(self.colorkeys('Keys'), self.default_keys)
usermain.remove_section('Keys')
def test_new_builtin_keys(self):
# IDLE writes name2 for new builtins.
usermain.read_string('''
[Keys]
default = True
name2 = IDLE Modern Unix
''')
self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
# Leftover 'name', not removed, is ignored.
usermain['Keys']['name'] = 'IDLE Classic Unix'
self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
# Erroneous non-default new builtin reverts to default.
usermain['Keys']['name2'] = 'non-existent'
self.assertEqual(self.colorkeys('Keys'), self.default_keys)
usermain.remove_section('Keys')
def test_user_override_keys(self):
# Erroneous custom name (no definition) reverts to default.
usermain.read_string('''
[Keys]
default = False
name = Custom Keys
''')
self.assertEqual(self.colorkeys('Keys'), self.default_keys)
# Custom name is valid with matching Section name.
userkeys.read_string('[Custom Keys]\na=b')
self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
# Name2 is ignored.
usermain['Keys']['name2'] = 'non-existent'
self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
usermain.remove_section('Keys')
userkeys.remove_section('Custom Keys')
class ChangesTest(unittest.TestCase):
empty = {'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}}
def load(self): # Test_add_option verifies that this works.
changes = self.changes
changes.add_option('main', 'Msec', 'mitem', 'mval')
changes.add_option('highlight', 'Hsec', 'hitem', 'hval')
changes.add_option('keys', 'Ksec', 'kitem', 'kval')
return changes
loaded = {'main': {'Msec': {'mitem': 'mval'}},
'highlight': {'Hsec': {'hitem': 'hval'}},
'keys': {'Ksec': {'kitem':'kval'}},
'extensions': {}}
def setUp(self):
self.changes = config.ConfigChanges()
def test_init(self):
self.assertEqual(self.changes, self.empty)
def test_add_option(self):
changes = self.load()
self.assertEqual(changes, self.loaded)
changes.add_option('main', 'Msec', 'mitem', 'mval')
self.assertEqual(changes, self.loaded)
def test_save_option(self): # Static function does not touch changes.
save_option = self.changes.save_option
self.assertTrue(save_option('main', 'Indent', 'what', '0'))
self.assertFalse(save_option('main', 'Indent', 'what', '0'))
self.assertEqual(usermain['Indent']['what'], '0')
self.assertTrue(save_option('main', 'Indent', 'use-spaces', '0'))
self.assertEqual(usermain['Indent']['use-spaces'], '0')
self.assertTrue(save_option('main', 'Indent', 'use-spaces', '1'))
self.assertFalse(usermain.has_option('Indent', 'use-spaces'))
usermain.remove_section('Indent')
def test_save_added(self):
changes = self.load()
self.assertTrue(changes.save_all())
self.assertEqual(usermain['Msec']['mitem'], 'mval')
self.assertEqual(userhigh['Hsec']['hitem'], 'hval')
self.assertEqual(userkeys['Ksec']['kitem'], 'kval')
changes.add_option('main', 'Msec', 'mitem', 'mval')
self.assertFalse(changes.save_all())
usermain.remove_section('Msec')
userhigh.remove_section('Hsec')
userkeys.remove_section('Ksec')
def test_save_help(self):
# Any change to HelpFiles overwrites entire section.
changes = self.changes
changes.save_option('main', 'HelpFiles', 'IDLE', 'idledoc')
changes.add_option('main', 'HelpFiles', 'ELDI', 'codeldi')
changes.save_all()
self.assertFalse(usermain.has_option('HelpFiles', 'IDLE'))
self.assertTrue(usermain.has_option('HelpFiles', 'ELDI'))
def test_save_default(self): # Cover 2nd and 3rd false branches.
changes = self.changes
changes.add_option('main', 'Indent', 'use-spaces', '1')
# save_option returns False; cfg_type_changed remains False.
# TODO: test that save_all calls usercfg Saves.
def test_delete_section(self):
changes = self.load()
changes.delete_section('main', 'fake') # Test no exception.
self.assertEqual(changes, self.loaded) # Test nothing deleted.
for cfgtype, section in (('main', 'Msec'), ('keys', 'Ksec')):
testcfg[cfgtype].SetOption(section, 'name', 'value')
changes.delete_section(cfgtype, section)
with self.assertRaises(KeyError):
changes[cfgtype][section] # Test section gone from changes
testcfg[cfgtype][section] # and from mock userCfg.
# TODO test for save call.
def test_clear(self):
changes = self.load()
changes.clear()
self.assertEqual(changes, self.empty)
class WarningTest(unittest.TestCase):
def test_warn(self):
Equal = self.assertEqual
config._warned = set()
with captured_stderr() as stderr:
config._warn('warning', 'key')
Equal(config._warned, {('warning','key')})
Equal(stderr.getvalue(), 'warning'+'\n')
with captured_stderr() as stderr:
config._warn('warning', 'key')
Equal(stderr.getvalue(), '')
with captured_stderr() as stderr:
config._warn('warn2', 'yek')
Equal(config._warned, {('warning','key'), ('warn2','yek')})
Equal(stderr.getvalue(), 'warn2'+'\n')
if __name__ == '__main__':
unittest.main(verbosity=2)
| 32,805 | 823 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_searchbase.py | "Test searchbase, coverage 98%."
# The only thing not covered is inconsequential --
# testing skipping of suite when self.needwrapbutton is false.
import unittest
from test.support import requires
from tkinter import Tk, Frame ##, BooleanVar, StringVar
from idlelib import searchengine as se
from idlelib import searchbase as sdb
from idlelib.idle_test.mock_idle import Func
## from idlelib.idle_test.mock_tk import Var
# The ## imports above & following could help make some tests gui-free.
# However, they currently make radiobutton tests fail.
##def setUpModule():
## # Replace tk objects used to initialize se.SearchEngine.
## se.BooleanVar = Var
## se.StringVar = Var
##
##def tearDownModule():
## se.BooleanVar = BooleanVar
## se.StringVar = StringVar
class SearchDialogBaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def setUp(self):
self.engine = se.SearchEngine(self.root) # None also seems to work
self.dialog = sdb.SearchDialogBase(root=self.root, engine=self.engine)
def tearDown(self):
self.dialog.close()
def test_open_and_close(self):
# open calls create_widgets, which needs default_command
self.dialog.default_command = None
# Since text parameter of .open is not used in base class,
# pass dummy 'text' instead of tk.Text().
self.dialog.open('text')
self.assertEqual(self.dialog.top.state(), 'normal')
self.dialog.close()
self.assertEqual(self.dialog.top.state(), 'withdrawn')
self.dialog.open('text', searchphrase="hello")
self.assertEqual(self.dialog.ent.get(), 'hello')
self.dialog.close()
def test_create_widgets(self):
self.dialog.create_entries = Func()
self.dialog.create_option_buttons = Func()
self.dialog.create_other_buttons = Func()
self.dialog.create_command_buttons = Func()
self.dialog.default_command = None
self.dialog.create_widgets()
self.assertTrue(self.dialog.create_entries.called)
self.assertTrue(self.dialog.create_option_buttons.called)
self.assertTrue(self.dialog.create_other_buttons.called)
self.assertTrue(self.dialog.create_command_buttons.called)
def test_make_entry(self):
equal = self.assertEqual
self.dialog.row = 0
self.dialog.top = self.root
entry, label = self.dialog.make_entry("Test:", 'hello')
equal(label['text'], 'Test:')
self.assertIn(entry.get(), 'hello')
egi = entry.grid_info()
equal(int(egi['row']), 0)
equal(int(egi['column']), 1)
equal(int(egi['rowspan']), 1)
equal(int(egi['columnspan']), 1)
equal(self.dialog.row, 1)
def test_create_entries(self):
self.dialog.top = self.root
self.dialog.row = 0
self.engine.setpat('hello')
self.dialog.create_entries()
self.assertIn(self.dialog.ent.get(), 'hello')
def test_make_frame(self):
self.dialog.row = 0
self.dialog.top = self.root
frame, label = self.dialog.make_frame()
self.assertEqual(label, '')
self.assertIsInstance(frame, Frame)
frame, label = self.dialog.make_frame('testlabel')
self.assertEqual(label['text'], 'testlabel')
self.assertIsInstance(frame, Frame)
def btn_test_setup(self, meth):
self.dialog.top = self.root
self.dialog.row = 0
return meth()
def test_create_option_buttons(self):
e = self.engine
for state in (0, 1):
for var in (e.revar, e.casevar, e.wordvar, e.wrapvar):
var.set(state)
frame, options = self.btn_test_setup(
self.dialog.create_option_buttons)
for spec, button in zip (options, frame.pack_slaves()):
var, label = spec
self.assertEqual(button['text'], label)
self.assertEqual(var.get(), state)
def test_create_other_buttons(self):
for state in (False, True):
var = self.engine.backvar
var.set(state)
frame, others = self.btn_test_setup(
self.dialog.create_other_buttons)
buttons = frame.pack_slaves()
for spec, button in zip(others, buttons):
val, label = spec
self.assertEqual(button['text'], label)
if val == state:
# hit other button, then this one
# indexes depend on button order
self.assertEqual(var.get(), state)
def test_make_button(self):
self.dialog.top = self.root
self.dialog.buttonframe = Frame(self.dialog.top)
btn = self.dialog.make_button('Test', self.dialog.close)
self.assertEqual(btn['text'], 'Test')
def test_create_command_buttons(self):
self.dialog.top = self.root
self.dialog.create_command_buttons()
# Look for close button command in buttonframe
closebuttoncommand = ''
for child in self.dialog.buttonframe.winfo_children():
if child['text'] == 'close':
closebuttoncommand = child['command']
self.assertIn('close', closebuttoncommand)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
| 5,479 | 157 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_text.py | ''' Test mock_tk.Text class against tkinter.Text class
Run same tests with both by creating a mixin class.
'''
import unittest
from test.support import requires
from _tkinter import TclError
class TextTest(object):
"Define items common to both sets of tests."
hw = 'hello\nworld' # Several tests insert this after initialization.
hwn = hw+'\n' # \n present at initialization, before insert
# setUpClass defines cls.Text and maybe cls.root.
# setUp defines self.text from Text and maybe root.
def test_init(self):
self.assertEqual(self.text.get('1.0'), '\n')
self.assertEqual(self.text.get('end'), '')
def test_index_empty(self):
index = self.text.index
for dex in (-1.0, 0.3, '1.-1', '1.0', '1.0 lineend', '1.end', '1.33',
'insert'):
self.assertEqual(index(dex), '1.0')
for dex in 'end', 2.0, '2.1', '33.44':
self.assertEqual(index(dex), '2.0')
def test_index_data(self):
index = self.text.index
self.text.insert('1.0', self.hw)
for dex in -1.0, 0.3, '1.-1', '1.0':
self.assertEqual(index(dex), '1.0')
for dex in '1.0 lineend', '1.end', '1.33':
self.assertEqual(index(dex), '1.5')
for dex in 'end', '33.44':
self.assertEqual(index(dex), '3.0')
def test_get(self):
get = self.text.get
Equal = self.assertEqual
self.text.insert('1.0', self.hw)
Equal(get('end'), '')
Equal(get('end', 'end'), '')
Equal(get('1.0'), 'h')
Equal(get('1.0', '1.1'), 'h')
Equal(get('1.0', '1.3'), 'hel')
Equal(get('1.1', '1.3'), 'el')
Equal(get('1.0', '1.0 lineend'), 'hello')
Equal(get('1.0', '1.10'), 'hello')
Equal(get('1.0 lineend'), '\n')
Equal(get('1.1', '2.3'), 'ello\nwor')
Equal(get('1.0', '2.5'), self.hw)
Equal(get('1.0', 'end'), self.hwn)
Equal(get('0.0', '5.0'), self.hwn)
def test_insert(self):
insert = self.text.insert
get = self.text.get
Equal = self.assertEqual
insert('1.0', self.hw)
Equal(get('1.0', 'end'), self.hwn)
insert('1.0', '') # nothing
Equal(get('1.0', 'end'), self.hwn)
insert('1.0', '*')
Equal(get('1.0', 'end'), '*hello\nworld\n')
insert('1.0 lineend', '*')
Equal(get('1.0', 'end'), '*hello*\nworld\n')
insert('2.3', '*')
Equal(get('1.0', 'end'), '*hello*\nwor*ld\n')
insert('end', 'x')
Equal(get('1.0', 'end'), '*hello*\nwor*ldx\n')
insert('1.4', 'x\n')
Equal(get('1.0', 'end'), '*helx\nlo*\nwor*ldx\n')
def test_no_delete(self):
# if index1 == 'insert' or 'end' or >= end, there is no deletion
delete = self.text.delete
get = self.text.get
Equal = self.assertEqual
self.text.insert('1.0', self.hw)
delete('insert')
Equal(get('1.0', 'end'), self.hwn)
delete('end')
Equal(get('1.0', 'end'), self.hwn)
delete('insert', 'end')
Equal(get('1.0', 'end'), self.hwn)
delete('insert', '5.5')
Equal(get('1.0', 'end'), self.hwn)
delete('1.4', '1.0')
Equal(get('1.0', 'end'), self.hwn)
delete('1.4', '1.4')
Equal(get('1.0', 'end'), self.hwn)
def test_delete_char(self):
delete = self.text.delete
get = self.text.get
Equal = self.assertEqual
self.text.insert('1.0', self.hw)
delete('1.0')
Equal(get('1.0', '1.end'), 'ello')
delete('1.0', '1.1')
Equal(get('1.0', '1.end'), 'llo')
# delete \n and combine 2 lines into 1
delete('1.end')
Equal(get('1.0', '1.end'), 'lloworld')
self.text.insert('1.3', '\n')
delete('1.10')
Equal(get('1.0', '1.end'), 'lloworld')
self.text.insert('1.3', '\n')
delete('1.3', '2.0')
Equal(get('1.0', '1.end'), 'lloworld')
def test_delete_slice(self):
delete = self.text.delete
get = self.text.get
Equal = self.assertEqual
self.text.insert('1.0', self.hw)
delete('1.0', '1.0 lineend')
Equal(get('1.0', 'end'), '\nworld\n')
delete('1.0', 'end')
Equal(get('1.0', 'end'), '\n')
self.text.insert('1.0', self.hw)
delete('1.0', '2.0')
Equal(get('1.0', 'end'), 'world\n')
delete('1.0', 'end')
Equal(get('1.0', 'end'), '\n')
self.text.insert('1.0', self.hw)
delete('1.2', '2.3')
Equal(get('1.0', 'end'), 'held\n')
def test_multiple_lines(self): # insert and delete
self.text.insert('1.0', 'hello')
self.text.insert('1.3', '1\n2\n3\n4\n5')
self.assertEqual(self.text.get('1.0', 'end'), 'hel1\n2\n3\n4\n5lo\n')
self.text.delete('1.3', '5.1')
self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')
def test_compare(self):
compare = self.text.compare
Equal = self.assertEqual
# need data so indexes not squished to 1,0
self.text.insert('1.0', 'First\nSecond\nThird\n')
self.assertRaises(TclError, compare, '2.2', 'op', '2.2')
for op, less1, less0, equal, greater0, greater1 in (
('<', True, True, False, False, False),
('<=', True, True, True, False, False),
('>', False, False, False, True, True),
('>=', False, False, True, True, True),
('==', False, False, True, False, False),
('!=', True, True, False, True, True),
):
Equal(compare('1.1', op, '2.2'), less1, op)
Equal(compare('2.1', op, '2.2'), less0, op)
Equal(compare('2.2', op, '2.2'), equal, op)
Equal(compare('2.3', op, '2.2'), greater0, op)
Equal(compare('3.3', op, '2.2'), greater1, op)
class MockTextTest(TextTest, unittest.TestCase):
@classmethod
def setUpClass(cls):
from idlelib.idle_test.mock_tk import Text
cls.Text = Text
def setUp(self):
self.text = self.Text()
def test_decode(self):
# test endflags (-1, 0) not tested by test_index (which uses +1)
decode = self.text._decode
Equal = self.assertEqual
self.text.insert('1.0', self.hw)
Equal(decode('end', -1), (2, 5))
Equal(decode('3.1', -1), (2, 5))
Equal(decode('end', 0), (2, 6))
Equal(decode('3.1', 0), (2, 6))
class TkTextTest(TextTest, unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
from tkinter import Tk, Text
cls.Text = Text
cls.root = Tk()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def setUp(self):
self.text = self.Text(self.root)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=False)
| 6,978 | 237 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_codecontext.py | "Test codecontext, coverage 100%"
from idlelib import codecontext
import unittest
from test.support import requires
from tkinter import Tk, Frame, Text, TclError
from unittest import mock
import re
from idlelib import config
usercfg = codecontext.idleConf.userCfg
testcfg = {
'main': config.IdleUserConfParser(''),
'highlight': config.IdleUserConfParser(''),
'keys': config.IdleUserConfParser(''),
'extensions': config.IdleUserConfParser(''),
}
code_sample = """\
class C1():
# Class comment.
def __init__(self, a, b):
self.a = a
self.b = b
def compare(self):
if a > b:
return a
elif a < b:
return b
else:
return None
"""
class DummyEditwin:
def __init__(self, root, frame, text):
self.root = root
self.top = root
self.text_frame = frame
self.text = text
class CodeContextTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
root = cls.root = Tk()
root.withdraw()
frame = cls.frame = Frame(root)
text = cls.text = Text(frame)
text.insert('1.0', code_sample)
# Need to pack for creation of code context text widget.
frame.pack(side='left', fill='both', expand=1)
text.pack(side='top', fill='both', expand=1)
cls.editor = DummyEditwin(root, frame, text)
codecontext.idleConf.userCfg = testcfg
@classmethod
def tearDownClass(cls):
codecontext.idleConf.userCfg = usercfg
cls.editor.text.delete('1.0', 'end')
del cls.editor, cls.frame, cls.text
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def setUp(self):
self.text.yview(0)
self.cc = codecontext.CodeContext(self.editor)
def tearDown(self):
if self.cc.context:
self.cc.context.destroy()
# Explicitly call __del__ to remove scheduled scripts.
self.cc.__del__()
del self.cc.context, self.cc
def test_init(self):
eq = self.assertEqual
ed = self.editor
cc = self.cc
eq(cc.editwin, ed)
eq(cc.text, ed.text)
eq(cc.textfont, ed.text['font'])
self.assertIsNone(cc.context)
eq(cc.info, [(0, -1, '', False)])
eq(cc.topvisible, 1)
eq(self.root.tk.call('after', 'info', self.cc.t1)[1], 'timer')
eq(self.root.tk.call('after', 'info', self.cc.t2)[1], 'timer')
def test_del(self):
self.cc.__del__()
with self.assertRaises(TclError) as msg:
self.root.tk.call('after', 'info', self.cc.t1)
self.assertIn("doesn't exist", msg)
with self.assertRaises(TclError) as msg:
self.root.tk.call('after', 'info', self.cc.t2)
self.assertIn("doesn't exist", msg)
# For coverage on the except. Have to delete because the
# above Tcl error is caught by after_cancel.
del self.cc.t1, self.cc.t2
self.cc.__del__()
def test_reload(self):
codecontext.CodeContext.reload()
self.assertEqual(self.cc.colors, {'background': 'lightgray',
'foreground': '#000000'})
self.assertEqual(self.cc.context_depth, 15)
def test_toggle_code_context_event(self):
eq = self.assertEqual
cc = self.cc
toggle = cc.toggle_code_context_event
# Make sure code context is off.
if cc.context:
toggle()
# Toggle on.
eq(toggle(), 'break')
self.assertIsNotNone(cc.context)
eq(cc.context['font'], cc.textfont)
eq(cc.context['fg'], cc.colors['foreground'])
eq(cc.context['bg'], cc.colors['background'])
eq(cc.context.get('1.0', 'end-1c'), '')
# Toggle off.
eq(toggle(), 'break')
self.assertIsNone(cc.context)
def test_get_context(self):
eq = self.assertEqual
gc = self.cc.get_context
# stopline must be greater than 0.
with self.assertRaises(AssertionError):
gc(1, stopline=0)
eq(gc(3), ([(2, 0, 'class C1():', 'class')], 0))
# Don't return comment.
eq(gc(4), ([(2, 0, 'class C1():', 'class')], 0))
# Two indentation levels and no comment.
eq(gc(5), ([(2, 0, 'class C1():', 'class'),
(4, 4, ' def __init__(self, a, b):', 'def')], 0))
# Only one 'def' is returned, not both at the same indent level.
eq(gc(10), ([(2, 0, 'class C1():', 'class'),
(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if')], 0))
# With 'elif', also show the 'if' even though it's at the same level.
eq(gc(11), ([(2, 0, 'class C1():', 'class'),
(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 0))
# Set stop_line to not go back to first line in source code.
# Return includes stop_line.
eq(gc(11, stopline=2), ([(2, 0, 'class C1():', 'class'),
(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 0))
eq(gc(11, stopline=3), ([(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 4))
eq(gc(11, stopline=8), ([(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 8))
# Set stop_indent to test indent level to stop at.
eq(gc(11, stopindent=4), ([(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 4))
# Check that the 'if' is included.
eq(gc(11, stopindent=8), ([(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')], 8))
def test_update_code_context(self):
eq = self.assertEqual
cc = self.cc
# Ensure code context is active.
if not cc.context:
cc.toggle_code_context_event()
# Invoke update_code_context without scrolling - nothing happens.
self.assertIsNone(cc.update_code_context())
eq(cc.info, [(0, -1, '', False)])
eq(cc.topvisible, 1)
# Scroll down to line 1.
cc.text.yview(1)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False)])
eq(cc.topvisible, 2)
eq(cc.context.get('1.0', 'end-1c'), '')
# Scroll down to line 2.
cc.text.yview(2)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1():', 'class')])
eq(cc.topvisible, 3)
eq(cc.context.get('1.0', 'end-1c'), 'class C1():')
# Scroll down to line 3. Since it's a comment, nothing changes.
cc.text.yview(3)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1():', 'class')])
eq(cc.topvisible, 4)
eq(cc.context.get('1.0', 'end-1c'), 'class C1():')
# Scroll down to line 4.
cc.text.yview(4)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False),
(2, 0, 'class C1():', 'class'),
(4, 4, ' def __init__(self, a, b):', 'def')])
eq(cc.topvisible, 5)
eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
' def __init__(self, a, b):')
# Scroll down to line 11. Last 'def' is removed.
cc.text.yview(11)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False),
(2, 0, 'class C1():', 'class'),
(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')])
eq(cc.topvisible, 12)
eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
' def compare(self):\n'
' if a > b:\n'
' elif a < b:')
# No scroll. No update, even though context_depth changed.
cc.update_code_context()
cc.context_depth = 1
eq(cc.info, [(0, -1, '', False),
(2, 0, 'class C1():', 'class'),
(7, 4, ' def compare(self):', 'def'),
(8, 8, ' if a > b:', 'if'),
(10, 8, ' elif a < b:', 'elif')])
eq(cc.topvisible, 12)
eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
' def compare(self):\n'
' if a > b:\n'
' elif a < b:')
# Scroll up.
cc.text.yview(5)
cc.update_code_context()
eq(cc.info, [(0, -1, '', False),
(2, 0, 'class C1():', 'class'),
(4, 4, ' def __init__(self, a, b):', 'def')])
eq(cc.topvisible, 6)
# context_depth is 1.
eq(cc.context.get('1.0', 'end-1c'), ' def __init__(self, a, b):')
def test_jumptoline(self):
eq = self.assertEqual
cc = self.cc
jump = cc.jumptoline
if not cc.context:
cc.toggle_code_context_event()
# Empty context.
cc.text.yview(f'{2}.0')
cc.update_code_context()
eq(cc.topvisible, 2)
cc.context.mark_set('insert', '1.5')
jump()
eq(cc.topvisible, 1)
# 4 lines of context showing.
cc.text.yview(f'{12}.0')
cc.update_code_context()
eq(cc.topvisible, 12)
cc.context.mark_set('insert', '3.0')
jump()
eq(cc.topvisible, 8)
# More context lines than limit.
cc.context_depth = 2
cc.text.yview(f'{12}.0')
cc.update_code_context()
eq(cc.topvisible, 12)
cc.context.mark_set('insert', '1.0')
jump()
eq(cc.topvisible, 8)
@mock.patch.object(codecontext.CodeContext, 'update_code_context')
def test_timer_event(self, mock_update):
# Ensure code context is not active.
if self.cc.context:
self.cc.toggle_code_context_event()
self.cc.timer_event()
mock_update.assert_not_called()
# Activate code context.
self.cc.toggle_code_context_event()
self.cc.timer_event()
mock_update.assert_called()
def test_config_timer_event(self):
eq = self.assertEqual
cc = self.cc
save_font = cc.text['font']
save_colors = codecontext.CodeContext.colors
test_font = 'FakeFont'
test_colors = {'background': '#222222', 'foreground': '#ffff00'}
# Ensure code context is not active.
if cc.context:
cc.toggle_code_context_event()
# Nothing updates on inactive code context.
cc.text['font'] = test_font
codecontext.CodeContext.colors = test_colors
cc.config_timer_event()
eq(cc.textfont, save_font)
eq(cc.contextcolors, save_colors)
# Activate code context, but no change to font or color.
cc.toggle_code_context_event()
cc.text['font'] = save_font
codecontext.CodeContext.colors = save_colors
cc.config_timer_event()
eq(cc.textfont, save_font)
eq(cc.contextcolors, save_colors)
eq(cc.context['font'], save_font)
eq(cc.context['background'], save_colors['background'])
eq(cc.context['foreground'], save_colors['foreground'])
# Active code context, change font.
cc.text['font'] = test_font
cc.config_timer_event()
eq(cc.textfont, test_font)
eq(cc.contextcolors, save_colors)
eq(cc.context['font'], test_font)
eq(cc.context['background'], save_colors['background'])
eq(cc.context['foreground'], save_colors['foreground'])
# Active code context, change color.
cc.text['font'] = save_font
codecontext.CodeContext.colors = test_colors
cc.config_timer_event()
eq(cc.textfont, save_font)
eq(cc.contextcolors, test_colors)
eq(cc.context['font'], save_font)
eq(cc.context['background'], test_colors['background'])
eq(cc.context['foreground'], test_colors['foreground'])
codecontext.CodeContext.colors = save_colors
cc.config_timer_event()
class HelperFunctionText(unittest.TestCase):
def test_get_spaces_firstword(self):
get = codecontext.get_spaces_firstword
test_lines = (
(' first word', (' ', 'first')),
('\tfirst word', ('\t', 'first')),
(' \u19D4\u19D2: ', (' ', '\u19D4\u19D2')),
('no spaces', ('', 'no')),
('', ('', '')),
('# TEST COMMENT', ('', '')),
(' (continuation)', (' ', ''))
)
for line, expected_output in test_lines:
self.assertEqual(get(line), expected_output)
# Send the pattern in the call.
self.assertEqual(get(' (continuation)',
c=re.compile(r'^(\s*)([^\s]*)')),
(' ', '(continuation)'))
def test_get_line_info(self):
eq = self.assertEqual
gli = codecontext.get_line_info
lines = code_sample.splitlines()
# Line 1 is not a BLOCKOPENER.
eq(gli(lines[0]), (codecontext.INFINITY, '', False))
# Line 2 is a BLOCKOPENER without an indent.
eq(gli(lines[1]), (0, 'class C1():', 'class'))
# Line 3 is not a BLOCKOPENER and does not return the indent level.
eq(gli(lines[2]), (codecontext.INFINITY, ' # Class comment.', False))
# Line 4 is a BLOCKOPENER and is indented.
eq(gli(lines[3]), (4, ' def __init__(self, a, b):', 'def'))
# Line 8 is a different BLOCKOPENER and is indented.
eq(gli(lines[7]), (8, ' if a > b:', 'if'))
# Test tab.
eq(gli('\tif a == b:'), (1, '\tif a == b:', 'if'))
if __name__ == '__main__':
unittest.main(verbosity=2)
| 14,494 | 404 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Lib/idlelib/idle_test/test_squeezer.py | from collections import namedtuple
from tkinter import Text, Tk
import unittest
from unittest.mock import Mock, NonCallableMagicMock, patch, sentinel, ANY
from test.support import requires
from idlelib.config import idleConf
from idlelib.squeezer import count_lines_with_wrapping, ExpandingButton, \
Squeezer
from idlelib import macosx
from idlelib.textview import view_text
from idlelib.tooltip import Hovertip
from idlelib.pyshell import PyShell
SENTINEL_VALUE = sentinel.SENTINEL_VALUE
def get_test_tk_root(test_instance):
"""Helper for tests: Create a root Tk object."""
requires('gui')
root = Tk()
root.withdraw()
def cleanup_root():
root.update_idletasks()
root.destroy()
test_instance.addCleanup(cleanup_root)
return root
class CountLinesTest(unittest.TestCase):
"""Tests for the count_lines_with_wrapping function."""
def check(self, expected, text, linewidth, tabwidth):
return self.assertEqual(
expected,
count_lines_with_wrapping(text, linewidth, tabwidth),
)
def test_count_empty(self):
"""Test with an empty string."""
self.assertEqual(count_lines_with_wrapping(""), 0)
def test_count_begins_with_empty_line(self):
"""Test with a string which begins with a newline."""
self.assertEqual(count_lines_with_wrapping("\ntext"), 2)
def test_count_ends_with_empty_line(self):
"""Test with a string which ends with a newline."""
self.assertEqual(count_lines_with_wrapping("text\n"), 1)
def test_count_several_lines(self):
"""Test with several lines of text."""
self.assertEqual(count_lines_with_wrapping("1\n2\n3\n"), 3)
def test_tab_width(self):
"""Test with various tab widths and line widths."""
self.check(expected=1, text='\t' * 1, linewidth=8, tabwidth=4)
self.check(expected=1, text='\t' * 2, linewidth=8, tabwidth=4)
self.check(expected=2, text='\t' * 3, linewidth=8, tabwidth=4)
self.check(expected=2, text='\t' * 4, linewidth=8, tabwidth=4)
self.check(expected=3, text='\t' * 5, linewidth=8, tabwidth=4)
# test longer lines and various tab widths
self.check(expected=4, text='\t' * 10, linewidth=12, tabwidth=4)
self.check(expected=10, text='\t' * 10, linewidth=12, tabwidth=8)
self.check(expected=2, text='\t' * 4, linewidth=10, tabwidth=3)
# test tabwidth=1
self.check(expected=2, text='\t' * 9, linewidth=5, tabwidth=1)
self.check(expected=2, text='\t' * 10, linewidth=5, tabwidth=1)
self.check(expected=3, text='\t' * 11, linewidth=5, tabwidth=1)
# test for off-by-one errors
self.check(expected=2, text='\t' * 6, linewidth=12, tabwidth=4)
self.check(expected=3, text='\t' * 6, linewidth=11, tabwidth=4)
self.check(expected=2, text='\t' * 6, linewidth=13, tabwidth=4)
class SqueezerTest(unittest.TestCase):
"""Tests for the Squeezer class."""
def make_mock_editor_window(self):
"""Create a mock EditorWindow instance."""
editwin = NonCallableMagicMock()
# isinstance(editwin, PyShell) must be true for Squeezer to enable
# auto-squeezing; in practice this will always be true
editwin.__class__ = PyShell
return editwin
def make_squeezer_instance(self, editor_window=None):
"""Create an actual Squeezer instance with a mock EditorWindow."""
if editor_window is None:
editor_window = self.make_mock_editor_window()
return Squeezer(editor_window)
def test_count_lines(self):
"""Test Squeezer.count_lines() with various inputs.
This checks that Squeezer.count_lines() calls the
count_lines_with_wrapping() function with the appropriate parameters.
"""
for tabwidth, linewidth in [(4, 80), (1, 79), (8, 80), (3, 120)]:
self._test_count_lines_helper(linewidth=linewidth,
tabwidth=tabwidth)
def _prepare_mock_editwin_for_count_lines(self, editwin,
linewidth, tabwidth):
"""Prepare a mock EditorWindow object for Squeezer.count_lines."""
CHAR_WIDTH = 10
BORDER_WIDTH = 2
PADDING_WIDTH = 1
# Prepare all the required functionality on the mock EditorWindow object
# so that the calculations in Squeezer.count_lines() can run.
editwin.get_tk_tabwidth.return_value = tabwidth
editwin.text.winfo_width.return_value = \
linewidth * CHAR_WIDTH + 2 * (BORDER_WIDTH + PADDING_WIDTH)
text_opts = {
'border': BORDER_WIDTH,
'padx': PADDING_WIDTH,
'font': None,
}
editwin.text.cget = lambda opt: text_opts[opt]
# monkey-path tkinter.font.Font with a mock object, so that
# Font.measure('0') returns CHAR_WIDTH
mock_font = Mock()
def measure(char):
if char == '0':
return CHAR_WIDTH
raise ValueError("measure should only be called on '0'!")
mock_font.return_value.measure = measure
patcher = patch('idlelib.squeezer.Font', mock_font)
patcher.start()
self.addCleanup(patcher.stop)
def _test_count_lines_helper(self, linewidth, tabwidth):
"""Helper for test_count_lines."""
editwin = self.make_mock_editor_window()
self._prepare_mock_editwin_for_count_lines(editwin, linewidth, tabwidth)
squeezer = self.make_squeezer_instance(editwin)
mock_count_lines = Mock(return_value=SENTINEL_VALUE)
text = 'TEXT'
with patch('idlelib.squeezer.count_lines_with_wrapping',
mock_count_lines):
self.assertIs(squeezer.count_lines(text), SENTINEL_VALUE)
mock_count_lines.assert_called_with(text, linewidth, tabwidth)
def test_init(self):
"""Test the creation of Squeezer instances."""
editwin = self.make_mock_editor_window()
squeezer = self.make_squeezer_instance(editwin)
self.assertIs(squeezer.editwin, editwin)
self.assertEqual(squeezer.expandingbuttons, [])
def test_write_no_tags(self):
"""Test Squeezer's overriding of the EditorWindow's write() method."""
editwin = self.make_mock_editor_window()
for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
self.assertEqual(squeezer.editwin.write(text, ()), SENTINEL_VALUE)
self.assertEqual(orig_write.call_count, 1)
orig_write.assert_called_with(text, ())
self.assertEqual(len(squeezer.expandingbuttons), 0)
def test_write_not_stdout(self):
"""Test Squeezer's overriding of the EditorWindow's write() method."""
for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
editwin = self.make_mock_editor_window()
editwin.write.return_value = SENTINEL_VALUE
orig_write = editwin.write
squeezer = self.make_squeezer_instance(editwin)
self.assertEqual(squeezer.editwin.write(text, "stderr"),
SENTINEL_VALUE)
self.assertEqual(orig_write.call_count, 1)
orig_write.assert_called_with(text, "stderr")
self.assertEqual(len(squeezer.expandingbuttons), 0)
def test_write_stdout(self):
"""Test Squeezer's overriding of the EditorWindow's write() method."""
editwin = self.make_mock_editor_window()
self._prepare_mock_editwin_for_count_lines(editwin,
linewidth=80, tabwidth=8)
for text in ['', 'TEXT']:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50
self.assertEqual(squeezer.editwin.write(text, "stdout"),
SENTINEL_VALUE)
self.assertEqual(orig_write.call_count, 1)
orig_write.assert_called_with(text, "stdout")
self.assertEqual(len(squeezer.expandingbuttons), 0)
for text in ['LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50
self.assertEqual(squeezer.editwin.write(text, "stdout"), None)
self.assertEqual(orig_write.call_count, 0)
self.assertEqual(len(squeezer.expandingbuttons), 1)
def test_auto_squeeze(self):
"""Test that the auto-squeezing creates an ExpandingButton properly."""
root = get_test_tk_root(self)
text_widget = Text(root)
text_widget.mark_set("iomark", "1.0")
editwin = self.make_mock_editor_window()
editwin.text = text_widget
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 5
squeezer.count_lines = Mock(return_value=6)
editwin.write('TEXT\n'*6, "stdout")
self.assertEqual(text_widget.get('1.0', 'end'), '\n')
self.assertEqual(len(squeezer.expandingbuttons), 1)
def test_squeeze_current_text_event(self):
"""Test the squeeze_current_text event."""
root = get_test_tk_root(self)
# squeezing text should work for both stdout and stderr
for tag_name in ["stdout", "stderr"]:
text_widget = Text(root)
text_widget.mark_set("iomark", "1.0")
editwin = self.make_mock_editor_window()
editwin.text = editwin.per.bottom = text_widget
squeezer = self.make_squeezer_instance(editwin)
squeezer.count_lines = Mock(return_value=6)
# prepare some text in the Text widget
text_widget.insert("1.0", "SOME\nTEXT\n", tag_name)
text_widget.mark_set("insert", "1.0")
self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 0)
# test squeezing the current text
retval = squeezer.squeeze_current_text_event(event=Mock())
self.assertEqual(retval, "break")
self.assertEqual(text_widget.get('1.0', 'end'), '\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 1)
self.assertEqual(squeezer.expandingbuttons[0].s, 'SOME\nTEXT')
# test that expanding the squeezed text works and afterwards the
# Text widget contains the original text
squeezer.expandingbuttons[0].expand(event=Mock())
self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 0)
def test_squeeze_current_text_event_no_allowed_tags(self):
"""Test that the event doesn't squeeze text without a relevant tag."""
root = get_test_tk_root(self)
text_widget = Text(root)
text_widget.mark_set("iomark", "1.0")
editwin = self.make_mock_editor_window()
editwin.text = editwin.per.bottom = text_widget
squeezer = self.make_squeezer_instance(editwin)
squeezer.count_lines = Mock(return_value=6)
# prepare some text in the Text widget
text_widget.insert("1.0", "SOME\nTEXT\n", "TAG")
text_widget.mark_set("insert", "1.0")
self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 0)
# test squeezing the current text
retval = squeezer.squeeze_current_text_event(event=Mock())
self.assertEqual(retval, "break")
self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 0)
def test_squeeze_text_before_existing_squeezed_text(self):
"""Test squeezing text before existing squeezed text."""
root = get_test_tk_root(self)
text_widget = Text(root)
text_widget.mark_set("iomark", "1.0")
editwin = self.make_mock_editor_window()
editwin.text = editwin.per.bottom = text_widget
squeezer = self.make_squeezer_instance(editwin)
squeezer.count_lines = Mock(return_value=6)
# prepare some text in the Text widget and squeeze it
text_widget.insert("1.0", "SOME\nTEXT\n", "stdout")
text_widget.mark_set("insert", "1.0")
squeezer.squeeze_current_text_event(event=Mock())
self.assertEqual(len(squeezer.expandingbuttons), 1)
# test squeezing the current text
text_widget.insert("1.0", "MORE\nSTUFF\n", "stdout")
text_widget.mark_set("insert", "1.0")
retval = squeezer.squeeze_current_text_event(event=Mock())
self.assertEqual(retval, "break")
self.assertEqual(text_widget.get('1.0', 'end'), '\n\n\n')
self.assertEqual(len(squeezer.expandingbuttons), 2)
self.assertTrue(text_widget.compare(
squeezer.expandingbuttons[0],
'<',
squeezer.expandingbuttons[1],
))
GetOptionSignature = namedtuple('GetOptionSignature',
'configType section option default type warn_on_default raw')
@classmethod
def _make_sig(cls, configType, section, option, default=sentinel.NOT_GIVEN,
type=sentinel.NOT_GIVEN,
warn_on_default=sentinel.NOT_GIVEN,
raw=sentinel.NOT_GIVEN):
return cls.GetOptionSignature(configType, section, option, default,
type, warn_on_default, raw)
@classmethod
def get_GetOption_signature(cls, mock_call_obj):
args, kwargs = mock_call_obj[-2:]
return cls._make_sig(*args, **kwargs)
def test_reload(self):
"""Test the reload() class-method."""
self.assertIsInstance(Squeezer.auto_squeeze_min_lines, int)
idleConf.SetOption('main', 'PyShell', 'auto-squeeze-min-lines', '42')
Squeezer.reload()
self.assertEqual(Squeezer.auto_squeeze_min_lines, 42)
class ExpandingButtonTest(unittest.TestCase):
"""Tests for the ExpandingButton class."""
# In these tests the squeezer instance is a mock, but actual tkinter
# Text and Button instances are created.
def make_mock_squeezer(self):
"""Helper for tests: Create a mock Squeezer object."""
root = get_test_tk_root(self)
squeezer = Mock()
squeezer.editwin.text = Text(root)
# Set default values for the configuration settings
squeezer.auto_squeeze_min_lines = 50
return squeezer
@patch('idlelib.squeezer.Hovertip', autospec=Hovertip)
def test_init(self, MockHovertip):
"""Test the simplest creation of an ExpandingButton."""
squeezer = self.make_mock_squeezer()
text_widget = squeezer.editwin.text
expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
self.assertEqual(expandingbutton.s, 'TEXT')
# check that the underlying tkinter.Button is properly configured
self.assertEqual(expandingbutton.master, text_widget)
self.assertTrue('50 lines' in expandingbutton.cget('text'))
# check that the text widget still contains no text
self.assertEqual(text_widget.get('1.0', 'end'), '\n')
# check that the mouse events are bound
self.assertIn('<Double-Button-1>', expandingbutton.bind())
right_button_code = '<Button-%s>' % ('2' if macosx.isAquaTk() else '3')
self.assertIn(right_button_code, expandingbutton.bind())
# check that ToolTip was called once, with appropriate values
self.assertEqual(MockHovertip.call_count, 1)
MockHovertip.assert_called_with(expandingbutton, ANY, hover_delay=ANY)
# check that 'right-click' appears in the tooltip text
tooltip_text = MockHovertip.call_args[0][1]
self.assertIn('right-click', tooltip_text.lower())
def test_expand(self):
"""Test the expand event."""
squeezer = self.make_mock_squeezer()
expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
# insert the button into the text widget
# (this is normally done by the Squeezer class)
text_widget = expandingbutton.text
text_widget.window_create("1.0", window=expandingbutton)
# set base_text to the text widget, so that changes are actually made
# to it (by ExpandingButton) and we can inspect these changes afterwards
expandingbutton.base_text = expandingbutton.text
# trigger the expand event
retval = expandingbutton.expand(event=Mock())
self.assertEqual(retval, None)
# check that the text was inserted into the text widget
self.assertEqual(text_widget.get('1.0', 'end'), 'TEXT\n')
# check that the 'TAGS' tag was set on the inserted text
text_end_index = text_widget.index('end-1c')
self.assertEqual(text_widget.get('1.0', text_end_index), 'TEXT')
self.assertEqual(text_widget.tag_nextrange('TAGS', '1.0'),
('1.0', text_end_index))
# check that the button removed itself from squeezer.expandingbuttons
self.assertEqual(squeezer.expandingbuttons.remove.call_count, 1)
squeezer.expandingbuttons.remove.assert_called_with(expandingbutton)
def test_expand_dangerous_oupput(self):
"""Test that expanding very long output asks user for confirmation."""
squeezer = self.make_mock_squeezer()
text = 'a' * 10**5
expandingbutton = ExpandingButton(text, 'TAGS', 50, squeezer)
expandingbutton.set_is_dangerous()
self.assertTrue(expandingbutton.is_dangerous)
# insert the button into the text widget
# (this is normally done by the Squeezer class)
text_widget = expandingbutton.text
text_widget.window_create("1.0", window=expandingbutton)
# set base_text to the text widget, so that changes are actually made
# to it (by ExpandingButton) and we can inspect these changes afterwards
expandingbutton.base_text = expandingbutton.text
# patch the message box module to always return False
with patch('idlelib.squeezer.tkMessageBox') as mock_msgbox:
mock_msgbox.askokcancel.return_value = False
mock_msgbox.askyesno.return_value = False
# trigger the expand event
retval = expandingbutton.expand(event=Mock())
# check that the event chain was broken and no text was inserted
self.assertEqual(retval, 'break')
self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), '')
# patch the message box module to always return True
with patch('idlelib.squeezer.tkMessageBox') as mock_msgbox:
mock_msgbox.askokcancel.return_value = True
mock_msgbox.askyesno.return_value = True
# trigger the expand event
retval = expandingbutton.expand(event=Mock())
# check that the event chain wasn't broken and the text was inserted
self.assertEqual(retval, None)
self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), text)
def test_copy(self):
"""Test the copy event."""
# testing with the actual clipboard proved problematic, so this test
# replaces the clipboard manipulation functions with mocks and checks
# that they are called appropriately
squeezer = self.make_mock_squeezer()
expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
expandingbutton.clipboard_clear = Mock()
expandingbutton.clipboard_append = Mock()
# trigger the copy event
retval = expandingbutton.copy(event=Mock())
self.assertEqual(retval, None)
# check that the expanding button called clipboard_clear() and
# clipboard_append('TEXT') once each
self.assertEqual(expandingbutton.clipboard_clear.call_count, 1)
self.assertEqual(expandingbutton.clipboard_append.call_count, 1)
expandingbutton.clipboard_append.assert_called_with('TEXT')
def test_view(self):
"""Test the view event."""
squeezer = self.make_mock_squeezer()
expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
expandingbutton.selection_own = Mock()
with patch('idlelib.squeezer.view_text', autospec=view_text)\
as mock_view_text:
# trigger the view event
expandingbutton.view(event=Mock())
# check that the expanding button called view_text
self.assertEqual(mock_view_text.call_count, 1)
# check that the proper text was passed
self.assertEqual(mock_view_text.call_args[0][2], 'TEXT')
def test_rmenu(self):
"""Test the context menu."""
squeezer = self.make_mock_squeezer()
expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
with patch('tkinter.Menu') as mock_Menu:
mock_menu = Mock()
mock_Menu.return_value = mock_menu
mock_event = Mock()
mock_event.x = 10
mock_event.y = 10
expandingbutton.context_menu_event(event=mock_event)
self.assertEqual(mock_menu.add_command.call_count,
len(expandingbutton.rmenu_specs))
for label, *data in expandingbutton.rmenu_specs:
mock_menu.add_command.assert_any_call(label=label, command=ANY)
if __name__ == '__main__':
unittest.main(verbosity=2)
| 21,861 | 510 | jart/cosmopolitan | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.