desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Destroy the page whose name is given in page_name.'
| def remove_page(self, page_name):
| if (not (page_name in self.pages)):
raise KeyError(("No such TabPage: '%s" % page_name))
self._pages_order.remove(page_name)
if (len(self._pages_order) > 0):
if (page_name == self._default_page):
self._default_page = self._pages_order[0]
else:
self._default_page = None
if (page_name == self._current_page):
self.change_page(self._default_page)
self._tab_set.remove_tab(page_name)
page = self.pages.pop(page_name)
page.frame.destroy()
|
'Show the page whose name is given in page_name.'
| def change_page(self, page_name):
| if (self._current_page == page_name):
return
if ((page_name is not None) and (page_name not in self.pages)):
raise KeyError(("No such TabPage: '%s'" % page_name))
if (self._current_page is not None):
self.pages[self._current_page]._hide()
self._current_page = None
if (page_name is not None):
self._current_page = page_name
self.pages[page_name]._show()
self._tab_set.set_selected_tab(page_name)
|
'cfgFile - string, fully specified configuration file name'
| def __init__(self, cfgFile, cfgDefaults=None):
| self.file = cfgFile
ConfigParser.__init__(self, defaults=cfgDefaults)
|
'Get an option value for given section/option or return default.
If type is specified, return as type.'
| def Get(self, section, option, type=None, default=None, raw=False):
| 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)
|
'Get an option list for given section'
| def GetOptionList(self, section):
| if self.has_section(section):
return self.options(section)
else:
return []
|
'Load the configuration file from disk'
| def Load(self):
| self.read(self.file)
|
'if section doesn\'t exist, add it'
| def AddSection(self, section):
| if (not self.has_section(section)):
self.add_section(section)
|
'remove any sections that have no options'
| def RemoveEmptySections(self):
| for section in self.sections():
if (not self.GetOptionList(section)):
self.remove_section(section)
|
'Remove empty sections and then return 1 if parser has no sections
left, else return 0.'
| def IsEmpty(self):
| self.RemoveEmptySections()
if self.sections():
return 0
else:
return 1
|
'If section/option exists, remove it.
Returns 1 if option was removed, 0 otherwise.'
| def RemoveOption(self, section, option):
| if self.has_section(section):
return self.remove_option(section, option)
|
'Sets option to value, adding section if required.
Returns 1 if option was added or changed, otherwise 0.'
| def SetOption(self, section, option, value):
| if self.has_option(section, option):
if (self.get(section, option) == value):
return 0
else:
self.set(section, option, value)
return 1
else:
if (not self.has_section(section)):
self.add_section(section)
self.set(section, option, value)
return 1
|
'Removes the user config file from disk if it exists.'
| def RemoveFile(self):
| if os.path.exists(self.file):
os.remove(self.file)
|
'Update user configuration file.
Remove empty sections. If resulting config isn\'t empty, write the file
to disk. If config is empty, remove the file from disk if it exists.'
| def Save(self):
| if (not self.IsEmpty()):
fname = self.file
try:
cfgFile = open(fname, 'w')
except IOError:
os.unlink(fname)
cfgFile = open(fname, 'w')
self.write(cfgFile)
else:
self.RemoveFile()
|
'set up a dictionary of config parsers for default and user
configurations respectively'
| def CreateConfigHandlers(self):
| if (__name__ != '__main__'):
idleDir = os.path.dirname(__file__)
else:
idleDir = os.path.abspath(sys.path[0])
userDir = self.GetUserCfgDir()
configTypes = ('main', 'extensions', 'highlight', 'keys')
defCfgFiles = {}
usrCfgFiles = {}
for cfgType in configTypes:
defCfgFiles[cfgType] = os.path.join(idleDir, (('config-' + cfgType) + '.def'))
usrCfgFiles[cfgType] = os.path.join(userDir, (('config-' + cfgType) + '.cfg'))
for cfgType in configTypes:
self.defaultCfg[cfgType] = IdleConfParser(defCfgFiles[cfgType])
self.userCfg[cfgType] = IdleUserConfParser(usrCfgFiles[cfgType])
|
'Creates (if required) and returns a filesystem directory for storing
user config files.'
| def GetUserCfgDir(self):
| cfgDir = '.idlerc'
userDir = os.path.expanduser('~')
if (userDir != '~'):
if (not os.path.exists(userDir)):
warn = (('\n Warning: os.path.expanduser("~") points to\n ' + userDir) + ',\n but the path does not exist.\n')
try:
sys.stderr.write(warn)
except IOError:
pass
userDir = '~'
if (userDir == '~'):
userDir = os.getcwd()
userDir = os.path.join(userDir, cfgDir)
if (not os.path.exists(userDir)):
try:
os.mkdir(userDir)
except (OSError, IOError):
warn = (('\n Warning: unable to create user config directory\n' + userDir) + '\n Check path and permissions.\n Exiting!\n\n')
sys.stderr.write(warn)
raise SystemExit
return userDir
|
'Get an option value for given config type and given general
configuration section/option or return a default. If type is specified,
return as type. Firstly the user configuration is checked, with a
fallback to the default configuration, and a final \'catch all\'
fallback to a useable passed-in default if the option isn\'t present in
either the user or the default configuration.
configType must be one of (\'main\',\'extensions\',\'highlight\',\'keys\')
If a default is returned, and warn_on_default is True, a warning is
printed to stderr.'
| def GetOption(self, configType, section, option, default=None, type=None, warn_on_default=True, raw=False):
| if self.userCfg[configType].has_option(section, option):
return self.userCfg[configType].Get(section, option, type=type, raw=raw)
elif self.defaultCfg[configType].has_option(section, option):
return self.defaultCfg[configType].Get(section, option, type=type, raw=raw)
else:
if warn_on_default:
warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n problem retrieving configuration option %r\n from section %r.\n returning default value: %r\n' % (option, section, default))
try:
sys.stderr.write(warning)
except IOError:
pass
return default
|
'In user\'s config file, set section\'s option to value.'
| def SetOption(self, configType, section, option, value):
| self.userCfg[configType].SetOption(section, option, value)
|
'Get a list of sections from either the user or default config for
the given config type.
configSet must be either \'user\' or \'default\'
configType must be one of (\'main\',\'extensions\',\'highlight\',\'keys\')'
| def GetSectionList(self, configSet, configType):
| if (not (configType in ('main', 'extensions', 'highlight', 'keys'))):
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()
|
'return individual highlighting theme elements.
fgBg - string (\'fg\'or\'bg\') or None, if None return a dictionary
containing fg and bg colours (appropriate for passing to Tkinter in,
e.g., a tag_config call), otherwise fg or bg colour only as specified.'
| def GetHighlight(self, theme, element, fgBg=None):
| 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'):
back = themeDict['normal-background']
else:
back = themeDict[(element + '-background')]
highlight = {'foreground': fore, 'background': back}
if (not fgBg):
return highlight
else:
if (fgBg == 'fg'):
return highlight['foreground']
if (fgBg == 'bg'):
return highlight['background']
else:
raise InvalidFgBg, 'Invalid fgBg specified'
|
'type - string, \'default\' or \'user\' theme type
themeName - string, theme name
Returns a dictionary which holds {option:value} for each element
in the specified theme. Values are loaded over a set of ultimate last
fallback defaults to guarantee that all theme elements are present in
a newly created theme.'
| def GetThemeDict(self, type, themeName):
| if (type == 'user'):
cfgParser = self.userCfg['highlight']
elif (type == 'default'):
cfgParser = self.defaultCfg['highlight']
else:
raise InvalidTheme, 'Invalid theme type specified'
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-foreground': '#000000', 'stdout-foreground': '#000000', 'stdout-background': '#ffffff', 'stderr-foreground': '#000000', 'stderr-background': '#ffffff', 'console-foreground': '#000000', 'console-background': '#ffffff'}
for element in theme.keys():
if (not cfgParser.has_option(themeName, element)):
warning = ('\n Warning: configHandler.py - IdleConf.GetThemeDict -\n problem retrieving theme element %r\n from theme %r.\n returning default value: %r\n' % (element, themeName, theme[element]))
try:
sys.stderr.write(warning)
except IOError:
pass
colour = cfgParser.Get(themeName, element, default=theme[element])
theme[element] = colour
return theme
|
'Returns the name of the currently active theme'
| def CurrentTheme(self):
| return self.GetOption('main', 'Theme', 'name', default='')
|
'Returns the name of the currently active key set'
| def CurrentKeys(self):
| return self.GetOption('main', 'Keys', 'name', default='')
|
'Gets a list of all idle extensions declared in the config files.
active_only - boolean, if true only return active (enabled) extensions'
| def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
| extns = self.RemoveKeyBindNames(self.GetSectionList('default', 'extensions'))
userExtns = self.RemoveKeyBindNames(self.GetSectionList('user', 'extensions'))
for extn in userExtns:
if (extn not in extns):
extns.append(extn)
if active_only:
activeExtns = []
for extn in extns:
if self.GetOption('extensions', extn, 'enable', default=True, type='bool'):
if (editor_only or shell_only):
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
|
'Returns the name of the extension that virtualEvent is bound in, or
None if not bound in any extension.
virtualEvent - string, name of the virtual event to test for, without
the enclosing \'<< >>\''
| def GetExtnNameForEvent(self, virtualEvent):
| extName = None
vEvent = (('<<' + virtualEvent) + '>>')
for extn in self.GetExtensions(active_only=0):
for event in self.GetExtensionKeys(extn).keys():
if (event == vEvent):
extName = extn
return extName
|
'returns a dictionary of the configurable keybindings for a particular
extension,as they exist in the dictionary returned by GetCurrentKeySet;
that is, where previously used bindings are disabled.'
| def GetExtensionKeys(self, extensionName):
| 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
|
'returns a dictionary of the configurable keybindings for a particular
extension, as defined in the configuration files, or an empty dictionary
if no bindings are found'
| def __GetRawExtensionKeys(self, extensionName):
| 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
|
'Returns a dictionary of all the event bindings for a particular
extension. The configurable keybindings are returned as they exist in
the dictionary returned by GetCurrentKeySet; that is, where re-used
keybindings are disabled.'
| def GetExtensionBindings(self, extensionName):
| bindsName = (extensionName + '_bindings')
extBinds = self.GetExtensionKeys(extensionName)
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
|
'returns the keybinding for a specific event.
keySetName - string, name of key binding set
eventStr - string, the virtual event we want the binding for,
represented as a string, eg. \'<<event>>\''
| def GetKeyBinding(self, keySetName, eventStr):
| eventName = eventStr[2:(-2)]
binding = self.GetOption('keys', keySetName, eventName, default='').split()
return binding
|
'Returns a dictionary of: all requested core keybindings, plus the
keybindings for all currently active extensions. If a binding defined
in an extension is already in use, that binding is disabled.'
| def GetKeySet(self, keySetName):
| keySet = self.GetCoreKeys(keySetName)
activeExtns = self.GetExtensions(active_only=1)
for extn in activeExtns:
extKeys = self.__GetRawExtensionKeys(extn)
if extKeys:
for event in extKeys.keys():
if (extKeys[event] in keySet.values()):
extKeys[event] = ''
keySet[event] = extKeys[event]
return keySet
|
'returns true if the virtual event is bound in the core idle keybindings.
virtualEvent - string, name of the virtual event to test for, without
the enclosing \'<< >>\''
| def IsCoreBinding(self, virtualEvent):
| return ((('<<' + virtualEvent) + '>>') in self.GetCoreKeys().keys())
|
'returns the requested set of core keybindings, with fallbacks if
required.
Keybindings loaded 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.'
| def GetCoreKeys(self, keySetName=None):
| 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>']}
if keySetName:
for event in keyBindings.keys():
binding = self.GetKeyBinding(keySetName, event)
if binding:
keyBindings[event] = binding
else:
warning = ('\n Warning: configHandler.py - IdleConf.GetCoreKeys -\n problem retrieving key binding for event %r\n from key set %r.\n returning default value: %r\n' % (event, keySetName, keyBindings[event]))
try:
sys.stderr.write(warning)
except IOError:
pass
return keyBindings
|
'Fetch 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\'.'
| def GetExtraHelpSourceList(self, configSet):
| 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)):
menuItem = ''
helpPath = ''
else:
value = string.split(value, ';')
menuItem = value[0].strip()
helpPath = value[1].strip()
if (menuItem and helpPath):
helpSources.append((menuItem, helpPath, option))
helpSources.sort(key=(lambda x: int(x[2])))
return helpSources
|
'Returns a list of tuples containing the details of all additional help
sources configured, or an empty list if there are none. Tuples are of
the format returned by GetExtraHelpSourceList.'
| def GetAllExtraHelpSourcesList(self):
| allHelpSources = (self.GetExtraHelpSourceList('default') + self.GetExtraHelpSourceList('user'))
return allHelpSources
|
'load all configuration files.'
| def LoadCfgFiles(self):
| for key in self.defaultCfg.keys():
self.defaultCfg[key].Load()
self.userCfg[key].Load()
|
'write all loaded user configuration files back to disk'
| def SaveUserCfgFiles(self):
| for key in self.userCfg.keys():
self.userCfg[key].Save()
|
'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 ColorDelegator.py.'
| def dispatch(self, operation, *args):
| m = self._operations.get(operation)
try:
if m:
return m(*args)
else:
return self.tk.call(((self.orig, operation) + args))
except TclError:
return ''
|
'Happens when the user really wants to open a CallTip, even if a
function call is needed.'
| def force_open_calltip_event(self, event):
| self.open_calltip(True)
|
'Happens when it would be nice to open a CallTip, but not really
necessary, for example after an opening bracket, so function calls
won\'t be made.'
| def try_open_calltip_event(self, event):
| self.open_calltip(False)
|
'If there is already a calltip window, check if it is still needed,
and if so, reload it.'
| def refresh_calltip_event(self, event):
| if (self.calltip and self.calltip.is_active()):
self.open_calltip(False)
|
'Return the argument list and docstring of a function or class
If there is a Python subprocess, get the calltip there. Otherwise,
either fetch_tip() is running in the subprocess itself or it was called
in an IDLE EditorWindow before any script had been run.
The subprocess environment is that of the most recently run script. If
two unrelated modules are being edited some calltips in the current
module may be inoperative if the module was not the last to run.
To find methods, fetch_tip must be fed a fully qualified name.'
| def fetch_tip(self, name):
| try:
rpcclt = self.editwin.flist.pyshell.interp.rpcclt
except:
rpcclt = None
if rpcclt:
return rpcclt.remotecall('exec', 'get_the_calltip', (name,), {})
else:
entity = self.get_entity(name)
return get_arg_text(entity)
|
'Lookup name in a namespace spanning sys.modules and __main.dict__'
| def get_entity(self, name):
| if name:
namespace = sys.modules.copy()
namespace.update(__main__.__dict__)
try:
return eval(name, namespace)
except (NameError, AttributeError):
return None
|
'Clear and rebuild the HelpFiles section in self.changedItems'
| def UpdateUserHelpChangedItems(self):
| self.changedItems['main']['HelpFiles'] = {}
for num in range(1, (len(self.userHelpList) + 1)):
self.AddChangedItem('main', 'HelpFiles', str(num), string.join(self.userHelpList[(num - 1)][:2], ';'))
|
'load configuration from default and user config files and populate
the widgets on the config dialog pages.'
| def LoadConfigs(self):
| self.LoadFontCfg()
self.LoadTabCfg()
self.LoadThemeCfg()
self.LoadKeyCfg()
self.LoadGeneralCfg()
|
'save a newly created core key set.
keySetName - string, the name of the new key set
keySet - dictionary containing the new key set'
| def SaveNewKeySet(self, keySetName, keySet):
| if (not idleConf.userCfg['keys'].has_section(keySetName)):
idleConf.userCfg['keys'].add_section(keySetName)
for event in keySet.keys():
value = keySet[event]
idleConf.userCfg['keys'].SetOption(keySetName, event, value)
|
'save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme'
| def SaveNewTheme(self, themeName, theme):
| if (not idleConf.userCfg['highlight'].has_section(themeName)):
idleConf.userCfg['highlight'].add_section(themeName)
for element in theme.keys():
value = theme[element]
idleConf.userCfg['highlight'].SetOption(themeName, element, value)
|
'Save configuration changes to the user config file.'
| def SaveAllChangedConfigs(self):
| idleConf.userCfg['main'].Save()
for configType in self.changedItems.keys():
cfgTypeHasChanges = False
for section in self.changedItems[configType].keys():
if (section == 'HelpFiles'):
idleConf.userCfg['main'].remove_section('HelpFiles')
cfgTypeHasChanges = True
for item in self.changedItems[configType][section].keys():
value = self.changedItems[configType][section][item]
if self.SetUserValue(configType, section, item, value):
cfgTypeHasChanges = True
if cfgTypeHasChanges:
idleConf.userCfg[configType].Save()
for configType in ['keys', 'highlight']:
idleConf.userCfg[configType].Save()
self.ResetChangedItems()
|
'Dynamically apply configuration changes'
| def ActivateConfigChanges(self):
| winInstances = self.parent.instance_dict.keys()
for instance in winInstances:
instance.ResetColorizer()
instance.ResetFont()
instance.set_notabs_indentwidth()
instance.ApplyKeybindings()
instance.reset_help_menu_entries()
|
'Get menu entry and url/ local file location for Additional Help
User selects a name for the Help resource and provides a web url
or a local file as its source. The user can enter a url or browse
for the file.'
| def __init__(self, parent, title, menuItem='', filePath=''):
| Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol('WM_DELETE_WINDOW', self.Cancel)
self.parent = parent
self.result = None
self.CreateWidgets()
self.menu.set(menuItem)
self.path.set(filePath)
self.withdraw()
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))))))
self.deiconify()
self.bind('<Return>', self.Ok)
self.wait_window()
|
'Simple validity check for a sensible menu item name'
| def MenuOk(self):
| menuOk = True
menu = self.menu.get()
menu.strip()
if (not menu):
tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self)
self.entryMenu.focus_set()
menuOk = False
elif (len(menu) > 30):
tkMessageBox.showerror(title='Menu Item Error', message='Menu item too long:\nLimit 30 characters.', parent=self)
self.entryMenu.focus_set()
menuOk = False
return menuOk
|
'Simple validity check for menu file path'
| def PathOk(self):
| pathOk = True
path = self.path.get()
path.strip()
if (not path):
tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self)
self.entryPath.focus_set()
pathOk = False
elif path.startswith(('www.', 'http')):
pass
else:
if (path[:5] == 'file:'):
path = path[5:]
if (not os.path.exists(path)):
tkMessageBox.showerror(title='File Path Error', message='Help file path does not exist.', parent=self)
self.entryPath.focus_set()
pathOk = False
return pathOk
|
'message - string, informational message to display
usedNames - list, list of names already in use for validity check'
| def __init__(self, parent, title, message, usedNames):
| Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol('WM_DELETE_WINDOW', self.Cancel)
self.parent = parent
self.message = message
self.usedNames = usedNames
self.result = ''
self.CreateWidgets()
self.withdraw()
self.update_idletasks()
self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
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))))))
self.deiconify()
self.wait_window()
|
'Initialize the HyperParser to analyze the surroundings of the given
index.'
| def __init__(self, editwin, index):
| self.editwin = editwin
self.text = text = editwin.text
parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth)
def index2line(index):
return int(float(index))
lno = index2line(text.index(index))
if (not editwin.context_use_ps1):
for context in editwin.num_context_lines:
startat = max((lno - context), 1)
startatindex = (repr(startat) + '.0')
stopatindex = ('%d.end' % lno)
parser.set_str((text.get(startatindex, stopatindex) + ' \n'))
bod = parser.find_good_parse_start(editwin._build_char_in_string_func(startatindex))
if ((bod is not None) or (startat == 1)):
break
parser.set_lo((bod or 0))
else:
r = text.tag_prevrange('console', index)
if r:
startatindex = r[1]
else:
startatindex = '1.0'
stopatindex = ('%d.end' % lno)
parser.set_str((text.get(startatindex, stopatindex) + ' \n'))
parser.set_lo(0)
self.rawtext = parser.str[:(-2)]
self.stopatindex = stopatindex
self.bracketing = parser.get_last_stmt_bracketing()
self.isopener = [((i > 0) and (self.bracketing[i][1] > self.bracketing[(i - 1)][1])) for i in range(len(self.bracketing))]
self.set_index(index)
|
'Set the index to which the functions relate. Note that it must be
in the same statement.'
| def set_index(self, index):
| indexinrawtext = (len(self.rawtext) - len(self.text.get(index, self.stopatindex)))
if (indexinrawtext < 0):
raise ValueError('The index given is before the analyzed statement')
self.indexinrawtext = indexinrawtext
self.indexbracket = 0
while ((self.indexbracket < (len(self.bracketing) - 1)) and (self.bracketing[(self.indexbracket + 1)][0] < self.indexinrawtext)):
self.indexbracket += 1
if ((self.indexbracket < (len(self.bracketing) - 1)) and (self.bracketing[(self.indexbracket + 1)][0] == self.indexinrawtext) and (not self.isopener[(self.indexbracket + 1)])):
self.indexbracket += 1
|
'Is the index given to the HyperParser is in a string?'
| def is_in_string(self):
| return (self.isopener[self.indexbracket] and (self.rawtext[self.bracketing[self.indexbracket][0]] in ('"', "'")))
|
'Is the index given to the HyperParser is in a normal code?'
| def is_in_code(self):
| return ((not self.isopener[self.indexbracket]) or (self.rawtext[self.bracketing[self.indexbracket][0]] not in ('#', '"', "'")))
|
'If the index given to the HyperParser is surrounded by a bracket
defined in openers (or at least has one before it), return the
indices of the opening bracket and the closing bracket (or the
end of line, whichever comes first).
If it is not surrounded by brackets, or the end of line comes before
the closing bracket and mustclose is True, returns None.'
| def get_surrounding_brackets(self, openers='([{', mustclose=False):
| bracketinglevel = self.bracketing[self.indexbracket][1]
before = self.indexbracket
while ((not self.isopener[before]) or (self.rawtext[self.bracketing[before][0]] not in openers) or (self.bracketing[before][1] > bracketinglevel)):
before -= 1
if (before < 0):
return None
bracketinglevel = min(bracketinglevel, self.bracketing[before][1])
after = (self.indexbracket + 1)
while ((after < len(self.bracketing)) and (self.bracketing[after][1] >= bracketinglevel)):
after += 1
beforeindex = self.text.index(('%s-%dc' % (self.stopatindex, (len(self.rawtext) - self.bracketing[before][0]))))
if ((after >= len(self.bracketing)) or (self.bracketing[after][0] > len(self.rawtext))):
if mustclose:
return None
afterindex = self.stopatindex
else:
afterindex = self.text.index(('%s-%dc' % (self.stopatindex, (len(self.rawtext) - (self.bracketing[after][0] - 1)))))
return (beforeindex, afterindex)
|
'Return a string with the Python expression which ends at the given
index, which is empty if there is no real one.'
| def get_expression(self):
| if (not self.is_in_code()):
raise ValueError('get_expression should only be called if index is inside a code.')
rawtext = self.rawtext
bracketing = self.bracketing
brck_index = self.indexbracket
brck_limit = bracketing[brck_index][0]
pos = self.indexinrawtext
last_identifier_pos = pos
postdot_phase = True
while 1:
while 1:
if ((pos > brck_limit) and (rawtext[(pos - 1)] in self._whitespace_chars)):
pos -= 1
elif ((not postdot_phase) and (pos > brck_limit) and (rawtext[(pos - 1)] == '.')):
pos -= 1
postdot_phase = True
elif ((pos == brck_limit) and (brck_index > 0) and (rawtext[bracketing[(brck_index - 1)][0]] == '#')):
brck_index -= 2
brck_limit = bracketing[brck_index][0]
pos = bracketing[(brck_index + 1)][0]
else:
break
if (not postdot_phase):
break
ret = self._eat_identifier(rawtext, brck_limit, pos)
if ret:
pos = (pos - ret)
last_identifier_pos = pos
postdot_phase = False
elif (pos == brck_limit):
level = bracketing[brck_index][1]
while ((brck_index > 0) and (bracketing[(brck_index - 1)][1] > level)):
brck_index -= 1
if (bracketing[brck_index][0] == brck_limit):
break
pos = bracketing[brck_index][0]
brck_index -= 1
brck_limit = bracketing[brck_index][0]
last_identifier_pos = pos
if (rawtext[pos] in '(['):
pass
else:
break
else:
break
return rawtext[last_identifier_pos:self.indexinrawtext]
|
'Save breakpoints when file is saved'
| def store_file_breaks(self):
| breaks = self.breakpoints
filename = self.io.filename
try:
lines = open(self.breakpointPath, 'r').readlines()
except IOError:
lines = []
new_file = open(self.breakpointPath, 'w')
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'))
new_file.close()
|
'Retrieves all the breakpoints in the current window'
| def update_breakpoints(self):
| text = self.text
ranges = text.tag_ranges('BREAK')
linenumber_list = self.ranges_to_linenumbers(ranges)
self.breakpoints = linenumber_list
|
'Extend base method - clear breaks when module is closed'
| def _close(self):
| self.clear_file_breaks()
EditorWindow._close(self)
|
'Override the base class - just re-raise EOFError'
| def handle_EOF(self):
| raise EOFError
|
'UNIX: make sure subprocess is terminated and collect status'
| def unix_terminate(self):
| if hasattr(os, 'kill'):
try:
os.kill(self.rpcpid, SIGTERM)
except OSError:
return
else:
try:
os.waitpid(self.rpcpid, 0)
except OSError:
return
|
'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.'
| def open_remote_stack_viewer(self):
| self.tkconsole.text.after(300, self.remote_stack_viewer)
return
|
'Like runsource() but assumes complete exec source'
| def execsource(self, source):
| filename = self.stuffsource(source)
self.execfile(filename, source)
|
'Execute an existing file'
| def execfile(self, filename, source=None):
| if (source is None):
source = open(filename, 'r').read()
try:
code = compile(source, filename, 'exec')
except (OverflowError, SyntaxError):
self.tkconsole.resetoutput()
tkerr = self.tkconsole.stderr
print >>tkerr, '*** Error in script or command!\n'
print >>tkerr, 'Traceback (most recent call last):'
InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt()
else:
self.runcode(code)
|
'Extend base class method: Stuff the source in the line cache first'
| def runsource(self, source):
| filename = self.stuffsource(source)
self.more = 0
self.save_warnings_filters = warnings.filters[:]
warnings.filterwarnings(action='error', category=SyntaxWarning)
if isinstance(source, types.UnicodeType):
from idlelib import IOBinding
try:
source = source.encode(IOBinding.encoding)
except UnicodeError:
self.tkconsole.resetoutput()
self.write('Unsupported characters in input\n')
return
try:
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
|
'Stuff source in the filename cache'
| def stuffsource(self, source):
| 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
|
'Prepend sys.path with file\'s directory if not already included'
| def prepend_syspath(self, filename):
| self.runcommand(('if 1:\n _filename = %r\n import sys as _sys\n from os.path import dirname as _dirname\n _dir = _dirname(_filename)\n if not _dir in _sys.path:\n _sys.path.insert(0, _dir)\n del _filename, _sys, _dirname, _dir\n \n' % (filename,)))
|
'Extend base class method: Add Colorizing
Color the offending position instead of printing it and pointing at it
with a caret.'
| def showsyntaxerror(self, filename=None):
| text = self.tkconsole.text
stuff = self.unpackerror()
if stuff:
(msg, lineno, offset, line) = stuff
if (lineno == 1):
pos = ('iomark + %d chars' % (offset - 1))
else:
pos = ('iomark linestart + %d lines + %d chars' % ((lineno - 1), (offset - 1)))
text.tag_add('ERROR', pos)
text.see(pos)
char = text.get(pos)
if (char and (char in IDENTCHARS)):
text.tag_add('ERROR', (pos + ' wordstart'), pos)
self.tkconsole.resetoutput()
self.write(('SyntaxError: %s\n' % str(msg)))
else:
self.tkconsole.resetoutput()
InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt()
|
'Extend base class method to reset output properly'
| def showtraceback(self):
| self.tkconsole.resetoutput()
self.checklinecache()
InteractiveInterpreter.showtraceback(self)
if self.tkconsole.getvar('<<toggle-jit-stack-viewer>>'):
self.tkconsole.open_stack_viewer()
|
'Run the code without invoking the debugger'
| def runcommand(self, code):
| if self.tkconsole.executing:
self.display_executing_dialog()
return 0
if self.rpcclt:
self.rpcclt.remotequeue('exec', 'runcode', (code,), {})
else:
exec code in self.locals
return 1
|
'Override base class method'
| def runcode(self, code):
| 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 in self.locals
except SystemExit:
if (not self.tkconsole.closing):
if tkMessageBox.askyesno('Exit?', 'Do you want to exit altogether?', default='yes', master=self.tkconsole.text):
raise
else:
self.showtraceback()
else:
raise
except:
if use_subprocess:
print >>self.tkconsole.stderr, 'IDLE internal error in runcode()'
self.showtraceback()
self.tkconsole.endexecuting()
elif self.tkconsole.canceled:
self.tkconsole.canceled = False
print >>self.tkconsole.stderr, 'KeyboardInterrupt'
else:
self.showtraceback()
finally:
if (not use_subprocess):
try:
self.tkconsole.endexecuting()
except AttributeError:
pass
|
'Override base class method'
| def write(self, s):
| self.tkconsole.stderr.write(s)
|
'Helper for ModifiedInterpreter'
| def beginexecuting(self):
| self.resetoutput()
self.executing = 1
|
'Helper for ModifiedInterpreter'
| def endexecuting(self):
| self.executing = 0
self.canceled = 0
self.showprompt()
|
'Extend EditorWindow.close()'
| def close(self):
| if self.executing:
response = tkMessageBox.askokcancel('Kill?', 'The program is still running!\n Do you want to kill it?', default='ok', parent=self.text)
if (response is False):
return 'cancel'
if self.reading:
self.top.quit()
self.canceled = True
self.closing = True
self.text.after((2 * self.pollinterval), self.close2)
|
'Extend EditorWindow._close(), shut down debugger and execution server'
| def _close(self):
| self.close_debugger()
if use_subprocess:
self.interp.kill_subprocess()
sys.stdout = self.save_stdout
sys.stderr = self.save_stderr
sys.stdin = self.save_stdin
self.interp = None
self.console = None
self.flist.pyshell = None
self.history = None
EditorWindow._close(self)
|
'Override EditorWindow method: never remove the colorizer'
| def ispythonsource(self, filename):
| return True
|
'Override RPCServer method for IDLE
Interrupt the MainThread and exit server if link is dropped.'
| def handle_error(self, request, client_address):
| global quitting
try:
raise
except SystemExit:
raise
except EOFError:
global exit_now
exit_now = True
thread.interrupt_main()
except:
erf = sys.__stderr__
print >>erf, ('\n' + ('-' * 40))
print >>erf, 'Unhandled server exception!'
print >>erf, ('Thread: %s' % threading.currentThread().getName())
print >>erf, 'Client Address: ', client_address
print >>erf, 'Request: ', repr(request)
traceback.print_exc(file=erf)
print >>erf, '\n*** Unrecoverable, server exiting!'
print >>erf, ('-' * 40)
quitting = True
thread.interrupt_main()
|
'Override base method'
| def handle(self):
| executive = Executive(self)
self.register('exec', executive)
sys.stdin = self.console = self.get_remote_proxy('stdin')
sys.stdout = self.get_remote_proxy('stdout')
sys.stderr = self.get_remote_proxy('stderr')
from idlelib import IOBinding
sys.stdin.encoding = sys.stdout.encoding = sys.stderr.encoding = IOBinding.encoding
self.interp = self.get_remote_proxy('interp')
rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
|
'override SocketIO method - wait for MainThread to shut us down'
| def exithook(self):
| time.sleep(10)
|
'Override SocketIO method - terminate wait on callback and exit thread'
| def EOFhook(self):
| global quitting
quitting = True
thread.interrupt_main()
|
'interrupt awakened thread'
| def decode_interrupthook(self):
| global quitting
quitting = True
thread.interrupt_main()
|
'Unregister the Idb Adapter. Link objects and Idb then subject to GC'
| def stop_the_debugger(self, idb_adap_oid):
| self.rpchandler.unregister(idb_adap_oid)
|
'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'
| def SetMenu(self, valueList, value=None):
| 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)
|
'Highlight the single paren that matches'
| def create_tag_default(self, indices):
| self.text.tag_add('paren', indices[0])
self.text.tag_config('paren', self.HILITE_CONFIG)
|
'Highlight the entire expression'
| def create_tag_expression(self, indices):
| if (self.text.get(indices[1]) in (')', ']', '}')):
rightindex = (indices[1] + '+1c')
else:
rightindex = indices[1]
self.text.tag_add('paren', indices[0], rightindex)
self.text.tag_config('paren', self.HILITE_CONFIG)
|
'Highlight will remain until user input turns it off
or the insert has moved'
| def set_timeout_none(self):
| 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)
|
'The last highlight created will be removed after .5 sec'
| def set_timeout_last(self):
| self.counter += 1
self.editwin.text_frame.after(self.FLASH_DELAY, (lambda self=self, c=self.counter: self.handle_restore_timer(c)))
|
'Search a text widget for the pattern.
If prog is given, it should be the precompiled pattern.
Return a tuple (lineno, matchobj); None if not found.
This obeys the wrap and direction (back) settings.
The search starts at the selection (if there is one) or
at the insert mark (otherwise). If the search is forward,
it starts at the right of the selection; for a backward
search, it starts at the left end. An empty match exactly
at either end of the selection (or at the insert mark if
there is no selection) is ignored unless the ok flag is true
-- this is done to guarantee progress.
If the search is allowed to wrap around, it will return the
original selection if (and only if) it is the only match.'
| def search_text(self, text, prog=None, ok=0):
| if (not prog):
prog = self.getprog()
if (not prog):
return None
wrap = self.wrapvar.get()
(first, last) = get_selection(text)
if self.isback():
if ok:
start = last
else:
start = first
(line, col) = get_line_col(start)
res = self.search_backward(text, prog, line, col, wrap, ok)
else:
if ok:
start = first
else:
start = last
(line, col) = get_line_col(start)
res = self.search_forward(text, prog, line, col, wrap, ok)
return res
|
'Do not override! Called by TreeNode.'
| def _IsExpandable(self):
| if (self.expandable is None):
self.expandable = self.IsExpandable()
return self.expandable
|
'Return whether there are subitems.'
| def IsExpandable(self):
| return 1
|
'Do not override! Called by TreeNode.'
| def _GetSubList(self):
| if (not self.IsExpandable()):
return []
sublist = self.GetSubList()
if (not sublist):
self.expandable = 0
return sublist
|
'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'
| def __init__(self, parent, title, action, currentKeySequences):
| Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol('WM_DELETE_WINDOW', self.Cancel)
self.parent = parent
self.action = action
self.currentKeySequences = currentKeySequences
self.result = ''
self.keyString = StringVar(self)
self.keyString.set('')
self.SetModifiersForPlatform()
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.withdraw()
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))))))
self.deiconify()
self.wait_window()
|
'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.'
| def SetModifiersForPlatform(self):
| from idlelib import macosxSupport
if macosxSupport.runningAsOSXApp():
self.modifiers = ['Shift', 'Control', 'Option', 'Command']
else:
self.modifiers = ['Control', 'Alt', 'Shift']
self.modifier_label = {'Control': 'Ctrl'}
|
'Translate from keycap symbol to the Tkinter keysym'
| def TranslateKey(self, key, modifiers):
| 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.keys()):
key = translateDict[key]
if (('Shift' in modifiers) and (key in string.ascii_lowercase)):
key = key.upper()
key = ('Key-' + key)
return key
|
'Validity check on user\'s \'basic\' keybinding selection.
Doesn\'t check the string produced by the advanced dialog because
\'modifiers\' isn\'t set.'
| def KeysOK(self):
| keys = self.keyString.get()
keys.strip()
finalKey = self.listKeysFinal.get(ANCHOR)
modifiers = self.GetModifiers()
keySequence = keys.split()
keysOK = False
title = 'Key Sequence Error'
if (not keys):
tkMessageBox.showerror(title=title, parent=self, message='No keys specified.')
elif (not keys.endswith('>')):
tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key')
elif ((not modifiers) and (finalKey not in (self.functionKeys + self.moveKeys))):
tkMessageBox.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.'
tkMessageBox.showerror(title=title, parent=self, message=msg)
elif (keySequence in self.currentKeySequences):
msg = 'This key combination is already in use.'
tkMessageBox.showerror(title=title, parent=self, message=msg)
else:
keysOK = True
return keysOK
|
'Check if needs to reposition the window, and if so - do it.'
| def position_window(self):
| curline = int(self.widget.index('insert').split('.')[0])
if (curline == self.lastline):
return
self.lastline = curline
self.widget.see('insert')
if (curline == self.parenline):
box = self.widget.bbox(('%d.%d' % (self.parenline, self.parencol)))
else:
box = self.widget.bbox(('%d.0' % curline))
if (not box):
box = list(self.widget.bbox('insert'))
box[0] = 0
box[2] = 0
x = ((box[0] + self.widget.winfo_rootx()) + 2)
y = ((box[1] + box[3]) + self.widget.winfo_rooty())
self.tipwindow.wm_geometry(('+%d+%d' % (x, y)))
|
'Show the calltip, bind events which will close it and reposition it.'
| def showtip(self, text, parenleft, parenright):
| if (len(text) >= 79):
textlines = text.splitlines()
for (i, line) in enumerate(textlines):
if (len(line) > 79):
textlines[i] = (line[:75] + ' ...')
text = '\n'.join(textlines)
self.text = text
if (self.tipwindow or (not self.text)):
return
self.widget.mark_set(MARK_RIGHT, parenright)
(self.parenline, self.parencol) = map(int, self.widget.index(parenleft).split('.'))
self.tipwindow = tw = Toplevel(self.widget)
self.position_window()
tw.wm_overrideredirect(1)
try:
tw.tk.call('::tk::unsupported::MacWindowStyle', 'style', tw._w, 'help', 'noActivates')
except TclError:
pass
self.label = Label(tw, text=self.text, justify=LEFT, background='#ffffe0', relief=SOLID, borderwidth=1, font=self.widget['font'])
self.label.pack()
self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event)
for seq in CHECKHIDE_SEQUENCES:
self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq)
self.widget.after(CHECKHIDE_TIME, self.checkhide_event)
self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
for seq in HIDE_SEQUENCES:
self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
|
'Happens when the user really wants to open a completion list, even
if a function call is needed.'
| def force_open_completions_event(self, event):
| self.open_completions(True, False, True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.