]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxPython/lib/PyCrust/filling.py
b7a29eda78a2da5ef32903f2874983c128a687db
[wxWidgets.git] / wxPython / wxPython / lib / PyCrust / filling.py
1 """PyCrust Filling is the gui tree control through which a user can navigate
2 the local namespace or any object."""
3
4 __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
5 __cvsid__ = "$Id$"
6 __version__ = "$Revision$"[11:-2]
7
8 from wxPython.wx import *
9 from wxPython.stc import *
10 from version import VERSION
11 import inspect
12 import introspect
13 import keyword
14 import sys
15 import types
16
17
18 class FillingTree(wxTreeCtrl):
19 """PyCrust FillingTree based on wxTreeCtrl."""
20
21 name = 'PyCrust Filling Tree'
22 revision = __version__
23
24 def __init__(self, parent, id=-1, pos=wxDefaultPosition, \
25 size=wxDefaultSize, style=wxTR_HAS_BUTTONS, \
26 rootObject=None, rootLabel=None, rootIsNamespace=0):
27 """Create a PyCrust FillingTree instance."""
28 wxTreeCtrl.__init__(self, parent, id, pos, size)
29 self.rootIsNamespace = rootIsNamespace
30 if not rootObject:
31 import __main__
32 rootObject = __main__
33 self.rootIsNamespace = 1
34 if not rootLabel: rootLabel = 'Ingredients'
35 rootData = wxTreeItemData(rootObject)
36 self.root = self.AddRoot(rootLabel, -1, -1, rootData)
37 self.SetItemHasChildren(self.root, self.hasChildren(self.root))
38 EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.OnItemExpanding)
39 EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemCollapsed)
40 EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged)
41
42 def hasChildren(self, object):
43 """Return true if object has children."""
44 if self.getChildren(object):
45 return true
46 else:
47 return false
48
49 def getChildren(self, object):
50 """Return a dictionary with the attributes or contents of object."""
51 dict = {}
52 objtype = type(object)
53 if objtype is types.DictType:
54 dict = object
55 elif (objtype in (types.ClassType, \
56 types.InstanceType, \
57 types.ModuleType)):
58 for key in introspect.getAttributeNames(object):
59 # Believe it or not, some attributes can disappear, such as
60 # the exc_traceback attribute of the sys module. So this is
61 # nested in a try block.
62 try:
63 dict[key] = getattr(object, key)
64 except:
65 pass
66 return dict
67
68 def OnItemExpanding(self, event):
69 selection = event.GetItem()
70 if self.IsExpanded(selection):
71 return
72 object = self.GetPyData(selection)
73 children = self.getChildren(object)
74 if not children:
75 return
76 list = children.keys()
77 list.sort(lambda x, y: cmp(x.lower(), y.lower()))
78 for item in list:
79 itemtext = str(item)
80 # Show string dictionary items with single quotes, except for
81 # the first level of items, if they represent a namespace.
82 if type(object) is types.DictType \
83 and type(item) is types.StringType \
84 and (selection != self.root \
85 or (selection == self.root and not self.rootIsNamespace)):
86 itemtext = repr(item)
87 child = self.AppendItem(selection, itemtext, -1, -1, \
88 wxTreeItemData(children[item]))
89 self.SetItemHasChildren(child, self.hasChildren(children[item]))
90
91 def OnItemCollapsed(self, event):
92 """Remove all children from the item."""
93 item = event.GetItem()
94 self.DeleteChildren(item)
95
96 def OnSelChanged(self, event):
97 item = event.GetItem()
98 if item == self.root:
99 self.setText('')
100 return
101 object = self.GetPyData(item)
102 text = ''
103 text += self.getFullName(item)
104 text += '\n\nType: ' + str(type(object))[7:-2]
105 value = str(object)
106 if type(object) is types.StringType:
107 value = repr(value)
108 text += '\n\nValue: ' + value
109 if type(object) is types.InstanceType:
110 try:
111 text += '\n\nClass Definition:\n\n' + \
112 inspect.getsource(object.__class__)
113 except:
114 try:
115 text += '\n\n"""' + inspect.getdoc(object).strip() + '"""'
116 except:
117 pass
118 else:
119 try:
120 text += '\n\nSource Code:\n\n' + \
121 inspect.getsource(object)
122 except:
123 try:
124 text += '\n\n"""' + inspect.getdoc(object).strip() + '"""'
125 except:
126 pass
127 self.setText(text)
128
129 def getFullName(self, item, partial=''):
130 """Return a syntactically proper name for item."""
131 parent = self.GetItemParent(item)
132 parentobject = self.GetPyData(parent)
133 name = self.GetItemText(item)
134 # Apply dictionary syntax to dictionary items, except the root
135 # and first level children of a namepace.
136 if type(parentobject) is types.DictType \
137 and ((item != self.root and parent != self.root) \
138 or (parent == self.root and not self.rootIsNamespace)):
139 name = '[' + name + ']'
140 # Apply dot syntax to multipart names.
141 if partial:
142 if partial[0] == '[':
143 name += partial
144 else:
145 name += '.' + partial
146 # Repeat for everything but the root item
147 # and first level children of a namespace.
148 if (item != self.root and parent != self.root) \
149 or (parent == self.root and not self.rootIsNamespace):
150 name = self.getFullName(parent, partial=name)
151 return name
152
153 def setText(self, text):
154 """Display information about the current selection."""
155
156 # This method will most likely be replaced by the enclosing app
157 # to do something more interesting, like write to a text control.
158 print text
159
160 def setStatusText(self, text):
161 """Display status information."""
162
163 # This method will most likely be replaced by the enclosing app
164 # to do something more interesting, like write to a status bar.
165 print text
166
167
168 if wxPlatform == '__WXMSW__':
169 faces = { 'times' : 'Times New Roman',
170 'mono' : 'Courier New',
171 'helv' : 'Lucida Console',
172 'lucida' : 'Lucida Console',
173 'other' : 'Comic Sans MS',
174 'size' : 10,
175 'lnsize' : 9,
176 'backcol': '#FFFFFF',
177 }
178 # Versions of wxPython prior to 2.3.2 had a sizing bug on Win platform.
179 # The font was 2 points too large. So we need to reduce the font size.
180 if ((wxMAJOR_VERSION, wxMINOR_VERSION) == (2, 3) and wxRELEASE_NUMBER < 2) \
181 or (wxMAJOR_VERSION <= 2 and wxMINOR_VERSION <= 2):
182 faces['size'] -= 2
183 faces['lnsize'] -= 2
184 else: # GTK
185 faces = { 'times' : 'Times',
186 'mono' : 'Courier',
187 'helv' : 'Helvetica',
188 'other' : 'new century schoolbook',
189 'size' : 12,
190 'lnsize' : 10,
191 'backcol': '#FFFFFF',
192 }
193
194
195 class FillingText(wxStyledTextCtrl):
196 """PyCrust FillingText based on wxStyledTextCtrl."""
197
198 name = 'PyCrust Filling Text'
199 revision = __version__
200
201 def __init__(self, parent, id=-1, pos=wxDefaultPosition, \
202 size=wxDefaultSize, style=wxCLIP_CHILDREN):
203 """Create a PyCrust FillingText instance."""
204 wxStyledTextCtrl.__init__(self, parent, id, pos, size, style)
205 # Configure various defaults and user preferences.
206 self.config()
207
208 def config(self):
209 """Configure shell based on user preferences."""
210 self.SetMarginWidth(1, 0)
211
212 self.SetLexer(wxSTC_LEX_PYTHON)
213 self.SetKeyWords(0, ' '.join(keyword.kwlist))
214
215 self.setStyles(faces)
216 self.SetViewWhiteSpace(0)
217 self.SetTabWidth(4)
218 self.SetUseTabs(0)
219 self.SetReadOnly(1)
220
221 def setStyles(self, faces):
222 """Configure font size, typeface and color for lexer."""
223
224 # Default style
225 self.StyleSetSpec(wxSTC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces)
226
227 self.StyleClearAll()
228
229 # Built in styles
230 self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(mono)s,size:%(lnsize)d" % faces)
231 self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, "face:%(mono)s" % faces)
232 self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, "fore:#0000FF,back:#FFFF88")
233 self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, "fore:#FF0000,back:#FFFF88")
234
235 # Python styles
236 self.StyleSetSpec(wxSTC_P_DEFAULT, "face:%(mono)s" % faces)
237 self.StyleSetSpec(wxSTC_P_COMMENTLINE, "fore:#007F00,face:%(mono)s" % faces)
238 self.StyleSetSpec(wxSTC_P_NUMBER, "")
239 self.StyleSetSpec(wxSTC_P_STRING, "fore:#7F007F,face:%(mono)s" % faces)
240 self.StyleSetSpec(wxSTC_P_CHARACTER, "fore:#7F007F,face:%(mono)s" % faces)
241 self.StyleSetSpec(wxSTC_P_WORD, "fore:#00007F,bold")
242 self.StyleSetSpec(wxSTC_P_TRIPLE, "fore:#7F0000")
243 self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, "fore:#000033,back:#FFFFE8")
244 self.StyleSetSpec(wxSTC_P_CLASSNAME, "fore:#0000FF,bold")
245 self.StyleSetSpec(wxSTC_P_DEFNAME, "fore:#007F7F,bold")
246 self.StyleSetSpec(wxSTC_P_OPERATOR, "")
247 self.StyleSetSpec(wxSTC_P_IDENTIFIER, "")
248 self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, "fore:#7F7F7F")
249 self.StyleSetSpec(wxSTC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled" % faces)
250
251 def SetText(self, *args, **kwds):
252 self.SetReadOnly(0)
253 wxStyledTextCtrl.SetText(self, *args, **kwds)
254 self.SetReadOnly(1)
255
256
257 class Filling(wxSplitterWindow):
258 """PyCrust Filling based on wxSplitterWindow."""
259
260 name = 'PyCrust Filling'
261 revision = __version__
262
263 def __init__(self, parent, id=-1, pos=wxDefaultPosition, \
264 size=wxDefaultSize, style=wxSP_3D, name='Filling Window', \
265 rootObject=None, rootLabel=None, rootIsNamespace=0):
266 """Create a PyCrust Filling instance."""
267 wxSplitterWindow.__init__(self, parent, id, pos, size, style, name)
268 self.fillingTree = FillingTree(parent=self, rootObject=rootObject, \
269 rootLabel=rootLabel, \
270 rootIsNamespace=rootIsNamespace)
271 self.fillingText = FillingText(parent=self)
272 self.SplitVertically(self.fillingTree, self.fillingText, 200)
273 self.SetMinimumPaneSize(1)
274 # Override the filling so that descriptions go to fillingText.
275 self.fillingTree.setText = self.fillingText.SetText
276 # Select the root item.
277 self.fillingTree.SelectItem(self.fillingTree.root)
278
279
280 class FillingFrame(wxFrame):
281 """Frame containing the PyCrust filling, or namespace tree component."""
282
283 name = 'PyCrust Filling Frame'
284 revision = __version__
285
286 def __init__(self, parent=None, id=-1, title='PyFilling', \
287 pos=wxDefaultPosition, size=wxDefaultSize, \
288 style=wxDEFAULT_FRAME_STYLE, rootObject=None, \
289 rootLabel=None, rootIsNamespace=0):
290 """Create a PyCrust FillingFrame instance."""
291 wxFrame.__init__(self, parent, id, title, pos, size, style)
292 intro = 'Welcome To PyFilling - The Tastiest Namespace Inspector'
293 self.CreateStatusBar()
294 self.SetStatusText(intro)
295 if wxPlatform == '__WXMSW__':
296 import os
297 filename = os.path.join(os.path.dirname(__file__), 'PyCrust.ico')
298 icon = wxIcon(filename, wxBITMAP_TYPE_ICO)
299 self.SetIcon(icon)
300 self.filling = Filling(parent=self, rootObject=rootObject, \
301 rootLabel=rootLabel, \
302 rootIsNamespace=rootIsNamespace)
303 # Override the filling so that status messages go to the status bar.
304 self.filling.fillingTree.setStatusText = self.SetStatusText
305
306
307 class App(wxApp):
308 """PyFilling standalone application."""
309
310 def OnInit(self):
311 self.fillingFrame = FillingFrame()
312 self.fillingFrame.Show(true)
313 self.SetTopWindow(self.fillingFrame)
314 return true
315
316
317
318