wxPython Merge #2 of 2.4 branch --> HEAD (branch tag: wxPy_2_4_merge_2)

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@21593 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Robin Dunn
2003-07-02 23:13:10 +00:00
parent e234d4c9b7
commit 1fded56b37
535 changed files with 48899 additions and 20067 deletions
-3
View File
@@ -1,3 +0,0 @@
*.pyc
*.BAK
*.$$$
File diff suppressed because it is too large Load Diff
+1 -65
View File
@@ -1,70 +1,6 @@
"""PyCrustApp is a python shell and namespace browser application."""
from wxPython.py.PyCrust import *
# The next two lines, and the other code below that makes use of
# ``__main__`` and ``original``, serve the purpose of cleaning up the
# main namespace to look as much as possible like the regular Python
# shell environment.
import __main__
original = __main__.__dict__.keys()
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from wxPython import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.wxApp):
"""PyCrust standalone application."""
def OnInit(self):
from wxPython import wx
wx.wxInitAllImageHandlers()
locals = __main__.__dict__
from crust import CrustFrame
self.frame = CrustFrame(locals=locals)
self.frame.SetSize((800, 600))
self.frame.Show()
self.SetTopWindow(self.frame)
# Add the application object to the sys module's namespace.
# This allows a shell user to do:
# >>> import sys
# >>> sys.app.whatever
import sys
sys.app = self
return 1
'''
The main() function needs to handle being imported, such as with the
pycrust script that wxPython installs:
#!/usr/bin/env python
from wxPython.lib.PyCrust.PyCrustApp import main
main()
'''
def main():
import __main__
md = __main__.__dict__
keepers = original
keepers.append('App')
for key in md.keys():
if key not in keepers:
del md[key]
app = App(0)
if md.has_key('App') and md['App'] is App:
del md['App']
if md.has_key('__main__') and md['__main__'] is __main__:
del md['__main__']
app.MainLoop()
if __name__ == '__main__':
main()
+1 -40
View File
@@ -1,44 +1,5 @@
"""PyFillingApp is a python namespace inspection application."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
# We use this object to get more introspection when run standalone.
app = None
import filling
# These are imported just to have something interesting to inspect.
import crust
import interpreter
import introspect
import pseudo
import shell
import sys
from wxPython import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(filling.App):
def OnInit(self):
filling.App.OnInit(self)
self.root = self.fillingFrame.filling.tree.root
return True
def main():
"""Create and run the application."""
global app
app = App(0)
app.fillingFrame.filling.tree.Expand(app.root)
app.MainLoop()
from wxPython.py.PyFilling import *
if __name__ == '__main__':
+1 -66
View File
@@ -1,71 +1,6 @@
"""PyShellApp is a python shell application."""
from wxPython.py.PyShell import *
# The next two lines, and the other code below that makes use of
# ``__main__`` and ``original``, serve the purpose of cleaning up the
# main namespace to look as much as possible like the regular Python
# shell environment.
import __main__
original = __main__.__dict__.keys()
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from wxPython import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.wxApp):
"""PyShell standalone application."""
def OnInit(self):
from wxPython import wx
wx.wxInitAllImageHandlers()
locals = __main__.__dict__
from shell import ShellFrame
self.frame = ShellFrame(locals=locals)
self.frame.SetSize((750, 525))
self.frame.Show()
self.SetTopWindow(self.frame)
self.frame.shell.SetFocus()
# Add the application object to the sys module's namespace.
# This allows a shell user to do:
# >>> import sys
# >>> sys.app.whatever
import sys
sys.app = self
return 1
'''
The main() function needs to handle being imported, such as with the
pycrust script that wxPython installs:
#!/usr/bin/env python
from wxPython.lib.PyCrust.PyCrustApp import main
main()
'''
def main():
import __main__
md = __main__.__dict__
keepers = original
keepers.append('App')
for key in md.keys():
if key not in keepers:
del md[key]
app = App(0)
if md.has_key('App') and md['App'] is App:
del md['App']
if md.has_key('__main__') and md['__main__'] is __main__:
del md['__main__']
app.MainLoop()
if __name__ == '__main__':
main()
+5 -1
View File
@@ -1 +1,5 @@
# Orbtech python package.
# Change this to an ImportError after the next release
import warnings
warnings.warn("PyCrust has been renamed to Py. Use 'from wx import py'", stacklevel=2)
+1 -168
View File
@@ -1,169 +1,2 @@
"""PyCrust Crust combines the shell and filling into one control."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from wxPython import wx
from filling import Filling
import os
from shell import Shell
from shellmenu import ShellMenu
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
class Crust(wx.wxSplitterWindow):
"""PyCrust Crust based on wxSplitterWindow."""
name = 'PyCrust Crust'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.wxDefaultPosition,
size=wx.wxDefaultSize, style=wx.wxSP_3D,
name='Crust Window', rootObject=None, rootLabel=None,
rootIsNamespace=True, intro='', locals=None,
InterpClass=None, *args, **kwds):
"""Create a PyCrust Crust instance."""
wx.wxSplitterWindow.__init__(self, parent, id, pos, size, style, name)
self.shell = Shell(parent=self, introText=intro,
locals=locals, InterpClass=InterpClass,
*args, **kwds)
if rootObject is None:
rootObject = self.shell.interp.locals
self.notebook = wx.wxNotebook(parent=self, id=-1)
self.shell.interp.locals['notebook'] = self.notebook
self.filling = Filling(parent=self.notebook,
rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace)
# Add 'filling' to the interpreter's locals.
self.shell.interp.locals['filling'] = self.filling
self.notebook.AddPage(page=self.filling, text='Namespace', select=True)
self.calltip = Calltip(parent=self.notebook)
self.notebook.AddPage(page=self.calltip, text='Calltip')
self.sessionlisting = SessionListing(parent=self.notebook)
self.notebook.AddPage(page=self.sessionlisting, text='Session')
self.dispatcherlisting = DispatcherListing(parent=self.notebook)
self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')
from wxd import wx_
self.wxdocs = Filling(parent=self.notebook,
rootObject=wx_,
rootLabel='wx',
rootIsNamespace=False,
static=True)
self.notebook.AddPage(page=self.wxdocs, text='wxPython Docs')
from wxd import stc_
self.stcdocs = Filling(parent=self.notebook,
rootObject=stc_.StyledTextCtrl,
rootLabel='StyledTextCtrl',
rootIsNamespace=False,
static=True)
self.notebook.AddPage(page=self.stcdocs, text='StyledTextCtrl Docs')
self.SplitHorizontally(self.shell, self.notebook, 300)
self.SetMinimumPaneSize(1)
class Calltip(wx.wxTextCtrl):
"""Text control containing the most recent shell calltip."""
def __init__(self, parent=None, id=-1):
import dispatcher
style = wx.wxTE_MULTILINE | wx.wxTE_READONLY | wx.wxTE_RICH2
wx.wxTextCtrl.__init__(self, parent=parent, id=id, style=style)
self.SetBackgroundColour(wx.wxColour(255, 255, 232))
dispatcher.connect(receiver=self.display, signal='Shell.calltip')
def display(self, calltip):
"""Receiver for Shell.calltip signal."""
self.SetValue(calltip)
class SessionListing(wx.wxTextCtrl):
"""Text control containing all commands for session."""
def __init__(self, parent=None, id=-1):
import dispatcher
style = wx.wxTE_MULTILINE | wx.wxTE_READONLY | \
wx.wxTE_RICH2 | wx.wxTE_DONTWRAP
wx.wxTextCtrl.__init__(self, parent=parent, id=id, style=style)
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
if command and not more:
self.SetInsertionPointEnd()
start, end = self.GetSelection()
if start != end:
self.SetSelection(0, 0)
self.AppendText(command + '\n')
class DispatcherListing(wx.wxTextCtrl):
"""Text control containing all dispatches for session."""
def __init__(self, parent=None, id=-1):
import dispatcher
style = wx.wxTE_MULTILINE | wx.wxTE_READONLY | \
wx.wxTE_RICH2 | wx.wxTE_DONTWRAP
wx.wxTextCtrl.__init__(self, parent=parent, id=id, style=style)
dispatcher.connect(receiver=self.spy)
def spy(self, signal, sender):
"""Receiver for Any signal from Any sender."""
text = '%r from %s' % (signal, sender)
self.SetInsertionPointEnd()
start, end = self.GetSelection()
if start != end:
self.SetSelection(0, 0)
self.AppendText(text + '\n')
class CrustFrame(wx.wxFrame, ShellMenu):
"""Frame containing all the PyCrust components."""
name = 'PyCrust Frame'
revision = __revision__
def __init__(self, parent=None, id=-1, title='PyCrust',
pos=wx.wxDefaultPosition, size=wx.wxDefaultSize,
style=wx.wxDEFAULT_FRAME_STYLE,
rootObject=None, rootLabel=None, rootIsNamespace=True,
locals=None, InterpClass=None, *args, **kwds):
"""Create a PyCrust CrustFrame instance."""
wx.wxFrame.__init__(self, parent, id, title, pos, size, style)
intro = 'PyCrust %s - The Flakiest Python Shell' % VERSION
intro += '\nSponsored by Orbtech - '
intro += 'Your source for Python programming expertise.'
self.CreateStatusBar()
self.SetStatusText(intro.replace('\n', ', '))
import images
self.SetIcon(images.getPyCrustIcon())
self.crust = Crust(parent=self, intro=intro,
rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
locals=locals,
InterpClass=InterpClass, *args, **kwds)
# Override the filling so that status messages go to the status bar.
self.crust.filling.tree.setStatusText = self.SetStatusText
# Override the shell so that status messages go to the status bar.
self.crust.shell.setStatusText = self.SetStatusText
# Fix a problem with the sash shrinking to nothing.
self.crust.filling.SetSashPosition(200)
self.shell = self.crust.shell
self.createMenus()
wx.EVT_CLOSE(self, self.OnCloseWindow)
# Set focus to the shell editor.
self.crust.shell.SetFocus()
def OnCloseWindow(self, event):
self.crust.shell.destroy()
self.Destroy()
from wxPython.py.crust import *
+1 -434
View File
@@ -1,436 +1,3 @@
"""PyCrust Filling is the gui tree control through which a user can
navigate the local namespace or any object."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from wxPython.py.filling import *
from wxPython import wx
from wxPython import stc
from version import VERSION
import dispatcher
import inspect
import introspect
import keyword
import sys
import types
try:
True
except NameError:
True = 1==1
False = 1==0
COMMONTYPES = [getattr(types, t) for t in dir(types) \
if not t.startswith('_') \
and t not in ('ClassType', 'InstanceType', 'ModuleType')]
DOCTYPES = ('BuiltinFunctionType', 'BuiltinMethodType', 'ClassType',
'FunctionType', 'GeneratorType', 'InstanceType',
'LambdaType', 'MethodType', 'ModuleType',
'UnboundMethodType', 'method-wrapper')
SIMPLETYPES = [getattr(types, t) for t in dir(types) \
if not t.startswith('_') and t not in DOCTYPES]
try:
COMMONTYPES.append(type(''.__repr__)) # Method-wrapper in version 2.2.x.
except AttributeError:
pass
class FillingTree(wx.wxTreeCtrl):
"""PyCrust FillingTree based on wxTreeCtrl."""
name = 'PyCrust Filling Tree'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.wxDefaultPosition,
size=wx.wxDefaultSize, style=wx.wxTR_DEFAULT_STYLE,
rootObject=None, rootLabel=None, rootIsNamespace=0,
static=False):
"""Create a PyCrust FillingTree instance."""
wx.wxTreeCtrl.__init__(self, parent, id, pos, size, style)
self.rootIsNamespace = rootIsNamespace
import __main__
if rootObject is None:
rootObject = __main__.__dict__
self.rootIsNamespace = 1
if rootObject is __main__.__dict__ and rootLabel is None:
rootLabel = 'locals()'
if not rootLabel:
rootLabel = 'Ingredients'
rootData = wx.wxTreeItemData(rootObject)
self.item = self.root = self.AddRoot(rootLabel, -1, -1, rootData)
self.SetItemHasChildren(self.root, self.hasChildren(rootObject))
wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding)
wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed)
wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged)
wx.EVT_TREE_ITEM_ACTIVATED(self, self.GetId(), self.OnItemActivated)
if not static:
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
self.display()
def OnItemExpanding(self, event):
"""Add children to the item."""
busy = wx.wxBusyCursor()
item = event.GetItem()
if self.IsExpanded(item):
return
self.addChildren(item)
# self.SelectItem(item)
def OnItemCollapsed(self, event):
"""Remove all children from the item."""
busy = wx.wxBusyCursor()
item = event.GetItem()
# self.CollapseAndReset(item)
# self.DeleteChildren(item)
# self.SelectItem(item)
def OnSelChanged(self, event):
"""Display information about the item."""
busy = wx.wxBusyCursor()
self.item = event.GetItem()
self.display()
def OnItemActivated(self, event):
"""Launch a DirFrame."""
item = event.GetItem()
text = self.getFullName(item)
obj = self.GetPyData(item)
frame = FillingFrame(parent=self, size=(600, 100), rootObject=obj,
rootLabel=text, rootIsNamespace=False)
frame.Show()
def hasChildren(self, obj):
"""Return true if object has children."""
if self.getChildren(obj):
return True
else:
return False
def getChildren(self, obj):
"""Return dictionary with attributes or contents of object."""
busy = wx.wxBusyCursor()
otype = type(obj)
if otype is types.DictType \
or str(otype)[17:23] == 'BTrees' and hasattr(obj, 'keys'):
return obj
d = {}
if otype is types.ListType or otype is types.TupleType:
for n in range(len(obj)):
key = '[' + str(n) + ']'
d[key] = obj[n]
if otype not in COMMONTYPES:
for key in introspect.getAttributeNames(obj):
# Believe it or not, some attributes can disappear,
# such as the exc_traceback attribute of the sys
# module. So this is nested in a try block.
try:
d[key] = getattr(obj, key)
except:
pass
return d
def addChildren(self, item):
self.DeleteChildren(item)
obj = self.GetPyData(item)
children = self.getChildren(obj)
if not children:
return
keys = children.keys()
keys.sort(lambda x, y: cmp(x.lower(), y.lower()))
for key in keys:
itemtext = str(key)
# Show string dictionary items with single quotes, except
# for the first level of items, if they represent a
# namespace.
if type(obj) is types.DictType \
and type(key) is types.StringType \
and (item != self.root \
or (item == self.root and not self.rootIsNamespace)):
itemtext = repr(key)
child = children[key]
data = wx.wxTreeItemData(child)
branch = self.AppendItem(parent=item, text=itemtext, data=data)
self.SetItemHasChildren(branch, self.hasChildren(child))
def display(self):
item = self.item
if self.IsExpanded(item):
self.addChildren(item)
self.setText('')
obj = self.GetPyData(item)
if obj is None: # Windows bug fix.
return
self.SetItemHasChildren(item, self.hasChildren(obj))
otype = type(obj)
text = ''
text += self.getFullName(item)
text += '\n\nType: ' + str(otype)
try:
value = str(obj)
except:
value = ''
if otype is types.StringType or otype is types.UnicodeType:
value = repr(obj)
text += '\n\nValue: ' + value
if otype not in SIMPLETYPES:
try:
text += '\n\nDocstring:\n\n"""' + \
inspect.getdoc(obj).strip() + '"""'
except:
pass
if otype is types.InstanceType:
try:
text += '\n\nClass Definition:\n\n' + \
inspect.getsource(obj.__class__)
except:
pass
else:
try:
text += '\n\nSource Code:\n\n' + \
inspect.getsource(obj)
except:
pass
self.setText(text)
def getFullName(self, item, partial=''):
"""Return a syntactically proper name for item."""
name = self.GetItemText(item)
parent = None
obj = None
if item != self.root:
parent = self.GetItemParent(item)
obj = self.GetPyData(parent)
# Apply dictionary syntax to dictionary items, except the root
# and first level children of a namepace.
if (type(obj) is types.DictType \
or str(type(obj))[17:23] == 'BTrees' \
and hasattr(obj, 'keys')) \
and ((item != self.root and parent != self.root) \
or (parent == self.root and not self.rootIsNamespace)):
name = '[' + name + ']'
# Apply dot syntax to multipart names.
if partial:
if partial[0] == '[':
name += partial
else:
name += '.' + partial
# Repeat for everything but the root item
# and first level children of a namespace.
if (item != self.root and parent != self.root) \
or (parent == self.root and not self.rootIsNamespace):
name = self.getFullName(parent, partial=name)
return name
def setText(self, text):
"""Display information about the current selection."""
# This method will likely be replaced by the enclosing app to
# do something more interesting, like write to a text control.
print text
def setStatusText(self, text):
"""Display status information."""
# This method will likely be replaced by the enclosing app to
# do something more interesting, like write to a status bar.
print text
if wx.wxPlatform == '__WXMSW__':
faces = { 'times' : 'Times New Roman',
'mono' : 'Courier New',
'helv' : 'Lucida Console',
'lucida' : 'Lucida Console',
'other' : 'Comic Sans MS',
'size' : 10,
'lnsize' : 9,
'backcol': '#FFFFFF',
}
else: # GTK
faces = { 'times' : 'Times',
'mono' : 'Courier',
'helv' : 'Helvetica',
'other' : 'new century schoolbook',
'size' : 12,
'lnsize' : 10,
'backcol': '#FFFFFF',
}
class FillingText(stc.wxStyledTextCtrl):
"""PyCrust FillingText based on wxStyledTextCtrl."""
name = 'PyCrust Filling Text'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.wxDefaultPosition,
size=wx.wxDefaultSize, style=wx.wxCLIP_CHILDREN,
static=False):
"""Create a PyCrust FillingText instance."""
stc.wxStyledTextCtrl.__init__(self, parent, id, pos, size, style)
# Configure various defaults and user preferences.
self.config()
dispatcher.connect(receiver=self.fontsizer, signal='FontIncrease')
dispatcher.connect(receiver=self.fontsizer, signal='FontDecrease')
dispatcher.connect(receiver=self.fontsizer, signal='FontDefault')
if not static:
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
self.Refresh()
def fontsizer(self, signal):
"""Receiver for Font* signals."""
size = self.GetZoom()
if signal == 'FontIncrease':
size += 1
elif signal == 'FontDecrease':
size -= 1
elif signal == 'FontDefault':
size = 0
self.SetZoom(size)
def config(self):
"""Configure shell based on user preferences."""
self.SetMarginWidth(1, 0)
self.SetLexer(stc.wxSTC_LEX_PYTHON)
self.SetKeyWords(0, ' '.join(keyword.kwlist))
self.setStyles(faces)
self.SetViewWhiteSpace(0)
self.SetTabWidth(4)
self.SetUseTabs(0)
self.SetReadOnly(1)
try:
self.SetWrapMode(1)
except AttributeError:
pass
def setStyles(self, faces):
"""Configure font size, typeface and color for lexer."""
# Default style
self.StyleSetSpec(stc.wxSTC_STYLE_DEFAULT,
"face:%(mono)s,size:%(size)d" % faces)
self.StyleClearAll()
# Built in styles
self.StyleSetSpec(stc.wxSTC_STYLE_LINENUMBER,
"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d" % faces)
self.StyleSetSpec(stc.wxSTC_STYLE_CONTROLCHAR,
"face:%(mono)s" % faces)
self.StyleSetSpec(stc.wxSTC_STYLE_BRACELIGHT,
"fore:#0000FF,back:#FFFF88")
self.StyleSetSpec(stc.wxSTC_STYLE_BRACEBAD,
"fore:#FF0000,back:#FFFF88")
# Python styles
self.StyleSetSpec(stc.wxSTC_P_DEFAULT,
"face:%(mono)s" % faces)
self.StyleSetSpec(stc.wxSTC_P_COMMENTLINE,
"fore:#007F00,face:%(mono)s" % faces)
self.StyleSetSpec(stc.wxSTC_P_NUMBER,
"")
self.StyleSetSpec(stc.wxSTC_P_STRING,
"fore:#7F007F,face:%(mono)s" % faces)
self.StyleSetSpec(stc.wxSTC_P_CHARACTER,
"fore:#7F007F,face:%(mono)s" % faces)
self.StyleSetSpec(stc.wxSTC_P_WORD,
"fore:#00007F,bold")
self.StyleSetSpec(stc.wxSTC_P_TRIPLE,
"fore:#7F0000")
self.StyleSetSpec(stc.wxSTC_P_TRIPLEDOUBLE,
"fore:#000033,back:#FFFFE8")
self.StyleSetSpec(stc.wxSTC_P_CLASSNAME,
"fore:#0000FF,bold")
self.StyleSetSpec(stc.wxSTC_P_DEFNAME,
"fore:#007F7F,bold")
self.StyleSetSpec(stc.wxSTC_P_OPERATOR,
"")
self.StyleSetSpec(stc.wxSTC_P_IDENTIFIER,
"")
self.StyleSetSpec(stc.wxSTC_P_COMMENTBLOCK,
"fore:#7F7F7F")
self.StyleSetSpec(stc.wxSTC_P_STRINGEOL,
"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled" % faces)
def SetText(self, *args, **kwds):
self.SetReadOnly(0)
stc.wxStyledTextCtrl.SetText(self, *args, **kwds)
self.SetReadOnly(1)
class Filling(wx.wxSplitterWindow):
"""PyCrust Filling based on wxSplitterWindow."""
name = 'PyCrust Filling'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.wxDefaultPosition,
size=wx.wxDefaultSize, style=wx.wxSP_3D,
name='Filling Window', rootObject=None,
rootLabel=None, rootIsNamespace=0, static=False):
"""Create a PyCrust Filling instance."""
wx.wxSplitterWindow.__init__(self, parent, id, pos, size, style, name)
self.tree = FillingTree(parent=self, rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
static=static)
self.text = FillingText(parent=self, static=static)
self.SplitVertically(self.tree, self.text, 200)
self.SetMinimumPaneSize(1)
# Override the filling so that descriptions go to FillingText.
self.tree.setText = self.text.SetText
# Display the root item.
## self.tree.SelectItem(self.tree.root)
self.tree.display()
class FillingFrame(wx.wxFrame):
"""Frame containing the PyCrust filling, or namespace tree component."""
name = 'PyCrust Filling Frame'
revision = __revision__
def __init__(self, parent=None, id=-1, title='PyFilling',
pos=wx.wxDefaultPosition, size=wx.wxDefaultSize,
style=wx.wxDEFAULT_FRAME_STYLE, rootObject=None,
rootLabel=None, rootIsNamespace=0, static=False):
"""Create a PyCrust FillingFrame instance."""
wx.wxFrame.__init__(self, parent, id, title, pos, size, style)
intro = 'PyFilling - The Tastiest Namespace Inspector'
self.CreateStatusBar()
self.SetStatusText(intro)
import images
self.SetIcon(images.getPyCrustIcon())
self.filling = Filling(parent=self, rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
static=static)
# Override so that status messages go to the status bar.
self.filling.tree.setStatusText = self.SetStatusText
class App(wx.wxApp):
"""PyFilling standalone application."""
def OnInit(self):
wx.wxInitAllImageHandlers()
self.fillingFrame = FillingFrame()
self.fillingFrame.Show(True)
self.SetTopWindow(self.fillingFrame)
return True
File diff suppressed because it is too large Load Diff
-226
View File
@@ -1,226 +0,0 @@
"""Shell menu mixin shared by shell and crust."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from wxPython import wx
import sys
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
ID_AUTOCOMP = wx.wxNewId()
ID_AUTOCOMP_SHOW = wx.wxNewId()
ID_AUTOCOMP_INCLUDE_MAGIC = wx.wxNewId()
ID_AUTOCOMP_INCLUDE_SINGLE = wx.wxNewId()
ID_AUTOCOMP_INCLUDE_DOUBLE = wx.wxNewId()
ID_CALLTIPS = wx.wxNewId()
ID_CALLTIPS_SHOW = wx.wxNewId()
ID_COPY_PLUS = wx.wxNewId()
ID_PASTE_PLUS = wx.wxNewId()
ID_WRAP = wx.wxNewId()
class ShellMenu:
"""Mixin class to add standard menu items."""
def createMenus(self):
m = self.fileMenu = wx.wxMenu()
m.AppendSeparator()
m.Append(wx.wxID_EXIT, 'E&xit', 'Exit PyCrust')
m = self.editMenu = wx.wxMenu()
m.Append(wx.wxID_UNDO, '&Undo \tCtrl+Z',
'Undo the last action')
m.Append(wx.wxID_REDO, '&Redo \tCtrl+Y',
'Redo the last undone action')
m.AppendSeparator()
m.Append(wx.wxID_CUT, 'Cu&t \tCtrl+X',
'Cut the selection')
m.Append(wx.wxID_COPY, '&Copy \tCtrl+C',
'Copy the selection - removing prompts')
m.Append(ID_COPY_PLUS, 'Cop&y Plus \tCtrl+Shift+C',
'Copy the selection - retaining prompts')
m.Append(wx.wxID_PASTE, '&Paste \tCtrl+V', 'Paste')
m.Append(ID_PASTE_PLUS, 'Past&e Plus \tCtrl+Shift+V',
'Paste and run commands')
m.AppendSeparator()
m.Append(wx.wxID_CLEAR, 'Cle&ar',
'Delete the selection')
m.Append(wx.wxID_SELECTALL, 'Select A&ll \tCtrl+A',
'Select all text')
m = self.autocompMenu = wx.wxMenu()
m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion',
'Show auto completion during dot syntax', 1)
m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes',
'Include attributes visible to __getattr__ and __setattr__',
1)
m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores',
'Include attibutes prefixed by a single underscore', 1)
m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores',
'Include attibutes prefixed by a double underscore', 1)
m = self.calltipsMenu = wx.wxMenu()
m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips',
'Show call tips with argument specifications', 1)
m = self.optionsMenu = wx.wxMenu()
m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu,
'Auto Completion Options')
m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu,
'Call Tip Options')
m.Append(ID_WRAP, '&Wrap Lines',
'Wrap lines at right edge', 1)
m = self.helpMenu = wx.wxMenu()
m.AppendSeparator()
m.Append(wx.wxID_ABOUT, '&About...', 'About PyCrust')
b = self.menuBar = wx.wxMenuBar()
b.Append(self.fileMenu, '&File')
b.Append(self.editMenu, '&Edit')
b.Append(self.optionsMenu, '&Options')
b.Append(self.helpMenu, '&Help')
self.SetMenuBar(b)
wx.EVT_MENU(self, wx.wxID_EXIT, self.OnExit)
wx.EVT_MENU(self, wx.wxID_UNDO, self.OnUndo)
wx.EVT_MENU(self, wx.wxID_REDO, self.OnRedo)
wx.EVT_MENU(self, wx.wxID_CUT, self.OnCut)
wx.EVT_MENU(self, wx.wxID_COPY, self.OnCopy)
wx.EVT_MENU(self, ID_COPY_PLUS, self.OnCopyPlus)
wx.EVT_MENU(self, wx.wxID_PASTE, self.OnPaste)
wx.EVT_MENU(self, ID_PASTE_PLUS, self.OnPastePlus)
wx.EVT_MENU(self, wx.wxID_CLEAR, self.OnClear)
wx.EVT_MENU(self, wx.wxID_SELECTALL, self.OnSelectAll)
wx.EVT_MENU(self, wx.wxID_ABOUT, self.OnAbout)
wx.EVT_MENU(self, ID_AUTOCOMP_SHOW,
self.OnAutoCompleteShow)
wx.EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC,
self.OnAutoCompleteIncludeMagic)
wx.EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE,
self.OnAutoCompleteIncludeSingle)
wx.EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE,
self.OnAutoCompleteIncludeDouble)
wx.EVT_MENU(self, ID_CALLTIPS_SHOW,
self.OnCallTipsShow)
wx.EVT_MENU(self, ID_WRAP, self.OnWrap)
wx.EVT_UPDATE_UI(self, wx.wxID_UNDO, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, wx.wxID_REDO, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, wx.wxID_CUT, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, wx.wxID_COPY, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_COPY_PLUS, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, wx.wxID_PASTE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_PASTE_PLUS, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, wx.wxID_CLEAR, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_WRAP, self.OnUpdateMenu)
def OnExit(self, event):
self.Close(True)
def OnUndo(self, event):
self.shell.Undo()
def OnRedo(self, event):
self.shell.Redo()
def OnCut(self, event):
self.shell.Cut()
def OnCopy(self, event):
self.shell.Copy()
def OnCopyPlus(self, event):
self.shell.CopyWithPrompts()
def OnPaste(self, event):
self.shell.Paste()
def OnPastePlus(self, event):
self.shell.PasteAndRun()
def OnClear(self, event):
self.shell.Clear()
def OnSelectAll(self, event):
self.shell.SelectAll()
def OnAbout(self, event):
"""Display an About PyCrust window."""
title = 'About PyCrust'
text = 'PyCrust %s\n\n' % VERSION + \
'Yet another Python shell, only flakier.\n\n' + \
'Half-baked by Patrick K. O\'Brien,\n' + \
'the other half is still in the oven.\n\n' + \
'Shell Revision: %s\n' % self.shell.revision + \
'Interpreter Revision: %s\n\n' % self.shell.interp.revision + \
'Python Version: %s\n' % sys.version.split()[0] + \
'wxPython Version: %s\n' % wx.__version__ + \
'Platform: %s\n' % sys.platform
dialog = wx.wxMessageDialog(self, text, title,
wx.wxOK | wx.wxICON_INFORMATION)
dialog.ShowModal()
dialog.Destroy()
def OnAutoCompleteShow(self, event):
self.shell.autoComplete = event.IsChecked()
def OnAutoCompleteIncludeMagic(self, event):
self.shell.autoCompleteIncludeMagic = event.IsChecked()
def OnAutoCompleteIncludeSingle(self, event):
self.shell.autoCompleteIncludeSingle = event.IsChecked()
def OnAutoCompleteIncludeDouble(self, event):
self.shell.autoCompleteIncludeDouble = event.IsChecked()
def OnCallTipsShow(self, event):
self.shell.autoCallTip = event.IsChecked()
def OnWrap(self, event):
self.shell.SetWrapMode(event.IsChecked())
def OnUpdateMenu(self, event):
"""Update menu items based on current status."""
id = event.GetId()
if id == wx.wxID_UNDO:
event.Enable(self.shell.CanUndo())
elif id == wx.wxID_REDO:
event.Enable(self.shell.CanRedo())
elif id == wx.wxID_CUT:
event.Enable(self.shell.CanCut())
elif id == wx.wxID_COPY:
event.Enable(self.shell.CanCopy())
elif id == ID_COPY_PLUS:
event.Enable(self.shell.CanCopy())
elif id == wx.wxID_PASTE:
event.Enable(self.shell.CanPaste())
elif id == ID_PASTE_PLUS:
event.Enable(self.shell.CanPaste())
elif id == wx.wxID_CLEAR:
event.Enable(self.shell.CanCut())
elif id == ID_AUTOCOMP_SHOW:
event.Check(self.shell.autoComplete)
elif id == ID_AUTOCOMP_INCLUDE_MAGIC:
event.Check(self.shell.autoCompleteIncludeMagic)
elif id == ID_AUTOCOMP_INCLUDE_SINGLE:
event.Check(self.shell.autoCompleteIncludeSingle)
elif id == ID_AUTOCOMP_INCLUDE_DOUBLE:
event.Check(self.shell.autoCompleteIncludeDouble)
elif id == ID_CALLTIPS_SHOW:
event.Check(self.shell.autoCallTip)
elif id == ID_WRAP:
event.Check(self.shell.GetWrapMode())
+1 -50
View File
@@ -1,54 +1,5 @@
"""Wrap is a command line utility that runs a wxPython program with
additional runtime-tools, such as PyCrust."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import os
import sys
from wxPython import wx
from crust import CrustFrame as Frame
try:
True
except NameError:
True = 1==1
False = 1==0
def wrap(app):
wx.wxInitAllImageHandlers()
frame = Frame()
frame.SetSize((750, 525))
frame.Show(True)
frame.shell.interp.locals['app'] = app
app.MainLoop()
def main(argv):
if len(argv) < 2:
print "Please specify a module name."
raise SystemExit
name = argv[1]
if name[-3:] == '.py':
name = name[:-3]
module = __import__(name)
# Find the App class.
App = None
d = module.__dict__
for item in d.keys():
try:
if issubclass(d[item], wx.wxApp):
App = d[item]
except (NameError, TypeError):
pass
if App is None:
print "No App class found."
raise SystemExit
app = App()
wrap(app)
from wxPython.py.PyWrap import *
if __name__ == '__main__':
-488
View File
@@ -1,488 +0,0 @@
"""Decorator classes for documentation and shell scripting.
"""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
# These are not the real wxPython classes. These are Python versions
# for documentation purposes. They are also used to apply docstrings
# to the real wxPython classes, which are SWIG-generated wrappers for
# C-language classes.
from Base import Object
import Parameters as wx
class Sizer(Object):
""""""
def Add(self):
""""""
pass
def AddMany(self):
""""""
pass
def AddSizer(self):
""""""
pass
def AddSpacer(self):
""""""
pass
def AddWindow(self):
""""""
pass
def Clear(self):
""""""
pass
def DeleteWindows(self):
""""""
pass
def Destroy(self):
""""""
pass
def Fit(self):
""""""
pass
def FitInside(self):
""""""
pass
def GetChildren(self):
""""""
pass
def GetMinSize(self):
""""""
pass
def GetMinSizeTuple(self):
""""""
pass
def GetPosition(self):
""""""
pass
def GetPositionTuple(self):
""""""
pass
def GetSize(self):
""""""
pass
def GetSizeTuple(self):
""""""
pass
def Hide(self):
""""""
pass
def HideSizer(self):
""""""
pass
def HideWindow(self):
""""""
pass
def Insert(self):
""""""
pass
def InsertSizer(self):
""""""
pass
def InsertSpacer(self):
""""""
pass
def InsertWindow(self):
""""""
pass
def IsShown(self):
""""""
pass
def IsShownSizer(self):
""""""
pass
def IsShownWindow(self):
""""""
pass
def Layout(self):
""""""
pass
def Prepend(self):
""""""
pass
def PrependSizer(self):
""""""
pass
def PrependSpacer(self):
""""""
pass
def PrependWindow(self):
""""""
pass
def Remove(self):
""""""
pass
def RemovePos(self):
""""""
pass
def RemoveSizer(self):
""""""
pass
def RemoveWindow(self):
""""""
pass
def SetDimension(self):
""""""
pass
def SetItemMinSize(self):
""""""
pass
def SetItemMinSizePos(self):
""""""
pass
def SetItemMinSizeSizer(self):
""""""
pass
def SetItemMinSizeWindow(self):
""""""
pass
def SetMinSize(self):
""""""
pass
def SetSizeHints(self):
""""""
pass
def SetVirtualSizeHints(self):
""""""
pass
def Show(self):
""""""
pass
def ShowItems(self):
""""""
pass
def ShowSizer(self):
""""""
pass
def ShowWindow(self):
""""""
pass
def __init__(self):
""""""
pass
def _setOORInfo(self):
""""""
pass
class SizerItem(Object):
""""""
def CalcMin(self):
""""""
pass
def DeleteWindows(self):
""""""
pass
def GetBorder(self):
""""""
pass
def GetFlag(self):
""""""
pass
def GetOption(self):
""""""
pass
def GetPosition(self):
""""""
pass
def GetRatio(self):
""""""
pass
def GetSize(self):
""""""
pass
def GetSizer(self):
""""""
pass
def GetUserData(self):
""""""
pass
def GetWindow(self):
""""""
pass
def IsShown(self):
""""""
pass
def IsSizer(self):
""""""
pass
def IsSpacer(self):
""""""
pass
def IsWindow(self):
""""""
pass
def SetBorder(self):
""""""
pass
def SetDimension(self):
""""""
pass
def SetFlag(self):
""""""
pass
def SetInitSize(self):
""""""
pass
def SetOption(self):
""""""
pass
def SetRatio(self):
""""""
pass
def SetRatioSize(self):
""""""
pass
def SetRatioWH(self):
""""""
pass
def SetSizer(self):
""""""
pass
def SetWindow(self):
""""""
pass
def Show(self):
""""""
pass
def __init__(self):
""""""
pass
class BoxSizer(Sizer):
""""""
def CalcMin(self):
""""""
pass
def GetOrientation(self):
""""""
pass
def RecalcSizes(self):
""""""
pass
def SetOrientation(self):
""""""
pass
def __init__(self):
""""""
pass
class GridSizer(Sizer):
""""""
def CalcMin(self):
""""""
pass
def GetCols(self):
""""""
pass
def GetHGap(self):
""""""
pass
def GetRows(self):
""""""
pass
def GetVGap(self):
""""""
pass
def RecalcSizes(self):
""""""
pass
def SetCols(self):
""""""
pass
def SetHGap(self):
""""""
pass
def SetRows(self):
""""""
pass
def SetVGap(self):
""""""
pass
def __init__(self):
""""""
pass
class FlexGridSizer(GridSizer):
""""""
def AddGrowableCol(self):
""""""
pass
def AddGrowableRow(self):
""""""
pass
def CalcMin(self):
""""""
pass
def RecalcSizes(self):
""""""
pass
def RemoveGrowableCol(self):
""""""
pass
def RemoveGrowableRow(self):
""""""
pass
def __init__(self):
""""""
pass
class NotebookSizer(Sizer):
""""""
def CalcMin(self):
""""""
pass
def GetNotebook(self):
""""""
pass
def RecalcSizes(self):
""""""
pass
def __init__(self):
""""""
pass
class PySizer(Sizer):
""""""
def __init__(self):
""""""
pass
def _setCallbackInfo(self):
""""""
pass
class StaticBoxSizer(BoxSizer):
""""""
def CalcMin(self):
""""""
pass
def GetStaticBox(self):
""""""
pass
def RecalcSizes(self):
""""""
pass
def __init__(self):
""""""
pass
+201
View File
@@ -0,0 +1,201 @@
#----------------------------------------------------------------------
# Name: wxPython.lib.analogclock
# Purpose: A simple analog clock window
#
# Author: several folks on wxPython-users
#
# Created: 16-April-2003
# RCS-ID: $Id$
# Copyright: (c) 2003 by Total Control Software
# Licence: wxWindows license
#----------------------------------------------------------------------
import math, sys, string, time
from wxPython.wx import *
class AnalogClockWindow(wxWindow):
"""A simple analog clock window"""
TICKS_NONE = 0
TICKS_SQUARE = 1
TICKS_CIRCLE = 2
def __init__(self, parent, ID=-1, pos=wxDefaultPosition, size=wxDefaultSize,
style=0, name="clock"):
# Initialize the wxWindow...
wxWindow.__init__(self, parent, ID, pos, size, style, name)
# Initialize the default clock settings...
self.minuteMarks = 60
self.hourMarks = 12
self.tickMarksBrushC = self.GetForegroundColour()
self.tickMarksPenC = self.GetForegroundColour()
self.tickMarkStyle = self.TICKS_SQUARE
# Make an initial bitmap for the face, it will be updated and
# painted at the first EVT_SIZE event.
W, H = size
self.faceBitmap = wxEmptyBitmap(max(W,1), max(H,1))
# Initialize the timer that drives the update of the clock
# face. Update every half second to ensure that there is at
# least one true update during each realtime second.
self.timer = wxTimer(self)
self.timer.Start(500)
# Set event handlers...
EVT_PAINT(self, self.OnPaint)
EVT_ERASE_BACKGROUND(self, lambda x: None)
EVT_SIZE(self, self.OnSize)
EVT_TIMER(self, -1, self.OnTimerExpire)
EVT_WINDOW_DESTROY(self, self.OnQuit)
def SetTickMarkStyle(self, style):
"""
Set the style of the marks around the edge of the clock.
Options are TICKS_NONE, TICKS_SQUARE, and TICKS_CIRCLE
"""
self.tickMarkStyle = style
def SetTickMarkColours(self, brushC, penC="BLACK"):
"""
Set the brush colour and optionally the pen colour of
the marks around the edge of the clock.
"""
self.tickMarksBrushC = brushC
self.tickMarksPenC = penC
SetTickMarkColour = SetTickMarkColours
def SetHandsColour(self, c):
"""An alias for SetForegroundColour"""
self.SetForegroundColour(c) # the hands just use the foreground colour
# Using the current settings, render the points and line endings for the
# circle inside the specified device context. In this case, the DC is
# a memory based device context that will be blitted to the actual
# display DC inside the OnPaint() event handler.
def OnSize(self, event):
# The faceBitmap init is done here, to make sure the buffer is always
# the same size as the Window
size = self.GetClientSize()
self.faceBitmap = wxEmptyBitmap(size.width, size.height)
self.DrawFace()
def OnPaint(self, event):
self.DrawHands(wxPaintDC(self))
def OnQuit(self, event):
self.timer.Stop()
del self.timer
def OnTimerExpire(self, event):
self.DrawHands(wxClientDC(self))
def DrawHands(self, drawDC):
# Start by drawing the face bitmap
drawDC.DrawBitmap(self.faceBitmap,0,0)
currentTime = time.localtime(time.time())
hour, minutes, seconds = currentTime[3:6]
W,H = self.faceBitmap.GetWidth(), self.faceBitmap.GetHeight()
centerX = W / 2
centerY = H / 2
radius = min(centerX, centerY)
hour += minutes / 60.0 # added so the hour hand moves continuously
x, y = self.point(hour, 12, (radius * .65))
hourX, hourY = (x + centerX), (centerY - y)
x, y = self.point(minutes, 60, (radius * .85))
minutesX, minutesY = (x + centerX), (centerY - y)
x, y = self.point(seconds, 60, (radius * .85))
secondsX, secondsY = (x + centerX), (centerY - y)
# Draw the hour hand...
drawDC.SetPen(wxPen(self.GetForegroundColour(), 5, wxSOLID))
drawDC.DrawLine(centerX, centerY, hourX, hourY)
# Draw the minutes hand...
drawDC.SetPen(wxPen(self.GetForegroundColour(), 3, wxSOLID))
drawDC.DrawLine(centerX, centerY, minutesX, minutesY)
# Draw the seconds hand...
drawDC.SetPen(wxPen(self.GetForegroundColour(), 1, wxSOLID))
drawDC.DrawLine(centerX, centerY, secondsX, secondsY)
# Draw the specified set of line marks inside the clock face for the
# hours or minutes...
def DrawFace(self):
backgroundBrush = wxBrush(self.GetBackgroundColour(), wxSOLID)
drawDC = wxMemoryDC()
drawDC.SelectObject(self.faceBitmap)
drawDC.SetBackground(backgroundBrush)
drawDC.Clear()
W,H = self.faceBitmap.GetWidth(), self.faceBitmap.GetHeight()
centerX = W / 2
centerY = H / 2
# Draw the marks for hours and minutes...
self.DrawTimeMarks(drawDC, self.minuteMarks, centerX, centerY, 4)
self.DrawTimeMarks(drawDC, self.hourMarks, centerX, centerY, 9)
def DrawTimeMarks(self, drawDC, markCount, centerX, centerY, markSize):
for i in range(markCount):
x, y = self.point(i + 1, markCount, min(centerX,centerY) - 16)
scaledX = x + centerX - markSize/2
scaledY = centerY - y - markSize/2
drawDC.SetBrush(wxBrush(self.tickMarksBrushC, wxSOLID))
drawDC.SetPen(wxPen(self.tickMarksPenC, 1, wxSOLID))
if self.tickMarkStyle != self.TICKS_NONE:
if self.tickMarkStyle == self.TICKS_CIRCLE:
drawDC.DrawEllipse(scaledX - 2, scaledY, markSize, markSize)
else:
drawDC.DrawRectangle(scaledX - 3, scaledY, markSize, markSize)
def point(self, tick, range, radius):
angle = tick * (360.0 / range)
radiansPerDegree = math.pi / 180
pointX = int(round(radius * math.sin(angle * radiansPerDegree)))
pointY = int(round(radius * math.cos(angle * radiansPerDegree)))
return wxPoint(pointX, pointY)
if __name__ == "__main__":
class App(wxApp):
def OnInit(self):
frame = wxFrame(None, -1, "AnalogClockWindow Test", size=(375,375))
clock = AnalogClockWindow(frame)
clock.SetTickMarkColours("RED")
clock.SetHandsColour("WHITE")
clock.SetBackgroundColour("BLUE")
frame.Centre(wxBOTH)
frame.Show(True)
self.SetTopWindow(frame)
return true
theApp = App(0)
theApp.MainLoop()
+5 -5
View File
@@ -716,12 +716,12 @@ class CalenDlg(wxDialog):
monthlist = GetMonthList()
# select the month
mID = NewId()
mID = wxNewId()
self.date = wxComboBox(self, mID, Month[start_month], wxPoint(20, 20), wxSize(90, -1), monthlist, wxCB_DROPDOWN)
EVT_COMBOBOX(self, mID, self.EvtComboBox)
# alternate spin button to control the month
mID = NewId()
mID = wxNewId()
h = self.date.GetSize().height
self.m_spin = wxSpinButton(self, mID, wxPoint(130, 20), wxSize(h*2, h), wxSP_VERTICAL)
self.m_spin.SetRange(1, 12)
@@ -730,7 +730,7 @@ class CalenDlg(wxDialog):
EVT_SPIN(self, mID, self.OnMonthSpin)
# spin button to control the year
mID = NewId()
mID = wxNewId()
self.dtext = wxTextCtrl(self, -1, str(start_year), wxPoint(160, 20), wxSize(60, -1))
h = self.dtext.GetSize().height
@@ -746,11 +746,11 @@ class CalenDlg(wxDialog):
y_pos = 280
but_size = wxSize(60, 25)
mID = NewId()
mID = wxNewId()
wxButton(self, mID, ' Ok ', wxPoint(x_pos, y_pos), but_size)
EVT_BUTTON(self, mID, self.OnOk)
mID = NewId()
mID = wxNewId()
wxButton(self, mID, ' Close ', wxPoint(x_pos + 120, y_pos), but_size)
EVT_BUTTON(self, mID, self.OnCancel)
+4 -3
View File
@@ -33,15 +33,16 @@ class wxScrolledMessageDialog(wx.wxDialog):
class wxMultipleChoiceDialog(wx.wxDialog):
def __init__(self, parent, msg, title, lst, pos = wx.wxDefaultPosition, size = (200,200)):
wx.wxDialog.__init__(self, parent, -1, title, pos, size)
def __init__(self, parent, msg, title, lst, pos = wx.wxDefaultPosition,
size = (200,200), style = wx.wxDEFAULT_DIALOG_STYLE):
wx.wxDialog.__init__(self, parent, -1, title, pos, size, style)
x, y = pos
if x == -1 and y == -1:
self.CenterOnScreen(wx.wxBOTH)
dc = wx.wxClientDC(self)
height = 0
for line in msg.splitlines():
height = height + dc.GetTextExtent(msg)[1] + 4
height = height + dc.GetTextExtent(line)[1] + 2
stat = wx.wxStaticText(self, -1, msg)
self.lbox = wx.wxListBox(self, 100, wx.wxDefaultPosition,
wx.wxDefaultSize, lst, wx.wxLB_MULTIPLE)
+3 -4
View File
@@ -8,7 +8,7 @@
#
# Created: 12-December-2002
# RCS-ID: $Id$
# Copyright: (c) 2002 by Robb Shecter <robb@acm.org>
# Copyright: (c) 2003 by db-X Corporation
# Licence: wxWindows license
#---------------------------------------------------------------------------
@@ -32,7 +32,6 @@ programmer to declare or track control ids or parent containers:
This module is Python 2.1+ compatible.
Author: Robb Shecter
"""
from wxPython import wx
import pubsub
@@ -176,7 +175,7 @@ class EventManager:
Return a dictionary with data about my state.
"""
stats = {}
stats['Adapters: Message'] = reduce(lambda x,y: x+y, map(len, self.messageAdapterDict.values()))
stats['Adapters: Message'] = reduce(lambda x,y: x+y, [0] + map(len, self.messageAdapterDict.values()))
stats['Adapters: Event'] = len(self.eventAdapterDict)
stats['Topics: Total'] = len(self.__getTopics())
stats['Topics: Dead'] = len(self.GetDeadTopics())
@@ -193,7 +192,7 @@ class EventManager:
is a problem.
"""
for topic in self.GetDeadTopics():
self.DeregisterTopic(topic)
self.__deregisterTopic(topic)
def GetDeadTopics(self):
+1
View File
@@ -133,6 +133,7 @@ class ImageDialog(wxDialog):
size = wxSize(80, 25)
self.set_dir = os.getcwd()
self.set_file = None
if set_dir != None:
if os.path.exists(set_dir): # set to working directory if nothing set
+2 -2
View File
@@ -130,12 +130,12 @@ class _MyStatusBar(wxStatusBar):
self.SetStatusText("",0)
ID = NewId()
ID = wxNewId()
self.button1 = wxButton(self,ID,"Dismiss",
style=wxTAB_TRAVERSAL)
EVT_BUTTON(self,ID,self.OnButton1)
ID = NewId()
ID = wxNewId()
if not useopenbutton:
self.button2 = wxButton(self,ID,"Close File",
style=wxTAB_TRAVERSAL)
+44 -16
View File
@@ -338,17 +338,18 @@ class wxIntCtrl(wxTextCtrl):
wxIntCtrl(
parent, id = -1,
value = 0,
pos = wxDefaultPosition,
size = wxDefaultSize,
style = 0,
validator = wxDefaultValidator,
name = "integer",
min = None,
max = None,
limited = False,
allow_none = False,
allow_long = False,
default_color = wxBLACK,
oob_color = wxRED,
pos = wxDefaultPosition,
size = wxDefaultSize,
style = 0,
name = "integer")
oob_color = wxRED )
value
If no initial value is set, the default will be zero, or
@@ -390,14 +391,22 @@ class wxIntCtrl(wxTextCtrl):
oob_color
Color value used for out-of-bounds values of the control
when the bounds are set but the control is not limited.
validator
Normally None, wxIntCtrl uses its own validator to do value
validation and input control. However, a validator derived
from wxIntValidator can be supplied to override the data
transfer methods for the wxIntValidator class.
"""
def __init__ (
self, parent, id=-1,
pos = wxDefaultPosition, size = wxDefaultSize,
style = 0, validator = wxDefaultValidator,
name = "integer",
value = 0, min=None, max=None,
limited = 0, allow_none = 0, allow_long = 0,
default_color = wxBLACK, oob_color = wxRED,
pos = wxDefaultPosition, size = wxDefaultSize,
style = 0, name = "integer",
):
# Establish attrs required for any operation on value:
@@ -408,10 +417,14 @@ class wxIntCtrl(wxTextCtrl):
self.__oob_color = wxRED
self.__allow_none = 0
self.__allow_long = 0
self.__oldvalue = None
if validator == wxDefaultValidator:
validator = wxIntValidator()
wxTextCtrl.__init__(
self, parent, id, self._toGUI(0),
pos, size, style, wxIntValidator(), name )
pos, size, style, validator, name )
# The following lets us set out our "integer update" events:
EVT_TEXT( self, self.GetId(), self.OnText )
@@ -424,20 +437,28 @@ class wxIntCtrl(wxTextCtrl):
self.SetNoneAllowed(allow_none)
self.SetLongAllowed(allow_long)
self.SetValue(value)
self.__oldvalue = 0
def OnText( self, event ):
"""
Handles an event indicating that the text control's value
has changed, and issue EVT_INT event.
NOTE: using wxTextCtrl.SetValue() to change the control's
contents from within a EVT_CHAR handler can cause double
text events. So we check for actual changes to the text
before passing the events on.
"""
try:
self.GetEventHandler().ProcessEvent(
wxIntUpdatedEvent( self.GetId(), self.GetValue(), self ) )
except ValueError:
return
# let normal processing of the text continue
event.Skip()
value = self.GetValue()
if value != self.__oldvalue:
try:
self.GetEventHandler().ProcessEvent(
wxIntUpdatedEvent( self.GetId(), self.GetValue(), self ) )
except ValueError:
return
# let normal processing of the text continue
event.Skip()
self.__oldvalue = value # record for next event
def GetValue(self):
@@ -719,6 +740,13 @@ class wxIntCtrl(wxTextCtrl):
"""
Conversion function used in getting the value of the control.
"""
# One or more of the underlying text control implementations
# issue an intermediate EVT_TEXT when replacing the control's
# value, where the intermediate value is an empty string.
# So, to ensure consistency and to prevent spurious ValueErrors,
# we make the following test, and react accordingly:
#
if value == '':
if not self.IsNoneAllowed():
return 0
@@ -811,7 +839,7 @@ if __name__ == '__main__':
style = wxDEFAULT_DIALOG_STYLE ):
wxDialog.__init__(self, parent, id, title, pos, size, style)
self.int_ctrl = wxIntCtrl(self, NewId(), size=(55,20))
self.int_ctrl = wxIntCtrl(self, wxNewId(), size=(55,20))
self.OK = wxButton( self, wxID_OK, "OK")
self.Cancel = wxButton( self, wxID_CANCEL, "Cancel")
File diff suppressed because it is too large Load Diff
+13 -6
View File
@@ -1,14 +1,21 @@
#---------------------------------------------------------------------------
# Name: wxPython.lib.mixins.rubberband
# Purpose: A mixin class for doing "RubberBand"-ing on a window.
#
# Author: Robb Shecter and members of wxPython-users
#
# Created: 11-September-2002
# RCS-ID: $Id$
# Copyright: (c) 2002 by db-X Corporation
# Licence: wxWindows license
#---------------------------------------------------------------------------
"""
A mixin class for doing "RubberBand"-ing on a window.
by "Robb Shecter" <rs@onsitetech.com>
$Id$
"""
from wxPython.wx import *
import Image
#
# Some miscellaneous mathematical and geometrical functions
+7 -1
View File
@@ -140,7 +140,7 @@ class PopButton(wxPyControl):
# Tried to use wxPopupWindow but the control misbehaves on MSW
class wxPopupDialog(wxDialog):
def __init__(self,parent,content = None):
wxDialog.__init__(self,parent,-1,'', style = wxSTAY_ON_TOP)
wxDialog.__init__(self,parent,-1,'', style = wxBORDER_SIMPLE|wxSTAY_ON_TOP)
self.ctrl = parent
self.win = wxWindow(self,-1,pos = wxPoint(0,0),style = 0)
@@ -197,6 +197,12 @@ class wxPopupControl(wxPyControl):
EVT_SIZE(self,self.OnSize)
EVT_BUTTON(self.bCtrl,self.bCtrl.GetId(),self.OnButton)
# embedded control should get focus on TAB keypress
EVT_SET_FOCUS(self,self.OnFocus)
def OnFocus(self,evt):
self.textCtrl.SetFocus()
evt.Skip()
def OnSize(self,evt):
w,h = self.GetClientSizeTuple()
+1 -1
View File
@@ -6,7 +6,7 @@
#
# Created: 12-December-2002
# RCS-ID: $Id$
# Copyright: (c) 2002 by Robb Shecter <robb@acm.org>
# Copyright: (c) 2002 by db-X Corporation
# Licence: wxWindows license
#---------------------------------------------------------------------------
"""
+9
View File
@@ -28,6 +28,9 @@ Hope this can help someone, as much as this list helps me.
Josu Oyanguren
Ubera Servicios Informáticos.
P.S. This only works well on wxMSW.
"""
from wxPython.wx import *
@@ -51,6 +54,12 @@ class wxRightTextCtrl(wxTextCtrl):
y = (dcheight - textheight) / 2
x = dcwidth - textwidth - 2
if self.IsEnabled():
fclr = self.GetForegroundColour()
else:
fclr = wxSystemSettings_GetColour(wxSYS_COLOUR_GRAYTEXT)
dc.SetTextForeground(fclr)
dc.SetClippingRegion(0, 0, dcwidth, dcheight)
dc.DrawText(text, x, y)
+14 -4
View File
@@ -27,8 +27,10 @@ as a proper class (and the demo is now converted to just use it.)
pos=pos, size=size,
style=style, name=name)
EVT_CHILD_FOCUS(self, self.OnChildFocus)
def SetupScrolling(self, scroll_x=True, scroll_y=True, rate_x=1, rate_y=1):
def SetupScrolling(self, scroll_x=True, scroll_y=True, rate_x=20, rate_y=20):
"""
This function sets up the event handling necessary to handle
scrolling properly. It should be called within the __init__
@@ -42,10 +44,18 @@ as a proper class (and the demo is now converted to just use it.)
if not scroll_x: rate_x = 0
if not scroll_y: rate_y = 0
self.SetScrollRate(rate_x, rate_y)
# Round up the virtual size to be a multiple of the scroll rate
sizer = self.GetSizer()
if sizer:
w, h = sizer.GetMinSize()
if rate_x:
w += rate_x - (w % rate_x)
if rate_y:
h += rate_y - (h % rate_y)
self.SetVirtualSize( (w, h) )
self.SetVirtualSizeHints( w, h )
self.GetSizer().SetVirtualSizeHints(self)
EVT_CHILD_FOCUS(self, self.OnChildFocus)
self.SetScrollRate(rate_x, rate_y)
wxCallAfter(self.Scroll, 0, 0) # scroll back to top after initial events
+14 -6
View File
@@ -26,7 +26,8 @@ class wxGenStaticText(wxPyControl):
pos = wxDefaultPosition, size = wxDefaultSize,
style = 0,
name = "genstattext"):
wxPyControl.__init__(self, parent, ID, pos, size, style, wxDefaultValidator, name)
wxPyControl.__init__(self, parent, ID, pos, size, style|wxNO_BORDER,
wxDefaultValidator, name)
wxPyControl.SetLabel(self, label) # don't check wxST_NO_AUTORESIZE yet
self.SetPosition(pos)
@@ -35,10 +36,10 @@ class wxGenStaticText(wxPyControl):
font = wxSystemSettings_GetSystemFont(wxSYS_DEFAULT_GUI_FONT)
wxPyControl.SetFont(self, font) # same here
clr = parent.GetBackgroundColour()
if not clr.Ok():
clr = wxSystemSettings_GetSystemColour(wxSYS_COLOUR_BTNFACE)
self.SetBackgroundColour(clr)
self.defBackClr = parent.GetBackgroundColour()
if not self.defBackClr.Ok():
self.defBackClr = wxSystemSettings_GetSystemColour(wxSYS_COLOUR_3DFACE)
self.SetBackgroundColour(self.defBackClr)
clr = parent.GetForegroundColour()
if not clr.Ok():
@@ -105,7 +106,14 @@ class wxGenStaticText(wxPyControl):
width, height = self.GetClientSize()
if not width or not height:
return
dc.SetBackground(wxBrush(self.GetBackgroundColour(), wxSOLID))
clr = self.GetBackgroundColour()
backBrush = wxBrush(clr, wxSOLID)
if wxPlatform == "__WXMAC__" and clr == self.defBackClr:
# if colour still the default the use the striped background on Mac
backBrush.SetMacTheme(1) # 1 == kThemeBrushDialogBackgroundActive
dc.SetBackground(backBrush)
dc.SetTextForeground(self.GetForegroundColour())
dc.Clear()
dc.SetFont(self.GetFont())
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

+43
View File
@@ -0,0 +1,43 @@
"""PyAlaCarte is a simple programmer's editor."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import os
import sys
import editor
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.App):
"""PyAlaCarte standalone application."""
def __init__(self, filename=None):
self.filename = filename
wx.App.__init__(self, redirect=False)
def OnInit(self):
wx.InitAllImageHandlers()
self.frame = editor.EditorFrame(filename=self.filename)
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(filename=None):
if not filename and len(sys.argv) > 1:
filename = sys.argv[1]
if filename:
filename = os.path.realpath(filename)
app = App(filename)
app.MainLoop()
if __name__ == '__main__':
main()
+43
View File
@@ -0,0 +1,43 @@
"""PyAlaMode is a programmer's editor."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import os
import sys
import editor
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.App):
"""PyAlaMode standalone application."""
def __init__(self, filename=None):
self.filename = filename
wx.App.__init__(self, redirect=False)
def OnInit(self):
wx.InitAllImageHandlers()
self.frame = editor.EditorNotebookFrame(filename=self.filename)
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(filename=None):
if not filename and len(sys.argv) > 1:
filename = sys.argv[1]
if filename:
filename = os.path.realpath(filename)
app = App(filename)
app.MainLoop()
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
"""PyAlaModeTest is a programmer's editor."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import os
import sys
import editor
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.App):
"""PyAlaModeTest standalone application."""
def __init__(self, filename=None):
self.filename = filename
wx.App.__init__(self, redirect=False)
def OnInit(self):
wx.InitAllImageHandlers()
self.frame = editor.EditorShellNotebookFrame(filename=self.filename)
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(filename=None):
app = App(filename)
app.MainLoop()
if __name__ == '__main__':
filename = None
if len(sys.argv) > 1:
filename = os.path.realpath(sys.argv[1])
main(filename)
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

+78
View File
@@ -0,0 +1,78 @@
"""PyCrust is a python shell and namespace browser application."""
# The next two lines, and the other code below that makes use of
# ``__main__`` and ``original``, serve the purpose of cleaning up the
# main namespace to look as much as possible like the regular Python
# shell environment.
import __main__
original = __main__.__dict__.keys()
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.App):
"""PyCrust standalone application."""
def OnInit(self):
import wx
wx.InitAllImageHandlers()
locals = __main__.__dict__
from crust import CrustFrame
self.frame = CrustFrame(locals=locals)
self.frame.SetSize((800, 600))
self.frame.Show()
self.SetTopWindow(self.frame)
return True
'''
The main() function needs to handle being imported, such as with the
pycrust script that wxPython installs:
#!/usr/bin/env python
from wx.py.PyCrust import main
main()
'''
def main():
"""The main function for the PyCrust program."""
# Cleanup the main namespace, leaving the App class.
import __main__
md = __main__.__dict__
keepers = original
keepers.append('App')
for key in md.keys():
if key not in keepers:
del md[key]
# Create an application instance.
app = App(0)
# Mimic the contents of the standard Python shell's sys.path.
import sys
if sys.path[0]:
sys.path[0] = ''
# Add the application object to the sys module's namespace.
# This allows a shell user to do:
# >>> import sys
# >>> sys.app.whatever
sys.app = app
del sys
# Cleanup the main namespace some more.
if md.has_key('App') and md['App'] is App:
del md['App']
if md.has_key('__main__') and md['__main__'] is __main__:
del md['__main__']
# Start the wxPython event loop.
app.MainLoop()
if __name__ == '__main__':
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 706 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+43
View File
@@ -0,0 +1,43 @@
"""PyFilling is a python namespace inspection application."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
# We use this object to get more introspection when run standalone.
app = None
import filling
# These are imported just to have something interesting to inspect.
import crust
import interpreter
import introspect
import pseudo
import shell
import sys
import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(filling.App):
def OnInit(self):
filling.App.OnInit(self)
self.root = self.fillingFrame.filling.tree.root
return True
def main():
"""Create and run the application."""
global app
app = App(0)
app.fillingFrame.filling.tree.Expand(app.root)
app.MainLoop()
if __name__ == '__main__':
main()
+79
View File
@@ -0,0 +1,79 @@
"""PyShell is a python shell application."""
# The next two lines, and the other code below that makes use of
# ``__main__`` and ``original``, serve the purpose of cleaning up the
# main namespace to look as much as possible like the regular Python
# shell environment.
import __main__
original = __main__.__dict__.keys()
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
try:
True
except NameError:
True = 1==1
False = 1==0
class App(wx.App):
"""PyShell standalone application."""
def OnInit(self):
import wx
wx.InitAllImageHandlers()
locals = __main__.__dict__
from shell import ShellFrame
self.frame = ShellFrame(locals=locals)
self.frame.SetSize((750, 525))
self.frame.Show()
self.SetTopWindow(self.frame)
self.frame.shell.SetFocus()
return True
'''
The main() function needs to handle being imported, such as with the
pyshell script that wxPython installs:
#!/usr/bin/env python
from wx.py.PyShell import main
main()
'''
def main():
"""The main function for the PyShell program."""
# Cleanup the main namespace, leaving the App class.
import __main__
md = __main__.__dict__
keepers = original
keepers.append('App')
for key in md.keys():
if key not in keepers:
del md[key]
# Create an application instance.
app = App(0)
# Cleanup the main namespace some more.
if md.has_key('App') and md['App'] is App:
del md['App']
if md.has_key('__main__') and md['__main__'] is __main__:
del md['__main__']
# Mimic the contents of the standard Python shell's sys.path.
import sys
if sys.path[0]:
sys.path[0] = ''
# Add the application object to the sys module's namespace.
# This allows a shell user to do:
# >>> import sys
# >>> sys.app.whatever
sys.app = app
del sys
# Start the wxPython event loop.
app.MainLoop()
if __name__ == '__main__':
main()
+56
View File
@@ -0,0 +1,56 @@
"""PyWrap is a command line utility that runs a wxPython program with
additional runtime-tools, such as PyCrust."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import os
import sys
import wx
from crust import CrustFrame as Frame
try:
True
except NameError:
True = 1==1
False = 1==0
def wrap(app):
wx.InitAllImageHandlers()
frame = Frame()
frame.SetSize((750, 525))
frame.Show(True)
frame.shell.interp.locals['app'] = app
app.MainLoop()
def main(modulename=None):
sys.path.insert(0, os.curdir)
if not modulename:
if len(sys.argv) < 2:
print "Please specify a module name."
raise SystemExit
modulename = sys.argv[1]
if modulename.endswith('.py'):
modulename = modulename[:-3]
module = __import__(modulename)
# Find the App class.
App = None
d = module.__dict__
for item in d.keys():
try:
if issubclass(d[item], wx.App):
App = d[item]
except (NameError, TypeError):
pass
if App is None:
print "No App class found."
raise SystemExit
app = App()
wrap(app)
if __name__ == '__main__':
main()
+20
View File
@@ -0,0 +1,20 @@
"""The py package, formerly the PyCrust package."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import buffer
import crust
import dispatcher
import document
import editor
import editwindow
import filling
import frame
import images
import interpreter
import introspect
import pseudo
import shell
import version
+144
View File
@@ -0,0 +1,144 @@
"""Buffer class."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
from interpreter import Interpreter
import imp
import os
import sys
import document
try:
True
except NameError:
True = 1==1
False = 1==0
class Buffer:
"""Buffer class."""
id = 0
def __init__(self, filename=None):
"""Create a Buffer instance."""
Buffer.id += 1
self.id = Buffer.id
self.interp = Interpreter(locals={})
self.name = ''
self.editors = {}
self.editor = None
self.modules = sys.modules.keys()
self.syspath = sys.path[:]
while True:
try:
self.syspath.remove('')
except ValueError:
break
while True:
try:
self.syspath.remove('.')
except ValueError:
break
self.open(filename)
def addEditor(self, editor):
"""Add an editor."""
self.editor = editor
self.editors[editor.id] = editor
def hasChanged(self):
"""Return True if text in editor has changed since last save."""
if self.editor:
return self.editor.hasChanged()
else:
return False
def new(self, filepath):
"""New empty buffer."""
if not filepath:
return
if os.path.exists(filepath):
self.confirmed = self.overwriteConfirm(filepath)
else:
self.confirmed = True
def open(self, filename):
"""Open file into buffer."""
self.doc = document.Document(filename)
self.name = self.doc.filename or ('Untitled:' + str(self.id))
self.modulename = self.doc.filebase
# XXX This should really make sure filedir is first item in syspath.
# XXX Or maybe this should be moved to the update namespace method.
if self.doc.filedir and self.doc.filedir not in self.syspath:
# To create the proper context for updateNamespace.
self.syspath.insert(0, self.doc.filedir)
if self.doc.filepath and os.path.exists(self.doc.filepath):
self.confirmed = True
if self.editor:
text = self.doc.read()
self.editor._setBuffer(buffer=self, text=text)
def overwriteConfirm(filepath):
"""Confirm overwriting an existing file."""
return False
def save(self):
"""Save buffer."""
filepath = self.doc.filepath
if not filepath:
return # XXX Get filename
if not os.path.exists(filepath):
self.confirmed = True
if not self.confirmed:
self.confirmed = self.overwriteConfirm(filepath)
if self.confirmed:
self.doc.write(self.editor.getText())
if self.editor:
self.editor.setSavePoint()
def saveAs(self, filename):
"""Save buffer."""
self.doc = document.Document(filename)
self.name = self.doc.filename
self.modulename = self.doc.filebase
self.save()
def updateNamespace(self):
"""Update the namespace for autocompletion and calltips.
Return True if updated, False if there was an error."""
if not self.interp or not hasattr(self.editor, 'getText'):
return False
syspath = sys.path
sys.path = self.syspath
text = self.editor.getText()
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
name = self.modulename or self.name
module = imp.new_module(name)
newspace = module.__dict__.copy()
try:
try:
code = compile(text, name, 'exec')
except:
raise
# return False
try:
exec code in newspace
except:
raise
# return False
else:
# No problems, so update the namespace.
self.interp.locals.clear()
self.interp.locals.update(newspace)
return True
finally:
sys.path = syspath
for m in sys.modules.keys():
if m not in self.modules:
del sys.modules[m]
+221
View File
@@ -0,0 +1,221 @@
"""Crust combines the shell and filling into one control."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import os
import pprint
import sys
import dispatcher
import editwindow
from filling import Filling
import frame
from shell import Shell
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
class Crust(wx.SplitterWindow):
"""Crust based on SplitterWindow."""
name = 'Crust'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.SP_3D,
name='Crust Window', rootObject=None, rootLabel=None,
rootIsNamespace=True, intro='', locals=None,
InterpClass=None, *args, **kwds):
"""Create Crust instance."""
wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)
self.shell = Shell(parent=self, introText=intro,
locals=locals, InterpClass=InterpClass,
*args, **kwds)
self.editor = self.shell
if rootObject is None:
rootObject = self.shell.interp.locals
self.notebook = wx.Notebook(parent=self, id=-1)
self.shell.interp.locals['notebook'] = self.notebook
self.filling = Filling(parent=self.notebook,
rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace)
# Add 'filling' to the interpreter's locals.
self.shell.interp.locals['filling'] = self.filling
self.notebook.AddPage(page=self.filling, text='Namespace', select=True)
self.display = Display(parent=self.notebook)
self.notebook.AddPage(page=self.display, text='Display')
# Add 'pp' (pretty print) to the interpreter's locals.
self.shell.interp.locals['pp'] = self.display.setItem
self.calltip = Calltip(parent=self.notebook)
self.notebook.AddPage(page=self.calltip, text='Calltip')
self.sessionlisting = SessionListing(parent=self.notebook)
self.notebook.AddPage(page=self.sessionlisting, text='Session')
self.dispatcherlisting = DispatcherListing(parent=self.notebook)
self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')
from wxd import wx_
self.wxdocs = Filling(parent=self.notebook,
rootObject=wx_,
rootLabel='wx',
rootIsNamespace=False,
static=True)
self.notebook.AddPage(page=self.wxdocs, text='wxPython Docs')
from wxd import stc_
self.stcdocs = Filling(parent=self.notebook,
rootObject=stc_.StyledTextCtrl,
rootLabel='StyledTextCtrl',
rootIsNamespace=False,
static=True)
self.notebook.AddPage(page=self.stcdocs, text='StyledTextCtrl Docs')
self.SplitHorizontally(self.shell, self.notebook, 300)
self.SetMinimumPaneSize(1)
class Display(editwindow.EditWindow):
"""STC used to display an object using Pretty Print."""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER,
static=False):
"""Create Display instance."""
editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
# Configure various defaults and user preferences.
self.SetReadOnly(True)
self.SetWrapMode(False)
if not static:
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
self.Refresh()
def Refresh(self):
if not hasattr(self, "item"):
return
self.SetReadOnly(False)
text = pprint.pformat(self.item)
self.SetText(text)
self.SetReadOnly(True)
def setItem(self, item):
"""Set item to pretty print in the notebook Display tab."""
self.item = item
self.Refresh()
class Calltip(wx.TextCtrl):
"""Text control containing the most recent shell calltip."""
def __init__(self, parent=None, id=-1):
style = wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH2
wx.TextCtrl.__init__(self, parent=parent, id=id, style=style)
self.SetBackgroundColour(wx.Colour(255, 255, 232))
dispatcher.connect(receiver=self.display, signal='Shell.calltip')
def display(self, calltip):
"""Receiver for Shell.calltip signal."""
self.SetValue(calltip)
class SessionListing(wx.TextCtrl):
"""Text control containing all commands for session."""
def __init__(self, parent=None, id=-1):
style = wx.TE_MULTILINE | wx.TE_READONLY | \
wx.TE_RICH2 | wx.TE_DONTWRAP
wx.TextCtrl.__init__(self, parent=parent, id=id, style=style)
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
if command and not more:
self.SetInsertionPointEnd()
start, end = self.GetSelection()
if start != end:
self.SetSelection(0, 0)
self.AppendText(command + '\n')
class DispatcherListing(wx.TextCtrl):
"""Text control containing all dispatches for session."""
def __init__(self, parent=None, id=-1):
style = wx.TE_MULTILINE | wx.TE_READONLY | \
wx.TE_RICH2 | wx.TE_DONTWRAP
wx.TextCtrl.__init__(self, parent=parent, id=id, style=style)
dispatcher.connect(receiver=self.spy)
def spy(self, signal, sender):
"""Receiver for Any signal from Any sender."""
text = '%r from %s' % (signal, sender)
self.SetInsertionPointEnd()
start, end = self.GetSelection()
if start != end:
self.SetSelection(0, 0)
self.AppendText(text + '\n')
class CrustFrame(frame.Frame):
"""Frame containing all the PyCrust components."""
name = 'CrustFrame'
revision = __revision__
def __init__(self, parent=None, id=-1, title='PyCrust',
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE,
rootObject=None, rootLabel=None, rootIsNamespace=True,
locals=None, InterpClass=None, *args, **kwds):
"""Create CrustFrame instance."""
frame.Frame.__init__(self, parent, id, title, pos, size, style)
intro = 'PyCrust %s - The Flakiest Python Shell' % VERSION
intro += '\nSponsored by Orbtech - '
intro += 'Your source for Python programming expertise.'
self.SetStatusText(intro.replace('\n', ', '))
self.crust = Crust(parent=self, intro=intro,
rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
locals=locals,
InterpClass=InterpClass, *args, **kwds)
self.shell = self.crust.shell
# Override the filling so that status messages go to the status bar.
self.crust.filling.tree.setStatusText = self.SetStatusText
# Override the shell so that status messages go to the status bar.
self.shell.setStatusText = self.SetStatusText
# Fix a problem with the sash shrinking to nothing.
self.crust.filling.SetSashPosition(200)
# Set focus to the shell editor.
self.shell.SetFocus()
def OnClose(self, event):
"""Event handler for closing."""
self.crust.shell.destroy()
self.Destroy()
def OnAbout(self, event):
"""Display an About window."""
title = 'About PyCrust'
text = 'PyCrust %s\n\n' % VERSION + \
'Yet another Python shell, only flakier.\n\n' + \
'Half-baked by Patrick K. O\'Brien,\n' + \
'the other half is still in the oven.\n\n' + \
'Shell Revision: %s\n' % self.shell.revision + \
'Interpreter Revision: %s\n\n' % self.shell.interp.revision + \
'Python Version: %s\n' % sys.version.split()[0] + \
'wxPython Version: %s\n' % wx.VERSION_STRING + \
'Platform: %s\n' % sys.platform
dialog = wx.MessageDialog(self, text, title,
wx.OK | wx.ICON_INFORMATION)
dialog.ShowModal()
dialog.Destroy()
+49
View File
@@ -0,0 +1,49 @@
"""Document class."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import os
try:
True
except NameError:
True = 1==1
False = 1==0
class Document:
"""Document class."""
def __init__(self, filename=None):
"""Create a Document instance."""
self.filename = filename
self.filepath = None
self.filedir = None
self.filebase = None
self.fileext = None
if self.filename:
self.filepath = os.path.realpath(self.filename)
self.filedir, self.filename = os.path.split(self.filepath)
self.filebase, self.fileext = os.path.splitext(self.filename)
def read(self):
"""Return contents of file."""
if self.filepath and os.path.exists(self.filepath):
f = file(self.filepath, 'rb')
try:
return f.read()
finally:
f.close()
else:
return ''
def write(self, text):
"""Write text to file."""
try:
f = file(self.filepath, 'wb')
f.write(text)
finally:
if f:
f.close()
File diff suppressed because it is too large Load Diff
+199
View File
@@ -0,0 +1,199 @@
"""EditWindow class."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
from wx import stc
import keyword
import os
import sys
import time
import dispatcher
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
if wx.Platform == '__WXMSW__':
FACES = { 'times' : 'Times New Roman',
'mono' : 'Courier New',
'helv' : 'Lucida Console',
'lucida' : 'Lucida Console',
'other' : 'Comic Sans MS',
'size' : 10,
'lnsize' : 9,
'backcol': '#FFFFFF',
}
else: # GTK
FACES = { 'times' : 'Times',
'mono' : 'Courier',
'helv' : 'Helvetica',
'other' : 'new century schoolbook',
'size' : 12,
'lnsize' : 10,
'backcol': '#FFFFFF',
}
class EditWindow(stc.StyledTextCtrl):
"""EditWindow based on StyledTextCtrl."""
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):
"""Create EditWindow instance."""
stc.StyledTextCtrl.__init__(self, parent, id, pos, size, style)
self.__config()
stc.EVT_STC_UPDATEUI(self, id, self.OnUpdateUI)
dispatcher.connect(receiver=self._fontsizer, signal='FontIncrease')
dispatcher.connect(receiver=self._fontsizer, signal='FontDecrease')
dispatcher.connect(receiver=self._fontsizer, signal='FontDefault')
def _fontsizer(self, signal):
"""Receiver for Font* signals."""
size = self.GetZoom()
if signal == 'FontIncrease':
size += 1
elif signal == 'FontDecrease':
size -= 1
elif signal == 'FontDefault':
size = 0
self.SetZoom(size)
def __config(self):
"""Configure shell based on user preferences."""
self.SetMarginType(1, stc.STC_MARGIN_NUMBER)
self.SetMarginWidth(1, 40)
self.SetLexer(stc.STC_LEX_PYTHON)
self.SetKeyWords(0, ' '.join(keyword.kwlist))
self.setStyles(FACES)
self.SetViewWhiteSpace(False)
self.SetTabWidth(4)
self.SetUseTabs(False)
# Do we want to automatically pop up command completion options?
self.autoComplete = True
self.autoCompleteIncludeMagic = True
self.autoCompleteIncludeSingle = True
self.autoCompleteIncludeDouble = True
self.autoCompleteCaseInsensitive = True
self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive)
self.AutoCompSetAutoHide(False)
self.AutoCompStops(' .,;:([)]}\'"\\<>%^&+-=*/|`')
# Do we want to automatically pop up command argument help?
self.autoCallTip = True
self.CallTipSetBackground(wx.Colour(255, 255, 232))
self.SetWrapMode(False)
try:
self.SetEndAtLastLine(False)
except AttributeError:
pass
def setStyles(self, faces):
"""Configure font size, typeface and color for lexer."""
# Default style
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
"face:%(mono)s,size:%(size)d,back:%(backcol)s" % \
faces)
self.StyleClearAll()
# Built in styles
self.StyleSetSpec(stc.STC_STYLE_LINENUMBER,
"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d" % faces)
self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR,
"face:%(mono)s" % faces)
self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT,
"fore:#0000FF,back:#FFFF88")
self.StyleSetSpec(stc.STC_STYLE_BRACEBAD,
"fore:#FF0000,back:#FFFF88")
# Python styles
self.StyleSetSpec(stc.STC_P_DEFAULT,
"face:%(mono)s" % faces)
self.StyleSetSpec(stc.STC_P_COMMENTLINE,
"fore:#007F00,face:%(mono)s" % faces)
self.StyleSetSpec(stc.STC_P_NUMBER,
"")
self.StyleSetSpec(stc.STC_P_STRING,
"fore:#7F007F,face:%(mono)s" % faces)
self.StyleSetSpec(stc.STC_P_CHARACTER,
"fore:#7F007F,face:%(mono)s" % faces)
self.StyleSetSpec(stc.STC_P_WORD,
"fore:#00007F,bold")
self.StyleSetSpec(stc.STC_P_TRIPLE,
"fore:#7F0000")
self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE,
"fore:#000033,back:#FFFFE8")
self.StyleSetSpec(stc.STC_P_CLASSNAME,
"fore:#0000FF,bold")
self.StyleSetSpec(stc.STC_P_DEFNAME,
"fore:#007F7F,bold")
self.StyleSetSpec(stc.STC_P_OPERATOR,
"")
self.StyleSetSpec(stc.STC_P_IDENTIFIER,
"")
self.StyleSetSpec(stc.STC_P_COMMENTBLOCK,
"fore:#7F7F7F")
self.StyleSetSpec(stc.STC_P_STRINGEOL,
"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled" % faces)
def OnUpdateUI(self, event):
"""Check for matching braces."""
# If the auto-complete window is up let it do its thing.
if self.AutoCompActive() or self.CallTipActive():
return
braceAtCaret = -1
braceOpposite = -1
charBefore = None
caretPos = self.GetCurrentPos()
if caretPos > 0:
charBefore = self.GetCharAt(caretPos - 1)
styleBefore = self.GetStyleAt(caretPos - 1)
# Check before.
if charBefore and chr(charBefore) in '[]{}()' \
and styleBefore == stc.STC_P_OPERATOR:
braceAtCaret = caretPos - 1
# Check after.
if braceAtCaret < 0:
charAfter = self.GetCharAt(caretPos)
styleAfter = self.GetStyleAt(caretPos)
if charAfter and chr(charAfter) in '[]{}()' \
and styleAfter == stc.STC_P_OPERATOR:
braceAtCaret = caretPos
if braceAtCaret >= 0:
braceOpposite = self.BraceMatch(braceAtCaret)
if braceAtCaret != -1 and braceOpposite == -1:
self.BraceBadLight(braceAtCaret)
else:
self.BraceHighlight(braceAtCaret, braceOpposite)
def CanCopy(self):
"""Return True if text is selected and can be copied."""
return self.GetSelectionStart() != self.GetSelectionEnd()
def CanCut(self):
"""Return True if text is selected and can be cut."""
return self.CanCopy() and self.CanEdit()
def CanEdit(self):
"""Return True if editing should succeed."""
return not self.GetReadOnly()
def CanPaste(self):
"""Return True if pasting should succeed."""
return stc.StyledTextCtrl.CanPaste(self) and self.CanEdit()
+337
View File
@@ -0,0 +1,337 @@
"""Filling is the gui tree control through which a user can navigate
the local namespace or any object."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import dispatcher
import editwindow
import inspect
import introspect
import keyword
import sys
import types
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
COMMONTYPES = [getattr(types, t) for t in dir(types) \
if not t.startswith('_') \
and t not in ('ClassType', 'InstanceType', 'ModuleType')]
DOCTYPES = ('BuiltinFunctionType', 'BuiltinMethodType', 'ClassType',
'FunctionType', 'GeneratorType', 'InstanceType',
'LambdaType', 'MethodType', 'ModuleType',
'UnboundMethodType', 'method-wrapper')
SIMPLETYPES = [getattr(types, t) for t in dir(types) \
if not t.startswith('_') and t not in DOCTYPES]
del t
try:
COMMONTYPES.append(type(''.__repr__)) # Method-wrapper in version 2.2.x.
except AttributeError:
pass
class FillingTree(wx.TreeCtrl):
"""FillingTree based on TreeCtrl."""
name = 'Filling Tree'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.TR_DEFAULT_STYLE,
rootObject=None, rootLabel=None, rootIsNamespace=False,
static=False):
"""Create FillingTree instance."""
wx.TreeCtrl.__init__(self, parent, id, pos, size, style)
self.rootIsNamespace = rootIsNamespace
import __main__
if rootObject is None:
rootObject = __main__.__dict__
self.rootIsNamespace = True
if rootObject is __main__.__dict__ and rootLabel is None:
rootLabel = 'locals()'
if not rootLabel:
rootLabel = 'Ingredients'
rootData = wx.TreeItemData(rootObject)
self.item = self.root = self.AddRoot(rootLabel, -1, -1, rootData)
self.SetItemHasChildren(self.root, self.objHasChildren(rootObject))
wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding)
wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed)
wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged)
wx.EVT_TREE_ITEM_ACTIVATED(self, self.GetId(), self.OnItemActivated)
if not static:
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
self.display()
def OnItemExpanding(self, event):
"""Add children to the item."""
busy = wx.BusyCursor()
item = event.GetItem()
if self.IsExpanded(item):
return
self.addChildren(item)
# self.SelectItem(item)
def OnItemCollapsed(self, event):
"""Remove all children from the item."""
busy = wx.BusyCursor()
item = event.GetItem()
# self.CollapseAndReset(item)
# self.DeleteChildren(item)
# self.SelectItem(item)
def OnSelChanged(self, event):
"""Display information about the item."""
busy = wx.BusyCursor()
self.item = event.GetItem()
self.display()
def OnItemActivated(self, event):
"""Launch a DirFrame."""
item = event.GetItem()
text = self.getFullName(item)
obj = self.GetPyData(item)
frame = FillingFrame(parent=self, size=(600, 100), rootObject=obj,
rootLabel=text, rootIsNamespace=False)
frame.Show()
def objHasChildren(self, obj):
"""Return true if object has children."""
if self.objGetChildren(obj):
return True
else:
return False
def objGetChildren(self, obj):
"""Return dictionary with attributes or contents of object."""
busy = wx.BusyCursor()
otype = type(obj)
if otype is types.DictType \
or str(otype)[17:23] == 'BTrees' and hasattr(obj, 'keys'):
return obj
d = {}
if otype is types.ListType or otype is types.TupleType:
for n in range(len(obj)):
key = '[' + str(n) + ']'
d[key] = obj[n]
if otype not in COMMONTYPES:
for key in introspect.getAttributeNames(obj):
# Believe it or not, some attributes can disappear,
# such as the exc_traceback attribute of the sys
# module. So this is nested in a try block.
try:
d[key] = getattr(obj, key)
except:
pass
return d
def addChildren(self, item):
self.DeleteChildren(item)
obj = self.GetPyData(item)
children = self.objGetChildren(obj)
if not children:
return
keys = children.keys()
keys.sort(lambda x, y: cmp(str(x).lower(), str(y).lower()))
for key in keys:
itemtext = str(key)
# Show string dictionary items with single quotes, except
# for the first level of items, if they represent a
# namespace.
if type(obj) is types.DictType \
and type(key) is types.StringType \
and (item != self.root \
or (item == self.root and not self.rootIsNamespace)):
itemtext = repr(key)
child = children[key]
data = wx.TreeItemData(child)
branch = self.AppendItem(parent=item, text=itemtext, data=data)
self.SetItemHasChildren(branch, self.objHasChildren(child))
def display(self):
item = self.item
if self.IsExpanded(item):
self.addChildren(item)
self.setText('')
obj = self.GetPyData(item)
if wx.Platform == '__WXMSW__':
if obj is None: # Windows bug fix.
return
self.SetItemHasChildren(item, self.objHasChildren(obj))
otype = type(obj)
text = ''
text += self.getFullName(item)
text += '\n\nType: ' + str(otype)
try:
value = str(obj)
except:
value = ''
if otype is types.StringType or otype is types.UnicodeType:
value = repr(obj)
text += '\n\nValue: ' + value
if otype not in SIMPLETYPES:
try:
text += '\n\nDocstring:\n\n"""' + \
inspect.getdoc(obj).strip() + '"""'
except:
pass
if otype is types.InstanceType:
try:
text += '\n\nClass Definition:\n\n' + \
inspect.getsource(obj.__class__)
except:
pass
else:
try:
text += '\n\nSource Code:\n\n' + \
inspect.getsource(obj)
except:
pass
self.setText(text)
def getFullName(self, item, partial=''):
"""Return a syntactically proper name for item."""
name = self.GetItemText(item)
parent = None
obj = None
if item != self.root:
parent = self.GetItemParent(item)
obj = self.GetPyData(parent)
# Apply dictionary syntax to dictionary items, except the root
# and first level children of a namepace.
if (type(obj) is types.DictType \
or str(type(obj))[17:23] == 'BTrees' \
and hasattr(obj, 'keys')) \
and ((item != self.root and parent != self.root) \
or (parent == self.root and not self.rootIsNamespace)):
name = '[' + name + ']'
# Apply dot syntax to multipart names.
if partial:
if partial[0] == '[':
name += partial
else:
name += '.' + partial
# Repeat for everything but the root item
# and first level children of a namespace.
if (item != self.root and parent != self.root) \
or (parent == self.root and not self.rootIsNamespace):
name = self.getFullName(parent, partial=name)
return name
def setText(self, text):
"""Display information about the current selection."""
# This method will likely be replaced by the enclosing app to
# do something more interesting, like write to a text control.
print text
def setStatusText(self, text):
"""Display status information."""
# This method will likely be replaced by the enclosing app to
# do something more interesting, like write to a status bar.
print text
class FillingText(editwindow.EditWindow):
"""FillingText based on StyledTextCtrl."""
name = 'Filling Text'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CLIP_CHILDREN,
static=False):
"""Create FillingText instance."""
editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
# Configure various defaults and user preferences.
self.SetReadOnly(True)
self.SetWrapMode(True)
self.SetMarginWidth(1, 0)
if not static:
dispatcher.connect(receiver=self.push, signal='Interpreter.push')
def push(self, command, more):
"""Receiver for Interpreter.push signal."""
self.Refresh()
def SetText(self, *args, **kwds):
self.SetReadOnly(False)
editwindow.EditWindow.SetText(self, *args, **kwds)
self.SetReadOnly(True)
class Filling(wx.SplitterWindow):
"""Filling based on wxSplitterWindow."""
name = 'Filling'
revision = __revision__
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.SP_3D,
name='Filling Window', rootObject=None,
rootLabel=None, rootIsNamespace=False, static=False):
"""Create a Filling instance."""
wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)
self.tree = FillingTree(parent=self, rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
static=static)
self.text = FillingText(parent=self, static=static)
self.SplitVertically(self.tree, self.text, 130)
self.SetMinimumPaneSize(1)
# Override the filling so that descriptions go to FillingText.
self.tree.setText = self.text.SetText
# Display the root item.
## self.tree.SelectItem(self.tree.root)
self.tree.display()
class FillingFrame(wx.Frame):
"""Frame containing the namespace tree component."""
name = 'Filling Frame'
revision = __revision__
def __init__(self, parent=None, id=-1, title='PyFilling',
pos=wx.DefaultPosition, size=(600, 400),
style=wx.DEFAULT_FRAME_STYLE, rootObject=None,
rootLabel=None, rootIsNamespace=False, static=False):
"""Create FillingFrame instance."""
wx.Frame.__init__(self, parent, id, title, pos, size, style)
intro = 'PyFilling - The Tastiest Namespace Inspector'
self.CreateStatusBar()
self.SetStatusText(intro)
import images
self.SetIcon(images.getPyIcon())
self.filling = Filling(parent=self, rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
static=static)
# Override so that status messages go to the status bar.
self.filling.tree.setStatusText = self.SetStatusText
class App(wx.App):
"""PyFilling standalone application."""
def OnInit(self):
wx.InitAllImageHandlers()
self.fillingFrame = FillingFrame()
self.fillingFrame.Show(True)
self.SetTopWindow(self.fillingFrame)
return True
+348
View File
@@ -0,0 +1,348 @@
"""Base frame with menu."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
from version import VERSION
try:
True
except NameError:
True = 1==1
False = 1==0
ID_NEW = wx.ID_NEW
ID_OPEN = wx.ID_OPEN
ID_REVERT = wx.ID_REVERT
ID_CLOSE = wx.ID_CLOSE
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_PRINT = wx.ID_PRINT
ID_EXIT = wx.ID_EXIT
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CLEAR = wx.ID_CLEAR
ID_SELECTALL = wx.ID_SELECTALL
ID_ABOUT = wx.ID_ABOUT
ID_AUTOCOMP = wx.NewId()
ID_AUTOCOMP_SHOW = wx.NewId()
ID_AUTOCOMP_MAGIC = wx.NewId()
ID_AUTOCOMP_SINGLE = wx.NewId()
ID_AUTOCOMP_DOUBLE = wx.NewId()
ID_CALLTIPS = wx.NewId()
ID_CALLTIPS_SHOW = wx.NewId()
ID_COPY_PLUS = wx.NewId()
ID_NAMESPACE = wx.NewId()
ID_PASTE_PLUS = wx.NewId()
ID_WRAP = wx.NewId()
class Frame(wx.Frame):
"""Frame with standard menu items."""
revision = __revision__
def __init__(self, parent=None, id=-1, title='Editor',
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE):
"""Create a Frame instance."""
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.CreateStatusBar()
self.SetStatusText('Frame')
import images
self.SetIcon(images.getPyIcon())
self.__createMenus()
wx.EVT_CLOSE(self, self.OnClose)
def OnClose(self, event):
"""Event handler for closing."""
self.Destroy()
def __createMenus(self):
m = self.fileMenu = wx.Menu()
m.Append(ID_NEW, '&New \tCtrl+N',
'New file')
m.Append(ID_OPEN, '&Open... \tCtrl+O',
'Open file')
m.AppendSeparator()
m.Append(ID_REVERT, '&Revert \tCtrl+R',
'Revert to last saved version')
m.Append(ID_CLOSE, '&Close \tCtrl+W',
'Close file')
m.AppendSeparator()
m.Append(ID_SAVE, '&Save... \tCtrl+S',
'Save file')
m.Append(ID_SAVEAS, 'Save &As \tShift+Ctrl+S',
'Save file with new name')
m.AppendSeparator()
m.Append(ID_PRINT, '&Print... \tCtrl+P',
'Print file')
m.AppendSeparator()
m.Append(ID_NAMESPACE, '&Update Namespace \tShift+Ctrl+N',
'Update namespace for autocompletion and calltips')
m.AppendSeparator()
m.Append(ID_EXIT, 'E&xit', 'Exit Program')
m = self.editMenu = wx.Menu()
m.Append(ID_UNDO, '&Undo \tCtrl+Z',
'Undo the last action')
m.Append(ID_REDO, '&Redo \tCtrl+Y',
'Redo the last undone action')
m.AppendSeparator()
m.Append(ID_CUT, 'Cu&t \tCtrl+X',
'Cut the selection')
m.Append(ID_COPY, '&Copy \tCtrl+C',
'Copy the selection')
m.Append(ID_COPY_PLUS, 'Cop&y Plus \tShift+Ctrl+C',
'Copy the selection - retaining prompts')
m.Append(ID_PASTE, '&Paste \tCtrl+V', 'Paste from clipboard')
m.Append(ID_PASTE_PLUS, 'Past&e Plus \tShift+Ctrl+V',
'Paste and run commands')
m.AppendSeparator()
m.Append(ID_CLEAR, 'Cle&ar',
'Delete the selection')
m.Append(ID_SELECTALL, 'Select A&ll \tCtrl+A',
'Select all text')
m = self.autocompMenu = wx.Menu()
m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion',
'Show auto completion list', 1)
m.Append(ID_AUTOCOMP_MAGIC, 'Include Magic Attributes',
'Include attributes visible to __getattr__ and __setattr__',
1)
m.Append(ID_AUTOCOMP_SINGLE, 'Include Single Underscores',
'Include attibutes prefixed by a single underscore', 1)
m.Append(ID_AUTOCOMP_DOUBLE, 'Include Double Underscores',
'Include attibutes prefixed by a double underscore', 1)
m = self.calltipsMenu = wx.Menu()
m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips',
'Show call tips with argument signature and docstring', 1)
m = self.optionsMenu = wx.Menu()
m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu,
'Auto Completion Options')
m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu,
'Call Tip Options')
m.Append(ID_WRAP, '&Wrap Lines',
'Wrap lines at right edge', 1)
m = self.helpMenu = wx.Menu()
m.AppendSeparator()
m.Append(ID_ABOUT, '&About...', 'About this program')
b = self.menuBar = wx.MenuBar()
b.Append(self.fileMenu, '&File')
b.Append(self.editMenu, '&Edit')
b.Append(self.optionsMenu, '&Options')
b.Append(self.helpMenu, '&Help')
self.SetMenuBar(b)
wx.EVT_MENU(self, ID_NEW, self.OnFileNew)
wx.EVT_MENU(self, ID_OPEN, self.OnFileOpen)
wx.EVT_MENU(self, ID_REVERT, self.OnFileRevert)
wx.EVT_MENU(self, ID_CLOSE, self.OnFileClose)
wx.EVT_MENU(self, ID_SAVE, self.OnFileSave)
wx.EVT_MENU(self, ID_SAVEAS, self.OnFileSaveAs)
wx.EVT_MENU(self, ID_NAMESPACE, self.OnFileUpdateNamespace)
wx.EVT_MENU(self, ID_PRINT, self.OnFilePrint)
wx.EVT_MENU(self, ID_EXIT, self.OnExit)
wx.EVT_MENU(self, ID_UNDO, self.OnUndo)
wx.EVT_MENU(self, ID_REDO, self.OnRedo)
wx.EVT_MENU(self, ID_CUT, self.OnCut)
wx.EVT_MENU(self, ID_COPY, self.OnCopy)
wx.EVT_MENU(self, ID_COPY_PLUS, self.OnCopyPlus)
wx.EVT_MENU(self, ID_PASTE, self.OnPaste)
wx.EVT_MENU(self, ID_PASTE_PLUS, self.OnPastePlus)
wx.EVT_MENU(self, ID_CLEAR, self.OnClear)
wx.EVT_MENU(self, ID_SELECTALL, self.OnSelectAll)
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
wx.EVT_MENU(self, ID_AUTOCOMP_SHOW, self.OnAutoCompleteShow)
wx.EVT_MENU(self, ID_AUTOCOMP_MAGIC, self.OnAutoCompleteMagic)
wx.EVT_MENU(self, ID_AUTOCOMP_SINGLE, self.OnAutoCompleteSingle)
wx.EVT_MENU(self, ID_AUTOCOMP_DOUBLE, self.OnAutoCompleteDouble)
wx.EVT_MENU(self, ID_CALLTIPS_SHOW, self.OnCallTipsShow)
wx.EVT_MENU(self, ID_WRAP, self.OnWrap)
wx.EVT_UPDATE_UI(self, ID_NEW, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_OPEN, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_REVERT, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_CLOSE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_SAVE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_SAVEAS, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_NAMESPACE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_PRINT, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_UNDO, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_REDO, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_CUT, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_COPY, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_COPY_PLUS, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_PASTE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_PASTE_PLUS, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_CLEAR, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_SELECTALL, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_MAGIC, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_SINGLE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_AUTOCOMP_DOUBLE, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu)
wx.EVT_UPDATE_UI(self, ID_WRAP, self.OnUpdateMenu)
def OnFileNew(self, event):
self.bufferNew()
def OnFileOpen(self, event):
self.bufferOpen()
def OnFileRevert(self, event):
self.bufferRevert()
def OnFileClose(self, event):
self.bufferClose()
def OnFileSave(self, event):
self.bufferSave()
def OnFileSaveAs(self, event):
self.bufferSaveAs()
def OnFileUpdateNamespace(self, event):
self.updateNamespace()
def OnFilePrint(self, event):
self.bufferPrint()
def OnExit(self, event):
self.Close(False)
def OnUndo(self, event):
win = wx.Window_FindFocus()
win.Undo()
def OnRedo(self, event):
win = wx.Window_FindFocus()
win.Redo()
def OnCut(self, event):
win = wx.Window_FindFocus()
win.Cut()
def OnCopy(self, event):
win = wx.Window_FindFocus()
win.Copy()
def OnCopyPlus(self, event):
win = wx.Window_FindFocus()
win.CopyWithPrompts()
def OnPaste(self, event):
win = wx.Window_FindFocus()
win.Paste()
def OnPastePlus(self, event):
win = wx.Window_FindFocus()
win.PasteAndRun()
def OnClear(self, event):
win = wx.Window_FindFocus()
win.Clear()
def OnSelectAll(self, event):
win = wx.Window_FindFocus()
win.SelectAll()
def OnAbout(self, event):
"""Display an About window."""
title = 'About'
text = 'Your message here.'
dialog = wx.MessageDialog(self, text, title,
wx.OK | wx.ICON_INFORMATION)
dialog.ShowModal()
dialog.Destroy()
def OnAutoCompleteShow(self, event):
win = wx.Window_FindFocus()
win.autoComplete = event.IsChecked()
def OnAutoCompleteMagic(self, event):
win = wx.Window_FindFocus()
win.autoCompleteIncludeMagic = event.IsChecked()
def OnAutoCompleteSingle(self, event):
win = wx.Window_FindFocus()
win.autoCompleteIncludeSingle = event.IsChecked()
def OnAutoCompleteDouble(self, event):
win = wx.Window_FindFocus()
win.autoCompleteIncludeDouble = event.IsChecked()
def OnCallTipsShow(self, event):
win = wx.Window_FindFocus()
win.autoCallTip = event.IsChecked()
def OnWrap(self, event):
win = wx.Window_FindFocus()
win.SetWrapMode(event.IsChecked())
def OnUpdateMenu(self, event):
"""Update menu items based on current status and context."""
win = wx.Window_FindFocus()
id = event.GetId()
event.Enable(True)
try:
if id == ID_NEW:
event.Enable(hasattr(self, 'bufferNew'))
elif id == ID_OPEN:
event.Enable(hasattr(self, 'bufferOpen'))
elif id == ID_REVERT:
event.Enable(hasattr(self, 'bufferRevert') and self.hasBuffer())
elif id == ID_CLOSE:
event.Enable(hasattr(self, 'bufferClose') and self.hasBuffer())
elif id == ID_SAVE:
event.Enable(hasattr(self, 'bufferSave') and self.bufferHasChanged())
elif id == ID_SAVEAS:
event.Enable(hasattr(self, 'bufferSaveAs') and self.hasBuffer())
elif id == ID_NAMESPACE:
event.Enable(hasattr(self, 'updateNamespace') and self.hasBuffer())
elif id == ID_PRINT:
event.Enable(hasattr(self, 'bufferPrint') and self.hasBuffer())
elif id == ID_UNDO:
event.Enable(win.CanUndo())
elif id == ID_REDO:
event.Enable(win.CanRedo())
elif id == ID_CUT:
event.Enable(win.CanCut())
elif id == ID_COPY:
event.Enable(win.CanCopy())
elif id == ID_COPY_PLUS:
event.Enable(win.CanCopy() and hasattr(win, 'CopyWithPrompts'))
elif id == ID_PASTE:
event.Enable(win.CanPaste())
elif id == ID_PASTE_PLUS:
event.Enable(win.CanPaste() and hasattr(win, 'PasteAndRun'))
elif id == ID_CLEAR:
event.Enable(win.CanCut())
elif id == ID_SELECTALL:
event.Enable(hasattr(win, 'SelectAll'))
elif id == ID_AUTOCOMP_SHOW:
event.Check(win.autoComplete)
elif id == ID_AUTOCOMP_MAGIC:
event.Check(win.autoCompleteIncludeMagic)
elif id == ID_AUTOCOMP_SINGLE:
event.Check(win.autoCompleteIncludeSingle)
elif id == ID_AUTOCOMP_DOUBLE:
event.Check(win.autoCompleteIncludeDouble)
elif id == ID_CALLTIPS_SHOW:
event.Check(win.autoCallTip)
elif id == ID_WRAP:
event.Check(win.GetWrapMode())
else:
event.Enable(False)
except AttributeError:
# This menu option is not supported in the current context.
event.Enable(False)
@@ -1,12 +1,26 @@
#----------------------------------------------------------------------
# This file was generated by ../scripts/img2py
#
from wxPython.wx import wxImageFromStream, wxBitmapFromImage
from wxPython.wx import wxEmptyIcon
"""Support for icons."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import wx
import cStringIO
def getPyCrustData():
def getPyIcon():
icon = wx.EmptyIcon()
icon.CopyFromBitmap(getPyBitmap())
return icon
def getPyBitmap():
return wx.BitmapFromImage(getPyImage())
def getPyImage():
stream = cStringIO.StringIO(getPyData())
return wx.ImageFromStream(stream)
def getPyData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\
\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x04\
@@ -56,16 +70,3 @@ N\xba\xb3\xab\x87\xfb\x8f\x97\xd8\xd9\xd5\x03\xc0\xfd\xc7K\xec\xd8\xd6\xdd\
\x8f\xdb\xbel\x8e\xa1S\xc7\xda\xc6\xe6\xee\xccs\xe9\xdcYnV\x95\xd8\xf2?&q+\
\x9c\x1b1\xf3\xbf\xcd3{\xfdJ\xdb\xf8\xde\xfd\x19.\\\xad\x08\x80\xbf\x01\xd1\
\x86\xfa\x8b\xc7\xc0\xc8\xb7\x00\x00\x00\x00IEND\xaeB`\x82'
def getPyCrustBitmap():
return wxBitmapFromImage(getPyCrustImage())
def getPyCrustImage():
stream = cStringIO.StringIO(getPyCrustData())
return wxImageFromStream(stream)
def getPyCrustIcon():
icon = wxEmptyIcon()
icon.CopyFromBitmap(getPyCrustBitmap())
return icon

Some files were not shown because too many files have changed in this diff Show More