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