Kaydet (Commit) 57cd21fd authored tarafından Guido van Rossum's avatar Guido van Rossum

Checking in IDLEFORK exactly as it appears in the idlefork CVS.

On a branch, for now.
üst 19691360
This diff is collapsed.
IDLEfork Credits
==================
Guido van Rossum, as well as being the creator of the Python language, is
the original creator of IDLE. He also developed the RPC code and Remote
Debugger extension used in IDLEfork.
The IDLEfork project was initiated and brought up to version 0.7.1 primarily
by David Scherer, with help from Peter Schneider-Kamp and Nicholas Riley.
Bruce Sherwood has contributed considerable time testing and suggesting
improvements.
Besides Guido, the main developers who have been active on IDLEfork version
0.8.1 and later are Stephen M. Gava, who implemented the Configuration GUI, the
new configuration system, and the new About menu, and Kurt B. Kaiser, who
completed the integration of the RPC and remote debugger, and made a number of
usability enhancements.
Other contributors include Raymond Hettinger, Tony Lownds (Mac integration),
Neal Norwitz (code check and clean-up), and Chui Tey (RPC integration, debugger
integration and persistent breakpoints).
Hernan Foffani, Christos Georgiou, Jason Orendorff, Josh Robb, and Bruce
Sherwood have submitted useful patches. Thanks, guys!
There are others who should be included here, especially those who contributed
to IDLE versions prior to 0.8, principally Mark Hammond, Jeremy Hylton,
Tim Peters, and Moshe Zadka. For additional details refer to NEWS.txt and
Changelog.
Please contact the IDLEfork maintainer to have yourself included here if you
are one of those we missed!
Contact details at http://idlefork.sourceforge.net
from repr import Repr
from Tkinter import *
class FrameViewer:
def __init__(self, root, frame):
self.root = root
self.frame = frame
self.top = Toplevel(self.root)
self.repr = Repr()
self.repr.maxstring = 60
self.load_variables()
def load_variables(self):
row = 0
if self.frame.f_locals is not self.frame.f_globals:
l = Label(self.top, text="Local Variables",
borderwidth=2, relief="raised")
l.grid(row=row, column=0, columnspan=2, sticky="ew")
row = self.load_names(self.frame.f_locals, row+1)
l = Label(self.top, text="Global Variables",
borderwidth=2, relief="raised")
l.grid(row=row, column=0, columnspan=2, sticky="ew")
row = self.load_names(self.frame.f_globals, row+1)
def load_names(self, dict, row):
names = dict.keys()
names.sort()
for name in names:
value = dict[name]
svalue = self.repr.repr(value)
l = Label(self.top, text=name)
l.grid(row=row, column=0, sticky="w")
l = Entry(self.top, width=60, borderwidth=0)
l.insert(0, svalue)
l.grid(row=row, column=1, sticky="w")
row = row+1
return row
IDLE History
============
This file contains the release messages for previous IDLE releases.
As you read on you go back to the dark ages of IDLE's history.
IDLE 0.5 - February 2000 - Release Notes
----------------------------------------
This is an early release of IDLE, my own attempt at a Tkinter-based
IDE for Python.
(For a more detailed change log, see the file ChangeLog.)
FEATURES
IDLE has the following features:
- coded in 100% pure Python, using the Tkinter GUI toolkit (i.e. Tcl/Tk)
- cross-platform: works on Windows and Unix (on the Mac, there are
currently problems with Tcl/Tk)
- multi-window text editor with multiple undo, Python colorizing
and many other features, e.g. smart indent and call tips
- Python shell window (a.k.a. interactive interpreter)
- debugger (not complete, but you can set breakpoints, view and step)
USAGE
The main program is in the file "idle.py"; on Unix, you should be able
to run it by typing "./idle.py" to your shell. On Windows, you can
run it by double-clicking it; you can use idle.pyw to avoid popping up
a DOS console. If you want to pass command line arguments on Windows,
use the batch file idle.bat.
Command line arguments: files passed on the command line are executed,
not opened for editing, unless you give the -e command line option.
Try "./idle.py -h" to see other command line options.
IDLE requires Python 1.5.2, so it is currently only usable with a
Python 1.5.2 distribution. (An older version of IDLE is distributed
with Python 1.5.2; you can drop this version on top of it.)
COPYRIGHT
IDLE is covered by the standard Python copyright notice
(http://www.python.org/doc/Copyright.html).
New in IDLE 0.5 (2/15/2000)
---------------------------
Tons of stuff, much of it contributed by Tim Peters and Mark Hammond:
- Status bar, displaying current line/column (Moshe Zadka).
- Better stack viewer, using tree widget. (XXX Only used by Stack
Viewer menu, not by the debugger.)
- Format paragraph now recognizes Python block comments and reformats
them correctly (MH)
- New version of pyclbr.py parses top-level functions and understands
much more of Python's syntax; this is reflected in the class and path
browsers (TP)
- Much better auto-indent; knows how to indent the insides of
multi-line statements (TP)
- Call tip window pops up when you type the name of a known function
followed by an open parenthesis. Hit ESC or click elsewhere in the
window to close the tip window (MH)
- Comment out region now inserts ## to make it stand out more (TP)
- New path and class browsers based on a tree widget that looks
familiar to Windows users
- Reworked script running commands to be more intuitive: I/O now
always goes to the *Python Shell* window, and raw_input() works
correctly. You use F5 to import/reload a module: this adds the module
name to the __main__ namespace. You use Control-F5 to run a script:
this runs the script *in* the __main__ namespace. The latter also
sets sys.argv[] to the script name
New in IDLE 0.4 (4/7/99)
------------------------
Most important change: a new menu entry "File -> Path browser", shows
a 4-column hierarchical browser which lets you browse sys.path,
directories, modules, and classes. Yes, it's a superset of the Class
browser menu entry. There's also a new internal module,
MultiScrolledLists.py, which provides the framework for this dialog.
New in IDLE 0.3 (2/17/99)
-------------------------
Most important changes:
- Enabled support for running a module, with or without the debugger.
Output goes to a new window. Pressing F5 in a module is effectively a
reload of that module; Control-F5 loads it under the debugger.
- Re-enable tearing off the Windows menu, and make a torn-off Windows
menu update itself whenever a window is opened or closed.
- Menu items can now be have a checkbox (when the menu label starts
with "!"); use this for the Debugger and "Auto-open stack viewer"
(was: JIT stack viewer) menu items.
- Added a Quit button to the Debugger API.
- The current directory is explicitly inserted into sys.path.
- Fix the debugger (when using Python 1.5.2b2) to use canonical
filenames for breakpoints, so these actually work. (There's still a
lot of work to be done to the management of breakpoints in the
debugger though.)
- Closing a window that is still colorizing now actually works.
- Allow dragging of the separator between the two list boxes in the
class browser.
- Bind ESC to "close window" of the debugger, stack viewer and class
browser. It removes the selection highlighting in regular text
windows. (These are standard Windows conventions.)
New in IDLE 0.2 (1/8/99)
------------------------
Lots of changes; here are the highlights:
General:
- You can now write and configure your own IDLE extension modules; see
extend.txt.
File menu:
The command to open the Python shell window is now in the File menu.
Edit menu:
New Find dialog with more options; replace dialog; find in files dialog.
Commands to tabify or untabify a region.
Command to format a paragraph.
Debug menu:
JIT (Just-In-Time) stack viewer toggle -- if set, the stack viewer
automaticall pops up when you get a traceback.
Windows menu:
Zoom height -- make the window full height.
Help menu:
The help text now show up in a regular window so you can search and
even edit it if you like.
IDLE 0.1 was distributed with the Python 1.5.2b1 release on 12/22/98.
======================================================================
IDLEfork Installation Notes
===========================
IDLEfork requires Python Version 2.2 or later.
There are several distribution files (where xx is the subversion):
IDLEfork-0.9xx.win32.exe
This is a Windows installer which will install IDLEfork in
..../site-packages/idleforklib/ and place the idefork startup script
at ..../scripts/idlefork. Rename this to idlefork.pyw and
point your launcher icons at it. Installation is as idlefork
to avoid conflict with the original Python IDLE.
IDLEfork-0.9xx-1.noarch.rpm
This is an rpm which is designed to install as idleforklib in an
existing /usr/lib/python2.2 tree. It installs as idlefork to avoid
conflict with Python IDLE.
Python rpms are available at http://www.python.org/2.2.2/rpms.html and
http://www.python.org/2.2.1/rpms.html.
IDLEfork-0.9xx.tar.gz
This is a distutils sdist (source) tarfile which can be used to make
installations on platforms not supported by the above files.
** It remains configured to install as idlelib, not idleforklib. **
Unpack in ..../Tools/, cd to the IDLEfork directory created, and
"python setup.py install" to install in ....site-packages/idlelib.
This will overwrite the Python IDLE installation.
If you don't want to overwrite Python IDLE, it is also possible to
simply call "python idle.py" to run from the IDLEfork source directory
without making an installation. In this case, IDLE will not be on
your PATH unless you are in the source directory. Also, it is then
advisable to remove any Python IDLE installation by removing
..../site-packages/idlelib so the two identically named packages don't
conflict.
On Redhat Linux systems prior to 8.0, /usr/bin/python may be pointing
at python1.5. If so, change the first line in the /usr/bin/idle
script to read:
!# /usr/bin/python2.2
See README.txt for more details on this version of IDLEfork.
"""Provides access to configuration information"""
import os
import sys
from ConfigParser import ConfigParser, NoOptionError, NoSectionError
class IdleConfParser(ConfigParser):
# these conf sections do not define extensions!
builtin_sections = {}
for section in ('EditorWindow', 'Colors'):
builtin_sections[section] = section
def getcolor(self, sec, name):
"""Return a dictionary with foreground and background colors
The return value is appropriate for passing to Tkinter in, e.g.,
a tag_config call.
"""
fore = self.getdef(sec, name + "-foreground")
back = self.getdef(sec, name + "-background")
return {"foreground": fore,
"background": back}
def getdef(self, sec, options, raw=0, vars=None, default=None):
"""Get an option value for given section or return default"""
try:
return self.get(sec, options, raw, vars)
except (NoSectionError, NoOptionError):
return default
def getsection(self, section):
"""Return a SectionConfigParser object"""
return SectionConfigParser(section, self)
def getextensions(self):
exts = []
for sec in self.sections():
if self.builtin_sections.has_key(sec):
continue
# enable is a bool, but it may not be defined
if self.getdef(sec, 'enable') != '0':
exts.append(sec)
return exts
def reload(self):
global idleconf
idleconf = IdleConfParser()
load(_dir) # _dir is a global holding the last directory loaded
class SectionConfigParser:
"""A ConfigParser object specialized for one section
This class has all the get methods that a regular ConfigParser does,
but without requiring a section argument.
"""
def __init__(self, section, config):
self.section = section
self.config = config
def options(self):
return self.config.options(self.section)
def get(self, options, raw=0, vars=None):
return self.config.get(self.section, options, raw, vars)
def getdef(self, options, raw=0, vars=None, default=None):
return self.config.getdef(self.section, options, raw, vars, default)
def getint(self, option):
return self.config.getint(self.section, option)
def getfloat(self, option):
return self.config.getint(self.section, option)
def getboolean(self, option):
return self.config.getint(self.section, option)
def getcolor(self, option):
return self.config.getcolor(self.section, option)
def load(dir):
"""Load IDLE configuration files based on IDLE install in dir
Attempts to load two config files:
dir/config.txt
dir/config-[win/mac/unix].txt
dir/config-%(sys.platform)s.txt
~/.idle
"""
global _dir
_dir = dir
if sys.platform[:3] == 'win':
genplatfile = os.path.join(dir, "config-win.txt")
# XXX don't know what the platform string is on a Mac
elif sys.platform[:3] == 'mac':
genplatfile = os.path.join(dir, "config-mac.txt")
else:
genplatfile = os.path.join(dir, "config-unix.txt")
platfile = os.path.join(dir, "config-%s.txt" % sys.platform)
try:
homedir = os.environ['HOME']
except KeyError:
homedir = os.getcwd()
idleconf.read((os.path.join(dir, "config.txt"), genplatfile, platfile,
os.path.join(homedir, ".idle")))
idleconf = IdleConfParser()
load(os.path.dirname(__file__))
To apply this license to IDLE or IDLEfork, read 'IDLE' or 'IDLEfork'
for every occurence of 'Python 2.1.1' in the text below.
PSF LICENSE AGREEMENT
---------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 2.1.1 software in source or binary form and its
associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 2.1.1
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
2001 Python Software Foundation; All Rights Reserved" are retained in
Python 2.1.1 alone or in any derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.1.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.1.1.
4. PSF is making Python 2.1.1 available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.1.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.1.1, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
# Makefile to build the interrupt module, which is a C extension
PYTHON=python2.3
all: interrupt.so
interrupt.so: interruptmodule.c
$(PYTHON) setup.py build_ext -i
# One or more ScrolledLists with HSeparators between them.
# There is a hierarchical relationship between them:
# the right list displays the substructure of the selected item
# in the left list.
from Tkinter import *
from WindowList import ListedToplevel
from Separator import HSeparator
from ScrolledList import ScrolledList
class MultiScrolledLists:
def __init__(self, root, nlists=2):
assert nlists >= 1
self.root = root
self.nlists = nlists
self.path = []
# create top
self.top = top = ListedToplevel(root)
top.protocol("WM_DELETE_WINDOW", self.close)
top.bind("<Escape>", self.close)
self.settitle()
# create frames and separators in between
self.frames = []
self.separators = []
last = top
for i in range(nlists-1):
sepa = HSeparator(last)
self.separators.append(sepa)
frame, last = sepa.parts()
self.frames.append(frame)
self.frames.append(last)
# create labels and lists
self.labels = []
self.lists = []
for i in range(nlists):
frame = self.frames[i]
label = Label(frame, text=self.subtitle(i),
relief="groove", borderwidth=2)
label.pack(fill="x")
self.labels.append(label)
list = ScrolledList(frame, width=self.width(i),
height=self.height(i))
self.lists.append(list)
list.on_select = \
lambda index, i=i, self=self: self.on_select(index, i)
list.on_double = \
lambda index, i=i, self=self: self.on_double(index, i)
# fill leftmost list (rest get filled on demand)
self.fill(0)
# XXX one after_idle isn't enough; two are...
top.after_idle(self.call_pack_propagate_1)
def call_pack_propagate_1(self):
self.top.after_idle(self.call_pack_propagate)
def call_pack_propagate(self):
for frame in self.frames:
frame.pack_propagate(0)
def close(self, event=None):
self.top.destroy()
def settitle(self):
short = self.shorttitle()
long = self.longtitle()
if short and long:
title = short + " - " + long
elif short:
title = short
elif long:
title = long
else:
title = "Untitled"
icon = short or long or title
self.top.wm_title(title)
self.top.wm_iconname(icon)
def longtitle(self):
# override this
return "Multi Scrolled Lists"
def shorttitle(self):
# override this
return None
def width(self, i):
# override this
return 20
def height(self, i):
# override this
return 10
def subtitle(self, i):
# override this
return "Column %d" % i
def fill(self, i):
for k in range(i, self.nlists):
self.lists[k].clear()
self.labels[k].configure(text=self.subtitle(k))
list = self.lists[i]
l = self.items(i)
for s in l:
list.append(s)
def on_select(self, index, i):
item = self.lists[i].get(index)
del self.path[i:]
self.path.append(item)
if i+1 < self.nlists:
self.fill(i+1)
def items(self, i):
# override this
l = []
for k in range(10):
s = str(k)
if i > 0:
s = self.path[i-1] + "." + s
l.append(s)
return l
def on_double(self, index, i):
pass
def main():
root = Tk()
quit = Button(root, text="Exit", command=root.destroy)
quit.pack()
MultiScrolledLists(root, 4)
root.mainloop()
if __name__ == "__main__":
main()
import sys
import os
from Tkinter import *
import linecache
from repr import Repr
from WindowList import ListedToplevel
from ScrolledList import ScrolledList
class StackBrowser:
def __init__(self, root, flist, stack=None):
self.top = top = ListedToplevel(root)
top.protocol("WM_DELETE_WINDOW", self.close)
top.bind("<Key-Escape>", self.close)
top.wm_title("Stack viewer")
top.wm_iconname("Stack")
# Create help label
self.helplabel = Label(top,
text="Click once to view variables; twice for source",
borderwidth=2, relief="groove")
self.helplabel.pack(fill="x")
#
self.sv = StackViewer(top, flist, self)
if stack is None:
stack = get_stack()
self.sv.load_stack(stack)
def close(self, event=None):
self.top.destroy()
localsframe = None
localsviewer = None
localsdict = None
globalsframe = None
globalsviewer = None
globalsdict = None
curframe = None
def show_frame(self, (frame, lineno)):
if frame is self.curframe:
return
self.curframe = None
if frame.f_globals is not self.globalsdict:
self.show_globals(frame)
self.show_locals(frame)
self.curframe = frame
def show_globals(self, frame):
title = "Global Variables"
if frame.f_globals.has_key("__name__"):
try:
name = str(frame.f_globals["__name__"]) + ""
except:
name = ""
if name:
title = title + " in module " + name
self.globalsdict = None
if self.globalsviewer:
self.globalsviewer.close()
self.globalsviewer = None
if not self.globalsframe:
self.globalsframe = Frame(self.top)
self.globalsdict = frame.f_globals
self.globalsviewer = NamespaceViewer(
self.globalsframe,
title,
self.globalsdict)
self.globalsframe.pack(fill="both", side="bottom")
def show_locals(self, frame):
self.localsdict = None
if self.localsviewer:
self.localsviewer.close()
self.localsviewer = None
if frame.f_locals is not frame.f_globals:
title = "Local Variables"
code = frame.f_code
funcname = code.co_name
if funcname not in ("?", "", None):
title = title + " in " + funcname
if not self.localsframe:
self.localsframe = Frame(self.top)
self.localsdict = frame.f_locals
self.localsviewer = NamespaceViewer(
self.localsframe,
title,
self.localsdict)
self.localsframe.pack(fill="both", side="top")
else:
if self.localsframe:
self.localsframe.forget()
class StackViewer(ScrolledList):
def __init__(self, master, flist, browser):
ScrolledList.__init__(self, master, width=80)
self.flist = flist
self.browser = browser
self.stack = []
def load_stack(self, stack, index=None):
self.stack = stack
self.clear()
## if len(stack) > 10:
## l["height"] = 10
## self.topframe.pack(expand=1)
## else:
## l["height"] = len(stack)
## self.topframe.pack(expand=0)
for i in range(len(stack)):
frame, lineno = stack[i]
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)
if i == index:
item = "> " + item
self.append(item)
if index is not None:
self.select(index)
def popup_event(self, event):
if self.stack:
return ScrolledList.popup_event(self, event)
def fill_menu(self):
menu = self.menu
menu.add_command(label="Go to source line",
command=self.goto_source_line)
menu.add_command(label="Show stack frame",
command=self.show_stack_frame)
def on_select(self, index):
if 0 <= index < len(self.stack):
self.browser.show_frame(self.stack[index])
def on_double(self, index):
self.show_source(index)
def goto_source_line(self):
index = self.listbox.index("active")
self.show_source(index)
def show_stack_frame(self):
index = self.listbox.index("active")
if 0 <= index < len(self.stack):
self.browser.show_frame(self.stack[index])
def show_source(self, index):
if not (0 <= index < len(self.stack)):
return
frame, lineno = self.stack[index]
code = frame.f_code
filename = code.co_filename
if os.path.isfile(filename):
edit = self.flist.open(filename)
if edit:
edit.gotoline(lineno)
def get_stack(t=None, f=None):
if t is None:
t = sys.last_traceback
stack = []
if t and t.tb_frame is f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
if f is self.botframe:
break
f = f.f_back
stack.reverse()
while t is not None:
stack.append((t.tb_frame, t.tb_lineno))
t = t.tb_next
return stack
def getexception(type=None, value=None):
if type is None:
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
class NamespaceViewer:
def __init__(self, master, title, dict=None):
width = 0
height = 40
if dict:
height = 20*len(dict) # XXX 20 == observed height of Entry widget
self.master = master
self.title = title
self.repr = Repr()
self.repr.maxstring = 60
self.repr.maxother = 60
self.frame = frame = Frame(master)
self.frame.pack(expand=1, fill="both")
self.label = Label(frame, text=title, borderwidth=2, relief="groove")
self.label.pack(fill="x")
self.vbar = vbar = Scrollbar(frame, name="vbar")
vbar.pack(side="right", fill="y")
self.canvas = canvas = Canvas(frame,
height=min(300, max(40, height)),
scrollregion=(0, 0, width, height))
canvas.pack(side="left", fill="both", expand=1)
vbar["command"] = canvas.yview
canvas["yscrollcommand"] = vbar.set
self.subframe = subframe = Frame(canvas)
self.sfid = canvas.create_window(0, 0, window=subframe, anchor="nw")
self.load_dict(dict)
dict = -1
def load_dict(self, dict, force=0):
if dict is self.dict and not force:
return
subframe = self.subframe
frame = self.frame
for c in subframe.children.values():
c.destroy()
self.dict = None
if not dict:
l = Label(subframe, text="None")
l.grid(row=0, column=0)
else:
names = dict.keys()
names.sort()
row = 0
for name in names:
value = dict[name]
svalue = self.repr.repr(value) # repr(value)
l = Label(subframe, text=name)
l.grid(row=row, column=0, sticky="nw")
## l = Label(subframe, text=svalue, justify="l", wraplength=300)
l = Entry(subframe, width=0, borderwidth=0)
l.insert(0, svalue)
## l["state"] = "disabled"
l.grid(row=row, column=1, sticky="nw")
row = row+1
self.dict = dict
# XXX Could we use a <Configure> callback for the following?
subframe.update_idletasks() # Alas!
width = subframe.winfo_reqwidth()
height = subframe.winfo_reqheight()
canvas = self.canvas
self.canvas["scrollregion"] = (0, 0, width, height)
if height > 300:
canvas["height"] = 300
frame.pack(expand=1)
else:
canvas["height"] = height
frame.pack(expand=0)
def close(self):
self.frame.destroy()
This diff is collapsed.
import select
import socket
import struct
import sys
import types
VERBOSE = None
class SocketProtocol:
"""A simple protocol for sending strings across a socket"""
BUF_SIZE = 8192
def __init__(self, sock):
self.sock = sock
self._buffer = ''
self._closed = 0
def close(self):
self._closed = 1
self.sock.close()
def send(self, buf):
"""Encode buf and write it on the socket"""
if VERBOSE:
VERBOSE.write('send %d:%s\n' % (len(buf), `buf`))
self.sock.send('%d:%s' % (len(buf), buf))
def receive(self, timeout=0):
"""Get next complete string from socket or return None
Raise EOFError on EOF
"""
buf = self._read_from_buffer()
if buf is not None:
return buf
recvbuf = self._read_from_socket(timeout)
if recvbuf is None:
return None
if recvbuf == '' and self._buffer == '':
raise EOFError
if VERBOSE:
VERBOSE.write('recv %s\n' % `recvbuf`)
self._buffer = self._buffer + recvbuf
r = self._read_from_buffer()
return r
def _read_from_socket(self, timeout):
"""Does not block"""
if self._closed:
return ''
if timeout is not None:
r, w, x = select.select([self.sock], [], [], timeout)
if timeout is None or r:
return self.sock.recv(self.BUF_SIZE)
else:
return None
def _read_from_buffer(self):
buf = self._buffer
i = buf.find(':')
if i == -1:
return None
buflen = int(buf[:i])
enclen = i + 1 + buflen
if len(buf) >= enclen:
s = buf[i+1:enclen]
self._buffer = buf[enclen:]
return s
else:
self._buffer = buf
return None
# helpers for registerHandler method below
def get_methods(obj):
methods = []
for name in dir(obj):
attr = getattr(obj, name)
if callable(attr):
methods.append(name)
if type(obj) == types.InstanceType:
methods = methods + get_methods(obj.__class__)
if type(obj) == types.ClassType:
for super in obj.__bases__:
methods = methods + get_methods(super)
return methods
class CommandProtocol:
def __init__(self, sockp):
self.sockp = sockp
self.seqno = 0
self.handlers = {}
def close(self):
self.sockp.close()
self.handlers.clear()
def registerHandler(self, handler):
"""A Handler is an object with handle_XXX methods"""
for methname in get_methods(handler):
if methname[:7] == "handle_":
name = methname[7:]
self.handlers[name] = getattr(handler, methname)
def send(self, cmd, arg='', seqno=None):
if arg:
msg = "%s %s" % (cmd, arg)
else:
msg = cmd
if seqno is None:
seqno = self.get_seqno()
msgbuf = self.encode_seqno(seqno) + msg
self.sockp.send(msgbuf)
if cmd == "reply":
return
reply = self.sockp.receive(timeout=None)
r_cmd, r_arg, r_seqno = self._decode_msg(reply)
assert r_seqno == seqno and r_cmd == "reply", "bad reply"
return r_arg
def _decode_msg(self, msg):
seqno = self.decode_seqno(msg[:self.SEQNO_ENC_LEN])
msg = msg[self.SEQNO_ENC_LEN:]
parts = msg.split(" ", 2)
if len(parts) == 1:
cmd = msg
arg = ''
else:
cmd = parts[0]
arg = parts[1]
return cmd, arg, seqno
def dispatch(self):
msg = self.sockp.receive()
if msg is None:
return
cmd, arg, seqno = self._decode_msg(msg)
self._current_reply = seqno
h = self.handlers.get(cmd, self.default_handler)
try:
r = h(arg)
except TypeError, msg:
raise TypeError, "handle_%s: %s" % (cmd, msg)
if self._current_reply is None:
if r is not None:
sys.stderr.write("ignoring %s return value type %s\n" % \
(cmd, type(r).__name__))
return
if r is None:
r = ''
if type(r) != types.StringType:
raise ValueError, "invalid return type for %s" % cmd
self.send("reply", r, seqno=seqno)
def reply(self, arg=''):
"""Send a reply immediately
otherwise reply will be sent when handler returns
"""
self.send("reply", arg, self._current_reply)
self._current_reply = None
def default_handler(self, arg):
sys.stderr.write("WARNING: unhandled message %s\n" % arg)
return ''
SEQNO_ENC_LEN = 4
def get_seqno(self):
seqno = self.seqno
self.seqno = seqno + 1
return seqno
def encode_seqno(self, seqno):
return struct.pack("I", seqno)
def decode_seqno(self, buf):
return struct.unpack("I", buf)[0]
class StdioRedirector:
"""Redirect sys.std{in,out,err} to a set of file-like objects"""
def __init__(self, stdin, stdout, stderr):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
def redirect(self):
self.save()
sys.stdin = self.stdin
sys.stdout = self.stdout
sys.stderr = self.stderr
def save(self):
self._stdin = sys.stdin
self._stdout = sys.stdout
self._stderr = sys.stderr
def restore(self):
sys.stdin = self._stdin
sys.stdout = self._stdout
sys.stderr = self._stderr
class IOWrapper:
"""Send output from a file-like object across a SocketProtocol
XXX Should this be more tightly integrated with the CommandProtocol?
"""
def __init__(self, name, cmdp):
self.name = name
self.cmdp = cmdp
self.buffer = []
class InputWrapper(IOWrapper):
def write(self, buf):
# XXX what should this do on Windows?
raise IOError, (9, '[Errno 9] Bad file descriptor')
def read(self, arg=None):
if arg is not None:
if arg <= 0:
return ''
else:
arg = 0
return self.cmdp.send(self.name, "read,%s" % arg)
def readline(self):
return self.cmdp.send(self.name, "readline")
class OutputWrapper(IOWrapper):
def write(self, buf):
self.cmdp.send(self.name, buf)
def read(self, arg=None):
return ''
class RemoteInterp:
def __init__(self, sock):
self._sock = SocketProtocol(sock)
self._cmd = CommandProtocol(self._sock)
self._cmd.registerHandler(self)
def run(self):
try:
while 1:
self._cmd.dispatch()
except EOFError:
pass
def handle_execfile(self, arg):
self._cmd.reply()
io = StdioRedirector(InputWrapper("stdin", self._cmd),
OutputWrapper("stdout", self._cmd),
OutputWrapper("stderr", self._cmd))
io.redirect()
execfile(arg, {'__name__':'__main__'})
io.restore()
self._cmd.send("terminated")
def handle_quit(self, arg):
self._cmd.reply()
self._cmd.close()
def startRemoteInterp(id):
import os
# UNIX domain sockets are simpler for starters
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind("/var/tmp/ri.%s" % id)
try:
sock.listen(1)
cli, addr = sock.accept()
rinterp = RemoteInterp(cli)
rinterp.run()
finally:
os.unlink("/var/tmp/ri.%s" % id)
class RIClient:
"""Client of the remote interpreter"""
def __init__(self, sock):
self._sock = SocketProtocol(sock)
self._cmd = CommandProtocol(self._sock)
self._cmd.registerHandler(self)
def execfile(self, file):
self._cmd.send("execfile", file)
def run(self):
try:
while 1:
self._cmd.dispatch()
except EOFError:
pass
def handle_stdout(self, buf):
sys.stdout.write(buf)
## sys.stdout.flush()
def handle_stderr(self, buf):
sys.stderr.write(buf)
def handle_stdin(self, arg):
if arg == "readline":
return sys.stdin.readline()
i = arg.find(",") + 1
bytes = int(arg[i:])
if bytes == 0:
return sys.stdin.read()
else:
return sys.stdin.read(bytes)
def handle_terminated(self, arg):
self._cmd.reply()
self._cmd.send("quit")
self._cmd.close()
def riExec(id, file):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect("/var/tmp/ri.%s" % id)
cli = RIClient(sock)
cli.execfile(file)
cli.run()
if __name__ == "__main__":
import getopt
SERVER = 1
opts, args = getopt.getopt(sys.argv[1:], 'cv')
for o, v in opts:
if o == '-c':
SERVER = 0
elif o == '-v':
VERBOSE = sys.stderr
id = args[0]
if SERVER:
startRemoteInterp(id)
else:
file = args[1]
riExec(id, file)
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):
list = self.__item._GetSubList()
return map(remote_object_tree_item, 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):
list = self.sockio.remotecall(self.oid, "_GetSubList", (), {})
return [StubObjectTreeItem(self.sockio, oid) for oid in list]
import tkSimpleDialog
###$ event <<find>>
###$ win <Control-f>
###$ unix <Control-u><Control-u><Control-s>
###$ event <<find-again>>
###$ win <Control-g>
###$ win <F3>
###$ unix <Control-u><Control-s>
###$ event <<find-selection>>
###$ win <Control-F3>
###$ unix <Control-s>
###$ event <<find-in-files>>
###$ win <Alt-F3>
###$ event <<replace>>
###$ win <Control-h>
###$ event <<goto-line>>
###$ win <Alt-g>
###$ unix <Alt-g>
class SearchBinding:
windows_keydefs = {
'<<find-again>>': ['<Control-g>', '<F3>'],
'<<find-in-files>>': ['<Alt-F3>'],
'<<find-selection>>': ['<Control-F3>'],
'<<find>>': ['<Control-f>'],
'<<replace>>': ['<Control-h>'],
'<<goto-line>>': ['<Alt-g>'],
}
unix_keydefs = {
'<<find-again>>': ['<Control-u><Control-s>'],
'<<find-in-files>>': ['<Alt-s>', '<Meta-s>'],
'<<find-selection>>': ['<Control-s>'],
'<<find>>': ['<Control-u><Control-u><Control-s>'],
'<<replace>>': ['<Control-r>'],
'<<goto-line>>': ['<Alt-g>', '<Meta-g>'],
}
menudefs = [
('edit', [
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>>'),
]),
]
def __init__(self, editwin):
self.editwin = editwin
def find_event(self, event):
import SearchDialog
SearchDialog.find(self.editwin.text)
return "break"
def find_again_event(self, event):
import SearchDialog
SearchDialog.find_again(self.editwin.text)
return "break"
def find_selection_event(self, event):
import SearchDialog
SearchDialog.find_selection(self.editwin.text)
return "break"
def find_in_files_event(self, event):
import GrepDialog
GrepDialog.grep(self.editwin.text, self.editwin.io, self.editwin.flist)
return "break"
def replace_event(self, event):
import ReplaceDialog
ReplaceDialog.replace(self.editwin.text)
return "break"
def goto_line_event(self, event):
text = self.editwin.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")
from Tkinter import *
class Separator:
def __init__(self, master, orient, min=10, thickness=5, bg=None):
self.min = max(1, min)
self.thickness = max(1, thickness)
if orient in ("h", "horizontal"):
self.side = "left"
self.dim = "width"
self.dir = "x"
self.cursor = "sb_h_double_arrow"
elif orient in ("v", "vertical"):
self.side = "top"
self.dim = "height"
self.dir = "y"
self.cursor = "sb_v_double_arrow"
else:
raise ValueError, "Separator: orient should be h or v"
self.winfo_dim = "winfo_" + self.dim
self.master = master = Frame(master)
master.pack(expand=1, fill="both")
self.f1 = Frame(master)
self.f1.pack(expand=1, fill="both", side=self.side)
self.div = Frame(master, cursor=self.cursor)
self.div[self.dim] = self.thickness
self.div.pack(fill="both", side=self.side)
self.f2 = Frame(master)
self.f2.pack(expand=1, fill="both", side=self.side)
self.div.bind("<ButtonPress-1>", self.divider_press)
if bg:
##self.f1["bg"] = bg
##self.f2["bg"] = bg
self.div["bg"] = bg
def parts(self):
return self.f1, self.f2
def divider_press(self, event):
self.press_event = event
self.f1.pack_propagate(0)
self.f2.pack_propagate(0)
for f in self.f1, self.f2:
for dim in "width", "height":
f[dim] = getattr(f, "winfo_"+dim)()
self.div.bind("<Motion>", self.div_motion)
self.div.bind("<ButtonRelease-1>", self.div_release)
self.div.grab_set()
def div_motion(self, event):
delta = getattr(event, self.dir) - getattr(self.press_event, self.dir)
if delta:
dim1 = getattr(self.f1, self.winfo_dim)()
dim2 = getattr(self.f2, self.winfo_dim)()
delta = max(delta, self.min-dim1)
delta = min(delta, dim2-self.min)
dim1 = dim1 + delta
dim2 = dim2 - delta
self.f1[self.dim] = dim1
self.f2[self.dim] = dim2
def div_release(self, event):
self.div_motion(event)
self.div.unbind("<Motion>")
self.div.grab_release()
class VSeparator(Separator):
def __init__(self, master, min=10, thickness=5, bg=None):
Separator.__init__(self, master, "v", min, thickness, bg)
class HSeparator(Separator):
def __init__(self, master, min=10, thickness=5, bg=None):
Separator.__init__(self, master, "h", min, thickness, bg)
def main():
root = Tk()
tlist = []
outer = HSeparator(root, bg="red")
for part in outer.parts():
inner = VSeparator(part, bg="blue")
for f in inner.parts():
t = Text(f, width=40, height=10, borderwidth=0)
t.pack(fill="both", expand=1)
tlist.append(t)
tlist[0].insert("1.0", "Make your own Mondrian!")
tlist[1].insert("1.0", "Move the colored dividers...")
root.mainloop()
if __name__ == '__main__':
main()
"""
about box for idle
"""
from Tkinter import *
import string, os
import textView
import idlever
class AboutDialog(Toplevel):
"""
modal about dialog for idle
"""
def __init__(self,parent,title):
Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.geometry("+%d+%d" % (parent.winfo_rootx()+30,
parent.winfo_rooty()+30))
self.bg="#707070"
self.fg="#ffffff"
self.CreateWidgets()
self.resizable(height=FALSE,width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.Ok)
self.parent = parent
self.buttonOk.focus_set()
#key bindings for this dialog
self.bind('<Alt-c>',self.CreditsButtonBinding) #credits button
self.bind('<Alt-l>',self.LicenseButtonBinding) #license button
self.bind('<Return>',self.Ok) #dismiss dialog
self.bind('<Escape>',self.Ok) #dismiss dialog
self.wait_window()
def CreateWidgets(self):
frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
frameButtons = Frame(self)
frameButtons.pack(side=BOTTOM,fill=X)
frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
self.buttonOk = Button(frameButtons,text='Ok',
command=self.Ok)#,default=ACTIVE
self.buttonOk.pack(padx=5,pady=5)
#self.picture = Image('photo',data=self.pictureData)
frameBg = Frame(frameMain,bg=self.bg)
frameBg.pack(expand=TRUE,fill=BOTH)
labelTitle = Label(frameBg,text='IDLEfork',fg=self.fg,bg=self.bg,
font=('courier', 24, 'bold'))
labelTitle.grid(row=0,column=0,sticky=W,padx=10,pady=10)
#labelPicture = Label(frameBg,text='[picture]')
#image=self.picture,bg=self.bg)
#labelPicture.grid(row=0,column=1,sticky=W,rowspan=2,padx=0,pady=3)
labelVersion = Label(frameBg,text='version '+idlever.IDLE_VERSION,
fg=self.fg,bg=self.bg)
labelVersion.grid(row=1,column=0,sticky=W,padx=10,pady=5)
labelDesc = Label(frameBg,
text="A development version of Python's lightweight\n"+
'Integrated DeveLopment Environment, IDLE.',
justify=LEFT,fg=self.fg,bg=self.bg)
labelDesc.grid(row=2,column=0,sticky=W,columnspan=3,padx=10,pady=5)
labelCopyright = Label(frameBg,
text="Copyright (c) 2001 Python Software Foundation;\nAll Rights Reserved",
justify=LEFT,fg=self.fg,bg=self.bg)
labelCopyright.grid(row=3,column=0,sticky=W,columnspan=3,padx=10,pady=5)
labelLicense = Label(frameBg,
text='Released under the Python 2.1.1 PSF Licence',
justify=LEFT,fg=self.fg,bg=self.bg)
labelLicense.grid(row=4,column=0,sticky=W,columnspan=3,padx=10,pady=5)
Frame(frameBg,height=5,bg=self.bg).grid(row=5,column=0)
labelEmail = Label(frameBg,text='email: idle-dev@python.org',
justify=LEFT,fg=self.fg,bg=self.bg)
labelEmail.grid(row=6,column=0,columnspan=2,sticky=W,padx=10,pady=0)
labelWWW = Label(frameBg,text='www: http://idlefork.sourceforge.net',
justify=LEFT,fg=self.fg,bg=self.bg)
labelWWW.grid(row=7,column=0,columnspan=2,sticky=W,padx=10,pady=0)
Frame(frameBg,borderwidth=1,relief=SUNKEN,
height=2,bg=self.bg).grid(row=8,column=0,sticky=EW,
columnspan=3, padx=5, pady=5)
labelPythonVer = Label(frameBg,text='Python version: '+
sys.version.split()[0],fg=self.fg,bg=self.bg)
labelPythonVer.grid(row=9,column=0,sticky=W,padx=10,pady=0)
#handle weird tk version num in windoze python >= 1.6 (?!?)
tkVer = `TkVersion`.split('.')
tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:]
if tkVer[len(tkVer)-1] == '':
tkVer[len(tkVer)-1] = '0'
tkVer = string.join(tkVer,'.')
labelTkVer = Label(frameBg,text='Tk version: '+
tkVer,fg=self.fg,bg=self.bg)
labelTkVer.grid(row=9,column=1,sticky=W,padx=2,pady=0)
self.buttonLicense = Button(frameBg,text='View License',underline=5,
width=14,highlightbackground=self.bg,command=self.ShowLicense)#takefocus=FALSE
self.buttonLicense.grid(row=10,column=0,sticky=W,padx=10,pady=10)
self.buttonCredits = Button(frameBg,text='View Credits',underline=5,
width=14,highlightbackground=self.bg,command=self.ShowCredits)#takefocus=FALSE
self.buttonCredits.grid(row=10,column=1,columnspan=2,sticky=E,padx=10,pady=10)
def CreditsButtonBinding(self,event):
self.buttonCredits.invoke()
def LicenseButtonBinding(self,event):
self.buttonLicense.invoke()
def ShowLicense(self):
self.ViewFile('About - License','LICENSE.txt')
def ShowCredits(self):
self.ViewFile('About - Credits','CREDITS.txt')
def ViewFile(self,viewTitle,viewFile):
fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),viewFile)
textView.TextViewer(self,viewTitle,fn)
def Ok(self, event=None):
self.destroy()
if __name__ == '__main__':
#test the dialog
root=Tk()
def run():
import aboutDialog
aboutDialog.AboutDialog(root,'About')
Button(root,text='Dialog',command=run).pack()
root.mainloop()
"boolcheck - import this module to ensure True, False, bool() builtins exist."
try:
True
except NameError:
import __builtin__
__builtin__.True = 1
__builtin__.False = 0
from operator import truth
__builtin__.bool = truth
# IDLE reads several config files to determine user preferences. This
# file is the default config 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 (=1 to enable the
# extension, =0 to disable it) and also contains any other general
# configuration items for the extension. Each extension may also define up to
# two optional sections named ExtensionName_bindings and
# ExtensionName_cfgBindings. If present, ExtensionName_bindings defines virtual
# event bindings for the extension that are not sensibly re-configurable. If
# present, ExtensionName_cfgBindings defines virtual event bindings for the
# extension that may be sensibly re-configured.
# See config-keys.def for notes on specifying keys.
[FormatParagraph]
enable=1
[FormatParagraph_cfgBindings]
format-paragraph=<Alt-Key-q>
[AutoExpand]
enable=1
[AutoExpand_cfgBindings]
expand-word=<Alt-Key-slash>
[ZoomHeight]
enable=1
[ZoomHeight_cfgBindings]
zoom-height=<Alt-Key-2>
[ScriptBinding]
enable=1
[ScriptBinding_cfgBindings]
run-module=<Key-F5>
check-module=<Alt-Key-x>
[CallTips]
enable=1
[CallTips_bindings]
paren-open=<Key-parenleft>
paren-close=<Key-parenright>
check-calltip-cancel=<KeyRelease>
calltip-cancel=<ButtonPress> <Key-Escape>
[ParenMatch]
enable=0
style= expression
flash-delay= 500
bell= 1
hilite-foreground= black
hilite-background= #43cd80
[ParenMatch_bindings]
flash-open-paren=<KeyRelease-parenright> <KeyRelease-bracketright> <KeyRelease-braceright>
check-restore=<KeyPress>
# IDLE reads several config files to determine user preferences. This
# file is the default config file for idle highlight theme settings.
[IDLE Classic]
normal-foreground= #000000
normal-background= #ffffff
keyword-foreground= #ff7700
keyword-background= #ffffff
comment-foreground= #dd0000
comment-background= #ffffff
string-foreground= #00aa00
string-background= #ffffff
definition-foreground= #0000ff
definition-background= #ffffff
hilite-foreground= #000000
hilite-background= gray
break-foreground= black
break-background= #ffff55
hit-foreground= #ffffff
hit-background= #000000
error-foreground= #000000
error-background= #ff7777
#cursor (only foreground can be set)
cursor-foreground= black
#shell window
stdout-foreground= blue
stdout-background= #ffffff
stderr-foreground= red
stderr-background= #ffffff
console-foreground= #770000
console-background= #ffffff
[IDLE New]
normal-foreground= #000000
normal-background= #ffffff
keyword-foreground= #ff7700
keyword-background= #ffffff
comment-foreground= #dd0000
comment-background= #ffffff
string-foreground= #00aa00
string-background= #ffffff
definition-foreground= #0000ff
definition-background= #ffffff
hilite-foreground= #000000
hilite-background= gray
break-foreground= black
break-background= #ffff55
hit-foreground= #ffffff
hit-background= #000000
error-foreground= #000000
error-background= #ff7777
#cursor (only foreground can be set)
cursor-foreground= black
#shell window
stdout-foreground= blue
stdout-background= #ffffff
stderr-foreground= red
stderr-background= #ffffff
console-foreground= #770000
console-background= #ffffff
# IDLE reads several config files to determine user preferences. This
# file is the default config file for idle key binding settings.
# Where multiple keys are specified for an action: if they are separated
# by a space (eg. action=<key1> <key2>) then the keys are altenatives, if
# there is no space (eg. action=<key1><key2>) then the keys comprise a
# single 'emacs style' multi-keystoke binding. The tk event specifier 'Key'
# is used in all cases, for consistency in auto key conflict checking in the
# configuration gui.
[IDLE Classic Windows]
copy=<Control-Key-c>
cut=<Control-Key-x>
paste=<Control-Key-v>
beginning-of-line= <Key-Home>
center-insert=<Control-Key-l>
close-all-windows=<Control-Key-q>
close-window=<Alt-Key-F4> <Meta-Key-F4>
do-nothing=<Control-Key-F12>
end-of-file=<Control-Key-d>
python-docs=<Key-F1>
python-context-help=<Shift-Key-F1>
history-next=<Alt-Key-n> <Meta-Key-n>
history-previous=<Alt-Key-p> <Meta-Key-p>
interrupt-execution=<Control-Key-c>
view-restart=<Key-F6>
restart-shell=<Control-Key-F6>
open-class-browser=<Alt-Key-c> <Meta-Key-c>
open-module=<Alt-Key-m> <Meta-Key-m>
open-new-window=<Control-Key-n>
open-window-from-file=<Control-Key-o>
plain-newline-and-indent=<Control-Key-j>
print-window=<Control-Key-p>
redo=<Control-Shift-Key-z>
remove-selection=<Key-Escape>
save-copy-of-window-as-file=<Alt-Shift-Key-s>
save-window-as-file=<Control-Shift-Key-s>
save-window=<Control-Key-s>
select-all=<Control-Key-a>
toggle-auto-coloring=<Control-Key-slash>
undo=<Control-Key-z>
find=<Control-Key-f>
find-again=<Control-Key-g> <Key-F3>
find-in-files=<Alt-Key-F3> <Meta-Key-F3>
find-selection=<Control-Key-F3>
replace=<Control-Key-h>
goto-line=<Alt-Key-g> <Meta-Key-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> <Meta-Key-3>
uncomment-region=<Alt-Key-4> <Meta-Key-4>
tabify-region=<Alt-Key-5> <Meta-Key-5>
untabify-region=<Alt-Key-6> <Meta-Key-6>
toggle-tabs=<Alt-Key-t> <Meta-Key-t>
change-indentwidth=<Alt-Key-u> <Meta-Key-u>
[IDLE Classic Unix]
copy=<Alt-Key-w> <Meta-Key-w>
cut=<Control-Key-w>
paste=<Control-Key-y>
beginning-of-line=<Control-Key-a> <Key-Home>
center-insert=<Control-Key-l>
close-all-windows=<Control-Key-x><Control-Key-c>
close-window=<Control-Key-x><Control-Key-0>
do-nothing=<Control-Key-x>
end-of-file=<Control-Key-d>
history-next=<Alt-Key-n> <Meta-Key-n>
history-previous=<Alt-Key-p> <Meta-Key-p>
interrupt-execution=<Control-Key-c>
view-restart=<Key-F6>
restart-shell=<Control-Key-F6>
open-class-browser=<Control-Key-x><Control-Key-b>
open-module=<Control-Key-x><Control-Key-m>
open-new-window=<Control-Key-x><Control-Key-n>
open-window-from-file=<Control-Key-x><Control-Key-f>
plain-newline-and-indent=<Control-Key-j>
print-window=<Control-x><Control-Key-p>
python-docs=<Control-Key-h>
python-context-help=<Control-Shift-Key-h>
redo=<Alt-Key-z> <Meta-Key-z>
remove-selection=<Key-Escape>
save-copy-of-window-as-file=<Control-Key-x><Control-Key-y>
save-window-as-file=<Control-Key-x><Control-Key-w>
save-window=<Control-Key-x><Control-Key-s>
select-all=<Alt-Key-a> <Meta-Key-a>
toggle-auto-coloring=<Control-Key-slash>
undo=<Control-Key-z>
find=<Control-Key-u><Control-Key-u><Control-Key-s>
find-again=<Control-Key-u><Control-Key-s>
find-in-files=<Alt-Key-s> <Meta-Key-s>
find-selection=<Control-Key-s>
replace=<Control-Key-r>
goto-line=<Alt-Key-g> <Meta-Key-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>
[IDLE Classic Mac]
copy=<Command-Key-c>
cut=<Command-Key-x>
paste=<Command-Key-v>
beginning-of-line= <Key-Home>
center-insert=<Control-Key-l>
close-all-windows=<Command-Key-q>
close-window=<Command-Key-w>
do-nothing=<Control-Key-F12>
end-of-file=<Control-Key-d>
python-docs=<Key-F1>
python-context-help=<Shift-Key-F1>
history-next=<Control-Key-n>
history-previous=<Control-Key-p>
interrupt-execution=<Control-Key-c>
view-restart=<Key-F6>
restart-shell=<Control-Key-F6>
open-class-browser=<Command-Key-b>
open-module=<Command-Key-m>
open-new-window=<Command-Key-n>
open-window-from-file=<Command-Key-o>
plain-newline-and-indent=<Control-Key-j>
print-window=<Command-Key-p>
redo=<Shift-Command-Key-z>
remove-selection=<Key-Escape>
save-window-as-file=<Shift-Command-Key-s>
save-window=<Command-Key-s>
save-copy-of-window-as-file=<Option-Command-Key-s>
select-all=<Command-Key-a>
toggle-auto-coloring=<Control-Key-slash>
undo=<Command-Key-z>
find=<Command-Key-f>
find-again=<Command-Key-g> <Key-F3>
find-in-files=<Command-Key-F3>
find-selection=<Shift-Command-Key-F3>
replace=<Command-Key-r>
goto-line=<Command-Key-j>
smart-backspace=<Key-BackSpace>
newline-and-indent=<Key-Return> <Key-KP_Enter>
smart-indent=<Key-Tab>
indent-region=<Command-Key-bracketright>
dedent-region=<Command-Key-bracketleft>
comment-region=<Control-Key-3>
uncomment-region=<Control-Key-4>
tabify-region=<Control-Key-5>
untabify-region=<Control-Key-6>
toggle-tabs=<Control-Key-t>
change-indentwidth=<Control-Key-u>
[EditorWindow]
font-name= monaco
font-size= 9
# 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
# ---------------------
# config-main.def the default general config file
# config-extensions.def the default extension config file
# config-highlight.def the default highlighting config file
# config-keys.def the default keybinding config file
#
# user configuration
# -------------------
# ~/.idlerc/idle-main.cfg the user general config file
# ~/.idlerc/idle-extensions.cfg the user extension config file
# ~/.idlerc/idle-highlight.cfg the user highlighting config file
# ~/.idlerc/idle-keys.cfg the user keybinding config file
#
# Any options the user saves through the config dialog will be saved to
# the relevant user config file. Reverting any general setting to the
# default causes that entry to be wiped from the user file and re-read
# from the default file. User highlighting themes or keybinding sets 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 and must 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 is
# <sequence_number = menu item;/path/to/help/source>
# 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.
#
# It is best to use the Configuration GUI to set up additional help sources!
# Example:
#1 = My Extra Help Source;/usr/share/doc/foo/index.html
#2 = Another Help Source;/path/to/another.pdf
[General]
editor-on-startup= 0
print-command-posix=lpr %s
print-command-win=start /min notepad /p %s
[EditorWindow]
width= 80
height= 30
font= courier
font-size= 12
font-bold= 0
[Indent]
use-spaces= 1
num-spaces= 4
[Theme]
default= 1
name= IDLE Classic
[Keys]
default= 1
name= IDLE Classic Windows
[HelpFiles]
[EditorWindow]
font-name= courier
font-size= 10
print-command=lpr %s
[EditorWindow]
font-name: courier new
font-size: 10
print-command=start /min notepad /p %s
# IDLE reads several config files to determine user preferences. This
# file is the default config file. When IDLE starts, it will look in
# the following four files in order:
# config.txt the default config file
# config-[win/unix/mac].txt the generic platform config file
# config-[sys.platform].txt the specific platform config file
# ~/.idle the user config file
# XXX what about Windows?
#
# The last definition of each option is used. For example, you can
# override the default window size (80x24) by defining width and
# height options in the EditorWindow section of your ~/.idle file
#
# IDLE extensions can be enabled and disabled by adding them to one of
# the config files. To enable an extension, create a section with the
# same name as the extension, e.g. the [ParenMatch] section below. To
# disable an extension, either remove the section or add the 'enable'
# option with the value 0.
[EditorWindow]
width= 80
height= 24
# fonts defined in config-[win/unix].txt
[Colors]
normal-foreground= black
normal-background= white
# These color types are not explicitly defined= sync, todo, stdin
keyword-foreground= #ff7700
comment-foreground= #dd0000
string-foreground= #00aa00
definition-foreground= #0000ff
hilite-foreground= #000068
hilite-background= #006868
break-foreground= #ff7777
hit-foreground= #ffffff
hit-background= #000000
stdout-foreground= blue
stderr-foreground= red
console-foreground= #770000
error-background= #ff7777
cursor-background= black
[SearchBinding]
[AutoIndent]
[AutoExpand]
[FormatParagraph]
[ZoomHeight]
[ScriptBinding]
[CallTips]
[ParenMatch]
enable= 0
style= expression
flash-delay= 500
bell= 1
hilite-foreground= black
hilite-background= #43cd80
This diff is collapsed.
This diff is collapsed.
"Dialog to specify or edit the parameters for a user configured help source."
import os
from Tkinter import *
import tkMessageBox
import tkFileDialog
class GetHelpSourceDialog(Toplevel):
def __init__(self, parent, title, menuItem='', filePath=''):
"""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.
"""
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() #hide while setting geometry
#needs to be done here so that the winfo_reqwidth is valid
self.update_idletasks()
#centre dialog over parent:
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() #geometry set, unhide
self.bind('<Return>', self.Ok)
self.wait_window()
def CreateWidgets(self):
self.menu = StringVar(self)
self.path = StringVar(self)
self.fontSize = StringVar(self)
self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
text='Menu Item:')
self.entryMenu = Entry(self.frameMain, textvariable=self.menu,
width=30)
self.entryMenu.focus_set()
labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
text='Help File Path: Enter URL or browse for file')
self.entryPath = Entry(self.frameMain, textvariable=self.path,
width=40)
self.entryMenu.focus_set()
labelMenu.pack(anchor=W, padx=5, pady=3)
self.entryMenu.pack(anchor=W, padx=5, pady=3)
labelPath.pack(anchor=W, padx=5, pady=3)
self.entryPath.pack(anchor=W, padx=5, pady=3)
browseButton = Button(self.frameMain, text='Browse', width=8,
command=self.browseFile)
browseButton.pack(pady=3)
frameButtons = Frame(self)
frameButtons.pack(side=BOTTOM, fill=X)
self.buttonOk = Button(frameButtons, text='OK',
width=8, default=ACTIVE, 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)
def browseFile(self):
filetypes = [
("HTML Files", "*.htm *.html", "TEXT"),
("PDF Files", "*.pdf", "TEXT"),
("Windows Help Files", "*.chm"),
("Text Files", "*.txt", "TEXT"),
("All Files", "*")]
path = self.path.get()
if path:
dir, base = os.path.split(path)
else:
base = None
if sys.platform.count('win') or sys.platform.count('nt'):
dir = os.path.join(os.path.dirname(sys.executable), 'Doc')
if not os.path.isdir(dir):
dir = os.getcwd()
else:
dir = os.getcwd()
opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes)
file = opendialog.show(initialdir=dir, initialfile=base)
if file:
self.path.set(file)
def MenuOk(self):
"Simple validity check for a sensible menu item name"
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
def PathOk(self):
"Simple validity check for menu file path"
pathOk = True
path = self.path.get()
path.strip()
if not path: #no path specified
tkMessageBox.showerror(title='File Path Error',
message='No help file path specified.',
parent=self)
self.entryPath.focus_set()
pathOk = False
elif path.startswith('www.') or path.startswith('http'):
pathOk = True
elif 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
def Ok(self, event=None):
if self.MenuOk() and self.PathOk():
self.result = (self.menu.get().strip(),
self.path.get().strip())
self.destroy()
def Cancel(self, event=None):
self.result = None
self.destroy()
if __name__ == '__main__':
#test the dialog
root = Tk()
def run():
keySeq = ''
dlg = GetHelpSourceDialog(root, 'Get Help Source')
print dlg.result
Button(root,text='Dialog', command=run).pack()
root.mainloop()
"""
Dialog that allows user to specify a new config file section name.
Used to get new highlight theme and keybinding set names.
"""
from Tkinter import *
import tkMessageBox
class GetCfgSectionNameDialog(Toplevel):
def __init__(self,parent,title,message,usedNames):
"""
message - string, informational message to display
usedNames - list, list of names already in use for validity check
"""
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() #hide while setting geometry
self.update_idletasks()
#needs to be done here so that the winfo_reqwidth is valid
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)) )) ) #centre dialog over parent
self.deiconify() #geometry set, unhide
self.wait_window()
def CreateWidgets(self):
self.name=StringVar(self)
self.fontSize=StringVar(self)
self.frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
self.frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
self.messageInfo=Message(self.frameMain,anchor=W,justify=LEFT,padx=5,pady=5,
text=self.message)#,aspect=200)
entryName=Entry(self.frameMain,textvariable=self.name,width=30)
entryName.focus_set()
self.messageInfo.pack(padx=5,pady=5)#,expand=TRUE,fill=BOTH)
entryName.pack(padx=5,pady=5)
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)
def NameOk(self):
#simple validity check for a sensible
#ConfigParser file section name
nameOk=1
name=self.name.get()
name.strip()
if not name: #no name specified
tkMessageBox.showerror(title='Name Error',
message='No name specified.', parent=self)
nameOk=0
elif len(name)>30: #name too long
tkMessageBox.showerror(title='Name Error',
message='Name too long. It should be no more than '+
'30 characters.', parent=self)
nameOk=0
elif name in self.usedNames:
tkMessageBox.showerror(title='Name Error',
message='This name is already in use.', parent=self)
nameOk=0
return nameOk
def Ok(self, event=None):
if self.NameOk():
self.result=self.name.get().strip()
self.destroy()
def Cancel(self, event=None):
self.result=''
self.destroy()
if __name__ == '__main__':
#test the dialog
root=Tk()
def run():
keySeq=''
dlg=GetCfgSectionNameDialog(root,'Get Name',
'The information here should need to be word wrapped. Test.')
print dlg.result
Button(root,text='Dialog',command=run).pack()
root.mainloop()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
[bdist_rpm]
release = 1
packager = Kurt B. Kaiser <kbk@shore.net>
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment